Skip to content

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

feat(canvas): import devices into a zone by subnet

Pouzord9451f35dc33
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 630ea90..da126a6 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -15,6 +15,7 @@ import { parseYamlToCanvas } from '@/utils/importYaml'
import { TooltipProvider } from '@/components/ui/tooltip'
import { Toaster } from '@/components/ui/sonner'
import { toast } from 'sonner'
+import { isZoneSubnetCandidate } from '@/utils/subnet'
import { CanvasContainer } from '@/components/canvas/CanvasContainer'
import { Sidebar } from '@/components/panels/Sidebar'
import { Toolbar } from '@/components/panels/Toolbar'
@@ -64,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, 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, importZoneSubnet, floorMap, setFloorMap } = useCanvasStore()
const canvasRef = useRef<HTMLDivElement>(null)
const { isAuthenticated, isInitialized } = useAuthStore()
const authBootstrapStarted = useRef(false)
@@ -526,6 +527,26 @@ export default function App() {
toast.success(`Added "${data.label}"`)
}, [addNode, nodes, snapshotHistory])
+ // Subnet import is a one-shot action on an existing zone, so on the Add modal
+ // there is no zone to run it against yet: the CIDR is held here and applied
+ // once, right after the zone is created. Cleared whenever that modal closes.
+ const pendingZoneSubnet = useRef<string | null>(null)
+
+ const countSubnetMatches = useCallback(
+ (cidr: string, zoneId?: string) =>
+ nodes.filter((n) => isZoneSubnetCandidate(n, cidr, zoneId)).length,
+ [nodes],
+ )
+
+ const reportSubnetImport = useCallback((moved: number, cidr: string) => {
+ if (moved === 0) toast.info(`No unparented device in ${cidr}`)
+ else toast.success(`Moved ${moved} device${moved > 1 ? 's' : ''} from ${cidr} into the zone`)
+ }, [])
+
+ const handleImportSubnetIntoZone = useCallback((zoneId: string, cidr: string) => {
+ reportSubnetImport(importZoneSubnet(zoneId, cidr), cidr)
+ }, [importZoneSubnet, reportSubnetImport])
+
const handleAddGroupRect = useCallback((data: GroupRectFormData) => {
snapshotHistory()
const id = generateUUID()
@@ -556,7 +577,12 @@ export default function App() {
zIndex: data.z_order - 10,
}
addNode(newNode)
- }, [addNode, snapshotHistory])
+
+ const cidr = pendingZoneSubnet.current
+ pendingZoneSubnet.current = null
+ // addNode has already committed, so the zone is in the store by now.
+ if (cidr) reportSubnetImport(importZoneSubnet(id, cidr), cidr)
+ }, [addNode, snapshotHistory, importZoneSubnet, reportSubnetImport])
const handleUpdateGroupRect = useCallback((data: GroupRectFormData) => {
if (!editingGroupRectId) return
@@ -1190,8 +1216,11 @@ export default function App() {
<GroupRectModal
open={addGroupRectOpen}
- onClose={() => setAddGroupRectOpen(false)}
+ onClose={() => { pendingZoneSubnet.current = null; setAddGroupRectOpen(false) }}
onSubmit={handleAddGroupRect}
+ onImportSubnet={(cidr) => { pendingZoneSubnet.current = cidr }}
+ countSubnetMatches={(cidr) => countSubnetMatches(cidr)}
+ importOnSubmit
title="Add Zone"
/>
@@ -1202,6 +1231,8 @@ export default function App() {
onClose={() => setEditingGroupRectId(null)}
onSubmit={handleUpdateGroupRect}
onDelete={handleDeleteGroupRect}
+ onImportSubnet={(cidr) => { if (editingGroupRectId) handleImportSubnetIntoZone(editingGroupRectId, cidr) }}
+ countSubnetMatches={(cidr) => countSubnetMatches(cidr, editingGroupRectId ?? undefined)}
initial={(() => {
const n = editingGroupRectId ? nodes.find((nd) => nd.id === editingGroupRectId) : null
if (!n) return undefined
diff --git a/frontend/src/components/modals/GroupRectModal.tsx b/frontend/src/components/modals/GroupRectModal.tsx
index 75a0b16..7c32298 100644
--- a/frontend/src/components/modals/GroupRectModal.tsx
+++ b/frontend/src/components/modals/GroupRectModal.tsx
@@ -7,6 +7,7 @@ import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import type { TextPosition } from '@/types'
import { hexToRgba, rgbaToHex8 } from '@/utils/colorUtils'
+import { isValidCidr } from '@/utils/subnet'
import styles from './GroupRectModal.module.css'
export type BorderStyle = 'solid' | 'dashed' | 'dotted' | 'double' | 'none'
@@ -98,16 +99,51 @@ interface GroupRectModalProps {
onDelete?: () => void
initial?: Partial<GroupRectFormData>
title?: string
+ /** Run the subnet import for a valid CIDR. Omit to hide the whole section. */
+ onImportSubnet?: (cidr: string) => void
+ /** How many unparented devices a CIDR would pull in — drives the preview line. */
+ countSubnetMatches?: (cidr: string) => number
+ /**
+ * Add mode: the zone does not exist yet, so there is nothing to import into
+ * until it is created. The CIDR is handed over on submit instead of via an
+ * Import button, which would otherwise look like it did nothing.
+ */
+ importOnSubmit?: boolean
}
-export function GroupRectModal({ open, onClose, onSubmit, onDelete, initial, title = 'Add Zone' }: GroupRectModalProps) {
+export function GroupRectModal({
+ open,
+ onClose,
+ onSubmit,
+ onDelete,
+ initial,
+ title = 'Add Zone',
+ onImportSubnet,
+ countSubnetMatches,
+ importOnSubmit = false,
+}: GroupRectModalProps) {
const [form, setForm] = useState<GroupRectFormData>({ ...DEFAULT_FORM, ...initial })
+ const [subnet, setSubnet] = useState('')
+
+ const cidrValid = isValidCidr(subnet)
+ const showCidrError = subnet.trim() !== '' && !cidrValid
+ const canImport = cidrValid && !!onImportSubnet
+ const matchCount = cidrValid && countSubnetMatches ? countSubnetMatches(subnet) : null
+
+ const handleImport = () => {
+ if (!canImport) return
+ onImportSubnet!(subnet)
+ setSubnet('')
+ }
const set = <K extends keyof GroupRectFormData>(key: K, value: GroupRectFormData[K]) =>
setForm((f) => ({ ...f, [key]: value }))
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
+ // Hand the CIDR over first: the caller queues it, then creates the zone and
+ // runs the import against it.
+ if (importOnSubmit && canImport) onImportSubnet!(subnet)
onSubmit(form)
onClose()
}
@@ -355,6 +391,57 @@ export function GroupRectModal({ open, onClose, onSubmit, onDelete, initial, tit
</div>{/* ── end RIGHT column ── */}
</div>{/* ── end 2-column grid ── */}
+ {/* ── Import devices by subnet ──
+ Deliberately NOT part of the form: the CIDR is an argument to a
+ one-shot action, never a property of the zone, so it is not
+ submitted, not persisted, and cleared after each run. */}
+ {onImportSubnet && (
+ <div className="flex flex-col gap-2 pt-3 border-t border-[#30363d]">
+ <div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/70">
+ Import devices by subnet
+ </div>
+ <div className="flex gap-2">
+ <Input
+ value={subnet}
+ onChange={(e) => setSubnet(e.target.value)}
+ placeholder="192.168.1.0/24"
+ aria-label="Subnet"
+ className={`bg-[#21262d] border-[#30363d] text-sm h-8 font-mono ${modalStyles['modal-radius']}`}
+ style={showCidrError ? { borderColor: '#f85149' } : undefined}
+ // Enter runs the import instead of submitting the whole form —
+ // except in add mode, where submitting IS how the import runs.
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !importOnSubmit) {
+ e.preventDefault()
+ handleImport()
+ }
+ }}
+ />
+ {!importOnSubmit && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={!canImport}
+ className="cursor-pointer border-[#30363d] bg-[#21262d] shrink-0"
+ onClick={handleImport}
+ >
+ Import
+ </Button>
+ )}
+ </div>
+ <p className="text-[11px] text-muted-foreground/70">
+ {showCidrError
+ ? <span className="text-[#f85149]">Not a valid IPv4 CIDR — try 192.168.1.0/24</span>
+ : matchCount === null
+ ? 'Moves every unparented device in that range into this zone. Nothing is removed.'
+ : matchCount === 0
+ ? 'No unparented device in that range.'
+ : `${matchCount} device${matchCount > 1 ? 's' : ''} will move into this zone${importOnSubmit ? ' when you add it' : ''}.`}
+ </p>
+ </div>
+ )}
+
<div className="flex justify-between gap-2 pt-1">
{onDelete && (
<Button
diff --git a/frontend/src/components/modals/__tests__/GroupRectModal.test.tsx b/frontend/src/components/modals/__tests__/GroupRectModal.test.tsx
index 579de9c..7757a48 100644
--- a/frontend/src/components/modals/__tests__/GroupRectModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/GroupRectModal.test.tsx
@@ -345,3 +345,110 @@ describe('GroupRectModal font label rendering', () => {
expect(trigger.textContent).toContain('comic-sans-9000')
})
})
+
+describe('GroupRectModal — subnet import', () => {
+ const setup = (props: Partial<React.ComponentProps<typeof GroupRectModal>> = {}) => {
+ const onImportSubnet = vi.fn()
+ const onSubmit = vi.fn()
+ const onClose = vi.fn()
+ render(
+ <GroupRectModal
+ open
+ onClose={onClose}
+ onSubmit={onSubmit}
+ onImportSubnet={onImportSubnet}
+ countSubnetMatches={() => 3}
+ title="Edit Zone"
+ {...props}
+ />
+ )
+ return { onImportSubnet, onSubmit, onClose }
+ }
+
+ it('hides the whole section when no import handler is given', () => {
+ render(<GroupRectModal open onClose={vi.fn()} onSubmit={vi.fn()} />)
+ expect(screen.queryByText('Import devices by subnet')).toBeNull()
+ })
+
+ it('renders the field and disables Import until a CIDR is valid', () => {
+ setup()
+ const button = screen.getByRole('button', { name: 'Import' }) as HTMLButtonElement
+ expect(button.disabled).toBe(true)
+
+ fireEvent.change(screen.getByLabelText('Subnet'), { target: { value: '192.168.1.0/24' } })
+ expect(button.disabled).toBe(false)
+ })
+
+ it('explains an invalid CIDR instead of silently doing nothing', () => {
+ setup()
+ fireEvent.change(screen.getByLabelText('Subnet'), { target: { value: '192.168.1.0/99' } })
+ expect(screen.getByText(/Not a valid IPv4 CIDR/)).toBeInTheDocument()
+ expect((screen.getByRole('button', { name: 'Import' }) as HTMLButtonElement).disabled).toBe(true)
+ })
+
+ it('previews how many devices would move', () => {
+ setup()
+ fireEvent.change(screen.getByLabelText('Subnet'), { target: { value: '192.168.1.0/24' } })
+ expect(screen.getByText('3 devices will move into this zone.')).toBeInTheDocument()
+ })
+
+ it('imports without submitting or closing the form, and clears the field', () => {
+ const { onImportSubnet, onSubmit, onClose } = setup()
+ const field = screen.getByLabelText('Subnet') as HTMLInputElement
+ fireEvent.change(field, { target: { value: '192.168.1.0/24' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Import' }))
+
+ expect(onImportSubnet).toHaveBeenCalledWith('192.168.1.0/24')
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(onClose).not.toHaveBeenCalled()
+ expect(field.value).toBe('')
+ })
+
+ it('runs the import on Enter rather than submitting the zone', () => {
+ const { onImportSubnet, onSubmit } = setup()
+ const field = screen.getByLabelText('Subnet')
+ fireEvent.change(field, { target: { value: '10.0.0.0/8' } })
+ fireEvent.keyDown(field, { key: 'Enter' })
+
+ expect(onImportSubnet).toHaveBeenCalledWith('10.0.0.0/8')
+ expect(onSubmit).not.toHaveBeenCalled()
+ })
+
+ it('never submits the CIDR as zone data — it is an argument, not a property', () => {
+ const { onSubmit } = setup()
+ fireEvent.change(screen.getByLabelText('Subnet'), { target: { value: '192.168.1.0/24' } })
+ fireEvent.click(screen.getByText('Save'))
+ expect(Object.keys(onSubmit.mock.calls[0][0])).not.toContain('subnet')
+ })
+
+ describe('add mode (importOnSubmit)', () => {
+ it('drops the Import button — there is no zone to import into yet', () => {
+ setup({ importOnSubmit: true, title: 'Add Zone' })
+ expect(screen.getByText('Import devices by subnet')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Import' })).toBeNull()
+ })
+
+ it('says the move happens on creation', () => {
+ setup({ importOnSubmit: true, title: 'Add Zone' })
+ fireEvent.change(screen.getByLabelText('Subnet'), { target: { value: '192.168.1.0/24' } })
+ expect(screen.getByText('3 devices will move into this zone when you add it.')).toBeInTheDocument()
+ })
+
+ it('hands the CIDR over before submitting, so the caller can apply it to the new zone', () => {
+ const { onImportSubnet, onSubmit } = setup({ importOnSubmit: true, title: 'Add Zone' })
+ fireEvent.change(screen.getByLabelText('Subnet'), { target: { value: '192.168.1.0/24' } })
+ fireEvent.click(screen.getByText('Add'))
+
+ expect(onImportSubnet).toHaveBeenCalledWith('192.168.1.0/24')
+ expect(onSubmit).toHaveBeenCalledOnce()
+ expect(onImportSubnet.mock.invocationCallOrder[0]).toBeLessThan(onSubmit.mock.invocationCallOrder[0])
+ })
+
+ it('submits normally when the field is left empty', () => {
+ const { onImportSubnet, onSubmit } = setup({ importOnSubmit: true, title: 'Add Zone' })
+ fireEvent.click(screen.getByText('Add'))
+ expect(onImportSubnet).not.toHaveBeenCalled()
+ expect(onSubmit).toHaveBeenCalledOnce()
+ })
+ })
+})
diff --git a/frontend/src/stores/__tests__/canvasStore/zones.test.ts b/frontend/src/stores/__tests__/canvasStore/zones.test.ts
index 6d14fbd..e6af603 100644
--- a/frontend/src/stores/__tests__/canvasStore/zones.test.ts
+++ b/frontend/src/stores/__tests__/canvasStore/zones.test.ts
@@ -133,3 +133,149 @@ describe('canvasStore — zone (groupRect) parenting', () => {
expect(detached.position).toEqual({ x: 160, y: 220 })
})
})
+
+describe('canvasStore — importZoneSubnet', () => {
+ beforeEach(resetStore)
+
+ const device = (id: string, ip: string | undefined, over: Partial<ReturnType<typeof makeNode>> = {}) => ({
+ ...makeNode(id, { ip }),
+ position: { x: 900, y: 900 },
+ ...over,
+ })
+
+ it('moves every free device in range into the zone and reports the count', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), device('n1', '192.168.1.10'), device('n2', '192.168.1.11')],
+ })
+
+ const moved = useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')
+
+ expect(moved).toBe(2)
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'n1')!.parentId).toBe('z1')
+ expect(nodes.find((n) => n.id === 'n2')!.parentId).toBe('z1')
+ })
+
+ it('leaves out-of-range and address-less devices on the canvas', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), device('in', '192.168.1.10'), device('out', '10.0.0.1'), device('bare', undefined)],
+ })
+
+ expect(useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')).toBe(1)
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'out')!.parentId).toBeUndefined()
+ expect(nodes.find((n) => n.id === 'bare')!.parentId).toBeUndefined()
+ })
+
+ it('never steals a node that already has a parent', () => {
+ useCanvasStore.setState({
+ nodes: [
+ zone('z1'),
+ zone('z2', 800, 100),
+ { ...device('n1', '192.168.1.10'), parentId: 'z2' },
+ ],
+ })
+
+ expect(useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')).toBe(0)
+ expect(useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!.parentId).toBe('z2')
+ })
+
+ it('never swallows another zone, even one carrying an IP', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), { ...zone('z2', 800, 100), data: { ...zone('z2').data, ip: '192.168.1.9' } }],
+ })
+
+ expect(useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')).toBe(0)
+ expect(useCanvasStore.getState().nodes.find((n) => n.id === 'z2')!.parentId).toBeUndefined()
+ })
+
+ it('is a no-op for an invalid CIDR, a missing zone and a non-zone target', () => {
+ useCanvasStore.setState({ nodes: [zone('z1'), device('n1', '192.168.1.10'), device('plain', '192.168.1.11')] })
+ const before = useCanvasStore.getState().nodes
+
+ expect(useCanvasStore.getState().importZoneSubnet('z1', 'nonsense')).toBe(0)
+ expect(useCanvasStore.getState().importZoneSubnet('nope', '192.168.1.0/24')).toBe(0)
+ expect(useCanvasStore.getState().importZoneSubnet('plain', '192.168.1.0/24')).toBe(0)
+ expect(useCanvasStore.getState().nodes).toBe(before)
+ })
+
+ it('lays arrivals out on a non-overlapping grid inside the zone', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), device('n1', '192.168.1.10'), device('n2', '192.168.1.11')],
+ })
+ useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')
+
+ const nodes = useCanvasStore.getState().nodes
+ const a = nodes.find((n) => n.id === 'n1')!.position
+ const b = nodes.find((n) => n.id === 'n2')!.position
+ expect(a).not.toEqual(b)
+ // Zone-relative and clear of the label band at the top.
+ for (const p of [a, b]) {
+ expect(p.x).toBeGreaterThanOrEqual(0)
+ expect(p.y).toBeGreaterThanOrEqual(40)
+ }
+ })
+
+ it('packs around the boxes already inside the zone', () => {
+ useCanvasStore.setState({
+ nodes: [
+ zone('z1'),
+ { ...device('sitting', '10.0.0.1'), parentId: 'z1', position: { x: 16, y: 40 }, width: 160, height: 90 },
+ device('n1', '192.168.1.10'),
+ ],
+ })
+ useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')
+
+ const placed = useCanvasStore.getState().nodes.find((n) => n.id === 'n1')!.position
+ expect(placed).not.toEqual({ x: 16, y: 40 })
+ })
+
+ it('grows the zone when the arrivals overflow its height', () => {
+ const many = Array.from({ length: 12 }, (_, i) => device(`n${i}`, `192.168.1.${i + 10}`))
+ useCanvasStore.setState({ nodes: [zone('z1'), ...many] })
+
+ useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')
+
+ const z = useCanvasStore.getState().nodes.find((n) => n.id === 'z1')!
+ expect(z.height!).toBeGreaterThan(300)
+ // The renderer reads the persisted size back out of custom_colors.
+ expect(z.data.custom_colors?.height).toBe(z.height)
+ })
+
+ it('keeps the parent ahead of its new children, as React Flow requires', () => {
+ useCanvasStore.setState({
+ nodes: [device('n1', '192.168.1.10'), zone('z1'), device('n2', '192.168.1.11')],
+ })
+ useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')
+
+ const ids = useCanvasStore.getState().nodes.map((n) => n.id)
+ expect(ids.indexOf('z1')).toBeLessThan(ids.indexOf('n1'))
+ expect(ids.indexOf('z1')).toBeLessThan(ids.indexOf('n2'))
+ })
+
+ it('is additive: a second subnet keeps the first import inside', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), device('n1', '192.168.1.10'), device('n2', '10.0.0.5')],
+ })
+ useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')
+ useCanvasStore.getState().importZoneSubnet('z1', '10.0.0.0/8')
+
+ const nodes = useCanvasStore.getState().nodes
+ expect(nodes.find((n) => n.id === 'n1')!.parentId).toBe('z1')
+ expect(nodes.find((n) => n.id === 'n2')!.parentId).toBe('z1')
+ })
+
+ it('marks the canvas unsaved and undoes the whole import in one step', () => {
+ useCanvasStore.setState({
+ nodes: [zone('z1'), device('n1', '192.168.1.10'), device('n2', '192.168.1.11')],
+ })
+ useCanvasStore.getState().importZoneSubnet('z1', '192.168.1.0/24')
+ expect(useCanvasStore.getState().hasUnsavedChanges).toBe(true)
+
+ 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()
+ })
+})
diff --git a/frontend/src/stores/canvasStore.ts b/frontend/src/stores/canvasStore.ts
index 23b54b7..3a82be6 100644
--- a/frontend/src/stores/canvasStore.ts
+++ b/frontend/src/stores/canvasStore.ts
@@ -14,6 +14,7 @@ import { generateUUID } from '@/utils/uuid'
import { normalizeHandle, removedHandleIds, handleCountField, sideDefault, handleId, SIDES } from '@/utils/handleUtils'
import { applyOpacity } from '@/utils/colorUtils'
import { readHideIp, writeHideIp } from '@/utils/ipDisplay'
+import { isValidCidr, isZoneSubnetCandidate } from '@/utils/subnet'
import { CONTAINER_MODE_TYPES } from '@/utils/virtualEdgeParent'
import {
changedFactFields,
@@ -29,6 +30,18 @@ type Clipboard = { nodes: Node<NodeData>[]; edges: Edge<EdgeData>[] }
/** Resolve a node's effective parent id from either the RF field or domain data. */
const parentIdOf = (n: Node<NodeData>): string | undefined => n.parentId ?? n.data.parent_id ?? undefined
+// 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
+const DEFAULT_ZONE_HEIGHT = 240
+const ZONE_CELL_W = 180
+const ZONE_CELL_H = 110
+const ZONE_CELL_GAP = 20
+const ZONE_PAD_X = 32
+// Leaves the label band at the top of the zone clear.
+const ZONE_PAD_TOP = 40
+const ZONE_PAD_BOTTOM = 16
+
/**
* Whether a node change represents a real user edit that should dirty the canvas.
* Excludes:
@@ -198,6 +211,9 @@ interface CanvasState {
addToGroup: (groupId: string, childId: string) => void
addToContainer: (containerId: string, childId: string) => void
addToZone: (zoneId: string, childId: 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
removeFromGroup: (groupId: string, childId: string) => void
markSaved: () => void
markUnsaved: () => void
@@ -218,7 +234,7 @@ interface CanvasState {
applyAllCustomStyles: (def: CustomStyleDef) => void
}
-export const useCanvasStore = create<CanvasState>((rawSet) => {
+export const useCanvasStore = create<CanvasState>((rawSet, get) => {
// Wrap set so any update that flips hasUnsavedChanges to true also bumps
// editSeq. This centralises the "an edit happened" signal instead of touching
// every one of the ~two dozen mutating actions. Actions that update state
@@ -969,6 +985,106 @@ export const useCanvasStore = create<CanvasState>((rawSet) => {
}
}),
+ // 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:
+ // the CIDR is never stored, nothing is ever ejected, and running it twice with
+ // two subnets leaves both sets inside. Undo reverses the whole import at once.
+ importZoneSubnet: (zoneId, cidr) => {
+ const state = get()
+ const zone = state.nodes.find((n) => n.id === zoneId)
+ if (!zone || zone.data.type !== 'groupRect') return 0
+ if (!isValidCidr(cidr)) return 0
+
+ const matches = state.nodes.filter((n) => isZoneSubnetCandidate(n, cidr, zoneId))
+ if (matches.length === 0) return 0
+
+ const moved = new Set(matches.map((n) => n.id))
+ const zoneWidth = zone.width ?? DEFAULT_ZONE_WIDTH
+ const zoneHeight = zone.height ?? DEFAULT_ZONE_HEIGHT
+
+ // Boxes already inside the zone, in zone-relative coordinates. New arrivals
+ // are packed around them rather than on top of them.
+ const occupied = state.nodes
+ .filter((n) => n.parentId === zoneId && !moved.has(n.id))
+ .map((n) => ({
+ x: n.position.x,
+ y: n.position.y,
+ w: n.width ?? ZONE_CELL_W - ZONE_CELL_GAP,
+ h: n.height ?? ZONE_CELL_H - ZONE_CELL_GAP,
+ }))
+
+ const columns = Math.max(1, Math.floor((zoneWidth - ZONE_PAD_X) / ZONE_CELL_W))
+ const overlaps = (x: number, y: number) =>
+ occupied.some(
+ (b) =>
+ x < b.x + b.w &&
+ x + ZONE_CELL_W - ZONE_CELL_GAP > b.x &&
+ y < b.y + b.h &&
+ y + ZONE_CELL_H - ZONE_CELL_GAP > b.y,
+ )
+
+ // Row-major scan for the first free cell per arrival. Rows keep going past
+ // the current height; the zone grows at the end to cover the last one used.
+ const placements = new Map<string, { x: number; y: number }>()
+ let cursor = 0
+ let maxBottom = 0
+ for (const node of matches) {
+ let x = 0
+ let y = 0
+ for (;;) {
+ x = ZONE_PAD_X / 2 + (cursor % columns) * ZONE_CELL_W
+ y = ZONE_PAD_TOP + Math.floor(cursor / columns) * ZONE_CELL_H
+ cursor += 1
+ if (!overlaps(x, y)) break
+ }
+ placements.set(node.id, { x, y })
+ occupied.push({ x, y, w: ZONE_CELL_W - ZONE_CELL_GAP, h: ZONE_CELL_H - ZONE_CELL_GAP })
+ maxBottom = Math.max(maxBottom, y + ZONE_CELL_H)
+ }
+
+ const grownHeight = Math.max(zoneHeight, maxBottom + ZONE_PAD_BOTTOM)
+
+ set((s) => {
+ const updated = s.nodes.map((n) => {
+ if (n.id === zoneId) {
+ return grownHeight === zoneHeight
+ ? n
+ : {
+ ...n,
+ height: grownHeight,
+ data: {
+ ...n.data,
+ custom_colors: { ...(n.data.custom_colors ?? {}), height: grownHeight },
+ },
+ }
+ }
+ const at = placements.get(n.id)
+ if (!at) return n
+ return {
+ ...n,
+ parentId: zoneId,
+ position: at,
+ selected: false,
+ data: { ...n.data, parent_id: zoneId },
+ }
+ })
+
+ // React Flow requires a parent to precede its children in the array.
+ const others = updated.filter((n) => !moved.has(n.id))
+ const children = updated.filter((n) => moved.has(n.id))
+ const zoneIdx = others.findIndex((n) => n.id === zoneId)
+
+ return {
+ nodes: [...others.slice(0, zoneIdx + 1), ...children, ...others.slice(zoneIdx + 1)],
+ hasUnsavedChanges: true,
+ past: [...s.past.slice(-49), { nodes: s.nodes, edges: s.edges }],
+ future: [],
+ }
+ })
+
+ return matches.length
+ },
+
// 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__/subnet.test.ts b/frontend/src/utils/__tests__/subnet.test.ts
new file mode 100644
index 0000000..36e2a7c
--- /dev/null
+++ b/frontend/src/utils/__tests__/subnet.test.ts
@@ -0,0 +1,110 @@
+import { describe, it, expect } from 'vitest'
+import { ipToInt, parseCidr, isValidCidr, ipInSubnet, isZoneSubnetCandidate } from '@/utils/subnet'
+
+describe('ipToInt', () => {
+ it('converts a dotted quad', () => {
+ expect(ipToInt('0.0.0.0')).toBe(0)
+ expect(ipToInt('255.255.255.255')).toBe(4294967295)
+ expect(ipToInt('192.168.1.42')).toBe(3232235818)
+ })
+
+ it('tolerates surrounding whitespace', () => {
+ expect(ipToInt(' 10.0.0.1 ')).toBe(ipToInt('10.0.0.1'))
+ })
+
+ it('rejects malformed addresses', () => {
+ for (const bad of ['', '1.2.3', '1.2.3.4.5', '256.0.0.1', '1.2.3.-1', 'a.b.c.d', '1.2.3.4/24', '::1']) {
+ expect(ipToInt(bad)).toBeNull()
+ }
+ })
+})
+
+describe('parseCidr', () => {
+ it('masks the host bits off, so any address in the range parses to the network', () => {
+ expect(parseCidr('192.168.1.42/24')).toEqual(parseCidr('192.168.1.0/24'))
+ })
+
+ it('treats a bare address as /32', () => {
+ expect(parseCidr('10.0.0.7')).toEqual({ base: ipToInt('10.0.0.7'), bits: 32 })
+ })
+
+ it('handles /0 without the shift wrapping to -1', () => {
+ expect(parseCidr('0.0.0.0/0')).toEqual({ base: 0, bits: 0 })
+ expect(parseCidr('192.168.1.1/0')).toEqual({ base: 0, bits: 0 })
+ })
+
+ it('rejects junk', () => {
+ for (const bad of ['', ' ', '192.168.1.0/33', '192.168.1.0/x', '192.168.1.0/24/8', '192.168.1.0/', 'not-an-ip/24']) {
+ expect(parseCidr(bad)).toBeNull()
+ }
+ })
+
+ it('rejects IPv6 — out of scope, so the UI can say why', () => {
+ expect(parseCidr('2001:db8::/32')).toBeNull()
+ expect(isValidCidr('2001:db8::/32')).toBe(false)
+ })
+})
+
+describe('ipInSubnet', () => {
+ it('matches inside a /24 and rejects the neighbours', () => {
+ expect(ipInSubnet('192.168.1.1', '192.168.1.0/24')).toBe(true)
+ expect(ipInSubnet('192.168.1.255', '192.168.1.0/24')).toBe(true)
+ expect(ipInSubnet('192.168.2.1', '192.168.1.0/24')).toBe(false)
+ expect(ipInSubnet('192.168.0.255', '192.168.1.0/24')).toBe(false)
+ })
+
+ it('honours wider and narrower prefixes', () => {
+ expect(ipInSubnet('10.4.9.2', '10.0.0.0/8')).toBe(true)
+ expect(ipInSubnet('11.4.9.2', '10.0.0.0/8')).toBe(false)
+ expect(ipInSubnet('10.0.0.7', '10.0.0.7/32')).toBe(true)
+ expect(ipInSubnet('10.0.0.8', '10.0.0.7/32')).toBe(false)
+ expect(ipInSubnet('8.8.8.8', '0.0.0.0/0')).toBe(true)
+ })
+
+ it('strips a prefix or port suffix off the node address', () => {
+ expect(ipInSubnet('192.168.1.5/24', '192.168.1.0/24')).toBe(true)
+ expect(ipInSubnet('192.168.1.5:8006', '192.168.1.0/24')).toBe(true)
+ })
+
+ it('never matches a missing or unparseable address', () => {
+ expect(ipInSubnet(undefined, '192.168.1.0/24')).toBe(false)
+ expect(ipInSubnet(null, '192.168.1.0/24')).toBe(false)
+ expect(ipInSubnet('', '192.168.1.0/24')).toBe(false)
+ expect(ipInSubnet('fe80::1', '192.168.1.0/24')).toBe(false)
+ })
+
+ it('never matches against an invalid CIDR', () => {
+ expect(ipInSubnet('192.168.1.5', 'nonsense')).toBe(false)
+ })
+})
+
+describe('isZoneSubnetCandidate', () => {
+ const node = (over: Partial<{ id: string; parentId?: string; type: string; ip?: string }> = {}) => ({
+ id: over.id ?? 'n1',
+ parentId: over.parentId,
+ data: { type: over.type ?? 'server', ip: 'ip' in over ? over.ip : '192.168.1.5' },
+ })
+
+ it('accepts a free, addressed device in range', () => {
+ expect(isZoneSubnetCandidate(node(), '192.168.1.0/24', 'z1')).toBe(true)
+ })
+
+ it('leaves an already-parented node with the parent the user gave it', () => {
+ expect(isZoneSubnetCandidate(node({ parentId: 'g1' }), '192.168.1.0/24', 'z1')).toBe(false)
+ })
+
+ it('skips canvas furniture', () => {
+ for (const type of ['groupRect', 'group', 'text']) {
+ expect(isZoneSubnetCandidate(node({ type }), '192.168.1.0/24', 'z1')).toBe(false)
+ }
+ })
+
+ it('never treats the zone itself as a candidate', () => {
+ expect(isZoneSubnetCandidate(node({ id: 'z1', type: 'server' }), '192.168.1.0/24', 'z1')).toBe(false)
+ })
+
+ it('rejects an out-of-range or address-less node', () => {
+ expect(isZoneSubnetCandidate(node({ ip: '10.0.0.1' }), '192.168.1.0/24', 'z1')).toBe(false)
+ expect(isZoneSubnetCandidate(node({ ip: undefined }), '192.168.1.0/24', 'z1')).toBe(false)
+ })
+})
diff --git a/frontend/src/utils/subnet.ts b/frontend/src/utils/subnet.ts
new file mode 100644
index 0000000..8baea8c
--- /dev/null
+++ b/frontend/src/utils/subnet.ts
@@ -0,0 +1,105 @@
+/**
+ * IPv4 subnet matching, used by the zone "Import devices by subnet" action.
+ *
+ * IPv4 only on purpose: a homelab zone is drawn around a LAN segment, and the
+ * canvas has no IPv6 grouping story yet. `isValidCidr` rejects an IPv6 CIDR so
+ * the modal can say why instead of silently matching nothing.
+ */
+
+/** A parsed CIDR: the network address as a 32-bit int, plus the prefix length. */
+export interface ParsedCidr {
+ base: number
+ bits: number
+}
+
+/**
+ * "192.168.1.42" → 3232235818. Null for anything that is not four decimal
+ * octets in 0..255 — no leading zeros, no shorthand.
+ */
+export function ipToInt(ip: string): number | null {
+ const parts = ip.trim().split('.')
+ if (parts.length !== 4) return null
+ let acc = 0
+ for (const part of parts) {
+ if (!/^\d{1,3}$/.test(part)) return null
+ const n = Number(part)
+ if (n > 255) return null
+ acc = acc * 256 + n
+ }
+ return acc
+}
+
+/**
+ * Parse "192.168.1.0/24". The host bits of the given address are masked off, so
+ * "192.168.1.42/24" and "192.168.1.0/24" parse to the same network.
+ *
+ * A bare address with no "/" is treated as /32 — one host.
+ */
+export function parseCidr(cidr: string): ParsedCidr | null {
+ const trimmed = cidr.trim()
+ if (!trimmed) return null
+
+ const [addr, prefix, ...rest] = trimmed.split('/')
+ if (rest.length > 0) return null
+
+ const ip = ipToInt(addr)
+ if (ip === null) return null
+
+ let bits = 32
+ if (prefix !== undefined) {
+ if (!/^\d{1,2}$/.test(prefix)) return null
+ bits = Number(prefix)
+ if (bits > 32) return null
+ }
+
+ // A /0 mask would be `-1 << 32`, which JS evaluates as `-1 << 0` = -1 — the
+ // shift count wraps mod 32. Special-cased so "0.0.0.0/0" matches everything.
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0
+ return { base: (ip & mask) >>> 0, bits }
+}
+
+export function isValidCidr(cidr: string): boolean {
+ return parseCidr(cidr) !== null
+}
+
+/**
+ * Does `ip` fall inside `cidr`?
+ *
+ * `ip` comes straight off node data, so it may carry a prefix ("10.0.0.5/24")
+ * or a port ("10.0.0.5:8006"); both suffixes are stripped. Missing or
+ * unparseable addresses never match.
+ */
+export function ipInSubnet(ip: string | null | undefined, cidr: string): boolean {
+ const parsed = parseCidr(cidr)
+ if (!parsed) return false
+ if (!ip) return false
+
+ const bare = ip.trim().split('/')[0].split(':')[0]
+ const value = ipToInt(bare)
+ if (value === null) return false
+
+ const mask = parsed.bits === 0 ? 0 : (0xffffffff << (32 - parsed.bits)) >>> 0
+ return ((value & mask) >>> 0) === parsed.base
+}
+
+/**
+ * The rule the zone subnet import runs on, shared by the store action and the
+ * modal's match-count preview so the number shown is the number that moves.
+ *
+ * A candidate must be free (no parent — a node already nested in a group, a
+ * container host or another zone keeps the parent the user gave it), must not
+ * be canvas furniture (which describes nothing physical and so has no IP worth
+ * matching), and must have an IP inside the range.
+ */
+const FURNITURE_TYPES = new Set(['groupRect', 'group', 'text'])
+
+export function isZoneSubnetCandidate(
+ node: { id: string; parentId?: string; data: { type: string; ip?: string } },
+ cidr: string,
+ zoneId?: string,
+): boolean {
+ if (node.id === zoneId) return false
+ if (node.parentId) return false
+ if (FURNITURE_TYPES.has(node.data.type)) return false
+ return ipInSubnet(node.data.ip, cidr)
+}