Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(rack): commit height and colour edits on blur, not per keystroke
Pouzor5617f0800fe4
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex d8459ae..61bfc99 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -149,7 +149,9 @@ export default function App() {const saveDesignId = designIdOverride ?? activeDesignId// Rack canvases own their own state and persistence path.if (designTypeOf(saveDesignId) === 'rack') {- const ok = await useRackStore.getState().save()+ // Named explicitly: the design-switch flow saves the *old* design, and+ // the store refuses rather than writing under whichever one it holds.+ const ok = await useRackStore.getState().save(saveDesignId)if (ok) {if (!options?.silent) toast.success('Rack canvas saved')} else {diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdindex bfbeb4d..f299233 100644--- a/frontend/src/rack/README.md+++ b/frontend/src/rack/README.md@@ -38,7 +38,7 @@ debounces on the store's `editSeq`.| `racks`, `rack_devices`, `rack_cables` | One row set per design. `rack_devices.device_id → pending_devices` and `node_id → nodes` are both `ON DELETE SET NULL`, and `label` is denormalized, so a rack keeps rendering after an inventory purge. || `canvas_state.viewport` | Pan/zoom, shared with the logical canvas row for that design. || `GET /api/v1/racks?design_id=` | Full state. |-| `POST /api/v1/racks/save` | Full state: upsert what is sent, prune the rest. Rejects a device pointing at a rack outside the payload, or a cable pointing at a device outside it. |+| `POST /api/v1/racks/save` | Full state: upsert what is sent, prune the rest. Rejects a device pointing at a rack outside the payload, or a cable pointing at a device outside it. Also cross-checks geometry: a mount against the height of the rack it names, and `col_start + col_span` against the grid — each field is legal alone and the pair is not. || `GET /api/v1/racks/inventory?design_id=` | Rackable inventory entries, each flagged `racked` and resolved to a canvas node when one matches. || `POST /api/v1/scan/pending` | Manual inventory entry (`discovery_source: "manual"`), for hardware no scan can find. || Standalone | `homelable_rack:<designId>` in localStorage, inventory included (no `pending_devices` table to read). |@@ -56,6 +56,8 @@ types in `@/types/rack`, narrowing every enum on the way in.- Double-click empty rack chrome → `RackSettingsModal` (name, location, U height, 19"/10", numbering direction, frame/rail/interior colours, U numbers, enclosed, delete).- Growing a device — by hand or by picking a taller plate — relocates it to the nearest slot that takes the new size. Only a rack with no such slot rejects the edit, and says so.- Shrinking a **rack** follows the same rule: `updateRack` clamps `uHeight` to `[MIN_RACK_U, MAX_RACK_U]` (1–48; the backend tolerates 100) and relocates every mount the new height would push above the top rail, one at a time so two never land on the same slot. It returns false and changes nothing when one has nowhere to go. The number input's `min`/`max` are hints the browser does not enforce on typed input — a raw 999 used to make every save fail the backend's `1..100` check with no cause shown, and a shrink left plates drawn outside the chassis that nothing could drag back.+- The height field commits on **blur or Enter**, never per keystroke: backspacing `24` walks through `2`, and the relocation that would trigger is not undone when the digits come back — the rack canvas has no undo. The colour hex field in `RackCablePanel` commits the same way, falling back to the cable type's default when the value does not parse, rather than feeding the SVG `stroke` a half-typed `#39d`.+- **Delete rack** asks first, naming how many mounts it unmounts. It takes every mount and every cable touching them; only the Device Inventory survives.- **Patch mode**: drag from port A to port B to cable them — a dashed rubber band follows the pointer, exactly like dragging an edge on the logical canvas. Clicking A then B still works; Escape drops a half-drawn patch. Rack dragging is disabled while in patch mode.- **Click a cable** — in patch mode or out of it — to select it: it gets an accent halo and opens `RackCablePanel` on the right (endpoints, type, colour, label, properties, Unplug). Delete/Backspace unplugs the selection; Escape or a pane click deselects. Selecting a cable drops any mount/rack selection and vice versa — one rail, one occupant.- **Import links**: reads the physical edges (ethernet/fibre/vlan/cluster) of every non-rack design and matches them on `nodeId`. Idempotent — a device pair already cabled is skipped, whichever ports carry it, so a re-run after racking more gear adds only what is missing. There is no "done" flag: one lived in memory only, and a reload re-armed the import onto the next free ports.diff --git a/frontend/src/rack/__tests__/RackCablePanel.test.tsx b/frontend/src/rack/__tests__/RackCablePanel.test.tsxindex 0b41879..da2cc64 100644--- a/frontend/src/rack/__tests__/RackCablePanel.test.tsx+++ b/frontend/src/rack/__tests__/RackCablePanel.test.tsx@@ -52,10 +52,46 @@ describe('RackCablePanel', () => {fireEvent.click(screen.getByLabelText('Cable colour #a855f7'))expect(selected().color).toBe('#a855f7')- fireEvent.change(screen.getByLabelText('Cable colour hex'), { target: { value: '#123456' } })+ const hex = screen.getByLabelText('Cable colour hex')+ fireEvent.change(hex, { target: { value: '#123456' } })+ fireEvent.blur(hex)expect(selected().color).toBe('#123456')})+ it('leaves the cable alone while a hex is half-typed', () => {+ // "#39d" parses as a colour, but "#3" does not — a per-keystroke write fed+ // the SVG stroke junk and the run stopped rendering.+ const cable = store().cables[0]+ store().selectCable(cable.id)+ render(<RackCablePanel />)++ fireEvent.change(screen.getByLabelText('Cable colour hex'), { target: { value: '#12' } })+ expect(selected().color).toBe(cable.color)+ })++ it('falls back to the type default when the hex does not parse', () => {+ const cable = store().cables.find((c) => c.type === 'ethernet')!+ store().selectCable(cable.id)+ render(<RackCablePanel />)++ const hex = screen.getByLabelText('Cable colour hex')+ fireEvent.change(hex, { target: { value: 'zzz' } })+ fireEvent.blur(hex)++ expect(selected().color).toBe(CABLE_COLORS.ethernet)+ })++ it('accepts the three-digit shorthand', () => {+ store().selectCable(store().cables[0].id)+ render(<RackCablePanel />)++ const hex = screen.getByLabelText('Cable colour hex')+ fireEvent.change(hex, { target: { value: '#abc' } })+ fireEvent.blur(hex)++ expect(selected().color).toBe('#abc')+ })+it('recolours a default-coloured cable when its type changes', () => {const ethernet = store().cables.find((c) => c.type === 'ethernet')!store().updateCable(ethernet.id, { color: CABLE_COLORS.ethernet })diff --git a/frontend/src/rack/__tests__/RackSettingsModal.test.tsx b/frontend/src/rack/__tests__/RackSettingsModal.test.tsxindex 721cb88..c7f3762 100644--- a/frontend/src/rack/__tests__/RackSettingsModal.test.tsx+++ b/frontend/src/rack/__tests__/RackSettingsModal.test.tsx@@ -1,5 +1,5 @@/** Rack settings moved out of the right rail into their own dialog. */-import { describe, it, expect, beforeEach, vi } from 'vitest'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import { render, screen, fireEvent } from '@testing-library/react'import { RackSettingsModal } from '../components/RackSettingsModal'import { useRackStore } from '../store'@@ -10,6 +10,13 @@ const store = () => useRackStore.getState()beforeEach(() => {store().loadDemo()+ // Deleting a rack takes its mounts and their patching with it, so the modal+ // asks first. Default to "yes" and let the tests that care say otherwise.+ vi.spyOn(window, 'confirm').mockReturnValue(true)+})++afterEach(() => {+ vi.restoreAllMocks()})describe('RackSettingsModal', () => {@@ -18,12 +25,14 @@ describe('RackSettingsModal', () => {expect(container).toBeEmptyDOMElement()})- it('edits name and capacity live', () => {+ it('edits name live and capacity on commit', () => {store().openRackEditor('rack-main')render(<RackSettingsModal />)fireEvent.change(screen.getByLabelText('Rack name'), { target: { value: 'Garage' } })- fireEvent.change(screen.getByLabelText('Rack height'), { target: { value: '24' } })+ const height = screen.getByLabelText('Rack height')+ fireEvent.change(height, { target: { value: '24' } })+ fireEvent.blur(height)const rack = store().racks.find((r) => r.id === 'rack-main')!expect(rack.name).toBe('Garage')@@ -36,14 +45,87 @@ describe('RackSettingsModal', () => {expect(screen.getByText(/U used of 18U/)).toBeInTheDocument()})- it('deletes the rack and closes', () => {+ it('leaves the rack alone while the height is being typed', () => {+ // Backspacing "18" walks through "1", which would shrink the rack and+ // relocate every mount — a move nothing undoes when the digits come back.+ store().openRackEditor('rack-main')+ const before = store().devices.map((d) => ({ ...d }))+ render(<RackSettingsModal />)++ const height = screen.getByLabelText('Rack height')+ fireEvent.change(height, { target: { value: '1' } })++ expect(store().racks[0].uHeight).toBe(18)+ expect(store().devices).toEqual(before)+ })++ it('commits the height on Enter', () => {+ store().openRackEditor('rack-main')+ render(<RackSettingsModal />)++ const height = screen.getByLabelText('Rack height')+ fireEvent.change(height, { target: { value: '30' } })+ fireEvent.keyDown(height, { key: 'Enter' })+ fireEvent.blur(height)++ expect(store().racks[0].uHeight).toBe(30)+ })++ it('reverts the field when the shrink is refused', () => {+ store().openRackEditor('rack-main')+ render(<RackSettingsModal />)++ const height = screen.getByLabelText('Rack height')+ fireEvent.change(height, { target: { value: '1' } })+ fireEvent.blur(height)++ expect(store().racks[0].uHeight).toBe(18)+ expect((height as HTMLInputElement).value).toBe('18')+ })++ it('commits nothing when the dialog closes on a typed height', () => {+ // Escape closes the dialog; the uncommitted draft dies with the field.+ store().openRackEditor('rack-main')+ render(<RackSettingsModal />)++ fireEvent.change(screen.getByLabelText('Rack height'), { target: { value: '5' } })+ fireEvent.keyDown(screen.getByLabelText('Rack height'), { key: 'Escape' })++ expect(store().racks[0].uHeight).toBe(18)+ })++ it('deletes the rack and closes once confirmed', () => {store().openRackEditor('rack-main')render(<RackSettingsModal />)fireEvent.click(screen.getByRole('button', { name: 'Delete rack' }))+ expect(window.confirm).toHaveBeenCalled()expect(store().racks).toHaveLength(0)expect(store().devices).toHaveLength(0)expect(store().rackEditorId).toBeNull()})++ it('keeps the rack when the delete is declined', () => {+ vi.mocked(window.confirm).mockReturnValue(false)+ store().openRackEditor('rack-main')+ const mounted = store().devices.length+ render(<RackSettingsModal />)++ fireEvent.click(screen.getByRole('button', { name: 'Delete rack' }))++ expect(store().racks).toHaveLength(1)+ expect(store().devices).toHaveLength(mounted)+ expect(store().rackEditorId).toBe('rack-main')+ })++ it('counts the mounts it is about to unmount in the warning', () => {+ store().openRackEditor('rack-main')+ const mounted = store().devices.filter((d) => d.rackId === 'rack-main').length+ render(<RackSettingsModal />)++ fireEvent.click(screen.getByRole('button', { name: 'Delete rack' }))++ expect(vi.mocked(window.confirm).mock.calls[0][0]).toContain(`${mounted} device`)+ })})diff --git a/frontend/src/rack/__tests__/persistence.test.ts b/frontend/src/rack/__tests__/persistence.test.tsindex 8316ca8..957e8d5 100644--- a/frontend/src/rack/__tests__/persistence.test.ts+++ b/frontend/src/rack/__tests__/persistence.test.ts@@ -157,6 +157,22 @@ describe('save', () => {expect(await store().save()).toBe(false)expect(store().hasUnsavedChanges).toBe(true)})++ it('saves when the design it was told to save is the one loaded', async () => {+ await store().loadDesign('d1')+ expect(await store().save('d1')).toBe(true)+ expect(save.mock.calls[0][0].design_id).toBe('d1')+ })++ it('writes nothing when the store has moved on to another design', async () => {+ // The design-switch flow saves the old design; if the store already holds+ // the new one, saving would persist it under the wrong id.+ await store().loadDesign('d1')+ store().addRack()+ expect(await store().save('d-other')).toBe(false)+ expect(save).not.toHaveBeenCalled()+ expect(store().hasUnsavedChanges).toBe(true)+ })})describe('createInventoryDevice', () => {diff --git a/frontend/src/rack/components/RackCablePanel.tsx b/frontend/src/rack/components/RackCablePanel.tsxindex e9ef754..90ad6b6 100644--- a/frontend/src/rack/components/RackCablePanel.tsx+++ b/frontend/src/rack/components/RackCablePanel.tsx@@ -7,6 +7,7 @@* the same free-form property records the logical canvas uses for nodes, each* with its own "show it on the canvas" toggle.*/+import { useState } from 'react'import { Cable as CableIcon, Trash2, X } from 'lucide-react'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -112,12 +113,10 @@ export function RackCablePanel() {/>))}</div>- <Input+ <HexFieldvalue={cable.color}- onChange={(e) => updateCable(cable.id, { color: e.target.value })}- aria-label="Cable colour hex"- placeholder="#39d353"- className="mt-2 bg-[#21262d] border-[#30363d] text-xs h-7 font-mono"+ fallback={CABLE_COLORS[cable.type]}+ onCommit={(color) => updateCable(cable.id, { color })}/></div>@@ -166,6 +165,53 @@ export function RackCablePanel() {)}+/**+ * Free-text colour, committed on blur or Enter once it parses.+ *+ * Writing every keystroke into `cable.color` fed partial values (`#39d`) to the+ * SVG `stroke`, and the run stopped rendering with no feedback. An unparseable+ * value falls back to the cable type's default rather than leaving an invisible+ * cable behind.+ */+function HexField({ value, fallback, onCommit }: {+ value: string+ fallback: string+ onCommit: (color: string) => void+}) {+ const [draft, setDraft] = useState(value)++ // Follow a colour set elsewhere (a swatch, a type change). Adjusted during+ // render, not in an effect, so the field never shows the stale value first.+ const [seen, setSeen] = useState(value)+ if (seen !== value) {+ setSeen(value)+ setDraft(value)+ }++ const commit = () => {+ const next = draft.trim()+ const valid = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(next)+ const color = valid ? next : fallback+ setDraft(color)+ if (color !== value) onCommit(color)+ }++ return (+ <Input+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === 'Enter') e.currentTarget.blur()+ if (e.key === 'Escape') setDraft(value)+ }}+ aria-label="Cable colour hex"+ placeholder="#39d353"+ className="mt-2 bg-[#21262d] border-[#30363d] text-xs h-7 font-mono"+ />+ )+}+function EndpointRow({ side, device, port }: { side: string; device: string; port: string }) {return (<div className="flex items-baseline gap-2 min-w-0">diff --git a/frontend/src/rack/components/RackSettingsModal.tsx b/frontend/src/rack/components/RackSettingsModal.tsxindex 33685b0..2797d09 100644--- a/frontend/src/rack/components/RackSettingsModal.tsx+++ b/frontend/src/rack/components/RackSettingsModal.tsx@@ -4,6 +4,7 @@* Same reasoning as `RackDeviceModal`: the rack canvas has no right rail, so the* settings live in a dialog. Opened by double-clicking a rack's chassis.*/+import { useState } from 'react'import { toast } from 'sonner'import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'import { Button } from '@/components/ui/button'@@ -62,21 +63,7 @@ export function RackSettingsModal() {/></Field><Field label={`Height — ${used}U used of ${rack.uHeight}U`}>- <input- type="number"- min={MIN_RACK_U}- max={MAX_RACK_U}- className={inputClass}- aria-label="Rack height"- value={rack.uHeight}- onChange={(e) => {- // The store clamps and relocates; it only refuses when a mount- // the shrink pushes out has nowhere left to go.- if (!updateRack(rack.id, { uHeight: Number(e.target.value) || MIN_RACK_U })) {- toast.error('Not enough room to shrink the rack — unmount something first')- }- }}- />+ <HeightField rackId={rack.id} uHeight={rack.uHeight} /></Field><div className="grid grid-cols-2 gap-3">@@ -142,6 +129,13 @@ export function RackSettingsModal() {type="button"variant="ghost"onClick={() => {+ // Takes every mount and every patch touching them with it, and+ // the rack canvas has no undo. Ask first.+ const mounted = devices.filter((d) => d.rackId === rack.id).length+ const warning = mounted+ ? `Delete "${rack.name}" and unmount ${mounted} device${mounted > 1 ? 's' : ''}? Their cabling is removed too. The Device Inventory is untouched.`+ : `Delete "${rack.name}"?`+ if (!confirm(warning)) returnremoveRack(rack.id)close()}}@@ -158,3 +152,56 @@ export function RackSettingsModal() {</Dialog>)}++/**+ * Rack height, committed on blur or Enter rather than per keystroke.+ *+ * Typing into a controlled number input walks through intermediate values —+ * backspacing "24" yields "2" — and `updateRack` relocates the mounts a shrink+ * pushes past the top rail. Those relocations are not undone when the digits+ * come back, and the rack canvas has no undo, so a per-keystroke commit quietly+ * rearranged the rack. Only the settled value reaches the store.+ */+function HeightField({ rackId, uHeight }: { rackId: string; uHeight: number }) {+ const updateRack = useRackStore((s) => s.updateRack)+ const [draft, setDraft] = useState(String(uHeight))++ // Follow the store when the height changes elsewhere — a clamp, or another+ // rack opened into the same field. Adjusted during render rather than in an+ // effect, which would render the stale draft first.+ const [seen, setSeen] = useState({ rackId, uHeight })+ if (seen.rackId !== rackId || seen.uHeight !== uHeight) {+ setSeen({ rackId, uHeight })+ setDraft(String(uHeight))+ }++ const commit = () => {+ const next = Number(draft) || MIN_RACK_U+ if (next === uHeight) {+ setDraft(String(uHeight))+ return+ }+ if (!updateRack(rackId, { uHeight: next })) {+ toast.error('Not enough room to shrink the rack — unmount something first')+ setDraft(String(uHeight))+ }+ }++ return (+ <input+ type="number"+ min={MIN_RACK_U}+ max={MAX_RACK_U}+ className={inputClass}+ aria-label="Rack height"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={commit}+ // Escape needs no branch here: the dialog closes on it, and the draft+ // dies with the field having committed nothing.+ onKeyDown={(e) => {+ if (e.key === 'Enter') e.currentTarget.blur()+ }}+ />+ )+}diff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.tsindex f5501a4..e926733 100644--- a/frontend/src/rack/store.ts+++ b/frontend/src/rack/store.ts@@ -129,7 +129,12 @@ interface RackState {// PersistenceloadDesign: (designId: string) => Promise<void>refreshInventory: () => Promise<void>- save: () => Promise<boolean>+ /**+ * Persist the rack state. `expectedDesignId` guards against saving under a+ * design the caller did not mean: it returns false, saving nothing, when the+ * store has moved on to another design.+ */+ save: (expectedDesignId?: string | null) => Promise<boolean>markSaved: () => void/** Add an inventory entry by hand, for hardware no scan can find. */createInventoryDevice: (input: NewInventoryDevice) => Promise<InventoryDevice | null>@@ -330,9 +335,13 @@ export const useRackStore = create<RackState>((set, get) => {}},- save: async () => {+ save: async (expectedDesignId) => {const { designId, racks, devices, cables, viewport, inventory } = get()if (!designId) return false+ // The design-switch flow saves the *old* design before loading the new+ // one. This store writes whatever it currently holds, so a switch landing+ // mid-flight would persist the wrong design and drop the other's edits.+ if (expectedDesignId && expectedDesignId !== designId) return falsetry {if (STANDALONE) {standaloneStorage.saveRackCanvas(designId, { racks, devices, cables, viewport, inventory })diff --git a/frontend/src/utils/__tests__/rackSerializer.test.ts b/frontend/src/utils/__tests__/rackSerializer.test.tsindex b4695f3..32be80b 100644--- a/frontend/src/utils/__tests__/rackSerializer.test.ts+++ b/frontend/src/utils/__tests__/rackSerializer.test.ts@@ -13,6 +13,7 @@ import {type ApiRackDevice,} from '../rackSerializer'import { DEFAULT_RACK_STYLE } from '@/rack/rackDefaults'+import { RACK_COLUMNS } from '@/types'import type { Cable, Rack, RackDevice } from '@/types'const apiRack: ApiRack = {@@ -222,7 +223,17 @@ describe('domain → API', () => {const device = { ...toRackDevice(apiDevice), colStart: 99, colSpan: 99 }const back = fromRackDevice(device)expect(back.col_start).toBe(11)- expect(back.col_span).toBe(12)+ // Clamped against the start, not the grid alone: 11 + 12 would span to+ // column 23 of 12 and the backend 422s the whole save over it.+ expect(back.col_span).toBe(1)+ expect(back.col_start + back.col_span).toBeLessThanOrEqual(RACK_COLUMNS)+ })++ it('keeps a legal column run untouched', () => {+ const device = { ...toRackDevice(apiDevice), colStart: 6, colSpan: 6 }+ const back = fromRackDevice(device)+ expect(back.col_start).toBe(6)+ expect(back.col_span).toBe(6)})})diff --git a/frontend/src/utils/rackSerializer.ts b/frontend/src/utils/rackSerializer.tsindex fd10884..1028cc5 100644--- a/frontend/src/utils/rackSerializer.ts+++ b/frontend/src/utils/rackSerializer.ts@@ -259,6 +259,7 @@ export function fromRack(rack: Rack): Omit<ApiRack, 'design_id'> {}export function fromRackDevice(device: RackDevice): Omit<ApiRackDevice, 'design_id'> {+ const colStart = Math.min(Math.max(device.colStart, 0), RACK_COLUMNS - 1)return {id: device.id,rack_id: device.rackId,@@ -267,8 +268,11 @@ export function fromRackDevice(device: RackDevice): Omit<ApiRackDevice, 'design_label: device.label,u_start: device.uStart,u_height: device.uHeight,- col_start: Math.min(Math.max(device.colStart, 0), RACK_COLUMNS - 1),- col_span: Math.min(Math.max(device.colSpan, 1), RACK_COLUMNS),+ col_start: colStart,+ // Clamped against the start, not against the grid on its own: 11 + 12 is+ // two legal fields adding up to column 23 of 12, which the backend now+ // rejects — the whole save 422s over one device.+ col_span: Math.min(Math.max(device.colSpan, 1), RACK_COLUMNS - colStart),faceplate_id: device.faceplateId,color: device.color ?? null,status: device.status,