Skip to content

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

feat(inventory): draw and edit a device's rack faceplate from its inventory row

Pouzorf933f774fcaa
diff --git a/backend/app/schemas/scan.py b/backend/app/schemas/scan.py
index d9cb31e..d566f04 100644
--- a/backend/app/schemas/scan.py
+++ b/backend/app/schemas/scan.py
@@ -3,6 +3,11 @@ from typing import Any
from pydantic import BaseModel, field_validator
+from app.schemas.racks import RACK_COLUMNS
+
+# Tallest plate the rack canvas offers; `MAX_RACK_U` on the frontend.
+MAX_PLATE_U = 48
+
class InventoryDeviceResponse(BaseModel):
id: str
@@ -57,6 +62,20 @@ class InventoryDeviceResponse(BaseModel):
node_last_scan: datetime | None = None
node_last_modified: datetime | None = None
node_last_seen: datetime | None = None
+ # Rack modelisation: the front panel this device wears in every rack it is
+ # mounted in. The row owns it — see `RackDevice` and `/api/v1/racks`. All
+ # None/empty for a device that has never been racked or modelled.
+ rack_faceplate_id: str | None = None
+ rack_u_height: int | None = None
+ rack_col_span: int | None = None
+ rack_color: str | None = None
+ rack_ports: list[Any] = []
+
+ @field_validator("rack_ports", mode="before")
+ @classmethod
+ def _coerce_rack_ports(cls, v: Any) -> list[Any]:
+ """NULL on every row written before the column existed."""
+ return v if isinstance(v, list) else []
@field_validator("properties", "discovery_sources", "services", mode="before")
@classmethod
@@ -159,6 +178,36 @@ class InventoryDeviceUpdate(BaseModel):
show_hardware: bool | None = None
check_method: str | None = None
check_target: str | None = None
+ # Rack modelisation, edited from the Device Inventory as well as from a rack
+ # canvas. Sending `rack_faceplate_id` is what models a device; the rest
+ # describes the plate it wears.
+ rack_faceplate_id: str | None = None
+ rack_u_height: int | None = None
+ rack_col_span: int | None = None
+ rack_color: str | None = None
+ rack_ports: list[Any] | None = None
+
+ @field_validator("rack_u_height")
+ @classmethod
+ def _plate_height(cls, v: int | None) -> int | None:
+ if v is not None and not 1 <= v <= MAX_PLATE_U:
+ raise ValueError(f"rack_u_height must be between 1 and {MAX_PLATE_U}")
+ return v
+
+ @field_validator("rack_col_span")
+ @classmethod
+ def _plate_span(cls, v: int | None) -> int | None:
+ if v is not None and not 1 <= v <= RACK_COLUMNS:
+ raise ValueError(f"rack_col_span must be between 1 and {RACK_COLUMNS}")
+ return v
+
+ @field_validator("rack_ports")
+ @classmethod
+ def _plate_ports(cls, v: list[Any] | None) -> list[Any] | None:
+ """A port with no id is not a port: no cable could ever name it."""
+ if v is None:
+ return None
+ return [p for p in v if isinstance(p, dict) and p.get("id")]
class ScanRunResponse(BaseModel):
diff --git a/backend/tests/scan/test_scan_inventory_edit.py b/backend/tests/scan/test_scan_inventory_edit.py
index 4da4eed..c7bc1b4 100644
--- a/backend/tests/scan/test_scan_inventory_edit.py
+++ b/backend/tests/scan/test_scan_inventory_edit.py
@@ -163,3 +163,78 @@ async def test_legacy_row_defaults_are_coerced(client: AsyncClient, headers, db_
assert row["status_live"] == "unknown"
assert row["show_hardware"] is False
assert row["label"] is None
+
+
+async def test_update_pending_edits_the_rack_faceplate(
+ client: AsyncClient, headers, db_session
+):
+ """The front panel is a device fact, so the inventory can edit it too.
+
+ Same row the rack canvas writes on save — a plate edited here is the plate
+ every rack mounting this device draws on its next load.
+ """
+ device = await _seed(db_session, rack_faceplate_id="server-1u", rack_u_height=1)
+ res = await client.patch(
+ f"/api/v1/scan/pending/{device.id}",
+ headers=headers,
+ json={
+ "rack_faceplate_id": "server-2u-bays",
+ "rack_u_height": 2,
+ "rack_col_span": 12,
+ "rack_color": "#ff6e00",
+ "rack_ports": [
+ {"id": "p1", "label": "eth0", "type": "rj45", "x": 0.2, "y": 0.6},
+ # No id: nothing could ever cable it, so it never lands.
+ {"label": "ghost", "type": "rj45", "x": 0.5, "y": 0.5},
+ ],
+ },
+ )
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["rack_faceplate_id"] == "server-2u-bays"
+ assert body["rack_u_height"] == 2
+ assert body["rack_color"] == "#ff6e00"
+ assert [p["id"] for p in body["rack_ports"]] == ["p1"]
+
+
+async def test_update_pending_leaves_an_unsent_faceplate_alone(
+ client: AsyncClient, headers, db_session
+):
+ device = await _seed(db_session, rack_faceplate_id="switch-24", rack_u_height=1)
+ res = await client.patch(
+ f"/api/v1/scan/pending/{device.id}", headers=headers, json={"notes": "x"}
+ )
+ assert res.status_code == 200
+ assert res.json()["rack_faceplate_id"] == "switch-24"
+
+
+ "patch",
+ [
+ {"rack_u_height": 0},
+ {"rack_u_height": 49},
+ {"rack_col_span": 0},
+ {"rack_col_span": 13},
+ ],
+)
+async def test_update_pending_rejects_an_impossible_plate(
+ client: AsyncClient, headers, db_session, patch
+):
+ device = await _seed(db_session)
+ res = await client.patch(
+ f"/api/v1/scan/pending/{device.id}", headers=headers, json=patch
+ )
+ assert res.status_code == 422
+
+
+async def test_inventory_row_reports_no_plate_before_it_is_modelled(
+ client: AsyncClient, headers, db_session
+):
+ await _seed(db_session)
+ rows = (await client.get("/api/v1/scan/pending", headers=headers)).json()
+ assert rows[0]["rack_faceplate_id"] is None
+ assert rows[0]["rack_ports"] == []
diff --git a/frontend/src/components/modals/InventoryDeviceModal.tsx b/frontend/src/components/modals/InventoryDeviceModal.tsx
index 31ac6aa..35b760c 100644
--- a/frontend/src/components/modals/InventoryDeviceModal.tsx
+++ b/frontend/src/components/modals/InventoryDeviceModal.tsx
@@ -28,6 +28,7 @@ import {
Pencil,
Plus,
Radar,
+ Server,
StickyNote,
Tags,
X,
@@ -41,6 +42,8 @@ import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from '@/components/ui/select'
import { PropertyList } from '@/components/common/PropertyList'
+import { DeviceFaceplateEditor } from '@/rack/components/DeviceFaceplateEditor'
+import { emptyRackModel, type DeviceRackModel } from '@/rack/deviceRackModel'
import { ServiceModal } from './ServiceModal'
import { DeepScanModal } from './DeepScanModal'
import { scanApi } from '@/api/client'
@@ -54,7 +57,7 @@ import { DEVICE_TYPE_GROUPS } from '@/utils/nodeTypeGroups'
import { formatRelative, formatTimestamp } from '@/utils/timeFormat'
import { countPorts } from '@/utils/portSpec'
import { serviceToForm, type ServiceFormData, type ServiceSubmitData } from '@/utils/serviceForm'
-import { NODE_TYPE_LABELS, type CheckMethod, type InventoryEntry, type NodeProperty, type NodeType, type ServiceInfo } from '@/types'
+import { NODE_TYPE_LABELS, type CheckMethod, type DeviceStatus, type InventoryEntry, type NodeProperty, type NodeType, type ServiceInfo } from '@/types'
import modalStyles from './modal-interactive.module.css'
// Home is `@/types` now — re-exported because most call sites import it here.
@@ -257,6 +260,26 @@ function toForm(d: InventoryEntry): EditForm {
}
}
+/**
+ * The device's rack modelisation as the editor wants it, or null when the device
+ * has never been racked.
+ *
+ * `rack_faceplate_id` is the flag; the size columns beside it may still be NULL
+ * on a row written before they were recorded, and the plate's own defaults fill
+ * those in.
+ */
+function toRackModel(d: InventoryEntry): DeviceRackModel | null {
+ if (!d.rack_faceplate_id) return null
+ const base = emptyRackModel(d.rack_faceplate_id)
+ return {
+ ...base,
+ uHeight: d.rack_u_height ?? base.uHeight,
+ colSpan: d.rack_col_span ?? base.colSpan,
+ color: d.rack_color ?? null,
+ ports: d.rack_ports ?? [],
+ }
+}
+
const nullable = (v: string) => (v.trim() === '' ? null : v.trim())
const numeric = (v: string) => (v.trim() === '' ? null : Number(v))
@@ -265,6 +288,11 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
const [form, setForm] = useState<EditForm>(() => (device ? toForm(device) : toForm({} as InventoryEntry)))
const [properties, setProperties] = useState<NodeProperty[]>(device?.properties ?? [])
const [services, setServices] = useState<ServiceInfo[]>(device?.services ?? [])
+ // The device's front panel. Null for a device no rack has ever modelled —
+ // there is then nothing to draw and nothing to save.
+ const [rackModel, setRackModel] = useState<DeviceRackModel | null>(
+ device ? toRackModel(device) : null,
+ )
const [svcModal, setSvcModal] = useState<{ index: number | null; form?: ServiceFormData } | null>(null)
const [saving, setSaving] = useState(false)
// The id of the deep rescan this modal started, while it is still running.
@@ -299,6 +327,7 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
setForm(toForm(d))
setProperties(d.properties ?? [])
setServices(d.services ?? [])
+ setRackModel(toRackModel(d))
setEditing(false)
setSvcModal(null)
setRescanRunId(null)
@@ -361,6 +390,12 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
const rackOnly = isRackDevice(device)
const sources = orderedSources(device)
const live = LIVE_META[device.status_live ?? 'unknown'] ?? LIVE_META.unknown
+ // The faceplate's LED speaks the rack's three states, not the checker's four:
+ // "checking" is a moment, not a colour a plate carries.
+ const plateStatus: DeviceStatus =
+ device.status_live === 'online' || device.status_live === 'offline'
+ ? device.status_live
+ : 'unknown'
const titleLabel = device.label ?? device.friendly_name ?? device.hostname ?? device.ip ?? device.ieee_address ?? 'Pending device'
const set = <K extends keyof EditForm>(key: K, value: EditForm[K]) => setForm((f) => ({ ...f, [key]: value }))
@@ -374,6 +409,7 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
setForm(toForm(device))
setProperties(device.properties ?? [])
setServices(device.services ?? [])
+ setRackModel(toRackModel(device))
}
const handleRescan = async (ports: string) => {
@@ -442,6 +478,17 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
check_target: nullable(form.check_target),
properties,
services,
+ // Only for a device that has a front panel: sending these for one that
+ // has none would model every device the user ever edits.
+ ...(rackModel
+ ? {
+ rack_faceplate_id: rackModel.faceplateId,
+ rack_u_height: rackModel.uHeight,
+ rack_col_span: rackModel.colSpan,
+ rack_color: rackModel.color,
+ rack_ports: rackModel.ports,
+ }
+ : {}),
})
// Push the row straight into the canvas on screen. Its nodes carry a copy
// of these facts, loaded before this edit — left stale, the next canvas
@@ -827,6 +874,24 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn
</div>
</div>
)}
+ {/* Full width, under the columns: the plate is drawn at rack
+ proportions and needs the room. Only a device some rack has
+ modelled has one — the row owns it, so it is edited here as well as
+ from a mount. */}
+ {rackModel && (
+ <div className="mt-4">
+ <Section title="Rack faceplate" icon={Server}>
+ <DeviceFaceplateEditor
+ value={rackModel}
+ label={device.label || device.hostname || device.ip || 'device'}
+ status={plateStatus}
+ editable={editing}
+ onChange={setRackModel}
+ />
+ </Section>
+ </div>
+ )}
+
</div>
{/* ── Footer: lifecycle in view, form controls in edit ── */}
diff --git a/frontend/src/components/modals/__tests__/InventoryDeviceModalFaceplate.test.tsx b/frontend/src/components/modals/__tests__/InventoryDeviceModalFaceplate.test.tsx
new file mode 100644
index 0000000..b924e3b
--- /dev/null
+++ b/frontend/src/components/modals/__tests__/InventoryDeviceModalFaceplate.test.tsx
@@ -0,0 +1,131 @@
+/**
+ * The rack faceplate inside the Device Inventory.
+ *
+ * The inventory row owns the front panel, so the detail modal draws it and edits
+ * it — a device modelled on one rack canvas is modelled everywhere, and does not
+ * have to be racked again to have its ports moved.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { InventoryDeviceModal } from '../InventoryDeviceModal'
+import type { InventoryEntry } from '@/types'
+
+const mockUpdatePending = vi.fn()
+
+vi.mock('@/api/client', () => ({
+ scanApi: {
+ updatePending: (...a: unknown[]) => mockUpdatePending(...a),
+ },
+}))
+
+vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
+
+const PORTS = [
+ { id: 'p1', label: 'eth0', type: 'rj45' as const, x: 0.2, y: 0.5 },
+ { id: 'p2', label: 'eth1', type: 'rj45' as const, x: 0.6, y: 0.5 },
+]
+
+function makeDevice(overrides: Partial<InventoryEntry> = {}): InventoryEntry {
+ return {
+ id: 'dev-1',
+ ip: '192.168.1.100',
+ mac: 'aa:bb:cc:dd:ee:ff',
+ hostname: 'sw.local',
+ os: null,
+ services: [],
+ suggested_type: 'switch',
+ status: 'approved',
+ status_live: 'online',
+ discovered_at: '2024-01-15T10:30:00Z',
+ ...overrides,
+ }
+}
+
+const modelled = (over: Partial<InventoryEntry> = {}) =>
+ makeDevice({
+ rack_faceplate_id: 'switch-24',
+ rack_u_height: 1,
+ rack_col_span: 12,
+ rack_color: null,
+ rack_ports: PORTS,
+ ...over,
+ })
+
+const noop = { onClose: vi.fn(), onApprove: vi.fn(), onHide: vi.fn(), onIgnore: vi.fn() }
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mockUpdatePending.mockResolvedValue({ data: modelled() })
+})
+
+const edit = () => fireEvent.click(screen.getByRole('button', { name: /Edit/ }))
+
+describe('InventoryDeviceModal — rack faceplate', () => {
+ it('draws the plate of a device some rack has modelled', () => {
+ render(<InventoryDeviceModal {...noop} device={modelled()} />)
+
+ expect(screen.getByText('Rack faceplate')).toBeInTheDocument()
+ expect(screen.getByTestId('faceplate-stage')).toBeInTheDocument()
+ expect(screen.getByText(/Switch 24 ports.*1U.*2 ports/)).toBeInTheDocument()
+ })
+
+ it('shows no faceplate section for a device no rack has modelled', () => {
+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)
+
+ expect(screen.queryByText('Rack faceplate')).toBeNull()
+ expect(screen.queryByTestId('faceplate-stage')).toBeNull()
+ })
+
+ it('leaves the plate read-only until the modal is in edit mode', () => {
+ render(<InventoryDeviceModal {...noop} device={modelled()} />)
+
+ expect(screen.queryByRole('button', { name: 'Position ports' })).toBeNull()
+ edit()
+ expect(screen.getByRole('button', { name: 'Position ports' })).toBeInTheDocument()
+ expect(screen.getByLabelText('Port eth0 label')).toBeInTheDocument()
+ })
+
+ it('places a port from the inventory, without racking the device first', () => {
+ render(<InventoryDeviceModal {...noop} device={modelled()} />)
+ edit()
+ fireEvent.click(screen.getByRole('button', { name: 'Position ports' }))
+
+ const handle = screen.getByRole('button', { name: 'Move port eth0' })
+ expect(handle).toBeInTheDocument()
+ fireEvent.keyDown(handle, { key: 'ArrowRight' })
+ // The handle follows the port it moved, so the plate and the data agree.
+ expect(Number.parseFloat(handle.style.left)).toBeCloseTo(21)
+ })
+
+ it('saves the edited plate back onto the inventory row', async () => {
+ render(<InventoryDeviceModal {...noop} device={modelled()} />)
+ edit()
+ fireEvent.change(screen.getByLabelText('Port eth1 label'), { target: { value: 'uplink' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+
+ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())
+ const body = mockUpdatePending.mock.calls[0][1]
+ expect(body.rack_faceplate_id).toBe('switch-24')
+ expect(body.rack_u_height).toBe(1)
+ expect(body.rack_ports.map((p: { label: string }) => p.label)).toEqual(['eth0', 'uplink'])
+ })
+
+ it('sends no plate for a device that has none, rather than modelling it', async () => {
+ mockUpdatePending.mockResolvedValue({ data: makeDevice() })
+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)
+ edit()
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+
+ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())
+ expect(mockUpdatePending.mock.calls[0][1]).not.toHaveProperty('rack_faceplate_id')
+ })
+
+ it('drops an unsaved plate edit when the edit is cancelled', () => {
+ render(<InventoryDeviceModal {...noop} device={modelled()} />)
+ edit()
+ fireEvent.click(screen.getByLabelText('Remove port eth1'))
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ expect(screen.getByText(/2 ports/)).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.md
index c76554a..b62efe3 100644
--- a/frontend/src/rack/README.md
+++ b/frontend/src/rack/README.md
@@ -23,7 +23,7 @@ Create one from **New Canvas → Kind → Rack**.
| Status | A mount stores a `MountStatus`: `online` / `offline` / `unknown` pinned by hand, or `auto` — "check device", i.e. follow the status check already configured on the matching canvas node (ping, http, ssh…). The rack runs no checker of its own; `auto` resolves through the inventory entry's `node_status` (`resolveDeviceStatus` in `deviceStatus.ts`) and falls back to `unknown` when nothing is behind it. The Status select offers `auto` only when the mount — or the entry being picked — resolves to a node, and drops back to `unknown` when that link is lost. `useAutoStatusRefresh` polls the inventory every 60 s while at least one mount is on `auto`, and only then; the refresh writes inventory only, so autosave stays quiet. |
| 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. `suggestFaceplate()` picks one from the device's discovery type. Chosen from `FaceplatePicker` — a visual catalog, not a `<select>`: every template is drawn with the canvas renderer at its real relative width and U height, grouped, searchable, and filterable by `kind` (accessories are offered only to accessories). |
| 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, positioned by hand on the plate (`portLayout.ts` + `PortPositionEditor`). Accessories carry none. Power outlets are artwork, never a cable endpoint. |
-| Port ownership | The **Device Inventory row owns the rack modelisation** — faceplate, U height, column span, colour override and the port list, positions included — not the mount. A device therefore wears the same front panel in every rack. Only placement (`rackId`, `uStart`, `colStart`), pinned status and label stay per canvas. Columns `device_inventory.rack_*`; `POST /racks/save` writes them through and `GET /racks` overlays them on load. Size is applied only where it still fits the mount's rack — geometry is global, a rack is not. Standalone has no inventory row to hang this on, so ports stay per mount there. |
+| Port ownership | The **Device Inventory row owns the rack modelisation** — faceplate, U height, column span, colour override and the port list, positions included — not the mount. A device therefore wears the same front panel in every rack. Only placement (`rackId`, `uStart`, `colStart`), pinned status and label stay per canvas. Columns `device_inventory.rack_*`; `POST /racks/save` writes them through and `GET /racks` overlays them on load. Size is applied only where it still fits the mount's rack — geometry is global, a rack is not. Standalone has no inventory row to hang this on, so ports stay per mount there. Editable from both ends: a mount in `RackDeviceModal`, or the row itself in the Device Inventory detail modal (`DeviceFaceplateEditor`, shown only for a device already modelled), which writes the same columns through `PATCH /scan/pending/{id}`. |
| 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. `labelBox.y` (default 0.5) moves the name band *and* the LED off mid-height — desktop NAS boxes are drive doors over a badge strip at the bottom. |
| 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. |
diff --git a/frontend/src/rack/__tests__/DeviceFaceplateEditor.test.tsx b/frontend/src/rack/__tests__/DeviceFaceplateEditor.test.tsx
new file mode 100644
index 0000000..6f372db
--- /dev/null
+++ b/frontend/src/rack/__tests__/DeviceFaceplateEditor.test.tsx
@@ -0,0 +1,90 @@
+/**
+ * The device's front panel, edited away from any rack — the editor the Device
+ * Inventory embeds.
+ */
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import { DeviceFaceplateEditor } from '../components/DeviceFaceplateEditor'
+import { emptyRackModel, type DeviceRackModel } from '../deviceRackModel'
+import { getFaceplate } from '../faceplates'
+import { RACK_COLUMNS } from '@/types'
+
+const model: DeviceRackModel = {
+ faceplateId: 'switch-24',
+ uHeight: 1,
+ colSpan: RACK_COLUMNS,
+ color: null,
+ ports: [{ id: 'p1', label: 'eth0', type: 'rj45', x: 0.2, y: 0.5 }],
+}
+
+function draw(over: Partial<React.ComponentProps<typeof DeviceFaceplateEditor>> = {}) {
+ const onChange = vi.fn()
+ render(
+ <DeviceFaceplateEditor
+ value={model}
+ label="sw-01"
+ status="online"
+ editable
+ onChange={onChange}
+ {...over}
+ />,
+ )
+ return { onChange }
+}
+
+describe('emptyRackModel', () => {
+ it('takes its size from the plate, so a new model is never 0U', () => {
+ const plate = getFaceplate('server-2u-bays')
+ expect(emptyRackModel('server-2u-bays')).toEqual({
+ faceplateId: 'server-2u-bays',
+ uHeight: plate.uHeight,
+ colSpan: plate.colSpan,
+ color: null,
+ ports: [],
+ })
+ })
+})
+
+describe('DeviceFaceplateEditor', () => {
+ it('offers nothing to edit in read-only mode, only the plate and its summary', () => {
+ draw({ editable: false })
+
+ expect(screen.getByTestId('faceplate-stage')).toBeInTheDocument()
+ expect(screen.queryByLabelText('Faceplate')).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Add port' })).toBeNull()
+ expect(screen.getByText(/Switch 24 ports.*1U.*1 port$/)).toBeInTheDocument()
+ })
+
+ it('edits the ports through the same list the rack modal uses', () => {
+ const { onChange } = draw()
+ fireEvent.change(screen.getByLabelText('Port eth0 label'), { target: { value: 'wan' } })
+
+ expect(onChange.mock.calls.at(-1)![0].ports[0].label).toBe('wan')
+ })
+
+ it('reseeds the size from the plate that was picked, and keeps the ports', () => {
+ const { onChange } = draw()
+ fireEvent.click(screen.getByLabelText('Faceplate'))
+ fireEvent.click(screen.getByRole('button', { name: /Server 2U — 8 bays/ }))
+
+ const next = onChange.mock.calls.at(-1)![0] as DeviceRackModel
+ expect(next.faceplateId).toBe('server-2u-bays')
+ expect(next.uHeight).toBe(getFaceplate('server-2u-bays').uHeight)
+ // The ports belong to the device, not to the plate it happens to wear.
+ expect(next.ports).toEqual(model.ports)
+ })
+
+ it('clamps a typed height to what a rack can hold', () => {
+ const { onChange } = draw()
+ fireEvent.change(screen.getByLabelText('Height (U)'), { target: { value: '999' } })
+
+ expect(onChange.mock.calls.at(-1)![0].uHeight).toBe(48)
+ })
+
+ it('clears the colour override rather than writing a default hex', () => {
+ const { onChange } = draw({ value: { ...model, color: '#ff6e00' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }))
+
+ expect(onChange.mock.calls.at(-1)![0].color).toBeNull()
+ })
+})
diff --git a/frontend/src/rack/components/DeviceFaceplateEditor.tsx b/frontend/src/rack/components/DeviceFaceplateEditor.tsx
new file mode 100644
index 0000000..645b161
--- /dev/null
+++ b/frontend/src/rack/components/DeviceFaceplateEditor.tsx
@@ -0,0 +1,165 @@
+/**
+ * A device's rack modelisation, edited away from any rack.
+ *
+ * The Device Inventory row owns the front panel — plate, size, colour and ports
+ * — so it has to be editable from the inventory itself, not only from a mount on
+ * a rack canvas. Same plate catalog, same port list, same placement mode as
+ * `RackDeviceModal`; what is missing here is everything that belongs to a mount
+ * (which rack, which U, which column), because a device has none of that until
+ * it is racked.
+ */
+import { useState } from 'react'
+import { Label } from '@/components/ui/label'
+import { FaceplatePicker } from './FaceplatePicker'
+import { PortListEditor } from './PortListEditor'
+import { PortPositionEditor } from './PortPositionEditor'
+import { getFaceplate } from '../faceplates'
+import { MAX_RACK_U } from '../rackDefaults'
+import type { DeviceRackModel } from '../deviceRackModel'
+import { RACK_COLUMNS, type DeviceStatus } from '@/types'
+
+const inputClass =
+ 'w-full rounded border border-[#30363d] bg-[#21262d] px-2 py-1 text-sm text-foreground outline-none focus:border-[#00d4ff]'
+const fieldLabel = 'text-xs text-muted-foreground'
+
+const DEFAULT_COLOR = '#2b323c'
+
+interface Props {
+ value: DeviceRackModel
+ /** Printed on the plate, like the mount's label on a rack. */
+ label: string
+ status: DeviceStatus
+ /** Read-only outside the detail modal's edit mode. */
+ editable: boolean
+ onChange: (model: DeviceRackModel) => void
+}
+
+export function DeviceFaceplateEditor({ value, label, status, editable, onChange }: Props) {
+ const [pickerOpen, setPickerOpen] = useState(false)
+ const [positioning, setPositioning] = useState(false)
+ const [selectedPortId, setSelectedPortId] = useState<string | null>(null)
+
+ const plate = getFaceplate(value.faceplateId)
+
+ /** Swapping the plate reseeds its size; the ports stay, they are the device's. */
+ const pickFaceplate = (id: string) => {
+ const picked = getFaceplate(id)
+ onChange({ ...value, faceplateId: picked.id, uHeight: picked.uHeight, colSpan: picked.colSpan })
+ setPickerOpen(false)
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ {editable && (
+ <>
+ <div className="flex flex-col gap-1.5">
+ <Label className={fieldLabel}>Faceplate</Label>
+ <button
+ type="button"
+ aria-label="Faceplate"
+ data-faceplate={value.faceplateId}
+ onClick={() => setPickerOpen(true)}
+ className="flex cursor-pointer flex-col items-start gap-0.5 rounded border border-[#30363d] bg-[#21262d] px-2 py-1.5 text-left hover:border-[#00d4ff]"
+ >
+ <span className="text-sm">{plate.label}</span>
+ <span className="text-[11px] text-[#00d4ff]">Browse faceplates…</span>
+ </button>
+ <FaceplatePicker
+ open={pickerOpen}
+ value={value.faceplateId}
+ onPick={pickFaceplate}
+ onClose={() => setPickerOpen(false)}
+ />
+ </div>
+
+ <div className="grid grid-cols-3 gap-3">
+ <div className="flex flex-col gap-1.5">
+ <Label className={fieldLabel}>Height (U)</Label>
+ <input
+ type="number"
+ min={1}
+ max={MAX_RACK_U}
+ className={inputClass}
+ aria-label="Height (U)"
+ value={value.uHeight}
+ onChange={(e) =>
+ onChange({
+ ...value,
+ // The browser does not enforce min/max on a typed value, and
+ // a 0U plate draws as nothing at all.
+ uHeight: Math.min(MAX_RACK_U, Math.max(1, Number(e.target.value) || 1)),
+ })
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <Label className={fieldLabel}>{`Width (/${RACK_COLUMNS})`}</Label>
+ <select
+ className={inputClass}
+ aria-label="Width"
+ value={value.colSpan}
+ onChange={(e) => onChange({ ...value, 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>
+ <option value={RACK_COLUMNS / 6}>Sixth width</option>
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <Label className={fieldLabel}>Colour override</Label>
+ <div className="flex items-center gap-2">
+ <input
+ type="color"
+ aria-label="Colour override"
+ className="h-8 flex-1 cursor-pointer rounded border border-[#30363d] bg-[#21262d]"
+ value={value.color ?? DEFAULT_COLOR}
+ onChange={(e) => onChange({ ...value, color: e.target.value })}
+ />
+ <button
+ type="button"
+ className="cursor-pointer rounded border border-[#30363d] px-2 py-1 text-[11px] text-muted-foreground hover:text-foreground"
+ onClick={() => onChange({ ...value, color: null })}
+ >
+ Reset
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <PortListEditor
+ ports={value.ports}
+ onChange={(ports) => onChange({ ...value, ports })}
+ positioning={positioning}
+ onPositioningChange={setPositioning}
+ selectedPortId={selectedPortId}
+ onSelect={setSelectedPortId}
+ />
+ </>
+ )}
+
+ <div className="flex flex-col items-center gap-2 rounded border border-[#30363d] bg-[#0d1117] p-3">
+ <PortPositionEditor
+ faceplateId={value.faceplateId}
+ label={label}
+ status={status}
+ ports={value.ports}
+ uHeight={value.uHeight}
+ colSpan={value.colSpan}
+ color={value.color ?? undefined}
+ interactive={editable && positioning}
+ selectedPortId={selectedPortId}
+ onSelect={setSelectedPortId}
+ onChange={(ports) => onChange({ ...value, ports })}
+ />
+ {!editable && (
+ <p className="text-[11px] text-muted-foreground">
+ {plate.label} · {value.uHeight}U · {value.ports.length} port
+ {value.ports.length === 1 ? '' : 's'}
+ </p>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/rack/components/PortListEditor.tsx b/frontend/src/rack/components/PortListEditor.tsx
new file mode 100644
index 0000000..e358766
--- /dev/null
+++ b/frontend/src/rack/components/PortListEditor.tsx
@@ -0,0 +1,134 @@
+/**
+ * The port list of one faceplate: name, type, remove, and the switch into
+ * placement mode.
+ *
+ * Shared by the rack canvas' device modal and the Device Inventory detail modal
+ * — a device's ports belong to its inventory row, so both edit the same list and
+ * must offer the same editor.
+ */
+import { Move, Plus, X } from 'lucide-react'
+import { Label } from '@/components/ui/label'
+import { nextPortSpot } from '../portLayout'
+import { generateUUID } from '@/utils/uuid'
+import type { Port, PortType } from '@/types'
+
+const inputBase =
+ 'rounded border border-[#30363d] bg-[#21262d] px-2 py-1 text-sm text-foreground outline-none focus:border-[#00d4ff]'
+
+const PORT_TYPES: PortType[] = ['rj45', 'sfp', 'sfp+']
+
+interface Props {
+ ports: Port[]
+ onChange: (ports: Port[]) => void
+ /** Placement mode, owned by the parent: the plate it drives lives there. */
+ positioning: boolean
+ onPositioningChange: (positioning: boolean) => void
+ /** Highlighted port, shared with the plate. */
+ selectedPortId: string | null
+ onSelect: (portId: string | null) => void
+}
+
+export function PortListEditor({
+ ports,
+ onChange,
+ positioning,
+ onPositioningChange,
+ selectedPortId,
+ onSelect,
+}: Props) {
+ const patch = (portId: string, fields: Partial<Port>) =>
+ onChange(ports.map((p) => (p.id === portId ? { ...p, ...fields } : p)))
+
+ const add = () => {
+ // A new port continues the last row instead of landing on the middle of the
+ // plate, under the one before it.
+ const port: Port = {
+ id: generateUUID(),
+ label: `p${ports.length + 1}`,
+ type: 'rj45',
+ ...nextPortSpot(ports),
+ }
+ onSelect(port.id)
+ onChange([...ports, port])
+ }
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <Label className="text-xs text-muted-foreground">Ports ({ports.length})</Label>
+ <div className="flex items-center gap-1">
+ {/* Placing a port is a mode, not a field: the plate takes the pointer
+ while it is on. */}
+ <button
+ type="button"
+ aria-label="Position ports"
+ aria-pressed={positioning}
+ disabled={ports.length === 0}
+ className={`cursor-pointer rounded border px-2 py-0.5 text-xs disabled:cursor-not-allowed disabled:opacity-40 ${
+ positioning
+ ? 'border-[#00d4ff] text-[#00d4ff]'
+ : 'border-[#30363d] hover:border-[#00d4ff]'
+ }`}
+ onClick={() => onPositioningChange(!positioning)}
+ >
+ <Move size={12} className="inline" /> Position
+ </button>
+ <button
+ type="button"
+ aria-label="Add port"
+ className="cursor-pointer rounded border border-[#30363d] px-2 py-0.5 text-xs hover:border-[#00d4ff]"
+ onClick={add}
+ >
+ <Plus size={12} className="inline" /> Add
+ </button>
+ </div>
+ </div>
+ <ul className="max-h-[26rem] space-y-1 overflow-y-auto">
+ {ports.map((port) => (
+ <li
+ key={port.id}
+ // Editing a port's name highlights it on the plate, so the list and
+ // the drawing never disagree about which port is which.
+ onFocusCapture={() => onSelect(port.id)}
+ className={`flex items-center gap-1 rounded border px-1 py-1 ${
+ selectedPortId === port.id ? 'border-[#00d4ff] bg-[#00d4ff0f]' : 'border-transparent'
+ }`}
+ >
+ <input
+ // Without min-w-0 the flex row lets the type select win the space
+ // and the name field collapses into an unlabelled box.
+ className={`${inputBase} min-w-0 flex-1`}
+ aria-label={`Port ${port.label} label`}
+ placeholder="Port name"
+ value={port.label}
+ onChange={(e) => patch(port.id, { label: e.target.value })}
+ />
+ <select
+ className={`${inputBase} w-24 shrink-0`}
+ aria-label={`Port ${port.label} type`}
+ value={port.type}
+ onChange={(e) => patch(port.id, { type: e.target.value as PortType })}
+ >
+ {PORT_TYPES.map((t) => (
+ <option key={t} value={t}>
+ {t}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ aria-label={`Remove port ${port.label}`}
+ className="cursor-pointer px-1 text-xs text-muted-foreground hover:text-[#f85149]"
+ onClick={() => onChange(ports.filter((p) => p.id !== port.id))}
+ >
+ <X size={12} />
+ </button>
+ </li>
+ ))}
+ {ports.length === 0 && (
+ <li className="text-[11px] text-muted-foreground">No port on this plate.</li>
+ )}
+ </ul>
+ </div>
+ )
+}
diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsx
index 8db83e2..111bc62 100644
--- a/frontend/src/rack/components/RackDeviceModal.tsx
+++ b/frontend/src/rack/components/RackDeviceModal.tsx
@@ -11,7 +11,6 @@
* cable managers — are rack-only and never touch the inventory.
*/
import { useEffect, useMemo, useState } from 'react'
-import { Move, Plus, X } from 'lucide-react'
import { toast } from 'sonner'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
@@ -20,12 +19,12 @@ import { DeviceInventoryModal } from '@/components/modals/DeviceInventoryModal'
import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
import { useRackStore } from '../store'
import { FaceplatePicker } from './FaceplatePicker'
+import { PortListEditor } from './PortListEditor'
import { PortPositionEditor } from './PortPositionEditor'
import { LinkedDevicePanel } from './LinkedDevicePanel'
import { DevicePickerModal } from './DevicePickerModal'
import { deviceTypeForFaceplate, getFaceplate } from '../faceplates'
import { findSlot } from '../layout'
-import { nextPortSpot } from '../portLayout'
import { canFollowNode, resolveDeviceStatus } from '../deviceStatus'
import { generateUUID } from '@/utils/uuid'
import {
@@ -33,7 +32,6 @@ import {
type InventoryDevice,
type MountStatus,
type Port,
- type PortType,
} from '@/types'
const DEFAULT_COLOR = '#2b323c'
@@ -618,108 +616,14 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
<div className="flex flex-col gap-3">
{!isAccessory && (
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <Label className={fieldLabel}>Ports ({ports.length})</Label>
- <div className="flex items-center gap-1">
- {/* Placing a port is a mode, not a field: the plate below
- takes the pointer while it is on. */}
- <button
- type="button"
- aria-label="Position ports"
- aria-pressed={positioning}
- disabled={ports.length === 0}
- className={`cursor-pointer rounded border px-2 py-0.5 text-xs disabled:cursor-not-allowed disabled:opacity-40 ${
- positioning
- ? 'border-[#00d4ff] text-[#00d4ff]'
- : 'border-[#30363d] hover:border-[#00d4ff]'
- }`}
- onClick={() => setPositioning((on) => !on)}
- >
- <Move size={12} className="inline" /> Position
- </button>
- <button
- type="button"
- aria-label="Add port"
- className="cursor-pointer rounded border border-[#30363d] px-2 py-0.5 text-xs hover:border-[#00d4ff]"
- onClick={() =>
- setLocalPorts((p) => {
- // A new port continues the last row instead of landing
- // on the middle of the plate under the previous one.
- const port: Port = {
- id: generateUUID(),
- label: `p${p.length + 1}`,
- type: 'rj45',
- ...nextPortSpot(p),
- }
- setSelectedPortId(port.id)
- return [...p, port]
- })
- }
- >
- <Plus size={12} className="inline" /> Add
- </button>
- </div>
- </div>
- <ul className="max-h-[26rem] space-y-1 overflow-y-auto">
- {ports.map((port) => (
- <li
- key={port.id}
- // Editing a port's name highlights it on the plate, so the
- // list and the drawing never disagree about which is which.
- onFocusCapture={() => setSelectedPortId(port.id)}
- className={`flex items-center gap-1 rounded border px-1 py-1 ${
- selectedPortId === port.id
- ? 'border-[#00d4ff] bg-[#00d4ff0f]'
- : 'border-transparent'
- }`}
- >
- <input
- // `inputClass` is w-full: without min-w-0 the flex row lets the
- // type select win the space and the name field collapses to a box.
- className={`${inputBase} min-w-0 flex-1`}
- aria-label={`Port ${port.label} label`}
- placeholder="Port name"
- value={port.label}
- onChange={(e) =>
- setLocalPorts((list) =>
- list.map((p) => (p.id === port.id ? { ...p, label: e.target.value } : p)),
- )
- }
- />
- <select
- className={`${inputBase} w-24 shrink-0`}
- aria-label={`Port ${port.label} type`}
- value={port.type}
- onChange={(e) =>
- setLocalPorts((list) =>
- list.map((p) =>
- p.id === port.id ? { ...p, type: e.target.value as PortType } : p,
- ),
- )
- }
- >
- {(['rj45', 'sfp', 'sfp+'] as PortType[]).map((t) => (
- <option key={t} value={t}>
- {t}
- </option>
- ))}
- </select>
- <button
- type="button"
- aria-label={`Remove port ${port.label}`}
- className="cursor-pointer px-1 text-xs text-muted-foreground hover:text-[#f85149]"
- onClick={() => setLocalPorts((list) => list.filter((p) => p.id !== port.id))}
- >
- <X size={12} />
- </button>
- </li>
- ))}
- {ports.length === 0 && (
- <li className="text-[11px] text-muted-foreground">No port on this plate.</li>
- )}
- </ul>
- </div>
+ <PortListEditor
+ ports={ports}
+ onChange={setLocalPorts}
+ positioning={positioning}
+ onPositioningChange={setPositioning}
+ selectedPortId={selectedPortId}
+ onSelect={setSelectedPortId}
+ />
)}
{/* The column below the port list used to be dead space. A mount
diff --git a/frontend/src/rack/deviceRackModel.ts b/frontend/src/rack/deviceRackModel.ts
new file mode 100644
index 0000000..e0af3d6
--- /dev/null
+++ b/frontend/src/rack/deviceRackModel.ts
@@ -0,0 +1,29 @@
+/**
+ * The front panel a device wears in every rack.
+ *
+ * Mirrors `RackModel` on the wire (`device_inventory.rack_*`), with the size
+ * resolved: an unmodelled row carries nulls, and a caller fills them from the
+ * plate before handing the draft to an editor.
+ */
+import { getFaceplate } from './faceplates'
+import type { Port } from '@/types'
+
+export interface DeviceRackModel {
+ faceplateId: string
+ uHeight: number
+ colSpan: number
+ color: string | null
+ ports: Port[]
+}
+
+/** The model a device that has never been racked starts from. */
+export function emptyRackModel(faceplateId: string): DeviceRackModel {
+ const plate = getFaceplate(faceplateId)
+ return {
+ faceplateId: plate.id,
+ uHeight: plate.uHeight,
+ colSpan: plate.colSpan,
+ color: null,
+ ports: [],
+ }
+}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 19d4bad..912292d 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -1,4 +1,7 @@
export * from './rack'
+// The rack's `Port` describes a socket on a faceplate; an inventory row carries
+// the plate's ports, so the type is needed here as well as re-exported.
+import type { Port } from './rack'
/**
* `network` and `electrical` render the same React Flow canvas and differ only
@@ -175,6 +178,16 @@ export interface InventoryEntry {
node_last_scan?: string | null
node_last_modified?: string | null
node_last_seen?: string | null
+ /**
+ * Rack modelisation — the front panel this device wears in every rack it is
+ * mounted in. The inventory row owns it; a mount only places it. Null/absent
+ * until the device has been racked or modelled once.
+ */
+ rack_faceplate_id?: string | null
+ rack_u_height?: number | null
+ rack_col_span?: number | null
+ rack_color?: string | null
+ rack_ports?: Port[]
}
export interface NodeData extends Record<string, unknown> {