fix: persist manual node sizes and add width/height inputs

Nested vm/lxc/docker leaf nodes lost their size on reload: the
deserialize restore branch excluded those types entirely, so a
resized child snapped back to content-fit. Gate the restore on
container_mode instead of node type.

Also prefer explicit width/height over the DOM-measured value when
serializing, so a manual resize persists its exact target rather than
drifting to the fractional content-fit size.

Add a Size section to the detail panel with W/H number inputs
(setNodeSize store action, clamped to the resizer minimums). Inputs
resync live when the node is resized by corner drag, without
clobbering active keystrokes.

ha-relevant: yes
This commit is contained in:
Pouzor
2026-06-17 11:55:55 +02:00
parent 96bb048228
commit 2a4d109ee6
6 changed files with 237 additions and 10 deletions
+81 -1
View File
@@ -21,7 +21,7 @@ type PropForm = { key: string; value: string; icon: string | null; visible: bool
const EMPTY_PROP: PropForm = { key: '', value: '', icon: null, visible: true }
export function DetailPanel({ onEdit }: DetailPanelProps) {
const { nodes, selectedNodeId, selectedNodeIds, setSelectedNode, deleteNode, updateNode, snapshotHistory, createGroup, ungroup, removeFromGroup } = useCanvasStore()
const { nodes, selectedNodeId, selectedNodeIds, setSelectedNode, deleteNode, updateNode, snapshotHistory, createGroup, ungroup, removeFromGroup, setNodeSize } = useCanvasStore()
const serviceStatuses = useCanvasStore((s) => s.serviceStatuses)
const [addingForNode, setAddingForNode] = useState<string | null>(null)
@@ -255,6 +255,13 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
{data.last_seen && <DetailRow label="Last Seen" value={new Date(/[Zz]|[+-]\d{2}:?\d{2}$/.test(data.last_seen) ? data.last_seen : data.last_seen + 'Z').toLocaleString()} />}
</div>
{/* Size section — manual width/height entry for pixel-exact sizing */}
<SizeFields
key={node.id}
node={node}
onCommit={(size) => { snapshotHistory(); setNodeSize(node.id, size) }}
/>
{/* Properties section */}
<div className="px-4 py-3 border-t border-border">
<div className="flex items-center justify-between mb-2">
@@ -345,6 +352,79 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {
)
}
// --- Size fields (manual width/height entry) ---
const round = (v: number | undefined): string => (v != null ? String(Math.round(v)) : '')
function SizeFields({ node, onCommit }: { node: Node<NodeData>; onCommit: (size: { width?: number; height?: number }) => void }) {
// Live size from the explicit dimension, falling back to the DOM-measured
// size so the field shows the node's current footprint even before resize.
const liveWidth = round(node.width ?? node.measured?.width)
const liveHeight = round(node.height ?? node.measured?.height)
const [width, setWidth] = useState(liveWidth)
const [height, setHeight] = useState(liveHeight)
// Resync the fields when the node is resized by dragging its corner handle
// (which mutates node.width/height in the store). Adjusting state during
// render — the React-blessed alternative to an effect — keeps it in step
// without cascading renders. The field the user is actively editing is left
// alone so we don't clobber their keystrokes mid-type.
const [editing, setEditing] = useState<'width' | 'height' | null>(null)
const [prev, setPrev] = useState({ w: liveWidth, h: liveHeight })
if (prev.w !== liveWidth || prev.h !== liveHeight) {
setPrev({ w: liveWidth, h: liveHeight })
if (editing !== 'width') setWidth(liveWidth)
if (editing !== 'height') setHeight(liveHeight)
}
const commit = (raw: string, axis: 'width' | 'height') => {
const n = Number(raw)
if (!raw.trim() || Number.isNaN(n) || n <= 0) {
// Reset the field to the live value on invalid input — no mutation.
if (axis === 'width') setWidth(round(node.width ?? node.measured?.width))
else setHeight(round(node.height ?? node.measured?.height))
return
}
onCommit({ [axis]: n })
}
return (
<div className="px-4 py-3 border-t border-border">
<span className="text-xs text-muted-foreground">Size</span>
<div className="mt-2 flex items-center gap-2">
<label className="flex flex-1 items-center gap-1.5">
<span className="text-[10px] text-muted-foreground/70 w-3">W</span>
<Input
type="number"
min={140}
aria-label="Width"
value={width}
onFocus={() => setEditing('width')}
onChange={(e) => setWidth(e.target.value)}
onBlur={() => { setEditing(null); commit(width, 'width') }}
onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur() }}
className="h-7 text-xs font-mono"
/>
</label>
<label className="flex flex-1 items-center gap-1.5">
<span className="text-[10px] text-muted-foreground/70 w-3">H</span>
<Input
type="number"
min={50}
aria-label="Height"
value={height}
onFocus={() => setEditing('height')}
onChange={(e) => setHeight(e.target.value)}
onBlur={() => { setEditing(null); commit(height, 'height') }}
onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur() }}
className="h-7 text-xs font-mono"
/>
</label>
</div>
</div>
)
}
// --- Multi-select panel ---
interface MultiSelectPanelProps {
@@ -36,6 +36,7 @@ function setupStore(nodeData: Partial<NodeData> = {}, serviceStatuses: Record<st
snapshotHistory: vi.fn(),
createGroup: vi.fn(),
ungroup: vi.fn(),
setNodeSize: vi.fn(),
serviceStatuses,
}
// Support both the bare destructure call and the selector-based call.
@@ -571,4 +572,69 @@ describe('DetailPanel', () => {
expect(row?.textContent).not.toMatch(/Invalid Date/)
})
})
describe('Size section', () => {
function setupSized(node: Partial<Node<NodeData>>, setNodeSize = vi.fn()) {
const state = {
nodes: [{ ...makeNode({}), ...node }],
selectedNodeId: 'n1',
selectedNodeIds: [],
setSelectedNode: vi.fn(),
deleteNode: vi.fn(),
updateNode: vi.fn(),
snapshotHistory: vi.fn(),
createGroup: vi.fn(),
ungroup: vi.fn(),
setNodeSize,
serviceStatuses: {},
}
vi.mocked(canvasStore.useCanvasStore).mockImplementation(
((sel?: (s: typeof state) => unknown) => (sel ? sel(state) : state)) as unknown as typeof canvasStore.useCanvasStore,
)
return setNodeSize
}
it('shows the current width/height, preferring explicit over measured', () => {
setupSized({ width: 220, height: 130, measured: { width: 999, height: 999 } })
render(<DetailPanel onEdit={vi.fn()} />)
expect((screen.getByLabelText('Width') as HTMLInputElement).value).toBe('220')
expect((screen.getByLabelText('Height') as HTMLInputElement).value).toBe('130')
})
it('falls back to the measured size before a resize', () => {
setupSized({ measured: { width: 187, height: 73 } })
render(<DetailPanel onEdit={vi.fn()} />)
expect((screen.getByLabelText('Width') as HTMLInputElement).value).toBe('187')
expect((screen.getByLabelText('Height') as HTMLInputElement).value).toBe('73')
})
it('commits a manual width on blur', () => {
const setNodeSize = setupSized({ width: 200, height: 100 })
render(<DetailPanel onEdit={vi.fn()} />)
const w = screen.getByLabelText('Width')
fireEvent.change(w, { target: { value: '260' } })
fireEvent.blur(w)
expect(setNodeSize).toHaveBeenCalledWith('n1', { width: 260 })
})
it('reverts invalid input without committing', () => {
const setNodeSize = setupSized({ width: 200, height: 100 })
render(<DetailPanel onEdit={vi.fn()} />)
const w = screen.getByLabelText('Width') as HTMLInputElement
fireEvent.change(w, { target: { value: 'abc' } })
fireEvent.blur(w)
expect(setNodeSize).not.toHaveBeenCalled()
expect(w.value).toBe('200')
})
it('resyncs the field when the node is resized by corner drag', () => {
setupSized({ width: 200, height: 100 })
const { rerender } = render(<DetailPanel onEdit={vi.fn()} />)
expect((screen.getByLabelText('Width') as HTMLInputElement).value).toBe('200')
// Simulate a corner-drag resize updating the store dimension.
setupSized({ width: 340, height: 100 })
rerender(<DetailPanel onEdit={vi.fn()} />)
expect((screen.getByLabelText('Width') as HTMLInputElement).value).toBe('340')
})
})
})
@@ -1263,4 +1263,29 @@ describe('canvasStore — custom style apply', () => {
expect(e.data?.custom_color).toBe('#aabbcc')
expect(useCanvasStore.getState().hasUnsavedChanges).toBe(true)
})
it('setNodeSize sets explicit width/height and marks unsaved', () => {
useCanvasStore.setState({ nodes: [makeNode('n1')], hasUnsavedChanges: false })
useCanvasStore.getState().setNodeSize('n1', { width: 220, height: 130 })
const n = useCanvasStore.getState().nodes.find((x) => x.id === 'n1')!
expect(n.width).toBe(220)
expect(n.height).toBe(130)
expect(useCanvasStore.getState().hasUnsavedChanges).toBe(true)
})
it('setNodeSize clamps below the minimum box', () => {
useCanvasStore.setState({ nodes: [makeNode('n1')] })
useCanvasStore.getState().setNodeSize('n1', { width: 10, height: 10 })
const n = useCanvasStore.getState().nodes.find((x) => x.id === 'n1')!
expect(n.width).toBe(140)
expect(n.height).toBe(50)
})
it('setNodeSize updates only the provided axis', () => {
useCanvasStore.setState({ nodes: [{ ...makeNode('n1'), width: 200, height: 100 }] })
useCanvasStore.getState().setNodeSize('n1', { width: 300 })
const n = useCanvasStore.getState().nodes.find((x) => x.id === 'n1')!
expect(n.width).toBe(300)
expect(n.height).toBe(100)
})
})
+17
View File
@@ -61,6 +61,7 @@ interface CanvasState {
deleteEdge: (id: string) => void
setProxmoxContainerMode: (proxmoxId: string, enabled: boolean) => void
setNodeZIndex: (id: string, zIndex: number) => void
setNodeSize: (id: string, size: { width?: number; height?: number }) => void
editingGroupRectId: string | null
setEditingGroupRectId: (id: string | null) => void
editingTextId: string | null
@@ -466,6 +467,22 @@ export const useCanvasStore = create<CanvasState>((set) => ({
hasUnsavedChanges: true,
})),
// Manual width/height entry. Lets the user type an exact size instead of
// dragging the resize handle (which lands on fractional content-fit pixels).
// A clamp matches the NodeResizer minimums so the box can't collapse.
setNodeSize: (id, size) =>
set((state) => ({
nodes: state.nodes.map((n) => {
if (n.id !== id) return n
return {
...n,
...(size.width != null ? { width: Math.max(140, size.width) } : {}),
...(size.height != null ? { height: Math.max(50, size.height) } : {}),
}
}),
hasUnsavedChanges: true,
})),
setEditingGroupRectId: (id) => set({ editingGroupRectId: id }),
setEditingTextId: (id) => set({ editingTextId: id }),
@@ -102,6 +102,20 @@ describe('serializeNode — regular node', () => {
expect(result.height).toBeNull()
})
it('prefers explicit width/height over the measured (content-fit) value', () => {
const node: Node<NodeData> = { ...makeRfNode({ width: 200, height: 100 }), measured: { width: 187, height: 73 } }
const result = serializeNode(node)
expect(result.width).toBe(200)
expect(result.height).toBe(100)
})
it('falls back to measured when no explicit dimension is set', () => {
const node: Node<NodeData> = { ...makeRfNode(), measured: { width: 187, height: 73 } }
const result = serializeNode(node)
expect(result.width).toBe(187)
expect(result.height).toBe(73)
})
it('serializes hardware fields', () => {
const node = makeRfNode({
data: {
@@ -162,13 +176,14 @@ describe('serializeNode — groupRect', () => {
expect((result.custom_colors as Record<string, unknown>).height).toBe(250)
})
it('falls back to measured dimensions over explicit width/height', () => {
it('prefers explicit width/height over measured, falling back to measured per-axis', () => {
const node: Node<NodeData> = {
...makeRfNode({ type: 'groupRect', data: { label: 'Z', type: 'groupRect', status: 'unknown', services: [] }, width: 400 }),
measured: { width: 420, height: 260 },
}
const result = serializeNode(node)
expect((result.custom_colors as Record<string, unknown>).width).toBe(420)
// Explicit width wins; height has no explicit value so it uses measured.
expect((result.custom_colors as Record<string, unknown>).width).toBe(400)
expect((result.custom_colors as Record<string, unknown>).height).toBe(260)
})
@@ -323,6 +338,21 @@ describe('deserializeApiNode — regular node', () => {
expect(result.width).toBeUndefined()
expect(result.height).toBeUndefined()
})
// Regression: issue #205 — a leaf vm/lxc nested in a container would lose its
// saved size on reload because the restore branch excluded those types.
it.each(['vm', 'lxc', 'docker_host'] as const)(
'restores saved width/height for a leaf %s node (container_mode false)',
(type) => {
const map = new Map([['px1', true]])
const result = deserializeApiNode(
makeApiNode({ type, container_mode: false, parent_id: 'px1', width: 240, height: 90 }),
map,
)
expect(result.width).toBe(240)
expect(result.height).toBe(90)
},
)
})
// ── deserializeApiNode — groupRect ────────────────────────────────────────────
+16 -7
View File
@@ -75,8 +75,8 @@ export function serializeNode(n: Node<NodeData>): Record<string, unknown> {
pos_y: n.position.y,
custom_colors: {
...n.data.custom_colors,
width: n.measured?.width ?? n.width ?? 360,
height: n.measured?.height ?? n.height ?? 240,
width: n.width ?? n.measured?.width ?? 360,
height: n.height ?? n.measured?.height ?? 240,
// Stash collapse state inside custom_colors so the API/YAML blob does
// not need a new column. Hoisted back to `data.collapsed` on load.
collapsed: n.data.collapsed ?? false,
@@ -112,8 +112,11 @@ export function serializeNode(n: Node<NodeData>): Record<string, unknown> {
disk_gb: n.data.disk_gb ?? null,
show_hardware: n.data.show_hardware ?? false,
properties: n.data.properties ?? [],
width: n.measured?.width ?? n.width ?? null,
height: n.measured?.height ?? n.height ?? null,
// Prefer the explicit (resized) dimension over the DOM-measured one so a
// manual resize persists its exact target instead of drifting to the
// fractional content-fit value.
width: n.width ?? n.measured?.width ?? null,
height: n.height ?? n.measured?.height ?? null,
bottom_handles: clampBottomHandles(n.data.bottom_handles ?? 1),
show_port_numbers: n.data.show_port_numbers ?? false,
pos_x: n.position.x,
@@ -179,11 +182,17 @@ export function deserializeApiNode(
collapsed: Boolean(n.custom_colors?.collapsed),
} as unknown as NodeData,
...(n.parent_id && parentIsContainer ? { parentId: n.parent_id, extent: 'parent' as const } : {}),
// Container hosts (Proxmox/VM/LXC/docker in container_mode) get a default
// box if none was saved. Every other node — including LEAF vm/lxc/docker
// nodes nested inside a container — restores its own saved width/height.
// Gating on container_mode (not type) is what keeps a resized nested node
// from snapping back to content-fit on reload.
...(['proxmox', 'vm', 'lxc', 'docker_host'].includes(normalizedType) && n.container_mode !== false
? { width: n.width ?? 300, height: n.height ?? 200 }
: {}),
...(n.width && !['proxmox', 'vm', 'lxc', 'docker_host'].includes(normalizedType) ? { width: n.width } : {}),
...(n.height && !['proxmox', 'vm', 'lxc', 'docker_host'].includes(normalizedType) ? { height: n.height } : {}),
: {
...(n.width ? { width: n.width } : {}),
...(n.height ? { height: n.height } : {}),
}),
}
}