Skip to content

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

feat(canvas): add a whole selection to a zone in one drop

Pouzor3301f00e5739
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ba846b5..a168857 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -65,7 +65,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, addToZone, importZoneSubnet, 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, addNodesToGroup, addNodesToContainer, addNodesToZone, importZoneSubnet, floorMap, setFloorMap } = useCanvasStore()
const canvasRef = useRef<HTMLDivElement>(null)
const { isAuthenticated, isInitialized } = useAuthStore()
const authBootstrapStarted = useRef(false)
@@ -132,9 +132,14 @@ export default function App() {
const [addTextOpen, setAddTextOpen] = useState(false)
const [editNodeId, setEditNodeId] = useState<string | null>(null)
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 [pendingGroupAdd, setPendingGroupAdd] = useState<{ nodeIds: string[]; groupId: string } | null>(null)
+ const [pendingContainerAdd, setPendingContainerAdd] = useState<{ nodeIds: string[]; containerId: string } | null>(null)
+ const [pendingZoneAdd, setPendingZoneAdd] = useState<{ nodeIds: string[]; zoneId: string } | null>(null)
+ // Labels for the add-to-group/container/zone confirmation, in the order dropped.
+ const labelsOf = useCallback(
+ (ids: string[]) => ids.map((id) => nodes.find((n) => n.id === id)?.data.label ?? ''),
+ [nodes],
+ )
const [editEdgeId, setEditEdgeId] = useState<string | null>(null)
const [scanConfigOpen, setScanConfigOpen] = useState(false)
const [settingsOpen, setSettingsOpen] = useState(false)
@@ -1317,10 +1322,10 @@ export default function App() {
<ConfirmAddToGroupModal
open={!!pendingGroupAdd}
- nodeLabel={pendingGroupAdd ? (nodes.find((n) => n.id === pendingGroupAdd.nodeId)?.data.label ?? '') : ''}
+ nodeLabels={pendingGroupAdd ? labelsOf(pendingGroupAdd.nodeIds) : []}
targetLabel={pendingGroupAdd ? (nodes.find((n) => n.id === pendingGroupAdd.groupId)?.data.label ?? '') : ''}
onConfirm={() => {
- if (pendingGroupAdd) addToGroup(pendingGroupAdd.groupId, pendingGroupAdd.nodeId)
+ if (pendingGroupAdd) addNodesToGroup(pendingGroupAdd.groupId, pendingGroupAdd.nodeIds)
setPendingGroupAdd(null)
}}
onCancel={() => setPendingGroupAdd(null)}
@@ -1329,10 +1334,10 @@ export default function App() {
<ConfirmAddToGroupModal
open={!!pendingContainerAdd}
variant="container"
- nodeLabel={pendingContainerAdd ? (nodes.find((n) => n.id === pendingContainerAdd.nodeId)?.data.label ?? '') : ''}
+ nodeLabels={pendingContainerAdd ? labelsOf(pendingContainerAdd.nodeIds) : []}
targetLabel={pendingContainerAdd ? (nodes.find((n) => n.id === pendingContainerAdd.containerId)?.data.label ?? '') : ''}
onConfirm={() => {
- if (pendingContainerAdd) addToContainer(pendingContainerAdd.containerId, pendingContainerAdd.nodeId)
+ if (pendingContainerAdd) addNodesToContainer(pendingContainerAdd.containerId, pendingContainerAdd.nodeIds)
setPendingContainerAdd(null)
}}
onCancel={() => setPendingContainerAdd(null)}
@@ -1341,10 +1346,10 @@ export default function App() {
<ConfirmAddToGroupModal
open={!!pendingZoneAdd}
variant="zone"
- nodeLabel={pendingZoneAdd ? (nodes.find((n) => n.id === pendingZoneAdd.nodeId)?.data.label ?? '') : ''}
+ nodeLabels={pendingZoneAdd ? labelsOf(pendingZoneAdd.nodeIds) : []}
targetLabel={pendingZoneAdd ? (nodes.find((n) => n.id === pendingZoneAdd.zoneId)?.data.label ?? '') : ''}
onConfirm={() => {
- if (pendingZoneAdd) addToZone(pendingZoneAdd.zoneId, pendingZoneAdd.nodeId)
+ if (pendingZoneAdd) addNodesToZone(pendingZoneAdd.zoneId, pendingZoneAdd.nodeIds)
setPendingZoneAdd(null)
}}
onCancel={() => setPendingZoneAdd(null)}
diff --git a/frontend/src/components/canvas/CanvasContainer.tsx b/frontend/src/components/canvas/CanvasContainer.tsx
index 9593bc0..bc71076 100644
--- a/frontend/src/components/canvas/CanvasContainer.tsx
+++ b/frontend/src/components/canvas/CanvasContainer.tsx
@@ -32,9 +32,9 @@ interface CanvasContainerProps {
onEdgeDoubleClick?: (edge: Edge<EdgeData>) => void
onNodeDoubleClick?: (node: Node<NodeData>) => void
onNodeDragStart?: () => void
- onRequestAddToGroup?: (payload: { nodeId: string; groupId: string }) => void
- onRequestAddToContainer?: (payload: { nodeId: string; containerId: string }) => void
- onRequestAddToZone?: (payload: { nodeId: string; zoneId: string }) => void
+ onRequestAddToGroup?: (payload: { nodeIds: string[]; groupId: string }) => void
+ onRequestAddToContainer?: (payload: { nodeIds: string[]; containerId: string }) => void
+ onRequestAddToZone?: (payload: { nodeIds: string[]; zoneId: string }) => void
onOpenInventory?: (deviceId: string) => void
}
@@ -145,33 +145,55 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
const { guides, onNodeDrag, onNodeDragStop } = useAlignmentGuides()
- // 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.
+ // Drop a selection onto a group → ask App to confirm adding it. Runs before
+ // the alignment snap so detection uses the dropped position. `dragNodes` is
+ // the whole multi-selection being dragged; `dragNode` (the one under the
+ // cursor) only picks the destination.
const handleNodeDragStop = useCallback<NonNullable<typeof onNodeDragStop>>((event, dragNode, dragNodes) => {
- if (dragNode && dragNode.data.type !== 'group' && dragNode.data.type !== 'groupRect') {
+ // A single drag reports an empty `dragNodes` in some React Flow paths, so
+ // fall back to the dragged node itself.
+ const dragged = dragNodes && dragNodes.length > 0 ? dragNodes : dragNode ? [dragNode] : []
+ // Groups and zones are containers, never contents.
+ const movable = dragged.filter((n) => n.data.type !== 'group' && n.data.type !== 'groupRect')
+
+ if (dragNode && dragNode.data.type !== 'group' && dragNode.data.type !== 'groupRect' && movable.length > 0) {
const intersecting = getIntersectingNodes(dragNode)
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.
+ // how the user takes a node back out of it. The whole selection leaves
+ // with it, not only the node under the cursor.
if (!intersecting.some((n) => n.id === zoneParent.id)) {
- removeFromGroup(zoneParent.id, dragNode.id)
+ for (const n of movable) {
+ if (n.parentId === zoneParent.id) removeFromGroup(zoneParent.id, n.id)
+ }
}
} else if (!dragNode.parentId) {
+ // Only free nodes join a new parent; one already nested elsewhere in the
+ // selection keeps its own parent.
+ const nodeIds = movable.filter((n) => !n.parentId).map((n) => n.id)
const group = intersecting.find((n) => n.data.type === 'group')
const container = intersecting.find((n) => n.id !== dragNode.id && n.data.container_mode === true)
+ // The destination can be part of the dragged selection (lasso over
+ // everything); it cannot also be one of its own new children.
+ const targetless = (targetId: string) => nodeIds.filter((id) => id !== targetId)
if (group) {
- onRequestAddToGroup?.({ nodeId: dragNode.id, groupId: group.id })
+ const ids = targetless(group.id)
+ if (ids.length > 0) onRequestAddToGroup?.({ nodeIds: ids, groupId: group.id })
} else if (container) {
// Any node in container_mode (proxmox, docker_host, …) accepts children.
- onRequestAddToContainer?.({ nodeId: dragNode.id, containerId: container.id })
+ const ids = targetless(container.id)
+ if (ids.length > 0) onRequestAddToContainer?.({ nodeIds: ids, 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 })
+ if (zone) {
+ const ids = targetless(zone.id)
+ if (ids.length > 0) onRequestAddToZone?.({ nodeIds: ids, zoneId: zone.id })
+ }
}
}
}
diff --git a/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx b/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx
index 042ade7..0480da0 100644
--- a/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx
+++ b/frontend/src/components/canvas/__tests__/CanvasContainer.test.tsx
@@ -177,7 +177,7 @@ describe('CanvasContainer', () => {
rf.intersecting = [group]
render(<CanvasContainer onRequestAddToGroup={onRequestAddToGroup} />)
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
- expect(onRequestAddToGroup).toHaveBeenCalledWith({ nodeId: 'n1', groupId: 'g1' })
+ expect(onRequestAddToGroup).toHaveBeenCalledWith({ nodeIds: ['n1'], groupId: 'g1' })
})
it('does not fire onRequestAddToGroup when no group is under the node', () => {
@@ -219,7 +219,7 @@ describe('CanvasContainer', () => {
rf.intersecting = [containerNode('px1')]
render(<CanvasContainer onRequestAddToContainer={onRequestAddToContainer} />)
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
- expect(onRequestAddToContainer).toHaveBeenCalledWith({ nodeId: 'n1', containerId: 'px1' })
+ expect(onRequestAddToContainer).toHaveBeenCalledWith({ nodeIds: ['n1'], containerId: 'px1' })
})
it('prefers a group over a container when both intersect', () => {
@@ -229,7 +229,7 @@ describe('CanvasContainer', () => {
rf.intersecting = [containerNode('px1'), groupNode('g1')]
render(<CanvasContainer onRequestAddToGroup={onRequestAddToGroup} onRequestAddToContainer={onRequestAddToContainer} />)
;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, node, [node])
- expect(onRequestAddToGroup).toHaveBeenCalledWith({ nodeId: 'n1', groupId: 'g1' })
+ expect(onRequestAddToGroup).toHaveBeenCalledWith({ nodeIds: ['n1'], groupId: 'g1' })
expect(onRequestAddToContainer).not.toHaveBeenCalled()
})
@@ -263,7 +263,7 @@ describe('CanvasContainer', () => {
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' })
+ expect(onRequestAddToZone).toHaveBeenCalledWith({ nodeIds: ['n1'], zoneId: 'z1' })
})
it('prefers a group and a container over a zone when they overlap', () => {
@@ -273,7 +273,7 @@ describe('CanvasContainer', () => {
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(onRequestAddToContainer).toHaveBeenCalledWith({ nodeIds: ['n1'], containerId: 'px1' })
expect(onRequestAddToZone).not.toHaveBeenCalled()
})
@@ -308,6 +308,59 @@ describe('CanvasContainer', () => {
expect(useCanvasStore.getState().nodes.find((n) => n.id === 'n1')?.parentId).toBe('z1')
})
+ // ── Multi-selection drops (#365) ──────────────────────────────────────────
+
+ it('fires onRequestAddToZone with every dragged node, not just the one under the cursor', () => {
+ const onRequestAddToZone = vi.fn()
+ const dragged = [makeNode('n1'), makeNode('n2'), makeNode('n3')]
+ rf.intersecting = [zoneNode('z1')]
+ render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, dragged[0], dragged)
+ expect(onRequestAddToZone).toHaveBeenCalledWith({ nodeIds: ['n1', 'n2', 'n3'], zoneId: 'z1' })
+ })
+
+ it('leaves zones and groups out of a dragged selection', () => {
+ const onRequestAddToZone = vi.fn()
+ const dragged = [makeNode('n1'), zoneNode('z1'), groupNode('g1')]
+ rf.intersecting = [zoneNode('z2')]
+ render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, dragged[0], dragged)
+ expect(onRequestAddToZone).toHaveBeenCalledWith({ nodeIds: ['n1'], zoneId: 'z2' })
+ })
+
+ it('never asks to add the destination container to itself', () => {
+ const onRequestAddToContainer = vi.fn()
+ const target = containerNode('px1')
+ const dragged = [makeNode('n1'), target]
+ rf.intersecting = [target]
+ render(<CanvasContainer onRequestAddToContainer={onRequestAddToContainer} />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, dragged[0], dragged)
+ expect(onRequestAddToContainer).toHaveBeenCalledWith({ nodeIds: ['n1'], containerId: 'px1' })
+ })
+
+ it('keeps an already-parented node in the selection with its own parent', () => {
+ const onRequestAddToZone = vi.fn()
+ const dragged = [makeNode('n1'), { ...makeNode('n2'), parentId: 'pxOther' }]
+ rf.intersecting = [zoneNode('z1')]
+ render(<CanvasContainer onRequestAddToZone={onRequestAddToZone} />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, dragged[0], dragged)
+ expect(onRequestAddToZone).toHaveBeenCalledWith({ nodeIds: ['n1'], zoneId: 'z1' })
+ })
+
+ it('detaches every dragged child when a selection leaves its zone', () => {
+ const zone = { ...zoneNode('z1'), position: { x: 100, y: 100 } }
+ const c1 = { ...makeNode('n1'), parentId: 'z1', position: { x: 20, y: 20 } }
+ const c2 = { ...makeNode('n2'), parentId: 'z1', position: { x: 40, y: 40 } }
+ useCanvasStore.setState({ nodes: [zone, c1, c2] })
+ rf.intersecting = []
+ render(<CanvasContainer />)
+ ;(rfProps.onNodeDragStop as (...args: unknown[]) => unknown)({} as MouseEvent, c1, [c1, c2])
+ const after = useCanvasStore.getState().nodes
+ expect(after.find((n) => n.id === 'n1')!.parentId).toBeUndefined()
+ expect(after.find((n) => n.id === 'n2')!.parentId).toBeUndefined()
+ expect(after.find((n) => n.id === 'n2')!.position).toEqual({ x: 140, y: 140 })
+ })
+
// ── Canvas settings ───────────────────────────────────────────────────────
it('enables snapToGrid', () => {
diff --git a/frontend/src/components/modals/ConfirmAddToGroupModal.tsx b/frontend/src/components/modals/ConfirmAddToGroupModal.tsx
index 2ac85a0..3cf646b 100644
--- a/frontend/src/components/modals/ConfirmAddToGroupModal.tsx
+++ b/frontend/src/components/modals/ConfirmAddToGroupModal.tsx
@@ -9,9 +9,14 @@ import {
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
+/** Labels past this many are summarized as "+N more" instead of listed. */
+const MAX_LISTED_LABELS = 5
+
interface ConfirmAddToGroupModalProps {
open: boolean
- nodeLabel: string
+ /** Labels of the nodes being added — one entry for a single drop, several for
+ * a multi-selection. */
+ nodeLabels: string[]
/** Label of the destination group/container. */
targetLabel: string
/** Destination kind — drives the wording. Defaults to 'group'. */
@@ -22,7 +27,7 @@ interface ConfirmAddToGroupModalProps {
export function ConfirmAddToGroupModal({
open,
- nodeLabel,
+ nodeLabels,
targetLabel,
variant = 'group',
onConfirm,
@@ -30,6 +35,14 @@ export function ConfirmAddToGroupModal({
}: ConfirmAddToGroupModalProps) {
const noun = variant === 'container' ? 'container' : variant === 'zone' ? 'zone' : 'group'
const action = `Add to ${noun}`
+ const count = nodeLabels.length
+ const listed = nodeLabels.slice(0, MAX_LISTED_LABELS).join(', ')
+ const subject =
+ count === 1
+ ? nodeLabels[0]
+ : count <= MAX_LISTED_LABELS
+ ? `${count} nodes (${listed})`
+ : `${count} nodes (${listed}, +${count - MAX_LISTED_LABELS} more)`
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) onCancel() }}>
<DialogContent className="max-w-sm">
@@ -39,7 +52,7 @@ export function ConfirmAddToGroupModal({
{action}
</DialogTitle>
<DialogDescription>
- Add <span className="font-medium text-foreground">{nodeLabel}</span> to the {noun}{' '}
+ Add <span className="font-medium text-foreground">{subject}</span> to the {noun}{' '}
<span className="font-medium text-foreground">{targetLabel}</span>?
</DialogDescription>
</DialogHeader>
diff --git a/frontend/src/components/modals/__tests__/ConfirmAddToGroupModal.test.tsx b/frontend/src/components/modals/__tests__/ConfirmAddToGroupModal.test.tsx
index 5bc7d40..0427673 100644
--- a/frontend/src/components/modals/__tests__/ConfirmAddToGroupModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/ConfirmAddToGroupModal.test.tsx
@@ -5,14 +5,14 @@ import { ConfirmAddToGroupModal } from '../ConfirmAddToGroupModal'
describe('ConfirmAddToGroupModal', () => {
it('renders nothing when closed', () => {
render(
- <ConfirmAddToGroupModal open={false} nodeLabel="Router" targetLabel="DMZ" onConfirm={vi.fn()} onCancel={vi.fn()} />,
+ <ConfirmAddToGroupModal open={false} nodeLabels={['Router']} targetLabel="DMZ" onConfirm={vi.fn()} onCancel={vi.fn()} />,
)
expect(screen.queryByText('Add to group')).toBeNull()
})
it('shows node and group labels when open', () => {
render(
- <ConfirmAddToGroupModal open nodeLabel="Router" targetLabel="DMZ" onConfirm={vi.fn()} onCancel={vi.fn()} />,
+ <ConfirmAddToGroupModal open nodeLabels={['Router']} targetLabel="DMZ" onConfirm={vi.fn()} onCancel={vi.fn()} />,
)
expect(screen.getByText('Router')).toBeDefined()
expect(screen.getByText('DMZ')).toBeDefined()
@@ -21,7 +21,7 @@ describe('ConfirmAddToGroupModal', () => {
it('calls onConfirm when the confirm button is clicked', () => {
const onConfirm = vi.fn()
render(
- <ConfirmAddToGroupModal open nodeLabel="Router" targetLabel="DMZ" onConfirm={onConfirm} onCancel={vi.fn()} />,
+ <ConfirmAddToGroupModal open nodeLabels={['Router']} targetLabel="DMZ" onConfirm={onConfirm} onCancel={vi.fn()} />,
)
fireEvent.click(screen.getByRole('button', { name: /add to group/i }))
expect(onConfirm).toHaveBeenCalledOnce()
@@ -30,7 +30,7 @@ describe('ConfirmAddToGroupModal', () => {
it('calls onCancel when the cancel button is clicked', () => {
const onCancel = vi.fn()
render(
- <ConfirmAddToGroupModal open nodeLabel="Router" targetLabel="DMZ" onConfirm={vi.fn()} onCancel={onCancel} />,
+ <ConfirmAddToGroupModal open nodeLabels={['Router']} targetLabel="DMZ" onConfirm={vi.fn()} onCancel={onCancel} />,
)
fireEvent.click(screen.getByRole('button', { name: /cancel/i }))
expect(onCancel).toHaveBeenCalledOnce()
@@ -38,9 +38,30 @@ describe('ConfirmAddToGroupModal', () => {
it('uses container wording when variant is container', () => {
render(
- <ConfirmAddToGroupModal open variant="container" nodeLabel="VM" targetLabel="Proxmox" onConfirm={vi.fn()} onCancel={vi.fn()} />,
+ <ConfirmAddToGroupModal open variant="container" nodeLabels={['VM']} targetLabel="Proxmox" onConfirm={vi.fn()} onCancel={vi.fn()} />,
)
expect(screen.getByRole('button', { name: /add to container/i })).toBeDefined()
expect(screen.queryByText('Add to group')).toBeNull()
})
+
+ it('counts and lists the nodes when several are added at once', () => {
+ render(
+ <ConfirmAddToGroupModal open nodeLabels={['Router', 'Switch', 'NAS']} targetLabel="DMZ" variant="zone" onConfirm={vi.fn()} onCancel={vi.fn()} />,
+ )
+ expect(screen.getByText(/3 nodes \(Router, Switch, NAS\)/)).toBeInTheDocument()
+ expect(screen.getByText('DMZ')).toBeInTheDocument()
+ })
+
+ it('summarizes the tail past five labels', () => {
+ render(
+ <ConfirmAddToGroupModal
+ open
+ nodeLabels={['a', 'b', 'c', 'd', 'e', 'f', 'g']}
+ targetLabel="DMZ"
+ onConfirm={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ )
+ expect(screen.getByText(/7 nodes \(a, b, c, d, e, \+2 more\)/)).toBeInTheDocument()
+ })
})
diff --git a/frontend/src/stores/__tests__/canvasStore/zones.test.ts b/frontend/src/stores/__tests__/canvasStore/zones.test.ts
index f0618ab..49f0ee4 100644
--- a/frontend/src/stores/__tests__/canvasStore/zones.test.ts
+++ b/frontend/src/stores/__tests__/canvasStore/zones.test.ts
@@ -135,6 +135,129 @@ describe('canvasStore — zone (groupRect) parenting', () => {
})
})
+describe('canvasStore — batch parenting (#365)', () => {
+ beforeEach(resetStore)
+
+ it('addNodesToZone moves the whole selection, not just the first node', () => {
+ useCanvasStore.setState({
+ nodes: [
+ zone('z1'),
+ { ...makeNode('n1'), position: { x: 160, y: 220 } },
+ { ...makeNode('n2'), position: { x: 200, y: 260 } },
+ { ...makeNode('n3'), position: { x: 240, y: 300 } },
+ ],
+ })
+ useCanvasStore.getState().addNodesToZone('z1', ['n1', 'n2', 'n3'])
+
+ const nodes = useCanvasStore.getState().nodes
+ for (const id of ['n1', 'n2', 'n3']) {
+ const child = nodes.find((n) => n.id === id)!
+ expect(child.parentId).toBe('z1')
+ expect(child.data.parent_id).toBe('z1')
+ expect(child.extent).toBeUndefined()
+ }
+ expect(nodes.find((n) => n.id === 'n1')!.position).toEqual({ x: 60, y: 120 })
+ expect(nodes.find((n) => n.id === 'n3')!.position).toEqual({ x: 140, y: 200 })
+ })
+
+ it('undoes a batch add in a single step', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), makeNode('n1'), makeNode('n2')],
+ })
+ useCanvasStore.getState().addNodesToZone('z1', ['n1', 'n2'])
+ useCanvasStore.getState().undo()
+
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'n1')!.parentId).toBeUndefined()
+ expect(nodes.find((n) => n.id === 'n2')!.parentId).toBeUndefined()
+ })
+
+ it('skips a child whose own parent is in the same batch', () => {
+ useCanvasStore.setState({
+ nodes: [
+ zone('z1'),
+ { ...makeNode('host'), position: { x: 500, y: 500 } },
+ {
+ ...makeNode('vm'),
+ position: { x: 20, y: 20 },
+ parentId: 'host',
+ data: { ...makeNode('vm').data, parent_id: 'host' },
+ },
+ ],
+ })
+ useCanvasStore.getState().addNodesToZone('z1', ['host', 'vm'])
+
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'host')!.parentId).toBe('z1')
+ // The VM rides along with its host; re-parenting it would tear it out.
+ expect(nodes.find((n) => n.id === 'vm')!.parentId).toBe('host')
+ expect(nodes.find((n) => n.id === 'vm')!.position).toEqual({ x: 20, y: 20 })
+ })
+
+ it('refuses a node the zone itself descends from', () => {
+ useCanvasStore.setState({
+ nodes: [
+ makeNode('outer'),
+ {
+ ...zone('z1'),
+ parentId: 'outer',
+ data: { ...zone('z1').data, parent_id: 'outer' },
+ },
+ makeNode('n1'),
+ ],
+ })
+ useCanvasStore.getState().addNodesToZone('z1', ['outer', 'n1'])
+
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'outer')!.parentId).toBeUndefined()
+ expect(nodes.find((n) => n.id === 'n1')!.parentId).toBe('z1')
+ })
+
+ it('is a no-op when nothing in the batch is eligible', () => {
+ useCanvasStore.setState({ nodes: [zone('z1'), makeNode('n1')] })
+ useCanvasStore.getState().addToZone('z1', 'n1')
+ const before = useCanvasStore.getState().nodes
+ useCanvasStore.getState().addNodesToZone('z1', ['n1', 'z1'])
+ expect(useCanvasStore.getState().nodes).toBe(before)
+ })
+
+ it('addNodesToGroup clamps every child inside the group', () => {
+ useCanvasStore.setState({
+ nodes: [
+ { ...makeNode('g1', { type: 'group' }), type: 'group', position: { x: 100, y: 100 } },
+ { ...makeNode('n1'), position: { x: 160, y: 220 } },
+ { ...makeNode('n2'), position: { x: 100, y: 100 } },
+ ],
+ })
+ useCanvasStore.getState().addNodesToGroup('g1', ['n1', 'n2'])
+
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'n1')!.extent).toBe('parent')
+ expect(nodes.find((n) => n.id === 'n1')!.position).toEqual({ x: 60, y: 120 })
+ // Dropped on the group's own corner: clamped to the 8px inset.
+ expect(nodes.find((n) => n.id === 'n2')!.position).toEqual({ x: 8, y: 8 })
+ })
+
+ it('addNodesToContainer parents every child of a container-mode node', () => {
+ useCanvasStore.setState({
+ nodes: [
+ {
+ ...makeNode('px1', { type: 'proxmox', container_mode: true }),
+ position: { x: 100, y: 100 },
+ },
+ { ...makeNode('n1'), position: { x: 160, y: 220 } },
+ { ...makeNode('n2'), position: { x: 180, y: 240 } },
+ ],
+ })
+ useCanvasStore.getState().addNodesToContainer('px1', ['n1', 'n2'])
+
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'n1')!.parentId).toBe('px1')
+ expect(nodes.find((n) => n.id === 'n2')!.parentId).toBe('px1')
+ expect(nodes.find((n) => n.id === 'n2')!.extent).toBe('parent')
+ })
+})
+
describe('canvasStore — importZoneSubnet', () => {
beforeEach(resetStore)
diff --git a/frontend/src/stores/canvasStore.ts b/frontend/src/stores/canvasStore.ts
index ef9ff46..c6adb3c 100644
--- a/frontend/src/stores/canvasStore.ts
+++ b/frontend/src/stores/canvasStore.ts
@@ -56,6 +56,81 @@ function orderParentsFirst(nodes: Node<NodeData>[]): Node<NodeData>[] {
return out
}
+/** True when `maybeAncestorId` sits on `nodeId`'s parent chain. Cycle-safe. */
+function isAncestorOf(nodes: Node<NodeData>[], maybeAncestorId: string, nodeId: string): boolean {
+ const byId = new Map(nodes.map((n) => [n.id, n]))
+ const seen = new Set<string>([nodeId])
+ let current = byId.get(nodeId)
+ while (current) {
+ const pid = parentIdOf(current)
+ if (!pid || seen.has(pid)) return false
+ if (pid === maybeAncestorId) return true
+ seen.add(pid)
+ current = byId.get(pid)
+ }
+ return false
+}
+
+/**
+ * Re-parent a batch of nodes under one target in a single history entry —
+ * a multi-selection dropped on a group, a container or a zone.
+ *
+ * `clamp` is the only behavioural difference between the three: a group and a
+ * container pin their children inside the box (`extent: 'parent'`), a zone
+ * deliberately does not, so a node stays draggable back out of it.
+ *
+ * Ineligible children are dropped rather than failing the whole batch: the
+ * target itself, a node already parented to it, a node whose own parent is in
+ * the same batch (it rides along with that parent — re-parenting it would tear
+ * it out), and any node the target descends from (which would create a cycle).
+ */
+function nestNodesUnder(
+ state: CanvasState,
+ targetId: string,
+ childIds: string[],
+ opts: { isValidTarget: (n: Node<NodeData>) => boolean; clamp: boolean },
+): Partial<CanvasState> | CanvasState {
+ const target = state.nodes.find((n) => n.id === targetId)
+ if (!target || !opts.isValidTarget(target)) return state
+
+ const batch = new Set(childIds)
+ const moving = new Set<string>()
+ for (const id of batch) {
+ const child = state.nodes.find((n) => n.id === id)
+ if (!child || child.id === targetId) continue
+ const pid = parentIdOf(child)
+ if (pid === targetId) continue
+ if (pid && batch.has(pid)) continue
+ if (isAncestorOf(state.nodes, child.id, targetId)) continue
+ moving.add(id)
+ }
+ if (moving.size === 0) return state
+
+ const nodes = orderParentsFirst(
+ state.nodes.map((n) => {
+ if (!moving.has(n.id)) return n
+ // Absolute → target-relative.
+ const x = n.position.x - target.position.x
+ const y = n.position.y - target.position.y
+ return {
+ ...n,
+ parentId: targetId,
+ extent: opts.clamp ? ('parent' as const) : undefined,
+ position: opts.clamp ? { x: Math.max(8, x), y: Math.max(8, y) } : { x, y },
+ selected: false,
+ data: { ...n.data, parent_id: targetId },
+ }
+ }),
+ )
+
+ return {
+ nodes,
+ hasUnsavedChanges: true,
+ past: [...state.past.slice(-49), { nodes: state.nodes, edges: state.edges }],
+ future: [],
+ }
+}
+
// Zone subnet import: the grid the arrivals are packed on, in zone-relative
// pixels. A cell is one node box plus the gap that follows it.
const DEFAULT_ZONE_WIDTH = 360
@@ -243,8 +318,14 @@ interface CanvasState {
createGroup: (nodeIds: string[], name: string) => void
ungroup: (groupId: string) => void
addToGroup: (groupId: string, childId: string) => void
+ /** Batch form of addToGroup — one history entry for the whole selection. */
+ addNodesToGroup: (groupId: string, childIds: string[]) => void
addToContainer: (containerId: string, childId: string) => void
+ /** Batch form of addToContainer. */
+ addNodesToContainer: (containerId: string, childIds: string[]) => void
addToZone: (zoneId: string, childId: string) => void
+ /** Batch form of addToZone. */
+ addNodesToZone: (zoneId: string, childIds: string[]) => void
/** Move every free node whose IP falls in `cidr` into the zone. Returns the
* count moved; 0 for an invalid CIDR or no match. */
importZoneSubnet: (zoneId: string, cidr: string) => number
@@ -899,138 +980,46 @@ export const useCanvasStore = create<CanvasState>((rawSet, get) => {
}
}),
- // Nest an existing top-level node inside a group. Inverse of removeFromGroup.
- addToGroup: (groupId, childId) =>
- set((state) => {
- const group = state.nodes.find((n) => n.id === groupId)
- const child = state.nodes.find((n) => n.id === childId)
- if (!group || !child || group.data.type !== 'group') return state
- if (child.id === groupId || child.parentId === groupId) return state
-
- const updatedNodes = state.nodes.map((n) => {
- if (n.id !== childId) return n
- return {
- ...n,
- parentId: groupId,
- extent: 'parent' as const,
- // Absolute → group-relative. Clamp so the node stays inside the box.
- position: {
- x: Math.max(8, n.position.x - group.position.x),
- y: Math.max(8, n.position.y - group.position.y),
- },
- selected: false,
- data: { ...n.data, parent_id: groupId },
- }
- })
-
- // 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 groupIdx = others.findIndex((n) => n.id === groupId)
- const nodes = [
- ...others.slice(0, groupIdx + 1),
- movedChild,
- ...others.slice(groupIdx + 1),
- ]
-
- return {
- nodes,
- hasUnsavedChanges: true,
- past: [...state.past.slice(-49), { nodes: state.nodes, edges: state.edges }],
- future: [],
- }
- }),
-
- // Nest an existing top-level node inside a container node (proxmox /
- // docker_host / … in container_mode). Mirrors addToGroup but the target is
- // any node with data.container_mode === true rather than a group.
- addToContainer: (containerId, childId) =>
- set((state) => {
- const container = state.nodes.find((n) => n.id === containerId)
- const child = state.nodes.find((n) => n.id === childId)
- if (!container || !child || container.data.container_mode !== true) return state
- if (child.id === containerId || child.parentId === containerId) return state
+ // Nest existing nodes inside a group. Inverse of removeFromGroup. The
+ // singular form is the batch of one — a multi-selection dropped on a group
+ // lands in a single history entry.
+ addToGroup: (groupId, childId) => get().addNodesToGroup(groupId, [childId]),
- const updatedNodes = state.nodes.map((n) => {
- if (n.id !== childId) return n
- return {
- ...n,
- parentId: containerId,
- extent: 'parent' as const,
- // Absolute → container-relative. Clamp so the node stays inside.
- position: {
- x: Math.max(8, n.position.x - container.position.x),
- y: Math.max(8, n.position.y - container.position.y),
- },
- selected: false,
- data: { ...n.data, parent_id: containerId },
- }
- })
-
- // 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 containerIdx = others.findIndex((n) => n.id === containerId)
- const nodes = [
- ...others.slice(0, containerIdx + 1),
- movedChild,
- ...others.slice(containerIdx + 1),
- ]
-
- return {
- nodes,
- hasUnsavedChanges: true,
- past: [...state.past.slice(-49), { nodes: state.nodes, edges: state.edges }],
- future: [],
- }
- }),
-
- // 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: [],
- }
- }),
+ addNodesToGroup: (groupId, childIds) =>
+ set((state) =>
+ nestNodesUnder(state, groupId, childIds, {
+ isValidTarget: (n) => n.data.type === 'group',
+ clamp: true,
+ }),
+ ),
+
+ // Nest existing nodes inside a container node (proxmox / docker_host / … in
+ // container_mode). Mirrors addToGroup but the target is any node with
+ // data.container_mode === true rather than a group.
+ addToContainer: (containerId, childId) => get().addNodesToContainer(containerId, [childId]),
+
+ addNodesToContainer: (containerId, childIds) =>
+ set((state) =>
+ nestNodesUnder(state, containerId, childIds, {
+ isValidTarget: (n) => n.data.container_mode === true,
+ clamp: true,
+ }),
+ ),
+
+ // Nest existing nodes 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) => get().addNodesToZone(zoneId, [childId]),
+
+ addNodesToZone: (zoneId, childIds) =>
+ set((state) =>
+ nestNodesUnder(state, zoneId, childIds, {
+ isValidTarget: (n) => n.data.type === 'groupRect',
+ clamp: false,
+ }),
+ ),
// Pull every free node whose IP falls inside `cidr` into a zone, laying them
// out on a grid in the zone's free space. Deliberately additive and one-shot: