Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(rack): front-only rack canvas prototype at /racklab
Pouzor33df37b6918c
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex ad53488..90b05e1 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -3,11 +3,14 @@ import { createRoot } from 'react-dom/client'import './index.css'import App from './App.tsx'import LiveView from './components/LiveView.tsx'+import RackLab from './rack/components/RackLab.tsx'const isLiveView = window.location.pathname === '/view'+// Front-only rack canvas prototype — no backend, no persistence.+const isRackLab = window.location.pathname === '/racklab'createRoot(document.getElementById('root')!).render(<StrictMode>- {isLiveView ? <LiveView /> : <App />}+ {isLiveView ? <LiveView /> : isRackLab ? <RackLab /> : <App />}</StrictMode>,)diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdnew file mode 100644index 0000000..343b0ba--- /dev/null+++ b/frontend/src/rack/README.md@@ -0,0 +1,40 @@+# Rack canvas — UX prototype++Front-only. No API, no persistence, no backend enum changes. Open **`/racklab`**+(`npm run dev` → http://localhost:5173/racklab).++Isolated on purpose: `main.tsx` routes `/racklab` the same way it already routes+`/view`, so nothing here touches the logical canvas. Once the UX is settled, the+model in `types.ts` is what gets lifted into `@/types` + a `design_type: 'rack'`.++## Model++| Concern | Choice |+|---|---|+| Vertical | `uStart` (1-based, **always counted from the bottom rail**) + `uHeight`. `numbering` only changes the printed labels. |+| Horizontal | 12-column grid (`RACK_COLUMNS`). Full = 12, half = 6, third = 4, quarter = 3 — so 2 or 3 machines share one U. |+| Collision | `canPlace` / `findSlot` in `layout.ts`. A drop snaps to the nearest free slot; an impossible drop shows a red preview. |+| Inventory | A mount references an inventory id. **Unmounting never deletes the inventory entry** — same rule as the network canvas. Accessories (blank, shelf, cable manager) have `nodeId: null`. |+| Faceplates | Declarative templates in `faceplates.ts`, drawn as SVG in unit coordinates so a plate scales with U height and rack width. Applying a template seeds ports; the user edits them afterwards. |+| Ports | RJ45 and SFP/SFP+ only, drawn as real jack artwork at a fixed pixel size so plates of different U heights line up. Manual list per device; position is unit coordinates on the plate. Power outlets are artwork, never a cable endpoint. |+| Port visibility | Patch-facing gear (switches, patch panels) shows its ports permanently. Everything else reveals them on hover, on selection, or when cables are on — a cable never ends on an invisible port. |+| Plate zones | Each template reserves three non-overlapping bands: status LED (fixed left), `labelBox` (name, clipped), then artwork and ports. A test asserts no port lands on the name band. |+| Cables | Port-to-port, a relation of their own — not React Flow edges. One cable per port. Drawn in a `ViewportPortal` so they pan/zoom with the canvas and can cross racks. |+| Cable visibility | Hidden by default; shown on hover/selection, or all-on via patch mode / the toolbar. Plates fade to 40 % when cables are on, which is the "transparency" ask. Copper vs fibre follows the port the patch starts from. |+| Network import | `importCablesFromNetwork()` — one shot, at creation time only, guarded by `networkImportDone`. Fed by `networkEdgeHints()` (fake here; would read the network design's edges for real). |++## Interactions++- Drag from the left tray onto a rack → snaps to a free U.+- Drag a mounted device inside the rack → same snapping, own slot ignored.+- Click a device → inspector on the right (label, faceplate, U/height/column/width, status, colour, port list).+- Click empty rack chrome → rack settings (name, location, U height, 19"/10", numbering direction, frame/rail/interior colours, U numbers, enclosed).+- **Patch mode**: click port A then port B to cable them; click a cable to remove it. Rack dragging is disabled while in patch mode.++## Known gaps (deliberate, for the UX pass)++- Front view only — no rear, no half-depth pairing.+- No 0U side-mounted PDU.+- Power draw / outlet budgeting out of scope (v1 decision).+- No export yet (PNG/SVG comes with integration).+- Demo state resets on reload; `Reset demo` restores it mid-session.diff --git a/frontend/src/rack/__tests__/faceplates.test.ts b/frontend/src/rack/__tests__/faceplates.test.tsnew file mode 100644index 0000000..972876f--- /dev/null+++ b/frontend/src/rack/__tests__/faceplates.test.ts@@ -0,0 +1,121 @@+import { describe, it, expect } from 'vitest'+import { FACEPLATES, bank, faceplateGroups, getFaceplate } from '../faceplates'+import { RACK_COLUMNS, type PortType } from '../types'++const ALLOWED_PORT_TYPES: PortType[] = ['rj45', 'sfp', 'sfp+']++describe('faceplate catalog', () => {+ it('has unique ids', () => {+ expect(new Set(FACEPLATES.map((f) => f.id)).size).toBe(FACEPLATES.length)+ })++ it('keeps every plate inside the rack grid', () => {+ for (const plate of FACEPLATES) {+ expect(plate.colSpan).toBeGreaterThan(0)+ expect(plate.colSpan).toBeLessThanOrEqual(RACK_COLUMNS)+ expect(plate.uHeight).toBeGreaterThan(0)+ }+ })++ it('only uses data port types', () => {+ for (const plate of FACEPLATES) {+ for (const port of plate.ports) {+ expect(ALLOWED_PORT_TYPES).toContain(port.type)+ }+ }+ })++ it('keeps every port inside the plate', () => {+ for (const plate of FACEPLATES) {+ for (const port of plate.ports) {+ expect(port.x).toBeGreaterThanOrEqual(0)+ expect(port.x).toBeLessThanOrEqual(1)+ expect(port.y).toBeGreaterThanOrEqual(0)+ expect(port.y).toBeLessThanOrEqual(1)+ }+ }+ })++ it('keeps ports clear of the name band', () => {+ for (const plate of FACEPLATES) {+ const labelEnd = plate.labelBox.x + plate.labelBox.w+ for (const port of plate.ports) {+ expect(+ port.x >= labelEnd || port.x <= plate.labelBox.x,+ `${plate.id}: port ${port.label} sits on the label`,+ ).toBe(true)+ }+ }+ })++ it('keeps the name band clear of the status LED and inside the plate', () => {+ for (const plate of FACEPLATES) {+ expect(plate.labelBox.x).toBeGreaterThan(0)+ expect(plate.labelBox.x + plate.labelBox.w).toBeLessThanOrEqual(1)+ }+ })++ it('gives accessories no ports and no status LED', () => {+ for (const plate of FACEPLATES.filter((f) => f.kind === 'accessory')) {+ expect(plate.ports).toHaveLength(0)+ expect(plate.statusLed).toBeFalsy()+ }+ })++ it('shows ports permanently only on patch-facing gear', () => {+ const always = FACEPLATES.filter((f) => f.alwaysShowPorts).map((f) => f.id)+ expect(always).toEqual([+ 'switch-8',+ 'switch-24',+ 'switch-48',+ 'patch-24',+ 'patch-fiber-12',+ ])+ })++ it('leaves power gear uncabled, with outlets as artwork', () => {+ for (const id of ['pdu-1u', 'ups-2u']) {+ const plate = getFaceplate(id)+ expect(plate.ports).toHaveLength(0)+ expect(plate.elements.some((e) => e.kind === 'outlets')).toBe(true)+ }+ })++ it('falls back to the first plate on an unknown id', () => {+ expect(getFaceplate('does-not-exist')).toBe(FACEPLATES[0])+ })++ it('groups the picker without losing a plate', () => {+ const groups = faceplateGroups()+ expect(groups.flatMap((g) => g.items)).toHaveLength(FACEPLATES.length)+ expect(new Set(groups.map((g) => g.group)).size).toBe(groups.length)+ })+})++describe('bank', () => {+ it('centres a single row vertically', () => {+ const ports = bank({ type: 'rj45', count: 4, x: 0, w: 1 })+ expect(ports).toHaveLength(4)+ expect(ports.map((p) => p.x)).toEqual([0.125, 0.375, 0.625, 0.875])+ expect(ports.every((p) => p.y === 0.5)).toBe(true)+ })++ it('spreads two rows evenly around the centre', () => {+ const ports = bank({ type: 'rj45', count: 24, x: 0, w: 1, perRow: 12 })+ const rows = [...new Set(ports.map((p) => p.y))]+ expect(rows).toEqual([1 / 3, 2 / 3])+ expect(ports[0].y).toBeLessThan(ports[12].y)+ })++ it('aligns columns across rows', () => {+ const ports = bank({ type: 'rj45', count: 24, x: 0, w: 1, perRow: 12 })+ for (let i = 0; i < 12; i++) {+ expect(ports[i].x).toBe(ports[i + 12].x)+ }+ })++ it('numbers ports from the given start', () => {+ const ports = bank({ type: 'sfp+', count: 2, x: 0, w: 1, prefix: 'sfp', start: 3 })+ expect(ports.map((p) => p.label)).toEqual(['sfp3', 'sfp4'])+ })+})diff --git a/frontend/src/rack/__tests__/layout.test.ts b/frontend/src/rack/__tests__/layout.test.tsnew file mode 100644index 0000000..44b1979--- /dev/null+++ b/frontend/src/rack/__tests__/layout.test.ts@@ -0,0 +1,231 @@+import { describe, it, expect } from 'vitest'+import {+ FRAME_PAD_PX,+ INTERIOR_TOP_PX,+ U_PX,+ canPlace,+ columnWidth,+ deviceBox,+ findSlot,+ freeUnits,+ isInBounds,+ portPosition,+ rackHeight,+ rackWidth,+ uLabel,+ uToY,+ xToCol,+ yToU,+} from '../layout'+import { DEFAULT_RACK_STYLE } from '../rackDefaults'+import { RACK_COLUMNS, type Port, type Rack, type RackDevice } from '../types'++function makeRack(patch: Partial<Rack> = {}): Rack {+ return {+ id: 'r1',+ name: 'Rack',+ uHeight: 10,+ widthStandard: '19',+ numbering: 'bottom-up',+ style: { ...DEFAULT_RACK_STYLE },+ position: { x: 0, y: 0 },+ ...patch,+ }+}++function makeDevice(patch: Partial<RackDevice> = {}): RackDevice {+ return {+ id: 'd1',+ rackId: 'r1',+ nodeId: null,+ label: 'dev',+ uStart: 1,+ uHeight: 1,+ colStart: 0,+ colSpan: RACK_COLUMNS,+ faceplateId: 'blank-1u',+ status: 'unknown',+ ports: [],+ ...patch,+ }+}++describe('rack geometry', () => {+ it('places the top U at the top of the frame', () => {+ const rack = makeRack()+ expect(uToY(rack, rack.uHeight, 1)).toBe(INTERIOR_TOP_PX)+ expect(uToY(rack, 1, 1)).toBe(INTERIOR_TOP_PX + (rack.uHeight - 1) * U_PX)+ })++ it('anchors a multi-U device by its lowest U', () => {+ const rack = makeRack()+ // A 2U device starting at U5 occupies U5+U6, so its top edge sits at U6.+ expect(uToY(rack, 5, 2)).toBe(uToY(rack, 6, 1))+ })++ it('round-trips y -> U for every unit', () => {+ const rack = makeRack()+ for (let u = 1; u <= rack.uHeight; u++) {+ expect(yToU(rack, uToY(rack, u, 1) + U_PX / 2)).toBe(u)+ }+ })++ it('clamps out-of-frame pointers into the rack', () => {+ const rack = makeRack()+ expect(yToU(rack, -500)).toBe(rack.uHeight)+ expect(yToU(rack, 5000)).toBe(1)+ })++ it('maps x to a column and clamps at both edges', () => {+ const rack = makeRack()+ expect(xToCol(rack, -100)).toBe(0)+ expect(xToCol(rack, 1e6)).toBe(RACK_COLUMNS - 1)+ const col = columnWidth(rack)+ expect(xToCol(rack, deviceBox(rack, makeDevice()).x + col * 3.5)).toBe(3)+ })++ it('labels U according to the numbering direction', () => {+ const bottomUp = makeRack()+ const topDown = makeRack({ numbering: 'top-down' })+ expect(uLabel(bottomUp, 1)).toBe(1)+ expect(uLabel(bottomUp, 10)).toBe(10)+ expect(uLabel(topDown, 1)).toBe(10)+ expect(uLabel(topDown, 10)).toBe(1)+ })++ it('sizes the node from U height and width standard', () => {+ expect(rackHeight(makeRack({ uHeight: 24 }))).toBe(24 * U_PX + INTERIOR_TOP_PX + FRAME_PAD_PX)+ expect(rackWidth(makeRack({ widthStandard: '10' }))).toBeLessThan(+ rackWidth(makeRack({ widthStandard: '19' })),+ )+ })++ it('drops the number gutter when numbers are hidden', () => {+ const shown = makeRack()+ const hidden = makeRack({ style: { ...DEFAULT_RACK_STYLE, showNumbers: false } })+ expect(rackWidth(hidden)).toBeLessThan(rackWidth(shown))+ })++ it('projects a port into canvas space, rack offset included', () => {+ const rack = makeRack({ position: { x: 100, y: 50 } })+ const device = makeDevice({ uStart: 1, uHeight: 1, colStart: 0, colSpan: RACK_COLUMNS })+ const port: Port = { id: 'p', label: 'p', type: 'rj45', x: 0.5, y: 0.5 }+ const box = deviceBox(rack, device)+ expect(portPosition(rack, device, port)).toEqual({+ x: 100 + box.x + box.width / 2,+ y: 50 + box.y + box.height / 2,+ })+ })+})++describe('occupancy', () => {+ it('rejects placements outside the rack', () => {+ const rack = makeRack()+ expect(isInBounds(rack, { uStart: 0, uHeight: 1, colStart: 0, colSpan: 12 })).toBe(false)+ expect(isInBounds(rack, { uStart: 10, uHeight: 2, colStart: 0, colSpan: 12 })).toBe(false)+ expect(isInBounds(rack, { uStart: 1, uHeight: 1, colStart: 6, colSpan: 12 })).toBe(false)+ expect(isInBounds(rack, { uStart: 9, uHeight: 2, colStart: 0, colSpan: 12 })).toBe(true)+ })++ it('detects a full-width collision', () => {+ const rack = makeRack()+ const devices = [makeDevice({ uStart: 3 })]+ expect(canPlace(rack, devices, { uStart: 3, uHeight: 1, colStart: 0, colSpan: 12 })).toBe(false)+ })++ it('lets two half-width devices share one U', () => {+ const rack = makeRack()+ const devices = [makeDevice({ uStart: 3, colStart: 0, colSpan: 6 })]+ expect(canPlace(rack, devices, { uStart: 3, uHeight: 1, colStart: 6, colSpan: 6 })).toBe(true)+ expect(canPlace(rack, devices, { uStart: 3, uHeight: 1, colStart: 4, colSpan: 6 })).toBe(false)+ })++ it('lets three third-width devices share one U', () => {+ const rack = makeRack()+ const devices = [+ makeDevice({ id: 'a', uStart: 2, colStart: 0, colSpan: 4 }),+ makeDevice({ id: 'b', uStart: 2, colStart: 4, colSpan: 4 }),+ ]+ expect(canPlace(rack, devices, { uStart: 2, uHeight: 1, colStart: 8, colSpan: 4 })).toBe(true)+ })++ it('catches a multi-U overlap from either direction', () => {+ const rack = makeRack()+ const devices = [makeDevice({ uStart: 4, uHeight: 3 })] // U4..U6+ expect(canPlace(rack, devices, { uStart: 6, uHeight: 2, colStart: 0, colSpan: 12 })).toBe(false)+ expect(canPlace(rack, devices, { uStart: 2, uHeight: 3, colStart: 0, colSpan: 12 })).toBe(false)+ expect(canPlace(rack, devices, { uStart: 7, uHeight: 2, colStart: 0, colSpan: 12 })).toBe(true)+ })++ it('ignores the device being moved so a no-op drag stays valid', () => {+ const rack = makeRack()+ const devices = [makeDevice({ id: 'd1', uStart: 5 })]+ expect(canPlace(rack, devices, { uStart: 5, uHeight: 1, colStart: 0, colSpan: 12 })).toBe(false)+ expect(canPlace(rack, devices, { uStart: 5, uHeight: 1, colStart: 0, colSpan: 12 }, 'd1')).toBe(+ true,+ )+ })++ it('ignores devices mounted in another rack', () => {+ const rack = makeRack()+ const devices = [makeDevice({ rackId: 'other', uStart: 5 })]+ expect(canPlace(rack, devices, { uStart: 5, uHeight: 1, colStart: 0, colSpan: 12 })).toBe(true)+ })+})++describe('findSlot', () => {+ it('keeps the requested U when it is free', () => {+ const rack = makeRack()+ const slot = findSlot(rack, [], { uStart: 4, uHeight: 2, colStart: 0, colSpan: 12 })+ expect(slot).toEqual({ uStart: 4, uHeight: 2, colStart: 0, colSpan: 12 })+ })++ it('slides to a free U when the target is taken', () => {+ const rack = makeRack()+ const devices = [makeDevice({ uStart: 4 })]+ const slot = findSlot(rack, devices, { uStart: 4, uHeight: 1, colStart: 0, colSpan: 12 })+ expect(slot).not.toBeNull()+ expect(slot!.uStart).not.toBe(4)+ })++ it('uses free columns on the target U before moving away', () => {+ const rack = makeRack()+ const devices = [makeDevice({ uStart: 4, colStart: 0, colSpan: 6 })]+ const slot = findSlot(rack, devices, { uStart: 4, uHeight: 1, colStart: 7, colSpan: 6 })+ expect(slot).toEqual({ uStart: 4, uHeight: 1, colStart: 6, colSpan: 6 })+ })++ it('clamps a request that would overflow the top', () => {+ const rack = makeRack()+ const slot = findSlot(rack, [], { uStart: 10, uHeight: 3, colStart: 0, colSpan: 12 })+ expect(slot!.uStart).toBe(8)+ })++ it('returns null when the device is taller than the rack', () => {+ const rack = makeRack({ uHeight: 2 })+ expect(findSlot(rack, [], { uStart: 1, uHeight: 4, colStart: 0, colSpan: 12 })).toBeNull()+ })++ it('returns null when the rack is full', () => {+ const rack = makeRack({ uHeight: 2 })+ const devices = [+ makeDevice({ id: 'a', uStart: 1 }),+ makeDevice({ id: 'b', uStart: 2 }),+ ]+ expect(findSlot(rack, devices, { uStart: 1, uHeight: 1, colStart: 0, colSpan: 12 })).toBeNull()+ })+})++describe('freeUnits', () => {+ it('counts a partially filled U as busy', () => {+ const rack = makeRack({ uHeight: 4 })+ const devices = [makeDevice({ uStart: 2, colStart: 0, colSpan: 6 })]+ expect(freeUnits(rack, devices)).toBe(3)+ })++ it('counts multi-U devices once per occupied U', () => {+ const rack = makeRack({ uHeight: 4 })+ const devices = [makeDevice({ uStart: 1, uHeight: 3 })]+ expect(freeUnits(rack, devices)).toBe(1)+ })+})diff --git a/frontend/src/rack/__tests__/store.test.ts b/frontend/src/rack/__tests__/store.test.tsnew file mode 100644index 0000000..45b9cf6--- /dev/null+++ b/frontend/src/rack/__tests__/store.test.ts@@ -0,0 +1,263 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useRackStore } from '../store'+import { getFaceplate } from '../faceplates'+import { RACK_COLUMNS } from '../types'++const store = () => useRackStore.getState()++beforeEach(() => {+ useRackStore.getState().reset()+})++describe('racks', () => {+ it('boots with the demo rack and its mounted gear', () => {+ expect(store().racks).toHaveLength(1)+ expect(store().devices.length).toBeGreaterThan(0)+ expect(store().cables.length).toBeGreaterThan(0)+ })++ it('adds a rack and selects it', () => {+ const id = store().addRack()+ expect(store().racks).toHaveLength(2)+ expect(store().selectedRackId).toBe(id)+ })++ it('deletes a rack with its devices and their cables', () => {+ store().removeRack('rack-main')+ expect(store().racks).toHaveLength(0)+ expect(store().devices).toHaveLength(0)+ expect(store().cables).toHaveLength(0)+ })++ it('patches style without dropping the other style keys', () => {+ store().updateRackStyle('rack-main', { showNumbers: false })+ const style = store().racks[0].style+ expect(style.showNumbers).toBe(false)+ expect(style.frame).toBeTruthy()+ })+})++describe('mounting', () => {+ it('mounts an inventory item using its suggested faceplate', () => {+ const id = store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 5 })+ expect(id).not.toBeNull()+ const device = store().devices.find((d) => d.id === id)!+ expect(device.faceplateId).toBe('switch-8')+ expect(device.nodeId).toBe('inv-sw8')+ expect(device.ports.length).toBe(getFaceplate('switch-8').ports.length)+ })++ it('gives every mounted port a distinct id', () => {+ const id = store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 5 })!+ const ports = store().devices.find((d) => d.id === id)!.ports+ expect(new Set(ports.map((p) => p.id)).size).toBe(ports.length)+ })++ it('slides a drop onto an occupied U to a free one', () => {+ const taken = store().devices.find((d) => d.id === 'dev-sw24')!+ const id = store().mountFromInventory('inv-sw8', 'rack-main', { uStart: taken.uStart })!+ expect(store().devices.find((d) => d.id === id)!.uStart).not.toBe(taken.uStart)+ })++ it('returns null when the rack has no room', () => {+ const rackId = store().addRack({ uHeight: 1 })+ store().mountAccessory('blank-1u', rackId, { uStart: 1 })+ expect(store().mountAccessory('blank-1u', rackId, { uStart: 1 })).toBeNull()+ })++ it('mounts an accessory with no inventory link', () => {+ const id = store().mountAccessory('shelf-1u', 'rack-main', { uStart: 6 })!+ expect(store().devices.find((d) => d.id === id)!.nodeId).toBeNull()+ })++ it('keeps the inventory entry when a device is unmounted', () => {+ const before = store().inventory.length+ store().unmountDevice('dev-pve1')+ expect(store().devices.find((d) => d.id === 'dev-pve1')).toBeUndefined()+ expect(store().inventory).toHaveLength(before)+ expect(store().inventory.some((i) => i.id === 'inv-pve1')).toBe(true)+ })++ it('drops the cables of an unmounted device', () => {+ const had = store().cables.some(+ (c) => c.from.deviceId === 'dev-nas' || c.to.deviceId === 'dev-nas',+ )+ expect(had).toBe(true)+ store().unmountDevice('dev-nas')+ expect(+ store().cables.some((c) => c.from.deviceId === 'dev-nas' || c.to.deviceId === 'dev-nas'),+ ).toBe(false)+ })+})++describe('moving and resizing', () => {+ it('refuses a move onto an occupied slot', () => {+ const target = store().devices.find((d) => d.id === 'dev-sw24')!+ const ok = store().moveDevice('dev-fw', 'rack-main', {+ uStart: target.uStart,+ uHeight: 1,+ colStart: 0,+ colSpan: RACK_COLUMNS,+ })+ expect(ok).toBe(false)+ expect(store().devices.find((d) => d.id === 'dev-fw')!.uStart).toBe(15)+ })++ it('accepts a move onto a free slot', () => {+ const ok = store().moveDevice('dev-fw', 'rack-main', {+ uStart: 5,+ uHeight: 1,+ colStart: 0,+ colSpan: RACK_COLUMNS,+ })+ expect(ok).toBe(true)+ expect(store().devices.find((d) => d.id === 'dev-fw')!.uStart).toBe(5)+ })++ it('ignores a geometry edit that would collide', () => {+ // dev-pve1 is 2U at U11; growing it to 4U would run into dev-fw territory.+ store().updateDevice('dev-pve1', { uHeight: 5 })+ expect(store().devices.find((d) => d.id === 'dev-pve1')!.uHeight).toBe(2)+ })++ it('applies a non-geometry edit even in a tight rack', () => {+ store().updateDevice('dev-pve1', { label: 'renamed' })+ expect(store().devices.find((d) => d.id === 'dev-pve1')!.label).toBe('renamed')+ })++ it('resizes to the new faceplate when it fits', () => {+ store().updateDevice('dev-blank', { label: 'slot' })+ store().applyFaceplate('dev-pve2', 'server-1u')+ const device = store().devices.find((d) => d.id === 'dev-pve2')!+ expect(device.faceplateId).toBe('server-1u')+ expect(device.uHeight).toBe(1)+ })++ it('keeps the old geometry when the new faceplate does not fit', () => {+ store().applyFaceplate('dev-sw24', 'server-4u-storage')+ const device = store().devices.find((d) => d.id === 'dev-sw24')!+ expect(device.faceplateId).toBe('server-4u-storage')+ expect(device.uHeight).toBe(1)+ })+})++describe('ports', () => {+ it('adds and removes a port', () => {+ const before = store().devices.find((d) => d.id === 'dev-pve1')!.ports.length+ store().addPort('dev-pve1', { label: 'ipmi', type: 'rj45', x: 0.5, y: 0.5 })+ const ports = store().devices.find((d) => d.id === 'dev-pve1')!.ports+ expect(ports).toHaveLength(before + 1)+ store().removePort('dev-pve1', ports[ports.length - 1].id)+ expect(store().devices.find((d) => d.id === 'dev-pve1')!.ports).toHaveLength(before)+ })++ it('removes the cable attached to a deleted port', () => {+ const cable = store().cables[0]+ store().removePort(cable.from.deviceId, cable.from.portId)+ expect(store().cables.find((c) => c.id === cable.id)).toBeUndefined()+ })++ it('renames a port in place', () => {+ const port = store().devices.find((d) => d.id === 'dev-pve1')!.ports[0]+ store().updatePort('dev-pve1', port.id, { label: 'wan' })+ expect(store().devices.find((d) => d.id === 'dev-pve1')!.ports[0].label).toBe('wan')+ })+})++describe('cables', () => {+ const freePorts = () => {+ const used = new Set(+ store().cables.flatMap((c) => [+ `${c.from.deviceId}:${c.from.portId}`,+ `${c.to.deviceId}:${c.to.portId}`,+ ]),+ )+ const pick = (deviceId: string) => {+ const device = store().devices.find((d) => d.id === deviceId)!+ const port = device.ports.find((p) => !used.has(`${deviceId}:${p.id}`))!+ return { deviceId, portId: port.id }+ }+ return { a: pick('dev-sw24'), b: pick('dev-pve1') }+ }++ it('creates a cable between two free ports', () => {+ const { a, b } = freePorts()+ const id = store().addCable(a, b)+ expect(id).not.toBeNull()+ expect(store().cables.find((c) => c.id === id)!.color).toBeTruthy()+ })++ it('infers the cable type from the port it starts on', () => {+ const sw = store().devices.find((d) => d.id === 'dev-sw24')!+ const nas = store().devices.find((d) => d.id === 'dev-nas')!+ const freeOf = (deviceId: string, type: string) => {+ const patched = new Set(store().cables.flatMap((c) => [c.from.portId, c.to.portId]))+ const device = store().devices.find((d) => d.id === deviceId)!+ return device.ports.find((p) => p.type === type && !patched.has(p.id))!+ }++ const copper = store().addCable(+ { deviceId: sw.id, portId: freeOf(sw.id, 'rj45').id },+ { deviceId: nas.id, portId: freeOf(nas.id, 'rj45').id },+ )+ expect(store().cables.find((c) => c.id === copper)!.type).toBe('ethernet')++ const fiber = store().addCable(+ { deviceId: sw.id, portId: freeOf(sw.id, 'sfp+').id },+ { deviceId: nas.id, portId: freeOf(nas.id, 'rj45').id },+ )+ expect(store().cables.find((c) => c.id === fiber)!.type).toBe('fiber')+ })++ it('refuses a second cable on an already patched port', () => {+ const existing = store().cables[0]+ const { b } = freePorts()+ expect(store().addCable(existing.from, b)).toBeNull()+ })++ it('refuses a port patched to itself', () => {+ const { a } = freePorts()+ expect(store().addCable(a, a)).toBeNull()+ })++ it('refuses an unknown port', () => {+ const { a } = freePorts()+ expect(store().addCable(a, { deviceId: 'dev-pve1', portId: 'nope' })).toBeNull()+ })++ it('builds a cable across two clicks in patch mode', () => {+ const { a, b } = freePorts()+ const before = store().cables.length+ store().pickPort(a.deviceId, a.portId)+ expect(store().cableDraft).toEqual(a)+ store().pickPort(b.deviceId, b.portId)+ expect(store().cableDraft).toBeNull()+ expect(store().cables).toHaveLength(before + 1)+ })++ it('turns cables on when entering patch mode', () => {+ expect(store().cableVisibility).toBe('hover')+ store().toggleCableMode()+ expect(store().cableMode).toBe(true)+ expect(store().cableVisibility).toBe('always')+ })++ it('imports links from the network canvas once', () => {+ // Mount the two inventory items the hints reference.+ store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 4 })+ const first = store().importCablesFromNetwork()+ expect(first).toBeGreaterThan(0)+ expect(store().importCablesFromNetwork()).toBe(0)+ })++ it('skips hints whose devices are not racked', () => {+ // inv-jbod is never mounted in the demo, so its hint cannot resolve.+ store().importCablesFromNetwork()+ expect(+ store().cables.some((c) => {+ const from = store().devices.find((d) => d.id === c.from.deviceId)+ return from?.nodeId === 'inv-jbod'+ }),+ ).toBe(false)+ })+})diff --git a/frontend/src/rack/components/CableLayer.tsx b/frontend/src/rack/components/CableLayer.tsxnew file mode 100644index 0000000..e2b5e38--- /dev/null+++ b/frontend/src/rack/components/CableLayer.tsx@@ -0,0 +1,115 @@+/**+ * Port-to-port cabling, drawn in canvas space above the racks.+ *+ * Lives in a ViewportPortal so the paths pan and zoom with the flow without+ * being React Flow edges — rack cables are a physical relation, not a logical+ * one, and they attach to ports rather than to node handles.+ */+import { ViewportPortal } from '@xyflow/react'+import { portPosition } from '../layout'+import { useRackStore } from '../store'+import type { Cable, Port, Rack, RackDevice } from '../types'++interface Resolved {+ cable: Cable+ from: { x: number; y: number }+ to: { x: number; y: number }+}++/** Slack loop: cables bulge out sideways, more so over long vertical runs. */+function cablePath(a: { x: number; y: number }, b: { x: number; y: number }): string {+ const dy = Math.abs(b.y - a.y)+ const bulge = Math.min(90, 18 + dy * 0.45)+ return `M ${a.x} ${a.y} C ${a.x + bulge} ${a.y + bulge * 0.4}, ${b.x + bulge} ${b.y + bulge * 0.4}, ${b.x} ${b.y}`+}++export function CableLayer() {+ const racks = useRackStore((s) => s.racks)+ const devices = useRackStore((s) => s.devices)+ const cables = useRackStore((s) => s.cables)+ const visibility = useRackStore((s) => s.cableVisibility)+ const typeFilter = useRackStore((s) => s.cableTypeFilter)+ const hoveredDeviceId = useRackStore((s) => s.hoveredDeviceId)+ const selectedDeviceId = useRackStore((s) => s.selectedDeviceId)+ const cableMode = useRackStore((s) => s.cableMode)+ const removeCable = useRackStore((s) => s.removeCable)++ if (visibility === 'hidden' && !cableMode) return null++ const rackById = new Map<string, Rack>(racks.map((r) => [r.id, r]))+ const deviceById = new Map<string, RackDevice>(devices.map((d) => [d.id, d]))++ const focus = hoveredDeviceId ?? selectedDeviceId+ const showAll = cableMode || visibility === 'always'++ const resolve = (deviceId: string, portId: string) => {+ const device = deviceById.get(deviceId)+ const rack = device && rackById.get(device.rackId)+ const port: Port | undefined = device?.ports.find((p) => p.id === portId)+ if (!device || !rack || !port) return null+ return portPosition(rack, device, port)+ }++ const visible: Resolved[] = []+ for (const cable of cables) {+ if (typeFilter !== 'all' && cable.type !== typeFilter) continue+ if (!showAll) {+ if (!focus) continue+ if (cable.from.deviceId !== focus && cable.to.deviceId !== focus) continue+ }+ const from = resolve(cable.from.deviceId, cable.from.portId)+ const to = resolve(cable.to.deviceId, cable.to.portId)+ if (!from || !to) continue+ visible.push({ cable, from, to })+ }++ if (visible.length === 0) return null++ return (+ <ViewportPortal>+ <svg+ style={{+ position: 'absolute',+ left: 0,+ top: 0,+ width: 1,+ height: 1,+ overflow: 'visible',+ pointerEvents: 'none',+ zIndex: 5,+ }}+ >+ {visible.map(({ cable, from, to }) => {+ const dimmed = focus != null && cable.from.deviceId !== focus && cable.to.deviceId !== focus+ return (+ <g key={cable.id} opacity={dimmed ? 0.28 : 1}>+ <path+ d={cablePath(from, to)}+ fill="none"+ stroke="#0d1117"+ strokeWidth={3.5}+ strokeLinecap="round"+ />+ <path+ d={cablePath(from, to)}+ fill="none"+ stroke={cable.color}+ strokeWidth={1.8}+ strokeLinecap="round"+ style={{ pointerEvents: cableMode ? 'stroke' : 'none', cursor: cableMode ? 'pointer' : undefined }}+ onClick={() => cableMode && removeCable(cable.id)}+ >+ <title>+ {cable.label ? `${cable.label} — ${cable.type}` : cable.type}+ {cableMode ? ' (click to remove)' : ''}+ </title>+ </path>+ <circle cx={from.x} cy={from.y} r={2.2} fill={cable.color} />+ <circle cx={to.x} cy={to.y} r={2.2} fill={cable.color} />+ </g>+ )+ })}+ </svg>+ </ViewportPortal>+ )+}diff --git a/frontend/src/rack/components/Faceplate.tsx b/frontend/src/rack/components/Faceplate.tsxnew file mode 100644index 0000000..62d80ab--- /dev/null+++ b/frontend/src/rack/components/Faceplate.tsx@@ -0,0 +1,316 @@+/**+ * Draws a device front panel from its template.+ *+ * Layout is pixel-based on purpose: the status LED, the name band and the port+ * artwork all keep a fixed size whatever the U height, so plates of different+ * heights line up with each other instead of scaling apart.+ */+import { memo, useId } from 'react'+import { getFaceplate } from '../faceplates'+import type { DeviceStatus, FaceplateElement, Port, PortType } from '../types'++const STATUS_COLOR: Record<DeviceStatus, string> = {+ online: '#39d353',+ offline: '#f85149',+ unknown: '#8b949e',+}++/** Unpatched port artwork — a dark recess with a metal bezel. */+const PORT_BEZEL = '#5b6673'+const PORT_RECESS = '#0b0e13'++const LED_X = 9+const LED_R = 3++interface PortShapeSize {+ w: number+ h: number+}++/** Fixed-ish port artwork, nudged by plate height so 1U panels stay legible. */+function portShapeSize(size: 'sm' | 'md', height: number, type: PortType): PortShapeSize {+ const w =+ size === 'sm'+ ? Math.max(5, Math.min(8, height * 0.3))+ : Math.max(7, Math.min(12, height * 0.42))+ return type === 'rj45' ? { w, h: w * 0.92 } : { w: w * 1.15, h: w * 0.62 }+}++/** RJ45 silhouette: body with the latch slot cut into the top, centred on (0,0). */+function rj45Path(w: number, h: number): string {+ const left = -w / 2+ const top = -h / 2+ const notchW = w * 0.4+ const notchH = h * 0.4+ const shoulder = (w - notchW) / 2+ return [+ `M ${left} ${top + notchH}`,+ `h ${shoulder}`,+ `v ${-notchH}`,+ `h ${notchW}`,+ `v ${notchH}`,+ `h ${shoulder}`,+ `v ${h - notchH}`,+ `h ${-w}`,+ `Z`,+ ].join(' ')+}++function drawElement(el: FaceplateElement, i: number, w: number, h: number) {+ switch (el.kind) {+ case 'panel':+ return null // drawn by the caller as the plate background+ case 'vents': {+ const cellW = (el.w * w) / el.cols+ const cellH = (el.h * h) / el.rows+ const cells = []+ for (let r = 0; r < el.rows; r++) {+ for (let c = 0; c < el.cols; c++) {+ cells.push(+ <rect+ key={`${i}-${r}-${c}`}+ x={el.x * w + c * cellW + cellW * 0.15}+ y={el.y * h + r * cellH + cellH * 0.15}+ width={Math.max(1, cellW * 0.7)}+ height={Math.max(1, cellH * 0.7)}+ rx={1}+ fill={el.fill ?? '#141922'}+ />,+ )+ }+ }+ return <g key={i}>{cells}</g>+ }+ case 'bays': {+ const cellW = (el.w * w) / el.cols+ const cellH = (el.h * h) / el.rows+ const cells = []+ for (let r = 0; r < el.rows; r++) {+ for (let c = 0; c < el.cols; c++) {+ cells.push(+ <rect+ key={`${i}-${r}-${c}`}+ x={el.x * w + c * cellW + 1}+ y={el.y * h + r * cellH + 1}+ width={Math.max(2, cellW - 2)}+ height={Math.max(2, cellH - 2)}+ rx={1.5}+ fill={el.fill ?? '#1b1f26'}+ stroke="#0d1117"+ strokeWidth={0.5}+ />,+ )+ }+ }+ return <g key={i}>{cells}</g>+ }+ case 'strip':+ return (+ <rect+ key={i}+ x={el.x * w}+ y={el.y * h}+ width={el.w * w}+ height={el.h * h}+ rx={2}+ fill={el.fill}+ />+ )+ case 'outlets': {+ // C13-style outlets: artwork only, never a cable endpoint.+ const slotW = (el.w * w) / el.count+ const outletW = Math.min(slotW * 0.72, el.h * h * 0.9)+ const outletH = Math.min(el.h * h, outletW * 0.85)+ const cy = el.y * h + (el.h * h) / 2+ return (+ <g key={i}>+ {Array.from({ length: el.count }, (_, n) => {+ const cx = el.x * w + slotW * (n + 0.5)+ const pinW = Math.max(0.8, outletW * 0.12)+ const pinH = Math.max(1, outletH * 0.3)+ return (+ <g key={n}>+ <rect+ x={cx - outletW / 2}+ y={cy - outletH / 2}+ width={outletW}+ height={outletH}+ rx={1.5}+ fill="#0b0e13"+ stroke="#4b535e"+ strokeWidth={0.8}+ />+ <rect x={cx - outletW * 0.26 - pinW / 2} y={cy - pinH / 2} width={pinW} height={pinH} fill="#4b535e" />+ <rect x={cx - pinW / 2} y={cy - pinH / 2} width={pinW} height={pinH} fill="#4b535e" />+ <rect x={cx + outletW * 0.26 - pinW / 2} y={cy - pinH / 2} width={pinW} height={pinH} fill="#4b535e" />+ </g>+ )+ })}+ </g>+ )+ }+ }+}++interface Props {+ faceplateId: string+ label: string+ status: DeviceStatus+ ports: Port[]+ /** Rendered size in canvas pixels. */+ width: number+ height: number+ colorOverride?: string+ selected?: boolean+ /** Hover or selection: reveals the ports of non-patch gear. */+ revealed?: boolean+ /** Fade the plate so cables behind it stay readable. */+ transparent?: boolean+ /** Ports are clickable (patch mode). */+ interactivePorts?: boolean+ /** Port id -> colour of the cable plugged into it. */+ patchedPorts?: Map<string, string>+ draftPortId?: string | null+ onPortClick?: (portId: string) => void+}++export const Faceplate = memo(function Faceplate({+ faceplateId,+ label,+ status,+ ports,+ width,+ height,+ colorOverride,+ selected,+ revealed,+ transparent,+ interactivePorts,+ patchedPorts,+ draftPortId,+ onPortClick,+}: Props) {+ const template = getFaceplate(faceplateId)+ const clipId = useId()+ const panel = template.elements.find((e) => e.kind === 'panel')+ const fill = colorOverride ?? (panel?.kind === 'panel' ? panel.fill : '#2b323c')++ const showPorts = template.alwaysShowPorts || revealed || interactivePorts++ const labelX = template.labelBox.x * width+ const labelW = template.labelBox.w * width+ const fontSize = Math.max(8, Math.min(11, height * 0.42))+ const showLabel = labelW > 24 && height >= 14++ return (+ <svg+ width={width}+ height={height}+ viewBox={`0 0 ${width} ${height}`}+ style={{ opacity: transparent ? 0.4 : 1, display: 'block' }}+ >+ <defs>+ <clipPath id={clipId}>+ <rect x={labelX} y={0} width={labelW} height={height} />+ </clipPath>+ </defs>++ <rect+ x={0.5}+ y={0.5}+ width={width - 1}+ height={height - 1}+ rx={2}+ fill={fill}+ stroke={selected ? '#00d4ff' : '#0d1117'}+ strokeWidth={selected ? 1.5 : 1}+ />++ {/* Mounting ears */}+ <rect x={1.5} y={height * 0.3} width={2.5} height={height * 0.4} rx={1} fill="#0d1117" opacity={0.55} />+ <rect x={width - 4} y={height * 0.3} width={2.5} height={height * 0.4} rx={1} fill="#0d1117" opacity={0.55} />++ {template.elements.map((el, i) => drawElement(el, i, width, height))}++ {template.statusLed && (+ <circle cx={LED_X} cy={height / 2} r={LED_R} fill={STATUS_COLOR[status]} />+ )}++ {showLabel && (+ <text+ x={labelX}+ y={height / 2}+ clipPath={`url(#${clipId})`}+ fontSize={fontSize}+ fill="#c9d1d9"+ dominantBaseline="central"+ textAnchor="start"+ fontFamily="Inter, system-ui, sans-serif"+ >+ {label}+ </text>+ )}++ {showPorts &&+ ports.map((port) => {+ const cx = port.x * width+ const cy = port.y * height+ const patchColor = patchedPorts?.get(port.id)+ const isDraft = draftPortId === port.id+ const { w, h } = portShapeSize(template.portSize ?? 'md', height, port.type)+ const stroke = isDraft ? '#00d4ff' : patchColor ?? PORT_BEZEL++ return (+ <g+ key={port.id}+ transform={`translate(${cx} ${cy})`}+ style={{+ cursor: interactivePorts ? 'crosshair' : undefined,+ pointerEvents: interactivePorts ? 'auto' : 'none',+ }}+ onClick={+ interactivePorts+ ? (e) => {+ e.stopPropagation()+ onPortClick?.(port.id)+ }+ : undefined+ }+ >+ {port.type === 'rj45' ? (+ <path+ d={rj45Path(w, h)}+ fill={PORT_RECESS}+ stroke={stroke}+ strokeWidth={isDraft ? 1.4 : 0.9}+ strokeLinejoin="round"+ />+ ) : (+ <>+ <rect+ x={-w / 2}+ y={-h / 2}+ width={w}+ height={h}+ rx={1}+ fill={PORT_RECESS}+ stroke={stroke}+ strokeWidth={isDraft ? 1.4 : 0.9}+ />+ <rect+ x={-w / 2 + w * 0.18}+ y={-h / 2 + h * 0.3}+ width={w * 0.64}+ height={Math.max(0.8, h * 0.22)}+ fill={stroke}+ opacity={0.65}+ />+ </>+ )}+ <title>{`${port.label} · ${port.type}`}</title>+ </g>+ )+ })}+ </svg>+ )+})diff --git a/frontend/src/rack/components/InventoryTray.tsx b/frontend/src/rack/components/InventoryTray.tsxnew file mode 100644index 0000000..c0821d2--- /dev/null+++ b/frontend/src/rack/components/InventoryTray.tsx@@ -0,0 +1,100 @@+/** Left rail: unracked inventory + rack accessories, both drag sources. */+import { FACEPLATES, getFaceplate } from '../faceplates'+import { useRackStore } from '../store'+import type { InventoryDevice } from '../types'+import { endDrag, startDrag } from './dragPayload'++const STATUS_DOT: Record<InventoryDevice['status'], string> = {+ online: '#39d353',+ offline: '#f85149',+ unknown: '#8b949e',+}++export function InventoryTray() {+ const inventory = useRackStore((s) => s.inventory)+ const devices = useRackStore((s) => s.devices)++ const mountedNodeIds = new Set(devices.map((d) => d.nodeId).filter(Boolean))+ const unracked = inventory.filter((i) => !mountedNodeIds.has(i.id))+ const racked = inventory.filter((i) => mountedNodeIds.has(i.id))+ const accessories = FACEPLATES.filter((f) => f.kind === 'accessory')++ return (+ <aside className="w-64 shrink-0 overflow-y-auto border-r border-[#21262d] bg-[#0d1117] p-3 text-sm text-[#c9d1d9]">+ <h2 className="mb-1 text-xs font-semibold uppercase tracking-wide text-[#6e7681]">+ Inventory · unracked ({unracked.length})+ </h2>+ <p className="mb-2 text-[11px] leading-snug text-[#6e7681]">+ Drag onto a rack. Removing gear from a rack never deletes it here.+ </p>+ <ul className="mb-4 space-y-1">+ {unracked.map((item) => (+ <li+ key={item.id}+ draggable+ onDragStart={(e) =>+ startDrag(e.dataTransfer, {+ kind: 'inventory',+ id: item.id,+ faceplateId: item.suggestedFaceplateId,+ })+ }+ onDragEnd={endDrag}+ className="flex cursor-grab items-center gap-2 rounded border border-[#21262d] bg-[#161b22] px-2 py-1.5 hover:border-[#00d4ff]"+ title={`${item.type}${item.ip ? ` · ${item.ip}` : ''} · ${getFaceplate(item.suggestedFaceplateId).label}`}+ >+ <span+ className="size-2 shrink-0 rounded-full"+ style={{ background: STATUS_DOT[item.status] }}+ />+ <span className="truncate">{item.label}</span>+ <span className="ml-auto shrink-0 font-mono text-[10px] text-[#6e7681]">+ {getFaceplate(item.suggestedFaceplateId).uHeight}U+ </span>+ </li>+ ))}+ {unracked.length === 0 && (+ <li className="px-2 py-1 text-[11px] text-[#6e7681]">Everything is racked.</li>+ )}+ </ul>++ <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[#6e7681]">+ Accessories+ </h2>+ <ul className="mb-4 space-y-1">+ {accessories.map((plate) => (+ <li+ key={plate.id}+ draggable+ onDragStart={(e) =>+ startDrag(e.dataTransfer, {+ kind: 'accessory',+ id: plate.id,+ faceplateId: plate.id,+ })+ }+ onDragEnd={endDrag}+ className="cursor-grab rounded border border-[#21262d] bg-[#161b22] px-2 py-1.5 hover:border-[#00d4ff]"+ >+ {plate.label}+ </li>+ ))}+ </ul>++ <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[#6e7681]">+ Racked ({racked.length})+ </h2>+ <ul className="space-y-1">+ {racked.map((item) => (+ <li key={item.id} className="flex items-center gap-2 px-2 py-1 text-[#6e7681]">+ <span+ className="size-2 shrink-0 rounded-full"+ style={{ background: STATUS_DOT[item.status] }}+ />+ <span className="truncate">{item.label}</span>+ </li>+ ))}+ </ul>+ </aside>+ )+}diff --git a/frontend/src/rack/components/RackFlowNode.tsx b/frontend/src/rack/components/RackFlowNode.tsxnew file mode 100644index 0000000..ebe6188--- /dev/null+++ b/frontend/src/rack/components/RackFlowNode.tsx@@ -0,0 +1,320 @@+/** One rack = one React Flow node. The U grid inside is rendered by hand. */+import { useCallback, useState } from 'react'+import { useReactFlow, type NodeProps } from '@xyflow/react'+import { getFaceplate } from '../faceplates'+import {+ HEADER_PX,+ INTERIOR_TOP_PX,+ NUMBER_GUTTER_PX,+ RAIL_PX,+ U_PX,+ columnWidth,+ deviceBox,+ findSlot,+ innerWidth,+ interiorLeft,+ rackHeight,+ rackWidth,+ uLabel,+ xToCol,+ yToU,+} from '../layout'+import { useRackStore } from '../store'+import { RACK_COLUMNS } from '../types'+import { Faceplate } from './Faceplate'+import { endDrag, getDragPayload, parseDragPayload, startDrag } from './dragPayload'++interface DropPreview {+ uStart: number+ uHeight: number+ colStart: number+ colSpan: number+ valid: boolean+}++export function RackFlowNode({ id }: NodeProps) {+ const rack = useRackStore((s) => s.racks.find((r) => r.id === id))+ const devices = useRackStore((s) => s.devices)+ const cables = useRackStore((s) => s.cables)+ const selectedDeviceId = useRackStore((s) => s.selectedDeviceId)+ const selectedRackId = useRackStore((s) => s.selectedRackId)+ const hoveredDeviceId = useRackStore((s) => s.hoveredDeviceId)+ const cableMode = useRackStore((s) => s.cableMode)+ const cableDraft = useRackStore((s) => s.cableDraft)+ const cableVisibility = useRackStore((s) => s.cableVisibility)++ const selectDevice = useRackStore((s) => s.selectDevice)+ const selectRack = useRackStore((s) => s.selectRack)+ const hoverDevice = useRackStore((s) => s.hoverDevice)+ const pickPort = useRackStore((s) => s.pickPort)+ const mountFromInventory = useRackStore((s) => s.mountFromInventory)+ const mountAccessory = useRackStore((s) => s.mountAccessory)+ const moveDevice = useRackStore((s) => s.moveDevice)++ const { getZoom } = useReactFlow()+ const [preview, setPreview] = useState<DropPreview | null>(null)++ const mounted = devices.filter((d) => d.rackId === id)++ const localPoint = useCallback(+ (e: React.DragEvent<HTMLDivElement>) => {+ const rect = e.currentTarget.getBoundingClientRect()+ const zoom = getZoom() || 1+ return { x: (e.clientX - rect.left) / zoom, y: (e.clientY - rect.top) / zoom }+ },+ [getZoom],+ )++ const onDragOver = useCallback(+ (e: React.DragEvent<HTMLDivElement>) => {+ if (!rack) return+ e.preventDefault()+ e.dataTransfer.dropEffect = 'move'+ const payload = getDragPayload()+ if (!payload) return++ const { x, y } = localPoint(e)+ const source =+ payload.kind === 'device'+ ? devices.find((d) => d.id === payload.id)+ : getFaceplate(payload.faceplateId)+ if (!source) return++ const { uHeight, colSpan } = source+ const desired = {+ uStart: Math.max(1, yToU(rack, y) - Math.floor(uHeight / 2)),+ uHeight,+ colStart: Math.min(xToCol(rack, x), RACK_COLUMNS - colSpan),+ colSpan,+ }+ const slot = findSlot(+ rack,+ devices,+ desired,+ payload.kind === 'device' ? payload.id : undefined,+ )+ setPreview(slot ? { ...slot, valid: true } : { ...desired, valid: false })+ },+ [rack, devices, localPoint],+ )++ const onDrop = useCallback(+ (e: React.DragEvent<HTMLDivElement>) => {+ if (!rack) return+ e.preventDefault()+ const payload = parseDragPayload(e.dataTransfer)+ setPreview(null)+ endDrag()+ if (!payload) return++ const { x, y } = localPoint(e)+ const col = xToCol(rack, x)++ if (payload.kind === 'inventory') {+ mountFromInventory(payload.id, rack.id, { uStart: yToU(rack, y), colStart: col })+ } else if (payload.kind === 'accessory') {+ mountAccessory(payload.id, rack.id, { uStart: yToU(rack, y), colStart: col })+ } else {+ const device = devices.find((d) => d.id === payload.id)+ if (!device) return+ const desired = {+ uStart: Math.max(1, yToU(rack, y) - Math.floor(device.uHeight / 2)),+ uHeight: device.uHeight,+ colStart: Math.min(col, RACK_COLUMNS - device.colSpan),+ colSpan: device.colSpan,+ }+ const slot = findSlot(rack, devices, desired, device.id)+ if (slot) moveDevice(device.id, rack.id, slot)+ }+ },+ [rack, devices, localPoint, mountFromInventory, mountAccessory, moveDevice],+ )++ if (!rack) return null++ const width = rackWidth(rack)+ const height = rackHeight(rack)+ const gutter = rack.style.showNumbers ? NUMBER_GUTTER_PX : 0+ const col = columnWidth(rack)+ const patchedPorts = new Map<string, string>()+ for (const cable of cables) {+ patchedPorts.set(cable.from.portId, cable.color)+ patchedPorts.set(cable.to.portId, cable.color)+ }+ const cablesOn = cableVisibility === 'always' || cableMode+ // Ports of non-patch gear stay hidden until the plate is focused, or until+ // cables are on globally — a cable must never end on an invisible port.+ const revealAll = cablesOn++ return (+ <div+ className="rack-node"+ style={{ width, height, position: 'relative' }}+ onDragOver={onDragOver}+ onDragLeave={() => setPreview(null)}+ onDrop={onDrop}+ onClick={() => selectRack(rack.id)}+ >+ {/* Chassis */}+ <div+ style={{+ position: 'absolute',+ inset: 0,+ left: gutter,+ background: rack.style.frame,+ border: `2px solid ${selectedRackId === rack.id ? '#00d4ff' : '#0d1117'}`,+ borderRadius: 6,+ boxShadow: rack.style.enclosed ? 'inset 0 0 0 4px rgba(0,0,0,0.35)' : undefined,+ }}+ />+ {/* Interior */}+ <div+ style={{+ position: 'absolute',+ left: interiorLeft(rack),+ top: INTERIOR_TOP_PX,+ width: innerWidth(rack),+ height: rack.uHeight * U_PX,+ background: rack.style.interior,+ }}+ />+ {/* Rails */}+ {[interiorLeft(rack) - RAIL_PX, interiorLeft(rack) + innerWidth(rack)].map((x) => (+ <div+ key={x}+ style={{+ position: 'absolute',+ left: x,+ top: INTERIOR_TOP_PX,+ width: RAIL_PX,+ height: rack.uHeight * U_PX,+ background: rack.style.rail,+ backgroundImage:+ 'repeating-linear-gradient(to bottom, rgba(0,0,0,0.45) 0 2px, transparent 2px 8px)',+ }}+ />+ ))}++ {/* U number gutter + slot separators */}+ {Array.from({ length: rack.uHeight }, (_, i) => {+ const u = rack.uHeight - i+ return (+ <div key={u}>+ {rack.style.showNumbers && (+ <div+ style={{+ position: 'absolute',+ left: 0,+ top: INTERIOR_TOP_PX + i * U_PX,+ width: gutter - 4,+ height: U_PX,+ fontSize: 9,+ lineHeight: `${U_PX}px`,+ textAlign: 'right',+ color: '#6e7681',+ fontFamily: 'JetBrains Mono, monospace',+ }}+ >+ {uLabel(rack, u)}+ </div>+ )}+ <div+ style={{+ position: 'absolute',+ left: interiorLeft(rack),+ top: INTERIOR_TOP_PX + i * U_PX,+ width: innerWidth(rack),+ height: 1,+ background: 'rgba(255,255,255,0.04)',+ }}+ />+ </div>+ )+ })}++ {/* Drop preview */}+ {preview && (+ <div+ style={{+ position: 'absolute',+ left: interiorLeft(rack) + preview.colStart * col,+ top: INTERIOR_TOP_PX + (rack.uHeight - preview.uStart - preview.uHeight + 1) * U_PX,+ width: preview.colSpan * col,+ height: preview.uHeight * U_PX,+ border: `1.5px dashed ${preview.valid ? '#39d353' : '#f85149'}`,+ background: preview.valid ? 'rgba(57,211,83,0.12)' : 'rgba(248,81,73,0.12)',+ borderRadius: 3,+ pointerEvents: 'none',+ }}+ />+ )}++ {/* Mounted gear */}+ {mounted.map((device) => {+ const box = deviceBox(rack, device)+ const isDraftDevice = cableDraft?.deviceId === device.id+ const focused = hoveredDeviceId === device.id || selectedDeviceId === device.id+ return (+ <div+ key={device.id}+ className="nodrag"+ draggable={!cableMode}+ onDragStart={(e) => startDrag(e.dataTransfer, { kind: 'device', id: device.id })}+ onDragEnd={endDrag}+ onClick={(e) => {+ e.stopPropagation()+ selectDevice(device.id)+ }}+ onMouseEnter={() => hoverDevice(device.id)}+ onMouseLeave={() => hoverDevice(null)}+ style={{+ position: 'absolute',+ left: box.x,+ top: box.y,+ width: box.width,+ height: box.height,+ cursor: cableMode ? 'default' : 'grab',+ }}+ title={`${device.label} · ${device.uHeight}U · U${device.uStart}`}+ >+ <Faceplate+ faceplateId={device.faceplateId}+ label={device.label}+ status={device.status}+ ports={device.ports}+ width={box.width}+ height={box.height}+ colorOverride={device.color}+ selected={selectedDeviceId === device.id}+ revealed={revealAll || focused}+ transparent={cablesOn && !focused}+ interactivePorts={cableMode}+ patchedPorts={patchedPorts}+ draftPortId={isDraftDevice ? cableDraft.portId : null}+ onPortClick={(portId) => pickPort(device.id, portId)}+ />+ </div>+ )+ })}++ {/* Name plate — inside the chassis so it never gets clipped by fitView */}+ <div+ style={{+ position: 'absolute',+ left: gutter + 12,+ top: 6,+ height: HEADER_PX,+ lineHeight: `${HEADER_PX}px`,+ fontSize: 12,+ color: '#c9d1d9',+ fontFamily: 'Inter, system-ui, sans-serif',+ pointerEvents: 'none',+ }}+ >+ {rack.name}+ {rack.location && <span style={{ color: '#6e7681' }}> · {rack.location}</span>}+ <span style={{ color: '#6e7681' }}> · {rack.uHeight}U</span>+ </div>+ </div>+ )+}diff --git a/frontend/src/rack/components/RackInspector.tsx b/frontend/src/rack/components/RackInspector.tsxnew file mode 100644index 0000000..8284b3e--- /dev/null+++ b/frontend/src/rack/components/RackInspector.tsx@@ -0,0 +1,324 @@+/** Right rail: settings for the selected rack or the selected mounted device. */+import { faceplateGroups } from '../faceplates'+import { RACK_COLUMNS } from '../types'+import { freeUnits } from '../layout'+import { useRackStore } from '../store'+import { CABLE_TYPE_LABELS } from '../rackDefaults'+import type { CableType, DeviceStatus, PortType, RackNumbering, RackWidthStandard } from '../types'++const inputClass =+ 'w-full rounded border border-[#21262d] bg-[#0d1117] px-2 py-1 text-sm text-[#c9d1d9] outline-none focus:border-[#00d4ff]'+const labelClass = 'mb-1 block text-[11px] uppercase tracking-wide text-[#6e7681]'++function Field({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="mb-3">+ <span className={labelClass}>{label}</span>+ {children}+ </div>+ )+}++function RackSettings({ rackId }: { rackId: string }) {+ const rack = useRackStore((s) => s.racks.find((r) => r.id === rackId))+ const devices = useRackStore((s) => s.devices)+ const updateRack = useRackStore((s) => s.updateRack)+ const updateRackStyle = useRackStore((s) => s.updateRackStyle)+ const removeRack = useRackStore((s) => s.removeRack)++ if (!rack) return null+ const used = rack.uHeight - freeUnits(rack, devices)++ return (+ <div>+ <h2 className="mb-3 text-sm font-semibold">Rack settings</h2>++ <Field label="Name">+ <input+ className={inputClass}+ value={rack.name}+ onChange={(e) => updateRack(rack.id, { name: e.target.value })}+ />+ </Field>+ <Field label="Location">+ <input+ className={inputClass}+ value={rack.location ?? ''}+ onChange={(e) => updateRack(rack.id, { location: e.target.value })}+ />+ </Field>+ <Field label={`Height — ${used}U used of ${rack.uHeight}U`}>+ <input+ type="number"+ min={1}+ max={48}+ className={inputClass}+ value={rack.uHeight}+ onChange={(e) => updateRack(rack.id, { uHeight: Number(e.target.value) || 1 })}+ />+ </Field>+ <Field label="Width standard">+ <select+ className={inputClass}+ value={rack.widthStandard}+ onChange={(e) =>+ updateRack(rack.id, { widthStandard: e.target.value as RackWidthStandard })+ }+ >+ <option value="19">19 inch</option>+ <option value="10">10 inch (mini)</option>+ </select>+ </Field>+ <Field label="U numbering">+ <select+ className={inputClass}+ value={rack.numbering}+ onChange={(e) => updateRack(rack.id, { numbering: e.target.value as RackNumbering })}+ >+ <option value="bottom-up">1 at the bottom</option>+ <option value="top-down">1 at the top</option>+ </select>+ </Field>++ <h3 className="mb-2 mt-4 text-xs font-semibold uppercase tracking-wide text-[#6e7681]">+ Style+ </h3>+ {(['frame', 'rail', 'interior'] as const).map((key) => (+ <Field key={key} label={key}>+ <input+ type="color"+ className="h-8 w-full cursor-pointer rounded border border-[#21262d] bg-[#0d1117]"+ value={rack.style[key]}+ onChange={(e) => updateRackStyle(rack.id, { [key]: e.target.value })}+ />+ </Field>+ ))}+ <label className="mb-2 flex items-center gap-2 text-sm">+ <input+ type="checkbox"+ checked={rack.style.showNumbers}+ onChange={(e) => updateRackStyle(rack.id, { showNumbers: e.target.checked })}+ />+ Show U numbers+ </label>+ <label className="mb-4 flex items-center gap-2 text-sm">+ <input+ type="checkbox"+ checked={rack.style.enclosed}+ onChange={(e) => updateRackStyle(rack.id, { enclosed: e.target.checked })}+ />+ Enclosed cabinet+ </label>++ <button+ className="w-full rounded border border-[#f85149] px-2 py-1.5 text-sm text-[#f85149] hover:bg-[#f8514922]"+ onClick={() => removeRack(rack.id)}+ >+ Delete rack+ </button>+ </div>+ )+}++function DeviceSettings({ deviceId }: { deviceId: string }) {+ const device = useRackStore((s) => s.devices.find((d) => d.id === deviceId))+ const cables = useRackStore((s) => s.cables)+ const updateDevice = useRackStore((s) => s.updateDevice)+ const applyFaceplate = useRackStore((s) => s.applyFaceplate)+ const unmountDevice = useRackStore((s) => s.unmountDevice)+ const addPort = useRackStore((s) => s.addPort)+ const updatePort = useRackStore((s) => s.updatePort)+ const removePort = useRackStore((s) => s.removePort)++ if (!device) return null++ const cableOf = (portId: string) =>+ cables.find(+ (c) =>+ (c.from.deviceId === device.id && c.from.portId === portId) ||+ (c.to.deviceId === device.id && c.to.portId === portId),+ )++ return (+ <div>+ <h2 className="mb-1 text-sm font-semibold">{device.label}</h2>+ <p className="mb-3 text-[11px] text-[#6e7681]">+ {device.nodeId ? `Inventory: ${device.nodeId}` : 'Rack-only accessory'}+ </p>++ <Field label="Label">+ <input+ className={inputClass}+ value={device.label}+ onChange={(e) => updateDevice(device.id, { label: e.target.value })}+ />+ </Field>++ <Field label="Faceplate">+ <select+ className={inputClass}+ value={device.faceplateId}+ onChange={(e) => applyFaceplate(device.id, e.target.value)}+ >+ {faceplateGroups().map(({ group, items }) => (+ <optgroup key={group} label={group}>+ {items.map((plate) => (+ <option key={plate.id} value={plate.id}>+ {plate.label}+ </option>+ ))}+ </optgroup>+ ))}+ </select>+ </Field>++ <div className="grid grid-cols-2 gap-2">+ <Field label="U position">+ <input+ type="number"+ min={1}+ className={inputClass}+ value={device.uStart}+ onChange={(e) => updateDevice(device.id, { uStart: Number(e.target.value) || 1 })}+ />+ </Field>+ <Field label="Height (U)">+ <input+ type="number"+ min={1}+ className={inputClass}+ value={device.uHeight}+ onChange={(e) => updateDevice(device.id, { uHeight: Number(e.target.value) || 1 })}+ />+ </Field>+ <Field label="Column">+ <input+ type="number"+ min={0}+ max={RACK_COLUMNS - 1}+ className={inputClass}+ value={device.colStart}+ onChange={(e) => updateDevice(device.id, { colStart: Number(e.target.value) || 0 })}+ />+ </Field>+ <Field label={`Width (/${RACK_COLUMNS})`}>+ <select+ className={inputClass}+ value={device.colSpan}+ onChange={(e) => updateDevice(device.id, { colSpan: Number(e.target.value) })}+ >+ <option value={RACK_COLUMNS}>Full width</option>+ <option value={RACK_COLUMNS / 2}>Half width</option>+ <option value={RACK_COLUMNS / 3}>Third width</option>+ <option value={RACK_COLUMNS / 4}>Quarter width</option>+ </select>+ </Field>+ </div>++ <Field label="Status">+ <select+ className={inputClass}+ value={device.status}+ onChange={(e) => updateDevice(device.id, { status: e.target.value as DeviceStatus })}+ >+ <option value="online">Online</option>+ <option value="offline">Offline</option>+ <option value="unknown">Unknown</option>+ </select>+ </Field>++ <Field label="Colour override">+ <input+ type="color"+ className="h-8 w-full cursor-pointer rounded border border-[#21262d] bg-[#0d1117]"+ value={device.color ?? '#2b323c'}+ onChange={(e) => updateDevice(device.id, { color: e.target.value })}+ />+ </Field>++ <div className="mb-2 flex items-center justify-between">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-[#6e7681]">+ Ports ({device.ports.length})+ </h3>+ <button+ className="rounded border border-[#21262d] px-2 py-0.5 text-xs hover:border-[#00d4ff]"+ onClick={() =>+ addPort(device.id, {+ label: `p${device.ports.length + 1}`,+ type: 'rj45',+ x: 0.5,+ y: 0.5,+ })+ }+ >+ + Add+ </button>+ </div>+ <ul className="max-h-56 space-y-1 overflow-y-auto">+ {device.ports.map((port) => {+ const cable = cableOf(port.id)+ return (+ <li key={port.id} className="flex items-center gap-1">+ <input+ className={`${inputClass} flex-1`}+ value={port.label}+ onChange={(e) => updatePort(device.id, port.id, { label: e.target.value })}+ />+ <select+ className={`${inputClass} w-24`}+ value={port.type}+ onChange={(e) =>+ updatePort(device.id, port.id, { type: e.target.value as PortType })+ }+ >+ {(['rj45', 'sfp', 'sfp+'] as PortType[]).map((t) => (+ <option key={t} value={t}>+ {t}+ </option>+ ))}+ </select>+ <span+ className="size-2 shrink-0 rounded-full"+ style={{ background: cable ? cable.color : '#30363d' }}+ title={cable ? `Patched — ${CABLE_TYPE_LABELS[cable.type as CableType]}` : 'Free'}+ />+ <button+ className="px-1 text-xs text-[#6e7681] hover:text-[#f85149]"+ onClick={() => removePort(device.id, port.id)}+ title="Remove port"+ >+ ✕+ </button>+ </li>+ )+ })}+ </ul>++ <button+ className="mt-4 w-full rounded border border-[#f85149] px-2 py-1.5 text-sm text-[#f85149] hover:bg-[#f8514922]"+ onClick={() => unmountDevice(device.id)}+ >+ Unmount {device.nodeId ? '(stays in inventory)' : ''}+ </button>+ </div>+ )+}++export function RackInspector() {+ const selectedDeviceId = useRackStore((s) => s.selectedDeviceId)+ const selectedRackId = useRackStore((s) => s.selectedRackId)++ return (+ <aside className="w-72 shrink-0 overflow-y-auto border-l border-[#21262d] bg-[#0d1117] p-3 text-sm text-[#c9d1d9]">+ {selectedDeviceId ? (+ <DeviceSettings deviceId={selectedDeviceId} />+ ) : selectedRackId ? (+ <RackSettings rackId={selectedRackId} />+ ) : (+ <p className="text-[11px] text-[#6e7681]">+ Select a rack or a mounted device to edit it.+ </p>+ )}+ </aside>+ )+}diff --git a/frontend/src/rack/components/RackLab.tsx b/frontend/src/rack/components/RackLab.tsxnew file mode 100644index 0000000..fb5a5fa--- /dev/null+++ b/frontend/src/rack/components/RackLab.tsx@@ -0,0 +1,180 @@+/**+ * Rack canvas prototype shell.+ *+ * Front-only: no API calls, no persistence. Mounted at /racklab so it can be+ * iterated on without touching the logical canvas.+ */+import { useCallback, useMemo } from 'react'+import {+ Background,+ BackgroundVariant,+ Controls,+ ReactFlow,+ ReactFlowProvider,+ type Node,+ type NodeChange,+} from '@xyflow/react'+import '@xyflow/react/dist/style.css'+import { rackHeight, rackWidth } from '../layout'+import { useRackStore } from '../store'+import { CABLE_TYPE_LABELS } from '../rackDefaults'+import type { CableType, CableVisibility } from '../types'+import { CableLayer } from './CableLayer'+import { InventoryTray } from './InventoryTray'+import { RackFlowNode } from './RackFlowNode'+import { RackInspector } from './RackInspector'++const nodeTypes = { rack: RackFlowNode }++const barButton =+ 'rounded border border-[#21262d] bg-[#161b22] px-2.5 py-1 text-xs text-[#c9d1d9] hover:border-[#00d4ff]'+const barSelect =+ 'rounded border border-[#21262d] bg-[#161b22] px-2 py-1 text-xs text-[#c9d1d9] outline-none focus:border-[#00d4ff]'++function RackCanvas() {+ const racks = useRackStore((s) => s.racks)+ const moveRack = useRackStore((s) => s.moveRack)+ const selectDevice = useRackStore((s) => s.selectDevice)+ const cableMode = useRackStore((s) => s.cableMode)++ const nodes: Node[] = useMemo(+ () =>+ racks.map((rack) => ({+ id: rack.id,+ type: 'rack',+ position: rack.position,+ data: {},+ draggable: !cableMode,+ style: { width: rackWidth(rack), height: rackHeight(rack) },+ })),+ [racks, cableMode],+ )++ const onNodesChange = useCallback(+ (changes: NodeChange[]) => {+ for (const change of changes) {+ if (change.type === 'position' && change.position) {+ moveRack(change.id, change.position)+ }+ }+ },+ [moveRack],+ )++ return (+ <ReactFlow+ nodes={nodes}+ edges={[]}+ nodeTypes={nodeTypes}+ onNodesChange={onNodesChange}+ onPaneClick={() => selectDevice(null)}+ minZoom={0.2}+ maxZoom={3}+ fitView+ proOptions={{ hideAttribution: true }}+ style={{ background: '#0d1117' }}+ >+ <Background variant={BackgroundVariant.Dots} gap={24} size={1} color="#21262d" />+ <Controls />+ <CableLayer />+ </ReactFlow>+ )+}++function RackToolbar() {+ const addRack = useRackStore((s) => s.addRack)+ const cableMode = useRackStore((s) => s.cableMode)+ const toggleCableMode = useRackStore((s) => s.toggleCableMode)+ const cableVisibility = useRackStore((s) => s.cableVisibility)+ const setCableVisibility = useRackStore((s) => s.setCableVisibility)+ const cableTypeFilter = useRackStore((s) => s.cableTypeFilter)+ const setCableTypeFilter = useRackStore((s) => s.setCableTypeFilter)+ const cableDraft = useRackStore((s) => s.cableDraft)+ const cancelCableDraft = useRackStore((s) => s.cancelCableDraft)+ const importCables = useRackStore((s) => s.importCablesFromNetwork)+ const networkImportDone = useRackStore((s) => s.networkImportDone)+ const reset = useRackStore((s) => s.reset)++ return (+ <header className="flex items-center gap-2 border-b border-[#21262d] bg-[#161b22] px-3 py-2">+ <span className="mr-2 text-sm font-semibold text-[#c9d1d9]">Rack view</span>+ <span className="rounded bg-[#21262d] px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[#e3b341]">+ prototype+ </span>++ <button className={barButton} onClick={() => addRack()}>+ + Rack+ </button>++ <button+ className={`${barButton} ${cableMode ? 'border-[#00d4ff] text-[#00d4ff]' : ''}`}+ onClick={toggleCableMode}+ title="Click a port, then another, to patch. Click a cable to remove it."+ >+ {cableMode ? 'Exit patching' : 'Patch mode'}+ </button>++ {cableMode && cableDraft && (+ <button className={`${barButton} border-[#e3b341] text-[#e3b341]`} onClick={cancelCableDraft}>+ Cancel cable+ </button>+ )}++ <label className="ml-2 flex items-center gap-1 text-[11px] text-[#6e7681]">+ Cables+ <select+ className={barSelect}+ value={cableVisibility}+ onChange={(e) => setCableVisibility(e.target.value as CableVisibility)}+ >+ <option value="hover">On hover / selection</option>+ <option value="always">Always</option>+ <option value="hidden">Hidden</option>+ </select>+ </label>++ <select+ className={barSelect}+ value={cableTypeFilter}+ onChange={(e) => setCableTypeFilter(e.target.value as CableType | 'all')}+ >+ <option value="all">All types</option>+ {(Object.keys(CABLE_TYPE_LABELS) as CableType[]).map((t) => (+ <option key={t} value={t}>+ {CABLE_TYPE_LABELS[t]}+ </option>+ ))}+ </select>++ <button+ className={barButton}+ disabled={networkImportDone}+ onClick={() => importCables()}+ title="One-shot: derive cables from the links already drawn on the logical canvas"+ >+ Import links from network canvas+ </button>++ <button className={`${barButton} ml-auto`} onClick={reset}>+ Reset demo+ </button>+ </header>+ )+}++export default function RackLab() {+ return (+ <ReactFlowProvider>+ <div className="flex h-screen w-screen flex-col bg-[#0d1117]">+ <RackToolbar />+ <div className="flex min-h-0 flex-1">+ <InventoryTray />+ <main className="min-w-0 flex-1">+ <RackCanvas />+ </main>+ <RackInspector />+ </div>+ </div>+ </ReactFlowProvider>+ )+}diff --git a/frontend/src/rack/components/dragPayload.ts b/frontend/src/rack/components/dragPayload.tsnew file mode 100644index 0000000..cece475--- /dev/null+++ b/frontend/src/rack/components/dragPayload.ts@@ -0,0 +1,40 @@+/**+ * Drag payload shared between the inventory tray and the rack drop targets.+ *+ * `dataTransfer.getData()` is blocked during `dragover` in every browser, and+ * the drop preview needs the payload on every move — so the payload also lives+ * in a module-level slot for the duration of the drag.+ */+export type DragPayload =+ | { kind: 'inventory'; id: string; faceplateId: string }+ | { kind: 'accessory'; id: string; faceplateId: string }+ | { kind: 'device'; id: string }++export const DRAG_MIME = 'application/homelable-rack'++let current: DragPayload | null = null++export function startDrag(dataTransfer: DataTransfer, payload: DragPayload): void {+ current = payload+ dataTransfer.setData(DRAG_MIME, JSON.stringify(payload))+ dataTransfer.effectAllowed = 'move'+}++export function getDragPayload(): DragPayload | null {+ return current+}++export function endDrag(): void {+ current = null+}++/** Falls back to the module slot when the browser withholds the data. */+export function parseDragPayload(dataTransfer: DataTransfer | null): DragPayload | null {+ const raw = dataTransfer?.getData(DRAG_MIME)+ if (!raw) return current+ try {+ return JSON.parse(raw) as DragPayload+ } catch {+ return current+ }+}diff --git a/frontend/src/rack/demoData.ts b/frontend/src/rack/demoData.tsnew file mode 100644index 0000000..4f4864e--- /dev/null+++ b/frontend/src/rack/demoData.ts@@ -0,0 +1,154 @@+/**+ * Fake inventory + a pre-filled rack, so the prototype boots with something+ * to look at. Ids are fixed strings (not UUIDs) to keep tests readable.+ */+import { getFaceplate } from './faceplates'+import { CABLE_COLORS, DEFAULT_RACK_STYLE } from './rackDefaults'+import type { Cable, CableType, InventoryDevice, Port, Rack, RackDevice } from './types'++let portSeq = 0+function withIds(ports: Omit<Port, 'id'>[], deviceId: string): Port[] {+ return ports.map((p) => ({ ...p, id: `${deviceId}-p${portSeq++}` }))+}++export function demoInventory(): InventoryDevice[] {+ return [+ { id: 'inv-pve1', label: 'pve-01', type: 'proxmox', ip: '192.168.1.10', status: 'online', suggestedFaceplateId: 'server-2u-bays' },+ { id: 'inv-pve2', label: 'pve-02', type: 'proxmox', ip: '192.168.1.11', status: 'online', suggestedFaceplateId: 'server-1u-bays' },+ { id: 'inv-nuc1', label: 'nuc-k3s-a', type: 'server', ip: '192.168.1.21', status: 'online', suggestedFaceplateId: 'sff-half' },+ { id: 'inv-nuc2', label: 'nuc-k3s-b', type: 'server', ip: '192.168.1.22', status: 'online', suggestedFaceplateId: 'sff-half' },+ { id: 'inv-pi1', label: 'pi-dns', type: 'server', ip: '192.168.1.31', status: 'online', suggestedFaceplateId: 'mini-third' },+ { id: 'inv-pi2', label: 'pi-backup', type: 'server', ip: '192.168.1.32', status: 'offline', suggestedFaceplateId: 'mini-third' },+ { id: 'inv-sw24', label: 'sw-core-24', type: 'switch', ip: '192.168.1.2', status: 'online', suggestedFaceplateId: 'switch-24' },+ { id: 'inv-sw8', label: 'sw-lab-8', type: 'switch', ip: '192.168.1.3', status: 'online', suggestedFaceplateId: 'switch-8' },+ { id: 'inv-fw', label: 'opnsense', type: 'firewall', ip: '192.168.1.1', status: 'online', suggestedFaceplateId: 'router-1u' },+ { id: 'inv-nas', label: 'nas-truenas', type: 'nas', ip: '192.168.1.40', status: 'online', suggestedFaceplateId: 'nas-2u' },+ { id: 'inv-jbod', label: 'jbod-shelf', type: 'server', ip: '192.168.1.41', status: 'unknown', suggestedFaceplateId: 'server-4u-storage' },+ { id: 'inv-ups', label: 'ups-eaton', type: 'ups', ip: '192.168.1.50', status: 'online', suggestedFaceplateId: 'ups-2u' },+ { id: 'inv-pdu', label: 'pdu-main', type: 'pdu', status: 'unknown', suggestedFaceplateId: 'pdu-1u' },+ { id: 'inv-patch', label: 'patch-house', type: 'patch_panel', status: 'unknown', suggestedFaceplateId: 'patch-24' },+ ]+}++export function demoRacks(): Rack[] {+ return [+ {+ id: 'rack-main',+ name: 'Main rack',+ location: 'Garage',+ uHeight: 18,+ widthStandard: '19',+ numbering: 'bottom-up',+ style: { ...DEFAULT_RACK_STYLE },+ position: { x: 120, y: 60 },+ },+ ]+}++interface DemoMount {+ id: string+ nodeId: string | null+ label: string+ faceplateId: string+ uStart: number+ colStart?: number+ colSpan?: number+ status?: RackDevice['status']+}++/** Layout of the pre-filled rack, top (18U) down to the bottom. */+const DEMO_MOUNTS: DemoMount[] = [+ { id: 'dev-patch', nodeId: 'inv-patch', label: 'patch-house', faceplateId: 'patch-24', uStart: 18 },+ { id: 'dev-sw24', nodeId: 'inv-sw24', label: 'sw-core-24', faceplateId: 'switch-24', uStart: 17 },+ { id: 'dev-mgmt', nodeId: null, label: 'Cable manager', faceplateId: 'cable-manager-1u', uStart: 16 },+ { id: 'dev-fw', nodeId: 'inv-fw', label: 'opnsense', faceplateId: 'router-1u', uStart: 15 },+ // Two half-width mini PCs sharing 14U.+ { id: 'dev-nuc1', nodeId: 'inv-nuc1', label: 'nuc-k3s-a', faceplateId: 'sff-half', uStart: 14, colStart: 0, colSpan: 6 },+ { id: 'dev-nuc2', nodeId: 'inv-nuc2', label: 'nuc-k3s-b', faceplateId: 'sff-half', uStart: 14, colStart: 6, colSpan: 6 },+ // Three third-width nodes sharing 13U.+ { id: 'dev-pi1', nodeId: 'inv-pi1', label: 'pi-dns', faceplateId: 'mini-third', uStart: 13, colStart: 0, colSpan: 4 },+ { id: 'dev-pi2', nodeId: 'inv-pi2', label: 'pi-backup', faceplateId: 'mini-third', uStart: 13, colStart: 4, colSpan: 4, status: 'offline' },+ { id: 'dev-blank', nodeId: null, label: 'Blank', faceplateId: 'blank-1u', uStart: 13, colStart: 8, colSpan: 4 },+ { id: 'dev-pve1', nodeId: 'inv-pve1', label: 'pve-01', faceplateId: 'server-2u-bays', uStart: 11 },+ { id: 'dev-pve2', nodeId: 'inv-pve2', label: 'pve-02', faceplateId: 'server-1u-bays', uStart: 10 },+ { id: 'dev-nas', nodeId: 'inv-nas', label: 'nas-truenas', faceplateId: 'nas-2u', uStart: 8 },+ { id: 'dev-shelf', nodeId: null, label: 'Shelf', faceplateId: 'shelf-1u', uStart: 7 },+ { id: 'dev-pdu', nodeId: 'inv-pdu', label: 'pdu-main', faceplateId: 'pdu-1u', uStart: 3 },+ { id: 'dev-ups', nodeId: 'inv-ups', label: 'ups-eaton', faceplateId: 'ups-2u', uStart: 1 },+]++export function demoDevices(): RackDevice[] {+ portSeq = 0+ const inventory = demoInventory()+ return DEMO_MOUNTS.map((mount) => {+ const plate = getFaceplate(mount.faceplateId)+ const inv = mount.nodeId ? inventory.find((i) => i.id === mount.nodeId) : undefined+ return {+ id: mount.id,+ rackId: 'rack-main',+ nodeId: mount.nodeId,+ label: mount.label,+ uStart: mount.uStart,+ uHeight: plate.uHeight,+ colStart: mount.colStart ?? 0,+ colSpan: mount.colSpan ?? plate.colSpan,+ faceplateId: mount.faceplateId,+ status: mount.status ?? inv?.status ?? 'unknown',+ ports: withIds(plate.ports, mount.id),+ }+ })+}++/**+ * A few patch cables so the cabling overlay has something to show on boot.+ * Ports are picked by index into each device's generated port list.+ */+const DEMO_CABLE_SPECS: {+ from: [string, number]+ to: [string, number]+ type: CableType+ label?: string+}[] = [+ { from: ['dev-sw24', 0], to: ['dev-fw', 0], type: 'ethernet', label: 'WAN uplink' },+ { from: ['dev-sw24', 1], to: ['dev-pve1', 0], type: 'ethernet' },+ { from: ['dev-sw24', 2], to: ['dev-pve2', 0], type: 'ethernet' },+ { from: ['dev-sw24', 3], to: ['dev-nuc1', 0], type: 'ethernet' },+ { from: ['dev-sw24', 4], to: ['dev-nuc2', 0], type: 'ethernet' },+ // sw24 ports: 0..23 are RJ45, 24..25 are SFP+.+ { from: ['dev-sw24', 24], to: ['dev-nas', 2], type: 'fiber', label: '10G SAN' },+ { from: ['dev-patch', 0], to: ['dev-sw24', 12], type: 'ethernet', label: 'office' },+ { from: ['dev-patch', 1], to: ['dev-sw24', 13], type: 'ethernet', label: 'living room' },+]++export function demoCables(): Cable[] {+ const devices = demoDevices()+ const byId = new Map(devices.map((d) => [d.id, d]))+ const cables: Cable[] = []+ for (const [i, spec] of DEMO_CABLE_SPECS.entries()) {+ const from = byId.get(spec.from[0])?.ports[spec.from[1]]+ const to = byId.get(spec.to[0])?.ports[spec.to[1]]+ if (!from || !to) continue+ cables.push({+ id: `cable-${i}`,+ type: spec.type,+ color: CABLE_COLORS[spec.type],+ label: spec.label,+ from: { deviceId: spec.from[0], portId: from.id },+ to: { deviceId: spec.to[0], portId: to.id },+ })+ }+ return cables+}++/**+ * Stand-in for "read the links already drawn on the logical canvas".+ * The real implementation would read the network design's edges; here it is a+ * fixed list of inventory-id pairs used by the one-shot import action.+ */+export function networkEdgeHints(): { from: string; to: string; type: CableType; label?: string }[] {+ return [+ { from: 'inv-sw8', to: 'inv-sw24', type: 'ethernet', label: 'lab uplink' },+ { from: 'inv-jbod', to: 'inv-nas', type: 'ethernet' },+ { from: 'inv-pi1', to: 'inv-sw24', type: 'ethernet' },+ ]+}diff --git a/frontend/src/rack/faceplates.ts b/frontend/src/rack/faceplates.tsnew file mode 100644index 0000000..2e816e6--- /dev/null+++ b/frontend/src/rack/faceplates.ts@@ -0,0 +1,393 @@+/**+ * Front-panel templates.+ *+ * Artwork and port coordinates are unit coordinates (0..1 on both axes) so a+ * plate scales with U height, rack width and zoom. Every plate reserves three+ * bands that must not overlap: the status LED (far left), the name band+ * (`labelBox`) and whatever sits to the right of it.+ *+ * Templates only seed the ports — the user edits the port list afterwards.+ */+import { RACK_COLUMNS, type FaceplateTemplate, type Port, type PortType } from './types'++interface BankOptions {+ type: PortType+ count: number+ /** Horizontal band, in unit coordinates. */+ x: number+ w: number+ /** Ports per row; the bank wraps into as many evenly spaced rows as needed. */+ perRow?: number+ /** Label prefix; ports are numbered from `start`. */+ prefix?: string+ start?: number+}++/**+ * Evenly spread `count` ports across a horizontal band.+ * Rows are centred vertically so a bank always looks balanced on the plate,+ * whatever the U height.+ */+export function bank({+ type,+ count,+ x,+ w,+ perRow = count,+ prefix = 'P',+ start = 1,+}: BankOptions): Omit<Port, 'id'>[] {+ const rows = Math.max(1, Math.ceil(count / perRow))+ const stepX = w / perRow+ // Rows share the vertical space evenly: 1 row -> 0.5, 2 rows -> 0.3/0.7.+ const rowY = (row: number) => (row + 1) / (rows + 1)+ return Array.from({ length: count }, (_, i) => {+ const row = Math.floor(i / perRow)+ const col = i % perRow+ return {+ label: `${prefix}${start + i}`,+ type,+ x: x + stepX * (col + 0.5),+ y: rowY(row),+ }+ })+}++const STEEL = '#2b323c'+const STEEL_LIGHT = '#39424f'+const BLACK_BOX = '#1b1f26'+const VENT = '#141922'++/** Name band used by full-width plates that keep their ports on the right. */+const LABEL_LEFT = { x: 0.055, w: 0.24 }+/** Narrower band for dense port panels. */+const LABEL_TIGHT = { x: 0.05, w: 0.15 }+/** Half/third-width plates: the LED is proportionally wider, so shift right. */+const LABEL_SMALL = { x: 0.1, w: 0.4 }++export const FACEPLATES: FaceplateTemplate[] = [+ // --- Servers ------------------------------------------------------------+ {+ id: 'server-1u',+ label: 'Server 1U',+ kind: 'device',+ group: 'Servers',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: LABEL_LEFT,+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: STEEL, stroke: '#0d1117' },+ { kind: 'vents', x: 0.32, y: 0.22, w: 0.42, h: 0.56, cols: 16, rows: 2, fill: VENT },+ ],+ ports: bank({ type: 'rj45', count: 2, x: 0.79, w: 0.16, prefix: 'eth' }),+ },+ {+ id: 'server-1u-bays',+ label: 'Server 1U — 4 bays',+ kind: 'device',+ group: 'Servers',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: LABEL_LEFT,+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: STEEL, stroke: '#0d1117' },+ { kind: 'bays', x: 0.32, y: 0.18, w: 0.42, h: 0.64, cols: 4, rows: 1, fill: BLACK_BOX },+ ],+ ports: bank({ type: 'rj45', count: 2, x: 0.79, w: 0.16, prefix: 'eth' }),+ },+ {+ id: 'server-2u-bays',+ label: 'Server 2U — 8 bays',+ kind: 'device',+ group: 'Servers',+ uHeight: 2,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: LABEL_LEFT,+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: STEEL, stroke: '#0d1117' },+ { kind: 'bays', x: 0.32, y: 0.12, w: 0.42, h: 0.76, cols: 4, rows: 2, fill: BLACK_BOX },+ ],+ ports: [+ ...bank({ type: 'rj45', count: 4, x: 0.78, w: 0.13, perRow: 2, prefix: 'eth' }),+ ...bank({ type: 'sfp+', count: 2, x: 0.92, w: 0.06, perRow: 1, prefix: 'sfp' }),+ ],+ },+ {+ id: 'server-4u-storage',+ label: 'Storage 4U — 12 bays',+ kind: 'device',+ group: 'Servers',+ uHeight: 4,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: { x: 0.055, w: 0.18 },+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: STEEL_LIGHT, stroke: '#0d1117' },+ { kind: 'bays', x: 0.26, y: 0.1, w: 0.5, h: 0.8, cols: 4, rows: 3, fill: BLACK_BOX },+ ],+ ports: bank({ type: 'rj45', count: 2, x: 0.8, w: 0.14, prefix: 'eth' }),+ },+ {+ id: 'sff-half',+ label: 'SFF / mini PC (half width)',+ kind: 'device',+ group: 'Servers',+ uHeight: 1,+ colSpan: RACK_COLUMNS / 2,+ statusLed: true,+ labelBox: LABEL_SMALL,+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: STEEL_LIGHT, stroke: '#0d1117' },+ { kind: 'vents', x: 0.54, y: 0.25, w: 0.24, h: 0.5, cols: 8, rows: 2, fill: VENT },+ ],+ ports: bank({ type: 'rj45', count: 1, x: 0.82, w: 0.12, prefix: 'eth' }),+ },+ {+ id: 'mini-third',+ label: 'Mini node (third width)',+ kind: 'device',+ group: 'Servers',+ uHeight: 1,+ colSpan: RACK_COLUMNS / 3,+ statusLed: true,+ labelBox: { x: 0.14, w: 0.42 },+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: STEEL_LIGHT, stroke: '#0d1117' },+ { kind: 'vents', x: 0.6, y: 0.3, w: 0.16, h: 0.4, cols: 5, rows: 2, fill: VENT },+ ],+ ports: bank({ type: 'rj45', count: 1, x: 0.8, w: 0.14, prefix: 'eth' }),+ },++ // --- Network ------------------------------------------------------------+ {+ id: 'switch-8',+ label: 'Switch 8 ports',+ kind: 'device',+ group: 'Network',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ alwaysShowPorts: true,+ labelBox: LABEL_LEFT,+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: BLACK_BOX, stroke: '#0d1117' },+ { kind: 'strip', x: 0.32, y: 0.16, w: 0.42, h: 0.68, fill: '#11161d' },+ ],+ ports: [+ ...bank({ type: 'rj45', count: 8, x: 0.33, w: 0.4, prefix: '' }),+ ...bank({ type: 'sfp', count: 1, x: 0.79, w: 0.08, prefix: 'sfp' }),+ ],+ },+ {+ id: 'switch-24',+ label: 'Switch 24 ports + 2 SFP',+ kind: 'device',+ group: 'Network',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ alwaysShowPorts: true,+ labelBox: LABEL_TIGHT,+ portSize: 'sm',+ elements: [+ { kind: 'panel', fill: BLACK_BOX, stroke: '#0d1117' },+ { kind: 'strip', x: 0.22, y: 0.12, w: 0.55, h: 0.76, fill: '#11161d' },+ ],+ ports: [+ ...bank({ type: 'rj45', count: 24, x: 0.23, w: 0.53, perRow: 12, prefix: '' }),+ ...bank({ type: 'sfp+', count: 2, x: 0.8, w: 0.12, prefix: 'sfp' }),+ ],+ },+ {+ id: 'switch-48',+ label: 'Switch 48 ports + 4 SFP+',+ kind: 'device',+ group: 'Network',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ alwaysShowPorts: true,+ labelBox: LABEL_TIGHT,+ portSize: 'sm',+ elements: [+ { kind: 'panel', fill: BLACK_BOX, stroke: '#0d1117' },+ { kind: 'strip', x: 0.21, y: 0.12, w: 0.56, h: 0.76, fill: '#11161d' },+ ],+ ports: [+ ...bank({ type: 'rj45', count: 48, x: 0.22, w: 0.54, perRow: 24, prefix: '' }),+ ...bank({ type: 'sfp+', count: 4, x: 0.79, w: 0.14, perRow: 2, prefix: 'sfp' }),+ ],+ },+ {+ id: 'router-1u',+ label: 'Router / firewall 1U',+ kind: 'device',+ group: 'Network',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: LABEL_LEFT,+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: '#232a34', stroke: '#0d1117' },+ { kind: 'strip', x: 0.34, y: 0.16, w: 0.4, h: 0.68, fill: '#11161d' },+ ],+ ports: [+ ...bank({ type: 'rj45', count: 6, x: 0.35, w: 0.38, prefix: 'lan' }),+ ...bank({ type: 'sfp+', count: 1, x: 0.79, w: 0.08, prefix: 'sfp' }),+ ],+ },+ {+ id: 'patch-24',+ label: 'Patch panel 24',+ kind: 'device',+ group: 'Network',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ alwaysShowPorts: true,+ labelBox: { x: 0.02, w: 0.16 },+ portSize: 'sm',+ elements: [+ { kind: 'panel', fill: '#3a3f47', stroke: '#0d1117' },+ { kind: 'strip', x: 0.2, y: 0.14, w: 0.78, h: 0.72, fill: '#22262c' },+ ],+ ports: bank({ type: 'rj45', count: 24, x: 0.21, w: 0.76, perRow: 24, prefix: '' }),+ },+ {+ id: 'patch-fiber-12',+ label: 'Fiber panel 12 (LC)',+ kind: 'device',+ group: 'Network',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ alwaysShowPorts: true,+ labelBox: { x: 0.02, w: 0.16 },+ portSize: 'sm',+ elements: [+ { kind: 'panel', fill: '#3a3f47', stroke: '#0d1117' },+ { kind: 'strip', x: 0.2, y: 0.16, w: 0.6, h: 0.68, fill: '#22262c' },+ ],+ ports: bank({ type: 'sfp', count: 12, x: 0.21, w: 0.58, prefix: 'lc' }),+ },++ // --- Storage / power ----------------------------------------------------+ {+ id: 'nas-2u',+ label: 'NAS 2U — 8 bays',+ kind: 'device',+ group: 'Storage',+ uHeight: 2,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: LABEL_LEFT,+ portSize: 'md',+ elements: [+ { kind: 'panel', fill: '#262c35', stroke: '#0d1117' },+ { kind: 'bays', x: 0.32, y: 0.12, w: 0.42, h: 0.76, cols: 4, rows: 2, fill: BLACK_BOX },+ ],+ ports: [+ ...bank({ type: 'rj45', count: 2, x: 0.79, w: 0.12, perRow: 1, prefix: 'eth' }),+ ...bank({ type: 'sfp+', count: 1, x: 0.93, w: 0.05, prefix: 'sfp' }),+ ],+ },+ {+ id: 'ups-2u',+ label: 'UPS 2U',+ kind: 'device',+ group: 'Power',+ uHeight: 2,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: LABEL_LEFT,+ elements: [+ { kind: 'panel', fill: '#1f242c', stroke: '#0d1117' },+ { kind: 'vents', x: 0.34, y: 0.22, w: 0.26, h: 0.56, cols: 10, rows: 3, fill: VENT },+ { kind: 'outlets', x: 0.64, y: 0.28, w: 0.32, h: 0.44, count: 4 },+ ],+ // Outlets are artwork only — power cabling is out of v1.+ ports: [],+ },+ {+ id: 'pdu-1u',+ label: 'PDU 1U — 8 outlets',+ kind: 'device',+ group: 'Power',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ statusLed: true,+ labelBox: LABEL_LEFT,+ elements: [+ { kind: 'panel', fill: '#1f242c', stroke: '#0d1117' },+ { kind: 'outlets', x: 0.32, y: 0.22, w: 0.64, h: 0.56, count: 8 },+ ],+ ports: [],+ },++ // --- Accessories --------------------------------------------------------+ {+ id: 'blank-1u',+ label: 'Blank panel 1U',+ kind: 'accessory',+ group: 'Accessories',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ labelBox: { x: 0.04, w: 0.4 },+ elements: [{ kind: 'panel', fill: '#30363d', stroke: '#0d1117' }],+ ports: [],+ },+ {+ id: 'shelf-1u',+ label: 'Shelf 1U',+ kind: 'accessory',+ group: 'Accessories',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ labelBox: { x: 0.04, w: 0.4 },+ elements: [+ { kind: 'panel', fill: '#3a4048', stroke: '#0d1117' },+ { kind: 'strip', x: 0.46, y: 0.58, w: 0.5, h: 0.26, fill: '#242a31' },+ ],+ ports: [],+ },+ {+ id: 'cable-manager-1u',+ label: 'Cable manager 1U',+ kind: 'accessory',+ group: 'Accessories',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ labelBox: { x: 0.04, w: 0.3 },+ elements: [+ { kind: 'panel', fill: '#2a3038', stroke: '#0d1117' },+ { kind: 'vents', x: 0.36, y: 0.24, w: 0.6, h: 0.52, cols: 8, rows: 1, fill: '#161b22' },+ ],+ ports: [],+ },+]++const BY_ID = new Map(FACEPLATES.map((f) => [f.id, f]))++export function getFaceplate(id: string): FaceplateTemplate {+ return BY_ID.get(id) ?? FACEPLATES[0]+}++/** Templates grouped for the picker, preserving catalog order. */+export function faceplateGroups(): { group: string; items: FaceplateTemplate[] }[] {+ const groups: { group: string; items: FaceplateTemplate[] }[] = []+ for (const plate of FACEPLATES) {+ const existing = groups.find((g) => g.group === plate.group)+ if (existing) existing.items.push(plate)+ else groups.push({ group: plate.group, items: [plate] })+ }+ return groups+}diff --git a/frontend/src/rack/layout.ts b/frontend/src/rack/layout.tsnew file mode 100644index 0000000..eb41566--- /dev/null+++ b/frontend/src/rack/layout.ts@@ -0,0 +1,205 @@+/**+ * Rack geometry: U <-> pixel conversion, column math, occupancy and collision.+ *+ * All U values are 1-based and counted from the bottom rail, whatever the+ * rack's `numbering` setting is — numbering only affects the printed labels.+ */+import { RACK_COLUMNS, type Port, type Rack, type RackDevice } from './types'++/** Pixel height of one rack unit at zoom 1. */+export const U_PX = 24+/** Inner usable width, per rack standard. */+export const INNER_WIDTH_PX: Record<Rack['widthStandard'], number> = {+ '19': 456,+ '10': 264,+}+/** Rail strip width on each side of the usable area. */+export const RAIL_PX = 14+/** U-number gutter drawn outside the left rail. */+export const NUMBER_GUTTER_PX = 22+/** Chassis padding above and below the rails. */+export const FRAME_PAD_PX = 10+/** Name bar drawn inside the chassis, above the rails. */+export const HEADER_PX = 20+/** Y of the first U's top edge — kept inside the node so nothing gets clipped. */+export const INTERIOR_TOP_PX = FRAME_PAD_PX + HEADER_PX++export function innerWidth(rack: Rack): number {+ return INNER_WIDTH_PX[rack.widthStandard]+}++export function columnWidth(rack: Rack): number {+ return innerWidth(rack) / RACK_COLUMNS+}++/** Total node width of a rack, gutter + frame included. */+export function rackWidth(rack: Rack): number {+ const gutter = rack.style.showNumbers ? NUMBER_GUTTER_PX : 0+ return gutter + RAIL_PX * 2 + innerWidth(rack) + FRAME_PAD_PX * 2+}++/** Total node height of a rack. */+export function rackHeight(rack: Rack): number {+ return rack.uHeight * U_PX + INTERIOR_TOP_PX + FRAME_PAD_PX+}++/** X of the usable area's left edge, relative to the rack node. */+export function interiorLeft(rack: Rack): number {+ const gutter = rack.style.showNumbers ? NUMBER_GUTTER_PX : 0+ return gutter + FRAME_PAD_PX + RAIL_PX+}++/** Y of the top edge of a mount, relative to the rack node. */+export function uToY(rack: Rack, uStart: number, uHeight: number): number {+ const topU = uStart + uHeight - 1+ return INTERIOR_TOP_PX + (rack.uHeight - topU) * U_PX+}++/**+ * Which U a pointer sits on. `y` is relative to the rack node.+ * Clamped into [1, uHeight] so a drop slightly off the frame still lands.+ */+export function yToU(rack: Rack, y: number): number {+ const fromTop = Math.floor((y - INTERIOR_TOP_PX) / U_PX)+ const u = rack.uHeight - fromTop+ return clamp(u, 1, rack.uHeight)+}++/** Which column a pointer sits on. `x` is relative to the rack node. */+export function xToCol(rack: Rack, x: number): number {+ const col = Math.floor((x - interiorLeft(rack)) / columnWidth(rack))+ return clamp(col, 0, RACK_COLUMNS - 1)+}++export function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value))+}++/** Printed label for a U, honouring the rack's numbering direction. */+export function uLabel(rack: Rack, u: number): number {+ return rack.numbering === 'bottom-up' ? u : rack.uHeight - u + 1+}++// ---------------------------------------------------------------------------+// Device / port geometry+// ---------------------------------------------------------------------------++export interface Box {+ x: number+ y: number+ width: number+ height: number+}++/** Device box relative to the rack node. */+export function deviceBox(rack: Rack, device: RackDevice): Box {+ const col = columnWidth(rack)+ return {+ x: interiorLeft(rack) + device.colStart * col,+ y: uToY(rack, device.uStart, device.uHeight),+ width: device.colSpan * col,+ height: device.uHeight * U_PX,+ }+}++/** Port centre in canvas coordinates (rack position included). */+export function portPosition(+ rack: Rack,+ device: RackDevice,+ port: Port,+): { x: number; y: number } {+ const box = deviceBox(rack, device)+ return {+ x: rack.position.x + box.x + port.x * box.width,+ y: rack.position.y + box.y + port.y * box.height,+ }+}++// ---------------------------------------------------------------------------+// Occupancy+// ---------------------------------------------------------------------------++export interface Placement {+ uStart: number+ uHeight: number+ colStart: number+ colSpan: number+}++function overlaps(a: Placement, b: Placement): boolean {+ const uOverlap = a.uStart < b.uStart + b.uHeight && b.uStart < a.uStart + a.uHeight+ const colOverlap =+ a.colStart < b.colStart + b.colSpan && b.colStart < a.colStart + a.colSpan+ return uOverlap && colOverlap+}++/** True when the placement fits inside the rack bounds. */+export function isInBounds(rack: Rack, p: Placement): boolean {+ return (+ p.uStart >= 1 &&+ p.uHeight >= 1 &&+ p.uStart + p.uHeight - 1 <= rack.uHeight &&+ p.colStart >= 0 &&+ p.colSpan >= 1 &&+ p.colStart + p.colSpan <= RACK_COLUMNS+ )+}++/**+ * True when the placement fits and collides with nothing.+ * `ignoreId` skips the device being moved, so a no-op drag stays valid.+ */+export function canPlace(+ rack: Rack,+ devices: RackDevice[],+ p: Placement,+ ignoreId?: string,+): boolean {+ if (!isInBounds(rack, p)) return false+ return !devices.some(+ (d) => d.rackId === rack.id && d.id !== ignoreId && overlaps(p, d),+ )+}++/**+ * Nearest valid placement for a drop, searching the target U first and then+ * walking outwards. Returns null when the rack has no room at all.+ */+export function findSlot(+ rack: Rack,+ devices: RackDevice[],+ desired: Placement,+ ignoreId?: string,+): Placement | null {+ const maxU = rack.uHeight - desired.uHeight + 1+ if (maxU < 1) return null++ const colStart = clamp(desired.colStart, 0, RACK_COLUMNS - desired.colSpan)+ const targetU = clamp(desired.uStart, 1, maxU)++ for (let offset = 0; offset < rack.uHeight; offset++) {+ for (const u of offset === 0 ? [targetU] : [targetU - offset, targetU + offset]) {+ if (u < 1 || u > maxU) continue+ const candidate = { ...desired, uStart: u, colStart }+ if (canPlace(rack, devices, candidate, ignoreId)) return candidate+ // Same U may still have room on another column run.+ for (let c = 0; c <= RACK_COLUMNS - desired.colSpan; c++) {+ const shifted = { ...desired, uStart: u, colStart: c }+ if (canPlace(rack, devices, shifted, ignoreId)) return shifted+ }+ }+ }+ return null+}++/** Free U count, counting a U as free only when every column is free. */+export function freeUnits(rack: Rack, devices: RackDevice[]): number {+ let free = 0+ for (let u = 1; u <= rack.uHeight; u++) {+ const busy = devices.some(+ (d) => d.rackId === rack.id && u >= d.uStart && u < d.uStart + d.uHeight,+ )+ if (!busy) free+++ }+ return free+}diff --git a/frontend/src/rack/rackDefaults.ts b/frontend/src/rack/rackDefaults.tsnew file mode 100644index 0000000..e0e51ee--- /dev/null+++ b/frontend/src/rack/rackDefaults.ts@@ -0,0 +1,27 @@+/** Shared defaults, kept out of the store to avoid a cycle with demoData. */+import type { CableType, PortType, RackStyle } from './types'++export const DEFAULT_RACK_STYLE: RackStyle = {+ frame: '#1c2129',+ rail: '#39424f',+ interior: '#0d1117',+ showNumbers: true,+ enclosed: false,+}++export const CABLE_COLORS: Record<CableType, string> = {+ ethernet: '#39d353',+ fiber: '#f0a500',+}++export const CABLE_TYPE_LABELS: Record<CableType, string> = {+ ethernet: 'Ethernet',+ fiber: 'Fiber',+}++/** Cable type implied by the port a patch starts from. */+export const PORT_CABLE_TYPE: Record<PortType, CableType> = {+ rj45: 'ethernet',+ sfp: 'fiber',+ 'sfp+': 'fiber',+}diff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.tsnew file mode 100644index 0000000..88a23aa--- /dev/null+++ b/frontend/src/rack/store.ts@@ -0,0 +1,402 @@+/**+ * Rack canvas prototype store.+ *+ * In-memory only — the prototype deliberately has no API and no persistence.+ * Removing a device from a rack never removes it from the inventory, mirroring+ * how the network canvas already treats inventory nodes.+ */+import { create } from 'zustand'+import { generateUUID } from '@/utils/uuid'+import { getFaceplate } from './faceplates'+import { canPlace, findSlot, type Placement } from './layout'+import { RACK_COLUMNS, type Cable, type CableType, type CableVisibility, type InventoryDevice, type Port, type Rack, type RackDevice, type RackStyle } from './types'+import { demoCables, demoDevices, demoInventory, demoRacks, networkEdgeHints } from './demoData'+import { CABLE_COLORS, DEFAULT_RACK_STYLE, PORT_CABLE_TYPE } from './rackDefaults'++export { CABLE_COLORS, DEFAULT_RACK_STYLE }++/** Draft cable being drawn, port by port. */+interface CableDraft {+ deviceId: string+ portId: string+}++interface RackState {+ racks: Rack[]+ devices: RackDevice[]+ cables: Cable[]+ inventory: InventoryDevice[]++ // UI+ selectedDeviceId: string | null+ selectedRackId: string | null+ hoveredDeviceId: string | null+ cableVisibility: CableVisibility+ /** Port-picking mode: click a port, then another, to create a cable. */+ cableMode: boolean+ cableDraft: CableDraft | null+ cableTypeFilter: CableType | 'all'++ // Racks+ addRack: (partial?: Partial<Rack>) => string+ updateRack: (id: string, patch: Partial<Omit<Rack, 'id'>>) => void+ updateRackStyle: (id: string, patch: Partial<RackStyle>) => void+ moveRack: (id: string, position: { x: number; y: number }) => void+ /** Removes the rack and every device mounted in it (inventory untouched). */+ removeRack: (id: string) => void++ // Devices+ /** Mount an inventory entry. Returns the new device id, or null if no room. */+ mountFromInventory: (inventoryId: string, rackId: string, desired: Partial<Placement>) => string | null+ /** Mount a rack-only accessory (blank panel, shelf…). */+ mountAccessory: (faceplateId: string, rackId: string, desired: Partial<Placement>) => string | null+ moveDevice: (deviceId: string, rackId: string, desired: Placement) => boolean+ updateDevice: (id: string, patch: Partial<Omit<RackDevice, 'id' | 'ports'>>) => void+ /** Unmounts from the rack. The inventory entry survives. */+ unmountDevice: (id: string) => void+ applyFaceplate: (deviceId: string, faceplateId: string) => void++ // Ports+ addPort: (deviceId: string, port: Omit<Port, 'id'>) => void+ updatePort: (deviceId: string, portId: string, patch: Partial<Omit<Port, 'id'>>) => void+ removePort: (deviceId: string, portId: string) => void++ // Cables+ addCable: (+ from: CableDraft,+ to: CableDraft,+ options?: { type?: CableType; color?: string; label?: string },+ ) => string | null+ updateCable: (id: string, patch: Partial<Omit<Cable, 'id'>>) => void+ removeCable: (id: string) => void+ /** One-shot seed from the logical canvas — offered at creation time only. */+ importCablesFromNetwork: () => number+ networkImportDone: boolean++ // UI actions+ selectDevice: (id: string | null) => void+ selectRack: (id: string | null) => void+ hoverDevice: (id: string | null) => void+ setCableVisibility: (v: CableVisibility) => void+ setCableTypeFilter: (t: CableType | 'all') => void+ toggleCableMode: () => void+ pickPort: (deviceId: string, portId: string) => void+ cancelCableDraft: () => void+ reset: () => void+}++function withIds(ports: Omit<Port, 'id'>[]): Port[] {+ return ports.map((p) => ({ ...p, id: generateUUID() }))+}++function initialState() {+ return {+ racks: demoRacks(),+ devices: demoDevices(),+ cables: demoCables(),+ inventory: demoInventory(),+ selectedDeviceId: null,+ selectedRackId: null,+ hoveredDeviceId: null,+ cableVisibility: 'hover' as CableVisibility,+ cableMode: false,+ cableDraft: null,+ cableTypeFilter: 'all' as const,+ networkImportDone: false,+ }+}++export const useRackStore = create<RackState>((set, get) => ({+ ...initialState(),++ // --- Racks --------------------------------------------------------------+ addRack: (partial) => {+ const id = partial?.id ?? generateUUID()+ const count = get().racks.length+ const rack: Rack = {+ id,+ name: `Rack ${count + 1}`,+ uHeight: 24,+ widthStandard: '19',+ numbering: 'bottom-up',+ style: { ...DEFAULT_RACK_STYLE },+ position: { x: 80 + count * 620, y: 60 },+ ...partial,+ }+ set((s) => ({ racks: [...s.racks, rack], selectedRackId: id }))+ return id+ },++ updateRack: (id, patch) =>+ set((s) => ({ racks: s.racks.map((r) => (r.id === id ? { ...r, ...patch } : r)) })),++ updateRackStyle: (id, patch) =>+ set((s) => ({+ racks: s.racks.map((r) => (r.id === id ? { ...r, style: { ...r.style, ...patch } } : r)),+ })),++ moveRack: (id, position) =>+ set((s) => ({ racks: s.racks.map((r) => (r.id === id ? { ...r, position } : r)) })),++ removeRack: (id) =>+ set((s) => {+ const doomed = new Set(s.devices.filter((d) => d.rackId === id).map((d) => d.id))+ return {+ racks: s.racks.filter((r) => r.id !== id),+ devices: s.devices.filter((d) => d.rackId !== id),+ cables: s.cables.filter(+ (c) => !doomed.has(c.from.deviceId) && !doomed.has(c.to.deviceId),+ ),+ selectedRackId: s.selectedRackId === id ? null : s.selectedRackId,+ }+ }),++ // --- Devices ------------------------------------------------------------+ mountFromInventory: (inventoryId, rackId, desired) => {+ const { racks, devices, inventory } = get()+ const rack = racks.find((r) => r.id === rackId)+ const item = inventory.find((i) => i.id === inventoryId)+ if (!rack || !item) return null++ const plate = getFaceplate(item.suggestedFaceplateId)+ const slot = findSlot(rack, devices, {+ uStart: desired.uStart ?? 1,+ uHeight: desired.uHeight ?? plate.uHeight,+ colStart: desired.colStart ?? 0,+ colSpan: desired.colSpan ?? plate.colSpan,+ })+ if (!slot) return null++ const device: RackDevice = {+ id: generateUUID(),+ rackId,+ nodeId: item.id,+ label: item.label,+ status: item.status,+ faceplateId: plate.id,+ ports: withIds(plate.ports),+ ...slot,+ }+ set((s) => ({ devices: [...s.devices, device], selectedDeviceId: device.id }))+ return device.id+ },++ mountAccessory: (faceplateId, rackId, desired) => {+ const { racks, devices } = get()+ const rack = racks.find((r) => r.id === rackId)+ if (!rack) return null++ const plate = getFaceplate(faceplateId)+ const slot = findSlot(rack, devices, {+ uStart: desired.uStart ?? 1,+ uHeight: desired.uHeight ?? plate.uHeight,+ colStart: desired.colStart ?? 0,+ colSpan: desired.colSpan ?? plate.colSpan,+ })+ if (!slot) return null++ const device: RackDevice = {+ id: generateUUID(),+ rackId,+ nodeId: null,+ label: plate.label,+ status: 'unknown',+ faceplateId: plate.id,+ ports: withIds(plate.ports),+ ...slot,+ }+ set((s) => ({ devices: [...s.devices, device], selectedDeviceId: device.id }))+ return device.id+ },++ moveDevice: (deviceId, rackId, desired) => {+ const { racks, devices } = get()+ const rack = racks.find((r) => r.id === rackId)+ if (!rack) return false+ if (!canPlace(rack, devices, desired, deviceId)) return false+ set((s) => ({+ devices: s.devices.map((d) => (d.id === deviceId ? { ...d, rackId, ...desired } : d)),+ }))+ return true+ },++ updateDevice: (id, patch) =>+ set((s) => {+ const device = s.devices.find((d) => d.id === id)+ const rack = device && s.racks.find((r) => r.id === (patch.rackId ?? device.rackId))+ if (!device || !rack) return s+ const next = { ...device, ...patch }+ const geometryChanged =+ next.uStart !== device.uStart ||+ next.uHeight !== device.uHeight ||+ next.colStart !== device.colStart ||+ next.colSpan !== device.colSpan+ if (geometryChanged && !canPlace(rack, s.devices, next, id)) return s+ return { devices: s.devices.map((d) => (d.id === id ? next : d)) }+ }),++ unmountDevice: (id) =>+ set((s) => ({+ devices: s.devices.filter((d) => d.id !== id),+ cables: s.cables.filter((c) => c.from.deviceId !== id && c.to.deviceId !== id),+ selectedDeviceId: s.selectedDeviceId === id ? null : s.selectedDeviceId,+ })),++ applyFaceplate: (deviceId, faceplateId) =>+ set((s) => {+ const device = s.devices.find((d) => d.id === deviceId)+ const rack = device && s.racks.find((r) => r.id === device.rackId)+ if (!device || !rack) return s+ const plate = getFaceplate(faceplateId)+ const resized = {+ ...device,+ faceplateId,+ uHeight: plate.uHeight,+ colSpan: plate.colSpan,+ colStart: Math.min(device.colStart, RACK_COLUMNS - plate.colSpan),+ ports: withIds(plate.ports),+ }+ if (!canPlace(rack, s.devices, resized, deviceId)) {+ // Keep the plate but leave the geometry alone when it no longer fits.+ return {+ devices: s.devices.map((d) =>+ d.id === deviceId ? { ...d, faceplateId, ports: withIds(plate.ports) } : d,+ ),+ }+ }+ return {+ devices: s.devices.map((d) => (d.id === deviceId ? resized : d)),+ cables: s.cables.filter(+ (c) => c.from.deviceId !== deviceId && c.to.deviceId !== deviceId,+ ),+ }+ }),++ // --- Ports --------------------------------------------------------------+ addPort: (deviceId, port) =>+ set((s) => ({+ devices: s.devices.map((d) =>+ d.id === deviceId ? { ...d, ports: [...d.ports, { ...port, id: generateUUID() }] } : d,+ ),+ })),++ updatePort: (deviceId, portId, patch) =>+ set((s) => ({+ devices: s.devices.map((d) =>+ d.id === deviceId+ ? { ...d, ports: d.ports.map((p) => (p.id === portId ? { ...p, ...patch } : p)) }+ : d,+ ),+ })),++ removePort: (deviceId, portId) =>+ set((s) => ({+ devices: s.devices.map((d) =>+ d.id === deviceId ? { ...d, ports: d.ports.filter((p) => p.id !== portId) } : d,+ ),+ cables: s.cables.filter(+ (c) =>+ !(c.from.deviceId === deviceId && c.from.portId === portId) &&+ !(c.to.deviceId === deviceId && c.to.portId === portId),+ ),+ })),++ // --- Cables -------------------------------------------------------------+ addCable: (from, to, options) => {+ const { devices, cables } = get()+ if (from.deviceId === to.deviceId && from.portId === to.portId) return null++ const hasPort = (ref: CableDraft) =>+ devices.some((d) => d.id === ref.deviceId && d.ports.some((p) => p.id === ref.portId))+ if (!hasPort(from) || !hasPort(to)) return null++ // A physical port takes one cable.+ const taken = (ref: CableDraft) =>+ cables.some(+ (c) =>+ (c.from.deviceId === ref.deviceId && c.from.portId === ref.portId) ||+ (c.to.deviceId === ref.deviceId && c.to.portId === ref.portId),+ )+ if (taken(from) || taken(to)) return null++ // Fibre vs copper follows the port the patch starts from.+ const fromPort = devices+ .find((d) => d.id === from.deviceId)!+ .ports.find((p) => p.id === from.portId)!+ const type = options?.type ?? PORT_CABLE_TYPE[fromPort.type]+ const cable: Cable = {+ id: generateUUID(),+ type,+ color: options?.color ?? CABLE_COLORS[type],+ label: options?.label,+ from,+ to,+ }+ set((s) => ({ cables: [...s.cables, cable] }))+ return cable.id+ },++ updateCable: (id, patch) =>+ set((s) => ({ cables: s.cables.map((c) => (c.id === id ? { ...c, ...patch } : c)) })),++ removeCable: (id) => set((s) => ({ cables: s.cables.filter((c) => c.id !== id) })),++ importCablesFromNetwork: () => {+ const { devices, networkImportDone } = get()+ if (networkImportDone) return 0++ let created = 0+ for (const hint of networkEdgeHints()) {+ const a = devices.find((d) => d.nodeId === hint.from)+ const b = devices.find((d) => d.nodeId === hint.to)+ if (!a || !b) continue+ const usedPorts = new Set(+ get().cables.flatMap((c) => [+ `${c.from.deviceId}:${c.from.portId}`,+ `${c.to.deviceId}:${c.to.portId}`,+ ]),+ )+ const freePort = (device: typeof a) =>+ device.ports.find((p) => !usedPorts.has(`${device.id}:${p.id}`))+ const pa = freePort(a)+ const pb = freePort(b)+ if (!pa || !pb) continue+ const id = get().addCable(+ { deviceId: a.id, portId: pa.id },+ { deviceId: b.id, portId: pb.id },+ { type: hint.type, label: hint.label },+ )+ if (id) created+++ }+ set({ networkImportDone: true })+ return created+ },++ // --- UI -----------------------------------------------------------------+ selectDevice: (id) => set({ selectedDeviceId: id, selectedRackId: null }),+ selectRack: (id) => set({ selectedRackId: id, selectedDeviceId: null }),+ hoverDevice: (id) => set({ hoveredDeviceId: id }),+ setCableVisibility: (v) => set({ cableVisibility: v }),+ setCableTypeFilter: (t) => set({ cableTypeFilter: t }),++ toggleCableMode: () =>+ set((s) => ({+ cableMode: !s.cableMode,+ cableDraft: null,+ cableVisibility: !s.cableMode ? 'always' : s.cableVisibility,+ })),++ pickPort: (deviceId, portId) => {+ const { cableDraft } = get()+ if (!cableDraft) {+ set({ cableDraft: { deviceId, portId } })+ return+ }+ get().addCable(cableDraft, { deviceId, portId })+ set({ cableDraft: null })+ },++ cancelCableDraft: () => set({ cableDraft: null }),++ reset: () => set(initialState()),+}))diff --git a/frontend/src/rack/types.ts b/frontend/src/rack/types.tsnew file mode 100644index 0000000..86a7c7f--- /dev/null+++ b/frontend/src/rack/types.ts@@ -0,0 +1,183 @@+/**+ * Rack canvas prototype — domain types.+ *+ * Front-only UX prototype. Nothing here is persisted server-side yet; the+ * shapes are meant to be lifted into `@/types` once the UX is validated.+ */++/** Horizontal grid inside a rack. 12 columns = full width, 6 = half, 4 = third. */+export const RACK_COLUMNS = 12++export type RackWidthStandard = '19' | '10'++/** 1U is at the bottom (real-world rails) or at the top (some diagram tools). */+export type RackNumbering = 'bottom-up' | 'top-down'++export interface RackStyle {+ /** Frame / chassis colour. */+ frame: string+ /** Rail strip colour. */+ rail: string+ /** Empty slot colour, seen between mounted gear. */+ interior: string+ /** Show the U number strip alongside the rails. */+ showNumbers: boolean+ /** Draw side panels (enclosed cabinet) instead of an open frame. */+ enclosed: boolean+}++export interface Rack {+ id: string+ name: string+ /** Total usable height in U. */+ uHeight: number+ widthStandard: RackWidthStandard+ numbering: RackNumbering+ style: RackStyle+ /** Free-text location label ("garage", "office closet"). */+ location?: string+ /** Position on the canvas. */+ position: { x: number; y: number }+}++// ---------------------------------------------------------------------------+// Ports+// ---------------------------------------------------------------------------++/** Only data ports for now — power cabling is out of v1. */+export type PortType = 'rj45' | 'sfp' | 'sfp+'++export interface Port {+ id: string+ label: string+ type: PortType+ /**+ * Position on the faceplate, expressed in faceplate-local unit coordinates+ * (0..1 on both axes) so a port keeps its spot at any zoom level.+ */+ x: number+ y: number+}++// ---------------------------------------------------------------------------+// Faceplates+// ---------------------------------------------------------------------------++export type FaceplateElement =+ | { kind: 'panel'; fill: string; stroke?: string }+ | { kind: 'vents'; x: number; y: number; w: number; h: number; cols: number; rows: number; fill?: string }+ | { kind: 'bays'; x: number; y: number; w: number; h: number; cols: number; rows: number; fill?: string }+ | { kind: 'strip'; x: number; y: number; w: number; h: number; fill: string }+ /**+ * Power outlets. Artwork only — outlets are drawn but never cabled, since+ * power is out of v1.+ */+ | { kind: 'outlets'; x: number; y: number; w: number; h: number; count: number }++export type FaceplateKind = 'device' | 'accessory'++/** Horizontal band reserved for the device name, in unit coordinates. */+export interface LabelBox {+ x: number+ w: number+}++export interface FaceplateTemplate {+ id: string+ label: string+ kind: FaceplateKind+ /** Category used to group the picker list. */+ group: string+ /** Suggested height in U when the template is applied. */+ uHeight: number+ /** Suggested width in rack columns (see RACK_COLUMNS). */+ colSpan: number+ /** Static artwork, drawn in faceplate-local unit coordinates (0..1). */+ elements: FaceplateElement[]+ /** Ports pre-filled on apply. The user can add/remove afterwards. */+ ports: Omit<Port, 'id'>[]+ /**+ * Patch-facing gear (switches, patch panels) always shows its ports; on+ * everything else ports only appear on hover, selection or in patch mode.+ */+ alwaysShowPorts?: boolean+ /** Name band. Ports and artwork must stay clear of it. */+ labelBox: LabelBox+ /** Port artwork size. Dense panels use 'sm'. */+ portSize?: 'sm' | 'md'+ /** Devices get a status LED; accessories do not. */+ statusLed?: boolean+}++// ---------------------------------------------------------------------------+// Mounted devices+// ---------------------------------------------------------------------------++export type DeviceStatus = 'online' | 'offline' | 'unknown'++export interface RackDevice {+ id: string+ rackId: string+ /**+ * Inventory node id this mount represents. Null for accessories (blank+ * panels, shelves) that exist only in the rack view.+ */+ nodeId: string | null+ label: string+ /** Lowest U occupied, 1-based, always counted from the bottom rail. */+ uStart: number+ uHeight: number+ /** Left edge on the 12-column grid, 0-based. */+ colStart: number+ colSpan: number+ faceplateId: string+ /** Overrides the faceplate panel fill when set. */+ color?: string+ status: DeviceStatus+ ports: Port[]+}++// ---------------------------------------------------------------------------+// Cabling+// ---------------------------------------------------------------------------++export type CableType = 'ethernet' | 'fiber'++export interface Cable {+ id: string+ type: CableType+ color: string+ label?: string+ from: { deviceId: string; portId: string }+ to: { deviceId: string; portId: string }+}++/** How the cabling overlay behaves. */+export type CableVisibility = 'hover' | 'always' | 'hidden'++// ---------------------------------------------------------------------------+// Inventory (fake, prototype only)+// ---------------------------------------------------------------------------++/** Subset of the network inventory that can physically live in a rack. */+export type RackableNodeType =+ | 'server'+ | 'proxmox'+ | 'switch'+ | 'router'+ | 'firewall'+ | 'nas'+ | 'ups'+ | 'patch_panel'+ | 'pdu'+ | 'generic'++export interface InventoryDevice {+ id: string+ label: string+ type: RackableNodeType+ ip?: string+ status: DeviceStatus+ /** Faceplate proposed when the device is dropped into a rack. */+ suggestedFaceplateId: string+}