Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(canvas): let a zone parent the nodes dropped inside it

Pouzorfcc2927b69f8
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 98e06ce..630ea90 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -64,7 +64,7 @@ import { buildProxmoxClusterEdges } from '@/components/proxmox/clusterEdges'
const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
export default function App() {
- const { loadCanvas, applyLayout, markSaved, markUnsaved, hasUnsavedChanges, editSeq, selectedNodeId, selectedNodeIds, addNode, updateNode, deleteNode, onConnect, updateEdge, deleteEdge, setProxmoxContainerMode, setNodeZIndex, editingGroupRectId, setEditingGroupRectId, editingTextId, setEditingTextId, nodes, edges, snapshotHistory, undo, redo, addToGroup, addToContainer, floorMap, setFloorMap } = useCanvasStore()
+ const { loadCanvas, applyLayout, markSaved, markUnsaved, hasUnsavedChanges, editSeq, selectedNodeId, selectedNodeIds, addNode, updateNode, deleteNode, onConnect, updateEdge, deleteEdge, setProxmoxContainerMode, setNodeZIndex, editingGroupRectId, setEditingGroupRectId, editingTextId, setEditingTextId, nodes, edges, snapshotHistory, undo, redo, addToGroup, addToContainer, addToZone, floorMap, setFloorMap } = useCanvasStore()
const canvasRef = useRef<HTMLDivElement>(null)
const { isAuthenticated, isInitialized } = useAuthStore()
const authBootstrapStarted = useRef(false)
@@ -133,6 +133,7 @@ export default function App() {
const [pendingConnection, setPendingConnection] = useState<Connection | null>(null)
const [pendingGroupAdd, setPendingGroupAdd] = useState<{ nodeId: string; groupId: string } | null>(null)
const [pendingContainerAdd, setPendingContainerAdd] = useState<{ nodeId: string; containerId: string } | null>(null)
+ const [pendingZoneAdd, setPendingZoneAdd] = useState<{ nodeId: string; zoneId: string } | null>(null)
const [editEdgeId, setEditEdgeId] = useState<string | null>(null)
const [scanConfigOpen, setScanConfigOpen] = useState(false)
const [settingsOpen, setSettingsOpen] = useState(false)
@@ -224,8 +225,11 @@ export default function App() {
.filter((n) => n.type === 'group' || n.container_mode === true)
.map((n) => [n.id, true])
)
+ const zoneIds = new Set(
+ (apiNodes as ApiNode[]).filter((n) => n.type === 'groupRect').map((n) => n.id)
+ )
const { nodes: rfNodes, edges: rfEdges } = migrateClusterHandles(
- (apiNodes as ApiNode[]).map((n) => deserializeApiNode(n, proxmoxContainerMap)),
+ (apiNodes as ApiNode[]).map((n) => deserializeApiNode(n, proxmoxContainerMap, zoneIds)),
(apiEdges as ApiEdge[]).map(deserializeApiEdge),
)
const savedTheme = res.data.viewport?.theme_id
@@ -1053,6 +1057,7 @@ export default function App() {
onNodeDragStart={snapshotHistory}
onRequestAddToGroup={setPendingGroupAdd}
onRequestAddToContainer={setPendingContainerAdd}
+ onRequestAddToZone={setPendingZoneAdd}
onOpenInventory={(deviceId) => openInventoryModal(deviceId)}
/>
)}
@@ -1295,6 +1300,18 @@ export default function App() {
onCancel={() => setPendingContainerAdd(null)}
/>
+ <ConfirmAddToGroupModal
+ open={!!pendingZoneAdd}
+ variant="zone"
+ nodeLabel={pendingZoneAdd ? (nodes.find((n) => n.id === pendingZoneAdd.nodeId)?.data.label ?? '') : ''}
+ targetLabel={pendingZoneAdd ? (nodes.find((n) => n.id === pendingZoneAdd.zoneId)?.data.label ?? '') : ''}
+ onConfirm={() => {
+ if (pendingZoneAdd) addToZone(pendingZoneAdd.zoneId, pendingZoneAdd.nodeId)
+ setPendingZoneAdd(null)
+ }}
+ onCancel={() => setPendingZoneAdd(null)}
+ />
+
{/* Mounted in standalone too: status-check settings are hidden inside,
but canvas prefs (snap, hide-IP) still apply. */}
<SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} />
diff --git a/frontend/src/components/canvas/CanvasContainer.tsx b/frontend/src/components/canvas/CanvasContainer.tsx
index 5fb2b36..9593bc0 100644
--- a/frontend/src/components/canvas/CanvasContainer.tsx
+++ b/frontend/src/components/canvas/CanvasContainer.tsx
@@ -34,10 +34,11 @@ interface CanvasContainerProps {
onNodeDragStart?: () => void
onRequestAddToGroup?: (payload: { nodeId: string; groupId: string }) => void
onRequestAddToContainer?: (payload: { nodeId: string; containerId: string }) => void
+ onRequestAddToZone?: (payload: { nodeId: string; zoneId: string }) => void
onOpenInventory?: (deviceId: string) => void
}
-export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDoubleClick, onNodeDragStart, onRequestAddToGroup, onRequestAddToContainer, onOpenInventory }: CanvasContainerProps) {
+export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDoubleClick, onNodeDragStart, onRequestAddToGroup, onRequestAddToContainer, onRequestAddToZone, onOpenInventory }: CanvasContainerProps) {
const [lassoMode, setLassoMode] = useState(true)
const {
nodes, edges,
@@ -45,6 +46,7 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
setSelectedNode, snapshotHistory,
fitViewPending, clearFitViewPending,
copySelectedNodes, pasteNodes,
+ removeFromGroup,
} = useCanvasStore()
const { fitView, screenToFlowPosition, getIntersectingNodes } = useReactFlow<Node<NodeData>>()
@@ -146,20 +148,35 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
// Drop a top-level node onto a group → ask App to confirm adding it. Runs
// before the alignment snap so detection uses the dropped position.
const handleNodeDragStop = useCallback<NonNullable<typeof onNodeDragStop>>((event, dragNode, dragNodes) => {
- if (dragNode && !dragNode.parentId &&
- dragNode.data.type !== 'group' && dragNode.data.type !== 'groupRect') {
+ if (dragNode && dragNode.data.type !== 'group' && dragNode.data.type !== 'groupRect') {
const intersecting = getIntersectingNodes(dragNode)
- const group = intersecting.find((n) => n.data.type === 'group')
- if (group) {
- onRequestAddToGroup?.({ nodeId: dragNode.id, groupId: group.id })
- } else {
- // Any node in container_mode (proxmox, docker_host, …) accepts children.
+ const zoneParent = dragNode.parentId
+ ? nodes.find((n) => n.id === dragNode.parentId && n.data.type === 'groupRect')
+ : undefined
+ if (zoneParent) {
+ // Zone children are not extent-clamped, so a drop outside the zone is
+ // how the user takes a node back out of it.
+ if (!intersecting.some((n) => n.id === zoneParent.id)) {
+ removeFromGroup(zoneParent.id, dragNode.id)
+ }
+ } else if (!dragNode.parentId) {
+ const group = intersecting.find((n) => n.data.type === 'group')
const container = intersecting.find((n) => n.id !== dragNode.id && n.data.container_mode === true)
- if (container) onRequestAddToContainer?.({ nodeId: dragNode.id, containerId: container.id })
+ if (group) {
+ onRequestAddToGroup?.({ nodeId: dragNode.id, groupId: group.id })
+ } else if (container) {
+ // Any node in container_mode (proxmox, docker_host, …) accepts children.
+ onRequestAddToContainer?.({ nodeId: dragNode.id, containerId: container.id })
+ } else {
+ // Zones come last: they are the loosest container and the largest, so
+ // a group/container inside one still wins the drop.
+ const zone = intersecting.find((n) => n.data.type === 'groupRect')
+ if (zone) onRequestAddToZone?.({ nodeId: dragNode.id, zoneId: zone.id })
+ }
}
}
onNodeDragStop(event, dragNode, dragNodes)
- }, [onRequestAddToGroup, onRequestAddToContainer, getIntersectingNodes, onNodeDragStop])
+ }, [onRequestAddToGroup, onRequestAddToContainer, onRequestAddToZone, removeFromGroup, nodes, getIntersectingNodes, onNodeDragStop])
return (
<div ref={wrapperRef} className="w-full h-full" style={{ background: theme.colors.canvasBackground }} onMouseMove={onMouseMove}>
diff --git a/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx b/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx
index c0ea486..042ade7 100644
--- a/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx
+++ b/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx
@@ -251,6 +251,63 @@ describe('CanvasContainer', () => {
expect(onRequestAddToContainer).not.toHaveBeenCalled()
})
+ // ── Drag onto a zone → onRequestAddToZone / detach ────────────────────────
+
+ function zoneNode(id: string): Node<NodeData> {
+ return { id, type: 'groupRect', position: { x: 0, y: 0 }, data: { label: id, type: 'groupRect', status: 'unknown', services: [] } }
+ }
+
+ it('fires onRequestAddToZone when a node is dropped over a zone', () => {
+ const onRequestAddToZone = vi.fn()
+ const node = makeNode('n1')
+ rf.intersecting = [zoneNode('z1')]
+ render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
+ expect(onRequestAddToZone).toHaveBeenCalledWith({ nodeId: 'n1', zoneId: 'z1' })
+ })
+
+ it('prefers a group and a container over a zone when they overlap', () => {
+ const onRequestAddToZone = vi.fn()
+ const onRequestAddToContainer = vi.fn()
+ const node = makeNode('n1')
+ rf.intersecting = [zoneNode('z1'), containerNode('px1')]
+ render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} onRequestAddToContainer={onRequestAddToContainer} />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
+ expect(onRequestAddToContainer).toHaveBeenCalledWith({ nodeId: 'n1', containerId: 'px1' })
+ expect(onRequestAddToZone).not.toHaveBeenCalled()
+ })
+
+ it('does not fire onRequestAddToZone when the dragged node is a zone itself', () => {
+ const onRequestAddToZone = vi.fn()
+ const node = zoneNode('z2')
+ rf.intersecting = [zoneNode('z1')]
+ render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
+ expect(onRequestAddToZone).not.toHaveBeenCalled()
+ })
+
+ it('detaches a zone child dropped outside its zone', () => {
+ const zone = { ...zoneNode('z1'), position: { x: 100, y: 100 } }
+ const child = { ...makeNode('n1'), parentId: 'z1', position: { x: 20, y: 20 } }
+ useCanvasStore.setState({ nodes: [zone, child] })
+ rf.intersecting = []
+ render(<CanvasContainer />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, child, [child])
+ const after = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
+ expect(after.parentId).toBeUndefined()
+ expect(after.position).toEqual({ x: 120, y: 120 })
+ })
+
+ it('keeps a zone child parented when it is dropped inside its zone', () => {
+ const zone = zoneNode('z1')
+ const child = { ...makeNode('n1'), parentId: 'z1' }
+ useCanvasStore.setState({ nodes: [zone, child] })
+ rf.intersecting = [zone]
+ render(<CanvasContainer />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, child, [child])
+ expect(useCanvasStore.getState().nodes.find((n) => n.id === 'n1')?.parentId).toBe('z1')
+ })
+
// ── Canvas settings ───────────────────────────────────────────────────────
it('enables snapToGrid', () => {
diff --git a/frontend/src/components/canvas/nodes/GroupRectNode.tsx b/frontend/src/components/canvas/nodes/GroupRectNode.tsx
index 7a780a2..11ad2a2 100644
--- a/frontend/src/components/canvas/nodes/GroupRectNode.tsx
+++ b/frontend/src/components/canvas/nodes/GroupRectNode.tsx
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { Handle, Position, NodeResizer, type NodeProps, type Node } from '@xyflow/react'
import { ChevronDown } from 'lucide-react'
import { useCanvasStore } from '@/stores/canvasStore'
-import { getZoneSpatialChildren } from '@/utils/collapseFilter'
+import { getZoneChildren } from '@/utils/collapseFilter'
import type { NodeData, TextPosition } from '@/types'
const FONT_FAMILIES: Record<string, string> = {
@@ -55,11 +55,11 @@ export function GroupRectNode({ id, data, selected }: NodeProps<Node<NodeData>>)
const textPos = (rc.text_position ?? 'top-left') as TextPosition
const posStyle = POSITION_STYLES[textPos]
- // Count children for collapse badge — groupRect zones don't parent their
- // contents via React Flow parentId, so we hit-test by spatial containment.
+ // Count children for collapse badge — a zone holds both real parentId
+ // children (dropped inside) and top-level nodes merely overlapping it.
const selfNode = (nodes ?? []).find((n) => n.id === id)
const childrenCount = selfNode
- ? getZoneSpatialChildren(selfNode, nodes ?? []).length
+ ? getZoneChildren(selfNode, nodes ?? []).length
: 0
const outsideJustify = textPos.includes('right') ? 'flex-end'
diff --git a/frontend/src/components/modals/ConfirmAddToGroupModal.tsx b/frontend/src/components/modals/ConfirmAddToGroupModal.tsx
index bcdfabb..2ac85a0 100644
--- a/frontend/src/components/modals/ConfirmAddToGroupModal.tsx
+++ b/frontend/src/components/modals/ConfirmAddToGroupModal.tsx
@@ -15,7 +15,7 @@ interface ConfirmAddToGroupModalProps {
/** Label of the destination group/container. */
targetLabel: string
/** Destination kind — drives the wording. Defaults to 'group'. */
- variant?: 'group' | 'container'
+ variant?: 'group' | 'container' | 'zone'
onConfirm: () => void
onCancel: () => void
}
@@ -28,8 +28,8 @@ export function ConfirmAddToGroupModal({
onConfirm,
onCancel,
}: ConfirmAddToGroupModalProps) {
- const action = variant === 'container' ? 'Add to container' : 'Add to group'
- const noun = variant === 'container' ? 'container' : 'group'
+ const noun = variant === 'container' ? 'container' : variant === 'zone' ? 'zone' : 'group'
+ const action = `Add to ${noun}`
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) onCancel() }}>
<DialogContent className="max-w-sm">
diff --git a/frontend/src/stores/__tests__/canvasStore/zones.test.ts b/frontend/src/stores/__tests__/canvasStore/zones.test.ts
new file mode 100644
index 0000000..6d14fbd
--- /dev/null
+++ b/frontend/src/stores/__tests__/canvasStore/zones.test.ts
@@ -0,0 +1,135 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useCanvasStore } from '@/stores/canvasStore'
+import { makeNode } from '@/test/factories'
+
+function resetStore() {
+ useCanvasStore.setState({
+ nodes: [],
+ edges: [],
+ hasUnsavedChanges: false,
+ selectedNodeId: null,
+ selectedNodeIds: [],
+ editingGroupRectId: null,
+ editingTextId: null,
+ past: [],
+ future: [],
+ clipboard: { nodes: [], edges: [] },
+ serviceStatuses: {},
+ floorMap: null,
+ })
+}
+
+const zone = (id: string, x = 100, y = 100) => ({
+ ...makeNode(id, { type: 'groupRect' }),
+ type: 'groupRect',
+ position: { x, y },
+ width: 400,
+ height: 300,
+})
+
+describe('canvasStore — zone (groupRect) parenting', () => {
+ beforeEach(resetStore)
+
+ it('addToZone parents the node and rebases its position on the zone', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), { ...makeNode('n1'), position: { x: 160, y: 220 } }],
+ })
+ useCanvasStore.getState().addToZone('z1', 'n1')
+
+ const child = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
+ expect(child.parentId).toBe('z1')
+ expect(child.data.parent_id).toBe('z1')
+ expect(child.position).toEqual({ x: 60, y: 120 })
+ })
+
+ it('addToZone does not clamp the child with extent, so it can be dragged out', () => {
+ useCanvasStore.setState({ nodes: [zone('z1'), makeNode('n1')] })
+ useCanvasStore.getState().addToZone('z1', 'n1')
+ expect(useCanvasStore.getState().nodes.find((n) => n.id === 'n1')?.extent).toBeUndefined()
+ })
+
+ it('addToZone orders the zone before its child (React Flow requirement)', () => {
+ useCanvasStore.setState({ nodes: [makeNode('n1'), zone('z1')] })
+ useCanvasStore.getState().addToZone('z1', 'n1')
+ const ids = useCanvasStore.getState().nodes.map((n) => n.id)
+ expect(ids.indexOf('z1')).toBeLessThan(ids.indexOf('n1'))
+ })
+
+ it('addToZone is a no-op when the target is not a zone', () => {
+ useCanvasStore.setState({ nodes: [makeNode('g1', { type: 'group' }), makeNode('n1')] })
+ useCanvasStore.getState().addToZone('g1', 'n1')
+ expect(useCanvasStore.getState().nodes.find((n) => n.id === 'n1')?.parentId).toBeUndefined()
+ })
+
+ it('addToZone is a no-op when the node is already in that zone', () => {
+ useCanvasStore.setState({ nodes: [zone('z1'), makeNode('n1')] })
+ useCanvasStore.getState().addToZone('z1', 'n1')
+ const first = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
+ useCanvasStore.getState().addToZone('z1', 'n1')
+ expect(useCanvasStore.getState().nodes.find((n) => n.id === 'n1')).toEqual(first)
+ })
+
+ it('removeFromGroup releases a zone child back to absolute coords', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), { ...makeNode('n1'), position: { x: 160, y: 220 } }],
+ })
+ useCanvasStore.getState().addToZone('z1', 'n1')
+ useCanvasStore.getState().removeFromGroup('z1', 'n1')
+
+ const child = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
+ expect(child.parentId).toBeUndefined()
+ expect(child.data.parent_id).toBeUndefined()
+ expect(child.position).toEqual({ x: 160, y: 220 })
+ })
+
+ it('deleting a zone releases its children instead of deleting them', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), { ...makeNode('n1'), position: { x: 160, y: 220 } }],
+ })
+ useCanvasStore.getState().addToZone('z1', 'n1')
+ useCanvasStore.getState().deleteNode('z1')
+
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.map((n) => n.id)).toEqual(['n1'])
+ expect(nodes[0].parentId).toBeUndefined()
+ expect(nodes[0].position).toEqual({ x: 160, y: 220 })
+ })
+
+ it('deleting a container still cascades to its children', () => {
+ useCanvasStore.setState({
+ nodes: [
+ makeNode('px1', { type: 'proxmox', container_mode: true }),
+ { ...makeNode('vm1'), parentId: 'px1' },
+ ],
+ })
+ useCanvasStore.getState().deleteNode('px1')
+ expect(useCanvasStore.getState().nodes).toHaveLength(0)
+ })
+
+ it('addNode nests a node under a zone without clamping it', () => {
+ useCanvasStore.getState().addNode(zone('z1'))
+ useCanvasStore.getState().addNode({
+ ...makeNode('n1', { parent_id: 'z1' }),
+ position: { x: 160, y: 220 },
+ })
+ const child = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
+ expect(child.parentId).toBe('z1')
+ expect(child.extent).toBeUndefined()
+ expect(child.position).toEqual({ x: 60, y: 120 })
+ })
+
+ it('updateNode can attach a node to a zone and detach it again', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), { ...makeNode('n1'), position: { x: 160, y: 220 } }],
+ })
+ useCanvasStore.getState().updateNode('n1', { parent_id: 'z1' })
+ const attached = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
+ expect(attached.parentId).toBe('z1')
+ expect(attached.extent).toBeUndefined()
+
+ useCanvasStore.getState().updateNode('n1', { parent_id: undefined })
+ const detached = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!
+ expect(detached.parentId).toBeUndefined()
+ expect(detached.position).toEqual({ x: 160, y: 220 })
+ })
+})
diff --git a/frontend/src/stores/canvasStore.ts b/frontend/src/stores/canvasStore.ts
index def0f18..f01b473 100644
--- a/frontend/src/stores/canvasStore.ts
+++ b/frontend/src/stores/canvasStore.ts
@@ -191,6 +191,7 @@ interface CanvasState {
ungroup: (groupId: string) => void
addToGroup: (groupId: string, childId: string) => void
addToContainer: (containerId: string, childId: string) => void
+ addToZone: (zoneId: string, childId: string) => void
removeFromGroup: (groupId: string, childId: string) => void
markSaved: () => void
markUnsaved: () => void
@@ -448,13 +449,16 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {
addNode: (node) =>
set((state) => {
const parent = node.data.parent_id ? state.nodes.find((n) => n.id === node.data.parent_id) : null
- // A visual group nests its children just like a container-mode host.
- const shouldNestInParent = !!(parent?.data.container_mode) || parent?.data.type === 'group'
+ // A visual group — and a groupRect zone — nests its children just like a
+ // container-mode host.
+ const shouldNestInParent = !!(parent?.data.container_mode) || parent?.data.type === 'group' || parent?.data.type === 'groupRect'
+ // Zones keep their children free to be dragged back out (see addToZone).
+ const nestExtent = parent?.data.type === 'groupRect' ? undefined : ('parent' as const)
const enriched = node.data.parent_id && shouldNestInParent
? {
...node,
parentId: node.data.parent_id,
- extent: 'parent' as const,
+ extent: nestExtent,
position: {
x: Math.max(10, node.position.x - parent.position.x),
y: Math.max(10, node.position.y - parent.position.y),
@@ -503,10 +507,10 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {
updated.extent = undefined
} else if (newParentId && newParentId !== n.parentId) {
const parent = state.nodes.find((p) => p.id === newParentId)
- if (parent?.data.container_mode || parent?.data.type === 'group') {
- // Attaching to a container-mode host or a visual group: nest visually
+ if (parent?.data.container_mode || parent?.data.type === 'group' || parent?.data.type === 'groupRect') {
+ // Attaching to a container-mode host, a visual group or a zone.
updated.parentId = newParentId
- updated.extent = 'parent' as const
+ updated.extent = parent.data.type === 'groupRect' ? undefined : ('parent' as const)
// Convert absolute position to parent-relative (keep node visible inside)
updated.position = {
x: Math.max(10, n.position.x - parent.position.x),
@@ -563,13 +567,34 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {
deleteNode: (id) =>
set((state) => {
const idsToRemove = new Set<string>()
+ // Deleting a zone deletes the zone, never what it happens to contain:
+ // its children are released back to the canvas in absolute coords.
+ const released: Node<NodeData>[] = []
const collect = (nodeId: string) => {
idsToRemove.add(nodeId)
- state.nodes.filter((n) => n.parentId === nodeId).forEach((n) => collect(n.id))
+ const node = state.nodes.find((n) => n.id === nodeId)
+ const children = state.nodes.filter((n) => n.parentId === nodeId)
+ if (node?.data.type === 'groupRect') {
+ children.forEach((c) => released.push({
+ ...c,
+ parentId: undefined,
+ extent: undefined,
+ position: {
+ x: node.position.x + c.position.x,
+ y: node.position.y + c.position.y,
+ },
+ data: { ...c.data, parent_id: undefined },
+ }))
+ return
+ }
+ children.forEach((n) => collect(n.id))
}
collect(id)
+ const releasedById = new Map(released.map((n) => [n.id, n]))
return {
- nodes: state.nodes.filter((n) => !idsToRemove.has(n.id)),
+ nodes: state.nodes
+ .filter((n) => !idsToRemove.has(n.id))
+ .map((n) => releasedById.get(n.id) ?? n),
edges: state.edges.filter((e) => !idsToRemove.has(e.source) && !idsToRemove.has(e.target)),
selectedNodeId: idsToRemove.has(state.selectedNodeId ?? '') ? null : state.selectedNodeId,
hasUnsavedChanges: true,
@@ -891,6 +916,53 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {
}
}),
+ // Nest an existing top-level node inside a groupRect zone. Mirrors
+ // addToGroup, with one deliberate difference: NO `extent: 'parent'`. A zone
+ // is a loose visual area, so a child must stay draggable out of it — the
+ // canvas detaches it on drop (see CanvasContainer). Parenting is what makes
+ // moving the zone move its contents.
+ addToZone: (zoneId, childId) =>
+ set((state) => {
+ const zone = state.nodes.find((n) => n.id === zoneId)
+ const child = state.nodes.find((n) => n.id === childId)
+ if (!zone || !child || zone.data.type !== 'groupRect') return state
+ if (child.id === zoneId || child.parentId === zoneId) return state
+ // A zone cannot become a child of a node it already contains.
+ if (zone.parentId === childId) return state
+
+ const updatedNodes = state.nodes.map((n) => {
+ if (n.id !== childId) return n
+ return {
+ ...n,
+ parentId: zoneId,
+ // Absolute → zone-relative.
+ position: {
+ x: n.position.x - zone.position.x,
+ y: n.position.y - zone.position.y,
+ },
+ selected: false,
+ data: { ...n.data, parent_id: zoneId },
+ }
+ })
+
+ // React Flow requires the parent to precede its children in the array.
+ const others = updatedNodes.filter((n) => n.id !== childId)
+ const movedChild = updatedNodes.find((n) => n.id === childId)!
+ const zoneIdx = others.findIndex((n) => n.id === zoneId)
+ const nodes = [
+ ...others.slice(0, zoneIdx + 1),
+ movedChild,
+ ...others.slice(zoneIdx + 1),
+ ]
+
+ return {
+ nodes,
+ hasUnsavedChanges: true,
+ past: [...state.past.slice(-49), { nodes: state.nodes, edges: state.edges }],
+ future: [],
+ }
+ }),
+
// Release a single child from a group back to the canvas. Group stays.
removeFromGroup: (groupId, childId) =>
set((state) => {
diff --git a/frontend/src/utils/__tests__/canvasSerializer.test.ts b/frontend/src/utils/__tests__/canvasSerializer.test.ts
index 5ce0513..0da81fa 100644
--- a/frontend/src/utils/__tests__/canvasSerializer.test.ts
+++ b/frontend/src/utils/__tests__/canvasSerializer.test.ts
@@ -366,6 +366,12 @@ describe('deserializeApiNode — regular node', () => {
expect(result.extent).toBe('parent')
})
+ it('restores a zone child parented but not extent-clamped', () => {
+ const result = deserializeApiNode(makeApiNode({ parent_id: 'z1' }), emptyMap, new Set(['z1']))
+ expect(result.parentId).toBe('z1')
+ expect(result.extent).toBeUndefined()
+ })
+
it('does not set parentId when parent is not in container mode', () => {
const map = new Map([['px1', false]])
const result = deserializeApiNode(makeApiNode({ parent_id: 'px1' }), map)
diff --git a/frontend/src/utils/__tests__/collapseFilter.test.ts b/frontend/src/utils/__tests__/collapseFilter.test.ts
index c5e8290..1d588ab 100644
--- a/frontend/src/utils/__tests__/collapseFilter.test.ts
+++ b/frontend/src/utils/__tests__/collapseFilter.test.ts
@@ -4,6 +4,7 @@ import {
getVisibleNodeIds,
rewireEdgesForCollapse,
getZoneSpatialChildren,
+ getZoneChildren,
computeCollapseInfo,
} from '../collapseFilter'
import type { EdgeData, NodeData } from '@/types'
@@ -134,6 +135,31 @@ describe('getZoneSpatialChildren', () => {
})
})
+describe('getZoneChildren', () => {
+ it('unions real parentId children with the ones merely sitting on the zone', () => {
+ const zone = mkNode('zone', { position: { x: 0, y: 0 }, width: 400, height: 300 })
+ const parented = mkNode('parented', { parentId: 'zone', type: 'server' })
+ const overlapping = mkNode('overlapping', { position: { x: 100, y: 50 }, type: 'server' })
+ const outside = mkNode('outside', { position: FAR, type: 'server' })
+ const found = getZoneChildren(zone, [zone, parented, overlapping, outside])
+ expect(found.sort()).toEqual(['overlapping', 'parented'])
+ })
+
+ it('does not double-count a child that is both parented and overlapping', () => {
+ const zone = mkNode('zone', { position: { x: 0, y: 0 }, width: 400, height: 300 })
+ const child = mkNode('child', { parentId: 'zone', position: { x: 10, y: 10 }, type: 'server' })
+ expect(getZoneChildren(zone, [zone, child])).toEqual(['child'])
+ })
+})
+
+describe('computeCollapseInfo — a zone with real children', () => {
+ it('hides parentId children when the zone collapses', () => {
+ const zone = mkNode('zone', { collapsed: true, width: 400, height: 300 })
+ const child = mkNode('child', { parentId: 'zone', type: 'server' })
+ expect(getVisibleNodeIds([zone, child])).toEqual(new Set(['zone']))
+ })
+})
+
describe('computeCollapseInfo — spatial collapse via groupRect zones', () => {
it('hides nodes spatially inside a collapsed zone and records hiddenBy', () => {
const zone = mkNode('zone', { collapsed: true, width: 400, height: 300 })
diff --git a/frontend/src/utils/canvasSerializer.ts b/frontend/src/utils/canvasSerializer.ts
index 4561280..2d629d9 100644
--- a/frontend/src/utils/canvasSerializer.ts
+++ b/frontend/src/utils/canvasSerializer.ts
@@ -177,6 +177,8 @@ export function serializeEdge(e: Edge<EdgeData>): Record<string, unknown> {
export function deserializeApiNode(
n: ApiNode,
proxmoxContainerMap: Map<string, boolean>,
+ /** Ids of groupRect zones, which parent their contents without clamping them. */
+ zoneIds?: Set<string>,
): Node<NodeData> {
const normalizedType = n.type === 'docker' ? 'docker_host' : n.type
if (n.type === 'groupRect') {
@@ -199,6 +201,9 @@ export function deserializeApiNode(
}
}
const parentIsContainer = n.parent_id ? (proxmoxContainerMap.get(n.parent_id) ?? false) : false
+ // A node dropped inside a zone is parented (so the zone moves it) but never
+ // extent-clamped — it must stay draggable back out.
+ const parentIsZone = n.parent_id ? (zoneIds?.has(n.parent_id) ?? false) : false
return {
id: n.id,
type: normalizedType,
@@ -214,7 +219,11 @@ export function deserializeApiNode(
right_handles: clampHandles('right', n.right_handles ?? 0),
collapsed: Boolean(n.custom_colors?.collapsed),
} as unknown as NodeData,
- ...(n.parent_id && parentIsContainer ? { parentId: n.parent_id, extent: 'parent' as const } : {}),
+ ...(n.parent_id && parentIsZone
+ ? { parentId: n.parent_id }
+ : 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.
diff --git a/frontend/src/utils/collapseFilter.ts b/frontend/src/utils/collapseFilter.ts
index 83357d0..72597e3 100644
--- a/frontend/src/utils/collapseFilter.ts
+++ b/frontend/src/utils/collapseFilter.ts
@@ -66,6 +66,22 @@ export function getZoneSpatialChildren(
return out
}
+/**
+ * Everything a zone "contains": nodes really parented to it (dropped inside,
+ * so they follow it when it moves) plus the top-level nodes merely sitting on
+ * top of it. Used for the collapse badge count.
+ */
+export function getZoneChildren(
+ zone: Node<NodeData>,
+ nodes: Node<NodeData>[],
+): string[] {
+ const ids = new Set(getZoneSpatialChildren(zone, nodes))
+ for (const n of nodes) {
+ if (n.parentId === zone.id) ids.add(n.id)
+ }
+ return [...ids]
+}
+
function buildChildrenByParent(nodes: Node<NodeData>[]): Map<string, string[]> {
const m = new Map<string, string[]>()
for (const n of nodes) {