Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(canvas): group devices into zones by type or subnet from Auto Layout
Pouzor605a8a31846b
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 7550766..b4d930d 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -2,6 +2,7 @@ import { useEffect, useCallback, useMemo, useRef, useState, lazy, Suspense } froimport { ReactFlowProvider, type Connection, type Edge } from '@xyflow/react'import { type Node } from '@xyflow/react'import { applyDagreLayout } from '@/utils/layout'+import { groupIntoZones, liftEdgesToTopLevel, type AutoLayoutMode } from '@/utils/zoneGrouping'import { serializeNode, serializeEdge, deserializeApiNode, deserializeApiEdge, migrateClusterHandles, type ApiNode, type ApiEdge } from '@/utils/canvasSerializer'import { generateUUID } from '@/utils/uuid'import { getCenteredPosition } from '@/utils/viewportCenter'@@ -799,12 +800,30 @@ export default function App() {setEditNodeId(null)}, [editNodeId, updateNode, setProxmoxContainerMode, nodes, edges, deleteEdge, onConnect, snapshotHistory])- const handleAutoLayout = useCallback(() => {- const laid = applyDagreLayout(nodes, edges)- // applyLayout keeps undo history so the user can revert an accidental- // Auto Layout (#280); loadCanvas would wipe it.+ const handleAutoLayout = useCallback((mode: AutoLayoutMode) => {+ if (mode === 'hierarchy') {+ const laid = applyDagreLayout(nodes, edges)+ // applyLayout keeps undo history so the user can revert an accidental+ // Auto Layout (#280); loadCanvas would wipe it.+ applyLayout(laid, edges)+ toast.success('Canvas auto-arranged')+ return+ }+ const grouped = groupIntoZones(nodes, mode)+ if (grouped.moved === 0) {+ toast.info(mode === 'subnet' ? 'No free device with an IPv4 address to group' : 'No free device to group')+ return+ }+ // Dagre sees top-level boxes only: the edges are lifted onto the zones for+ // the layout pass, the canvas keeps the real ones. One applyLayout, so a+ // single undo reverts the zones, the moves and the arrangement together.+ const laid = applyDagreLayout(grouped.nodes, liftEdgesToTopLevel(grouped.nodes, edges))applyLayout(laid, edges)- toast.success('Canvas auto-arranged')+ const zones = grouped.zonesCreated+ toast.success(+ `Grouped ${grouped.moved} device${grouped.moved > 1 ? 's' : ''}`+ + (zones > 0 ? ` into ${zones} new zone${zones > 1 ? 's' : ''}` : ' into existing zones'),+ )}, [nodes, edges, applyLayout])const handleExportYaml = useCallback(() => {diff --git a/frontend/src/components/panels/Toolbar.tsx b/frontend/src/components/panels/Toolbar.tsxindex c44f4a7..069a44e 100644--- a/frontend/src/components/panels/Toolbar.tsx+++ b/frontend/src/components/panels/Toolbar.tsx@@ -1,17 +1,18 @@-import { useRef } from 'react'-import { Save, LayoutDashboard, Download, Palette, Undo2, Redo2, HelpCircle, FileDown, Upload, Eye } from 'lucide-react'+import { useEffect, useRef, useState } from 'react'+import { Save, LayoutDashboard, ChevronDown, Download, Palette, Undo2, Redo2, HelpCircle, FileDown, Upload, Eye } from 'lucide-react'import { Button } from '@/components/ui/button'import { Logo } from '@/components/ui/Logo'import { useCanvasStore } from '@/stores/canvasStore'import { useDesignStore } from '@/stores/designStore'import { useRackStore } from '@/rack/store'import { RackToolbarActions } from './RackToolbarActions'+import type { AutoLayoutMode } from '@/utils/zoneGrouping'const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'interface ToolbarProps {onSave: () => void- onAutoLayout: () => void+ onAutoLayout: (mode: AutoLayoutMode) => voidonExport: () => voidonChangeStyle: () => voidonUndo: () => void@@ -72,9 +73,7 @@ export function Toolbar({ onSave, onAutoLayout, onExport, onChangeStyle, onUndo,{isRack && <RackToolbarActions />}{!isRack && (<>- <Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onAutoLayout}>- <LayoutDashboard size={14} /> Auto Layout- </Button>+ <AutoLayoutButton onAutoLayout={onAutoLayout} /><Button data-tour="style" size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onChangeStyle}><Palette size={14} /> Style</Button>@@ -125,3 +124,71 @@ export function Toolbar({ onSave, onAutoLayout, onExport, onChangeStyle, onUndo,</header>)}++const LAYOUT_MODES: { mode: Exclude<AutoLayoutMode, 'hierarchy'>; label: string; hint: string }[] = [+ { mode: 'type', label: 'Group by device type', hint: 'One zone per family: hardware, virtualization, IoT…' },+ { mode: 'subnet', label: 'Group by subnet', hint: 'One zone per /24; devices without an IP stay loose' },+]++/**+ * Auto Layout as a split button: the main half runs the plain hierarchy, the+ * chevron offers the zone-grouping modes (#326).+ */+function AutoLayoutButton({ onAutoLayout }: { onAutoLayout: (mode: AutoLayoutMode) => void }) {+ const [open, setOpen] = useState(false)+ const rootRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (!open) return+ const onPointer = (e: PointerEvent) => {+ if (!rootRef.current?.contains(e.target as globalThis.Node)) setOpen(false)+ }+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) }+ document.addEventListener('pointerdown', onPointer)+ document.addEventListener('keydown', onKey)+ return () => {+ document.removeEventListener('pointerdown', onPointer)+ document.removeEventListener('keydown', onKey)+ }+ }, [open])++ const pick = (mode: AutoLayoutMode) => {+ setOpen(false)+ onAutoLayout(mode)+ }++ return (+ <div ref={rootRef} className="relative flex items-center">+ <Button size="sm" variant="ghost" className="gap-1.5 pr-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={() => pick('hierarchy')}>+ <LayoutDashboard size={14} /> Auto Layout+ </Button>+ <Button+ size="sm" variant="ghost"+ className="px-1 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]"+ onClick={() => setOpen((o) => !o)}+ aria-haspopup="menu"+ aria-expanded={open}+ aria-label="More layout options"+ title="More layout options"+ >+ <ChevronDown size={12} />+ </Button>+ {open && (+ <div role="menu" className="absolute left-0 top-full mt-1 z-50 w-64 rounded-md border border-border bg-card p-1 shadow-lg">+ {LAYOUT_MODES.map(({ mode, label, hint }) => (+ <button+ key={mode}+ type="button"+ role="menuitem"+ className="w-full rounded px-2 py-1.5 text-left cursor-pointer hover:bg-[#21262d]"+ onClick={() => pick(mode)}+ >+ <div className="text-xs text-foreground">{label}</div>+ <div className="text-[11px] text-muted-foreground">{hint}</div>+ </button>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/components/panels/__tests__/Toolbar.autoLayout.test.tsx b/frontend/src/components/panels/__tests__/Toolbar.autoLayout.test.tsxnew file mode 100644index 0000000..8785d02--- /dev/null+++ b/frontend/src/components/panels/__tests__/Toolbar.autoLayout.test.tsx@@ -0,0 +1,77 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { render, screen, fireEvent } from '@testing-library/react'+import { Toolbar } from '../Toolbar'+import { useCanvasStore } from '@/stores/canvasStore'++vi.mock('@/stores/canvasStore')++vi.mock('@/components/ui/Logo', () => ({+ Logo: () => <div data-testid="logo" />,+}))++const props = {+ onSave: vi.fn(),+ onAutoLayout: vi.fn(),+ onExport: vi.fn(),+ onChangeStyle: vi.fn(),+ onUndo: vi.fn(),+ onRedo: vi.fn(),+ onShortcuts: vi.fn(),+ onExportYaml: vi.fn(),+ onImportYaml: vi.fn(),+ onViewOnly: vi.fn(),+}++describe('Toolbar — Auto Layout modes (#326)', () => {+ beforeEach(() => {+ vi.mocked(useCanvasStore).mockReturnValue({+ hasUnsavedChanges: false,+ past: [],+ future: [],+ } as unknown as ReturnType<typeof useCanvasStore>)+ vi.clearAllMocks()+ })++ it('runs the plain hierarchy from the main button, without leaking the click event', () => {+ render(<Toolbar {...props} />)+ fireEvent.click(screen.getByText('Auto Layout'))+ expect(props.onAutoLayout).toHaveBeenCalledWith('hierarchy')+ })++ it('keeps the mode menu closed until the chevron opens it', () => {+ render(<Toolbar {...props} />)+ const chevron = screen.getByLabelText('More layout options')+ expect(screen.queryByRole('menu')).toBeNull()+ expect(chevron).toHaveAttribute('aria-expanded', 'false')++ fireEvent.click(chevron)+ expect(screen.getByRole('menu')).toBeInTheDocument()+ expect(chevron).toHaveAttribute('aria-expanded', 'true')+ expect(props.onAutoLayout).not.toHaveBeenCalled()+ })++ it.each([+ ['Group by device type', 'type'],+ ['Group by subnet', 'subnet'],+ ])('%s runs the %s mode and closes the menu', (label, mode) => {+ render(<Toolbar {...props} />)+ fireEvent.click(screen.getByLabelText('More layout options'))+ fireEvent.click(screen.getByText(label))+ expect(props.onAutoLayout).toHaveBeenCalledWith(mode)+ expect(screen.queryByRole('menu')).toBeNull()+ })++ it('closes the menu on Escape and on a click outside it', () => {+ render(<Toolbar {...props} />)+ const chevron = screen.getByLabelText('More layout options')++ fireEvent.click(chevron)+ fireEvent.keyDown(document, { key: 'Escape' })+ expect(screen.queryByRole('menu')).toBeNull()++ fireEvent.click(chevron)+ fireEvent.pointerDown(document.body)+ expect(screen.queryByRole('menu')).toBeNull()+ expect(props.onAutoLayout).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/utils/__tests__/zoneGrouping.test.ts b/frontend/src/utils/__tests__/zoneGrouping.test.tsnew file mode 100644index 0000000..39d0c71--- /dev/null+++ b/frontend/src/utils/__tests__/zoneGrouping.test.ts@@ -0,0 +1,233 @@+import { describe, it, expect } from 'vitest'+import type { Node, Edge } from '@xyflow/react'+import type { NodeData, EdgeData } from '@/types'+import {+ groupIntoZones,+ liftEdgesToTopLevel,+ subnetGroupLabel,+ typeGroupLabel,+} from '../zoneGrouping'+import { applyDagreLayout } from '../layout'++function node(id: string, type: string, extra: Partial<Node<NodeData>> & { ip?: string; label?: string } = {}): Node<NodeData> {+ const { ip, label, ...rest } = extra+ return {+ id,+ type,+ position: { x: 0, y: 0 },+ data: { type, label: label ?? id, ip, status: 'unknown', services: [] } as unknown as NodeData,+ ...rest,+ }+}++function edge(source: string, target: string, extra: Partial<Edge<EdgeData>> = {}): Edge<EdgeData> {+ return { id: `${source}-${target}`, source, target, data: {} as EdgeData, ...extra }+}++let seq = 0+const ids = () => `zone-${++seq}`++const zonesOf = (nodes: Node<NodeData>[]) => nodes.filter((n) => n.data.type === 'groupRect')+const zoneLabelled = (nodes: Node<NodeData>[], label: string) => zonesOf(nodes).find((z) => z.data.label === label)!++function overlaps(a: Node<NodeData>, b: Node<NodeData>, w = 160, h = 90) {+ return a.position.x < b.position.x + w && b.position.x < a.position.x + w+ && a.position.y < b.position.y + h && b.position.y < a.position.y + h+}++describe('typeGroupLabel', () => {+ it('maps a type to its picker family', () => {+ expect(typeGroupLabel('switch')).toBe('Hardware')+ expect(typeGroupLabel('lxc')).toBe('Virtualization')+ expect(typeGroupLabel('zigbee_router')).toBe('Zigbee')+ })++ it('files an unknown type under Other', () => {+ expect(typeGroupLabel('mystery_box')).toBe('Other')+ })+})++describe('subnetGroupLabel', () => {+ it('returns the /24 of an address', () => {+ expect(subnetGroupLabel('192.168.1.42')).toBe('192.168.1.0/24')+ })++ it('strips a stored prefix or port', () => {+ expect(subnetGroupLabel('10.0.5.7/16')).toBe('10.0.5.0/24')+ expect(subnetGroupLabel('10.0.5.7:8006')).toBe('10.0.5.0/24')+ })++ it('is null for a missing or non-IPv4 address', () => {+ expect(subnetGroupLabel(undefined)).toBeNull()+ expect(subnetGroupLabel('')).toBeNull()+ expect(subnetGroupLabel('fe80::1')).toBeNull()+ expect(subnetGroupLabel('nas.local')).toBeNull()+ })+})++describe('groupIntoZones', () => {+ it('creates one zone per family and nests every free device in it', () => {+ const nodes = [node('sw', 'switch'), node('srv', 'server'), node('vm1', 'vm'), node('ct1', 'lxc')]+ const { nodes: out, moved, zonesCreated } = groupIntoZones(nodes, 'type', ids)++ expect(moved).toBe(4)+ expect(zonesCreated).toBe(2)+ const hw = zoneLabelled(out, 'Hardware')+ const virt = zoneLabelled(out, 'Virtualization')+ expect(out.find((n) => n.id === 'sw')!.parentId).toBe(hw.id)+ expect(out.find((n) => n.id === 'srv')!.parentId).toBe(hw.id)+ expect(out.find((n) => n.id === 'vm1')!.parentId).toBe(virt.id)+ expect(out.find((n) => n.id === 'vm1')!.data.parent_id).toBe(virt.id)+ })++ it('groups by /24 and leaves a device with no IP loose', () => {+ const nodes = [+ node('a', 'server', { ip: '192.168.1.10' }),+ node('b', 'nas', { ip: '192.168.1.20' }),+ node('c', 'vm', { ip: '10.0.0.5' }),+ node('d', 'computer'),+ ]+ const { nodes: out, moved } = groupIntoZones(nodes, 'subnet', ids)++ expect(moved).toBe(3)+ expect(zonesOf(out).map((z) => z.data.label)).toEqual(['10.0.0.0/24', '192.168.1.0/24'])+ const lan = zoneLabelled(out, '192.168.1.0/24')+ expect(out.find((n) => n.id === 'a')!.parentId).toBe(lan.id)+ expect(out.find((n) => n.id === 'b')!.parentId).toBe(lan.id)+ expect(out.find((n) => n.id === 'd')!.parentId).toBeUndefined()+ })++ it('never moves a nested node or canvas furniture', () => {+ const nodes = [+ node('pve', 'proxmox', { width: 300, height: 200 }),+ node('vm1', 'vm', { parentId: 'pve' }),+ node('note', 'text'),+ node('g', 'group'),+ ]+ const { nodes: out, moved } = groupIntoZones(nodes, 'type', ids)++ expect(moved).toBe(1)+ const virt = zoneLabelled(out, 'Virtualization')+ expect(out.find((n) => n.id === 'pve')!.parentId).toBe(virt.id)+ expect(out.find((n) => n.id === 'vm1')!.parentId).toBe('pve')+ expect(out.find((n) => n.id === 'note')!.parentId).toBeUndefined()+ expect(out.find((n) => n.id === 'g')!.parentId).toBeUndefined()+ })++ it('reuses a zone that already carries the label, whatever its case', () => {+ const zone = node('mine', 'groupRect', { label: ' hardware ', width: 500, height: 300 })+ const { nodes: out, zonesCreated } = groupIntoZones([zone, node('sw', 'switch')], 'type', ids)++ expect(zonesCreated).toBe(0)+ expect(zonesOf(out)).toHaveLength(1)+ expect(out.find((n) => n.id === 'sw')!.parentId).toBe('mine')+ })++ it('is stable on a second run: nothing moves, no zone is added', () => {+ const first = groupIntoZones([node('sw', 'switch'), node('vm1', 'vm')], 'type', ids)+ const second = groupIntoZones(first.nodes, 'type', ids)++ expect(second.moved).toBe(0)+ expect(second.zonesCreated).toBe(0)+ expect(second.nodes).toBe(first.nodes)+ })++ it('packs arrivals below what a reused zone already holds', () => {+ const zone = node('z', 'groupRect', { label: 'Hardware', width: 400, height: 240 })+ const kept = node('kept', 'router', { parentId: 'z', position: { x: 16, y: 40 }, width: 160, height: 90 })+ const { nodes: out } = groupIntoZones([zone, kept, node('sw', 'switch')], 'type', ids)++ const sw = out.find((n) => n.id === 'sw')!+ expect(sw.position.y).toBeGreaterThanOrEqual(40 + 90)+ expect(out.find((n) => n.id === 'kept')!.position).toEqual({ x: 16, y: 40 })+ })++ it('lays members out without overlap and grows the zone to cover them', () => {+ const nodes = Array.from({ length: 9 }, (_, i) => node(`s${i}`, 'server'))+ const { nodes: out } = groupIntoZones(nodes, 'type', ids)++ const zone = zoneLabelled(out, 'Hardware')+ const members = out.filter((n) => n.parentId === zone.id)+ for (let i = 0; i < members.length; i++) {+ for (let j = i + 1; j < members.length; j++) expect(overlaps(members[i], members[j])).toBe(false)+ }+ for (const m of members) {+ expect(m.position.x + 160).toBeLessThanOrEqual(zone.width!)+ expect(m.position.y + 90).toBeLessThanOrEqual(zone.height!)+ }+ })++ it('makes room for a member larger than a card', () => {+ const pve = node('pve', 'proxmox', { width: 600, height: 400 })+ const { nodes: out } = groupIntoZones([pve, node('vm', 'vm')], 'type', ids)++ const zone = zoneLabelled(out, 'Virtualization')+ expect(zone.width!).toBeGreaterThanOrEqual(600 + 32)+ expect(zone.height!).toBeGreaterThanOrEqual(400 + 40)+ })++ it('never shrinks a reused zone', () => {+ const zone = node('z', 'groupRect', { label: 'Hardware', width: 900, height: 700 })+ const { nodes: out } = groupIntoZones([zone, node('sw', 'switch')], 'type', ids)++ expect(out.find((n) => n.id === 'z')!.width).toBe(900)+ expect(out.find((n) => n.id === 'z')!.height).toBe(700)+ })++ it('returns the input untouched when there is nothing to group', () => {+ const nodes = [node('d', 'computer')]+ const res = groupIntoZones(nodes, 'subnet', ids)+ expect(res).toEqual({ nodes, moved: 0, zonesCreated: 0 })+ })+})++describe('liftEdgesToTopLevel', () => {+ const nodes = [+ node('router', 'router'),+ node('z', 'groupRect'),+ node('pve', 'proxmox', { parentId: 'z' }),+ node('vm', 'vm', { parentId: 'pve' }),+ node('srv', 'server', { parentId: 'z' }),+ ]++ it('re-points a nested end at its top-level box and drops its handle', () => {+ const [e] = liftEdgesToTopLevel(nodes, [edge('router', 'vm', { sourceHandle: 'bottom-2', targetHandle: 'top' })])+ expect(e).toMatchObject({ source: 'router', target: 'z', sourceHandle: 'bottom-2', targetHandle: null })+ })++ it('drops an edge whose two ends share a box, and collapses duplicates', () => {+ const lifted = liftEdgesToTopLevel(nodes, [+ edge('pve', 'srv'),+ edge('router', 'vm'),+ edge('router', 'srv'),+ ])+ expect(lifted.map((e) => [e.source, e.target])).toEqual([['router', 'z']])+ })++ it('drops an edge to a node that does not exist', () => {+ expect(liftEdgesToTopLevel(nodes, [edge('router', 'ghost')])).toEqual([])+ })+})++describe('grouping then Dagre (the Auto Layout path)', () => {+ it('stacks the zones under the router they hang off, side by side', () => {+ const nodes = [+ node('router', 'router'),+ ...['1', '2', '3'].map((i) => node(`lan${i}`, 'server', { ip: `192.168.1.${i}` })),+ ...['1', '2'].map((i) => node(`iot${i}`, 'iot', { ip: `192.168.50.${i}` })),+ ]+ const edges = [...nodes.slice(1).map((n) => edge('router', n.id))]++ const grouped = groupIntoZones(nodes, 'subnet', ids)+ const laid = applyDagreLayout(grouped.nodes, liftEdgesToTopLevel(grouped.nodes, edges))++ const router = laid.find((n) => n.id === 'router')!+ const [a, b] = zonesOf(laid)+ for (const z of [a, b]) expect(z.position.y).toBeGreaterThanOrEqual(router.position.y + 52)+ // Same rank: Dagre centres boxes of different heights on it.+ expect(a.position.y + a.height! / 2).toBe(b.position.y + b.height! / 2)+ const [left, right] = a.position.x < b.position.x ? [a, b] : [b, a]+ expect(left.position.x + left.width!).toBeLessThanOrEqual(right.position.x)+ })+})+diff --git a/frontend/src/utils/zoneGrouping.ts b/frontend/src/utils/zoneGrouping.tsnew file mode 100644index 0000000..5e6063c--- /dev/null+++ b/frontend/src/utils/zoneGrouping.ts@@ -0,0 +1,222 @@+import type { Node, Edge } from '@xyflow/react'+import type { NodeData, EdgeData } from '@/types'+import { NODE_TYPE_GROUPS, FURNITURE_TYPES } from '@/utils/nodeTypeGroups'+import { ipToInt } from '@/utils/subnet'+import { generateUUID } from '@/utils/uuid'++/**+ * Auto Layout modes (#326). `hierarchy` is the plain Dagre tree; the other two+ * first sort the free devices into zones — one per device family, or one per+ * /24 — and then run the same tree over the zones and whatever stayed loose.+ */+export type AutoLayoutMode = 'hierarchy' | 'type' | 'subnet'++// Zone geometry, in zone-relative pixels. Matches the zone subnet import in the+// store: a 360×240 zone, a label band at the top, a card-sized default box.+const ZONE_MIN_WIDTH = 360+const ZONE_MIN_HEIGHT = 240+const PAD_X = 16+const PAD_TOP = 40+const PAD_BOTTOM = 16+const GAP = 20+const DEFAULT_BOX_W = 160+const DEFAULT_BOX_H = 90+const MAX_COLUMNS = 4++const TYPE_ORDER = NODE_TYPE_GROUPS.map((g) => g.label)+const OTHER_LABEL = 'Other'++/** The zone a node type belongs to: its family in the type picker. */+export function typeGroupLabel(type: string): string {+ return NODE_TYPE_GROUPS.find((g) => (g.types as string[]).includes(type))?.label ?? OTHER_LABEL+}++/**+ * The /24 an address sits in, as "192.168.1.0/24". A prefix or a port on the+ * stored value is stripped, as `ipInSubnet` does. Null for no or non-IPv4 address.+ */+export function subnetGroupLabel(ip: string | null | undefined): string | null {+ if (!ip) return null+ const value = ipToInt(ip.trim().split('/')[0].split(':')[0])+ if (value === null) return null+ const base = (value & 0xffffff00) >>> 0+ return `${[24, 16, 8, 0].map((s) => (base >>> s) & 0xff).join('.')}/24`+}++function groupLabel(node: Node<NodeData>, mode: Exclude<AutoLayoutMode, 'hierarchy'>): string | null {+ return mode === 'type' ? typeGroupLabel(node.data.type) : subnetGroupLabel(node.data.ip)+}++function compareLabels(mode: Exclude<AutoLayoutMode, 'hierarchy'>) {+ if (mode === 'subnet') {+ return (a: string, b: string) => (ipToInt(a.split('/')[0]) ?? 0) - (ipToInt(b.split('/')[0]) ?? 0)+ }+ const rank = (l: string) => {+ const i = TYPE_ORDER.indexOf(l)+ return i === -1 ? TYPE_ORDER.length : i+ }+ return (a: string, b: string) => rank(a) - rank(b)+}++function boxOf(n: Node<NodeData>): { w: number; h: number } {+ return {+ w: n.width ?? n.measured?.width ?? DEFAULT_BOX_W,+ h: n.height ?? n.measured?.height ?? DEFAULT_BOX_H,+ }+}++const sameLabel = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase()++export interface ZoneGroupingResult {+ nodes: Node<NodeData>[]+ /** Devices that moved into a zone. */+ moved: number+ /** Zones that did not exist before. */+ zonesCreated: number+}++/**+ * Sort every free device into a zone, by family or by /24.+ *+ * "Free" is the rule the zone subnet import runs on: top level (a node already+ * nested in a zone, a group or a container host keeps the parent the user gave+ * it) and not canvas furniture. In subnet mode a device with no IPv4 address+ * stays loose. A top-level zone already carrying the group's label is reused,+ * so a second run fills the same zones instead of stacking duplicates; its+ * current contents stay where they are and arrivals go in below them.+ *+ * Arrivals are packed on shelves at their real size, so a Proxmox host with its+ * VMs gets the room it needs. Zones grow to fit and never shrink. Positions of+ * the zones themselves are left to the Dagre pass that follows.+ */+export function groupIntoZones(+ nodes: Node<NodeData>[],+ mode: Exclude<AutoLayoutMode, 'hierarchy'>,+ newId: () => string = generateUUID,+): ZoneGroupingResult {+ const groups = new Map<string, Node<NodeData>[]>()+ for (const n of nodes) {+ if (n.parentId || FURNITURE_TYPES.has(n.data.type)) continue+ const label = groupLabel(n, mode)+ if (!label) continue+ if (!groups.has(label)) groups.set(label, [])+ groups.get(label)!.push(n)+ }+ if (groups.size === 0) return { nodes, moved: 0, zonesCreated: 0 }++ const zonesByLabel = nodes.filter((n) => n.data.type === 'groupRect' && !n.parentId)+ const updates = new Map<string, Node<NodeData>>()+ const created: Node<NodeData>[] = []+ let moved = 0++ for (const label of [...groups.keys()].sort(compareLabels(mode))) {+ const members = groups.get(label)!+ const existing = zonesByLabel.find((z) => sameLabel(z.data.label ?? '', label))+ const zoneId = existing?.id ?? newId()+ const zoneW = existing ? (existing.width ?? existing.measured?.width ?? ZONE_MIN_WIDTH) : ZONE_MIN_WIDTH+ const zoneH = existing ? (existing.height ?? existing.measured?.height ?? ZONE_MIN_HEIGHT) : ZONE_MIN_HEIGHT++ // Arrivals start under whatever the zone already holds.+ let y = PAD_TOP+ for (const child of nodes) {+ if (child.parentId !== zoneId) continue+ y = Math.max(y, child.position.y + boxOf(child).h + GAP)+ }++ // Shelf packing: a row is as wide as the zone (or MAX_COLUMNS default boxes+ // for a new zone, whichever is wider), as tall as its tallest box.+ const columns = Math.min(MAX_COLUMNS, Math.ceil(Math.sqrt(members.length)))+ const rowWidth = Math.max(zoneW - 2 * PAD_X, columns * (DEFAULT_BOX_W + GAP) - GAP)+ let x = PAD_X+ let rowH = 0+ let right = 0+ for (const m of members) {+ const { w, h } = boxOf(m)+ if (x > PAD_X && x + w > PAD_X + rowWidth) {+ x = PAD_X+ y += rowH + GAP+ rowH = 0+ }+ updates.set(m.id, {+ ...m,+ parentId: zoneId,+ extent: undefined,+ position: { x, y },+ selected: false,+ data: { ...m.data, parent_id: zoneId },+ })+ right = Math.max(right, x + w)+ rowH = Math.max(rowH, h)+ x += w + GAP+ moved += 1+ }++ const width = Math.max(zoneW, right + PAD_X)+ const height = Math.max(zoneH, y + rowH + PAD_BOTTOM)+ if (existing) {+ if (width !== zoneW || height !== zoneH) updates.set(existing.id, { ...existing, width, height })+ } else {+ created.push({+ id: zoneId,+ type: 'groupRect',+ position: { x: 0, y: 0 },+ data: {+ label,+ type: 'groupRect',+ status: 'unknown',+ services: [],+ custom_colors: { z_order: 1 },+ } as NodeData,+ width,+ height,+ // Same stacking as a zone drawn by hand at the default z-order.+ zIndex: 1 - 10,+ })+ }+ }++ return {+ nodes: [...created, ...nodes.map((n) => updates.get(n.id) ?? n)],+ moved,+ zonesCreated: created.length,+ }+}++/**+ * Edges re-pointed at the top-level box each endpoint lives in, for layout only.+ * Dagre sees top-level nodes alone, so without this a zone full of VMs wired to+ * a router would float free of it. Self-loops (both ends in one box) are+ * dropped, duplicates collapsed, and a lifted end loses its handle, which named+ * a port on the child, not on the box.+ */+export function liftEdgesToTopLevel(nodes: Node<NodeData>[], edges: Edge<EdgeData>[]): Edge<EdgeData>[] {+ const byId = new Map(nodes.map((n) => [n.id, n]))+ const topOf = (id: string): string | null => {+ let cur = byId.get(id)+ const seen = new Set<string>()+ while (cur?.parentId && !seen.has(cur.id)) {+ seen.add(cur.id)+ cur = byId.get(cur.parentId)+ }+ return cur?.id ?? null+ }++ const out: Edge<EdgeData>[] = []+ const pairs = new Set<string>()+ for (const e of edges) {+ const s = topOf(e.source)+ const t = topOf(e.target)+ if (!s || !t || s === t) continue+ const key = `${s}\u0000${t}`+ if (pairs.has(key)) continue+ pairs.add(key)+ out.push({+ ...e,+ source: s,+ target: t,+ sourceHandle: s === e.source ? e.sourceHandle : null,+ targetHandle: t === e.target ? e.targetHandle : null,+ })+ }+ return out+}