Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(rack): let the inventory own the front panel, and place ports by hand
Pouzorb658a68a09f3
diff --git a/backend/app/api/routes/racks.py b/backend/app/api/routes/racks.pyindex 03184cc..1dd3df9 100644--- a/backend/app/api/routes/racks.py+++ b/backend/app/api/routes/racks.py@@ -9,6 +9,7 @@ from app.api.deps import get_current_userfrom app.db.database import get_dbfrom app.db.models import CanvasState, Design, InventoryDevice, Node, Rack, RackCable, RackDevicefrom app.schemas.racks import (+ RACK_COLUMNS,RackCableResponse,RackDeviceResponse,RackInventoryItem,@@ -124,6 +125,51 @@ def _ip_tokens(ip: str | None) -> list[str]:return [t.strip() for t in ip.split(",") if t.strip()] if ip else []+def _rack_model(device: InventoryDevice) -> dict[str, Any] | None:+ """The rack modelisation the inventory row owns, or None when never modelled.++ `rack_faceplate_id` is the flag: a device that has never been mounted (or was+ mounted before this became inventory-owned) carries NULL, and the mount's own+ denormalized copy then stands unchanged.+ """+ if not device.rack_faceplate_id:+ return None+ return {+ "faceplate_id": device.rack_faceplate_id,+ "u_height": device.rack_u_height,+ "col_span": device.rack_col_span,+ "color": device.rack_color,+ "ports": [p for p in (device.rack_ports or []) if isinstance(p, dict) and p.get("id")],+ }+++def _with_model(+ device: RackDevice, model: dict[str, Any] | None, rack_u_height: int | None+) -> RackDeviceResponse:+ """Overlay the inventory's rack modelisation onto a mount for the response.++ Geometry is global, but a rack is not: a device grown to 4U in one rack may no+ longer fit where it sits in another. Height and width are therefore applied+ only when they still fit at the mount's own `u_start` / `col_start`; the plate,+ its colour and its ports always are, since none of them can overflow a rail.+ """+ row = RackDeviceResponse.model_validate(device)+ if model is None:+ return row+ patch: dict[str, Any] = {+ "faceplate_id": model["faceplate_id"],+ "ports": model["ports"],+ "color": model["color"],+ }+ u_height = model["u_height"]+ if u_height and (rack_u_height is None or row.u_start + u_height - 1 <= rack_u_height):+ patch["u_height"] = u_height+ col_span = model["col_span"]+ if col_span and row.col_start + col_span <= RACK_COLUMNS:+ patch["col_span"] = col_span+ return row.model_copy(update=patch)++_Row = TypeVar("_Row", Rack, RackDevice, RackCable)@@ -165,9 +211,27 @@ async def load_racks(cables = (await db.execute(select(RackCable).where(RackCable.design_id == design_id))).scalars().all()state = await db.get(CanvasState, design_id)+ # The inventory row owns the front panel, so it wins over the mount's copy.+ inventory_ids = {d.device_id for d in devices if d.device_id}+ models: dict[str, dict[str, Any]] = {}+ if inventory_ids:+ rows = (+ await db.execute(+ select(InventoryDevice).where(InventoryDevice.id.in_(inventory_ids))+ )+ ).scalars().all()+ for row in rows:+ model = _rack_model(row)+ if model is not None:+ models[row.id] = model+ heights = {r.id: r.u_height for r in racks}+return RackStateResponse(racks=[RackResponse.model_validate(r) for r in racks],- devices=[RackDeviceResponse.model_validate(d) for d in devices],+ devices=[+ _with_model(d, models.get(d.device_id or ""), heights.get(d.rack_id))+ for d in devices+ ],cables=[RackCableResponse.model_validate(c) for c in cables],viewport=state.viewport if state else {"x": 0, "y": 0, "zoom": 1},)@@ -233,6 +297,18 @@ async def save_racks(setattr(db_device, field, value)else:db.add(RackDevice(**payload))++ # Write-through: the device's front panel belongs to the inventory row,+ # not to this mount, so every rack showing the same device picks the+ # change up on its next load. Accessories have no row and keep theirs.+ if device_data.device_id:+ entry = await db.get(InventoryDevice, device_data.device_id)+ if entry is not None:+ entry.rack_faceplate_id = device_data.faceplate_id+ entry.rack_u_height = device_data.u_height+ entry.rack_col_span = device_data.col_span+ entry.rack_color = device_data.color+ entry.rack_ports = [p for p in device_data.ports if isinstance(p, dict)]await db.flush() # devices must exist before cables point at themfor cable_data in body.cables:@@ -349,6 +425,11 @@ async def rack_inventory(),node_last_seen=node_device.last_seen if node_device else None,racked=device.id in mounted,+ rack_faceplate_id=device.rack_faceplate_id,+ rack_u_height=device.rack_u_height,+ rack_col_span=device.rack_col_span,+ rack_color=device.rack_color,+ rack_ports=device.rack_ports or [],))return RackInventoryResponse(items=items)diff --git a/backend/app/db/database.py b/backend/app/db/database.pyindex b3fccbc..94a2fb2 100644--- a/backend/app/db/database.py+++ b/backend/app/db/database.py@@ -475,6 +475,27 @@ async def init_db() -> None:("nodes.display_view", "ALTER TABLE nodes ADD COLUMN display_view JSON"),):await _try_migrate(conn, sql, label=label)+ # 3.3.x — the inventory row owns the device's rack modelisation: the+ # faceplate it wears, its size and its ports (labels, types, positions).+ # A mount reads them at load and writes them back on save, so a device+ # keeps the same front panel in every rack it is mounted in.+ for label, sql in (+ (+ "device_inventory.rack_faceplate_id",+ "ALTER TABLE device_inventory ADD COLUMN rack_faceplate_id TEXT",+ ),+ (+ "device_inventory.rack_u_height",+ "ALTER TABLE device_inventory ADD COLUMN rack_u_height INTEGER",+ ),+ (+ "device_inventory.rack_col_span",+ "ALTER TABLE device_inventory ADD COLUMN rack_col_span INTEGER",+ ),+ ("device_inventory.rack_color", "ALTER TABLE device_inventory ADD COLUMN rack_color TEXT"),+ ("device_inventory.rack_ports", "ALTER TABLE device_inventory ADD COLUMN rack_ports JSON"),+ ):+ await _try_migrate(conn, sql, label=label)for label, sql in (("device_inventory.status_live.backfill",diff --git a/backend/app/db/models.py b/backend/app/db/models.pyindex dfe2ab7..05a62cb 100644--- a/backend/app/db/models.py+++ b/backend/app/db/models.py@@ -267,6 +267,19 @@ class InventoryDevice(Base):DateTime(timezone=True), default=_now, onupdate=_now)+ # --- Rack modelisation (owned here, not by the mount) ------------------+ # A device wears the same front panel in every rack it is mounted in, so the+ # inventory row — not `rack_devices` — owns the faceplate, its size and its+ # ports. The mount keeps a denormalized copy so a rack still renders after an+ # inventory purge; `/api/v1/racks` overlays these on load and `save` writes+ # them back. NULL means "never modelled" — the mount's own copy then stands.+ rack_faceplate_id: Mapped[str | None] = mapped_column(String, nullable=True)+ rack_u_height: Mapped[int | None] = mapped_column(Integer, nullable=True)+ rack_col_span: Mapped[int | None] = mapped_column(Integer, nullable=True)+ rack_color: Mapped[str | None] = mapped_column(String, nullable=True)+ # [{id, label, type, x, y}] — x/y are unit coordinates on the plate.+ rack_ports: Mapped[list[Any] | None] = mapped_column(JSON, nullable=True)+# Transient (not persisted): populated per-request by the scan routes to report# how many canvases this device already appears on. Not a mapped column.canvas_count: int = 0diff --git a/backend/app/schemas/racks.py b/backend/app/schemas/racks.pyindex 34f3bff..6db81cd 100644--- a/backend/app/schemas/racks.py+++ b/backend/app/schemas/racks.py@@ -282,6 +282,22 @@ class RackInventoryItem(BaseModel):node_last_seen: datetime | None = None# True when this device is already mounted somewhere in this design.racked: bool = False+ # Rack modelisation the inventory row owns — the same front panel wherever+ # the device is mounted. All None/empty for a device never modelled; the+ # tray then falls back to the type-suggested faceplate.+ 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[dict[str, Any]] = []++ @field_validator("rack_ports", mode="before")+ @classmethod+ def _clean_ports(cls, v: Any) -> list[dict[str, Any]]:+ """NULL for a row written before the column existed; junk stays out."""+ if not isinstance(v, list):+ return []+ return [p for p in v if isinstance(p, dict) and p.get("id")]@field_validator("node_last_seen")@classmethoddiff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.pyindex fe49030..b4af8b4 100644--- a/backend/tests/test_racks.py+++ b/backend/tests/test_racks.py@@ -93,6 +93,128 @@ class TestDesignType:assert res.status_code == 422+class TestDeviceRackModel:+ """The inventory row owns the front panel; the mount only places it.++ A device wears the same faceplate, size, colour and ports in every rack, so a+ save writes them onto `device_inventory` and a load reads them back out.+ """++ async def _mounted(self, client: AsyncClient, headers: dict, db_session, **device) -> str:+ design_id = await _design(client, headers)+ db_session.add(InventoryDevice(id="inv-sw", ip="192.168.1.10", suggested_type="switch"))+ await db_session.commit()+ state = _state(design_id, cables=[])+ state["devices"] = [{**state["devices"][0], "device_id": "inv-sw", **device}]+ res = await client.post("/api/v1/racks/save", json=state, headers=headers)+ assert res.status_code == 200, res.text+ return design_id++ async def test_writes_the_mount_panel_onto_the_inventory_row(+ self, client: AsyncClient, headers, db_session+ ):+ await self._mounted(client, headers, db_session, color="#ff6e00")++ entry = await db_session.get(InventoryDevice, "inv-sw")+ await db_session.refresh(entry)+ assert entry.rack_faceplate_id == "switch-24"+ assert entry.rack_u_height == 1+ assert entry.rack_col_span == 12+ assert entry.rack_color == "#ff6e00"+ assert entry.rack_ports == [{"id": "p1", "label": "1", "type": "rj45", "x": 0.4, "y": 0.5}]++ async def test_leaves_the_inventory_alone_for_an_accessory(+ self, client: AsyncClient, headers, db_session+ ):+ design_id = await _design(client, headers)+ db_session.add(InventoryDevice(id="inv-untouched", ip="192.168.1.11"))+ await db_session.commit()+ state = _state(design_id, cables=[])+ state["devices"] = [{**state["devices"][0], "faceplate_id": "shelf-1u", "ports": []}]+ await client.post("/api/v1/racks/save", json=state, headers=headers)++ entry = await db_session.get(InventoryDevice, "inv-untouched")+ await db_session.refresh(entry)+ assert entry.rack_faceplate_id is None++ async def test_load_serves_the_inventory_panel_over_the_mount_copy(+ self, client: AsyncClient, headers, db_session+ ):+ design_id = await self._mounted(client, headers, db_session)+ # Another rack modelled the same device differently since this mount was+ # written: the row wins, ports included.+ entry = await db_session.get(InventoryDevice, "inv-sw")+ entry.rack_faceplate_id = "switch-48"+ entry.rack_color = "#a855f7"+ entry.rack_ports = [{"id": "px", "label": "uplink", "type": "sfp+", "x": 0.9, "y": 0.4}]+ await db_session.commit()++ device = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["devices"][0]+ assert device["faceplate_id"] == "switch-48"+ assert device["color"] == "#a855f7"+ assert [p["id"] for p in device["ports"]] == ["px"]++ async def test_load_keeps_a_size_that_no_longer_fits_this_rack(+ self, client: AsyncClient, headers, db_session+ ):+ # The mount sits at U 10 of a 12U rack. Grown to 4U elsewhere, it would+ # now run past the top rail — geometry is global, a rack is not.+ design_id = await self._mounted(client, headers, db_session)+ entry = await db_session.get(InventoryDevice, "inv-sw")+ entry.rack_u_height = 4+ entry.rack_col_span = 12+ await db_session.commit()++ device = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["devices"][0]+ assert device["u_height"] == 1+ # The plate itself cannot overflow a rail, so it still comes from the row.+ assert device["faceplate_id"] == "switch-24"++ async def test_load_keeps_a_width_that_overruns_the_column_grid(+ self, client: AsyncClient, headers, db_session+ ):+ design_id = await self._mounted(client, headers, db_session, col_start=6, col_span=6)+ entry = await db_session.get(InventoryDevice, "inv-sw")+ entry.rack_col_span = 12+ await db_session.commit()++ device = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["devices"][0]+ assert device["col_span"] == 6++ async def test_the_tray_offers_the_saved_panel(+ self, client: AsyncClient, headers, db_session+ ):+ design_id = await self._mounted(client, headers, db_session, color="#ff6e00")++ items = (+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)+ ).json()["items"]+ item = next(i for i in items if i["id"] == "inv-sw")+ assert item["rack_faceplate_id"] == "switch-24"+ assert item["rack_color"] == "#ff6e00"+ assert [p["id"] for p in item["rack_ports"]] == ["p1"]++ async def test_a_never_racked_device_reports_no_panel(+ self, client: AsyncClient, headers, db_session+ ):+ design_id = await _design(client, headers)+ db_session.add(InventoryDevice(id="inv-fresh", ip="192.168.1.12", suggested_type="nas"))+ await db_session.commit()++ items = (+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)+ ).json()["items"]+ item = next(i for i in items if i["id"] == "inv-fresh")+ assert item["rack_faceplate_id"] is None+ assert item["rack_ports"] == []++class TestSaveAndLoad:async def test_round_trips_the_full_state(self, client: AsyncClient, headers):design_id = await _design(client, headers)diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdindex 86231a4..c76554a 100644--- a/frontend/src/rack/README.md+++ b/frontend/src/rack/README.md@@ -22,7 +22,8 @@ Create one from **New Canvas → Kind → Rack**.| Linked device panel | `LinkedDevicePanel`, under the port list in `RackDeviceModal`: what is known about the box a mount stands for — name, type, hostname, IP, MAC, OS, status check, the canvas it is drawn on, last seen, and the fingerprinted services. Read-only; the inventory and the logical canvas own them. `/racks/inventory` ships the canvas side as `node_*` alongside the inventory row's own `mac` / `hostname` / `os` / `services`, and the panel prefers the node value (curated) over the inventory one (what discovery last saw), dropping any row neither side can fill. A device on no canvas still prints everything discovery found — it is the record of a real box whether or not anyone drew it — and adds *Not on a logical canvas.*, which is why `auto` resolves to `unknown` there. *Link to another device…* is always on offer for a real mount, so a placeholder or the wrong twin of two look-alikes is not a dead end. A mount with no inventory entry — an accessory — gets no panel. || 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. Power outlets are artwork, never a cable endpoint. |+| 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 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. |@@ -53,7 +54,8 @@ types in `@/types/rack`, narrowing every enum on the way in.- **+ Device** (left rail) → `RackDeviceModal`. Source is either an existing **Device Inventory** entry, a new device created here (which lands in the inventory too), or a rack-only accessory. Nothing is preselected: the entry is picked in the Device Inventory modal, which the field opens.- Drag from the sidebar tray onto a rack → snaps to a free U.- Drag a mounted device inside the rack → same snapping, own slot ignored.-- The **Faceplate** field previews the current plate; clicking it opens `FaceplatePicker`. Switching the source between device and accessory swaps the plate to a sane default of the other kind.+- The **Faceplate** field names the current plate and opens `FaceplatePicker`; the plate itself is drawn full size at the bottom of the modal (`PortPositionEditor`, `interactive={false}`) — the old 160×18px thumbnail lost its label and stacked its ports. Switching the source between device and accessory swaps the plate to a sane default of the other kind.+- **Position** (port list header) turns that plate into the port editor: drag a handle to place a port, arrow keys nudge by 0.01, and each axis snaps to the nearest peer within 6px so banks stay in line. A new port continues the last row instead of landing on the middle of the plate. Editing a port's name highlights it on the plate. Positions are unit coordinates, so the blow-up never reaches the data.- Double-click a plate → the same modal in edit mode: label, faceplate, U/height/column/width, status, colour, port list, the **Linked device** panel, Unmount. Single click only selects.- Double-click empty rack chrome → `RackSettingsModal` (name, location, U height, 19"/10", numbering direction, frame/rail/interior colours, U numbers, enclosed, delete).- Growing a device — by hand or by picking a taller plate — relocates it to the nearest slot that takes the new size. Only a rack with no such slot rejects the edit, and says so.diff --git a/frontend/src/rack/__tests__/PortPositionEditor.test.tsx b/frontend/src/rack/__tests__/PortPositionEditor.test.tsxnew file mode 100644index 0000000..e77b873--- /dev/null+++ b/frontend/src/rack/__tests__/PortPositionEditor.test.tsx@@ -0,0 +1,124 @@+/**+ * Placing ports on the blown-up plate: handles only exist in drag mode, a drag+ * writes unit coordinates, and the pointer is not the only way in.+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, fireEvent } from '@testing-library/react'+import { PortPositionEditor } from '../components/PortPositionEditor'+import type { Port } from '@/types'++const PLATE = { left: 100, top: 50, width: 400, height: 100 }++const ports: Port[] = [+ { id: 'a', label: 'eth0', type: 'rj45', x: 0.2, y: 0.5 },+ { id: 'b', label: 'eth1', type: 'rj45', x: 0.8, y: 0.5 },+]++function draw(over: Partial<React.ComponentProps<typeof PortPositionEditor>> = {}) {+ const onChange = vi.fn()+ const onSelect = vi.fn()+ render(+ <PortPositionEditor+ faceplateId="switch-8"+ label="sw-01"+ status="online"+ ports={ports}+ uHeight={1}+ colSpan={12}+ interactive+ selectedPortId={null}+ onSelect={onSelect}+ onChange={onChange}+ {...over}+ />,+ )+ return { onChange, onSelect }+}++/** jsdom lays nothing out, so the stage has to be given a size to map against. */+beforeEach(() => {+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({+ ...PLATE,+ right: PLATE.left + PLATE.width,+ bottom: PLATE.top + PLATE.height,+ x: PLATE.left,+ y: PLATE.top,+ toJSON: () => ({}),+ } as DOMRect)+})++afterEach(() => vi.restoreAllMocks())++/** Drag a handle to a point given in unit coordinates of the plate. */+function dragTo(portId: string, x: number, y: number) {+ const handle = document.querySelector(`[data-port-handle="${portId}"]`)!+ fireEvent.pointerDown(handle)+ fireEvent.pointerMove(screen.getByTestId('faceplate-stage'), {+ clientX: PLATE.left + x * PLATE.width,+ clientY: PLATE.top + y * PLATE.height,+ })+}++describe('PortPositionEditor', () => {+ it('draws no handle at all outside drag mode', () => {+ draw({ interactive: false })+ expect(document.querySelectorAll('[data-port-handle]')).toHaveLength(0)+ // The plate itself is still there: it doubles as the modal's preview.+ expect(screen.getByTestId('faceplate-stage')).toBeInTheDocument()+ })++ it('offers one named handle per port in drag mode', () => {+ draw()+ expect(screen.getByRole('button', { name: 'Move port eth0' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Move port eth1' })).toBeInTheDocument()+ })++ it('writes the drop point as unit coordinates of the plate', () => {+ const { onChange } = draw()+ dragTo('a', 0.5, 0.25)++ const moved = onChange.mock.calls.at(-1)![0] as Port[]+ expect(moved.find((p) => p.id === 'a')).toMatchObject({ x: 0.5, y: 0.25 })+ // The port that was not dragged keeps its place.+ expect(moved.find((p) => p.id === 'b')).toMatchObject({ x: 0.8, y: 0.5 })+ })++ it('snaps onto a peer that is a couple of pixels away', () => {+ const { onChange } = draw()+ // 0.795 of a 400px plate is 2px left of the peer at 0.8 — inside the 6px+ // snap distance, so the two end up on the same column.+ dragTo('a', 0.795, 0.2)++ const moved = onChange.mock.calls.at(-1)![0] as Port[]+ expect(moved.find((p) => p.id === 'a')!.x).toBe(0.8)+ })++ it('selects the port it is about to move', () => {+ const { onSelect } = draw()+ fireEvent.pointerDown(document.querySelector('[data-port-handle="b"]')!)+ expect(onSelect).toHaveBeenCalledWith('b')+ })++ it('nudges the port with the arrow keys, for a placement no pointer can hit', () => {+ const { onChange } = draw()+ fireEvent.keyDown(screen.getByRole('button', { name: 'Move port eth0' }), { key: 'ArrowRight' })++ const moved = onChange.mock.calls.at(-1)![0] as Port[]+ expect(moved.find((p) => p.id === 'a')!.x).toBeCloseTo(0.21)+ })++ it('ignores a key that means nothing here', () => {+ const { onChange } = draw()+ fireEvent.keyDown(screen.getByRole('button', { name: 'Move port eth0' }), { key: 'Enter' })+ expect(onChange).not.toHaveBeenCalled()+ })++ it('drops the drag when the pointer leaves the plate', () => {+ const { onChange } = draw()+ const stage = screen.getByTestId('faceplate-stage')+ fireEvent.pointerDown(document.querySelector('[data-port-handle="a"]')!)+ fireEvent.pointerLeave(stage)+ fireEvent.pointerMove(stage, { clientX: PLATE.left + 10, clientY: PLATE.top + 10 })+ expect(onChange).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsxindex c95adef..c320e51 100644--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx@@ -258,8 +258,9 @@ describe('RackDeviceModal — adding', () => {render(<RackDeviceModal />)// Regression: a max-w-md dialog with one column pushed the port list — and- // the Add button — below the fold on a laptop screen.- expect(screen.getByRole('dialog')).toHaveClass('sm:max-w-3xl')+ // the Add button — below the fold on a laptop screen. Widened again when the+ // full-size faceplate moved under the form.+ expect(screen.getByRole('dialog')).toHaveClass('sm:max-w-5xl')const columns = document.querySelector('.sm\\:grid-cols-2')!expect(columns).not.toBeNull()// Fields on the left, ports on the right, both inside the same grid.@@ -509,6 +510,70 @@ describe('RackDeviceModal — editing', () => {)})+ it('shows the plate full size instead of the thumbnail that never fit', () => {+ store().openDeviceEditor('dev-pve1')+ render(<RackDeviceModal />)++ // Regression: the plate used to be drawn at 160×18px inside the faceplate+ // button, where it lost its label and stacked its ports on one another.+ const stage = screen.getByTestId('faceplate-stage')+ expect(stage).toBeInTheDocument()+ expect(Number.parseFloat(stage.style.width)).toBeGreaterThan(200)+ expect(screen.getByLabelText('Faceplate').querySelector('svg')).toBeNull()+ })++ it('reveals the drag handles only once positioning is switched on', () => {+ store().openDeviceEditor('dev-pve1')+ render(<RackDeviceModal />)++ const ports = store().devices.find((d) => d.id === 'dev-pve1')!.ports+ expect(document.querySelectorAll('[data-port-handle]')).toHaveLength(0)++ fireEvent.click(screen.getByRole('button', { name: 'Position ports' }))+ expect(document.querySelectorAll('[data-port-handle]')).toHaveLength(ports.length)+ })++ it('has nothing to position on a plate with no port', async () => {+ store().openDeviceEditor('dev-pve1')+ render(<RackDeviceModal />)++ const ports = store().devices.find((d) => d.id === 'dev-pve1')!.ports+ for (const port of ports) {+ fireEvent.click(screen.getByLabelText(`Remove port ${port.label}`))+ }+ expect(screen.getByRole('button', { name: 'Position ports' })).toBeDisabled()+ })++ it('spreads added ports along the plate instead of stacking them', () => {+ store().openDeviceEditor('dev-pve1')+ render(<RackDeviceModal />)++ // Regression: every new port landed on the middle of the plate, so three+ // added ports drew as one socket. Each continues the row of the last.+ const before = store().devices.find((d) => d.id === 'dev-pve1')!.ports+ fireEvent.click(screen.getByRole('button', { name: 'Add port' }))+ fireEvent.click(screen.getByRole('button', { name: 'Add port' }))+ fireEvent.click(screen.getByRole('button', { name: 'Position ports' }))++ const added = [...document.querySelectorAll<HTMLElement>('[data-port-handle]')].slice(+ before.length,+ )+ expect(added).toHaveLength(2)+ expect(added[0].style.left).not.toBe(added[1].style.left)+ })++ it('gives an accessory no port section at all', () => {+ const id = store().mountAccessory('shelf-1u', 'rack-main', { uStart: 6 })!+ store().openDeviceEditor(id)+ render(<RackDeviceModal />)++ // A shelf stands for no inventory row, so it has nothing to cable.+ expect(screen.queryByRole('button', { name: 'Add port' })).toBeNull()+ expect(screen.queryByRole('button', { name: 'Position ports' })).toBeNull()+ // The plate is still drawn: it is the preview of the accessory itself.+ expect(screen.getByTestId('faceplate-stage')).toBeInTheDocument()+ })+it('keeps the port name field usable next to the type select', () => {store().openDeviceEditor('dev-pve1')render(<RackDeviceModal />)diff --git a/frontend/src/rack/__tests__/portLayout.test.ts b/frontend/src/rack/__tests__/portLayout.test.tsnew file mode 100644index 0000000..2b2dd22--- /dev/null+++ b/frontend/src/rack/__tests__/portLayout.test.ts@@ -0,0 +1,100 @@+import { describe, it, expect } from 'vitest'+import {+ PORT_EDGE_INSET,+ clampPort,+ nextPortSpot,+ snapThreshold,+ snapToPeers,+} from '../portLayout'+import type { Port } from '@/types'++const port = (over: Partial<Port> = {}): Port => ({+ id: 'p1',+ label: 'p1',+ type: 'rj45',+ x: 0.5,+ y: 0.5,+ ...over,+})++describe('clampPort', () => {+ it('keeps a port off the edge of the plate, on both sides', () => {+ expect(clampPort({ x: -3, y: 2 })).toEqual({+ x: PORT_EDGE_INSET,+ y: 1 - PORT_EDGE_INSET,+ })+ })++ it('leaves a port inside the plate alone', () => {+ expect(clampPort({ x: 0.4, y: 0.6 })).toEqual({ x: 0.4, y: 0.6 })+ })+})++describe('snapThreshold', () => {+ it('converts the pixel threshold per axis, so a wide plate snaps evenly', () => {+ expect(snapThreshold(600, 60, 6)).toEqual({ x: 0.01, y: 0.1 })+ })++ it('reports no threshold for a plate that has not been measured yet', () => {+ expect(snapThreshold(0, 0)).toEqual({ x: 0, y: 0 })+ })+})++describe('snapToPeers', () => {+ const threshold = { x: 0.02, y: 0.05 }++ it('aligns onto the nearest peer column and reports the guide', () => {+ const result = snapToPeers({ x: 0.31, y: 0.8 }, [{ x: 0.3, y: 0.2 }], threshold)+ expect(result.x).toBe(0.3)+ expect(result.guideX).toBe(0.3)+ // The peer is far away vertically, so that axis stays free.+ expect(result.y).toBe(0.8)+ expect(result.guideY).toBeNull()+ })++ it('takes its column from one peer and its row from another', () => {+ const result = snapToPeers(+ { x: 0.405, y: 0.62 },+ [+ { x: 0.4, y: 0.1 },+ { x: 0.9, y: 0.6 },+ ],+ threshold,+ )+ expect(result).toMatchObject({ x: 0.4, y: 0.6, guideX: 0.4, guideY: 0.6 })+ })++ it('leaves a port that is out of reach of every peer where it was dropped', () => {+ const result = snapToPeers({ x: 0.5, y: 0.5 }, [{ x: 0.1, y: 0.1 }], threshold)+ expect(result).toEqual({ x: 0.5, y: 0.5, guideX: null, guideY: null })+ })++ it('clamps before snapping, so a drag off the plate cannot escape it', () => {+ const result = snapToPeers({ x: 5, y: -5 }, [], threshold)+ expect(result.x).toBe(1 - PORT_EDGE_INSET)+ expect(result.y).toBe(PORT_EDGE_INSET)+ })+})++describe('nextPortSpot', () => {+ it('centres the first port', () => {+ expect(nextPortSpot([])).toEqual({ x: 0.5, y: 0.5 })+ })++ it('continues the row rather than stacking on the last port', () => {+ const spot = nextPortSpot([port({ x: 0.2, y: 0.35 })])+ expect(spot.x).toBeGreaterThan(0.2)+ expect(spot.y).toBe(0.35)+ })++ it('wraps to a new row at the right edge', () => {+ const spot = nextPortSpot([port({ x: 0.98, y: 0.3 })])+ expect(spot.x).toBe(PORT_EDGE_INSET)+ expect(spot.y).toBeGreaterThan(0.3)+ })++ it('never wraps a bottom row off the plate', () => {+ const spot = nextPortSpot([port({ x: 0.98, y: 0.95 })])+ expect(spot.y).toBe(1 - PORT_EDGE_INSET)+ })+})diff --git a/frontend/src/rack/__tests__/store.test.ts b/frontend/src/rack/__tests__/store.test.tsindex 49a8a25..43e87ea 100644--- a/frontend/src/rack/__tests__/store.test.ts+++ b/frontend/src/rack/__tests__/store.test.ts@@ -165,6 +165,90 @@ describe('mounting', () => {expect(store().inventory.find((i) => i.id === 'inv-sw8')!.racked).toBe(true)})+ it('reuses the front panel the device already wears in another rack', () => {+ // The Device Inventory row owns the rack modelisation, so a device dropped+ // into a second rack must come back with the plate, size, colour and ports+ // it was given the first time — not the plate its type suggests.+ useRackStore.setState({+ inventory: store().inventory.map((item) =>+ item.id === 'inv-sw8'+ ? {+ ...item,+ rackModel: {+ faceplateId: 'switch-24',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ color: '#ff6e00',+ ports: [{ id: 'saved-1', label: 'uplink', type: 'sfp' as const, x: 0.9, y: 0.4 }],+ },+ }+ : item,+ ),+ })++ const id = store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 5 })!+ const device = store().devices.find((d) => d.id === id)!+ expect(device.faceplateId).toBe('switch-24')+ expect(device.colSpan).toBe(RACK_COLUMNS)+ expect(device.color).toBe('#ff6e00')+ expect(device.ports).toEqual([+ { id: 'saved-1', label: 'uplink', type: 'sfp', x: 0.9, y: 0.4 },+ ])+ })++ it('seeds the plate from the template when the drop asks for another one', () => {+ useRackStore.setState({+ inventory: store().inventory.map((item) =>+ item.id === 'inv-sw8'+ ? {+ ...item,+ rackModel: {+ faceplateId: 'switch-24',+ uHeight: 1,+ colSpan: RACK_COLUMNS,+ color: null,+ ports: [{ id: 'saved-1', label: 'uplink', type: 'sfp' as const, x: 0.9, y: 0.4 }],+ },+ }+ : item,+ ),+ })++ // The saved ports belong to the saved plate; a different plate brings its own.+ const id = store().mountFromInventory('inv-sw8', 'rack-main', {+ uStart: 5,+ faceplateId: 'switch-8',+ })!+ const device = store().devices.find((d) => d.id === id)!+ expect(device.faceplateId).toBe('switch-8')+ expect(device.ports).toHaveLength(getFaceplate('switch-8').ports.length)+ expect(device.ports.map((p) => p.id)).not.toContain('saved-1')+ })++ it('writes an edited plate back onto the inventory entry it stands for', () => {+ store().updateDevice('dev-pve1', { faceplateId: 'server-2u-bays', uHeight: 2 })++ const device = store().devices.find((d) => d.id === 'dev-pve1')!+ const entry = store().inventory.find((i) => i.id === device.deviceId)!+ expect(entry.rackModel).toMatchObject({ faceplateId: 'server-2u-bays', uHeight: 2 })+ })++ it('writes edited ports back onto the inventory entry too', () => {+ const ports = [{ id: 'p-x', label: 'wan', type: 'rj45' as const, x: 0.15, y: 0.6 }]+ store().setPorts('dev-pve1', ports)++ const device = store().devices.find((d) => d.id === 'dev-pve1')!+ const entry = store().inventory.find((i) => i.id === device.deviceId)!+ expect(entry.rackModel!.ports).toEqual(ports)+ })++ it('leaves the inventory alone for an accessory, which stands for no device', () => {+ const id = store().mountAccessory('shelf-1u', 'rack-main', { uStart: 6 })!+ const before = store().inventory+ store().updateDevice(id, { color: '#ffffff' })+ expect(store().inventory).toBe(before)+ })+it('clears the racked flag again when the device is unmounted', () => {expect(store().inventory.find((i) => i.id === 'inv-pve1')!.racked).toBe(true)store().unmountDevice('dev-pve1')diff --git a/frontend/src/rack/components/Faceplate.tsx b/frontend/src/rack/components/Faceplate.tsxindex d41ee4a..f3be95c 100644--- a/frontend/src/rack/components/Faceplate.tsx+++ b/frontend/src/rack/components/Faceplate.tsx@@ -26,10 +26,9 @@ interface PortShapeSize {*/const PORT_W = U_PX * 0.3-function portShapeSize(type: PortType): PortShapeSize {- return type === 'rj45'- ? { w: PORT_W, h: PORT_W * 0.92 }- : { w: PORT_W * 1.15, h: PORT_W * 0.62 }+function portShapeSize(type: PortType, scale: number = 1): PortShapeSize {+ const w = PORT_W * scale+ 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). */@@ -165,6 +164,14 @@ interface Props {revealed?: boolean/** Ports take the pointer (patch mode). */interactivePorts?: boolean+ /**+ * Multiplies the socket artwork.+ *+ * Sockets are a fixed pixel size so plates of different heights stay+ * comparable on the canvas (see `PORT_W`). A blown-up plate — the port+ * positioning editor — is not on the canvas and wants them to grow with it.+ */+ portScale?: number/** Port id -> colour of the cable plugged into it. */patchedPorts?: Map<string, string>draftPortId?: string | null@@ -184,6 +191,7 @@ export const Faceplate = memo(function Faceplate({selected,revealed,interactivePorts,+ portScale,patchedPorts,draftPortId,onPortPointerDown,@@ -262,7 +270,7 @@ export const Faceplate = memo(function Faceplate({const cy = port.y * heightconst patchColor = patchedPorts?.get(port.id)const isDraft = draftPortId === port.id- const { w, h } = portShapeSize(port.type)+ const { w, h } = portShapeSize(port.type, portScale)const stroke = isDraft ? palette.accent : patchColor ?? palette.portBezelreturn (diff --git a/frontend/src/rack/components/PortPositionEditor.tsx b/frontend/src/rack/components/PortPositionEditor.tsxnew file mode 100644index 0000000..0809dc8--- /dev/null+++ b/frontend/src/rack/components/PortPositionEditor.tsx@@ -0,0 +1,200 @@+/**+ * The device's faceplate, blown up — a preview, and the surface its ports are+ * placed on.+ *+ * The plate keeps true rack proportions (the canvas' width-to-U ratio, scaled+ * up), so a port dropped here lands where the user expects it on the rack. Both+ * axes scale together for the same reason: stretching one would move the ports+ * relative to the artwork they sit on.+ */+import { useCallback, useRef, useState } from 'react'+import { Faceplate } from './Faceplate'+import { INNER_WIDTH_PX, U_PX } from '../layout'+import { clampPort, snapThreshold, snapToPeers } from '../portLayout'+import { useRackPalette } from '../rackTheme'+import { RACK_COLUMNS, type DeviceStatus, type Port } from '@/types'++/** Width of a full-width (12-column) plate in the editor. */+const EDITOR_FULL_WIDTH = 660++/** Editor pixels per canvas pixel, before the small-plate blow-up below. */+const SCALE = EDITOR_FULL_WIDTH / INNER_WIDTH_PX['19']++/**+ * A 1U plate is ~35px tall at `SCALE` — a thin strip to aim a port at. A narrow+ * plate (a third-width mini node, the worst case for port placement) is scaled+ * up further until it reaches this height, never past the width a full-width+ * plate already gets.+ */+const MIN_PLATE_PX = 90++/** Nudge per arrow-key press, in unit coordinates. */+const NUDGE_STEP = 0.01++interface Props {+ faceplateId: string+ label: string+ status: DeviceStatus+ ports: Port[]+ uHeight: number+ colSpan: number+ color?: string+ /**+ * Drag mode. Off, the plate is a plain preview — no handles, no guides,+ * nothing to grab.+ */+ interactive: boolean+ /** Highlighted port, kept in step with the port list beside it. */+ selectedPortId: string | null+ onSelect: (portId: string | null) => void+ onChange: (ports: Port[]) => void+}++export function PortPositionEditor({+ faceplateId,+ label,+ status,+ ports,+ uHeight,+ colSpan,+ color,+ interactive,+ selectedPortId,+ onSelect,+ onChange,+}: Props) {+ const palette = useRackPalette()+ const plateRef = useRef<HTMLDivElement>(null)+ const [dragging, setDragging] = useState<string | null>(null)+ const [guides, setGuides] = useState<{ x: number | null; y: number | null }>({ x: null, y: null })++ const width = (EDITOR_FULL_WIDTH * colSpan) / RACK_COLUMNS+ const height = uHeight * U_PX * SCALE+ const zoom = Math.min(EDITOR_FULL_WIDTH / width, Math.max(1, MIN_PLATE_PX / height))+ const plateW = width * zoom+ const plateH = height * zoom++ const moveTo = useCallback(+ (portId: string, clientX: number, clientY: number) => {+ const box = plateRef.current?.getBoundingClientRect()+ if (!box || box.width === 0 || box.height === 0) return+ const snapped = snapToPeers(+ { x: (clientX - box.left) / box.width, y: (clientY - box.top) / box.height },+ ports.filter((p) => p.id !== portId),+ snapThreshold(box.width, box.height),+ )+ setGuides({ x: snapped.guideX, y: snapped.guideY })+ onChange(ports.map((p) => (p.id === portId ? { ...p, x: snapped.x, y: snapped.y } : p)))+ },+ [onChange, ports],+ )++ const endDrag = useCallback(() => {+ setDragging(null)+ setGuides({ x: null, y: null })+ }, [])++ /** A pointer cannot land a port on an exact fraction; the arrow keys can. */+ const nudge = (port: Port, dx: number, dy: number) =>+ onChange(+ ports.map((p) =>+ p.id === port.id+ ? { ...p, ...clampPort({ x: p.x + dx * NUDGE_STEP, y: p.y + dy * NUDGE_STEP }) }+ : p,+ ),+ )++ return (+ <div className="flex flex-col items-center gap-2">+ <div+ ref={plateRef}+ data-testid="faceplate-stage"+ className="relative touch-none select-none"+ style={{ width: plateW, height: plateH }}+ onPointerMove={(e) => {+ if (interactive && dragging) moveTo(dragging, e.clientX, e.clientY)+ }}+ onPointerUp={endDrag}+ onPointerLeave={endDrag}+ >+ <Faceplate+ faceplateId={faceplateId}+ label={label}+ status={status}+ ports={ports}+ width={plateW}+ height={plateH}+ colorOverride={color}+ portScale={zoom * SCALE}+ revealed+ />++ {/* Alignment guides — drawn only while a drag is actually snapped. */}+ {guides.x !== null && (+ <div+ className="pointer-events-none absolute top-0 h-full w-px"+ style={{ left: `${guides.x * 100}%`, background: palette.accent, opacity: 0.7 }}+ />+ )}+ {guides.y !== null && (+ <div+ className="pointer-events-none absolute left-0 h-px w-full"+ style={{ top: `${guides.y * 100}%`, background: palette.accent, opacity: 0.7 }}+ />+ )}++ {/* Grab handles ride above the drawn sockets: the artwork is too small to+ aim at, and a handle can take focus and wear a name, which an SVG+ socket cannot. */}+ {interactive &&+ ports.map((port) => {+ const selected = selectedPortId === port.id+ return (+ <button+ key={port.id}+ type="button"+ aria-label={`Move port ${port.label}`}+ data-port-handle={port.id}+ className="absolute flex h-6 w-6 -translate-x-1/2 -translate-y-1/2 cursor-grab items-center justify-center rounded-full border text-[8px] active:cursor-grabbing"+ style={{+ left: `${port.x * 100}%`,+ top: `${port.y * 100}%`,+ borderColor: selected ? palette.accent : 'rgba(255,255,255,0.35)',+ background: selected ? 'rgba(0,212,255,0.18)' : 'rgba(13,17,23,0.35)',+ }}+ onPointerDown={(e) => {+ // Keep the press off the plate: it would start an HTML5 drag.+ e.preventDefault()+ onSelect(port.id)+ setDragging(port.id)+ }}+ onKeyDown={(e) => {+ const steps: Record<string, [number, number]> = {+ ArrowLeft: [-1, 0],+ ArrowRight: [1, 0],+ ArrowUp: [0, -1],+ ArrowDown: [0, 1],+ }+ const step = steps[e.key]+ if (!step) return+ e.preventDefault()+ nudge(port, step[0], step[1])+ }}+ >+ <span className="pointer-events-none max-w-[22px] truncate text-white/80">+ {port.label}+ </span>+ </button>+ )+ })}+ </div>++ {interactive && (+ <p className="text-[11px] text-muted-foreground">+ Drag a port to place it. Arrow keys nudge the selected one, and ports snap to the row or+ column of their neighbours.+ </p>+ )}+ </div>+ )+}diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsxindex cd1237c..8db83e2 100644--- a/frontend/src/rack/components/RackDeviceModal.tsx+++ b/frontend/src/rack/components/RackDeviceModal.tsx@@ -11,7 +11,7 @@* cable managers — are rack-only and never touch the inventory.*/import { useEffect, useMemo, useState } from 'react'-import { Plus, X } from 'lucide-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,11 +20,12 @@ import { DeviceInventoryModal } from '@/components/modals/DeviceInventoryModal'import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'import { useRackStore } from '../store'import { FaceplatePicker } from './FaceplatePicker'-import { Faceplate } from './Faceplate'+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 {@@ -110,6 +111,10 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (const [ports, setLocalPorts] = useState<Port[]>(device?.ports ?? getFaceplate(faceplateId).ports.map((p) => ({ ...p, id: generateUUID() })),)+ /** Drag mode on the plate below the form. Off by default: most edits are text. */+ const [positioning, setPositioning] = useState(false)+ /** Highlighted port, shared between the list and the plate. */+ const [selectedPortId, setSelectedPortId] = useState<string | null>(null)const [plateChanged, setPlateChanged] = useState(false)const [pickerOpen, setPickerOpen] = useState(false)const [inventoryPickerOpen, setInventoryPickerOpen] = useState(false)@@ -334,6 +339,11 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (}const showInventoryPicker = !isEdit && source === 'inventory'+ /**+ * Rack furniture — a blank panel, a shelf, a cable manager. It stands for no+ * inventory row, so it carries no ports and gets no port UI at all.+ */+ const isAccessory = isEdit ? !device?.deviceId : source === 'accessory'// The plate preview draws a colour, never the word `auto`.const previewStatus = resolveDeviceStatus({ status, deviceId: mountEntry?.id ?? null },@@ -342,9 +352,10 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (return (<Dialog open onOpenChange={(o) => !o && onClose()}>- {/* Same footprint as NodeModal — the form is two columns wide so a mount- fits on screen without scrolling. */}- <DialogContent className="border-[#30363d] bg-[#161b22] text-foreground max-w-[calc(100%-2rem)] sm:max-w-3xl max-h-[90vh] overflow-y-auto">+ {/* Wider than NodeModal: the form is two columns, and under them sits the+ faceplate at rack proportions — the plate is where ports are placed, so+ it has to be big enough to aim at. */}+ <DialogContent className="border-[#30363d] bg-[#161b22] text-foreground max-w-[calc(100%-2rem)] sm:max-w-5xl max-h-[90vh] overflow-y-auto"><DialogHeader><DialogTitle className="text-sm font-semibold">{isEdit ? 'Edit Device' : 'Add Device'}@@ -493,16 +504,9 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (onClick={() => setPickerOpen(true)}className="flex cursor-pointer items-center gap-3 rounded border border-[#30363d] bg-[#21262d] p-2 text-left hover:border-[#00d4ff]">- <Faceplate- faceplateId={faceplateId}- label={label || getFaceplate(faceplateId).label}- status={previewStatus}- ports={ports}- width={(160 * colSpan) / RACK_COLUMNS}- height={Math.min(uHeight, 4) * 18}- colorOverride={color}- revealed- />+ {/* No thumbnail here any more: a plate squeezed into 160×18px+ dropped its label and stacked its ports on top of each other.+ The full-size plate below the form is the preview. */}<span className="flex flex-col"><span className="text-xs">{getFaceplate(faceplateId).label}</span><span className="text-[11px] text-[#00d4ff]">Browse faceplates…</span>@@ -613,72 +617,110 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (</div><div className="flex flex-col gap-3">- <div className="flex flex-col gap-1.5">- <div className="flex items-center justify-between">- <Label className={fieldLabel}>Ports ({ports.length})</Label>- <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) => [- ...p,- { id: generateUUID(), label: `p${p.length + 1}`, type: 'rj45', x: 0.5, y: 0.5 },- ])- }- >- <Plus size={12} className="inline" /> Add- </button>- </div>- <ul className="max-h-[26rem] space-y-1 overflow-y-auto">- {ports.map((port) => (- <li key={port.id} className="flex items-center gap-1">- <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,- ),- )- }+ {!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)}>- {(['rj45', 'sfp', 'sfp+'] as PortType[]).map((t) => (- <option key={t} value={t}>- {t}- </option>- ))}- </select>+ <Move size={12} className="inline" /> Position+ </button><buttontype="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))}+ 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]+ })+ }>- <X size={12} />+ <Plus size={12} className="inline" /> Add</button>- </li>- ))}- {ports.length === 0 && (- <li className="text-[11px] text-muted-foreground">No port on this plate.</li>- )}- </ul>- </div>+ </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>+ )}{/* The column below the port list used to be dead space. A mountthat stands for an inventory entry fills it with what the@@ -702,6 +744,25 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (</div></div>+ {/* The plate at rack proportions: the preview the thumbnail could+ never be, and the surface ports are placed on. Coordinates are unit+ fractions, so the blow-up never reaches the saved data. */}+ <div className="flex flex-col items-center gap-2 rounded border border-[#30363d] bg-[#0d1117] p-3">+ <PortPositionEditor+ faceplateId={faceplateId}+ label={label || getFaceplate(faceplateId).label}+ status={previewStatus}+ ports={ports}+ uHeight={uHeight}+ colSpan={colSpan}+ color={color}+ interactive={positioning && !isAccessory}+ selectedPortId={selectedPortId}+ onSelect={setSelectedPortId}+ onChange={setLocalPorts}+ />+ </div>+<div className="mt-1 flex items-center gap-2">{isEdit && (<Buttondiff --git a/frontend/src/rack/portLayout.ts b/frontend/src/rack/portLayout.tsnew file mode 100644index 0000000..c1f64bd--- /dev/null+++ b/frontend/src/rack/portLayout.ts@@ -0,0 +1,110 @@+/**+ * Where a port sits on its faceplate.+ *+ * Port coordinates are unit coordinates (0..1 on both axes), so the same numbers+ * describe the plate at any U height, rack width or zoom — see `faceplates.ts`.+ * Everything here is pure: the editor owns the pointer, this owns the maths.+ */+import type { Port } from '@/types'++/**+ * Keep a port off the very edge of the plate.+ *+ * The socket is drawn centred on its coordinate, so a port at x = 1 hangs half+ * outside the panel. The inset is roughly half a socket on a 1U plate.+ */+export const PORT_EDGE_INSET = 0.03++/** How close two ports must be, in pixels, before one snaps onto the other's axis. */+export const SNAP_PX = 6++export interface Point {+ x: number+ y: number+}++/**+ * Alignment guides to draw for a drag that snapped, in unit coordinates.+ * Null on an axis means the port is free there and no guide is shown.+ */+export interface SnapResult extends Point {+ guideX: number | null+ guideY: number | null+}++export function clampPort({ x, y }: Point): Point {+ const clamp = (v: number) => Math.min(1 - PORT_EDGE_INSET, Math.max(PORT_EDGE_INSET, v))+ return { x: clamp(x), y: clamp(y) }+}++/**+ * Snap distance on each axis, converted from pixels to unit coordinates.+ *+ * A plate is far wider than it is tall, so one shared unit threshold would snap+ * vertically at ten times the distance it snaps horizontally.+ */+export function snapThreshold(width: number, height: number, px: number = SNAP_PX): Point {+ return {+ x: width > 0 ? px / width : 0,+ y: height > 0 ? px / height : 0,+ }+}++/** Nearest value within `t`, or null when nothing is close enough. */+function nearest(value: number, values: number[], t: number): number | null {+ let best: number | null = null+ let bestDelta = t+ for (const candidate of values) {+ const delta = Math.abs(candidate - value)+ if (delta <= bestDelta) {+ best = candidate+ bestDelta = delta+ }+ }+ return best+}++/**+ * Pull a dragged port onto the nearest peer's row or column.+ *+ * Ports come in banks, and a bank only reads as one when its members share an+ * axis. Free dragging alone leaves a row of sockets a pixel out of line, which is+ * exactly the kind of thing nobody can fix by hand at this scale. Each axis snaps+ * on its own: a port can take its row from one peer and its column from another,+ * which is what makes a grid fall into place.+ */+export function snapToPeers(pos: Point, peers: Point[], threshold: Point): SnapResult {+ const { x, y } = clampPort(pos)+ const guideX = nearest(+ x,+ peers.map((p) => p.x),+ threshold.x,+ )+ const guideY = nearest(+ y,+ peers.map((p) => p.y),+ threshold.y,+ )+ return { x: guideX ?? x, y: guideY ?? y, guideX, guideY }+}++/** Horizontal step between two auto-placed ports, in unit coordinates. */+const NEXT_PORT_STEP = 0.06++/** Vertical drop when an auto-placed row runs into the right edge. */+const NEXT_ROW_STEP = 0.2++/**+ * Where a newly added port lands.+ *+ * Dropping every new port on the middle of the plate stacked them all on one+ * spot: the list said "3 ports" and the plate showed one. A new port continues+ * the last row instead, and wraps to a new one at the right edge.+ */+export function nextPortSpot(ports: Port[]): Point {+ const last = ports[ports.length - 1]+ if (!last) return { x: 0.5, y: 0.5 }+ const x = last.x + NEXT_PORT_STEP+ if (x <= 1 - PORT_EDGE_INSET) return { x, y: last.y }+ return clampPort({ x: PORT_EDGE_INSET, y: last.y + NEXT_ROW_STEP })+}diff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.tsindex 77017e5..edd8237 100644--- a/frontend/src/rack/store.ts+++ b/frontend/src/rack/store.ts@@ -289,6 +289,38 @@ function withRackedFlags(inventory: InventoryDevice[], devices: RackDevice[]): Ireturn inventory.map((item) => ({ ...item, racked: mounted.has(item.id) }))}+/**+ * Mirror a mount's front panel onto the inventory entry it stands for.+ *+ * The inventory row owns the rack modelisation (plate, size, colour, ports), so+ * a mount edit has to reach it — otherwise a second rack showing the same device+ * would keep the old panel until the next reload, and the tray would seed a new+ * mount from stale data. The backend does the same write-through on save; this+ * keeps the open session consistent in the meantime.+ *+ * Standalone has no inventory row to own anything, so ports stay per mount there.+ */+function withDeviceModel(+ inventory: InventoryDevice[],+ device: RackDevice | undefined,+): InventoryDevice[] {+ if (STANDALONE || !device?.deviceId) return inventory+ return inventory.map((item) =>+ item.id === device.deviceId+ ? {+ ...item,+ rackModel: {+ faceplateId: device.faceplateId,+ uHeight: device.uHeight,+ colSpan: device.colSpan,+ color: device.color ?? null,+ ports: device.ports,+ },+ }+ : item,+ )+}+export const useRackStore = create<RackState>((set, get) => {/** Apply a state patch and mark the canvas dirty. */const edit = (patch: Partial<RackState> | ((s: RackState) => Partial<RackState>)) =>@@ -509,12 +541,17 @@ export const useRackStore = create<RackState>((set, get) => {const item = inventory.find((i) => i.id === inventoryId)if (!rack || !item) return null- const plate = getFaceplate(desired.faceplateId ?? item.suggestedFaceplateId)+ // A device already modelled in another rack keeps that front panel — the+ // inventory row owns it. Only a never-racked device falls back to the+ // plate its type suggests.+ const model = STANDALONE ? null : item.rackModel ?? null+ const plate = getFaceplate(desired.faceplateId ?? model?.faceplateId ?? item.suggestedFaceplateId)+ const modelled = model?.faceplateId === plate.id ? model : nullconst slot = findSlot(rack, devices, {uStart: desired.uStart ?? 1,- uHeight: desired.uHeight ?? plate.uHeight,+ uHeight: desired.uHeight ?? modelled?.uHeight ?? plate.uHeight,colStart: desired.colStart ?? 0,- colSpan: desired.colSpan ?? plate.colSpan,+ colSpan: desired.colSpan ?? modelled?.colSpan ?? plate.colSpan,})if (!slot) return null@@ -526,7 +563,10 @@ export const useRackStore = create<RackState>((set, get) => {label: item.label,status: item.status,faceplateId: plate.id,- ports: withIds(plate.ports),+ color: modelled?.color ?? undefined,+ // Port ids are reused as-is: they are the device's, not the mount's, and+ // nothing outside this design's cables refers to them.+ ports: modelled ? modelled.ports.map((port) => ({ ...port })) : withIds(plate.ports),...slot,}edit((s) => {@@ -600,7 +640,10 @@ export const useRackStore = create<RackState>((set, get) => {if (!slot) return falseObject.assign(next, slot)}- edit((s) => ({ devices: s.devices.map((d) => (d.id === id ? next : d)) }))+ edit((s) => {+ const devicesNext = s.devices.map((d) => (d.id === id ? next : d))+ return { devices: devicesNext, inventory: withDeviceModel(s.inventory, next) }+ })return true},@@ -743,8 +786,10 @@ export const useRackStore = create<RackState>((set, get) => {edit((s) => {const next: Port[] = ports.map((p) => ('id' in p ? p : { ...p, id: generateUUID() }))const kept = new Set(next.map((p) => p.id))+ const devicesNext = s.devices.map((d) => (d.id === deviceId ? { ...d, ports: next } : d))return {- devices: s.devices.map((d) => (d.id === deviceId ? { ...d, ports: next } : d)),+ devices: devicesNext,+ inventory: withDeviceModel(s.inventory, devicesNext.find((d) => d.id === deviceId)),cables: s.cables.filter((c) =>!(c.from.deviceId === deviceId && !kept.has(c.from.portId)) &&diff --git a/frontend/src/types/rack.ts b/frontend/src/types/rack.tsindex b1db91e..39f706e 100644--- a/frontend/src/types/rack.ts+++ b/frontend/src/types/rack.ts@@ -63,6 +63,27 @@ export interface Port {y: number}+/**+ * The rack modelisation of a device — what it looks like in *any* rack.+ *+ * Owned by the Device Inventory row, not by the mount: a device wears the same+ * front panel, at the same size, with the same ports wherever it is racked.+ * Only its placement (`rackId`, `uStart`, `colStart`), its pinned status and its+ * label stay per canvas. Editing a mount writes this back, silently, for every+ * other rack.+ *+ * Full mode only. Standalone has no inventory to hang it on, so ports there stay+ * per mount (see `standaloneStorage`).+ */+export interface RackModel {+ faceplateId: string+ /** Null when the device was modelled before a size was recorded. */+ uHeight: number | null+ colSpan: number | null+ color: string | null+ ports: Port[]+}+// ---------------------------------------------------------------------------// Faceplates// ---------------------------------------------------------------------------@@ -267,4 +288,9 @@ export interface InventoryDevice {racked: boolean/** Faceplate proposed when the device is dropped into a rack. */suggestedFaceplateId: string+ /**+ * Front panel already modelled for this device, reused on every mount. Null+ * for a device never racked — `suggestedFaceplateId` then seeds the plate.+ */+ rackModel?: RackModel | null}diff --git a/frontend/src/utils/__tests__/rackSerializer.test.ts b/frontend/src/utils/__tests__/rackSerializer.test.tsindex e60c269..f54f585 100644--- a/frontend/src/utils/__tests__/rackSerializer.test.ts+++ b/frontend/src/utils/__tests__/rackSerializer.test.ts@@ -187,6 +187,53 @@ describe('API → domain', () => {expect(item.racked).toBe(true)})+ it('reads back the rack modelisation the inventory row owns', () => {+ const item = toInventoryDevice({+ id: 'inv4',+ label: 'sw-01',+ suggested_type: 'switch',+ ip: null,+ status: 'approved',+ discovery_source: 'manual',+ node_id: null,+ node_status: null,+ racked: true,+ rack_faceplate_id: 'switch-24',+ rack_u_height: 1,+ rack_col_span: 12,+ rack_color: '#ff6e00',+ rack_ports: [+ { id: 'p1', label: 'uplink', type: 'sfp', x: 0.9, y: 0.4 },+ // No id: not a port, and nothing can cable it.+ { label: 'ghost', type: 'rj45', x: 0.1, y: 0.1 },+ ],+ })+ expect(item.rackModel).toEqual({+ faceplateId: 'switch-24',+ uHeight: 1,+ colSpan: 12,+ color: '#ff6e00',+ ports: [{ id: 'p1', label: 'uplink', type: 'sfp', x: 0.9, y: 0.4 }],+ })+ })++ it('reports no modelisation for a device that has never been racked', () => {+ const item = toInventoryDevice({+ id: 'inv5',+ label: 'nas',+ suggested_type: 'nas',+ ip: null,+ status: 'pending',+ discovery_source: 'arp',+ node_id: null,+ node_status: null,+ racked: false,+ })+ // An older backend sends none of the rack_* fields at all.+ expect(item.rackModel).toBeNull()+ expect(item.suggestedFaceplateId).toBe('nas-2u')+ })+it('carries the linked node detail the rack prints beside a mount', () => {const item = toInventoryDevice({id: 'inv3',diff --git a/frontend/src/utils/rackSerializer.ts b/frontend/src/utils/rackSerializer.tsindex 486956f..cd3fb38 100644--- a/frontend/src/utils/rackSerializer.ts+++ b/frontend/src/utils/rackSerializer.ts@@ -20,6 +20,7 @@ import type {PortType,Rack,RackDevice,+ RackModel,RackNumbering,RackStyle,RackWidthStandard,@@ -105,6 +106,13 @@ export interface ApiInventoryItem {node_design_id?: string | nullnode_design_name?: string | nullnode_last_seen?: string | null+ // Rack modelisation the inventory row owns. Absent on an older backend, and+ // null on a device that has never been racked.+ rack_faceplate_id?: string | null+ rack_u_height?: number | null+ rack_col_span?: number | null+ rack_color?: string | null+ rack_ports?: unknown[] | null}export interface RackSavePayload {@@ -274,6 +282,24 @@ function asLinkedNode(api: ApiInventoryItem): LinkedNodeInfo | null {}}+/**+ * The device's saved front panel, or null when it has never been modelled.+ *+ * `rack_faceplate_id` is the flag the backend sets on the first save of a mount;+ * without it there is nothing to reuse and the tray falls back to the plate+ * suggested by the device type.+ */+function asRackModel(api: ApiInventoryItem): RackModel | null {+ if (!api.rack_faceplate_id) return null+ return {+ faceplateId: api.rack_faceplate_id,+ uHeight: typeof api.rack_u_height === 'number' ? api.rack_u_height : null,+ colSpan: typeof api.rack_col_span === 'number' ? api.rack_col_span : null,+ color: api.rack_color ?? null,+ ports: asPorts(Array.isArray(api.rack_ports) ? api.rack_ports : []),+ }+}+export function toInventoryDevice(api: ApiInventoryItem): InventoryDevice {return {id: api.id,@@ -292,6 +318,7 @@ export function toInventoryDevice(api: ApiInventoryItem): InventoryDevice {node: asLinkedNode(api),racked: api.racked,suggestedFaceplateId: suggestFaceplate(api.suggested_type),+ rackModel: asRackModel(api),}}