Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(rack): document a cable and print it on the canvas
Pouzor4d2128c4941b
diff --git a/backend/app/db/database.py b/backend/app/db/database.pyindex 79088f4..df0889b 100644--- a/backend/app/db/database.py+++ b/backend/app/db/database.py@@ -286,6 +286,22 @@ async def init_db() -> None:logger.warning("canvas_state migration failed: %s", exc)# --- end Electrical designs schema migrations --------------------------+ # Rack cables gained editable annotations: a label the user can print on+ # the canvas, plus the same free-form property records nodes carry.+ rack_cable_migrations: list[tuple[str, str]] = [+ (+ "rack_cables.label_visible",+ "ALTER TABLE rack_cables ADD COLUMN label_visible BOOLEAN NOT NULL DEFAULT 0",+ ),+ ("rack_cables.properties", "ALTER TABLE rack_cables ADD COLUMN properties JSON"),+ ]+ for label, sql in rack_cable_migrations:+ await _try_migrate(conn, sql, label=label)+ with suppress(OperationalError):+ await conn.exec_driver_sql(+ "UPDATE rack_cables SET properties = '[]' WHERE properties IS NULL"+ )+with suppress(OperationalError):await conn.exec_driver_sql("ALTER TABLE edges ADD COLUMN waypoints JSON")with suppress(OperationalError):diff --git a/backend/app/db/models.py b/backend/app/db/models.pyindex b5e45ee..79ae719 100644--- a/backend/app/db/models.py+++ b/backend/app/db/models.py@@ -195,6 +195,11 @@ class RackCable(Base):type: Mapped[str] = mapped_column(String, default="ethernet")color: Mapped[str] = mapped_column(String, default="#39d353")label: Mapped[str | None] = mapped_column(String, nullable=True)+ # Print the label next to the run on the canvas.+ label_visible: Mapped[bool] = mapped_column(Boolean, default=False)+ # [{key, value, icon, visible}] — same records nodes carry; the visible ones+ # are drawn beside the cable.+ properties: Mapped[list[Any]] = mapped_column(JSON, default=list)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)diff --git a/backend/app/schemas/racks.py b/backend/app/schemas/racks.pyindex 4360dcd..ff1de24 100644--- a/backend/app/schemas/racks.py+++ b/backend/app/schemas/racks.py@@ -89,6 +89,9 @@ class RackCableSave(BaseModel):type: str = "ethernet"color: str = "#39d353"label: str | None = None+ label_visible: bool = False+ # [{key, value, icon, visible}] — free-form, same shape as node properties.+ properties: list[dict[str, Any]] = []@field_validator("type")@classmethod@@ -97,6 +100,14 @@ class RackCableSave(BaseModel):raise ValueError(f"type must be one of {sorted(CABLE_TYPES)}")return v+ @field_validator("properties", mode="before")+ @classmethod+ def _clean_properties(cls, v: Any) -> list[dict[str, Any]]:+ """Keep only usable records — a property with no key draws an empty badge."""+ if not isinstance(v, list):+ return []+ return [p for p in v if isinstance(p, dict) and str(p.get("key", "")).strip()]+class RackSaveRequest(BaseModel):"""Full rack state for one design — upserted, with anything missing pruned.@@ -167,6 +178,19 @@ class RackCableResponse(BaseModel):type: strcolor: strlabel: str | None = None+ label_visible: bool = False+ properties: list[dict[str, Any]] = []++ @field_validator("properties", mode="before")+ @classmethod+ def _list_properties(cls, v: Any) -> list[dict[str, Any]]:+ """Rows written before the column existed read back as NULL."""+ return v if isinstance(v, list) else []++ @field_validator("label_visible", mode="before")+ @classmethod+ def _bool_label_visible(cls, v: Any) -> bool:+ return bool(v)model_config = {"from_attributes": True}diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.pyindex 60f5d7c..8fe57ed 100644--- a/backend/tests/test_racks.py+++ b/backend/tests/test_racks.py@@ -233,6 +233,83 @@ class TestSaveAndLoad:res = await client.post("/api/v1/racks/save", json=payload, headers=headers)assert res.status_code == 422+ async def test_round_trips_cable_annotations(self, client: AsyncClient, headers):+ design_id = await _design(client, headers)+ payload = _state(design_id)+ payload["cables"][0].update(+ {+ "label": "Uplink to core",+ "label_visible": True,+ "properties": [+ {"key": "Length", "value": "2 m", "icon": None, "visible": True},+ {"key": "VLAN", "value": "20", "icon": None, "visible": False},+ ],+ }+ )+ assert (+ await client.post("/api/v1/racks/save", json=payload, headers=headers)+ ).status_code == 200++ cable = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["cables"][0]+ assert cable["label"] == "Uplink to core"+ assert cable["label_visible"] is True+ assert [p["key"] for p in cable["properties"]] == ["Length", "VLAN"]+ assert cable["properties"][1]["visible"] is False++ async def test_defaults_cable_annotations_when_absent(+ self, client: AsyncClient, headers+ ):+ # A client that predates the feature sends neither key; the response must+ # still carry usable values rather than nulls.+ design_id = await _design(client, headers)+ assert (+ await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)+ ).status_code == 200++ cable = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["cables"][0]+ assert cable["label_visible"] is False+ assert cable["properties"] == []++ async def test_drops_cable_properties_with_no_key(self, client: AsyncClient, headers):+ design_id = await _design(client, headers)+ payload = _state(design_id)+ payload["cables"][0]["properties"] = [+ {"key": " ", "value": "orphan", "icon": None, "visible": True},+ {"key": "Length", "value": "2 m", "icon": None, "visible": True},+ ]+ assert (+ await client.post("/api/v1/racks/save", json=payload, headers=headers)+ ).status_code == 200++ cable = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["cables"][0]+ assert [p["key"] for p in cable["properties"]] == ["Length"]++ async def test_updates_cable_annotations_on_a_second_save(+ self, client: AsyncClient, headers+ ):+ design_id = await _design(client, headers)+ payload = _state(design_id)+ payload["cables"][0]["properties"] = [+ {"key": "Length", "value": "2 m", "icon": None, "visible": True}+ ]+ await client.post("/api/v1/racks/save", json=payload, headers=headers)++ payload["cables"][0]["properties"] = []+ payload["cables"][0]["label_visible"] = True+ await client.post("/api/v1/racks/save", json=payload, headers=headers)++ cable = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["cables"][0]+ assert cable["properties"] == []+ assert cable["label_visible"] is True+async def test_requires_auth(self, client: AsyncClient):assert (await client.get("/api/v1/racks?design_id=any")).status_code == 401diff --git a/docs/rack-canvas.md b/docs/rack-canvas.mdindex cb6326a..4079906 100644--- a/docs/rack-canvas.md+++ b/docs/rack-canvas.md@@ -148,8 +148,26 @@ To unplug: **click the cable** (it gets an accent halo), then pressdestroys a patch.A header select controls what you see: cables **on hover**, **always**, or-**hidden**. With cables shown, plates fade so the patching reads clearly. Cables-pan and zoom with the canvas and may run from one rack to another.+**hidden**. Cables+pan and zoom with the canvas and may run from one rack to another. A cable you+have selected stays drawn whatever that select says.++### Documenting a cable++**Click a cable** — patching or not — and a panel opens on the right:++| Field | What it does |+|---|---|+| Endpoints | The two devices and ports the run connects. Read-only: move a patch by unplugging it and drawing it again. |+| Type | Ethernet or fibre. A cable still wearing its type's default colour is recoloured to match; a colour you picked yourself is kept. |+| Colour | The sheath colours you actually have on the shelf, plus a free hex field for anything else. |+| Label | A name for the run — "Uplink to core", a patch-panel reference. **Show on canvas** prints it next to the cable. |+| Properties | Anything else worth recording: length, VLAN, speed, category, patch reference. Same editor as a node's properties on a diagram — a label, a value, an optional icon, and an eye that decides whether it shows on the canvas. |+| Unplug cable | Removes the patch. The devices and their ports stay. |++What you tick as visible is drawn on a small plate at the middle of the run, so a+rack photo exports with its cable lengths and VLANs on it. Everything else stays+in the panel, one click away.### Import links 🔒diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 457ea81..d8459ae 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -53,6 +53,7 @@ import { DEMO_SCAN_RUNS, DEMO_PENDING_DEVICES } from '@/walkthrough/demoTourDataimport { useStatusPolling } from '@/hooks/useStatusPolling'import { bootstrapAuth } from '@/auth/bootstrap'import { RackCanvas } from '@/rack/components/RackCanvas'+import { RackCablePanel } from '@/rack/components/RackCablePanel'import { useRackStore } from '@/rack/store'import type { NodeData, EdgeData, CustomStyleDef, DesignType, FloorMapConfig, NodeType } from '@/types'import type { ZigbeeNode, ZigbeeEdge } from '@/components/zigbee/types'@@ -1049,11 +1050,14 @@ export default function App() {/>)}</div>- {/* Rack designs have no right rail: a mount is edited in its own- modal, so the canvas keeps the full width. */}- {!isRackDesign && (selectedNodeId || selectedNodeIds.length > 1) && (- <DetailPanel onEdit={handleEditNode} />- )}+ {/* Rack designs keep the full width for mounted gear — a mount is+ edited in its own modal — but a selected cable has no plate to+ double-click, so it gets the rail. */}+ {isRackDesign+ ? <RackCablePanel />+ : (selectedNodeId || selectedNodeIds.length > 1) && (+ <DetailPanel onEdit={handleEditNode} />+ )}</div></div></div>diff --git a/frontend/src/components/common/PropertyList.tsx b/frontend/src/components/common/PropertyList.tsxnew file mode 100644index 0000000..8703a78--- /dev/null+++ b/frontend/src/components/common/PropertyList.tsx@@ -0,0 +1,323 @@+/**+ * Editable list of `NodeProperty` records — key, value, optional icon, and a+ * per-property "show it on the canvas" toggle.+ *+ * Extracted from `DetailPanel` so the rack cable panel gets the same editor+ * rather than a second implementation of it. The component owns only its form+ * and drag state; the array itself belongs to the caller, which receives every+ * mutation as a whole new array through `onChange`.+ */+import { createElement, useState } from 'react'+import { Eye, EyeOff, GripVertical, Pencil, Plus, X } from 'lucide-react'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { PROPERTY_ICONS, PROPERTY_ICON_NAMES, resolvePropertyIcon } from '@/utils/propertyIcons'+import type { NodeProperty } from '@/types'++export type PropForm = { key: string; value: string; icon: string | null; visible: boolean }+const EMPTY_PROP: PropForm = { key: '', value: '', icon: null, visible: true }++interface PropertyListProps {+ properties: NodeProperty[]+ /** Receives the full next array — the caller decides how to persist it. */+ onChange: (next: NodeProperty[]) => void+ /** Wording of the per-property visibility toggle ("Show on node" by default). */+ visibleLabel?: string+ /** Placeholder examples, so a cable does not suggest "CPU Model". */+ keyPlaceholder?: string+ valuePlaceholder?: string+ /** One-click keys pre-filling the add form (e.g. Length, VLAN). */+ suggestions?: string[]+ /** Section heading. */+ title?: string+ emptyHint?: string+}++export function PropertyList({+ properties,+ onChange,+ visibleLabel = 'Show on node',+ keyPlaceholder = 'Label (e.g. CPU Model)',+ valuePlaceholder = 'Value (e.g. i7-12700K)',+ suggestions,+ title = 'Properties',+ emptyHint = 'No properties — click Add to define one.',+}: PropertyListProps) {+ const [adding, setAdding] = useState(false)+ const [newProp, setNewProp] = useState<PropForm>(EMPTY_PROP)+ const [editingIndex, setEditingIndex] = useState<number | null>(null)+ const [editProp, setEditProp] = useState<PropForm>(EMPTY_PROP)+ const [dragIndex, setDragIndex] = useState<number | null>(null)+ const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)++ const handleAdd = () => {+ if (!newProp.key.trim() || !newProp.value.trim()) return+ onChange([+ ...properties,+ { key: newProp.key.trim(), value: newProp.value.trim(), icon: newProp.icon, visible: newProp.visible },+ ])+ setNewProp(EMPTY_PROP)+ setAdding(false)+ }++ const handleRemove = (index: number) => {+ onChange(properties.filter((_, i) => i !== index))+ if (editingIndex === index) setEditingIndex(null)+ }++ const handleToggleVisible = (index: number) => {+ onChange(properties.map((p, i) => (i === index ? { ...p, visible: !p.visible } : p)))+ }++ const handleStartEdit = (index: number) => {+ const p = properties[index]+ if (!p) return+ setEditProp({ key: p.key, value: p.value, icon: p.icon, visible: p.visible })+ setEditingIndex(index)+ setAdding(false)+ }++ const handleSaveEdit = () => {+ if (editingIndex === null || !editProp.key.trim() || !editProp.value.trim()) return+ onChange(+ properties.map((p, i) =>+ i === editingIndex+ ? { key: editProp.key.trim(), value: editProp.value.trim(), icon: editProp.icon, visible: editProp.visible }+ : p+ )+ )+ setEditingIndex(null)+ }++ const handleReorder = (from: number, to: number) => {+ if (from === to || from < 0 || to < 0 || from >= properties.length || to >= properties.length) return+ const reordered = [...properties]+ const [moved] = reordered.splice(from, 1)+ reordered.splice(to, 0, moved)+ onChange(reordered)+ }++ const startAddWith = (key: string) => {+ setEditingIndex(null)+ setNewProp({ ...EMPTY_PROP, key })+ setAdding(true)+ }++ return (+ <div className="px-4 py-3 border-t border-border">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs text-muted-foreground">{title}{properties.length > 0 ? ` (${properties.length})` : ''}</span>+ <button+ onClick={() => { setAdding((v) => !v); setEditingIndex(null) }}+ className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer"+ >+ <Plus size={10} /> Add+ </button>+ </div>+ {suggestions && suggestions.length > 0 && !adding && (+ <div className="flex flex-wrap gap-1 mb-2">+ {suggestions.map((key) => (+ <button+ key={key}+ onClick={() => startAddWith(key)}+ title={`Add a ${key} property`}+ className="rounded border border-[#30363d] px-1.5 py-0.5 text-[10px] text-muted-foreground hover:border-[#00d4ff] hover:text-[#00d4ff] transition-colors cursor-pointer"+ >+ + {key}+ </button>+ ))}+ </div>+ )}+ {adding && (+ <PropertyForm+ form={newProp}+ onChange={setNewProp}+ onConfirm={handleAdd}+ onCancel={() => { setAdding(false); setNewProp(EMPTY_PROP) }}+ confirmLabel="Add"+ visibleLabel={visibleLabel}+ keyPlaceholder={keyPlaceholder}+ valuePlaceholder={valuePlaceholder}+ />+ )}+ {properties.length > 0 && (+ <div className="flex flex-col gap-1.5">+ {properties.map((prop, i) =>+ editingIndex === i ? (+ <PropertyForm+ key={`edit-${i}`}+ form={editProp}+ onChange={setEditProp}+ onConfirm={handleSaveEdit}+ onCancel={() => setEditingIndex(null)}+ confirmLabel="Save"+ visibleLabel={visibleLabel}+ keyPlaceholder={keyPlaceholder}+ valuePlaceholder={valuePlaceholder}+ />+ ) : (+ <PropertyBadge+ key={`${prop.key}-${i}`}+ prop={prop}+ visibleLabel={visibleLabel}+ draggable={properties.length > 1}+ isDragging={dragIndex === i}+ isDragOver={dragOverIndex === i && dragIndex !== i}+ onDragStart={() => setDragIndex(i)}+ onDragEnter={() => { if (dragIndex !== null) setDragOverIndex(i) }}+ onDragEnd={() => { setDragIndex(null); setDragOverIndex(null) }}+ onDrop={() => {+ if (dragIndex !== null) handleReorder(dragIndex, i)+ setDragIndex(null)+ setDragOverIndex(null)+ }}+ onToggleVisible={() => handleToggleVisible(i)}+ onEdit={() => handleStartEdit(i)}+ onRemove={() => handleRemove(i)}+ />+ )+ )}+ </div>+ )}+ {properties.length === 0 && !adding && (+ <p className="text-[10px] text-muted-foreground/50">{emptyHint}</p>+ )}+ </div>+ )+}++export function PropertyForm({ form, onChange, onConfirm, onCancel, confirmLabel, visibleLabel = 'Show on node', keyPlaceholder = 'Label (e.g. CPU Model)', valuePlaceholder = 'Value (e.g. i7-12700K)' }: {+ form: PropForm+ onChange: (f: PropForm) => void+ onConfirm: () => void+ onCancel: () => void+ confirmLabel: string+ visibleLabel?: string+ keyPlaceholder?: string+ valuePlaceholder?: string+}) {+ return (+ <div className="flex flex-col gap-1.5 mb-1 p-2 rounded-md bg-[#0d1117] border border-[#30363d]">+ <Input+ value={form.key}+ onChange={(e) => onChange({ ...form, key: e.target.value })}+ placeholder={keyPlaceholder}+ className="bg-[#21262d] border-[#30363d] text-xs h-7"+ autoFocus+ onKeyDown={(e) => e.key === 'Enter' && onConfirm()}+ />+ <Input+ value={form.value}+ onChange={(e) => onChange({ ...form, value: e.target.value })}+ placeholder={valuePlaceholder}+ className="bg-[#21262d] border-[#30363d] text-xs h-7"+ onKeyDown={(e) => e.key === 'Enter' && onConfirm()}+ />+ {/* Icon picker */}+ <div className="flex flex-wrap gap-1 pt-0.5">+ <button+ onClick={() => onChange({ ...form, icon: null })}+ title="No icon"+ className={`w-6 h-6 rounded flex items-center justify-center text-[10px] border transition-colors ${+ form.icon === null ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]' : 'border-[#30363d] text-muted-foreground hover:border-[#8b949e]'+ }`}+ >+ –+ </button>+ {PROPERTY_ICON_NAMES.map((name) => {+ const Icon = PROPERTY_ICONS[name]+ const active = form.icon === name+ return (+ <button+ key={name}+ onClick={() => onChange({ ...form, icon: name })}+ title={name}+ className={`w-6 h-6 rounded flex items-center justify-center border transition-colors ${+ active ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]' : 'border-[#30363d] text-muted-foreground hover:border-[#8b949e]'+ }`}+ >+ {createElement(Icon, { size: 11 })}+ </button>+ )+ })}+ </div>+ {/* Visible toggle */}+ <label className="flex items-center gap-2 cursor-pointer pt-0.5">+ <input+ type="checkbox"+ checked={form.visible}+ onChange={(e) => onChange({ ...form, visible: e.target.checked })}+ className="accent-[#00d4ff] w-3 h-3"+ />+ <span className="text-[10px] text-muted-foreground">{visibleLabel}</span>+ </label>+ <div className="flex gap-1.5">+ <Button size="sm" className="flex-1 h-6 text-[10px] bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90" onClick={onConfirm}>+ {confirmLabel}+ </Button>+ <Button size="sm" variant="ghost" className="h-6 text-[10px]" onClick={onCancel}>Cancel</Button>+ </div>+ </div>+ )+}++export function PropertyBadge({ prop, visibleLabel = 'node', draggable, isDragging, isDragOver, onDragStart, onDragEnter, onDragEnd, onDrop, onToggleVisible, onEdit, onRemove }: {+ prop: NodeProperty+ /** Used to word the eye tooltip — "Show on node" / "Show on canvas". */+ visibleLabel?: string+ draggable: boolean+ isDragging: boolean+ isDragOver: boolean+ onDragStart: () => void+ onDragEnter: () => void+ onDragEnd: () => void+ onDrop: () => void+ onToggleVisible: () => void+ onEdit: () => void+ onRemove: () => void+}) {+ const Icon = resolvePropertyIcon(prop.icon)+ const where = visibleLabel.replace(/^Show on /i, '')+ return (+ <div+ draggable={draggable}+ onDragStart={onDragStart}+ onDragEnter={onDragEnter}+ onDragOver={(e) => e.preventDefault()}+ onDragEnd={onDragEnd}+ onDrop={(e) => { e.preventDefault(); onDrop() }}+ className="group flex items-center justify-between gap-2 px-2 py-1.5 rounded-md border text-xs transition-colors"+ style={{+ background: '#21262d',+ borderColor: isDragOver ? '#00d4ff' : '#30363d',+ opacity: isDragging ? 0.4 : 1,+ }}+ >+ <div className="flex items-center gap-1.5 min-w-0">+ {draggable && (+ <span className="shrink-0 cursor-grab active:cursor-grabbing text-[#8b949e] hover:text-[#00d4ff]" title="Drag to reorder">+ {createElement(GripVertical, { size: 11 })}+ </span>+ )}+ {Icon && createElement(Icon, { size: 11, className: 'shrink-0 text-muted-foreground' })}+ <span className="font-medium truncate text-foreground" title={prop.key}>{prop.key}</span>+ <span className="text-muted-foreground truncate" title={prop.value}>· {prop.value}</span>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={onToggleVisible}+ title={prop.visible ? `Hide on ${where}` : `Show on ${where}`}+ className="text-[#8b949e] hover:text-[#00d4ff] transition-colors"+ >+ {prop.visible ? <Eye size={10} /> : <EyeOff size={10} />}+ </button>+ <button onClick={onEdit} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#00d4ff]" title="Edit property">+ <Pencil size={10} />+ </button>+ <button onClick={onRemove} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#f85149]" title="Remove property">+ <X size={10} />+ </button>+ </div>+ </div>+ )+}diff --git a/frontend/src/components/panels/DetailPanel.tsx b/frontend/src/components/panels/DetailPanel.tsxindex fc78bee..5e5a30d 100644--- a/frontend/src/components/panels/DetailPanel.tsx+++ b/frontend/src/components/panels/DetailPanel.tsx@@ -7,7 +7,7 @@ import { useCanvasStore, serviceStatusKey } from '@/stores/canvasStore'import { NODE_TYPE_LABELS, STATUS_COLORS, type ServiceInfo, type ServiceStatus, type NodeData, type NodeProperty } from '@/types'import { getServiceUrl } from '@/utils/serviceUrl'import { splitIps } from '@/utils/maskIp'-import { PROPERTY_ICONS, PROPERTY_ICON_NAMES, resolvePropertyIcon } from '@/utils/propertyIcons'+import { PropertyList } from '@/components/common/PropertyList'import { formatTimestamp } from '@/utils/timeFormat'import { ServiceModal } from '@/components/modals/ServiceModal'import { serviceToForm, type ServiceFormData, type ServiceSubmitData } from '@/utils/serviceForm'@@ -21,9 +21,6 @@ interface DetailPanelProps {/** Open service editor: `index === null` means "add a new service". */type SvcModalState = { nodeId: string; index: number | null; form?: ServiceFormData }-type PropForm = { key: string; value: string; icon: string | null; visible: boolean }-const EMPTY_PROP: PropForm = { key: '', value: '', icon: null, visible: true }-export function DetailPanel({ onEdit }: DetailPanelProps) {const { nodes, selectedNodeId, selectedNodeIds, setSelectedNode, deleteNode, updateNode, snapshotHistory, createGroup, ungroup, removeFromGroup, setNodeSize } = useCanvasStore()const serviceStatuses = useCanvasStore((s) => s.serviceStatuses)@@ -32,13 +29,6 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {const [groupName, setGroupName] = useState('')const [creatingGroup, setCreatingGroup] = useState(false)- // Properties state- const [addingProp, setAddingProp] = useState(false)- const [newProp, setNewProp] = useState<PropForm>(EMPTY_PROP)- const [editingPropIndex, setEditingPropIndex] = useState<number | null>(null)- const [editProp, setEditProp] = useState<PropForm>(EMPTY_PROP)- const [dragPropIndex, setDragPropIndex] = useState<number | null>(null)- const [dragOverPropIndex, setDragOverPropIndex] = useState<number | null>(null)const [dragSvcIndex, setDragSvcIndex] = useState<number | null>(null)const [dragOverSvcIndex, setDragOverSvcIndex] = useState<number | null>(null)@@ -157,56 +147,9 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {// --- Property handlers ---const properties: NodeProperty[] = data.properties ?? []- const handleAddProp = () => {- if (!newProp.key.trim() || !newProp.value.trim()) return- snapshotHistory()- const prop: NodeProperty = { key: newProp.key.trim(), value: newProp.value.trim(), icon: newProp.icon, visible: newProp.visible }- updateNode(node.id, { properties: [...properties, prop] })- setNewProp(EMPTY_PROP)- setAddingProp(false)- }-- const handleRemoveProp = (index: number) => {- snapshotHistory()- updateNode(node.id, { properties: properties.filter((_, i) => i !== index) })- if (editingPropIndex === index) setEditingPropIndex(null)- }-- const handleTogglePropVisible = (index: number) => {- snapshotHistory()- updateNode(node.id, {- properties: properties.map((p, i) => i === index ? { ...p, visible: !p.visible } : p),- })- }-- const handleStartEditProp = (index: number) => {- const p = properties[index]- if (!p) return- setEditProp({ key: p.key, value: p.value, icon: p.icon, visible: p.visible })- setEditingPropIndex(index)- setAddingProp(false)- }-- const handleSaveEditProp = () => {- if (editingPropIndex === null || !editProp.key.trim() || !editProp.value.trim()) return+ const handleChangeProps = (next: NodeProperty[]) => {snapshotHistory()- updateNode(node.id, {- properties: properties.map((p, i) =>- i === editingPropIndex- ? { key: editProp.key.trim(), value: editProp.value.trim(), icon: editProp.icon, visible: editProp.visible }- : p- ),- })- setEditingPropIndex(null)- }-- const handleReorderProp = (from: number, to: number) => {- if (from === to || from < 0 || to < 0 || from >= properties.length || to >= properties.length) return- snapshotHistory()- const reordered = [...properties]- const [moved] = reordered.splice(from, 1)- reordered.splice(to, 0, moved)- updateNode(node.id, { properties: reordered })+ updateNode(node.id, { properties: next })}return (@@ -274,64 +217,7 @@ export function DetailPanel({ onEdit }: DetailPanelProps) {/>{/* Properties section */}- <div className="px-4 py-3 border-t border-border">- <div className="flex items-center justify-between mb-2">- <span className="text-xs text-muted-foreground">Properties{properties.length > 0 ? ` (${properties.length})` : ''}</span>- <button- onClick={() => { setAddingProp((v) => !v); setEditingPropIndex(null) }}- className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer"- >- <Plus size={10} /> Add- </button>- </div>- {addingProp && (- <PropertyForm- form={newProp}- onChange={setNewProp}- onConfirm={handleAddProp}- onCancel={() => { setAddingProp(false); setNewProp(EMPTY_PROP) }}- confirmLabel="Add"- />- )}- {properties.length > 0 && (- <div className="flex flex-col gap-1.5">- {properties.map((prop, i) =>- editingPropIndex === i ? (- <PropertyForm- key={`edit-${i}`}- form={editProp}- onChange={setEditProp}- onConfirm={handleSaveEditProp}- onCancel={() => setEditingPropIndex(null)}- confirmLabel="Save"- />- ) : (- <PropertyBadge- key={`${prop.key}-${i}`}- prop={prop}- draggable={properties.length > 1}- isDragging={dragPropIndex === i}- isDragOver={dragOverPropIndex === i && dragPropIndex !== i}- onDragStart={() => setDragPropIndex(i)}- onDragEnter={() => { if (dragPropIndex !== null) setDragOverPropIndex(i) }}- onDragEnd={() => { setDragPropIndex(null); setDragOverPropIndex(null) }}- onDrop={() => {- if (dragPropIndex !== null) handleReorderProp(dragPropIndex, i)- setDragPropIndex(null)- setDragOverPropIndex(null)- }}- onToggleVisible={() => handleTogglePropVisible(i)}- onEdit={() => handleStartEditProp(i)}- onRemove={() => handleRemoveProp(i)}- />- )- )}- </div>- )}- {properties.length === 0 && !addingProp && (- <p className="text-[10px] text-muted-foreground/50">No properties — click Add to define one.</p>- )}- </div>+ <PropertyList properties={properties} onChange={handleChangeProps} /><div className="px-4 py-3 border-t border-border"><div className="flex items-center justify-between mb-2">@@ -689,138 +575,6 @@ function DetailRow({ label, value, mono }: { label: string; value: string; mono?)}-// --- Property components -----function PropertyForm({ form, onChange, onConfirm, onCancel, confirmLabel }: {- form: PropForm- onChange: (f: PropForm) => void- onConfirm: () => void- onCancel: () => void- confirmLabel: string-}) {- return (- <div className="flex flex-col gap-1.5 mb-1 p-2 rounded-md bg-[#0d1117] border border-[#30363d]">- <Input- value={form.key}- onChange={(e) => onChange({ ...form, key: e.target.value })}- placeholder="Label (e.g. CPU Model)"- className="bg-[#21262d] border-[#30363d] text-xs h-7"- autoFocus- onKeyDown={(e) => e.key === 'Enter' && onConfirm()}- />- <Input- value={form.value}- onChange={(e) => onChange({ ...form, value: e.target.value })}- placeholder="Value (e.g. i7-12700K)"- className="bg-[#21262d] border-[#30363d] text-xs h-7"- onKeyDown={(e) => e.key === 'Enter' && onConfirm()}- />- {/* Icon picker */}- <div className="flex flex-wrap gap-1 pt-0.5">- <button- onClick={() => onChange({ ...form, icon: null })}- title="No icon"- className={`w-6 h-6 rounded flex items-center justify-center text-[10px] border transition-colors ${- form.icon === null ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]' : 'border-[#30363d] text-muted-foreground hover:border-[#8b949e]'- }`}- >- –- </button>- {PROPERTY_ICON_NAMES.map((name) => {- const Icon = PROPERTY_ICONS[name]- const active = form.icon === name- return (- <button- key={name}- onClick={() => onChange({ ...form, icon: name })}- title={name}- className={`w-6 h-6 rounded flex items-center justify-center border transition-colors ${- active ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]' : 'border-[#30363d] text-muted-foreground hover:border-[#8b949e]'- }`}- >- {createElement(Icon, { size: 11 })}- </button>- )- })}- </div>- {/* Visible toggle */}- <label className="flex items-center gap-2 cursor-pointer pt-0.5">- <input- type="checkbox"- checked={form.visible}- onChange={(e) => onChange({ ...form, visible: e.target.checked })}- className="accent-[#00d4ff] w-3 h-3"- />- <span className="text-[10px] text-muted-foreground">Show on node</span>- </label>- <div className="flex gap-1.5">- <Button size="sm" className="flex-1 h-6 text-[10px] bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90" onClick={onConfirm}>- {confirmLabel}- </Button>- <Button size="sm" variant="ghost" className="h-6 text-[10px]" onClick={onCancel}>Cancel</Button>- </div>- </div>- )-}--function PropertyBadge({ prop, draggable, isDragging, isDragOver, onDragStart, onDragEnter, onDragEnd, onDrop, onToggleVisible, onEdit, onRemove }: {- prop: NodeProperty- draggable: boolean- isDragging: boolean- isDragOver: boolean- onDragStart: () => void- onDragEnter: () => void- onDragEnd: () => void- onDrop: () => void- onToggleVisible: () => void- onEdit: () => void- onRemove: () => void-}) {- const Icon = resolvePropertyIcon(prop.icon)- return (- <div- draggable={draggable}- onDragStart={onDragStart}- onDragEnter={onDragEnter}- onDragOver={(e) => e.preventDefault()}- onDragEnd={onDragEnd}- onDrop={(e) => { e.preventDefault(); onDrop() }}- className="group flex items-center justify-between gap-2 px-2 py-1.5 rounded-md border text-xs transition-colors"- style={{- background: '#21262d',- borderColor: isDragOver ? '#00d4ff' : '#30363d',- opacity: isDragging ? 0.4 : 1,- }}- >- <div className="flex items-center gap-1.5 min-w-0">- {draggable && (- <span className="shrink-0 cursor-grab active:cursor-grabbing text-[#8b949e] hover:text-[#00d4ff]" title="Drag to reorder">- {createElement(GripVertical, { size: 11 })}- </span>- )}- {Icon && createElement(Icon, { size: 11, className: 'shrink-0 text-muted-foreground' })}- <span className="font-medium truncate text-foreground" title={prop.key}>{prop.key}</span>- <span className="text-muted-foreground truncate" title={prop.value}>· {prop.value}</span>- </div>- <div className="flex items-center gap-1 shrink-0">- <button- onClick={onToggleVisible}- title={prop.visible ? 'Hide on node' : 'Show on node'}- className="text-[#8b949e] hover:text-[#00d4ff] transition-colors"- >- {prop.visible ? <Eye size={10} /> : <EyeOff size={10} />}- </button>- <button onClick={onEdit} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#00d4ff]" title="Edit property">- <Pencil size={10} />- </button>- <button onClick={onRemove} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#8b949e] hover:text-[#f85149]" title="Remove property">- <X size={10} />- </button>- </div>- </div>- )-}-const CATEGORY_COLORS: Record<string, string> = {web: '#00d4ff', database: '#a855f7', monitoring: '#39d353', storage: '#e3b341', security: '#f85149', remote: '#8b949e',}diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdindex ce314eb..890411e 100644--- a/frontend/src/rack/README.md+++ b/frontend/src/rack/README.md@@ -24,7 +24,8 @@ Create one from **New Canvas → Kind → Rack**.| 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. |-| Cable visibility | Hidden by default; shown on hover/selection, or all-on via patch mode / the header. Plates fade to 40 % when cables are on. Copper vs fibre follows the port the patch starts from. |+| Cable visibility | Hidden by default; shown on hover/selection, or all-on via patch mode / the header. Plates stay opaque in every mode — fading them to 40 % showed the rails and the U grid through the gear. Copper vs fibre follows the port the patch starts from. A selected cable is drawn whatever the mode — its panel is open on the right, so hiding the run it describes would read as a bug. |+| Cable annotations | A cable carries a `label` plus `properties` — the same `NodeProperty` records the logical canvas uses (`key`, `value`, `icon`, `visible`), edited with the shared `components/common/PropertyList`. `labelVisible` and each property's `visible` decide what is printed on the canvas: `CableLayer` draws the lines on a small plate at the midpoint of the run (the cubic solved at `t = 0.5`, not `getPointAtLength`, which needs a mounted path). || Colours | `rackTheme.ts` derives the whole rack palette from the active app theme rather than declaring one per theme, so a new theme works here for free. Per-rack chrome (frame, rails, interior) stays user-editable; only its default comes from the theme. |## Persistence@@ -54,7 +55,8 @@ types in `@/types/rack`, narrowing every enum on the way in.- Double-click a plate → the same modal in edit mode: label, faceplate, U/height/column/width, status, colour, port list, 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.-- **Patch mode**: drag from port A to port B to cable them — a dashed rubber band follows the pointer, exactly like dragging an edge on the logical canvas. Clicking A then B still works; Escape drops a half-drawn patch. Click a cable to select it (it gets an accent halo), then press Delete/Backspace — or the header's Unplug button — to remove it; Escape or a pane click deselects. Rack dragging is disabled while in patch mode.+- **Patch mode**: drag from port A to port B to cable them — a dashed rubber band follows the pointer, exactly like dragging an edge on the logical canvas. Clicking A then B still works; Escape drops a half-drawn patch. Rack dragging is disabled while in patch mode.+- **Click a cable** — in patch mode or out of it — to select it: it gets an accent halo and opens `RackCablePanel` on the right (endpoints, type, colour, label, properties, Unplug). Delete/Backspace unplugs the selection; Escape or a pane click deselects. Selecting a cable drops any mount/rack selection and vice versa — one rail, one occupant.- **Import links**: reads the physical edges (ethernet/fibre/vlan/cluster) of every non-rack design and matches them on `nodeId`. Idempotent — a device pair already cabled is skipped, whichever ports carry it, so a re-run after racking more gear adds only what is missing. There is no "done" flag: one lived in memory only, and a reload re-armed the import onto the next free ports.- **New device**: the modal's *New device* source adds a Device Inventory entry (tagged `rack`), for gear no scan will ever discover. The left-rail tray only carries accessories, as a drag source.@@ -62,7 +64,7 @@ types in `@/types/rack`, narrowing every enum on the way in.- **Header**: undo/redo, auto layout, YAML import/export, MD and live View are hidden. Add Rack, Patch, cable visibility and Import links replace them. PNG export and Save stay.- **Left rail**: the design switcher, Device Inventory, Scan History, Settings and Logout stay. The node/zone/text/scan/import block becomes the accessory tray plus **+ Device**. Devices themselves are not listed there — they live in the Device Inventory modal. The footer counts racks, mounts, cables and free U instead of online/offline nodes.-- **Right rail**: none. A mount is edited in `RackDeviceModal`, a rack in `RackSettingsModal`, so the canvas keeps the full width.+- **Right rail**: only for a selected cable (`RackCablePanel`). A mount is edited in `RackDeviceModal` and a rack in `RackSettingsModal` — a cable has no plate to double-click, so it gets the rail instead. With nothing selected the canvas keeps the full width.## Known gapsdiff --git a/frontend/src/rack/__tests__/CableLayer.test.tsx b/frontend/src/rack/__tests__/CableLayer.test.tsxindex 8419b73..e207d50 100644--- a/frontend/src/rack/__tests__/CableLayer.test.tsx+++ b/frontend/src/rack/__tests__/CableLayer.test.tsx@@ -25,10 +25,26 @@ beforeEach(() => {})describe('CableLayer selection', () => {- it('offers no click target outside patch mode', () => {+ it('selects a cable on click outside patch mode too', () => {+ // A cable is clicked to read and edit it in the rail, not only to unplug it,+ // so the hit target is not gated on patch mode.useRackStore.getState().setCableVisibility('always')const { container } = render(<CableLayer />)- expect(hitPaths(container)).toHaveLength(0)+ const paths = hitPaths(container)+ expect(paths).toHaveLength(useRackStore.getState().cables.length)++ fireEvent.click(paths[0])+ expect(useRackStore.getState().cableMode).toBe(false)+ expect(useRackStore.getState().selectedCableId).toBe(useRackStore.getState().cables[0].id)+ })++ it('keeps the selected cable drawn when visibility is hover and nothing is focused', () => {+ const store = useRackStore.getState()+ store.setCableVisibility('hover')+ store.selectCable(store.cables[0].id)++ const { container } = render(<CableLayer />)+ expect(hitPaths(container)).toHaveLength(1)})it('selects a cable on click in patch mode', () => {@@ -90,6 +106,34 @@ describe('CableLayer selection', () => {expect(hitPaths(container)).toHaveLength(cables.length)})+ it('prints nothing beside a cable that has no visible annotation', () => {+ const store = useRackStore.getState()+ store.setCableVisibility('always')+ // A label alone is not enough — it is printed only once the user asks.+ store.updateCable(store.cables[0].id, { label: 'Uplink', labelVisible: false })+ const { queryAllByTestId } = render(<CableLayer />)+ expect(queryAllByTestId('cable-annotation')).toHaveLength(0)+ })++ it('prints the label and the visible properties on the canvas', () => {+ const store = useRackStore.getState()+ store.setCableVisibility('always')+ store.updateCable(store.cables[0].id, {+ label: 'Uplink',+ labelVisible: true,+ properties: [+ { key: 'Length', value: '2 m', icon: null, visible: true },+ { key: 'VLAN', value: '20', icon: null, visible: false },+ ],+ })++ const { getAllByTestId } = render(<CableLayer />)+ const badges = getAllByTestId('cable-annotation')+ expect(badges).toHaveLength(1)+ const lines = Array.from(badges[0].querySelectorAll('text')).map((t) => t.textContent)+ expect(lines).toEqual(['Uplink', 'Length: 2 m'])+ })+it('draws the selected cable with a highlight halo', () => {useRackStore.getState().toggleCableMode()const { container, rerender } = render(<CableLayer />)diff --git a/frontend/src/rack/__tests__/RackCablePanel.test.tsx b/frontend/src/rack/__tests__/RackCablePanel.test.tsxnew file mode 100644index 0000000..0b41879--- /dev/null+++ b/frontend/src/rack/__tests__/RackCablePanel.test.tsx@@ -0,0 +1,129 @@+/**+ * The rail a selected cable opens: physical facts up top, then the same+ * property records the logical canvas uses for nodes.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { render, screen, fireEvent } from '@testing-library/react'+import { RackCablePanel } from '../components/RackCablePanel'+import { CABLE_COLORS } from '../rackDefaults'+import { useRackStore } from '../store'++vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())++const store = () => useRackStore.getState()+const selected = () => store().cables.find((c) => c.id === store().selectedCableId)!++beforeEach(() => {+ store().loadDemo()+})++describe('RackCablePanel', () => {+ it('renders nothing until a cable is selected', () => {+ const { container } = render(<RackCablePanel />)+ expect(container).toBeEmptyDOMElement()+ })++ it('names both endpoints by device and port', () => {+ const cable = store().cables[0]+ store().selectCable(cable.id)+ const device = store().devices.find((d) => d.id === cable.from.deviceId)!+ const port = device.ports.find((p) => p.id === cable.from.portId)!++ render(<RackCablePanel />)+ expect(screen.getAllByTitle(device.label).length).toBeGreaterThan(0)+ expect(screen.getAllByTitle(port.label).length).toBeGreaterThan(0)+ })++ it('edits the label and toggles printing it on the canvas', () => {+ store().selectCable(store().cables[0].id)+ render(<RackCablePanel />)++ fireEvent.change(screen.getByLabelText('Cable label'), { target: { value: 'Uplink' } })+ expect(selected().label).toBe('Uplink')++ fireEvent.click(screen.getByRole('checkbox'))+ expect(selected().labelVisible).toBe(true)+ })++ it('recolours from a swatch and from the hex field', () => {+ store().selectCable(store().cables[0].id)+ render(<RackCablePanel />)++ fireEvent.click(screen.getByLabelText('Cable colour #a855f7'))+ expect(selected().color).toBe('#a855f7')++ fireEvent.change(screen.getByLabelText('Cable colour hex'), { target: { value: '#123456' } })+ expect(selected().color).toBe('#123456')+ })++ it('recolours a default-coloured cable when its type changes', () => {+ const ethernet = store().cables.find((c) => c.type === 'ethernet')!+ store().updateCable(ethernet.id, { color: CABLE_COLORS.ethernet })+ store().selectCable(ethernet.id)+ render(<RackCablePanel />)++ fireEvent.click(screen.getByText('Fibre'))+ expect(selected().type).toBe('fiber')+ expect(selected().color).toBe(CABLE_COLORS.fiber)+ })++ it('keeps a hand-picked colour across a type change', () => {+ const ethernet = store().cables.find((c) => c.type === 'ethernet')!+ store().updateCable(ethernet.id, { color: '#ff00ff' })+ store().selectCable(ethernet.id)+ render(<RackCablePanel />)++ fireEvent.click(screen.getByText('Fibre'))+ expect(selected().type).toBe('fiber')+ expect(selected().color).toBe('#ff00ff')+ })++ it('adds a property through a suggestion and stores it on the cable', () => {+ store().selectCable(store().cables[0].id)+ render(<RackCablePanel />)++ fireEvent.click(screen.getByText('+ Length'))+ fireEvent.change(screen.getByPlaceholderText('Value (e.g. 2 m)'), { target: { value: '2 m' } })+ // Two buttons read "Add": the section's, then the form's confirm.+ const addButtons = screen.getAllByRole('button', { name: 'Add' })+ fireEvent.click(addButtons[addButtons.length - 1])++ expect(selected().properties).toEqual([+ { key: 'Length', value: '2 m', icon: null, visible: true },+ ])+ })++ it('hides a property from the canvas without deleting it', () => {+ const cable = store().cables[0]+ store().updateCable(cable.id, {+ properties: [{ key: 'VLAN', value: '20', icon: null, visible: true }],+ })+ store().selectCable(cable.id)+ render(<RackCablePanel />)++ fireEvent.click(screen.getByTitle('Hide on canvas'))+ expect(selected().properties).toEqual([+ { key: 'VLAN', value: '20', icon: null, visible: false },+ ])+ })++ it('unplugs the cable', () => {+ const cable = store().cables[0]+ store().selectCable(cable.id)+ render(<RackCablePanel />)++ fireEvent.click(screen.getByRole('button', { name: /Unplug cable/ }))+ expect(store().cables.some((c) => c.id === cable.id)).toBe(false)+ expect(store().selectedCableId).toBeNull()+ })++ it('closes without touching the cable', () => {+ const before = store().cables.length+ store().selectCable(store().cables[0].id)+ render(<RackCablePanel />)++ fireEvent.click(screen.getByLabelText('Close panel'))+ expect(store().selectedCableId).toBeNull()+ expect(store().cables).toHaveLength(before)+ })+})diff --git a/frontend/src/rack/__tests__/RackFlowNode.test.tsx b/frontend/src/rack/__tests__/RackFlowNode.test.tsxindex a2eb976..8007b24 100644--- a/frontend/src/rack/__tests__/RackFlowNode.test.tsx+++ b/frontend/src/rack/__tests__/RackFlowNode.test.tsx@@ -74,6 +74,25 @@ describe('RackFlowNode status', () => {})})+describe('RackFlowNode plate opacity', () => {+ /** Every faceplate the rack draws, one <svg> each. */+ const plateOpacities = (container: HTMLElement) =>+ Array.from(container.querySelectorAll('svg')).map((s) => s.style.opacity)++ it('keeps plates opaque with cables always on', () => {+ // A faded plate let the rails and the U grid show through the gear.+ store().setCableVisibility('always')+ const { container } = renderRack()+ expect(plateOpacities(container).every((o) => o === '')).toBe(true)+ })++ it('keeps plates opaque in patch mode too', () => {+ store().toggleCableMode()+ const { container } = renderRack()+ expect(plateOpacities(container).every((o) => o === '')).toBe(true)+ })+})+describe('RackFlowNode patching', () => {/** Two mounted ports in this rack that nothing is plugged into yet. */function freePorts() {diff --git a/frontend/src/rack/__tests__/store.test.ts b/frontend/src/rack/__tests__/store.test.tsindex 86652c1..1742b48 100644--- a/frontend/src/rack/__tests__/store.test.ts+++ b/frontend/src/rack/__tests__/store.test.ts@@ -379,6 +379,41 @@ describe('cables', () => {expect(store().selectedCableId).toBeNull()})+ it('drops the device and rack selection when a cable is selected', () => {+ // Both drive the right rail, so the two selections cannot coexist.+ store().selectDevice(store().devices[0].id)+ store().selectCable(store().cables[0].id)+ expect(store().selectedDeviceId).toBeNull()+ expect(store().selectedRackId).toBeNull()+ })++ it('keeps the device selection when the cable selection is cleared', () => {+ store().selectDevice(store().devices[0].id)+ store().selectCable(null)+ expect(store().selectedDeviceId).toBe(store().devices[0].id)+ })++ it('edits a cable label, its canvas visibility and its properties', () => {+ const cable = store().cables[0]+ store().updateCable(cable.id, {+ label: 'Uplink to core',+ labelVisible: true,+ properties: [{ key: 'Length', value: '2 m', icon: null, visible: true }],+ })++ const updated = store().cables.find((c) => c.id === cable.id)!+ expect(updated.label).toBe('Uplink to core')+ expect(updated.labelVisible).toBe(true)+ expect(updated.properties).toEqual([{ key: 'Length', value: '2 m', icon: null, visible: true }])+ expect(store().hasUnsavedChanges).toBe(true)+ })++ it('leaves other cables untouched when one is edited', () => {+ const [first, second] = store().cables+ store().updateCable(first.id, { color: '#ff00ff' })+ expect(store().cables.find((c) => c.id === second.id)!.color).toBe(second.color)+ })+it('drops the cable selection when leaving patch mode', () => {store().toggleCableMode()store().selectCable(store().cables[0].id)diff --git a/frontend/src/rack/components/CableLayer.tsx b/frontend/src/rack/components/CableLayer.tsxindex 7e5206a..8af8eee 100644--- a/frontend/src/rack/components/CableLayer.tsx+++ b/frontend/src/rack/components/CableLayer.tsx@@ -7,7 +7,7 @@*/import { ViewportPortal } from '@xyflow/react'import { portPosition } from '../layout'-import { useRackPalette } from '../rackTheme'+import { useRackPalette, type RackPalette } from '../rackTheme'import { useRackStore } from '../store'import type { Cable, Port, Rack, RackDevice } from '@/types'@@ -18,12 +18,40 @@ interface Resolved {}/** Slack loop: cables bulge out sideways, more so over long vertical runs. */+function bulgeFor(a: { x: number; y: number }, b: { x: number; y: number }): number {+ return Math.min(90, 18 + Math.abs(b.y - a.y) * 0.45)+}+function cablePath(a: { x: number; y: number }, b: { x: number; y: number }): string {- const dy = Math.abs(b.y - a.y)- const bulge = Math.min(90, 18 + dy * 0.45)+ const bulge = bulgeFor(a, b)return `M ${a.x} ${a.y} C ${a.x + bulge} ${a.y + bulge * 0.4}, ${b.x + bulge} ${b.y + bulge * 0.4}, ${b.x} ${b.y}`}+/**+ * Midpoint of the same cubic, evaluated at t = 0.5 — where the annotations+ * hang. Solved analytically rather than with `getPointAtLength`, which needs a+ * mounted path element and would not work under jsdom.+ */+function cableMidpoint(a: { x: number; y: number }, b: { x: number; y: number }) {+ const bulge = bulgeFor(a, b)+ const c1 = { x: a.x + bulge, y: a.y + bulge * 0.4 }+ const c2 = { x: b.x + bulge, y: b.y + bulge * 0.4 }+ return {+ x: (a.x + 3 * c1.x + 3 * c2.x + b.x) / 8,+ y: (a.y + 3 * c1.y + 3 * c2.y + b.y) / 8,+ }+}++/** Lines a cable prints on the canvas: its label, then its visible properties. */+function annotationLines(cable: Cable): string[] {+ const lines: string[] = []+ if (cable.labelVisible && cable.label?.trim()) lines.push(cable.label.trim())+ for (const prop of cable.properties ?? []) {+ if (prop.visible) lines.push(`${prop.key}: ${prop.value}`)+ }+ return lines+}+export function CableLayer() {const racks = useRackStore((s) => s.racks)const devices = useRackStore((s) => s.devices)@@ -56,7 +84,9 @@ export function CableLayer() {const visible: Resolved[] = []for (const cable of cables) {- if (!showAll) {+ // A selected cable stays on screen whatever the visibility mode — its panel+ // is open on the right, so hiding the run it describes reads as a bug.+ if (!showAll && cable.id !== selectedCableId) {if (!focus) continueif (cable.from.deviceId !== focus && cable.to.deviceId !== focus) continue}@@ -88,10 +118,11 @@ export function CableLayer() {}}>{visible.map(({ cable, from, to }) => {- const selected = cableMode && cable.id === selectedCableId+ const selected = cable.id === selectedCableIdconst dimmed =!selected && focus != null && cable.from.deviceId !== focus && cable.to.deviceId !== focusconst d = cablePath(from, to)+ const lines = annotationLines(cable)return (<g key={cable.id} opacity={dimmed ? 0.28 : 1}>{selected && (@@ -120,29 +151,38 @@ export function CableLayer() {strokeLinecap="round"style={{ pointerEvents: 'none' }}/>- {/* Fat invisible hit area — a 1.8px path is hard to hit at low zoom. */}- {cableMode && (- <path- d={d}- fill="none"- stroke="transparent"- strokeWidth={14}- strokeLinecap="round"- style={{ pointerEvents: 'stroke', cursor: 'pointer' }}- onClick={(e) => {- // The pane click behind would clear the selection again.- e.stopPropagation()- selectCable(selected ? null : cable.id)- }}- >- <title>- {cable.label ? `${cable.label} — ${cable.type}` : cable.type}- {' (click to select, Delete to remove)'}- </title>- </path>- )}+ {/* Fat invisible hit area — a 1.8px path is hard to hit at low+ zoom. Clickable outside patch mode too: a cable is selected to+ read and edit it, not only to unplug it. */}+ <path+ data-testid={`cable-hit-${cable.id}`}+ d={d}+ fill="none"+ stroke="transparent"+ strokeWidth={14}+ strokeLinecap="round"+ style={{ pointerEvents: 'stroke', cursor: 'pointer' }}+ onClick={(e) => {+ // The pane click behind would clear the selection again.+ e.stopPropagation()+ selectCable(selected ? null : cable.id)+ }}+ >+ <title>+ {cable.label ? `${cable.label} — ${cable.type}` : cable.type}+ {' (click to select, Delete to remove)'}+ </title>+ </path><circle cx={from.x} cy={from.y} r={selected ? 3.2 : 2.2} fill={selected ? palette.accent : cable.color} /><circle cx={to.x} cy={to.y} r={selected ? 3.2 : 2.2} fill={selected ? palette.accent : cable.color} />+ {lines.length > 0 && (+ <CableAnnotation+ lines={lines}+ at={cableMidpoint(from, to)}+ color={selected ? palette.accent : cable.color}+ palette={palette}+ />+ )}</g>)})}@@ -172,3 +212,56 @@ export function CableLayer() {</ViewportPortal>)}++const ANNOTATION_FONT = 7+const ANNOTATION_LINE = 9++/**+ * The label and visible properties of one cable, printed on a plate at the+ * midpoint of its run.+ *+ * Drawn in flow coordinates like the rest of the overlay, so it pans and zooms+ * with the racks. The plate is sized from the character count — SVG has no text+ * metrics before layout, and measuring in the DOM would cost a reflow per cable.+ */+function CableAnnotation({ lines, at, color, palette }: {+ lines: string[]+ at: { x: number; y: number }+ color: string+ palette: RackPalette+}) {+ const longest = lines.reduce((max, line) => Math.max(max, line.length), 0)+ const width = Math.max(24, longest * ANNOTATION_FONT * 0.56 + 8)+ const height = lines.length * ANNOTATION_LINE + 4+ const x = at.x - width / 2+ const y = at.y - height / 2++ return (+ <g style={{ pointerEvents: 'none' }} data-testid="cable-annotation">+ <rect+ x={x}+ y={y}+ width={width}+ height={height}+ rx={2}+ fill={palette.plate}+ stroke={color}+ strokeWidth={0.6}+ opacity={0.95}+ />+ {lines.map((line, i) => (+ <text+ key={`${line}-${i}`}+ x={at.x}+ y={y + 2 + ANNOTATION_LINE * (i + 1) - 2.5}+ textAnchor="middle"+ fontSize={ANNOTATION_FONT}+ fill={palette.text}+ style={{ fontFamily: 'Inter, sans-serif' }}+ >+ {line}+ </text>+ ))}+ </g>+ )+}diff --git a/frontend/src/rack/components/Faceplate.tsx b/frontend/src/rack/components/Faceplate.tsxindex 43b6ffa..d41ee4a 100644--- a/frontend/src/rack/components/Faceplate.tsx+++ b/frontend/src/rack/components/Faceplate.tsx@@ -163,8 +163,6 @@ interface Props {selected?: boolean/** Hover or selection: reveals the ports of non-patch gear. */revealed?: boolean- /** Fade the plate so cables behind it stay readable. */- transparent?: boolean/** Ports take the pointer (patch mode). */interactivePorts?: boolean/** Port id -> colour of the cable plugged into it. */@@ -185,7 +183,6 @@ export const Faceplate = memo(function Faceplate({colorOverride,selected,revealed,- transparent,interactivePorts,patchedPorts,draftPortId,@@ -206,12 +203,16 @@ export const Faceplate = memo(function Faceplate({const fontSize = Math.max(8, Math.min(11, height * 0.42))const showLabel = labelW > 24 && height >= 14+ // Plates stay opaque whatever the cable visibility. Fading them let the rail+ // strips and the U grid show through the gear, which reads as a rendering+ // bug; cables are drawn above the plates anyway, so nothing needs to see+ // through them.return (<svgwidth={width}height={height}viewBox={`0 0 ${width} ${height}`}- style={{ opacity: transparent ? 0.4 : 1, display: 'block' }}+ style={{ display: 'block' }}><defs><clipPath id={clipId}>diff --git a/frontend/src/rack/components/RackCablePanel.tsx b/frontend/src/rack/components/RackCablePanel.tsxnew file mode 100644index 0000000..e9ef754--- /dev/null+++ b/frontend/src/rack/components/RackCablePanel.tsx@@ -0,0 +1,177 @@+/**+ * Right rail for the selected cable.+ *+ * The rack canvas has no rail for mounted gear — a mount is edited in its own+ * modal — but a cable has no plate to double-click, so clicking the run opens+ * this panel instead. It carries the physical facts (type, colour, label) and+ * the same free-form property records the logical canvas uses for nodes, each+ * with its own "show it on the canvas" toggle.+ */+import { Cable as CableIcon, Trash2, X } from 'lucide-react'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { PropertyList } from '@/components/common/PropertyList'+import { CABLE_COLOR_PRESETS, CABLE_COLORS, CABLE_PROPERTY_SUGGESTIONS } from '../rackDefaults'+import { useRackStore } from '../store'+import type { CableProperty, CableType, RackDevice } from '@/types'++const TYPE_LABELS: Record<CableType, string> = {+ ethernet: 'Ethernet',+ fiber: 'Fibre',+}++export function RackCablePanel() {+ const cables = useRackStore((s) => s.cables)+ const devices = useRackStore((s) => s.devices)+ const selectedCableId = useRackStore((s) => s.selectedCableId)+ const updateCable = useRackStore((s) => s.updateCable)+ const removeCable = useRackStore((s) => s.removeCable)+ const selectCable = useRackStore((s) => s.selectCable)++ const cable = cables.find((c) => c.id === selectedCableId)+ if (!cable) return null++ const endpoint = (ref: { deviceId: string; portId: string }) => {+ const device: RackDevice | undefined = devices.find((d) => d.id === ref.deviceId)+ return {+ device: device?.label ?? 'Unknown device',+ port: device?.ports.find((p) => p.id === ref.portId)?.label ?? '—',+ }+ }++ const from = endpoint(cable.from)+ const to = endpoint(cable.to)+ const properties: CableProperty[] = cable.properties ?? []++ const handleType = (type: CableType) => {+ if (type === cable.type) return+ // Recolour only a cable still wearing its type's default, so a colour the+ // user picked survives a type change.+ const patch =+ cable.color === CABLE_COLORS[cable.type] ? { type, color: CABLE_COLORS[type] } : { type }+ updateCable(cable.id, patch)+ }++ return (+ <aside className="w-72 shrink-0 flex flex-col border-l border-border bg-[#161b22] overflow-y-auto">+ <div className="flex items-center justify-between px-4 py-3 border-b border-border">+ <span className="flex items-center gap-2 min-w-0 font-semibold text-sm text-foreground">+ <CableIcon size={14} className="shrink-0" style={{ color: cable.color }} />+ <span className="truncate">{cable.label?.trim() || 'Cable'}</span>+ </span>+ <button+ aria-label="Close panel"+ onClick={() => selectCable(null)}+ className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ >+ <X size={16} />+ </button>+ </div>++ {/* Endpoints */}+ <div className="flex flex-col gap-2 px-4 py-3 border-b border-border">+ <span className="text-xs text-muted-foreground">Endpoints</span>+ <EndpointRow side="A" device={from.device} port={from.port} />+ <EndpointRow side="B" device={to.device} port={to.port} />+ </div>++ {/* Type */}+ <div className="px-4 py-3 border-b border-border">+ <span className="text-xs text-muted-foreground">Type</span>+ <div className="mt-2 flex gap-1.5">+ {(Object.keys(TYPE_LABELS) as CableType[]).map((type) => (+ <button+ key={type}+ onClick={() => handleType(type)}+ className={`flex-1 rounded border px-2 py-1 text-[11px] transition-colors cursor-pointer ${+ cable.type === type+ ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]'+ : 'border-[#30363d] text-muted-foreground hover:border-[#8b949e]'+ }`}+ >+ {TYPE_LABELS[type]}+ </button>+ ))}+ </div>+ </div>++ {/* Colour */}+ <div className="px-4 py-3 border-b border-border">+ <span className="text-xs text-muted-foreground">Colour</span>+ <div className="mt-2 flex flex-wrap gap-1">+ {CABLE_COLOR_PRESETS.map((color) => (+ <button+ key={color}+ aria-label={`Cable colour ${color}`}+ title={color}+ onClick={() => updateCable(cable.id, { color })}+ className={`h-6 w-6 rounded border transition-transform cursor-pointer hover:scale-110 ${+ cable.color.toLowerCase() === color.toLowerCase() ? 'border-[#00d4ff]' : 'border-[#30363d]'+ }`}+ style={{ background: color }}+ />+ ))}+ </div>+ <Input+ value={cable.color}+ onChange={(e) => updateCable(cable.id, { color: e.target.value })}+ aria-label="Cable colour hex"+ placeholder="#39d353"+ className="mt-2 bg-[#21262d] border-[#30363d] text-xs h-7 font-mono"+ />+ </div>++ {/* Label */}+ <div className="px-4 py-3 border-b border-border">+ <span className="text-xs text-muted-foreground">Label</span>+ <Input+ value={cable.label ?? ''}+ onChange={(e) => updateCable(cable.id, { label: e.target.value })}+ aria-label="Cable label"+ placeholder="e.g. Uplink to core"+ className="mt-2 bg-[#21262d] border-[#30363d] text-xs h-7"+ />+ <label className="mt-2 flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={cable.labelVisible === true}+ onChange={(e) => updateCable(cable.id, { labelVisible: e.target.checked })}+ className="accent-[#00d4ff] w-3 h-3"+ />+ <span className="text-[10px] text-muted-foreground">Show on canvas</span>+ </label>+ </div>++ <PropertyList+ properties={properties}+ onChange={(next) => updateCable(cable.id, { properties: next })}+ visibleLabel="Show on canvas"+ keyPlaceholder="Label (e.g. Length)"+ valuePlaceholder="Value (e.g. 2 m)"+ suggestions={CABLE_PROPERTY_SUGGESTIONS}+ emptyHint="No properties — add a length, a VLAN, whatever this run needs."+ />++ <div className="px-4 py-3 border-t border-border mt-auto">+ <Button+ size="sm"+ variant="ghost"+ onClick={() => removeCable(cable.id)}+ className="w-full h-7 text-[11px] text-[#f85149] hover:text-[#f85149] hover:bg-[#f85149]/10"+ >+ <Trash2 size={12} className="mr-1.5" /> Unplug cable+ </Button>+ </div>+ </aside>+ )+}++function EndpointRow({ side, device, port }: { side: string; device: string; port: string }) {+ return (+ <div className="flex items-baseline gap-2 min-w-0">+ <span className="w-3 shrink-0 text-[10px] text-muted-foreground">{side}</span>+ <span className="truncate text-xs text-foreground" title={device}>{device}</span>+ <span className="ml-auto shrink-0 font-mono text-[11px] text-[#00d4ff]" title={port}>{port}</span>+ </div>+ )+}diff --git a/frontend/src/rack/components/RackFlowNode.tsx b/frontend/src/rack/components/RackFlowNode.tsxindex 96dbd64..405eb42 100644--- a/frontend/src/rack/components/RackFlowNode.tsx+++ b/frontend/src/rack/components/RackFlowNode.tsx@@ -299,7 +299,6 @@ export function RackFlowNode({ id }: NodeProps) {colorOverride={device.color}selected={selectedDeviceId === device.id}revealed={revealAll || focused}- transparent={cablesOn && !focused}interactivePorts={cableMode}patchedPorts={patchedPorts}draftPortId={isDraftDevice ? cableDraft.portId : null}diff --git a/frontend/src/rack/rackDefaults.ts b/frontend/src/rack/rackDefaults.tsindex c3568d0..371bdf3 100644--- a/frontend/src/rack/rackDefaults.ts+++ b/frontend/src/rack/rackDefaults.ts@@ -14,6 +14,26 @@ export const CABLE_COLORS: Record<CableType, string> = {fiber: '#f0a500',}+/**+ * Swatches offered when recolouring a patch — the sheaths a homelab actually+ * has on the shelf. Any other colour still goes in through the free-text field.+ */+export const CABLE_COLOR_PRESETS: string[] = [+ '#39d353', // green+ '#00d4ff', // cyan+ '#f0a500', // amber / fibre+ '#f85149', // red+ '#a855f7', // purple+ '#e3b341', // yellow+ '#3b82f6', // blue+ '#8b949e', // grey+ '#f2f2f2', // white+ '#161b22', // black+]++/** Property keys a cable is most often annotated with, offered as one-click adds. */+export const CABLE_PROPERTY_SUGGESTIONS = ['Length', 'VLAN', 'Speed', 'Category', 'Patch ref']+/** Cable type implied by the port a patch starts from. */export const PORT_CABLE_TYPE: Record<PortType, CableType> = {rj45: 'ethernet',diff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.tsindex 9d1bbd6..2abec0f 100644--- a/frontend/src/rack/store.ts+++ b/frontend/src/rack/store.ts@@ -698,7 +698,10 @@ export const useRackStore = create<RackState>((set, get) => {setViewport: (v) => set({ viewport: v }),selectDevice: (id) => set({ selectedDeviceId: id, selectedRackId: null, selectedCableId: null }),selectRack: (id) => set({ selectedRackId: id, selectedDeviceId: null, selectedCableId: null }),- selectCable: (id) => set({ selectedCableId: id }),+ // A cable and a mount both drive the right rail, so picking one drops the+ // other — two panels can't share the slot.+ selectCable: (id) =>+ set(id ? { selectedCableId: id, selectedDeviceId: null, selectedRackId: null } : { selectedCableId: null }),removeSelectedCable: () => {const id = get().selectedCableIddiff --git a/frontend/src/types/rack.ts b/frontend/src/types/rack.tsindex ae81776..0a333a9 100644--- a/frontend/src/types/rack.ts+++ b/frontend/src/types/rack.ts@@ -5,6 +5,9 @@* what the store and components work with; `@/utils/rackSerializer` maps them to* and from the snake_case API payloads.*/+// Type-only, so the cycle with `./index` (which re-exports this module) is+// erased at compile time. Cables reuse the logical canvas' property records.+import type { NodeProperty } from './index'/** Horizontal grid inside a rack. 12 columns = full width, 6 = half, 4 = third. */export const RACK_COLUMNS = 12@@ -169,11 +172,22 @@ export interface RackDevice {export type CableType = 'ethernet' | 'fiber'+/**+ * Extra facts carried by a cable — length, VLAN, patch reference, whatever the+ * user needs. Same record shape as a node's properties (`key`/`value`/`icon`/+ * `visible`), and the same rule: `visible` puts it on the canvas.+ */+export type CableProperty = NodeProperty+export interface Cable {id: stringtype: CableTypecolor: stringlabel?: string+ /** Print the label alongside the run on the canvas. Off by default. */+ labelVisible?: boolean+ /** Free-form key/value facts; the `visible` ones are drawn on the canvas. */+ properties?: CableProperty[]from: { deviceId: string; portId: string }to: { deviceId: string; portId: string }}diff --git a/frontend/src/utils/__tests__/rackSerializer.test.ts b/frontend/src/utils/__tests__/rackSerializer.test.tsindex 5fd569a..b4695f3 100644--- a/frontend/src/utils/__tests__/rackSerializer.test.ts+++ b/frontend/src/utils/__tests__/rackSerializer.test.ts@@ -55,6 +55,8 @@ const apiCable: ApiRackCable = {type: 'fiber',color: '#f0a500',label: 'SAN',+ label_visible: true,+ properties: [{ key: 'Length', value: '3 m', icon: null, visible: true }],}describe('API → domain', () => {@@ -121,11 +123,36 @@ describe('API → domain', () => {expect(toCable(apiCable)).toMatchObject({type: 'fiber',label: 'SAN',+ labelVisible: true,+ properties: [{ key: 'Length', value: '3 m', icon: null, visible: true }],from: { deviceId: 'dev1', portId: 'p1' },to: { deviceId: 'dev2', portId: 'p2' },})})+ it('fills the annotations a cable saved before the feature has no columns for', () => {+ // Legacy rows read back without the two new keys; the mapper must not+ // produce `undefined.filter` fodder for the overlay.+ const legacy = { ...apiCable } as Partial<ApiRackCable>+ delete legacy.label_visible+ delete legacy.properties++ const cable = toCable(legacy as ApiRackCable)+ expect(cable.labelVisible).toBe(false)+ expect(cable.properties).toEqual([])+ })++ it('drops cable properties that carry no key', () => {+ const cable = toCable({+ ...apiCable,+ properties: [+ { key: '', value: 'x', icon: null, visible: true },+ { key: 'VLAN', value: '20', icon: null, visible: false },+ ],+ })+ expect(cable.properties).toEqual([{ key: 'VLAN', value: '20', icon: null, visible: false }])+ })+it('takes inventory status from the linked node, not the inventory row', () => {const item = toInventoryDevice({id: 'inv1',@@ -181,9 +208,16 @@ describe('domain → API', () => {from_device_id: 'dev1',to_port_id: 'p2',type: 'fiber',+ label_visible: true,+ properties: [{ key: 'Length', value: '3 m', icon: null, visible: true }],})})+ it('sends explicit defaults for a cable that was never annotated', () => {+ const bare = { ...toCable(apiCable), labelVisible: undefined, properties: undefined }+ expect(fromCable(bare)).toMatchObject({ label_visible: false, properties: [] })+ })+it('clamps a device back into the column grid', () => {const device = { ...toRackDevice(apiDevice), colStart: 99, colSpan: 99 }const back = fromRackDevice(device)diff --git a/frontend/src/utils/rackSerializer.ts b/frontend/src/utils/rackSerializer.tsindex eb865a8..fd10884 100644--- a/frontend/src/utils/rackSerializer.ts+++ b/frontend/src/utils/rackSerializer.ts@@ -9,6 +9,7 @@ import { suggestFaceplate } from '@/rack/faceplates'import { RACK_COLUMNS } from '@/types'import type {Cable,+ CableProperty,CableType,DeviceStatus,InventoryDevice,@@ -64,6 +65,9 @@ export interface ApiRackCable {type: stringcolor: stringlabel: string | null+ label_visible: boolean+ /** [{key, value, icon, visible}] — same records the logical canvas uses. */+ properties: CableProperty[]}export interface ApiRackState {@@ -155,6 +159,27 @@ function asPorts(raw: unknown[]): Port[] {return ports}+/**+ * Cable properties are opaque JSON on the wire. Anything missing a usable+ * key/value pair is dropped rather than rendered as an empty annotation.+ */+function asCableProperties(raw: unknown): CableProperty[] {+ if (!Array.isArray(raw)) return []+ const props: CableProperty[] = []+ for (const entry of raw) {+ if (!entry || typeof entry !== 'object') continue+ const p = entry as Record<string, unknown>+ if (typeof p.key !== 'string' || !p.key.trim()) continue+ props.push({+ key: p.key,+ value: typeof p.value === 'string' ? p.value : String(p.value ?? ''),+ icon: typeof p.icon === 'string' ? p.icon : null,+ visible: p.visible !== false,+ })+ }+ return props+}+// ── API → domain ─────────────────────────────────────────────────────────────export function toRack(api: ApiRack): Rack {@@ -195,6 +220,8 @@ export function toCable(api: ApiRackCable): Cable {type,color: api.color || CABLE_COLORS[type],label: api.label ?? undefined,+ labelVisible: api.label_visible === true,+ properties: asCableProperties(api.properties),from: { deviceId: api.from_device_id, portId: api.from_port_id },to: { deviceId: api.to_device_id, portId: api.to_port_id },}@@ -259,6 +286,8 @@ export function fromCable(cable: Cable): Omit<ApiRackCable, 'design_id'> {type: cable.type,color: cable.color || CABLE_COLORS[cable.type],label: cable.label ?? null,+ label_visible: cable.labelVisible === true,+ properties: cable.properties ?? [],}}