Skip to content

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

feat(rack): integrate the rack canvas as a design type

Pouzora0d16e1454f3
diff --git a/backend/app/api/routes/designs.py b/backend/app/api/routes/designs.py
index ce67ab6..c0018fd 100644
--- a/backend/app/api/routes/designs.py
+++ b/backend/app/api/routes/designs.py
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.db.database import get_db
-from app.db.models import CanvasState, Design, Edge, Node
+from app.db.models import CanvasState, Design, Edge, Node, Rack, RackCable, RackDevice
from app.schemas.designs import DesignCopy, DesignCreate, DesignResponse, DesignUpdate
router = APIRouter()
@@ -118,6 +118,56 @@ async def copy_design(
)
)
+ # Copy the rack canvas, if the source has one. Racks, mounted gear and patches
+ # all get new ids; the inventory / node links are carried over untouched, since
+ # a copy documents the same hardware.
+ src_racks = (await db.execute(select(Rack).where(Rack.design_id == source_id))).scalars().all()
+ rack_id_map = {r.id: str(uuid.uuid4()) for r in src_racks}
+ rack_skip = {"id", "design_id", "created_at", "updated_at"}
+ for r in src_racks:
+ cols = {c.name: getattr(r, c.name) for c in Rack.__table__.columns if c.name not in rack_skip}
+ db.add(Rack(id=rack_id_map[r.id], design_id=new_design.id, **cols))
+
+ src_rack_devices = (
+ await db.execute(select(RackDevice).where(RackDevice.design_id == source_id))
+ ).scalars().all()
+ rack_device_id_map = {d.id: str(uuid.uuid4()) for d in src_rack_devices}
+ rack_device_skip = {"id", "design_id", "rack_id", "created_at", "updated_at"}
+ for d in src_rack_devices:
+ if d.rack_id not in rack_id_map:
+ continue
+ cols = {
+ c.name: getattr(d, c.name)
+ for c in RackDevice.__table__.columns
+ if c.name not in rack_device_skip
+ }
+ db.add(
+ RackDevice(
+ id=rack_device_id_map[d.id],
+ design_id=new_design.id,
+ rack_id=rack_id_map[d.rack_id],
+ **cols,
+ )
+ )
+
+ src_cables = (await db.execute(select(RackCable).where(RackCable.design_id == source_id))).scalars().all()
+ cable_skip = {"id", "design_id", "from_device_id", "to_device_id", "created_at"}
+ for c_row in src_cables:
+ if c_row.from_device_id not in rack_device_id_map or c_row.to_device_id not in rack_device_id_map:
+ continue
+ cols = {
+ c.name: getattr(c_row, c.name) for c in RackCable.__table__.columns if c.name not in cable_skip
+ }
+ db.add(
+ RackCable(
+ id=str(uuid.uuid4()),
+ design_id=new_design.id,
+ from_device_id=rack_device_id_map[c_row.from_device_id],
+ to_device_id=rack_device_id_map[c_row.to_device_id],
+ **cols,
+ )
+ )
+
# Copy canvas state (viewport, custom style, and the floor plan carried in viewport).
src_state = await db.get(CanvasState, source_id)
db.add(
@@ -165,10 +215,20 @@ async def delete_design(
count = (await db.execute(select(Design))).scalars().all()
if len(count) <= 1:
raise HTTPException(400, "Cannot delete the only design")
- # Delete associated canvas state, edges, nodes
+ # Delete associated canvas state, rack rows, edges, nodes. SQLite does not
+ # always enforce the ON DELETE CASCADE, so unwind by hand — cables before
+ # devices before racks.
cs = await db.get(CanvasState, design_id)
if cs:
await db.delete(cs)
+ for cable in (await db.execute(select(RackCable).where(RackCable.design_id == design_id))).scalars().all():
+ await db.delete(cable)
+ for rack_device in (
+ await db.execute(select(RackDevice).where(RackDevice.design_id == design_id))
+ ).scalars().all():
+ await db.delete(rack_device)
+ for rack in (await db.execute(select(Rack).where(Rack.design_id == design_id))).scalars().all():
+ await db.delete(rack)
edges = (await db.execute(select(Edge).where(Edge.design_id == design_id))).scalars().all()
for e in edges:
await db.delete(e)
diff --git a/backend/app/api/routes/racks.py b/backend/app/api/routes/racks.py
new file mode 100644
index 0000000..a6a0f7a
--- /dev/null
+++ b/backend/app/api/routes/racks.py
@@ -0,0 +1,224 @@
+from datetime import datetime, timezone
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.deps import get_current_user
+from app.db.database import get_db
+from app.db.models import CanvasState, Design, Node, PendingDevice, Rack, RackCable, RackDevice
+from app.schemas.racks import (
+ RackCableResponse,
+ RackDeviceResponse,
+ RackInventoryItem,
+ RackInventoryResponse,
+ RackResponse,
+ RackSaveRequest,
+ RackStateResponse,
+)
+
+router = APIRouter()
+
+# Device kinds that cannot be racked. An exclusion list rather than an allow list:
+# new hardware types should show up in the tray by default, and only the obviously
+# virtual / mesh / annotation kinds need to opt out.
+_UNRACKABLE_TYPES = {
+ "vm",
+ "lxc",
+ "docker_container",
+ "mobile",
+ "laptop",
+ "light",
+ "socket",
+ "load",
+ "groupRect",
+ "group",
+ "text",
+ "zigbee_coordinator",
+ "zigbee_router",
+ "zigbee_enddevice",
+ "zwave_coordinator",
+ "zwave_router",
+ "zwave_enddevice",
+}
+
+
+def _ip_tokens(ip: str | None) -> list[str]:
+ """Split a device ``ip`` field into individual addresses.
+
+ Mirrors the scan routes: the canvas stores multiple addresses in one
+ comma-separated string, so matching must compare per-address.
+ """
+ return [t.strip() for t in ip.split(",") if t.strip()] if ip else []
+
+
+async def _require_design(db: AsyncSession, design_id: str) -> Design:
+ design = await db.get(Design, design_id)
+ if not design:
+ raise HTTPException(404, "Design not found")
+ return design
+
+
[email protected]("", response_model=RackStateResponse)
+async def load_racks(
+ design_id: str = Query(..., description="Rack design to load"),
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> RackStateResponse:
+ await _require_design(db, design_id)
+
+ racks = (await db.execute(select(Rack).where(Rack.design_id == design_id))).scalars().all()
+ devices = (
+ await db.execute(select(RackDevice).where(RackDevice.design_id == design_id))
+ ).scalars().all()
+ cables = (await db.execute(select(RackCable).where(RackCable.design_id == design_id))).scalars().all()
+ state = await db.get(CanvasState, design_id)
+
+ return RackStateResponse(
+ racks=[RackResponse.model_validate(r) for r in racks],
+ devices=[RackDeviceResponse.model_validate(d) 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},
+ )
+
+
+async def save_racks(
+ body: RackSaveRequest,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> dict[str, bool]:
+ """Persist the full rack state of one design: upsert what is sent, prune the rest."""
+ await _require_design(db, body.design_id)
+
+ rack_ids = {r.id for r in body.racks}
+ device_ids = {d.id for d in body.devices}
+
+ # A device must land in a rack that is part of the same payload, and a cable
+ # must join two devices in it — otherwise the prune below would orphan them.
+ for device in body.devices:
+ if device.rack_id not in rack_ids:
+ raise HTTPException(400, f"Device {device.id} references unknown rack {device.rack_id}")
+ for cable in body.cables:
+ if cable.from_device_id not in device_ids or cable.to_device_id not in device_ids:
+ raise HTTPException(400, f"Cable {cable.id} references a device outside this payload")
+
+ # Prune first (cables, then devices, then racks) so freed rows never collide
+ # with an upsert that reuses their geometry.
+ for existing_cable in (
+ await db.execute(select(RackCable).where(RackCable.design_id == body.design_id))
+ ).scalars().all():
+ if existing_cable.id not in {c.id for c in body.cables}:
+ await db.delete(existing_cable)
+ for existing_device in (
+ await db.execute(select(RackDevice).where(RackDevice.design_id == body.design_id))
+ ).scalars().all():
+ if existing_device.id not in device_ids:
+ await db.delete(existing_device)
+ for existing_rack in (
+ await db.execute(select(Rack).where(Rack.design_id == body.design_id))
+ ).scalars().all():
+ if existing_rack.id not in rack_ids:
+ await db.delete(existing_rack)
+ await db.flush()
+
+ for rack_data in body.racks:
+ payload: dict[str, Any] = rack_data.model_dump()
+ payload["design_id"] = body.design_id
+ db_rack = await db.get(Rack, rack_data.id)
+ if db_rack:
+ for field, value in payload.items():
+ setattr(db_rack, field, value)
+ else:
+ db.add(Rack(**payload))
+ await db.flush() # racks must exist before devices point at them
+
+ for device_data in body.devices:
+ payload = device_data.model_dump()
+ payload["design_id"] = body.design_id
+ db_device = await db.get(RackDevice, device_data.id)
+ if db_device:
+ for field, value in payload.items():
+ setattr(db_device, field, value)
+ else:
+ db.add(RackDevice(**payload))
+ await db.flush() # devices must exist before cables point at them
+
+ for cable_data in body.cables:
+ payload = cable_data.model_dump()
+ payload["design_id"] = body.design_id
+ db_cable = await db.get(RackCable, cable_data.id)
+ if db_cable:
+ for field, value in payload.items():
+ setattr(db_cable, field, value)
+ else:
+ db.add(RackCable(**payload))
+
+ # Viewport lives on the design's shared CanvasState row, like the logical canvas.
+ state = await db.get(CanvasState, body.design_id)
+ if state:
+ state.viewport = body.viewport
+ state.saved_at = datetime.now(timezone.utc)
+ else:
+ db.add(CanvasState(design_id=body.design_id, viewport=body.viewport))
+
+ await db.commit()
+ return {"saved": True}
+
+
[email protected]("/inventory", response_model=RackInventoryResponse)
+async def rack_inventory(
+ design_id: str = Query(..., description="Rack design the tray is for"),
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> RackInventoryResponse:
+ """Device Inventory entries that can be racked, flagged with what is already mounted.
+
+ Reads `pending_devices` — the inventory survives approval and node deletion,
+ so unracking or deleting a canvas node never removes the entry here.
+ """
+ await _require_design(db, design_id)
+
+ devices = (
+ await db.execute(select(PendingDevice).where(PendingDevice.status != "hidden"))
+ ).scalars().all()
+ mounted = {
+ row
+ for row in (
+ await db.execute(
+ select(RackDevice.device_id).where(RackDevice.design_id == design_id)
+ )
+ ).scalars().all()
+ if row
+ }
+
+ # Correlate against canvas nodes for live status: IEEE first (stable), then IP.
+ nodes = (await db.execute(select(Node))).scalars().all()
+ by_ieee = {n.ieee_address: n for n in nodes if n.ieee_address}
+ by_ip: dict[str, Node] = {}
+ for node in nodes:
+ for token in _ip_tokens(node.ip):
+ by_ip.setdefault(token, node)
+
+ items = []
+ for device in devices:
+ if device.suggested_type in _UNRACKABLE_TYPES:
+ continue
+ linked: Node | None = by_ieee.get(device.ieee_address) if device.ieee_address else None
+ if linked is None:
+ linked = next((by_ip[t] for t in _ip_tokens(device.ip) if t in by_ip), None)
+ items.append(
+ RackInventoryItem(
+ id=device.id,
+ label=device.friendly_name or device.hostname or device.ip or device.id,
+ suggested_type=device.suggested_type,
+ ip=device.ip,
+ status=device.status,
+ discovery_source=device.discovery_source,
+ node_id=linked.id if linked else None,
+ node_status=linked.status if linked else None,
+ racked=device.id in mounted,
+ )
+ )
+ return RackInventoryResponse(items=items)
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.py
index 51c5032..04733e7 100644
--- a/backend/app/api/routes/scan.py
+++ b/backend/app/api/routes/scan.py
@@ -14,7 +14,7 @@ from app.core.config import settings
from app.db.database import AsyncSessionLocal, get_db
from app.db.models import Design, Edge, Node, PendingDevice, PendingDeviceLink, ScanRun
from app.schemas.nodes import NodeCreate
-from app.schemas.scan import PendingDeviceResponse, ScanRunResponse
+from app.schemas.scan import PendingDeviceCreate, PendingDeviceResponse, ScanRunResponse
from app.services.node_dedupe import dedupe_nodes_by_ieee, find_duplicate_node
from app.services.scanner import DeepScanOptions, _valid_port_range, request_cancel, run_scan
from app.services.zigbee_service import (
@@ -312,6 +312,35 @@ async def list_pending(db: AsyncSession = Depends(get_db), _: str = Depends(get_
return await _with_canvas_counts(db, list(result.scalars().all()))
[email protected]("/pending", response_model=PendingDeviceResponse, status_code=201)
+async def create_pending(
+ body: PendingDeviceCreate,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> PendingDevice:
+ """Add an inventory entry by hand, for hardware no scan can discover.
+
+ Lands as ``status="pending"`` like a discovery would, so the existing approve
+ / hide / restore flows apply unchanged.
+ """
+ device = PendingDevice(
+ hostname=body.hostname,
+ ip=body.ip,
+ mac=body.mac,
+ suggested_type=body.suggested_type,
+ model=body.model,
+ vendor=body.vendor,
+ properties=body.properties,
+ status="pending",
+ discovery_source="manual",
+ discovery_sources=["manual"],
+ )
+ db.add(device)
+ await db.commit()
+ await db.refresh(device)
+ return (await _with_canvas_counts(db, [device]))[0]
+
+
@router.delete("/pending", response_model=dict)
async def clear_pending(
db: AsyncSession = Depends(get_db),
diff --git a/backend/app/db/models.py b/backend/app/db/models.py
index c656202..b5e45ee 100644
--- a/backend/app/db/models.py
+++ b/backend/app/db/models.py
@@ -105,6 +105,99 @@ class CanvasState(Base):
saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
+class Rack(Base):
+ """A physical rack on a `design_type='rack'` canvas.
+
+ Racks live per design, like nodes and edges. Geometry is expressed in rack
+ units: `u_height` is the number of mountable U, and a device's `u_start` is
+ always counted from the bottom rail — `numbering` only changes the printed
+ labels.
+ """
+
+ __tablename__ = "racks"
+
+ id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
+ design_id: Mapped[str] = mapped_column(String, ForeignKey("designs.id", ondelete="CASCADE"), nullable=False)
+ name: Mapped[str] = mapped_column(String, nullable=False)
+ u_height: Mapped[int] = mapped_column(Integer, default=42)
+ # "19" or "10" (inches). Drives the drawn inner width.
+ width_standard: Mapped[str] = mapped_column(String, default="19")
+ # "bottom-up" or "top-down" — printed U labels only, never storage order.
+ numbering: Mapped[str] = mapped_column(String, default="bottom-up")
+ location: Mapped[str | None] = mapped_column(String, nullable=True)
+ # Frame/rail/interior colours + showNumbers/enclosed flags.
+ style: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
+ pos_x: Mapped[float] = mapped_column(Float, default=0)
+ pos_y: Mapped[float] = mapped_column(Float, default=0)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now)
+
+
+class RackDevice(Base):
+ """A piece of gear mounted in a rack.
+
+ Two independent, both-optional links back to the rest of the app:
+
+ * `device_id` — the Device Inventory entry (`pending_devices`). This is the
+ primary link: inventory rows survive approval *and* node deletion, so
+ unracking or deleting a canvas node never removes the inventory entry.
+ * `node_id` — the logical-canvas node, when one exists. Only used to resolve
+ live status and to seed cables from the network design's edges.
+
+ Both are ``SET NULL`` on delete and `label` is denormalized, so a rack keeps
+ rendering after an inventory purge.
+ """
+
+ __tablename__ = "rack_devices"
+
+ id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
+ design_id: Mapped[str] = mapped_column(String, ForeignKey("designs.id", ondelete="CASCADE"), nullable=False)
+ rack_id: Mapped[str] = mapped_column(String, ForeignKey("racks.id", ondelete="CASCADE"), nullable=False)
+ device_id: Mapped[str | None] = mapped_column(
+ String, ForeignKey("pending_devices.id", ondelete="SET NULL"), nullable=True
+ )
+ node_id: Mapped[str | None] = mapped_column(String, ForeignKey("nodes.id", ondelete="SET NULL"), nullable=True)
+ label: Mapped[str] = mapped_column(String, nullable=False)
+ # 1-based, counted from the bottom rail.
+ u_start: Mapped[int] = mapped_column(Integer, default=1)
+ u_height: Mapped[int] = mapped_column(Integer, default=1)
+ # 12-column horizontal grid: full = 12, half = 6, third = 4, quarter = 3.
+ col_start: Mapped[int] = mapped_column(Integer, default=0)
+ col_span: Mapped[int] = mapped_column(Integer, default=12)
+ faceplate_id: Mapped[str] = mapped_column(String, nullable=False, default="blank-1u")
+ color: Mapped[str | None] = mapped_column(String, nullable=True)
+ status: Mapped[str] = mapped_column(String, default="unknown")
+ # [{id, label, type, x, y}] — positions are unit coordinates on the plate.
+ ports: Mapped[list[Any]] = mapped_column(JSON, default=list)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now)
+
+
+class RackCable(Base):
+ """A patch between two rack device ports.
+
+ Not an `Edge`: rack cables are port-to-port and may cross racks, so they are
+ their own relation rather than a canvas edge.
+ """
+
+ __tablename__ = "rack_cables"
+
+ id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
+ design_id: Mapped[str] = mapped_column(String, ForeignKey("designs.id", ondelete="CASCADE"), nullable=False)
+ from_device_id: Mapped[str] = mapped_column(
+ String, ForeignKey("rack_devices.id", ondelete="CASCADE"), nullable=False
+ )
+ from_port_id: Mapped[str] = mapped_column(String, nullable=False)
+ to_device_id: Mapped[str] = mapped_column(
+ String, ForeignKey("rack_devices.id", ondelete="CASCADE"), nullable=False
+ )
+ to_port_id: Mapped[str] = mapped_column(String, nullable=False)
+ 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)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
+
+
class PendingDevice(Base):
__tablename__ = "pending_devices"
# Permit the plain (non-Mapped[]) annotations on the transient request-only
diff --git a/backend/app/main.py b/backend/app/main.py
index 709231e..e04695c 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -17,6 +17,7 @@ from app.api.routes import (
media,
nodes,
proxmox,
+ racks,
scan,
stats,
status,
@@ -77,6 +78,7 @@ app.include_router(nodes.router, prefix="/api/v1/nodes", tags=["nodes"])
app.include_router(edges.router, prefix="/api/v1/edges", tags=["edges"])
app.include_router(canvas.router, prefix="/api/v1/canvas", tags=["canvas"])
app.include_router(designs.router, prefix="/api/v1/designs", tags=["designs"])
+app.include_router(racks.router, prefix="/api/v1/racks", tags=["racks"])
app.include_router(scan.router, prefix="/api/v1/scan", tags=["scan"])
app.include_router(status.router, prefix="/api/v1/status", tags=["status"])
app.include_router(settings_routes.router, prefix="/api/v1/settings", tags=["settings"])
diff --git a/backend/app/schemas/designs.py b/backend/app/schemas/designs.py
index f5c9f55..c3707c3 100644
--- a/backend/app/schemas/designs.py
+++ b/backend/app/schemas/designs.py
@@ -1,15 +1,27 @@
from datetime import datetime
-from pydantic import BaseModel
+from pydantic import BaseModel, field_validator
+
+# Kept in sync with DesignType in frontend/src/types.
+# "network" and "electrical" render the same React Flow canvas and differ only by
+# palette and node set — the icon drives their presentation. "rack" is a genuinely
+# different renderer (racks, mounted gear, port-to-port cables), so the frontend
+# does branch on this field.
+DESIGN_TYPES = {"network", "electrical", "rack"}
class DesignCreate(BaseModel):
name: str
icon: str = "dashboard"
- # Vestigial: kept for backward compatibility. The UI no longer branches on it;
- # the chosen icon now drives presentation. Defaults to a generic canvas.
design_type: str = "network"
+ @field_validator("design_type")
+ @classmethod
+ def _known_type(cls, v: str) -> str:
+ if v not in DESIGN_TYPES:
+ raise ValueError(f"design_type must be one of {sorted(DESIGN_TYPES)}")
+ return v
+
class DesignUpdate(BaseModel):
name: str | None = None
diff --git a/backend/app/schemas/racks.py b/backend/app/schemas/racks.py
new file mode 100644
index 0000000..4360dcd
--- /dev/null
+++ b/backend/app/schemas/racks.py
@@ -0,0 +1,198 @@
+from typing import Any
+
+from pydantic import BaseModel, field_validator
+
+# Kept in sync with the frontend rack model (frontend/src/types).
+WIDTH_STANDARDS = {"19", "10"}
+NUMBERINGS = {"bottom-up", "top-down"}
+CABLE_TYPES = {"ethernet", "fiber"}
+# 12-column horizontal grid: full = 12, half = 6, third = 4, quarter = 3.
+RACK_COLUMNS = 12
+
+
+class RackSave(BaseModel):
+ id: str
+ name: str
+ u_height: int = 42
+ width_standard: str = "19"
+ numbering: str = "bottom-up"
+ location: str | None = None
+ style: dict[str, Any] = {}
+ pos_x: float = 0
+ pos_y: float = 0
+
+ @field_validator("u_height")
+ @classmethod
+ def _positive_height(cls, v: int) -> int:
+ if not 1 <= v <= 100:
+ raise ValueError("u_height must be between 1 and 100")
+ return v
+
+ @field_validator("width_standard")
+ @classmethod
+ def _known_width(cls, v: str) -> str:
+ if v not in WIDTH_STANDARDS:
+ raise ValueError(f"width_standard must be one of {sorted(WIDTH_STANDARDS)}")
+ return v
+
+ @field_validator("numbering")
+ @classmethod
+ def _known_numbering(cls, v: str) -> str:
+ if v not in NUMBERINGS:
+ raise ValueError(f"numbering must be one of {sorted(NUMBERINGS)}")
+ return v
+
+
+class RackDeviceSave(BaseModel):
+ id: str
+ rack_id: str
+ device_id: str | None = None
+ node_id: str | None = None
+ label: str
+ u_start: int = 1
+ u_height: int = 1
+ col_start: int = 0
+ col_span: int = RACK_COLUMNS
+ faceplate_id: str = "blank-1u"
+ color: str | None = None
+ status: str = "unknown"
+ ports: list[Any] = []
+
+ @field_validator("u_start", "u_height")
+ @classmethod
+ def _positive(cls, v: int) -> int:
+ if v < 1:
+ raise ValueError("u_start and u_height are 1-based and must be >= 1")
+ return v
+
+ @field_validator("col_start")
+ @classmethod
+ def _column_in_grid(cls, v: int) -> int:
+ if not 0 <= v < RACK_COLUMNS:
+ raise ValueError(f"col_start must be within the {RACK_COLUMNS}-column grid")
+ return v
+
+ @field_validator("col_span")
+ @classmethod
+ def _span_in_grid(cls, v: int) -> int:
+ if not 1 <= v <= RACK_COLUMNS:
+ raise ValueError(f"col_span must be between 1 and {RACK_COLUMNS}")
+ return v
+
+
+class RackCableSave(BaseModel):
+ id: str
+ from_device_id: str
+ from_port_id: str
+ to_device_id: str
+ to_port_id: str
+ type: str = "ethernet"
+ color: str = "#39d353"
+ label: str | None = None
+
+ @field_validator("type")
+ @classmethod
+ def _known_type(cls, v: str) -> str:
+ if v not in CABLE_TYPES:
+ raise ValueError(f"type must be one of {sorted(CABLE_TYPES)}")
+ return v
+
+
+class RackSaveRequest(BaseModel):
+ """Full rack state for one design — upserted, with anything missing pruned.
+
+ Same contract as ``POST /api/v1/canvas/save``: the client owns the state and
+ sends all of it on an explicit Save.
+ """
+
+ design_id: str
+ racks: list[RackSave] = []
+ devices: list[RackDeviceSave] = []
+ cables: list[RackCableSave] = []
+ # Pan/zoom, stored on the design's shared CanvasState row like the logical canvas.
+ viewport: dict[str, Any] = {}
+
+
+class RackResponse(BaseModel):
+ id: str
+ design_id: str
+ name: str
+ u_height: int
+ width_standard: str
+ numbering: str
+ location: str | None = None
+ style: dict[str, Any] = {}
+ pos_x: float
+ pos_y: float
+
+ @field_validator("style", mode="before")
+ @classmethod
+ def _coerce_style(cls, v: Any) -> dict[str, Any]:
+ return v if isinstance(v, dict) else {}
+
+ model_config = {"from_attributes": True}
+
+
+class RackDeviceResponse(BaseModel):
+ id: str
+ design_id: str
+ rack_id: str
+ device_id: str | None = None
+ node_id: str | None = None
+ label: str
+ u_start: int
+ u_height: int
+ col_start: int
+ col_span: int
+ faceplate_id: str
+ color: str | None = None
+ status: str
+ ports: list[Any] = []
+
+ @field_validator("ports", mode="before")
+ @classmethod
+ def _coerce_ports(cls, v: Any) -> list[Any]:
+ return v if isinstance(v, list) else []
+
+ model_config = {"from_attributes": True}
+
+
+class RackCableResponse(BaseModel):
+ id: str
+ design_id: str
+ from_device_id: str
+ from_port_id: str
+ to_device_id: str
+ to_port_id: str
+ type: str
+ color: str
+ label: str | None = None
+
+ model_config = {"from_attributes": True}
+
+
+class RackStateResponse(BaseModel):
+ racks: list[RackResponse]
+ devices: list[RackDeviceResponse]
+ cables: list[RackCableResponse]
+ viewport: dict[str, Any] = {}
+
+
+class RackInventoryItem(BaseModel):
+ """A Device Inventory entry offered to the rack tray."""
+
+ id: str
+ label: str
+ suggested_type: str | None = None
+ ip: str | None = None
+ status: str
+ discovery_source: str | None = None
+ # Live status of the matching canvas node, when the device is on one.
+ node_id: str | None = None
+ node_status: str | None = None
+ # True when this device is already mounted somewhere in this design.
+ racked: bool = False
+
+
+class RackInventoryResponse(BaseModel):
+ items: list[RackInventoryItem]
diff --git a/backend/app/schemas/scan.py b/backend/app/schemas/scan.py
index 8660e64..52bdbbb 100644
--- a/backend/app/schemas/scan.py
+++ b/backend/app/schemas/scan.py
@@ -47,6 +47,23 @@ class PendingDeviceResponse(BaseModel):
model_config = {"from_attributes": True}
+class PendingDeviceCreate(BaseModel):
+ """Manually add an entry to the Device Inventory.
+
+ Used when the user documents hardware no scan can find — a dumb switch, a
+ patch panel, a machine that is powered off. Lands with
+ `discovery_source="manual"` so the inventory filters can tell it apart.
+ """
+
+ hostname: str
+ ip: str | None = None
+ mac: str | None = None
+ suggested_type: str | None = None
+ model: str | None = None
+ vendor: str | None = None
+ properties: list[Any] = []
+
+
class ScanRunResponse(BaseModel):
id: str
status: str
diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.py
new file mode 100644
index 0000000..b4d72f4
--- /dev/null
+++ b/backend/tests/test_racks.py
@@ -0,0 +1,337 @@
+import pytest
+from httpx import AsyncClient
+
+pytestmark = pytest.mark.asyncio
+
+
+async def _design(client: AsyncClient, headers: dict, *, name="Rack Room", design_type="rack") -> str:
+ res = await client.post(
+ "/api/v1/designs",
+ json={"name": name, "icon": "server", "design_type": design_type},
+ headers=headers,
+ )
+ assert res.status_code == 201, res.text
+ return res.json()["id"]
+
+
+def _state(design_id: str, **overrides) -> dict:
+ """A minimal but complete rack payload: one rack, two devices, one patch."""
+ payload = {
+ "design_id": design_id,
+ "racks": [
+ {
+ "id": "rack-1",
+ "name": "Main",
+ "u_height": 12,
+ "width_standard": "19",
+ "numbering": "bottom-up",
+ "location": "garage",
+ "style": {"frame": "#1c2129", "showNumbers": True},
+ "pos_x": 40,
+ "pos_y": 60,
+ }
+ ],
+ "devices": [
+ {
+ "id": "dev-sw",
+ "rack_id": "rack-1",
+ "label": "sw-24",
+ "u_start": 10,
+ "u_height": 1,
+ "col_start": 0,
+ "col_span": 12,
+ "faceplate_id": "switch-24",
+ "status": "online",
+ "ports": [{"id": "p1", "label": "1", "type": "rj45", "x": 0.4, "y": 0.5}],
+ },
+ {
+ "id": "dev-nas",
+ "rack_id": "rack-1",
+ "label": "nas",
+ "u_start": 4,
+ "u_height": 2,
+ "col_start": 0,
+ "col_span": 12,
+ "faceplate_id": "nas-2u",
+ "status": "unknown",
+ "ports": [{"id": "p2", "label": "eth0", "type": "rj45", "x": 0.7, "y": 0.5}],
+ },
+ ],
+ "cables": [
+ {
+ "id": "cbl-1",
+ "from_device_id": "dev-sw",
+ "from_port_id": "p1",
+ "to_device_id": "dev-nas",
+ "to_port_id": "p2",
+ "type": "ethernet",
+ "color": "#39d353",
+ }
+ ],
+ "viewport": {"x": 10, "y": 20, "zoom": 1.5},
+ }
+ payload.update(overrides)
+ return payload
+
+
+class TestDesignType:
+ async def test_creates_a_rack_design(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ res = await client.get("/api/v1/designs", headers=headers)
+ design = next(d for d in res.json() if d["id"] == design_id)
+ assert design["design_type"] == "rack"
+
+ async def test_rejects_an_unknown_design_type(self, client: AsyncClient, headers):
+ res = await client.post(
+ "/api/v1/designs",
+ json={"name": "Nope", "design_type": "spaceship"},
+ headers=headers,
+ )
+ assert res.status_code == 422
+
+
+class TestSaveAndLoad:
+ async def test_round_trips_the_full_state(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ res = await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
+ assert res.status_code == 200, res.text
+
+ loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()
+ assert [r["name"] for r in loaded["racks"]] == ["Main"]
+ assert loaded["racks"][0]["u_height"] == 12
+ assert loaded["racks"][0]["style"]["showNumbers"] is True
+ assert {d["id"] for d in loaded["devices"]} == {"dev-sw", "dev-nas"}
+ assert loaded["devices"][0]["ports"][0]["type"] == "rj45"
+ assert loaded["cables"][0]["from_port_id"] == "p1"
+ assert loaded["viewport"] == {"x": 10, "y": 20, "zoom": 1.5}
+
+ async def test_prunes_what_the_client_dropped(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
+
+ trimmed = _state(design_id)
+ trimmed["devices"] = [d for d in trimmed["devices"] if d["id"] == "dev-sw"]
+ trimmed["cables"] = []
+ await client.post("/api/v1/racks/save", json=trimmed, headers=headers)
+
+ loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()
+ assert {d["id"] for d in loaded["devices"]} == {"dev-sw"}
+ assert loaded["cables"] == []
+
+ async def test_updates_an_existing_device_in_place(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
+
+ moved = _state(design_id)
+ moved["devices"][1]["u_start"] = 1
+ moved["devices"][1]["label"] = "nas-renamed"
+ await client.post("/api/v1/racks/save", json=moved, headers=headers)
+
+ loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()
+ nas = next(d for d in loaded["devices"] if d["id"] == "dev-nas")
+ assert (nas["u_start"], nas["label"]) == (1, "nas-renamed")
+
+ async def test_keeps_designs_isolated(self, client: AsyncClient, headers):
+ first = await _design(client, headers, name="Rack A")
+ second = await _design(client, headers, name="Rack B")
+ await client.post("/api/v1/racks/save", json=_state(first), headers=headers)
+
+ loaded = (await client.get(f"/api/v1/racks?design_id={second}", headers=headers)).json()
+ assert loaded["racks"] == []
+ assert loaded["devices"] == []
+
+ async def test_rejects_an_unknown_design(self, client: AsyncClient, headers):
+ res = await client.post("/api/v1/racks/save", json=_state("nope"), headers=headers)
+ assert res.status_code == 404
+
+ async def test_rejects_a_device_pointing_outside_the_payload(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ broken = _state(design_id)
+ broken["devices"][0]["rack_id"] = "rack-ghost"
+ res = await client.post("/api/v1/racks/save", json=broken, headers=headers)
+ assert res.status_code == 400
+
+ async def test_rejects_a_cable_pointing_outside_the_payload(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ broken = _state(design_id)
+ broken["cables"][0]["to_device_id"] = "dev-ghost"
+ res = await client.post("/api/v1/racks/save", json=broken, headers=headers)
+ assert res.status_code == 400
+
+ @pytest.mark.parametrize(
+ "patch",
+ [
+ {"u_height": 0},
+ {"width_standard": "23"},
+ {"numbering": "sideways"},
+ ],
+ )
+ async def test_rejects_invalid_rack_geometry(self, client: AsyncClient, headers, patch):
+ design_id = await _design(client, headers)
+ payload = _state(design_id)
+ payload["racks"][0].update(patch)
+ res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
+ assert res.status_code == 422
+
+ @pytest.mark.parametrize(
+ "patch",
+ [
+ {"u_start": 0},
+ {"col_start": 12},
+ {"col_span": 13},
+ ],
+ )
+ async def test_rejects_invalid_device_geometry(self, client: AsyncClient, headers, patch):
+ design_id = await _design(client, headers)
+ payload = _state(design_id)
+ payload["devices"][0].update(patch)
+ res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
+ assert res.status_code == 422
+
+ async def test_rejects_an_unknown_cable_type(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ payload = _state(design_id)
+ payload["cables"][0]["type"] = "power"
+ res = await client.post("/api/v1/racks/save", json=payload, headers=headers)
+ assert res.status_code == 422
+
+ async def test_requires_auth(self, client: AsyncClient):
+ assert (await client.get("/api/v1/racks?design_id=any")).status_code == 401
+
+
+class TestInventory:
+ async def test_lists_rackable_devices_only(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "pve-01", "suggested_type": "proxmox"},
+ headers=headers,
+ )
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "phone", "suggested_type": "mobile"},
+ headers=headers,
+ )
+
+ res = await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
+ labels = [i["label"] for i in res.json()["items"]]
+ assert "pve-01" in labels
+ assert "phone" not in labels
+
+ async def test_flags_devices_already_mounted(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ created = (
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "sw-24", "suggested_type": "switch"},
+ headers=headers,
+ )
+ ).json()
+
+ payload = _state(design_id)
+ payload["devices"][0]["device_id"] = created["id"]
+ await client.post("/api/v1/racks/save", json=payload, headers=headers)
+
+ items = (
+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
+ ).json()["items"]
+ assert next(i for i in items if i["id"] == created["id"])["racked"] is True
+
+ async def test_resolves_the_canvas_node_for_live_status(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ node = (
+ await client.post(
+ "/api/v1/nodes",
+ json={"type": "server", "label": "nas", "ip": "192.168.1.9", "status": "online"},
+ headers=headers,
+ )
+ ).json()
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "nas", "ip": "192.168.1.9", "suggested_type": "nas"},
+ headers=headers,
+ )
+
+ items = (
+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
+ ).json()["items"]
+ entry = next(i for i in items if i["label"] == "nas")
+ assert entry["node_id"] == node["id"]
+ assert entry["node_status"] == "online"
+
+ async def test_manual_entry_is_tagged_as_such(self, client: AsyncClient, headers):
+ created = (
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "patch-panel", "suggested_type": "generic"},
+ headers=headers,
+ )
+ ).json()
+ assert created["discovery_source"] == "manual"
+ assert created["status"] == "pending"
+
+ listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
+ assert any(d["id"] == created["id"] for d in listed)
+
+
+class TestDesignLifecycle:
+ async def test_deleting_a_design_removes_its_rack_rows(self, client: AsyncClient, headers):
+ keeper = await _design(client, headers, name="Keeper", design_type="network")
+ design_id = await _design(client, headers)
+ await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
+
+ assert (await client.delete(f"/api/v1/designs/{design_id}", headers=headers)).status_code == 204
+ assert (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).status_code == 404
+ # The other design is untouched.
+ assert (await client.get(f"/api/v1/racks?design_id={keeper}", headers=headers)).status_code == 200
+
+ async def test_unmounting_keeps_the_inventory_entry(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ created = (
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "sw-24", "suggested_type": "switch"},
+ headers=headers,
+ )
+ ).json()
+
+ payload = _state(design_id)
+ payload["devices"][0]["device_id"] = created["id"]
+ await client.post("/api/v1/racks/save", json=payload, headers=headers)
+
+ # Unmount: the device disappears from the rack payload entirely.
+ unmounted = _state(design_id)
+ unmounted["devices"] = [d for d in unmounted["devices"] if d["id"] != "dev-sw"]
+ unmounted["cables"] = []
+ await client.post("/api/v1/racks/save", json=unmounted, headers=headers)
+
+ items = (
+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
+ ).json()["items"]
+ entry = next(i for i in items if i["id"] == created["id"])
+ assert entry["racked"] is False
+
+ async def test_copying_a_rack_design_duplicates_its_racks(self, client: AsyncClient, headers):
+ design_id = await _design(client, headers)
+ await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)
+
+ copy = (
+ await client.post(
+ f"/api/v1/designs/{design_id}/copy",
+ json={"name": "Rack Room (copy)", "icon": "server"},
+ headers=headers,
+ )
+ ).json()
+ assert copy["design_type"] == "rack"
+
+ loaded = (await client.get(f"/api/v1/racks?design_id={copy['id']}", headers=headers)).json()
+ assert [r["name"] for r in loaded["racks"]] == ["Main"]
+ assert len(loaded["devices"]) == 2
+ assert len(loaded["cables"]) == 1
+ # Fresh ids, so editing the copy cannot touch the original.
+ assert loaded["racks"][0]["id"] != "rack-1"
+ assert {d["id"] for d in loaded["devices"]}.isdisjoint({"dev-sw", "dev-nas"})
+ # Cables still join the copied devices, not the originals.
+ copied_ids = {d["id"] for d in loaded["devices"]}
+ assert loaded["cables"][0]["from_device_id"] in copied_ids
+ assert loaded["cables"][0]["to_device_id"] in copied_ids
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 7dcac07..65f415a 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -52,7 +52,10 @@ import { WalkthroughOverlay } from '@/walkthrough/WalkthroughOverlay'
import { DEMO_SCAN_RUNS, DEMO_PENDING_DEVICES } from '@/walkthrough/demoTourData'
import { useStatusPolling } from '@/hooks/useStatusPolling'
import { bootstrapAuth } from '@/auth/bootstrap'
-import type { NodeData, EdgeData, CustomStyleDef, FloorMapConfig, NodeType } from '@/types'
+import { RackCanvas } from '@/rack/components/RackCanvas'
+import { RackInspector } from '@/rack/components/RackInspector'
+import { useRackStore } from '@/rack/store'
+import type { NodeData, EdgeData, CustomStyleDef, DesignType, FloorMapConfig, NodeType } from '@/types'
import type { ZigbeeNode, ZigbeeEdge } from '@/components/zigbee/types'
import type { ZwaveNode, ZwaveEdge } from '@/components/zwave/types'
import type { ProxmoxNode, ProxmoxEdge } from '@/components/proxmox/types'
@@ -66,7 +69,17 @@ export default function App() {
const { isAuthenticated, isInitialized } = useAuthStore()
const authBootstrapStarted = useRef(false)
const { activeTheme, setTheme, customStyle, setCustomStyle } = useThemeStore()
- const { activeDesignId, setDesigns, setActiveDesign } = useDesignStore()
+ const { activeDesignId, activeDesignType, setDesigns, setActiveDesign } = useDesignStore()
+ const isRackDesign = activeDesignType === 'rack'
+ const rackDirty = useRackStore((s) => s.hasUnsavedChanges)
+ const rackEditSeq = useRackStore((s) => s.editSeq)
+
+ /** Kind of a design by id, read straight from the store (no stale closure). */
+ const designTypeOf = useCallback(
+ (id: string | null | undefined): DesignType =>
+ useDesignStore.getState().designs.find((d) => d.id === id)?.design_type ?? 'network',
+ [],
+ )
useStatusPolling()
@@ -134,6 +147,16 @@ export default function App() {
const handleSave = useCallback(async (designIdOverride?: string, options?: { silent?: boolean }): Promise<boolean> => {
try {
const saveDesignId = designIdOverride ?? activeDesignId
+ // Rack canvases own their own state and persistence path.
+ if (designTypeOf(saveDesignId) === 'rack') {
+ const ok = await useRackStore.getState().save()
+ if (ok) {
+ if (!options?.silent) toast.success('Rack canvas saved')
+ } else {
+ toast.error('Save failed')
+ }
+ return ok
+ }
if (STANDALONE) {
if (!saveDesignId) return false
// Floor plans are backend-only (upload/serve), so standalone never persists one.
@@ -154,7 +177,7 @@ export default function App() {
toast.error('Save failed')
return false
}
- }, [nodes, edges, markSaved, activeTheme, customStyle, activeDesignId, floorMap])
+ }, [nodes, edges, markSaved, activeTheme, customStyle, activeDesignId, floorMap, designTypeOf])
// Keep a ref so the keydown handler always calls the latest version
const handleSaveRef = useRef(handleSave)
@@ -165,12 +188,12 @@ export default function App() {
useAutosave({
enabled: autosave.enabled,
delaySeconds: autosave.delay,
- hasUnsavedChanges,
+ hasUnsavedChanges: isRackDesign ? rackDirty : hasUnsavedChanges,
designId: loadedDesignId,
// Debounce resets on each real user edit (editSeq), not on raw nodes/edges
// identity — live status polling churns those arrays without a user edit and
// would otherwise keep re-arming (and starving) the timer during monitoring.
- changeSignals: [editSeq],
+ changeSignals: [isRackDesign ? rackEditSeq : editSeq],
getLiveDesignId: () => loadedDesignIdRef.current,
onSave: (designId) => { void handleSaveRef.current(designId, { silent: true }) },
})
@@ -257,6 +280,24 @@ export default function App() {
setLoadedDesignId(designId)
}, [loadCanvas, setTheme, setCustomStyle, setFloorMap])
+ /**
+ * Load whichever canvas the design holds. Rack designs bypass the node/edge
+ * canvas entirely — different store, different endpoints.
+ */
+ const loadAnyDesign = useCallback(async (designId: string) => {
+ if (designTypeOf(designId) !== 'rack') {
+ if (STANDALONE) loadStandaloneCanvas(designId)
+ else await loadCanvasFromApi(designId)
+ return
+ }
+ // The rack store owns the fetch; App only records provenance afterwards, so
+ // none of these run synchronously inside the calling effect.
+ await useRackStore.getState().loadDesign(designId)
+ setIsNewUser(false)
+ setLoadError(false)
+ setLoadedDesignId(designId)
+ }, [designTypeOf, loadStandaloneCanvas, loadCanvasFromApi])
+
const loadDesignsAndCanvas = useCallback(async () => {
// Prefer a design id explicitly requested via the URL (?design=<id>), so a
// refresh or shared link opens that design. Ignore it when it doesn't match
@@ -269,7 +310,7 @@ export default function App() {
const targetId = fromUrl ?? activeDesignId ?? designs[0]?.id
if (targetId) {
setActiveDesign(targetId)
- loadStandaloneCanvas(targetId)
+ void loadAnyDesign(targetId)
}
return
}
@@ -281,7 +322,7 @@ export default function App() {
const targetId = fromUrl ?? activeDesignId ?? loadedDesigns[0]?.id
if (targetId) {
setActiveDesign(targetId)
- await loadCanvasFromApi(targetId)
+ await loadAnyDesign(targetId)
}
} catch {
// Backend unreachable/errored — surface it. Do NOT seed the demo: that would
@@ -289,7 +330,7 @@ export default function App() {
setLoadError(true)
toast.error('Could not reach backend — check the server and retry')
}
- }, [setDesigns, setActiveDesign, loadCanvasFromApi, loadStandaloneCanvas, activeDesignId])
+ }, [setDesigns, setActiveDesign, loadAnyDesign, activeDesignId])
// Keep a ref so the auth effect can call the latest loader without listing it
// as a dependency (which would re-fire on every design switch).
@@ -376,7 +417,7 @@ export default function App() {
}
// Standalone has no auth gate; backed mode requires authentication.
const ready = STANDALONE || isAuthenticated
- const loadForDesign = STANDALONE ? loadStandaloneCanvas : loadCanvasFromApi
+ const loadForDesign = loadAnyDesign
if (ready && activeDesignId && initialLoadDone.current) {
const oldId = prevDesignRef.current
// If the previous design was deleted (no longer in the list), don't try to
@@ -390,7 +431,7 @@ export default function App() {
const targetId = activeDesignId
handleSave(oldId).then((ok) => {
if (ok) {
- loadForDesign(targetId)
+ void loadForDesign(targetId)
} else {
// Save failed: don't load the new design — that would overwrite the
// unsaved in-memory canvas. Revert the selection back to the old
@@ -401,7 +442,12 @@ export default function App() {
}
})
} else {
- loadForDesign(activeDesignId)
+ // Loading a design is exactly the "synchronize with an external system"
+ // case: it fetches and then publishes the result into React state. The
+ // rule can't see through the loader, so silence it here rather than
+ // deferring the fetch by a tick.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ void loadForDesign(activeDesignId)
}
}
if (activeDesignId) {
@@ -990,17 +1036,25 @@ export default function App() {
/>
<div className="flex flex-1 min-h-0">
<div ref={canvasRef} className="flex-1 min-w-0 h-full">
- <CanvasContainer
- onConnect={handleEdgeConnect}
- onEdgeDoubleClick={handleEdgeDoubleClick}
- onNodeDoubleClick={handleNodeDoubleClick}
- onNodeDragStart={snapshotHistory}
- onRequestAddToGroup={setPendingGroupAdd}
- onRequestAddToContainer={setPendingContainerAdd}
- onOpenPending={(deviceId) => openPendingModal(deviceId)}
- />
+ {isRackDesign ? (
+ <RackCanvas />
+ ) : (
+ <CanvasContainer
+ onConnect={handleEdgeConnect}
+ onEdgeDoubleClick={handleEdgeDoubleClick}
+ onNodeDoubleClick={handleNodeDoubleClick}
+ onNodeDragStart={snapshotHistory}
+ onRequestAddToGroup={setPendingGroupAdd}
+ onRequestAddToContainer={setPendingContainerAdd}
+ onOpenPending={(deviceId) => openPendingModal(deviceId)}
+ />
+ )}
</div>
- {(selectedNodeId || selectedNodeIds.length > 1) && <DetailPanel onEdit={handleEditNode} />}
+ {isRackDesign ? (
+ <RackInspector />
+ ) : (
+ (selectedNodeId || selectedNodeIds.length > 1) && <DetailPanel onEdit={handleEditNode} />
+ )}
</div>
</div>
</div>
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index abacdf6..2478b75 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -109,6 +109,15 @@ export interface DuplicateNodeConflict {
export const scanApi = {
trigger: (deepScan?: Partial<DeepScanConfig>) => api.post('/scan/trigger', deepScan ?? {}),
pending: () => api.get('/scan/pending'),
+ /** Add an inventory entry by hand, for hardware no scan can discover. */
+ createPending: (data: {
+ hostname: string
+ ip?: string | null
+ mac?: string | null
+ suggested_type?: string | null
+ model?: string | null
+ vendor?: string | null
+ }) => api.post<{ id: string; hostname: string | null }>('/scan/pending', data),
hidden: () => api.get('/scan/hidden'),
runs: () => api.get('/scan/runs'),
clearPending: () => api.delete('/scan/pending'),
@@ -220,6 +229,17 @@ export const designsApi = {
delete: (id: string) => api.delete(`/designs/${id}`),
}
+export const racksApi = {
+ load: (designId: string) =>
+ api.get<import('@/utils/rackSerializer').ApiRackState>('/racks', { params: { design_id: designId } }),
+ save: (payload: import('@/utils/rackSerializer').RackSavePayload) =>
+ api.post<{ saved: boolean }>('/racks/save', payload),
+ inventory: (designId: string) =>
+ api.get<{ items: import('@/utils/rackSerializer').ApiInventoryItem[] }>('/racks/inventory', {
+ params: { design_id: designId },
+ }),
+}
+
export interface ZigbeeConfigData {
mqtt_host: string
mqtt_port: number
diff --git a/frontend/src/components/modals/DesignModal.tsx b/frontend/src/components/modals/DesignModal.tsx
index 5cf08f4..028db1c 100644
--- a/frontend/src/components/modals/DesignModal.tsx
+++ b/frontend/src/components/modals/DesignModal.tsx
@@ -4,11 +4,22 @@ import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { DESIGN_ICONS, DEFAULT_DESIGN_ICON, resolveDesignIcon } from '@/utils/designIcons'
-import type { Design, FloorMapConfig } from '@/types'
+import type { Design, DesignType, FloorMapConfig } from '@/types'
+
+/** Canvas kinds offered on create. `electrical` shares the network renderer. */
+const CANVAS_KINDS: { value: DesignType; label: string; hint: string }[] = [
+ { value: 'network', label: 'Diagram', hint: 'Nodes and links on a free canvas' },
+ { value: 'rack', label: 'Rack', hint: 'Racks, mounted gear and patching' },
+]
export interface DesignFormData {
name: string
icon: string
+ /**
+ * Kind of canvas to create. Only offered in create mode — a canvas cannot
+ * change kind afterwards, since network and rack store different things.
+ */
+ designType?: DesignType
/**
* Floor plan for THIS canvas. Only present when the floor-plan section is
* shown (edit mode on the active canvas). `null` means "remove the floor
@@ -60,9 +71,12 @@ export function DesignModal({
}: DesignModalProps) {
const [name, setName] = useState(initial?.name ?? '')
const [icon, setIcon] = useState(initial?.icon ?? DEFAULT_DESIGN_ICON)
+ const [designType, setDesignType] = useState<DesignType>(initial?.designType ?? 'network')
// "Copy from existing" is create-mode only (no floor-plan section shown).
const canCopy = !showFloorMap && sourceDesigns.length > 0
+ // Editing never changes the kind; `initial` is only passed in edit mode.
+ const canPickKind = !initial && !showFloorMap
const [fromExisting, setFromExisting] = useState(false)
const [sourceId, setSourceId] = useState<string>(sourceDesigns[0]?.id ?? '')
@@ -103,6 +117,7 @@ export function DesignModal({
if (!trimmed) return
if (canCopy && fromExisting && !sourceId) return
const data: DesignFormData = { name: trimmed, icon }
+ if (canPickKind) data.designType = designType
if (canCopy && fromExisting && sourceId) {
data.sourceId = sourceId
}
@@ -146,6 +161,35 @@ export function DesignModal({
/>
</div>
+ {/* A copy inherits the source's kind, so the picker would be a lie. */}
+ {canPickKind && !fromExisting && (
+ <div className="space-y-1.5">
+ <Label>Kind</Label>
+ <div className="grid grid-cols-2 gap-1.5">
+ {CANVAS_KINDS.map((kind) => {
+ const selected = kind.value === designType
+ return (
+ <button
+ key={kind.value}
+ type="button"
+ aria-pressed={selected}
+ title={kind.hint}
+ onClick={() => setDesignType(kind.value)}
+ className={`rounded-md border px-2 py-2 text-left transition-colors cursor-pointer ${
+ selected
+ ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#00d4ff]'
+ : 'border-border text-muted-foreground hover:text-foreground hover:border-[#30363d]'
+ }`}
+ >
+ <span className="block text-xs font-medium">{kind.label}</span>
+ <span className="block text-[10px] leading-tight opacity-70">{kind.hint}</span>
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ )}
+
<div className="space-y-1.5">
<Label>Icon</Label>
<div className="grid grid-cols-8 gap-1.5">
diff --git a/frontend/src/components/modals/__tests__/DesignModal.test.tsx b/frontend/src/components/modals/__tests__/DesignModal.test.tsx
index da5fd5b..1b212a7 100644
--- a/frontend/src/components/modals/__tests__/DesignModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/DesignModal.test.tsx
@@ -15,7 +15,7 @@ describe('DesignModal', () => {
const { onSubmit } = renderModal()
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Home Network' } })
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
- expect(onSubmit).toHaveBeenCalledWith({ name: 'Home Network', icon: DEFAULT_DESIGN_ICON })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'Home Network', icon: DEFAULT_DESIGN_ICON, designType: 'network' })
})
it('submits the selected icon', () => {
@@ -23,7 +23,41 @@ describe('DesignModal', () => {
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Rack Power' } })
fireEvent.click(screen.getByRole('button', { name: 'Electrical' })) // zap icon's aria-label
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
- expect(onSubmit).toHaveBeenCalledWith({ name: 'Rack Power', icon: 'zap' })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'Rack Power', icon: 'zap', designType: 'network' })
+ })
+
+ describe('canvas kind', () => {
+ it('defaults to a diagram canvas', () => {
+ const { onSubmit } = renderModal()
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Net' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))
+ expect(onSubmit.mock.calls[0][0].designType).toBe('network')
+ })
+
+ it('submits the rack kind when picked', () => {
+ const { onSubmit } = renderModal()
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Rack Room' } })
+ fireEvent.click(screen.getByRole('button', { name: /^Rack/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))
+ expect(onSubmit.mock.calls[0][0].designType).toBe('rack')
+ })
+
+ it('is not offered in edit mode — a canvas cannot change kind', () => {
+ renderModal({ initial: { name: 'Existing', icon: 'server' }, submitLabel: 'Save' })
+ expect(screen.queryByRole('button', { name: /^Rack/ })).toBeNull()
+ })
+
+ it('is hidden once copying — a copy inherits the source kind', () => {
+ renderModal({
+ sourceDesigns: [
+ { id: 's1', name: 'Home Net', icon: 'network', design_type: 'network' as const,
+ created_at: '', updated_at: '', node_count: 1, group_count: 0, text_count: 0 },
+ ],
+ })
+ expect(screen.getByRole('button', { name: /^Rack/ })).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'Copy from existing' }))
+ expect(screen.queryByRole('button', { name: /^Rack/ })).toBeNull()
+ })
})
it('trims whitespace and blocks empty names', () => {
@@ -34,7 +68,7 @@ describe('DesignModal', () => {
fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' Spaced ' } })
fireEvent.click(submit)
- expect(onSubmit).toHaveBeenCalledWith({ name: 'Spaced', icon: DEFAULT_DESIGN_ICON })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'Spaced', icon: DEFAULT_DESIGN_ICON, designType: 'network' })
})
it('prefills name and icon in edit mode', () => {
@@ -55,7 +89,7 @@ describe('DesignModal', () => {
const input = screen.getByLabelText('Name')
fireEvent.change(input, { target: { value: 'Quick' } })
fireEvent.keyDown(input, { key: 'Enter' })
- expect(onSubmit).toHaveBeenCalledWith({ name: 'Quick', icon: DEFAULT_DESIGN_ICON })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'Quick', icon: DEFAULT_DESIGN_ICON, designType: 'network' })
})
it('calls onClose from Cancel', () => {
@@ -93,7 +127,7 @@ describe('DesignModal', () => {
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Copy of Home' } })
fireEvent.click(screen.getByRole('button', { name: 'Copy from existing' }))
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
- expect(onSubmit).toHaveBeenCalledWith({ name: 'Copy of Home', icon: DEFAULT_DESIGN_ICON, sourceId: 's1' })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'Copy of Home', icon: DEFAULT_DESIGN_ICON, designType: 'network', sourceId: 's1' })
})
it('includes the picked sourceId on submit', () => {
@@ -102,14 +136,14 @@ describe('DesignModal', () => {
fireEvent.click(screen.getByRole('button', { name: 'Copy from existing' }))
fireEvent.click(screen.getByRole('radio', { name: /Lab/ }))
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
- expect(onSubmit).toHaveBeenCalledWith({ name: 'Copy of Lab', icon: DEFAULT_DESIGN_ICON, sourceId: 's2' })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'Copy of Lab', icon: DEFAULT_DESIGN_ICON, designType: 'network', sourceId: 's2' })
})
it('omits sourceId when the blank option is kept', () => {
const { onSubmit } = renderModal({ sourceDesigns })
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Fresh' } })
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
- expect(onSubmit).toHaveBeenCalledWith({ name: 'Fresh', icon: DEFAULT_DESIGN_ICON })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'Fresh', icon: DEFAULT_DESIGN_ICON, designType: 'network' })
expect('sourceId' in onSubmit.mock.calls[0][0]).toBe(false)
})
@@ -131,7 +165,7 @@ describe('DesignModal', () => {
expect(screen.queryByText('Floor Plan')).toBeNull()
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'X' } })
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
- expect(onSubmit).toHaveBeenCalledWith({ name: 'X', icon: DEFAULT_DESIGN_ICON })
+ expect(onSubmit).toHaveBeenCalledWith({ name: 'X', icon: DEFAULT_DESIGN_ICON, designType: 'network' })
expect('floorMap' in onSubmit.mock.calls[0][0]).toBe(false)
})
diff --git a/frontend/src/components/panels/RackToolbarActions.tsx b/frontend/src/components/panels/RackToolbarActions.tsx
new file mode 100644
index 0000000..4bcb1f4
--- /dev/null
+++ b/frontend/src/components/panels/RackToolbarActions.tsx
@@ -0,0 +1,123 @@
+/**
+ * Rack-specific middle group of the header toolbar.
+ *
+ * Replaces the logical canvas actions (auto layout, YAML import/export) with the
+ * ones a rack canvas actually has: adding racks, patching, and controlling how
+ * much of the cabling is on screen.
+ */
+import { useState } from 'react'
+import { Cable, Link2, Plus, X } from 'lucide-react'
+import { toast } from 'sonner'
+import { Button } from '@/components/ui/button'
+import { useRackStore } from '@/rack/store'
+import { useRackPalette } from '@/rack/rackTheme'
+import { loadNetworkLinks } from '@/rack/networkLinks'
+import { CABLE_TYPE_LABELS } from '@/rack/rackDefaults'
+import { useDesignStore } from '@/stores/designStore'
+import type { CableType, CableVisibility } from '@/types'
+
+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
+
+const ghost =
+ 'gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]'
+const selectClass =
+ 'rounded border border-border bg-[#0d1117] px-2 py-1 text-xs text-foreground outline-none focus:border-[#00d4ff] cursor-pointer'
+
+export function RackToolbarActions() {
+ const palette = useRackPalette()
+ const addRack = useRackStore((s) => s.addRack)
+ const cableMode = useRackStore((s) => s.cableMode)
+ const toggleCableMode = useRackStore((s) => s.toggleCableMode)
+ const cableVisibility = useRackStore((s) => s.cableVisibility)
+ const setCableVisibility = useRackStore((s) => s.setCableVisibility)
+ const cableTypeFilter = useRackStore((s) => s.cableTypeFilter)
+ const setCableTypeFilter = useRackStore((s) => s.setCableTypeFilter)
+ const cableDraft = useRackStore((s) => s.cableDraft)
+ const cancelCableDraft = useRackStore((s) => s.cancelCableDraft)
+ const importCables = useRackStore((s) => s.importCablesFromNetwork)
+ const networkImportDone = useRackStore((s) => s.networkImportDone)
+ const designs = useDesignStore((s) => s.designs)
+ const [importing, setImporting] = useState(false)
+
+ async function handleImport() {
+ setImporting(true)
+ try {
+ const hints = STANDALONE ? [] : await loadNetworkLinks(designs)
+ const created = importCables(hints)
+ toast[created > 0 ? 'success' : 'info'](
+ created > 0
+ ? `${created} cable${created > 1 ? 's' : ''} imported from the network canvas`
+ : 'No matching link found — rack the devices first',
+ )
+ } finally {
+ setImporting(false)
+ }
+ }
+
+ return (
+ <>
+ <Button size="sm" variant="ghost" className={ghost} onClick={() => addRack({ style: palette.defaultRackStyle })}>
+ <Plus size={14} /> Rack
+ </Button>
+
+ <Button
+ size="sm"
+ variant="ghost"
+ className={`${ghost} ${cableMode ? 'text-[#00d4ff]' : ''}`}
+ onClick={toggleCableMode}
+ title="Click a port, then another, to patch. Click a cable to remove it."
+ >
+ <Cable size={14} /> {cableMode ? 'Exit patching' : 'Patch'}
+ </Button>
+
+ {cableMode && cableDraft && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className={`${ghost} text-[#e3b341]`}
+ onClick={cancelCableDraft}
+ >
+ <X size={14} /> Cancel cable
+ </Button>
+ )}
+
+ <select
+ className={selectClass}
+ aria-label="Cable visibility"
+ value={cableVisibility}
+ onChange={(e) => setCableVisibility(e.target.value as CableVisibility)}
+ >
+ <option value="hover">Cables on hover</option>
+ <option value="always">Cables always</option>
+ <option value="hidden">Cables hidden</option>
+ </select>
+
+ <select
+ className={selectClass}
+ aria-label="Cable type filter"
+ value={cableTypeFilter}
+ onChange={(e) => setCableTypeFilter(e.target.value as CableType | 'all')}
+ >
+ <option value="all">All types</option>
+ {(Object.keys(CABLE_TYPE_LABELS) as CableType[]).map((t) => (
+ <option key={t} value={t}>
+ {CABLE_TYPE_LABELS[t]}
+ </option>
+ ))}
+ </select>
+
+ {!STANDALONE && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className={ghost}
+ disabled={networkImportDone || importing}
+ onClick={() => void handleImport()}
+ title="One-shot: derive patches from the links already drawn on the logical canvases"
+ >
+ <Link2 size={14} /> Import links
+ </Button>
+ )}
+ </>
+ )
+}
diff --git a/frontend/src/components/panels/Sidebar.tsx b/frontend/src/components/panels/Sidebar.tsx
index 30f285c..1d22120 100644
--- a/frontend/src/components/panels/Sidebar.tsx
+++ b/frontend/src/components/panels/Sidebar.tsx
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect } from 'react'
-import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, EyeOff, Square, Settings, LogOut, Network, RadioTower, Server, Type, PlusCircle, Pencil, Trash2 } from 'lucide-react'
+import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, EyeOff, Square, Settings, LogOut, Network, RadioTower, Server, Type, PlusCircle, Pencil, Trash2, Rows3 } from 'lucide-react'
import { Logo } from '@/components/ui/Logo'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useCanvasStore } from '@/stores/canvasStore'
@@ -9,6 +9,10 @@ import { authApi, designsApi, mediaApi } from '@/api/client'
import * as standaloneStorage from '@/utils/standaloneStorage'
import { resolveDesignIcon, DEFAULT_DESIGN_ICON } from '@/utils/designIcons'
import { DesignModal, type DesignFormData } from '@/components/modals/DesignModal'
+import { InventoryTray } from '@/rack/components/InventoryTray'
+import { useRackStore } from '@/rack/store'
+import { useRackPalette } from '@/rack/rackTheme'
+import { freeUnits } from '@/rack/layout'
import type { Design } from '@/types'
import { toast } from 'sonner'
import { useLatestRelease } from '@/hooks/useLatestRelease'
@@ -37,15 +41,20 @@ interface SidebarProps {
export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbeeImport, onZwaveImport, onProxmoxImport, onSave, onOpenSettings, onOpenHistory, onOpenPending }: SidebarProps) {
const [collapsed, setCollapsed] = useState(false)
const logout = useAuthStore((s) => s.logout)
- const { designs, activeDesignId, setActiveDesign, addDesign, updateDesign, removeDesign } = useDesignStore()
+ const { designs, activeDesignId, activeDesignType, setActiveDesign, addDesign, updateDesign, removeDesign } = useDesignStore()
+ const isRack = activeDesignType === 'rack'
const [designSwitcherOpen, setDesignSwitcherOpen] = useState(false)
const [designModal, setDesignModal] = useState<{ mode: 'create' | 'edit'; design?: Design } | null>(null)
// Bumped on every open so the modal remounts and re-seeds its local state from
// the current floor plan — otherwise a reopen keeps stale width/height/lock
// and Save would clobber canvas-side resize/move.
const [openSeq, setOpenSeq] = useState(0)
- const { nodes, hasUnsavedChanges, floorMap, setFloorMap } = useCanvasStore()
+ const { nodes, hasUnsavedChanges: canvasDirty, floorMap, setFloorMap } = useCanvasStore()
const floorMapEditNonce = useCanvasStore((s) => s.floorMapEditNonce)
+ const rackPalette = useRackPalette()
+ const rackDirty = useRackStore((s) => s.hasUnsavedChanges)
+ const addRack = useRackStore((s) => s.addRack)
+ const hasUnsavedChanges = isRack ? rackDirty : canvasDirty
const handleLogout = useCallback(async () => {
try {
@@ -72,9 +81,10 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
? standaloneStorage.copyDesign(data.sourceId, data.name, data.icon)
: (await designsApi.copy(data.sourceId, { name: data.name, icon: data.icon })).data
} else {
+ const designType = data.designType ?? 'network'
created = STANDALONE
- ? standaloneStorage.createDesign(data.name, data.icon)
- : (await designsApi.create({ name: data.name, icon: data.icon })).data
+ ? standaloneStorage.createDesign(data.name, data.icon, designType)
+ : (await designsApi.create({ name: data.name, icon: data.icon, design_type: designType })).data
}
addDesign(created)
} else if (designModal.design) {
@@ -231,8 +241,8 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
{/* Views */}
<nav className="flex flex-col gap-0.5 p-2">
<SidebarItem
- icon={LayoutDashboard}
- label="Canvas"
+ icon={isRack ? Rows3 : LayoutDashboard}
+ label={isRack ? 'Rack view' : 'Canvas'}
collapsed={collapsed}
active
/>
@@ -255,10 +265,13 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
)}
</nav>
- {!collapsed && <div className="flex-1" />}
+ {/* The rack inventory is the sidebar's body: it scrolls, everything else
+ stays pinned. On a logical canvas the space is just a spacer. */}
+ {isRack && !collapsed ? <InventoryTray /> : !collapsed && <div className="flex-1" />}
{/* Stats footer — hidden in standalone (no scan / live status to count) */}
- {!collapsed && !STANDALONE && (
+ {!collapsed && isRack && <RackStats />}
+ {!collapsed && !isRack && !STANDALONE && (
<div className="px-3 py-2 border-t border-border text-xs text-muted-foreground space-y-0.5">
<div className="flex justify-between">
<span>Total</span>
@@ -277,16 +290,22 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
{/* Actions */}
<div className="flex flex-col gap-0.5 p-2 border-t border-border">
- <SidebarItem icon={Plus} label="Add Node" collapsed={collapsed} onClick={onAddNode} dataTour="add-node" />
- <SidebarItem icon={Square} label="Add Zone" collapsed={collapsed} onClick={onAddGroupRect} dataTour="add-zone" />
- <SidebarItem icon={Type} label="Add Text" collapsed={collapsed} onClick={onAddText} dataTour="add-text" />
- {!STANDALONE && <SidebarItem icon={ScanLine} label="Scan Network" collapsed={collapsed} onClick={handleScan} dataTour="scan-network" />}
- {!STANDALONE && <SidebarItem icon={Network} label="Zigbee Import" collapsed={collapsed} onClick={onZigbeeImport} dataTour="zigbee-import" />}
- {!STANDALONE && <SidebarItem icon={RadioTower} label="Z-Wave Import" collapsed={collapsed} onClick={onZwaveImport} dataTour="zwave-import" />}
- {!STANDALONE && <SidebarItem icon={Server} label="Proxmox Import" collapsed={collapsed} onClick={onProxmoxImport} dataTour="proxmox-import" />}
+ {isRack ? (
+ <SidebarItem icon={Plus} label="Add Rack" collapsed={collapsed} onClick={() => addRack({ style: rackPalette.defaultRackStyle })} />
+ ) : (
+ <>
+ <SidebarItem icon={Plus} label="Add Node" collapsed={collapsed} onClick={onAddNode} dataTour="add-node" />
+ <SidebarItem icon={Square} label="Add Zone" collapsed={collapsed} onClick={onAddGroupRect} dataTour="add-zone" />
+ <SidebarItem icon={Type} label="Add Text" collapsed={collapsed} onClick={onAddText} dataTour="add-text" />
+ </>
+ )}
+ {!STANDALONE && !isRack && <SidebarItem icon={ScanLine} label="Scan Network" collapsed={collapsed} onClick={handleScan} dataTour="scan-network" />}
+ {!STANDALONE && !isRack && <SidebarItem icon={Network} label="Zigbee Import" collapsed={collapsed} onClick={onZigbeeImport} dataTour="zigbee-import" />}
+ {!STANDALONE && !isRack && <SidebarItem icon={RadioTower} label="Z-Wave Import" collapsed={collapsed} onClick={onZwaveImport} dataTour="zwave-import" />}
+ {!STANDALONE && !isRack && <SidebarItem icon={Server} label="Proxmox Import" collapsed={collapsed} onClick={onProxmoxImport} dataTour="proxmox-import" />}
<SidebarItem
icon={Save}
- label="Save Canvas"
+ label={isRack ? 'Save Rack' : 'Save Canvas'}
collapsed={collapsed}
onClick={() => onSave()}
badge={hasUnsavedChanges}
@@ -333,6 +352,37 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
)
}
+/** Rack equivalent of the node stats footer: capacity rather than reachability. */
+function RackStats() {
+ const racks = useRackStore((s) => s.racks)
+ const devices = useRackStore((s) => s.devices)
+ const cables = useRackStore((s) => s.cables)
+
+ const free = racks.reduce((sum, rack) => sum + freeUnits(rack, devices), 0)
+ const total = racks.reduce((sum, rack) => sum + rack.uHeight, 0)
+
+ return (
+ <div className="px-3 py-2 border-t border-border text-xs text-muted-foreground space-y-0.5">
+ <div className="flex justify-between">
+ <span>Racks</span>
+ <span className="text-foreground font-mono">{racks.length}</span>
+ </div>
+ <div className="flex justify-between">
+ <span>Mounted</span>
+ <span className="text-foreground font-mono">{devices.length}</span>
+ </div>
+ <div className="flex justify-between">
+ <span>Cables</span>
+ <span className="text-foreground font-mono">{cables.length}</span>
+ </div>
+ <div className="flex justify-between">
+ <span className="text-[#39d353]">Free</span>
+ <span className="font-mono text-[#39d353]">{free}U / {total}U</span>
+ </div>
+ </div>
+ )
+}
+
function VersionBadge() {
const current = __APP_VERSION__
const { latest, hasUpdate } = useLatestRelease(current)
diff --git a/frontend/src/components/panels/Toolbar.tsx b/frontend/src/components/panels/Toolbar.tsx
index 2960dcf..d02a01a 100644
--- a/frontend/src/components/panels/Toolbar.tsx
+++ b/frontend/src/components/panels/Toolbar.tsx
@@ -3,6 +3,9 @@ import { Save, LayoutDashboard, Download, Palette, Undo2, Redo2, HelpCircle, Tab
import { Button } from '@/components/ui/button'
import { Logo } from '@/components/ui/Logo'
import { useCanvasStore } from '@/stores/canvasStore'
+import { useDesignStore } from '@/stores/designStore'
+import { useRackStore } from '@/rack/store'
+import { RackToolbarActions } from './RackToolbarActions'
const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
@@ -21,7 +24,10 @@ interface ToolbarProps {
}
export function Toolbar({ onSave, onAutoLayout, onExport, onChangeStyle, onUndo, onRedo, onShortcuts, onExportMd, onExportYaml, onImportYaml, onViewOnly }: ToolbarProps) {
- const { hasUnsavedChanges, past, future } = useCanvasStore()
+ const { hasUnsavedChanges: canvasDirty, past, future } = useCanvasStore()
+ const isRack = useDesignStore((s) => s.activeDesignType) === 'rack'
+ const rackDirty = useRackStore((s) => s.hasUnsavedChanges)
+ const hasUnsavedChanges = isRack ? rackDirty : canvasDirty
const fileInputRef = useRef<HTMLInputElement>(null)
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
@@ -40,25 +46,33 @@ export function Toolbar({ onSave, onAutoLayout, onExport, onChangeStyle, onUndo,
<header className="flex items-center gap-2 px-4 py-2 border-b border-border bg-[#161b22] shrink-0">
<Logo size={28} showText={true} />
<div className="flex-1" />
- <Button
- size="sm" variant="ghost"
- className="gap-1.5 text-muted-foreground hover:text-foreground disabled:opacity-30 cursor-pointer hover:bg-[#21262d]"
- onClick={onUndo}
- disabled={past.length === 0}
- title="Undo (Ctrl+Z)"
- >
- <Undo2 size={14} />
- </Button>
- <Button
- size="sm" variant="ghost"
- className="gap-1.5 text-muted-foreground hover:text-foreground disabled:opacity-30 cursor-pointer hover:bg-[#21262d]"
- onClick={onRedo}
- disabled={future.length === 0}
- title="Redo (Ctrl+Y)"
- >
- <Redo2 size={14} />
- </Button>
+ {/* Undo/redo are canvas history; the rack canvas has none yet. */}
+ {!isRack && (
+ <>
+ <Button
+ size="sm" variant="ghost"
+ className="gap-1.5 text-muted-foreground hover:text-foreground disabled:opacity-30 cursor-pointer hover:bg-[#21262d]"
+ onClick={onUndo}
+ disabled={past.length === 0}
+ title="Undo (Ctrl+Z)"
+ >
+ <Undo2 size={14} />
+ </Button>
+ <Button
+ size="sm" variant="ghost"
+ className="gap-1.5 text-muted-foreground hover:text-foreground disabled:opacity-30 cursor-pointer hover:bg-[#21262d]"
+ onClick={onRedo}
+ disabled={future.length === 0}
+ title="Redo (Ctrl+Y)"
+ >
+ <Redo2 size={14} />
+ </Button>
+ </>
+ )}
<div className="w-px h-4 bg-border mx-1" />
+ {isRack && <RackToolbarActions />}
+ {!isRack && (
+ <>
<Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onAutoLayout}>
<LayoutDashboard size={14} /> Auto Layout
</Button>
@@ -78,15 +92,21 @@ export function Toolbar({ onSave, onAutoLayout, onExport, onChangeStyle, onUndo,
<Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onExportYaml} title="Export canvas as YAML">
<Download size={14} /> Export
</Button>
+ </>
+ )}
+ {/* PNG capture is DOM-based, so it works for both canvas kinds. */}
<Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onExport} title="Download canvas as PNG">
<FileDown size={14} /> PNG
</Button>
- <Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onExportMd} title="Copy inventory as Markdown table">
- <Table2 size={14} /> MD
- </Button>
+ {!isRack && (
+ <Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onExportMd} title="Copy inventory as Markdown table">
+ <Table2 size={14} /> MD
+ </Button>
+ )}
{/* Live view reads backend/localStorage canvas; pointless in standalone
- where the editor already shows the only (localStorage) copy. */}
- {!STANDALONE && (
+ where the editor already shows the only (localStorage) copy. Rack
+ canvases have no live view yet. */}
+ {!STANDALONE && !isRack && (
<Button size="sm" variant="ghost" className="gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer hover:bg-[#21262d]" onClick={onViewOnly} title="Open read-only live view of this canvas">
<Eye size={14} /> View
</Button>
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 90b05e1..ad53488 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -3,14 +3,11 @@ import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import LiveView from './components/LiveView.tsx'
-import RackLab from './rack/components/RackLab.tsx'
const isLiveView = window.location.pathname === '/view'
-// Front-only rack canvas prototype — no backend, no persistence.
-const isRackLab = window.location.pathname === '/racklab'
createRoot(document.getElementById('root')!).render(
<StrictMode>
- {isLiveView ? <LiveView /> : isRackLab ? <RackLab /> : <App />}
+ {isLiveView ? <LiveView /> : <App />}
</StrictMode>,
)
diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.md
index 343b0ba..5dd88b3 100644
--- a/frontend/src/rack/README.md
+++ b/frontend/src/rack/README.md
@@ -1,11 +1,11 @@
-# Rack canvas — UX prototype
+# Rack canvas
-Front-only. No API, no persistence, no backend enum changes. Open **`/racklab`**
-(`npm run dev` → http://localhost:5173/racklab).
+A rack canvas is a design of `design_type: 'rack'` — the physical counterpart to
+the logical network canvas. It lives in the same shell: same header, same left
+rail, same right panel, same design switcher. `App` swaps the renderer when the
+active design is a rack.
-Isolated on purpose: `main.tsx` routes `/racklab` the same way it already routes
-`/view`, so nothing here touches the logical canvas. Once the UX is settled, the
-model in `types.ts` is what gets lifted into `@/types` + a `design_type: 'rack'`.
+Create one from **New Canvas → Kind → Rack**.
## Model
@@ -14,27 +14,54 @@ model in `types.ts` is what gets lifted into `@/types` + a `design_type: 'rack'`
| Vertical | `uStart` (1-based, **always counted from the bottom rail**) + `uHeight`. `numbering` only changes the printed labels. |
| Horizontal | 12-column grid (`RACK_COLUMNS`). Full = 12, half = 6, third = 4, quarter = 3 — so 2 or 3 machines share one U. |
| Collision | `canPlace` / `findSlot` in `layout.ts`. A drop snaps to the nearest free slot; an impossible drop shows a red preview. |
-| Inventory | A mount references an inventory id. **Unmounting never deletes the inventory entry** — same rule as the network canvas. Accessories (blank, shelf, cable manager) have `nodeId: null`. |
-| Faceplates | Declarative templates in `faceplates.ts`, drawn as SVG in unit coordinates so a plate scales with U height and rack width. Applying a template seeds ports; the user edits them afterwards. |
-| Ports | RJ45 and SFP/SFP+ only, drawn as real jack artwork at a fixed pixel size so plates of different U heights line up. Manual list per device; position is unit coordinates on the plate. Power outlets are artwork, never a cable endpoint. |
+| Inventory | A mount references a **Device Inventory** entry (`pending_devices`) via `deviceId`. Those rows survive approval *and* node deletion, so unracking never removes the device. Accessories (blank, shelf, cable manager) have `deviceId: null`. |
+| Canvas node link | `nodeId` is a second, optional link to a logical-canvas node, resolved server-side by IEEE then IP. It supplies live status and lets the network-link import match endpoints. Never required. |
+| 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. |
+| 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. |
| Port visibility | Patch-facing gear (switches, patch panels) shows its ports permanently. Everything else reveals them on hover, on selection, or when cables are on — a cable never ends on an invisible port. |
| Plate zones | Each template reserves three non-overlapping bands: status LED (fixed left), `labelBox` (name, clipped), then artwork and ports. A test asserts no port lands on the name band. |
| Cables | Port-to-port, a relation of their own — not React Flow edges. One cable per port. Drawn in a `ViewportPortal` so they pan/zoom with the canvas and can cross racks. |
-| Cable visibility | Hidden by default; shown on hover/selection, or all-on via patch mode / the toolbar. Plates fade to 40 % when cables are on, which is the "transparency" ask. Copper vs fibre follows the port the patch starts from. |
-| Network import | `importCablesFromNetwork()` — one shot, at creation time only, guarded by `networkImportDone`. Fed by `networkEdgeHints()` (fake here; would read the network design's edges for real). |
+| 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. |
+| 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
+
+Explicit save, like the logical canvas — plus the same opt-in autosave, which
+debounces on the store's `editSeq`.
+
+| Where | What |
+|---|---|
+| `racks`, `rack_devices`, `rack_cables` | One row set per design. `rack_devices.device_id → pending_devices` and `node_id → nodes` are both `ON DELETE SET NULL`, and `label` is denormalized, so a rack keeps rendering after an inventory purge. |
+| `canvas_state.viewport` | Pan/zoom, shared with the logical canvas row for that design. |
+| `GET /api/v1/racks?design_id=` | Full state. |
+| `POST /api/v1/racks/save` | Full state: upsert what is sent, prune the rest. Rejects a device pointing at a rack outside the payload, or a cable pointing at a device outside it. |
+| `GET /api/v1/racks/inventory?design_id=` | Rackable inventory entries, each flagged `racked` and resolved to a canvas node when one matches. |
+| `POST /api/v1/scan/pending` | Manual inventory entry (`discovery_source: "manual"`), for hardware no scan can find. |
+| Standalone | `homelable_rack:<designId>` in localStorage, inventory included (no `pending_devices` table to read). |
+
+`@/utils/rackSerializer` maps the snake_case wire shapes to the camelCase domain
+types in `@/types/rack`, narrowing every enum on the way in.
## Interactions
-- Drag from the left tray onto a rack → snaps to a free U.
+- 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.
- Click a device → inspector on the right (label, faceplate, U/height/column/width, status, colour, port list).
- Click empty rack chrome → rack settings (name, location, U height, 19"/10", numbering direction, frame/rail/interior colours, U numbers, enclosed).
- **Patch mode**: click port A then port B to cable them; click a cable to remove it. Rack dragging is disabled while in patch mode.
+- **Import links**: one shot per canvas, guarded by `networkImportDone`. Reads the physical edges (ethernet/fibre/vlan/cluster) of every non-rack design and matches them on `nodeId`.
+- **New device**: adds a Device Inventory entry from the tray, for gear no scan will ever discover.
+
+## Panel behaviour in rack mode
+
+- **Header**: undo/redo, auto layout, YAML import/export, MD and live View are hidden. Add Rack, Patch, cable visibility, cable type filter 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 inventory tray plus Add Rack. The footer counts racks, mounts, cables and free U instead of online/offline nodes.
+- **Right rail**: `RackInspector` replaces `DetailPanel`, and is always visible rather than appearing on selection.
-## Known gaps (deliberate, for the UX pass)
+## Known gaps
- Front view only — no rear, no half-depth pairing.
- No 0U side-mounted PDU.
- Power draw / outlet budgeting out of scope (v1 decision).
-- No export yet (PNG/SVG comes with integration).
-- Demo state resets on reload; `Reset demo` restores it mid-session.
+- No undo/redo on the rack canvas.
+- No read-only live view for rack designs.
diff --git a/frontend/src/rack/__tests__/faceplates.test.ts b/frontend/src/rack/__tests__/faceplates.test.ts
index 972876f..73a6127 100644
--- a/frontend/src/rack/__tests__/faceplates.test.ts
+++ b/frontend/src/rack/__tests__/faceplates.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest'
import { FACEPLATES, bank, faceplateGroups, getFaceplate } from '../faceplates'
-import { RACK_COLUMNS, type PortType } from '../types'
+import { RACK_COLUMNS, type PortType } from '@/types'
const ALLOWED_PORT_TYPES: PortType[] = ['rj45', 'sfp', 'sfp+']
diff --git a/frontend/src/rack/__tests__/layout.test.ts b/frontend/src/rack/__tests__/layout.test.ts
index 44b1979..11b22e9 100644
--- a/frontend/src/rack/__tests__/layout.test.ts
+++ b/frontend/src/rack/__tests__/layout.test.ts
@@ -18,7 +18,7 @@ import {
yToU,
} from '../layout'
import { DEFAULT_RACK_STYLE } from '../rackDefaults'
-import { RACK_COLUMNS, type Port, type Rack, type RackDevice } from '../types'
+import { RACK_COLUMNS, type Port, type Rack, type RackDevice } from '@/types'
function makeRack(patch: Partial<Rack> = {}): Rack {
return {
diff --git a/frontend/src/rack/__tests__/networkLinks.test.ts b/frontend/src/rack/__tests__/networkLinks.test.ts
new file mode 100644
index 0000000..1724835
--- /dev/null
+++ b/frontend/src/rack/__tests__/networkLinks.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { loadNetworkLinks } from '../networkLinks'
+import type { Design } from '@/types'
+
+const canvasLoad = vi.fn()
+
+vi.mock('@/api/client', () => ({
+ canvasApi: { load: (...args: unknown[]) => canvasLoad(...args) },
+}))
+
+function design(id: string, design_type: Design['design_type'] = 'network'): Design {
+ return { id, name: id, design_type, icon: null, created_at: '', updated_at: '' }
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('loadNetworkLinks', () => {
+ it('collects physical edges from a logical canvas', async () => {
+ canvasLoad.mockResolvedValue({
+ data: { edges: [{ source: 'a', target: 'b', type: 'ethernet', label: 'uplink' }] },
+ })
+ const hints = await loadNetworkLinks([design('d1')])
+ expect(hints).toEqual([{ from: 'a', to: 'b', type: 'ethernet', label: 'uplink' }])
+ })
+
+ it('maps a fibre edge onto a fiber patch', async () => {
+ canvasLoad.mockResolvedValue({ data: { edges: [{ source: 'a', target: 'b', type: 'fibre' }] } })
+ const [hint] = await loadNetworkLinks([design('d1')])
+ expect(hint.type).toBe('fiber')
+ })
+
+ it('skips links that are not physical', async () => {
+ canvasLoad.mockResolvedValue({
+ data: {
+ edges: [
+ { source: 'a', target: 'b', type: 'wifi' },
+ { source: 'c', target: 'd', type: 'virtual' },
+ { source: 'e', target: 'f', type: 'ethernet' },
+ ],
+ },
+ })
+ const hints = await loadNetworkLinks([design('d1')])
+ expect(hints.map((h) => h.from)).toEqual(['e'])
+ })
+
+ it('never reads a rack design — it has no edges to import', async () => {
+ canvasLoad.mockResolvedValue({ data: { edges: [] } })
+ await loadNetworkLinks([design('d1', 'rack')])
+ expect(canvasLoad).not.toHaveBeenCalled()
+ })
+
+ it('dedupes the same pair drawn on two canvases, either way round', async () => {
+ canvasLoad
+ .mockResolvedValueOnce({ data: { edges: [{ source: 'a', target: 'b', type: 'ethernet' }] } })
+ .mockResolvedValueOnce({ data: { edges: [{ source: 'b', target: 'a', type: 'ethernet' }] } })
+ const hints = await loadNetworkLinks([design('d1'), design('d2')])
+ expect(hints).toHaveLength(1)
+ })
+
+ it('skips a design that fails to load instead of failing the import', async () => {
+ canvasLoad
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce({ data: { edges: [{ source: 'a', target: 'b', type: 'ethernet' }] } })
+ const hints = await loadNetworkLinks([design('d1'), design('d2')])
+ expect(hints).toHaveLength(1)
+ })
+})
diff --git a/frontend/src/rack/__tests__/persistence.test.ts b/frontend/src/rack/__tests__/persistence.test.ts
new file mode 100644
index 0000000..b32fb5a
--- /dev/null
+++ b/frontend/src/rack/__tests__/persistence.test.ts
@@ -0,0 +1,208 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { useRackStore } from '../store'
+
+const load = vi.fn()
+const inventory = vi.fn()
+const save = vi.fn()
+const createPending = vi.fn()
+
+vi.mock('@/api/client', () => ({
+ racksApi: {
+ load: (...args: unknown[]) => load(...args),
+ inventory: (...args: unknown[]) => inventory(...args),
+ save: (...args: unknown[]) => save(...args),
+ },
+ scanApi: {
+ createPending: (...args: unknown[]) => createPending(...args),
+ },
+}))
+
+const store = () => useRackStore.getState()
+
+const apiState = {
+ racks: [
+ {
+ id: 'r1',
+ design_id: 'd1',
+ name: 'Main',
+ u_height: 12,
+ width_standard: '19',
+ numbering: 'bottom-up',
+ location: null,
+ style: {},
+ pos_x: 0,
+ pos_y: 0,
+ },
+ ],
+ devices: [
+ {
+ id: 'dev1',
+ design_id: 'd1',
+ rack_id: 'r1',
+ device_id: 'inv1',
+ node_id: null,
+ label: 'sw-24',
+ u_start: 4,
+ u_height: 1,
+ col_start: 0,
+ col_span: 12,
+ faceplate_id: 'switch-24',
+ color: null,
+ status: 'online',
+ ports: [{ id: 'p1', label: '1', type: 'rj45', x: 0.3, y: 0.5 }],
+ },
+ ],
+ cables: [],
+ viewport: { x: 5, y: 6, zoom: 0.8 },
+}
+
+const apiInventory = {
+ items: [
+ {
+ id: 'inv1',
+ label: 'sw-24',
+ suggested_type: 'switch',
+ ip: '192.168.1.2',
+ status: 'approved',
+ discovery_source: 'arp',
+ node_id: null,
+ node_status: null,
+ racked: false,
+ },
+ {
+ id: 'inv2',
+ label: 'nas',
+ suggested_type: 'nas',
+ ip: '192.168.1.9',
+ status: 'approved',
+ discovery_source: 'arp',
+ node_id: 'node2',
+ node_status: 'online',
+ racked: false,
+ },
+ ],
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ useRackStore.getState().reset()
+ load.mockResolvedValue({ data: apiState })
+ inventory.mockResolvedValue({ data: apiInventory })
+ save.mockResolvedValue({ data: { saved: true } })
+})
+
+describe('loadDesign', () => {
+ it('pulls state and inventory for the design', async () => {
+ await store().loadDesign('d1')
+ expect(load).toHaveBeenCalledWith('d1')
+ expect(inventory).toHaveBeenCalledWith('d1')
+ expect(store().designId).toBe('d1')
+ expect(store().racks.map((r) => r.name)).toEqual(['Main'])
+ expect(store().devices[0].label).toBe('sw-24')
+ expect(store().viewport).toEqual({ x: 5, y: 6, zoom: 0.8 })
+ })
+
+ it('lands clean — a fresh load is not an unsaved change', async () => {
+ await store().loadDesign('d1')
+ expect(store().hasUnsavedChanges).toBe(false)
+ expect(store().loading).toBe(false)
+ })
+
+ it('recomputes racked flags from the loaded mounts, not the server hint', async () => {
+ await store().loadDesign('d1')
+ expect(store().inventory.find((i) => i.id === 'inv1')!.racked).toBe(true)
+ expect(store().inventory.find((i) => i.id === 'inv2')!.racked).toBe(false)
+ })
+
+ it('surfaces a failed load instead of showing an empty canvas as success', async () => {
+ load.mockRejectedValue(new Error('boom'))
+ await store().loadDesign('d1')
+ expect(store().loadError).toBe(true)
+ expect(store().loading).toBe(false)
+ })
+
+ it('clears the previous design before loading the next one', async () => {
+ await store().loadDesign('d1')
+ load.mockResolvedValue({ data: { ...apiState, racks: [], devices: [] } })
+ inventory.mockResolvedValue({ data: { items: [] } })
+ await store().loadDesign('d2')
+ expect(store().racks).toEqual([])
+ expect(store().devices).toEqual([])
+ })
+})
+
+describe('save', () => {
+ it('refuses to save before a design is loaded', async () => {
+ expect(await store().save()).toBe(false)
+ expect(save).not.toHaveBeenCalled()
+ })
+
+ it('posts the full state and clears the dirty flag', async () => {
+ await store().loadDesign('d1')
+ store().addRack({ id: 'r2', name: 'Second' })
+ expect(store().hasUnsavedChanges).toBe(true)
+
+ expect(await store().save()).toBe(true)
+ const payload = save.mock.calls[0][0]
+ expect(payload.design_id).toBe('d1')
+ expect(payload.racks.map((r: { id: string }) => r.id)).toEqual(['r1', 'r2'])
+ expect(payload.devices[0].u_start).toBe(4)
+ expect(store().hasUnsavedChanges).toBe(false)
+ })
+
+ it('keeps the canvas dirty when the save fails', async () => {
+ await store().loadDesign('d1')
+ store().addRack()
+ save.mockRejectedValue(new Error('nope'))
+ expect(await store().save()).toBe(false)
+ expect(store().hasUnsavedChanges).toBe(true)
+ })
+})
+
+describe('createInventoryDevice', () => {
+ it('creates the inventory entry server-side and adds it to the tray', async () => {
+ await store().loadDesign('d1')
+ createPending.mockResolvedValue({ data: { id: 'inv-new', hostname: 'patch panel' } })
+
+ const created = await store().createInventoryDevice({ label: 'patch panel' })
+ expect(createPending).toHaveBeenCalledWith({
+ hostname: 'patch panel',
+ ip: null,
+ mac: null,
+ suggested_type: null,
+ })
+ expect(created!.id).toBe('inv-new')
+ expect(store().inventory.some((i) => i.id === 'inv-new')).toBe(true)
+ expect(store().hasUnsavedChanges).toBe(true)
+ })
+
+ it('adds nothing when the backend refuses', async () => {
+ await store().loadDesign('d1')
+ const before = store().inventory.length
+ createPending.mockRejectedValue(new Error('nope'))
+
+ expect(await store().createInventoryDevice({ label: 'ghost' })).toBeNull()
+ expect(store().inventory).toHaveLength(before)
+ })
+})
+
+describe('refreshInventory', () => {
+ it('re-reads the tray without touching the mounts', async () => {
+ await store().loadDesign('d1')
+ inventory.mockResolvedValue({
+ data: { items: [...apiInventory.items, { ...apiInventory.items[1], id: 'inv3', label: 'new box' }] },
+ })
+
+ await store().refreshInventory()
+ expect(store().inventory.some((i) => i.id === 'inv3')).toBe(true)
+ expect(store().devices).toHaveLength(1)
+ })
+
+ it('keeps the existing tray when the refresh fails', async () => {
+ await store().loadDesign('d1')
+ const before = store().inventory.length
+ inventory.mockRejectedValue(new Error('offline'))
+ await store().refreshInventory()
+ expect(store().inventory).toHaveLength(before)
+ })
+})
diff --git a/frontend/src/rack/__tests__/rackTheme.test.ts b/frontend/src/rack/__tests__/rackTheme.test.ts
new file mode 100644
index 0000000..f312fe6
--- /dev/null
+++ b/frontend/src/rack/__tests__/rackTheme.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect } from 'vitest'
+import { rackPalette } from '../rackTheme'
+import { THEMES, THEME_ORDER } from '@/utils/themes'
+
+describe('rackPalette', () => {
+ it('takes the canvas and status colours from the active theme', () => {
+ const palette = rackPalette('matrix')
+ const theme = THEMES.matrix.colors
+ expect(palette.canvas).toBe(theme.canvasBackground)
+ expect(palette.dot).toBe(theme.canvasDotColor)
+ expect(palette.status.online).toBe(theme.statusColors.online)
+ expect(palette.status.offline).toBe(theme.statusColors.offline)
+ })
+
+ it('resolves a full palette for every theme, so none renders a blank rack', () => {
+ for (const id of THEME_ORDER) {
+ const palette = rackPalette(id)
+ for (const value of [palette.canvas, palette.plate, palette.text, palette.muted, palette.accent]) {
+ expect(value).toBeTruthy()
+ }
+ expect(palette.defaultRackStyle.showNumbers).toBe(true)
+ }
+ })
+
+ it('keeps a port recess darker than the plate on a light theme', () => {
+ // A jack has to read as a hole, not a highlight.
+ const light = rackPalette('light')
+ expect(light.portRecess).not.toBe(light.plate)
+ })
+
+ it('seeds a new rack with chrome drawn from the theme', () => {
+ const palette = rackPalette('neon')
+ expect(palette.defaultRackStyle.interior).toBe(THEMES.neon.colors.canvasBackground)
+ expect(palette.defaultRackStyle.enclosed).toBe(false)
+ })
+
+ it('falls back to the default theme for an unknown id', () => {
+ // Guards against a stored theme id that a later release removed.
+ const palette = rackPalette('nope' as never)
+ expect(palette.canvas).toBe(THEMES.default.colors.canvasBackground)
+ })
+})
diff --git a/frontend/src/rack/__tests__/store.test.ts b/frontend/src/rack/__tests__/store.test.ts
index 45b9cf6..ce399d3 100644
--- a/frontend/src/rack/__tests__/store.test.ts
+++ b/frontend/src/rack/__tests__/store.test.ts
@@ -1,12 +1,13 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useRackStore } from '../store'
import { getFaceplate } from '../faceplates'
-import { RACK_COLUMNS } from '../types'
+import { RACK_COLUMNS } from '@/types'
+import { demoNetworkLinks } from '../demoData'
const store = () => useRackStore.getState()
beforeEach(() => {
- useRackStore.getState().reset()
+ useRackStore.getState().loadDemo()
})
describe('racks', () => {
@@ -43,7 +44,7 @@ describe('mounting', () => {
expect(id).not.toBeNull()
const device = store().devices.find((d) => d.id === id)!
expect(device.faceplateId).toBe('switch-8')
- expect(device.nodeId).toBe('inv-sw8')
+ expect(device.deviceId).toBe('inv-sw8')
expect(device.ports.length).toBe(getFaceplate('switch-8').ports.length)
})
@@ -67,7 +68,24 @@ describe('mounting', () => {
it('mounts an accessory with no inventory link', () => {
const id = store().mountAccessory('shelf-1u', 'rack-main', { uStart: 6 })!
- expect(store().devices.find((d) => d.id === id)!.nodeId).toBeNull()
+ expect(store().devices.find((d) => d.id === id)!.deviceId).toBeNull()
+ })
+
+ it('flags the inventory entry as racked once it is mounted', () => {
+ expect(store().inventory.find((i) => i.id === 'inv-sw8')!.racked).toBe(false)
+ store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 5 })
+ expect(store().inventory.find((i) => i.id === 'inv-sw8')!.racked).toBe(true)
+ })
+
+ 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')
+ expect(store().inventory.find((i) => i.id === 'inv-pve1')!.racked).toBe(false)
+ })
+
+ it('carries the canvas node link onto the mount', () => {
+ const id = store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 5 })!
+ expect(store().devices.find((d) => d.id === id)!.nodeId).toBe('node-inv-sw8')
})
it('keeps the inventory entry when a device is unmounted', () => {
@@ -243,21 +261,60 @@ describe('cables', () => {
})
it('imports links from the network canvas once', () => {
- // Mount the two inventory items the hints reference.
+ // Mount the inventory item the hints reference; the other end is racked already.
store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 4 })
- const first = store().importCablesFromNetwork()
+ const first = store().importCablesFromNetwork(demoNetworkLinks())
expect(first).toBeGreaterThan(0)
- expect(store().importCablesFromNetwork()).toBe(0)
+ expect(store().importCablesFromNetwork(demoNetworkLinks())).toBe(0)
})
it('skips hints whose devices are not racked', () => {
// inv-jbod is never mounted in the demo, so its hint cannot resolve.
- store().importCablesFromNetwork()
+ store().importCablesFromNetwork(demoNetworkLinks())
expect(
store().cables.some((c) => {
const from = store().devices.find((d) => d.id === c.from.deviceId)
- return from?.nodeId === 'inv-jbod'
+ return from?.nodeId === 'node-inv-jbod'
}),
).toBe(false)
})
})
+
+describe('dirty tracking', () => {
+ it('starts clean after loading the sample and marks edits', () => {
+ // loadDemo seeds unsaved sample data on purpose; a real load starts clean.
+ store().markSaved()
+ expect(store().hasUnsavedChanges).toBe(false)
+ store().addRack()
+ expect(store().hasUnsavedChanges).toBe(true)
+ })
+
+ it('bumps the edit counter on every mutation', () => {
+ const before = store().editSeq
+ store().updateRack('rack-main', { name: 'renamed' })
+ expect(store().editSeq).toBeGreaterThan(before)
+ })
+
+ it('does not dirty the canvas for pan and zoom', () => {
+ store().markSaved()
+ store().setViewport({ x: 12, y: 34, zoom: 2 })
+ expect(store().hasUnsavedChanges).toBe(false)
+ expect(store().viewport).toEqual({ x: 12, y: 34, zoom: 2 })
+ })
+
+ it('does not dirty the canvas for selection or cable visibility', () => {
+ store().markSaved()
+ store().selectDevice('dev-sw24')
+ store().setCableVisibility('always')
+ store().toggleCableMode()
+ expect(store().hasUnsavedChanges).toBe(false)
+ })
+
+ it('clears everything on reset', () => {
+ store().reset()
+ expect(store().racks).toEqual([])
+ expect(store().devices).toEqual([])
+ expect(store().inventory).toEqual([])
+ expect(store().hasUnsavedChanges).toBe(false)
+ })
+})
diff --git a/frontend/src/rack/components/CableLayer.tsx b/frontend/src/rack/components/CableLayer.tsx
index e2b5e38..1d61483 100644
--- a/frontend/src/rack/components/CableLayer.tsx
+++ b/frontend/src/rack/components/CableLayer.tsx
@@ -8,7 +8,7 @@
import { ViewportPortal } from '@xyflow/react'
import { portPosition } from '../layout'
import { useRackStore } from '../store'
-import type { Cable, Port, Rack, RackDevice } from '../types'
+import type { Cable, Port, Rack, RackDevice } from '@/types'
interface Resolved {
cable: Cable
diff --git a/frontend/src/rack/components/Faceplate.tsx b/frontend/src/rack/components/Faceplate.tsx
index 62d80ab..3729358 100644
--- a/frontend/src/rack/components/Faceplate.tsx
+++ b/frontend/src/rack/components/Faceplate.tsx
@@ -7,17 +7,8 @@
*/
import { memo, useId } from 'react'
import { getFaceplate } from '../faceplates'
-import type { DeviceStatus, FaceplateElement, Port, PortType } from '../types'
-
-const STATUS_COLOR: Record<DeviceStatus, string> = {
- online: '#39d353',
- offline: '#f85149',
- unknown: '#8b949e',
-}
-
-/** Unpatched port artwork — a dark recess with a metal bezel. */
-const PORT_BEZEL = '#5b6673'
-const PORT_RECESS = '#0b0e13'
+import { useRackPalette } from '../rackTheme'
+import type { DeviceStatus, FaceplateElement, Port, PortType } from '@/types'
const LED_X = 9
const LED_R = 3
@@ -191,9 +182,10 @@ export const Faceplate = memo(function Faceplate({
onPortClick,
}: Props) {
const template = getFaceplate(faceplateId)
+ const palette = useRackPalette()
const clipId = useId()
const panel = template.elements.find((e) => e.kind === 'panel')
- const fill = colorOverride ?? (panel?.kind === 'panel' ? panel.fill : '#2b323c')
+ const fill = colorOverride ?? (panel?.kind === 'panel' ? panel.fill : palette.plate)
const showPorts = template.alwaysShowPorts || revealed || interactivePorts
@@ -222,7 +214,7 @@ export const Faceplate = memo(function Faceplate({
height={height - 1}
rx={2}
fill={fill}
- stroke={selected ? '#00d4ff' : '#0d1117'}
+ stroke={selected ? palette.accent : palette.plateOutline}
strokeWidth={selected ? 1.5 : 1}
/>
@@ -233,7 +225,7 @@ export const Faceplate = memo(function Faceplate({
{template.elements.map((el, i) => drawElement(el, i, width, height))}
{template.statusLed && (
- <circle cx={LED_X} cy={height / 2} r={LED_R} fill={STATUS_COLOR[status]} />
+ <circle cx={LED_X} cy={height / 2} r={LED_R} fill={palette.status[status]} />
)}
{showLabel && (
@@ -242,7 +234,7 @@ export const Faceplate = memo(function Faceplate({
y={height / 2}
clipPath={`url(#${clipId})`}
fontSize={fontSize}
- fill="#c9d1d9"
+ fill={palette.text}
dominantBaseline="central"
textAnchor="start"
fontFamily="Inter, system-ui, sans-serif"
@@ -258,7 +250,7 @@ export const Faceplate = memo(function Faceplate({
const patchColor = patchedPorts?.get(port.id)
const isDraft = draftPortId === port.id
const { w, h } = portShapeSize(template.portSize ?? 'md', height, port.type)
- const stroke = isDraft ? '#00d4ff' : patchColor ?? PORT_BEZEL
+ const stroke = isDraft ? palette.accent : patchColor ?? palette.portBezel
return (
<g
@@ -280,7 +272,7 @@ export const Faceplate = memo(function Faceplate({
{port.type === 'rj45' ? (
<path
d={rj45Path(w, h)}
- fill={PORT_RECESS}
+ fill={palette.portRecess}
stroke={stroke}
strokeWidth={isDraft ? 1.4 : 0.9}
strokeLinejoin="round"
@@ -293,7 +285,7 @@ export const Faceplate = memo(function Faceplate({
width={w}
height={h}
rx={1}
- fill={PORT_RECESS}
+ fill={palette.portRecess}
stroke={stroke}
strokeWidth={isDraft ? 1.4 : 0.9}
/>
diff --git a/frontend/src/rack/components/InventoryTray.tsx b/frontend/src/rack/components/InventoryTray.tsx
index c0821d2..f93791f 100644
--- a/frontend/src/rack/components/InventoryTray.tsx
+++ b/frontend/src/rack/components/InventoryTray.tsx
@@ -1,7 +1,16 @@
-/** Left rail: unracked inventory + rack accessories, both drag sources. */
+/**
+ * Sidebar section for rack designs: Device Inventory entries and rack
+ * accessories, both drag sources for the canvas.
+ *
+ * The inventory is the app's Device Inventory — unmounting gear from a rack
+ * never removes it here.
+ */
+import { useState } from 'react'
+import { PlusCircle, RefreshCw } from 'lucide-react'
+import { toast } from 'sonner'
import { FACEPLATES, getFaceplate } from '../faceplates'
import { useRackStore } from '../store'
-import type { InventoryDevice } from '../types'
+import type { InventoryDevice } from '@/types'
import { endDrag, startDrag } from './dragPayload'
const STATUS_DOT: Record<InventoryDevice['status'], string> = {
@@ -10,24 +19,59 @@ const STATUS_DOT: Record<InventoryDevice['status'], string> = {
unknown: '#8b949e',
}
+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
+
export function InventoryTray() {
const inventory = useRackStore((s) => s.inventory)
- const devices = useRackStore((s) => s.devices)
+ const createInventoryDevice = useRackStore((s) => s.createInventoryDevice)
+ const refreshInventory = useRackStore((s) => s.refreshInventory)
+ const [adding, setAdding] = useState(false)
+ const [draftName, setDraftName] = useState('')
+ const [busy, setBusy] = useState(false)
- const mountedNodeIds = new Set(devices.map((d) => d.nodeId).filter(Boolean))
- const unracked = inventory.filter((i) => !mountedNodeIds.has(i.id))
- const racked = inventory.filter((i) => mountedNodeIds.has(i.id))
+ const unracked = inventory.filter((i) => !i.racked)
+ const racked = inventory.filter((i) => i.racked)
const accessories = FACEPLATES.filter((f) => f.kind === 'accessory')
+ async function handleCreate(e: React.FormEvent) {
+ e.preventDefault()
+ const label = draftName.trim()
+ if (!label) return
+ setBusy(true)
+ const created = await createInventoryDevice({ label })
+ setBusy(false)
+ if (!created) {
+ toast.error('Could not add the device')
+ return
+ }
+ setDraftName('')
+ setAdding(false)
+ toast.success(`${label} added to the inventory`)
+ }
+
return (
- <aside className="w-64 shrink-0 overflow-y-auto border-r border-[#21262d] bg-[#0d1117] p-3 text-sm text-[#c9d1d9]">
- <h2 className="mb-1 text-xs font-semibold uppercase tracking-wide text-[#6e7681]">
- Inventory · unracked ({unracked.length})
- </h2>
- <p className="mb-2 text-[11px] leading-snug text-[#6e7681]">
- Drag onto a rack. Removing gear from a rack never deletes it here.
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 pb-2 text-sm text-foreground">
+ <div className="flex items-center justify-between pt-2">
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Unracked ({unracked.length})
+ </h2>
+ {!STANDALONE && (
+ <button
+ type="button"
+ title="Refresh from the Device Inventory"
+ aria-label="Refresh inventory"
+ onClick={() => void refreshInventory()}
+ className="p-1 text-muted-foreground hover:text-foreground cursor-pointer"
+ >
+ <RefreshCw size={12} />
+ </button>
+ )}
+ </div>
+ <p className="mb-2 text-[11px] leading-snug text-muted-foreground">
+ Drag onto a rack. Unmounting never deletes the device from the inventory.
</p>
- <ul className="mb-4 space-y-1">
+
+ <ul className="mb-3 space-y-1">
{unracked.map((item) => (
<li
key={item.id}
@@ -40,28 +84,65 @@ export function InventoryTray() {
})
}
onDragEnd={endDrag}
- className="flex cursor-grab items-center gap-2 rounded border border-[#21262d] bg-[#161b22] px-2 py-1.5 hover:border-[#00d4ff]"
- title={`${item.type}${item.ip ? ` · ${item.ip}` : ''} · ${getFaceplate(item.suggestedFaceplateId).label}`}
+ className="flex cursor-grab items-center gap-2 rounded border border-border bg-[#161b22] px-2 py-1.5 hover:border-[#00d4ff]"
+ title={`${item.type ?? 'device'}${item.ip ? ` · ${item.ip}` : ''} · ${getFaceplate(item.suggestedFaceplateId).label}`}
>
<span
className="size-2 shrink-0 rounded-full"
style={{ background: STATUS_DOT[item.status] }}
/>
- <span className="truncate">{item.label}</span>
- <span className="ml-auto shrink-0 font-mono text-[10px] text-[#6e7681]">
+ <span className="truncate text-xs">{item.label}</span>
+ <span className="ml-auto shrink-0 font-mono text-[10px] text-muted-foreground">
{getFaceplate(item.suggestedFaceplateId).uHeight}U
</span>
</li>
))}
{unracked.length === 0 && (
- <li className="px-2 py-1 text-[11px] text-[#6e7681]">Everything is racked.</li>
+ <li className="px-2 py-1 text-[11px] text-muted-foreground">Everything is racked.</li>
)}
</ul>
- <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[#6e7681]">
+ {adding ? (
+ <form onSubmit={handleCreate} className="mb-3 space-y-1">
+ <input
+ autoFocus
+ value={draftName}
+ onChange={(e) => setDraftName(e.target.value)}
+ placeholder="Device name"
+ aria-label="Device name"
+ className="w-full rounded border border-border bg-[#0d1117] px-2 py-1 text-xs text-foreground outline-none focus:border-[#00d4ff]"
+ />
+ <div className="flex gap-1">
+ <button
+ type="submit"
+ disabled={busy || !draftName.trim()}
+ className="flex-1 rounded border border-[#00d4ff] px-2 py-1 text-[11px] text-[#00d4ff] hover:bg-[#00d4ff]/10 disabled:opacity-40 cursor-pointer"
+ >
+ Add
+ </button>
+ <button
+ type="button"
+ onClick={() => { setAdding(false); setDraftName('') }}
+ className="rounded border border-border px-2 py-1 text-[11px] text-muted-foreground hover:text-foreground cursor-pointer"
+ >
+ Cancel
+ </button>
+ </div>
+ </form>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setAdding(true)}
+ className="mb-3 flex items-center gap-1.5 rounded px-2 py-1 text-[11px] text-[#00d4ff] hover:bg-[#00d4ff]/10 cursor-pointer"
+ >
+ <PlusCircle size={12} /> New device
+ </button>
+ )}
+
+ <h2 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Accessories
</h2>
- <ul className="mb-4 space-y-1">
+ <ul className="mb-3 space-y-1">
{accessories.map((plate) => (
<li
key={plate.id}
@@ -74,27 +155,34 @@ export function InventoryTray() {
})
}
onDragEnd={endDrag}
- className="cursor-grab rounded border border-[#21262d] bg-[#161b22] px-2 py-1.5 hover:border-[#00d4ff]"
+ className="cursor-grab rounded border border-border bg-[#161b22] px-2 py-1.5 text-xs hover:border-[#00d4ff]"
>
{plate.label}
</li>
))}
</ul>
- <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[#6e7681]">
- Racked ({racked.length})
- </h2>
- <ul className="space-y-1">
- {racked.map((item) => (
- <li key={item.id} className="flex items-center gap-2 px-2 py-1 text-[#6e7681]">
- <span
- className="size-2 shrink-0 rounded-full"
- style={{ background: STATUS_DOT[item.status] }}
- />
- <span className="truncate">{item.label}</span>
- </li>
- ))}
- </ul>
- </aside>
+ {racked.length > 0 && (
+ <>
+ <h2 className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Racked ({racked.length})
+ </h2>
+ <ul className="space-y-1">
+ {racked.map((item) => (
+ <li
+ key={item.id}
+ className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground"
+ >
+ <span
+ className="size-2 shrink-0 rounded-full"
+ style={{ background: STATUS_DOT[item.status] }}
+ />
+ <span className="truncate">{item.label}</span>
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ </div>
)
}
diff --git a/frontend/src/rack/components/RackCanvas.tsx b/frontend/src/rack/components/RackCanvas.tsx
new file mode 100644
index 0000000..4a29d6a
--- /dev/null
+++ b/frontend/src/rack/components/RackCanvas.tsx
@@ -0,0 +1,127 @@
+/**
+ * Rack canvas: one React Flow node per rack, plus the cabling overlay.
+ *
+ * Rendered by `App` in place of `CanvasContainer` when the active design is of
+ * type `rack`. React Flow context comes from the App-level provider.
+ */
+import { useCallback, useEffect, useMemo, useRef } from 'react'
+import {
+ Background,
+ BackgroundVariant,
+ Controls,
+ ReactFlow,
+ useReactFlow,
+ type Node,
+ type NodeChange,
+ type Viewport,
+} from '@xyflow/react'
+import { Plus } from 'lucide-react'
+import { rackHeight, rackWidth } from '../layout'
+import { useRackStore } from '../store'
+import { useRackPalette } from '../rackTheme'
+import { CableLayer } from './CableLayer'
+import { RackFlowNode } from './RackFlowNode'
+
+const nodeTypes = { rack: RackFlowNode }
+
+export function RackCanvas() {
+ const racks = useRackStore((s) => s.racks)
+ const moveRack = useRackStore((s) => s.moveRack)
+ const selectDevice = useRackStore((s) => s.selectDevice)
+ const cableMode = useRackStore((s) => s.cableMode)
+ const loading = useRackStore((s) => s.loading)
+ const loadError = useRackStore((s) => s.loadError)
+ const designId = useRackStore((s) => s.designId)
+ const storedViewport = useRackStore((s) => s.viewport)
+ const setViewport = useRackStore((s) => s.setViewport)
+ const addRack = useRackStore((s) => s.addRack)
+ const loadDemo = useRackStore((s) => s.loadDemo)
+
+ const palette = useRackPalette()
+ const { setViewport: applyViewport } = useReactFlow()
+
+ // Restore the saved pan/zoom once per design, not on every viewport nudge.
+ const restoredFor = useRef<string | null>(null)
+ useEffect(() => {
+ if (!designId || loading || restoredFor.current === designId) return
+ restoredFor.current = designId
+ if (storedViewport.zoom > 0) void applyViewport(storedViewport)
+ }, [designId, loading, storedViewport, applyViewport])
+
+ const nodes: Node[] = useMemo(
+ () =>
+ racks.map((rack) => ({
+ id: rack.id,
+ type: 'rack',
+ position: rack.position,
+ data: {},
+ draggable: !cableMode,
+ style: { width: rackWidth(rack), height: rackHeight(rack) },
+ })),
+ [racks, cableMode],
+ )
+
+ const onNodesChange = useCallback(
+ (changes: NodeChange[]) => {
+ for (const change of changes) {
+ if (change.type === 'position' && change.position) {
+ moveRack(change.id, change.position)
+ }
+ }
+ },
+ [moveRack],
+ )
+
+ const onMoveEnd = useCallback(
+ (_: unknown, viewport: Viewport) => setViewport(viewport),
+ [setViewport],
+ )
+
+ if (loadError) {
+ return (
+ <div className="flex h-full items-center justify-center text-sm text-[#f85149]">
+ Rack canvas could not be loaded.
+ </div>
+ )
+ }
+
+ return (
+ <ReactFlow
+ nodes={nodes}
+ edges={[]}
+ nodeTypes={nodeTypes}
+ onNodesChange={onNodesChange}
+ onMoveEnd={onMoveEnd}
+ onPaneClick={() => selectDevice(null)}
+ minZoom={0.2}
+ maxZoom={3}
+ proOptions={{ hideAttribution: true }}
+ style={{ background: palette.canvas }}
+ >
+ <Background variant={BackgroundVariant.Dots} gap={24} size={1} color={palette.dot} />
+ <Controls />
+ <CableLayer />
+ {!loading && racks.length === 0 && (
+ <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-3 text-center">
+ <p className="text-sm text-[#8b949e]">This rack canvas is empty.</p>
+ <div className="pointer-events-auto flex gap-2">
+ <button
+ type="button"
+ onClick={() => addRack({ style: palette.defaultRackStyle })}
+ className="flex items-center gap-1.5 rounded border border-[#00d4ff] px-3 py-1.5 text-xs text-[#00d4ff] hover:bg-[#00d4ff]/10 cursor-pointer"
+ >
+ <Plus size={14} /> Add a rack
+ </button>
+ <button
+ type="button"
+ onClick={loadDemo}
+ className="rounded border border-[#21262d] bg-[#161b22] px-3 py-1.5 text-xs text-[#8b949e] hover:border-[#30363d] hover:text-[#c9d1d9] cursor-pointer"
+ >
+ Load a sample rack
+ </button>
+ </div>
+ </div>
+ )}
+ </ReactFlow>
+ )
+}
diff --git a/frontend/src/rack/components/RackFlowNode.tsx b/frontend/src/rack/components/RackFlowNode.tsx
index ebe6188..9741ece 100644
--- a/frontend/src/rack/components/RackFlowNode.tsx
+++ b/frontend/src/rack/components/RackFlowNode.tsx
@@ -20,7 +20,8 @@ import {
yToU,
} from '../layout'
import { useRackStore } from '../store'
-import { RACK_COLUMNS } from '../types'
+import { useRackPalette } from '../rackTheme'
+import { RACK_COLUMNS } from '@/types'
import { Faceplate } from './Faceplate'
import { endDrag, getDragPayload, parseDragPayload, startDrag } from './dragPayload'
@@ -33,6 +34,7 @@ interface DropPreview {
}
export function RackFlowNode({ id }: NodeProps) {
+ const palette = useRackPalette()
const rack = useRackStore((s) => s.racks.find((r) => r.id === id))
const devices = useRackStore((s) => s.devices)
const cables = useRackStore((s) => s.cables)
@@ -162,7 +164,7 @@ export function RackFlowNode({ id }: NodeProps) {
inset: 0,
left: gutter,
background: rack.style.frame,
- border: `2px solid ${selectedRackId === rack.id ? '#00d4ff' : '#0d1117'}`,
+ border: `2px solid ${selectedRackId === rack.id ? palette.accent : palette.plateOutline}`,
borderRadius: 6,
boxShadow: rack.style.enclosed ? 'inset 0 0 0 4px rgba(0,0,0,0.35)' : undefined,
}}
@@ -211,7 +213,7 @@ export function RackFlowNode({ id }: NodeProps) {
fontSize: 9,
lineHeight: `${U_PX}px`,
textAlign: 'right',
- color: '#6e7681',
+ color: palette.muted,
fontFamily: 'JetBrains Mono, monospace',
}}
>
@@ -241,7 +243,7 @@ export function RackFlowNode({ id }: NodeProps) {
top: INTERIOR_TOP_PX + (rack.uHeight - preview.uStart - preview.uHeight + 1) * U_PX,
width: preview.colSpan * col,
height: preview.uHeight * U_PX,
- border: `1.5px dashed ${preview.valid ? '#39d353' : '#f85149'}`,
+ border: `1.5px dashed ${preview.valid ? palette.status.online : palette.status.offline}`,
background: preview.valid ? 'rgba(57,211,83,0.12)' : 'rgba(248,81,73,0.12)',
borderRadius: 3,
pointerEvents: 'none',
@@ -306,14 +308,14 @@ export function RackFlowNode({ id }: NodeProps) {
height: HEADER_PX,
lineHeight: `${HEADER_PX}px`,
fontSize: 12,
- color: '#c9d1d9',
+ color: palette.text,
fontFamily: 'Inter, system-ui, sans-serif',
pointerEvents: 'none',
}}
>
{rack.name}
- {rack.location && <span style={{ color: '#6e7681' }}> · {rack.location}</span>}
- <span style={{ color: '#6e7681' }}> · {rack.uHeight}U</span>
+ {rack.location && <span style={{ color: palette.muted }}> · {rack.location}</span>}
+ <span style={{ color: palette.muted }}> · {rack.uHeight}U</span>
</div>
</div>
)
diff --git a/frontend/src/rack/components/RackInspector.tsx b/frontend/src/rack/components/RackInspector.tsx
index 8284b3e..f0b161b 100644
--- a/frontend/src/rack/components/RackInspector.tsx
+++ b/frontend/src/rack/components/RackInspector.tsx
@@ -1,10 +1,10 @@
/** Right rail: settings for the selected rack or the selected mounted device. */
import { faceplateGroups } from '../faceplates'
-import { RACK_COLUMNS } from '../types'
+import { RACK_COLUMNS } from '@/types'
import { freeUnits } from '../layout'
import { useRackStore } from '../store'
import { CABLE_TYPE_LABELS } from '../rackDefaults'
-import type { CableType, DeviceStatus, PortType, RackNumbering, RackWidthStandard } from '../types'
+import type { CableType, DeviceStatus, PortType, RackNumbering, RackWidthStandard } from '@/types'
const inputClass =
'w-full rounded border border-[#21262d] bg-[#0d1117] px-2 py-1 text-sm text-[#c9d1d9] outline-none focus:border-[#00d4ff]'
@@ -143,7 +143,11 @@ function DeviceSettings({ deviceId }: { deviceId: string }) {
<div>
<h2 className="mb-1 text-sm font-semibold">{device.label}</h2>
<p className="mb-3 text-[11px] text-[#6e7681]">
- {device.nodeId ? `Inventory: ${device.nodeId}` : 'Rack-only accessory'}
+ {device.deviceId
+ ? device.nodeId
+ ? 'From the Device Inventory · on a logical canvas'
+ : 'From the Device Inventory'
+ : 'Rack-only accessory'}
</p>
<Field label="Label">
@@ -298,7 +302,7 @@ function DeviceSettings({ deviceId }: { deviceId: string }) {
className="mt-4 w-full rounded border border-[#f85149] px-2 py-1.5 text-sm text-[#f85149] hover:bg-[#f8514922]"
onClick={() => unmountDevice(device.id)}
>
- Unmount {device.nodeId ? '(stays in inventory)' : ''}
+ Unmount {device.deviceId ? '(stays in inventory)' : ''}
</button>
</div>
)
@@ -309,7 +313,7 @@ export function RackInspector() {
const selectedRackId = useRackStore((s) => s.selectedRackId)
return (
- <aside className="w-72 shrink-0 overflow-y-auto border-l border-[#21262d] bg-[#0d1117] p-3 text-sm text-[#c9d1d9]">
+ <aside className="w-72 shrink-0 overflow-y-auto border-l border-border bg-[#161b22] p-3 text-sm text-foreground">
{selectedDeviceId ? (
<DeviceSettings deviceId={selectedDeviceId} />
) : selectedRackId ? (
diff --git a/frontend/src/rack/components/RackLab.tsx b/frontend/src/rack/components/RackLab.tsx
deleted file mode 100644
index fb5a5fa..0000000
--- a/frontend/src/rack/components/RackLab.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-/**
- * Rack canvas prototype shell.
- *
- * Front-only: no API calls, no persistence. Mounted at /racklab so it can be
- * iterated on without touching the logical canvas.
- */
-import { useCallback, useMemo } from 'react'
-import {
- Background,
- BackgroundVariant,
- Controls,
- ReactFlow,
- ReactFlowProvider,
- type Node,
- type NodeChange,
-} from '@xyflow/react'
-import '@xyflow/react/dist/style.css'
-import { rackHeight, rackWidth } from '../layout'
-import { useRackStore } from '../store'
-import { CABLE_TYPE_LABELS } from '../rackDefaults'
-import type { CableType, CableVisibility } from '../types'
-import { CableLayer } from './CableLayer'
-import { InventoryTray } from './InventoryTray'
-import { RackFlowNode } from './RackFlowNode'
-import { RackInspector } from './RackInspector'
-
-const nodeTypes = { rack: RackFlowNode }
-
-const barButton =
- 'rounded border border-[#21262d] bg-[#161b22] px-2.5 py-1 text-xs text-[#c9d1d9] hover:border-[#00d4ff]'
-const barSelect =
- 'rounded border border-[#21262d] bg-[#161b22] px-2 py-1 text-xs text-[#c9d1d9] outline-none focus:border-[#00d4ff]'
-
-function RackCanvas() {
- const racks = useRackStore((s) => s.racks)
- const moveRack = useRackStore((s) => s.moveRack)
- const selectDevice = useRackStore((s) => s.selectDevice)
- const cableMode = useRackStore((s) => s.cableMode)
-
- const nodes: Node[] = useMemo(
- () =>
- racks.map((rack) => ({
- id: rack.id,
- type: 'rack',
- position: rack.position,
- data: {},
- draggable: !cableMode,
- style: { width: rackWidth(rack), height: rackHeight(rack) },
- })),
- [racks, cableMode],
- )
-
- const onNodesChange = useCallback(
- (changes: NodeChange[]) => {
- for (const change of changes) {
- if (change.type === 'position' && change.position) {
- moveRack(change.id, change.position)
- }
- }
- },
- [moveRack],
- )
-
- return (
- <ReactFlow
- nodes={nodes}
- edges={[]}
- nodeTypes={nodeTypes}
- onNodesChange={onNodesChange}
- onPaneClick={() => selectDevice(null)}
- minZoom={0.2}
- maxZoom={3}
- fitView
- proOptions={{ hideAttribution: true }}
- style={{ background: '#0d1117' }}
- >
- <Background variant={BackgroundVariant.Dots} gap={24} size={1} color="#21262d" />
- <Controls />
- <CableLayer />
- </ReactFlow>
- )
-}
-
-function RackToolbar() {
- const addRack = useRackStore((s) => s.addRack)
- const cableMode = useRackStore((s) => s.cableMode)
- const toggleCableMode = useRackStore((s) => s.toggleCableMode)
- const cableVisibility = useRackStore((s) => s.cableVisibility)
- const setCableVisibility = useRackStore((s) => s.setCableVisibility)
- const cableTypeFilter = useRackStore((s) => s.cableTypeFilter)
- const setCableTypeFilter = useRackStore((s) => s.setCableTypeFilter)
- const cableDraft = useRackStore((s) => s.cableDraft)
- const cancelCableDraft = useRackStore((s) => s.cancelCableDraft)
- const importCables = useRackStore((s) => s.importCablesFromNetwork)
- const networkImportDone = useRackStore((s) => s.networkImportDone)
- const reset = useRackStore((s) => s.reset)
-
- return (
- <header className="flex items-center gap-2 border-b border-[#21262d] bg-[#161b22] px-3 py-2">
- <span className="mr-2 text-sm font-semibold text-[#c9d1d9]">Rack view</span>
- <span className="rounded bg-[#21262d] px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[#e3b341]">
- prototype
- </span>
-
- <button className={barButton} onClick={() => addRack()}>
- + Rack
- </button>
-
- <button
- className={`${barButton} ${cableMode ? 'border-[#00d4ff] text-[#00d4ff]' : ''}`}
- onClick={toggleCableMode}
- title="Click a port, then another, to patch. Click a cable to remove it."
- >
- {cableMode ? 'Exit patching' : 'Patch mode'}
- </button>
-
- {cableMode && cableDraft && (
- <button className={`${barButton} border-[#e3b341] text-[#e3b341]`} onClick={cancelCableDraft}>
- Cancel cable
- </button>
- )}
-
- <label className="ml-2 flex items-center gap-1 text-[11px] text-[#6e7681]">
- Cables
- <select
- className={barSelect}
- value={cableVisibility}
- onChange={(e) => setCableVisibility(e.target.value as CableVisibility)}
- >
- <option value="hover">On hover / selection</option>
- <option value="always">Always</option>
- <option value="hidden">Hidden</option>
- </select>
- </label>
-
- <select
- className={barSelect}
- value={cableTypeFilter}
- onChange={(e) => setCableTypeFilter(e.target.value as CableType | 'all')}
- >
- <option value="all">All types</option>
- {(Object.keys(CABLE_TYPE_LABELS) as CableType[]).map((t) => (
- <option key={t} value={t}>
- {CABLE_TYPE_LABELS[t]}
- </option>
- ))}
- </select>
-
- <button
- className={barButton}
- disabled={networkImportDone}
- onClick={() => importCables()}
- title="One-shot: derive cables from the links already drawn on the logical canvas"
- >
- Import links from network canvas
- </button>
-
- <button className={`${barButton} ml-auto`} onClick={reset}>
- Reset demo
- </button>
- </header>
- )
-}
-
-export default function RackLab() {
- return (
- <ReactFlowProvider>
- <div className="flex h-screen w-screen flex-col bg-[#0d1117]">
- <RackToolbar />
- <div className="flex min-h-0 flex-1">
- <InventoryTray />
- <main className="min-w-0 flex-1">
- <RackCanvas />
- </main>
- <RackInspector />
- </div>
- </div>
- </ReactFlowProvider>
- )
-}
diff --git a/frontend/src/rack/demoData.ts b/frontend/src/rack/demoData.ts
index 4f4864e..e604b2b 100644
--- a/frontend/src/rack/demoData.ts
+++ b/frontend/src/rack/demoData.ts
@@ -1,33 +1,67 @@
/**
- * Fake inventory + a pre-filled rack, so the prototype boots with something
- * to look at. Ids are fixed strings (not UUIDs) to keep tests readable.
+ * A sample inventory + a pre-filled rack, offered on an empty rack canvas and
+ * used as fixtures by the rack tests. Ids are fixed strings (not UUIDs) to keep
+ * tests readable.
+ *
+ * `inv-*` ids stand in for Device Inventory entries, `node-*` for the matching
+ * canvas nodes — the same two links a real mount carries.
*/
import { getFaceplate } from './faceplates'
import { CABLE_COLORS, DEFAULT_RACK_STYLE } from './rackDefaults'
-import type { Cable, CableType, InventoryDevice, Port, Rack, RackDevice } from './types'
+import type { Cable, CableType, InventoryDevice, Port, Rack, RackDevice } from '@/types'
let portSeq = 0
function withIds(ports: Omit<Port, 'id'>[], deviceId: string): Port[] {
return ports.map((p) => ({ ...p, id: `${deviceId}-p${portSeq++}` }))
}
+interface DemoInventorySpec {
+ id: string
+ label: string
+ type: string
+ ip?: string
+ status: InventoryDevice['status']
+ suggestedFaceplateId: string
+ /** Omitted for gear that was never placed on a logical canvas. */
+ onCanvas?: false
+}
+
+const DEMO_INVENTORY: DemoInventorySpec[] = [
+ { id: 'inv-pve1', label: 'pve-01', type: 'proxmox', ip: '192.168.1.10', status: 'online', suggestedFaceplateId: 'server-2u-bays' },
+ { id: 'inv-pve2', label: 'pve-02', type: 'proxmox', ip: '192.168.1.11', status: 'online', suggestedFaceplateId: 'server-1u-bays' },
+ { id: 'inv-nuc1', label: 'nuc-k3s-a', type: 'server', ip: '192.168.1.21', status: 'online', suggestedFaceplateId: 'sff-half' },
+ { id: 'inv-nuc2', label: 'nuc-k3s-b', type: 'server', ip: '192.168.1.22', status: 'online', suggestedFaceplateId: 'sff-half' },
+ { id: 'inv-pi1', label: 'pi-dns', type: 'server', ip: '192.168.1.31', status: 'online', suggestedFaceplateId: 'mini-third' },
+ { id: 'inv-pi2', label: 'pi-backup', type: 'server', ip: '192.168.1.32', status: 'offline', suggestedFaceplateId: 'mini-third' },
+ { id: 'inv-sw24', label: 'sw-core-24', type: 'switch', ip: '192.168.1.2', status: 'online', suggestedFaceplateId: 'switch-24' },
+ { id: 'inv-sw8', label: 'sw-lab-8', type: 'switch', ip: '192.168.1.3', status: 'online', suggestedFaceplateId: 'switch-8' },
+ { id: 'inv-fw', label: 'opnsense', type: 'firewall', ip: '192.168.1.1', status: 'online', suggestedFaceplateId: 'router-1u' },
+ { id: 'inv-nas', label: 'nas-truenas', type: 'nas', ip: '192.168.1.40', status: 'online', suggestedFaceplateId: 'nas-2u' },
+ { id: 'inv-jbod', label: 'jbod-shelf', type: 'server', ip: '192.168.1.41', status: 'unknown', suggestedFaceplateId: 'server-4u-storage' },
+ { id: 'inv-ups', label: 'ups-eaton', type: 'ups', ip: '192.168.1.50', status: 'online', suggestedFaceplateId: 'ups-2u' },
+ // Dumb hardware: documented by hand, never on a logical canvas.
+ { id: 'inv-pdu', label: 'pdu-main', type: 'generic', status: 'unknown', suggestedFaceplateId: 'pdu-1u', onCanvas: false },
+ { id: 'inv-patch', label: 'patch-house', type: 'generic', status: 'unknown', suggestedFaceplateId: 'patch-24', onCanvas: false },
+]
+
+/** Canvas node id for an inventory entry, when it has one. */
+export function demoNodeId(inventoryId: string): string | null {
+ const spec = DEMO_INVENTORY.find((i) => i.id === inventoryId)
+ if (!spec || spec.onCanvas === false) return null
+ return `node-${inventoryId}`
+}
+
export function demoInventory(): InventoryDevice[] {
- return [
- { id: 'inv-pve1', label: 'pve-01', type: 'proxmox', ip: '192.168.1.10', status: 'online', suggestedFaceplateId: 'server-2u-bays' },
- { id: 'inv-pve2', label: 'pve-02', type: 'proxmox', ip: '192.168.1.11', status: 'online', suggestedFaceplateId: 'server-1u-bays' },
- { id: 'inv-nuc1', label: 'nuc-k3s-a', type: 'server', ip: '192.168.1.21', status: 'online', suggestedFaceplateId: 'sff-half' },
- { id: 'inv-nuc2', label: 'nuc-k3s-b', type: 'server', ip: '192.168.1.22', status: 'online', suggestedFaceplateId: 'sff-half' },
- { id: 'inv-pi1', label: 'pi-dns', type: 'server', ip: '192.168.1.31', status: 'online', suggestedFaceplateId: 'mini-third' },
- { id: 'inv-pi2', label: 'pi-backup', type: 'server', ip: '192.168.1.32', status: 'offline', suggestedFaceplateId: 'mini-third' },
- { id: 'inv-sw24', label: 'sw-core-24', type: 'switch', ip: '192.168.1.2', status: 'online', suggestedFaceplateId: 'switch-24' },
- { id: 'inv-sw8', label: 'sw-lab-8', type: 'switch', ip: '192.168.1.3', status: 'online', suggestedFaceplateId: 'switch-8' },
- { id: 'inv-fw', label: 'opnsense', type: 'firewall', ip: '192.168.1.1', status: 'online', suggestedFaceplateId: 'router-1u' },
- { id: 'inv-nas', label: 'nas-truenas', type: 'nas', ip: '192.168.1.40', status: 'online', suggestedFaceplateId: 'nas-2u' },
- { id: 'inv-jbod', label: 'jbod-shelf', type: 'server', ip: '192.168.1.41', status: 'unknown', suggestedFaceplateId: 'server-4u-storage' },
- { id: 'inv-ups', label: 'ups-eaton', type: 'ups', ip: '192.168.1.50', status: 'online', suggestedFaceplateId: 'ups-2u' },
- { id: 'inv-pdu', label: 'pdu-main', type: 'pdu', status: 'unknown', suggestedFaceplateId: 'pdu-1u' },
- { id: 'inv-patch', label: 'patch-house', type: 'patch_panel', status: 'unknown', suggestedFaceplateId: 'patch-24' },
- ]
+ return DEMO_INVENTORY.map((spec) => ({
+ id: spec.id,
+ label: spec.label,
+ type: spec.type,
+ ip: spec.ip ?? null,
+ status: spec.status,
+ nodeId: demoNodeId(spec.id),
+ racked: false,
+ suggestedFaceplateId: spec.suggestedFaceplateId,
+ }))
}
export function demoRacks(): Rack[] {
@@ -47,7 +81,8 @@ export function demoRacks(): Rack[] {
interface DemoMount {
id: string
- nodeId: string | null
+ /** Device Inventory entry; null for rack-only accessories. */
+ deviceId: string | null
label: string
faceplateId: string
uStart: number
@@ -58,23 +93,23 @@ interface DemoMount {
/** Layout of the pre-filled rack, top (18U) down to the bottom. */
const DEMO_MOUNTS: DemoMount[] = [
- { id: 'dev-patch', nodeId: 'inv-patch', label: 'patch-house', faceplateId: 'patch-24', uStart: 18 },
- { id: 'dev-sw24', nodeId: 'inv-sw24', label: 'sw-core-24', faceplateId: 'switch-24', uStart: 17 },
- { id: 'dev-mgmt', nodeId: null, label: 'Cable manager', faceplateId: 'cable-manager-1u', uStart: 16 },
- { id: 'dev-fw', nodeId: 'inv-fw', label: 'opnsense', faceplateId: 'router-1u', uStart: 15 },
+ { id: 'dev-patch', deviceId: 'inv-patch', label: 'patch-house', faceplateId: 'patch-24', uStart: 18 },
+ { id: 'dev-sw24', deviceId: 'inv-sw24', label: 'sw-core-24', faceplateId: 'switch-24', uStart: 17 },
+ { id: 'dev-mgmt', deviceId: null, label: 'Cable manager', faceplateId: 'cable-manager-1u', uStart: 16 },
+ { id: 'dev-fw', deviceId: 'inv-fw', label: 'opnsense', faceplateId: 'router-1u', uStart: 15 },
// Two half-width mini PCs sharing 14U.
- { id: 'dev-nuc1', nodeId: 'inv-nuc1', label: 'nuc-k3s-a', faceplateId: 'sff-half', uStart: 14, colStart: 0, colSpan: 6 },
- { id: 'dev-nuc2', nodeId: 'inv-nuc2', label: 'nuc-k3s-b', faceplateId: 'sff-half', uStart: 14, colStart: 6, colSpan: 6 },
+ { id: 'dev-nuc1', deviceId: 'inv-nuc1', label: 'nuc-k3s-a', faceplateId: 'sff-half', uStart: 14, colStart: 0, colSpan: 6 },
+ { id: 'dev-nuc2', deviceId: 'inv-nuc2', label: 'nuc-k3s-b', faceplateId: 'sff-half', uStart: 14, colStart: 6, colSpan: 6 },
// Three third-width nodes sharing 13U.
- { id: 'dev-pi1', nodeId: 'inv-pi1', label: 'pi-dns', faceplateId: 'mini-third', uStart: 13, colStart: 0, colSpan: 4 },
- { id: 'dev-pi2', nodeId: 'inv-pi2', label: 'pi-backup', faceplateId: 'mini-third', uStart: 13, colStart: 4, colSpan: 4, status: 'offline' },
- { id: 'dev-blank', nodeId: null, label: 'Blank', faceplateId: 'blank-1u', uStart: 13, colStart: 8, colSpan: 4 },
- { id: 'dev-pve1', nodeId: 'inv-pve1', label: 'pve-01', faceplateId: 'server-2u-bays', uStart: 11 },
- { id: 'dev-pve2', nodeId: 'inv-pve2', label: 'pve-02', faceplateId: 'server-1u-bays', uStart: 10 },
- { id: 'dev-nas', nodeId: 'inv-nas', label: 'nas-truenas', faceplateId: 'nas-2u', uStart: 8 },
- { id: 'dev-shelf', nodeId: null, label: 'Shelf', faceplateId: 'shelf-1u', uStart: 7 },
- { id: 'dev-pdu', nodeId: 'inv-pdu', label: 'pdu-main', faceplateId: 'pdu-1u', uStart: 3 },
- { id: 'dev-ups', nodeId: 'inv-ups', label: 'ups-eaton', faceplateId: 'ups-2u', uStart: 1 },
+ { id: 'dev-pi1', deviceId: 'inv-pi1', label: 'pi-dns', faceplateId: 'mini-third', uStart: 13, colStart: 0, colSpan: 4 },
+ { id: 'dev-pi2', deviceId: 'inv-pi2', label: 'pi-backup', faceplateId: 'mini-third', uStart: 13, colStart: 4, colSpan: 4, status: 'offline' },
+ { id: 'dev-blank', deviceId: null, label: 'Blank', faceplateId: 'blank-1u', uStart: 13, colStart: 8, colSpan: 4 },
+ { id: 'dev-pve1', deviceId: 'inv-pve1', label: 'pve-01', faceplateId: 'server-2u-bays', uStart: 11 },
+ { id: 'dev-pve2', deviceId: 'inv-pve2', label: 'pve-02', faceplateId: 'server-1u-bays', uStart: 10 },
+ { id: 'dev-nas', deviceId: 'inv-nas', label: 'nas-truenas', faceplateId: 'nas-2u', uStart: 8 },
+ { id: 'dev-shelf', deviceId: null, label: 'Shelf', faceplateId: 'shelf-1u', uStart: 7 },
+ { id: 'dev-pdu', deviceId: 'inv-pdu', label: 'pdu-main', faceplateId: 'pdu-1u', uStart: 3 },
+ { id: 'dev-ups', deviceId: 'inv-ups', label: 'ups-eaton', faceplateId: 'ups-2u', uStart: 1 },
]
export function demoDevices(): RackDevice[] {
@@ -82,11 +117,12 @@ export function demoDevices(): RackDevice[] {
const inventory = demoInventory()
return DEMO_MOUNTS.map((mount) => {
const plate = getFaceplate(mount.faceplateId)
- const inv = mount.nodeId ? inventory.find((i) => i.id === mount.nodeId) : undefined
+ const inv = mount.deviceId ? inventory.find((i) => i.id === mount.deviceId) : undefined
return {
id: mount.id,
rackId: 'rack-main',
- nodeId: mount.nodeId,
+ deviceId: mount.deviceId,
+ nodeId: mount.deviceId ? demoNodeId(mount.deviceId) : null,
label: mount.label,
uStart: mount.uStart,
uHeight: plate.uHeight,
@@ -141,14 +177,14 @@ export function demoCables(): Cable[] {
}
/**
- * Stand-in for "read the links already drawn on the logical canvas".
- * The real implementation would read the network design's edges; here it is a
- * fixed list of inventory-id pairs used by the one-shot import action.
+ * Sample "links already drawn on the logical canvas", keyed by canvas node id.
+ * The real list comes from `networkLinks.ts`; this one backs the tests and the
+ * sample canvas.
*/
-export function networkEdgeHints(): { from: string; to: string; type: CableType; label?: string }[] {
+export function demoNetworkLinks(): { from: string; to: string; type: CableType; label?: string }[] {
return [
- { from: 'inv-sw8', to: 'inv-sw24', type: 'ethernet', label: 'lab uplink' },
- { from: 'inv-jbod', to: 'inv-nas', type: 'ethernet' },
- { from: 'inv-pi1', to: 'inv-sw24', type: 'ethernet' },
+ { from: 'node-inv-sw8', to: 'node-inv-sw24', type: 'ethernet', label: 'lab uplink' },
+ { from: 'node-inv-jbod', to: 'node-inv-nas', type: 'ethernet' },
+ { from: 'node-inv-pi1', to: 'node-inv-sw24', type: 'ethernet' },
]
}
diff --git a/frontend/src/rack/faceplates.ts b/frontend/src/rack/faceplates.ts
index 2e816e6..d1f5a5a 100644
--- a/frontend/src/rack/faceplates.ts
+++ b/frontend/src/rack/faceplates.ts
@@ -8,7 +8,7 @@
*
* Templates only seed the ports — the user edits the port list afterwards.
*/
-import { RACK_COLUMNS, type FaceplateTemplate, type Port, type PortType } from './types'
+import { RACK_COLUMNS, type FaceplateTemplate, type Port, type PortType } from '@/types'
interface BankOptions {
type: PortType
@@ -381,6 +381,34 @@ export function getFaceplate(id: string): FaceplateTemplate {
return BY_ID.get(id) ?? FACEPLATES[0]
}
+/**
+ * Faceplate proposed when an inventory device is dropped into a rack.
+ *
+ * Keyed on the device's discovery `suggested_type`, which is free-form — an
+ * unknown or missing type falls back to a plain 1U server plate, which the user
+ * can swap in the inspector.
+ */
+const FACEPLATE_BY_DEVICE_TYPE: Record<string, string> = {
+ server: 'server-1u-bays',
+ proxmox: 'server-2u-bays',
+ nas: 'nas-2u',
+ switch: 'switch-24',
+ router: 'router-1u',
+ firewall: 'router-1u',
+ ap: 'sff-half',
+ computer: 'sff-half',
+ docker_host: 'server-1u',
+ ups: 'ups-2u',
+ printer: 'shelf-1u',
+ camera: 'mini-third',
+ iot: 'mini-third',
+ cpl: 'mini-third',
+}
+
+export function suggestFaceplate(deviceType: string | null | undefined): string {
+ return (deviceType && FACEPLATE_BY_DEVICE_TYPE[deviceType]) || 'server-1u'
+}
+
/** Templates grouped for the picker, preserving catalog order. */
export function faceplateGroups(): { group: string; items: FaceplateTemplate[] }[] {
const groups: { group: string; items: FaceplateTemplate[] }[] = []
diff --git a/frontend/src/rack/layout.ts b/frontend/src/rack/layout.ts
index eb41566..ec6da34 100644
--- a/frontend/src/rack/layout.ts
+++ b/frontend/src/rack/layout.ts
@@ -4,7 +4,7 @@
* All U values are 1-based and counted from the bottom rail, whatever the
* rack's `numbering` setting is — numbering only affects the printed labels.
*/
-import { RACK_COLUMNS, type Port, type Rack, type RackDevice } from './types'
+import { RACK_COLUMNS, type Port, type Rack, type RackDevice } from '@/types'
/** Pixel height of one rack unit at zoom 1. */
export const U_PX = 24
diff --git a/frontend/src/rack/networkLinks.ts b/frontend/src/rack/networkLinks.ts
new file mode 100644
index 0000000..4583ad2
--- /dev/null
+++ b/frontend/src/rack/networkLinks.ts
@@ -0,0 +1,61 @@
+/**
+ * Reads the links already drawn on the logical canvases, so a fresh rack can be
+ * seeded with the patches the user has already documented.
+ *
+ * Endpoints are canvas node ids, matched against `RackDevice.nodeId` — a mount
+ * only carries one when its inventory entry resolves to a node.
+ */
+import { canvasApi } from '@/api/client'
+import type { CableType, Design } from '@/types'
+import type { NetworkLinkHint } from './store'
+
+interface ApiEdgeLike {
+ source: string
+ target: string
+ type?: string
+ label?: string | null
+}
+
+/** Edge types worth turning into a physical patch. */
+const PHYSICAL_EDGE_TYPES = new Set(['ethernet', 'fibre', 'vlan', 'cluster'])
+
+function toCableType(edgeType: string | undefined): CableType {
+ return edgeType === 'fibre' ? 'fiber' : 'ethernet'
+}
+
+/**
+ * Collect physical links across every non-rack design.
+ *
+ * Best-effort: a design that fails to load is skipped rather than failing the
+ * whole import, since this only ever seeds an optional starting point.
+ */
+export async function loadNetworkLinks(designs: Design[]): Promise<NetworkLinkHint[]> {
+ const sources = designs.filter((d) => d.design_type !== 'rack')
+ const hints: NetworkLinkHint[] = []
+ const seen = new Set<string>()
+
+ for (const design of sources) {
+ let edges: ApiEdgeLike[] = []
+ try {
+ const res = await canvasApi.load(design.id)
+ edges = ((res.data as { edges?: ApiEdgeLike[] })?.edges ?? [])
+ } catch {
+ continue
+ }
+ for (const edge of edges) {
+ if (edge.type && !PHYSICAL_EDGE_TYPES.has(edge.type)) continue
+ // Node ids are unique across designs, so an unordered pair dedupes links
+ // that the user drew on more than one canvas.
+ const key = [edge.source, edge.target].sort().join('|')
+ if (seen.has(key)) continue
+ seen.add(key)
+ hints.push({
+ from: edge.source,
+ to: edge.target,
+ type: toCableType(edge.type),
+ label: edge.label ?? undefined,
+ })
+ }
+ }
+ return hints
+}
diff --git a/frontend/src/rack/rackDefaults.ts b/frontend/src/rack/rackDefaults.ts
index e0e51ee..97114e9 100644
--- a/frontend/src/rack/rackDefaults.ts
+++ b/frontend/src/rack/rackDefaults.ts
@@ -1,5 +1,5 @@
/** Shared defaults, kept out of the store to avoid a cycle with demoData. */
-import type { CableType, PortType, RackStyle } from './types'
+import type { CableType, PortType, RackStyle } from '@/types'
export const DEFAULT_RACK_STYLE: RackStyle = {
frame: '#1c2129',
diff --git a/frontend/src/rack/rackTheme.ts b/frontend/src/rack/rackTheme.ts
new file mode 100644
index 0000000..f17e19f
--- /dev/null
+++ b/frontend/src/rack/rackTheme.ts
@@ -0,0 +1,73 @@
+/**
+ * Rack palette, derived from the active app theme.
+ *
+ * Deliberately derived rather than declared per theme: the rack canvas needs a
+ * background, a text colour, an accent and the status dots — all of which the
+ * node/edge themes already define. Deriving keeps a new theme working with the
+ * rack view for free, and keeps the two from drifting apart.
+ *
+ * Rack chrome proper (frame, rails, interior) stays user-configurable per rack;
+ * only its *default* comes from here.
+ */
+import { useThemeStore } from '@/stores/themeStore'
+import { THEMES } from '@/utils/themes'
+import type { ThemeId } from '@/utils/themes'
+import type { DeviceStatus, RackStyle } from '@/types'
+
+export interface RackPalette {
+ /** Canvas background and dot grid. */
+ canvas: string
+ dot: string
+ /** Faceplate default fill and its outline. */
+ plate: string
+ plateOutline: string
+ /** Primary and secondary text on the rack (labels, U numbers). */
+ text: string
+ muted: string
+ /** Selection accent, shared with the rest of the app. */
+ accent: string
+ /** Status LED on a mounted device. */
+ status: Record<DeviceStatus, string>
+ /** Port artwork: dark recess, metal bezel. */
+ portRecess: string
+ portBezel: string
+ /** Default chrome for a newly created rack. */
+ defaultRackStyle: RackStyle
+}
+
+export function rackPalette(themeId: ThemeId): RackPalette {
+ const c = THEMES[themeId]?.colors ?? THEMES.default.colors
+ const light = c.reactFlowColorMode === 'light'
+
+ return {
+ canvas: c.canvasBackground,
+ dot: c.canvasDotColor,
+ plate: c.nodeCardBackground,
+ plateOutline: c.canvasBackground,
+ text: c.nodeLabelColor,
+ muted: c.nodeSubtextColor,
+ accent: c.nodeAccents.router.border,
+ status: {
+ online: c.statusColors.online,
+ offline: c.statusColors.offline,
+ unknown: c.statusColors.unknown,
+ },
+ // A jack is a hole: darker than the plate on dark themes, and still darker
+ // (not lighter) on light ones, or the artwork stops reading as a socket.
+ portRecess: light ? '#c9d1d9' : '#0b0e13',
+ portBezel: c.nodeSubtextColor,
+ defaultRackStyle: {
+ frame: c.nodeIconBackground,
+ rail: c.nodeSubtextColor,
+ interior: c.canvasBackground,
+ showNumbers: true,
+ enclosed: false,
+ },
+ }
+}
+
+/** Palette for the active theme. Re-renders with a theme switch. */
+export function useRackPalette(): RackPalette {
+ const activeTheme = useThemeStore((s) => s.activeTheme)
+ return rackPalette(activeTheme)
+}
diff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.ts
index 88a23aa..7a8a64e 100644
--- a/frontend/src/rack/store.ts
+++ b/frontend/src/rack/store.ts
@@ -1,31 +1,94 @@
/**
- * Rack canvas prototype store.
+ * Rack canvas store.
*
- * In-memory only — the prototype deliberately has no API and no persistence.
- * Removing a device from a rack never removes it from the inventory, mirroring
- * how the network canvas already treats inventory nodes.
+ * Holds one rack design at a time: its racks, mounted gear, patches and the
+ * Device Inventory entries offered to the tray. Persistence is explicit — the
+ * user saves, like the logical canvas — and every mutating action marks the
+ * canvas dirty.
+ *
+ * Unmounting a device never removes it from the inventory, mirroring how the
+ * network canvas already treats inventory nodes.
*/
import { create } from 'zustand'
+import { racksApi, scanApi } from '@/api/client'
import { generateUUID } from '@/utils/uuid'
-import { getFaceplate } from './faceplates'
+import * as standaloneStorage from '@/utils/standaloneStorage'
+import {
+ buildSavePayload,
+ toCable,
+ toInventoryDevice,
+ toRack,
+ toRackDevice,
+} from '@/utils/rackSerializer'
+import { getFaceplate, suggestFaceplate } from './faceplates'
import { canPlace, findSlot, type Placement } from './layout'
-import { RACK_COLUMNS, type Cable, type CableType, type CableVisibility, type InventoryDevice, type Port, type Rack, type RackDevice, type RackStyle } from './types'
-import { demoCables, demoDevices, demoInventory, demoRacks, networkEdgeHints } from './demoData'
+import {
+ RACK_COLUMNS,
+ type Cable,
+ type CableType,
+ type CableVisibility,
+ type InventoryDevice,
+ type Port,
+ type Rack,
+ type RackDevice,
+ type RackStyle,
+} from '@/types'
+import { demoCables, demoDevices, demoInventory, demoRacks } from './demoData'
import { CABLE_COLORS, DEFAULT_RACK_STYLE, PORT_CABLE_TYPE } from './rackDefaults'
export { CABLE_COLORS, DEFAULT_RACK_STYLE }
+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
+
+const DEFAULT_VIEWPORT = { x: 0, y: 0, zoom: 1 }
+
/** Draft cable being drawn, port by port. */
interface CableDraft {
deviceId: string
portId: string
}
+export interface Viewport {
+ x: number
+ y: number
+ zoom: number
+}
+
+/**
+ * A link already drawn on a logical canvas, offered as a starting patch.
+ * Endpoints are canvas node ids, matched against `RackDevice.nodeId`.
+ */
+export interface NetworkLinkHint {
+ from: string
+ to: string
+ type?: CableType
+ label?: string
+}
+
+export interface NewInventoryDevice {
+ label: string
+ type?: string | null
+ ip?: string | null
+ mac?: string | null
+}
+
interface RackState {
+ /** Design currently loaded. Null before the first `loadDesign`. */
+ designId: string | null
racks: Rack[]
devices: RackDevice[]
cables: Cable[]
inventory: InventoryDevice[]
+ viewport: Viewport
+
+ loading: boolean
+ loadError: boolean
+ hasUnsavedChanges: boolean
+ /**
+ * Bumped on every user edit. Autosave debounces on this rather than on the
+ * arrays themselves, so a status refresh can't keep re-arming the timer.
+ */
+ editSeq: number
// UI
selectedDeviceId: string | null
@@ -37,6 +100,14 @@ interface RackState {
cableDraft: CableDraft | null
cableTypeFilter: CableType | 'all'
+ // Persistence
+ loadDesign: (designId: string) => Promise<void>
+ refreshInventory: () => Promise<void>
+ save: () => Promise<boolean>
+ markSaved: () => void
+ /** Add an inventory entry by hand, for hardware no scan can find. */
+ createInventoryDevice: (input: NewInventoryDevice) => Promise<InventoryDevice | null>
+
// Racks
addRack: (partial?: Partial<Rack>) => string
updateRack: (id: string, patch: Partial<Omit<Rack, 'id'>>) => void
@@ -70,10 +141,11 @@ interface RackState {
updateCable: (id: string, patch: Partial<Omit<Cable, 'id'>>) => void
removeCable: (id: string) => void
/** One-shot seed from the logical canvas — offered at creation time only. */
- importCablesFromNetwork: () => number
+ importCablesFromNetwork: (hints: NetworkLinkHint[]) => number
networkImportDone: boolean
// UI actions
+ setViewport: (v: Viewport) => void
selectDevice: (id: string | null) => void
selectRack: (id: string | null) => void
hoverDevice: (id: string | null) => void
@@ -82,6 +154,8 @@ interface RackState {
toggleCableMode: () => void
pickPort: (deviceId: string, portId: string) => void
cancelCableDraft: () => void
+ /** Seed the demo rack. Used by tests and by the empty-canvas sample button. */
+ loadDemo: () => void
reset: () => void
}
@@ -89,12 +163,18 @@ function withIds(ports: Omit<Port, 'id'>[]): Port[] {
return ports.map((p) => ({ ...p, id: generateUUID() }))
}
-function initialState() {
+function emptyState() {
return {
- racks: demoRacks(),
- devices: demoDevices(),
- cables: demoCables(),
- inventory: demoInventory(),
+ designId: null,
+ racks: [] as Rack[],
+ devices: [] as RackDevice[],
+ cables: [] as Cable[],
+ inventory: [] as InventoryDevice[],
+ viewport: { ...DEFAULT_VIEWPORT },
+ loading: false,
+ loadError: false,
+ hasUnsavedChanges: false,
+ editSeq: 0,
selectedDeviceId: null,
selectedRackId: null,
hoveredDeviceId: null,
@@ -106,297 +186,452 @@ function initialState() {
}
}
-export const useRackStore = create<RackState>((set, get) => ({
- ...initialState(),
-
- // --- Racks --------------------------------------------------------------
- addRack: (partial) => {
- const id = partial?.id ?? generateUUID()
- const count = get().racks.length
- const rack: Rack = {
- id,
- name: `Rack ${count + 1}`,
- uHeight: 24,
- widthStandard: '19',
- numbering: 'bottom-up',
- style: { ...DEFAULT_RACK_STYLE },
- position: { x: 80 + count * 620, y: 60 },
- ...partial,
- }
- set((s) => ({ racks: [...s.racks, rack], selectedRackId: id }))
- return id
- },
-
- updateRack: (id, patch) =>
- set((s) => ({ racks: s.racks.map((r) => (r.id === id ? { ...r, ...patch } : r)) })),
-
- updateRackStyle: (id, patch) =>
- set((s) => ({
- racks: s.racks.map((r) => (r.id === id ? { ...r, style: { ...r.style, ...patch } } : r)),
- })),
-
- moveRack: (id, position) =>
- set((s) => ({ racks: s.racks.map((r) => (r.id === id ? { ...r, position } : r)) })),
-
- removeRack: (id) =>
- set((s) => {
- const doomed = new Set(s.devices.filter((d) => d.rackId === id).map((d) => d.id))
- return {
- racks: s.racks.filter((r) => r.id !== id),
- devices: s.devices.filter((d) => d.rackId !== id),
- cables: s.cables.filter(
- (c) => !doomed.has(c.from.deviceId) && !doomed.has(c.to.deviceId),
- ),
- selectedRackId: s.selectedRackId === id ? null : s.selectedRackId,
- }
- }),
-
- // --- Devices ------------------------------------------------------------
- mountFromInventory: (inventoryId, rackId, desired) => {
- const { racks, devices, inventory } = get()
- const rack = racks.find((r) => r.id === rackId)
- const item = inventory.find((i) => i.id === inventoryId)
- if (!rack || !item) return null
-
- const plate = getFaceplate(item.suggestedFaceplateId)
- const slot = findSlot(rack, devices, {
- uStart: desired.uStart ?? 1,
- uHeight: desired.uHeight ?? plate.uHeight,
- colStart: desired.colStart ?? 0,
- colSpan: desired.colSpan ?? plate.colSpan,
- })
- if (!slot) return null
-
- const device: RackDevice = {
- id: generateUUID(),
- rackId,
- nodeId: item.id,
- label: item.label,
- status: item.status,
- faceplateId: plate.id,
- ports: withIds(plate.ports),
- ...slot,
- }
- set((s) => ({ devices: [...s.devices, device], selectedDeviceId: device.id }))
- return device.id
- },
-
- mountAccessory: (faceplateId, rackId, desired) => {
- const { racks, devices } = get()
- const rack = racks.find((r) => r.id === rackId)
- if (!rack) return null
-
- const plate = getFaceplate(faceplateId)
- const slot = findSlot(rack, devices, {
- uStart: desired.uStart ?? 1,
- uHeight: desired.uHeight ?? plate.uHeight,
- colStart: desired.colStart ?? 0,
- colSpan: desired.colSpan ?? plate.colSpan,
- })
- if (!slot) return null
-
- const device: RackDevice = {
- id: generateUUID(),
- rackId,
- nodeId: null,
- label: plate.label,
- status: 'unknown',
- faceplateId: plate.id,
- ports: withIds(plate.ports),
- ...slot,
- }
- set((s) => ({ devices: [...s.devices, device], selectedDeviceId: device.id }))
- return device.id
- },
-
- moveDevice: (deviceId, rackId, desired) => {
- const { racks, devices } = get()
- const rack = racks.find((r) => r.id === rackId)
- if (!rack) return false
- if (!canPlace(rack, devices, desired, deviceId)) return false
+/**
+ * Which devices in `inventory` are already mounted in this design.
+ * Recomputed on every load and mount so the tray never goes stale.
+ */
+function withRackedFlags(inventory: InventoryDevice[], devices: RackDevice[]): InventoryDevice[] {
+ const mounted = new Set(devices.map((d) => d.deviceId).filter(Boolean))
+ return inventory.map((item) => ({ ...item, racked: mounted.has(item.id) }))
+}
+
+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>)) =>
set((s) => ({
- devices: s.devices.map((d) => (d.id === deviceId ? { ...d, rackId, ...desired } : d)),
+ ...(typeof patch === 'function' ? patch(s) : patch),
+ hasUnsavedChanges: true,
+ editSeq: s.editSeq + 1,
}))
- return true
- },
-
- updateDevice: (id, patch) =>
- set((s) => {
- const device = s.devices.find((d) => d.id === id)
- const rack = device && s.racks.find((r) => r.id === (patch.rackId ?? device.rackId))
- if (!device || !rack) return s
- const next = { ...device, ...patch }
- const geometryChanged =
- next.uStart !== device.uStart ||
- next.uHeight !== device.uHeight ||
- next.colStart !== device.colStart ||
- next.colSpan !== device.colSpan
- if (geometryChanged && !canPlace(rack, s.devices, next, id)) return s
- return { devices: s.devices.map((d) => (d.id === id ? next : d)) }
- }),
-
- unmountDevice: (id) =>
- set((s) => ({
- devices: s.devices.filter((d) => d.id !== id),
- cables: s.cables.filter((c) => c.from.deviceId !== id && c.to.deviceId !== id),
- selectedDeviceId: s.selectedDeviceId === id ? null : s.selectedDeviceId,
- })),
-
- applyFaceplate: (deviceId, faceplateId) =>
- set((s) => {
- const device = s.devices.find((d) => d.id === deviceId)
- const rack = device && s.racks.find((r) => r.id === device.rackId)
- if (!device || !rack) return s
+
+ return {
+ ...emptyState(),
+
+ // --- Persistence --------------------------------------------------------
+ loadDesign: async (designId) => {
+ set({ ...emptyState(), designId, loading: true })
+ try {
+ if (STANDALONE) {
+ const stored = standaloneStorage.loadRackCanvas(designId)
+ const devices = stored?.devices ?? []
+ set({
+ racks: stored?.racks ?? [],
+ devices,
+ cables: stored?.cables ?? [],
+ inventory: withRackedFlags(stored?.inventory ?? [], devices),
+ viewport: stored?.viewport ?? { ...DEFAULT_VIEWPORT },
+ loading: false,
+ hasUnsavedChanges: false,
+ })
+ return
+ }
+
+ const [state, inventory] = await Promise.all([
+ racksApi.load(designId),
+ racksApi.inventory(designId),
+ ])
+ // A design switch may have completed while these were in flight.
+ if (get().designId !== designId) return
+ const devices = state.data.devices.map(toRackDevice)
+ set({
+ racks: state.data.racks.map(toRack),
+ devices,
+ cables: state.data.cables.map(toCable),
+ inventory: withRackedFlags(inventory.data.items.map(toInventoryDevice), devices),
+ viewport: {
+ x: state.data.viewport?.x ?? 0,
+ y: state.data.viewport?.y ?? 0,
+ zoom: state.data.viewport?.zoom ?? 1,
+ },
+ loading: false,
+ hasUnsavedChanges: false,
+ })
+ } catch {
+ if (get().designId !== designId) return
+ set({ loading: false, loadError: true })
+ }
+ },
+
+ refreshInventory: async () => {
+ const { designId, devices } = get()
+ if (!designId || STANDALONE) return
+ try {
+ const res = await racksApi.inventory(designId)
+ if (get().designId !== designId) return
+ set({ inventory: withRackedFlags(res.data.items.map(toInventoryDevice), devices) })
+ } catch {
+ // The tray keeps whatever it already had; racking still works.
+ }
+ },
+
+ save: async () => {
+ const { designId, racks, devices, cables, viewport, inventory } = get()
+ if (!designId) return false
+ try {
+ if (STANDALONE) {
+ standaloneStorage.saveRackCanvas(designId, { racks, devices, cables, viewport, inventory })
+ } else {
+ await racksApi.save(buildSavePayload(designId, racks, devices, cables, viewport))
+ }
+ set({ hasUnsavedChanges: false })
+ return true
+ } catch {
+ return false
+ }
+ },
+
+ markSaved: () => set({ hasUnsavedChanges: false }),
+
+ createInventoryDevice: async ({ label, type = null, ip = null, mac = null }) => {
+ const item: InventoryDevice = {
+ id: generateUUID(),
+ label,
+ type,
+ ip,
+ status: 'unknown',
+ nodeId: null,
+ racked: false,
+ suggestedFaceplateId: suggestFaceplate(type),
+ }
+ if (!STANDALONE) {
+ try {
+ const res = await scanApi.createPending({
+ hostname: label,
+ ip,
+ mac,
+ suggested_type: type,
+ })
+ item.id = res.data.id
+ } catch {
+ return null
+ }
+ }
+ // Standalone keeps its inventory in the rack canvas blob, so this entry is
+ // only durable once the canvas is saved.
+ edit((s) => ({ inventory: [...s.inventory, item] }))
+ return item
+ },
+
+ // --- Racks --------------------------------------------------------------
+ addRack: (partial) => {
+ const id = partial?.id ?? generateUUID()
+ const count = get().racks.length
+ const rack: Rack = {
+ id,
+ name: `Rack ${count + 1}`,
+ uHeight: 24,
+ widthStandard: '19',
+ numbering: 'bottom-up',
+ style: { ...DEFAULT_RACK_STYLE },
+ position: { x: 80 + count * 620, y: 60 },
+ ...partial,
+ }
+ edit((s) => ({ racks: [...s.racks, rack], selectedRackId: id }))
+ return id
+ },
+
+ updateRack: (id, patch) =>
+ edit((s) => ({ racks: s.racks.map((r) => (r.id === id ? { ...r, ...patch } : r)) })),
+
+ updateRackStyle: (id, patch) =>
+ edit((s) => ({
+ racks: s.racks.map((r) => (r.id === id ? { ...r, style: { ...r.style, ...patch } } : r)),
+ })),
+
+ moveRack: (id, position) =>
+ edit((s) => ({ racks: s.racks.map((r) => (r.id === id ? { ...r, position } : r)) })),
+
+ removeRack: (id) =>
+ edit((s) => {
+ const doomed = new Set(s.devices.filter((d) => d.rackId === id).map((d) => d.id))
+ const devices = s.devices.filter((d) => d.rackId !== id)
+ return {
+ racks: s.racks.filter((r) => r.id !== id),
+ devices,
+ cables: s.cables.filter(
+ (c) => !doomed.has(c.from.deviceId) && !doomed.has(c.to.deviceId),
+ ),
+ inventory: withRackedFlags(s.inventory, devices),
+ selectedRackId: s.selectedRackId === id ? null : s.selectedRackId,
+ }
+ }),
+
+ // --- Devices ------------------------------------------------------------
+ mountFromInventory: (inventoryId, rackId, desired) => {
+ const { racks, devices, inventory } = get()
+ const rack = racks.find((r) => r.id === rackId)
+ const item = inventory.find((i) => i.id === inventoryId)
+ if (!rack || !item) return null
+
+ const plate = getFaceplate(item.suggestedFaceplateId)
+ const slot = findSlot(rack, devices, {
+ uStart: desired.uStart ?? 1,
+ uHeight: desired.uHeight ?? plate.uHeight,
+ colStart: desired.colStart ?? 0,
+ colSpan: desired.colSpan ?? plate.colSpan,
+ })
+ if (!slot) return null
+
+ const device: RackDevice = {
+ id: generateUUID(),
+ rackId,
+ deviceId: item.id,
+ nodeId: item.nodeId,
+ label: item.label,
+ status: item.status,
+ faceplateId: plate.id,
+ ports: withIds(plate.ports),
+ ...slot,
+ }
+ edit((s) => {
+ const next = [...s.devices, device]
+ return {
+ devices: next,
+ inventory: withRackedFlags(s.inventory, next),
+ selectedDeviceId: device.id,
+ }
+ })
+ return device.id
+ },
+
+ mountAccessory: (faceplateId, rackId, desired) => {
+ const { racks, devices } = get()
+ const rack = racks.find((r) => r.id === rackId)
+ if (!rack) return null
+
const plate = getFaceplate(faceplateId)
- const resized = {
- ...device,
- faceplateId,
- uHeight: plate.uHeight,
- colSpan: plate.colSpan,
- colStart: Math.min(device.colStart, RACK_COLUMNS - plate.colSpan),
+ const slot = findSlot(rack, devices, {
+ uStart: desired.uStart ?? 1,
+ uHeight: desired.uHeight ?? plate.uHeight,
+ colStart: desired.colStart ?? 0,
+ colSpan: desired.colSpan ?? plate.colSpan,
+ })
+ if (!slot) return null
+
+ const device: RackDevice = {
+ id: generateUUID(),
+ rackId,
+ deviceId: null,
+ nodeId: null,
+ label: plate.label,
+ status: 'unknown',
+ faceplateId: plate.id,
ports: withIds(plate.ports),
+ ...slot,
}
- if (!canPlace(rack, s.devices, resized, deviceId)) {
- // Keep the plate but leave the geometry alone when it no longer fits.
+ edit((s) => ({ devices: [...s.devices, device], selectedDeviceId: device.id }))
+ return device.id
+ },
+
+ moveDevice: (deviceId, rackId, desired) => {
+ const { racks, devices } = get()
+ const rack = racks.find((r) => r.id === rackId)
+ if (!rack) return false
+ if (!canPlace(rack, devices, desired, deviceId)) return false
+ edit((s) => ({
+ devices: s.devices.map((d) => (d.id === deviceId ? { ...d, rackId, ...desired } : d)),
+ }))
+ return true
+ },
+
+ updateDevice: (id, patch) =>
+ edit((s) => {
+ const device = s.devices.find((d) => d.id === id)
+ const rack = device && s.racks.find((r) => r.id === (patch.rackId ?? device.rackId))
+ if (!device || !rack) return {}
+ const next = { ...device, ...patch }
+ const geometryChanged =
+ next.uStart !== device.uStart ||
+ next.uHeight !== device.uHeight ||
+ next.colStart !== device.colStart ||
+ next.colSpan !== device.colSpan
+ if (geometryChanged && !canPlace(rack, s.devices, next, id)) return {}
+ return { devices: s.devices.map((d) => (d.id === id ? next : d)) }
+ }),
+
+ unmountDevice: (id) =>
+ edit((s) => {
+ const devices = s.devices.filter((d) => d.id !== id)
return {
- devices: s.devices.map((d) =>
- d.id === deviceId ? { ...d, faceplateId, ports: withIds(plate.ports) } : d,
+ devices,
+ cables: s.cables.filter((c) => c.from.deviceId !== id && c.to.deviceId !== id),
+ inventory: withRackedFlags(s.inventory, devices),
+ selectedDeviceId: s.selectedDeviceId === id ? null : s.selectedDeviceId,
+ }
+ }),
+
+ applyFaceplate: (deviceId, faceplateId) =>
+ edit((s) => {
+ const device = s.devices.find((d) => d.id === deviceId)
+ const rack = device && s.racks.find((r) => r.id === device.rackId)
+ if (!device || !rack) return {}
+ const plate = getFaceplate(faceplateId)
+ const resized = {
+ ...device,
+ faceplateId,
+ uHeight: plate.uHeight,
+ colSpan: plate.colSpan,
+ colStart: Math.min(device.colStart, RACK_COLUMNS - plate.colSpan),
+ ports: withIds(plate.ports),
+ }
+ if (!canPlace(rack, s.devices, resized, deviceId)) {
+ // Keep the plate but leave the geometry alone when it no longer fits.
+ return {
+ devices: s.devices.map((d) =>
+ d.id === deviceId ? { ...d, faceplateId, ports: withIds(plate.ports) } : d,
+ ),
+ }
+ }
+ return {
+ devices: s.devices.map((d) => (d.id === deviceId ? resized : d)),
+ cables: s.cables.filter(
+ (c) => c.from.deviceId !== deviceId && c.to.deviceId !== deviceId,
),
}
- }
- return {
- devices: s.devices.map((d) => (d.id === deviceId ? resized : d)),
+ }),
+
+ // --- Ports --------------------------------------------------------------
+ addPort: (deviceId, port) =>
+ edit((s) => ({
+ devices: s.devices.map((d) =>
+ d.id === deviceId ? { ...d, ports: [...d.ports, { ...port, id: generateUUID() }] } : d,
+ ),
+ })),
+
+ updatePort: (deviceId, portId, patch) =>
+ edit((s) => ({
+ devices: s.devices.map((d) =>
+ d.id === deviceId
+ ? { ...d, ports: d.ports.map((p) => (p.id === portId ? { ...p, ...patch } : p)) }
+ : d,
+ ),
+ })),
+
+ removePort: (deviceId, portId) =>
+ edit((s) => ({
+ devices: s.devices.map((d) =>
+ d.id === deviceId ? { ...d, ports: d.ports.filter((p) => p.id !== portId) } : d,
+ ),
cables: s.cables.filter(
- (c) => c.from.deviceId !== deviceId && c.to.deviceId !== deviceId,
+ (c) =>
+ !(c.from.deviceId === deviceId && c.from.portId === portId) &&
+ !(c.to.deviceId === deviceId && c.to.portId === portId),
),
+ })),
+
+ // --- Cables -------------------------------------------------------------
+ addCable: (from, to, options) => {
+ const { devices, cables } = get()
+ if (from.deviceId === to.deviceId && from.portId === to.portId) return null
+
+ const hasPort = (ref: CableDraft) =>
+ devices.some((d) => d.id === ref.deviceId && d.ports.some((p) => p.id === ref.portId))
+ if (!hasPort(from) || !hasPort(to)) return null
+
+ // A physical port takes one cable.
+ const taken = (ref: CableDraft) =>
+ cables.some(
+ (c) =>
+ (c.from.deviceId === ref.deviceId && c.from.portId === ref.portId) ||
+ (c.to.deviceId === ref.deviceId && c.to.portId === ref.portId),
+ )
+ if (taken(from) || taken(to)) return null
+
+ // Fibre vs copper follows the port the patch starts from.
+ const fromPort = devices
+ .find((d) => d.id === from.deviceId)!
+ .ports.find((p) => p.id === from.portId)!
+ const type = options?.type ?? PORT_CABLE_TYPE[fromPort.type]
+ const cable: Cable = {
+ id: generateUUID(),
+ type,
+ color: options?.color ?? CABLE_COLORS[type],
+ label: options?.label,
+ from,
+ to,
}
- }),
-
- // --- Ports --------------------------------------------------------------
- addPort: (deviceId, port) =>
- set((s) => ({
- devices: s.devices.map((d) =>
- d.id === deviceId ? { ...d, ports: [...d.ports, { ...port, id: generateUUID() }] } : d,
- ),
- })),
-
- updatePort: (deviceId, portId, patch) =>
- set((s) => ({
- devices: s.devices.map((d) =>
- d.id === deviceId
- ? { ...d, ports: d.ports.map((p) => (p.id === portId ? { ...p, ...patch } : p)) }
- : d,
- ),
- })),
-
- removePort: (deviceId, portId) =>
- set((s) => ({
- devices: s.devices.map((d) =>
- d.id === deviceId ? { ...d, ports: d.ports.filter((p) => p.id !== portId) } : d,
- ),
- cables: s.cables.filter(
- (c) =>
- !(c.from.deviceId === deviceId && c.from.portId === portId) &&
- !(c.to.deviceId === deviceId && c.to.portId === portId),
- ),
- })),
-
- // --- Cables -------------------------------------------------------------
- addCable: (from, to, options) => {
- const { devices, cables } = get()
- if (from.deviceId === to.deviceId && from.portId === to.portId) return null
-
- const hasPort = (ref: CableDraft) =>
- devices.some((d) => d.id === ref.deviceId && d.ports.some((p) => p.id === ref.portId))
- if (!hasPort(from) || !hasPort(to)) return null
-
- // A physical port takes one cable.
- const taken = (ref: CableDraft) =>
- cables.some(
- (c) =>
- (c.from.deviceId === ref.deviceId && c.from.portId === ref.portId) ||
- (c.to.deviceId === ref.deviceId && c.to.portId === ref.portId),
- )
- if (taken(from) || taken(to)) return null
-
- // Fibre vs copper follows the port the patch starts from.
- const fromPort = devices
- .find((d) => d.id === from.deviceId)!
- .ports.find((p) => p.id === from.portId)!
- const type = options?.type ?? PORT_CABLE_TYPE[fromPort.type]
- const cable: Cable = {
- id: generateUUID(),
- type,
- color: options?.color ?? CABLE_COLORS[type],
- label: options?.label,
- from,
- to,
- }
- set((s) => ({ cables: [...s.cables, cable] }))
- return cable.id
- },
-
- updateCable: (id, patch) =>
- set((s) => ({ cables: s.cables.map((c) => (c.id === id ? { ...c, ...patch } : c)) })),
-
- removeCable: (id) => set((s) => ({ cables: s.cables.filter((c) => c.id !== id) })),
-
- importCablesFromNetwork: () => {
- const { devices, networkImportDone } = get()
- if (networkImportDone) return 0
-
- let created = 0
- for (const hint of networkEdgeHints()) {
- const a = devices.find((d) => d.nodeId === hint.from)
- const b = devices.find((d) => d.nodeId === hint.to)
- if (!a || !b) continue
- const usedPorts = new Set(
- get().cables.flatMap((c) => [
- `${c.from.deviceId}:${c.from.portId}`,
- `${c.to.deviceId}:${c.to.portId}`,
- ]),
- )
- const freePort = (device: typeof a) =>
- device.ports.find((p) => !usedPorts.has(`${device.id}:${p.id}`))
- const pa = freePort(a)
- const pb = freePort(b)
- if (!pa || !pb) continue
- const id = get().addCable(
- { deviceId: a.id, portId: pa.id },
- { deviceId: b.id, portId: pb.id },
- { type: hint.type, label: hint.label },
- )
- if (id) created++
- }
- set({ networkImportDone: true })
- return created
- },
-
- // --- UI -----------------------------------------------------------------
- selectDevice: (id) => set({ selectedDeviceId: id, selectedRackId: null }),
- selectRack: (id) => set({ selectedRackId: id, selectedDeviceId: null }),
- hoverDevice: (id) => set({ hoveredDeviceId: id }),
- setCableVisibility: (v) => set({ cableVisibility: v }),
- setCableTypeFilter: (t) => set({ cableTypeFilter: t }),
-
- toggleCableMode: () =>
- set((s) => ({
- cableMode: !s.cableMode,
- cableDraft: null,
- cableVisibility: !s.cableMode ? 'always' : s.cableVisibility,
- })),
-
- pickPort: (deviceId, portId) => {
- const { cableDraft } = get()
- if (!cableDraft) {
- set({ cableDraft: { deviceId, portId } })
- return
- }
- get().addCable(cableDraft, { deviceId, portId })
- set({ cableDraft: null })
- },
-
- cancelCableDraft: () => set({ cableDraft: null }),
-
- reset: () => set(initialState()),
-}))
+ edit((s) => ({ cables: [...s.cables, cable] }))
+ return cable.id
+ },
+
+ updateCable: (id, patch) =>
+ edit((s) => ({ cables: s.cables.map((c) => (c.id === id ? { ...c, ...patch } : c)) })),
+
+ removeCable: (id) => edit((s) => ({ cables: s.cables.filter((c) => c.id !== id) })),
+
+ importCablesFromNetwork: (hints) => {
+ const { devices, networkImportDone } = get()
+ if (networkImportDone) return 0
+
+ let created = 0
+ for (const hint of hints) {
+ const a = devices.find((d) => d.nodeId === hint.from)
+ const b = devices.find((d) => d.nodeId === hint.to)
+ if (!a || !b) continue
+ const usedPorts = new Set(
+ get().cables.flatMap((c) => [
+ `${c.from.deviceId}:${c.from.portId}`,
+ `${c.to.deviceId}:${c.to.portId}`,
+ ]),
+ )
+ const freePort = (device: typeof a) =>
+ device.ports.find((p) => !usedPorts.has(`${device.id}:${p.id}`))
+ const pa = freePort(a)
+ const pb = freePort(b)
+ if (!pa || !pb) continue
+ const id = get().addCable(
+ { deviceId: a.id, portId: pa.id },
+ { deviceId: b.id, portId: pb.id },
+ { type: hint.type, label: hint.label },
+ )
+ if (id) created++
+ }
+ set({ networkImportDone: true })
+ return created
+ },
+
+ // --- UI -----------------------------------------------------------------
+ // Pan/zoom is persisted, but nudging the view is not an edit worth a Save
+ // badge — the logical canvas treats the viewport the same way.
+ setViewport: (v) => set({ viewport: v }),
+ selectDevice: (id) => set({ selectedDeviceId: id, selectedRackId: null }),
+ selectRack: (id) => set({ selectedRackId: id, selectedDeviceId: null }),
+ hoverDevice: (id) => set({ hoveredDeviceId: id }),
+ setCableVisibility: (v) => set({ cableVisibility: v }),
+ setCableTypeFilter: (t) => set({ cableTypeFilter: t }),
+
+ toggleCableMode: () =>
+ set((s) => ({
+ cableMode: !s.cableMode,
+ cableDraft: null,
+ cableVisibility: !s.cableMode ? 'always' : s.cableVisibility,
+ })),
+
+ pickPort: (deviceId, portId) => {
+ const { cableDraft } = get()
+ if (!cableDraft) {
+ set({ cableDraft: { deviceId, portId } })
+ return
+ }
+ get().addCable(cableDraft, { deviceId, portId })
+ set({ cableDraft: null })
+ },
+
+ cancelCableDraft: () => set({ cableDraft: null }),
+
+ loadDemo: () => {
+ const devices = demoDevices()
+ set({
+ ...emptyState(),
+ designId: get().designId,
+ racks: demoRacks(),
+ devices,
+ cables: demoCables(),
+ inventory: withRackedFlags(demoInventory(), devices),
+ hasUnsavedChanges: true,
+ })
+ },
+
+ reset: () => set(emptyState()),
+ }
+})
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 9df87f4..c234a26 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -1,4 +1,13 @@
-export type DesignType = 'network' | 'electrical'
+export * from './rack'
+
+/**
+ * `network` and `electrical` render the same React Flow canvas and differ only
+ * by palette and node set. `rack` is a different renderer entirely (racks,
+ * mounted gear, port-to-port patching), so `App` branches on this.
+ *
+ * Kept in sync with DESIGN_TYPES in backend/app/schemas/designs.py.
+ */
+export type DesignType = 'network' | 'electrical' | 'rack'
export interface Design {
id: string
diff --git a/frontend/src/rack/types.ts b/frontend/src/types/rack.ts
similarity index 78%
rename from frontend/src/rack/types.ts
rename to frontend/src/types/rack.ts
index 86a7c7f..72dd0d8 100644
--- a/frontend/src/rack/types.ts
+++ b/frontend/src/types/rack.ts
@@ -1,8 +1,9 @@
/**
- * Rack canvas prototype — domain types.
+ * Rack canvas — domain types.
*
- * Front-only UX prototype. Nothing here is persisted server-side yet; the
- * shapes are meant to be lifted into `@/types` once the UX is validated.
+ * A rack canvas is a design of `design_type: 'rack'`. These camelCase shapes are
+ * what the store and components work with; `@/utils/rackSerializer` maps them to
+ * and from the snake_case API payloads.
*/
/** Horizontal grid inside a rack. 12 columns = full width, 6 = half, 4 = third. */
@@ -119,8 +120,17 @@ export interface RackDevice {
id: string
rackId: string
/**
- * Inventory node id this mount represents. Null for accessories (blank
+ * Device Inventory entry this mount represents. Null for accessories (blank
* panels, shelves) that exist only in the rack view.
+ *
+ * Unmounting never deletes the inventory entry — the inventory outlives both
+ * the rack mount and any canvas node, which is the whole point of keying on it.
+ */
+ deviceId: string | null
+ /**
+ * Logical-canvas node for the same hardware, when one exists. Read-only here:
+ * resolved by the backend from the inventory entry, used for live status and
+ * for seeding cables from the network design's edges.
*/
nodeId: string | null
label: string
@@ -156,28 +166,28 @@ export interface Cable {
export type CableVisibility = 'hover' | 'always' | 'hidden'
// ---------------------------------------------------------------------------
-// Inventory (fake, prototype only)
+// Inventory
// ---------------------------------------------------------------------------
-/** Subset of the network inventory that can physically live in a rack. */
-export type RackableNodeType =
- | 'server'
- | 'proxmox'
- | 'switch'
- | 'router'
- | 'firewall'
- | 'nas'
- | 'ups'
- | 'patch_panel'
- | 'pdu'
- | 'generic'
-
+/**
+ * A Device Inventory entry offered to the rack tray.
+ *
+ * Sourced from the backend's `pending_devices` — the same list the Device
+ * Inventory panel shows. Entries survive approval and node deletion, so racking
+ * and unracking never mutates them.
+ */
export interface InventoryDevice {
id: string
label: string
- type: RackableNodeType
- ip?: string
+ /** `suggested_type` from discovery; free-form, may be unknown to the UI. */
+ type: string | null
+ ip?: string | null
+ /** Live status of the matching canvas node, `unknown` when there is none. */
status: DeviceStatus
+ /** Matching canvas node, when the device is on a logical canvas. */
+ nodeId: string | null
+ /** Already mounted somewhere in this rack design. */
+ racked: boolean
/** Faceplate proposed when the device is dropped into a rack. */
suggestedFaceplateId: string
}
diff --git a/frontend/src/utils/__tests__/rackSerializer.test.ts b/frontend/src/utils/__tests__/rackSerializer.test.ts
new file mode 100644
index 0000000..ab46867
--- /dev/null
+++ b/frontend/src/utils/__tests__/rackSerializer.test.ts
@@ -0,0 +1,214 @@
+import { describe, it, expect } from 'vitest'
+import {
+ buildSavePayload,
+ fromCable,
+ fromRack,
+ fromRackDevice,
+ toCable,
+ toInventoryDevice,
+ toRack,
+ toRackDevice,
+ type ApiRack,
+ type ApiRackCable,
+ type ApiRackDevice,
+} from '../rackSerializer'
+import { DEFAULT_RACK_STYLE } from '@/rack/rackDefaults'
+import type { Cable, Rack, RackDevice } from '@/types'
+
+const apiRack: ApiRack = {
+ id: 'r1',
+ design_id: 'd1',
+ name: 'Main',
+ u_height: 24,
+ width_standard: '10',
+ numbering: 'top-down',
+ location: 'garage',
+ style: { frame: '#111111', showNumbers: false },
+ pos_x: 40,
+ pos_y: 60,
+}
+
+const apiDevice: ApiRackDevice = {
+ id: 'dev1',
+ design_id: 'd1',
+ rack_id: 'r1',
+ device_id: 'inv1',
+ node_id: 'node1',
+ label: 'sw-24',
+ u_start: 10,
+ u_height: 1,
+ col_start: 0,
+ col_span: 12,
+ faceplate_id: 'switch-24',
+ color: null,
+ status: 'online',
+ ports: [{ id: 'p1', label: '1', type: 'sfp+', x: 0.4, y: 0.5 }],
+}
+
+const apiCable: ApiRackCable = {
+ id: 'c1',
+ design_id: 'd1',
+ from_device_id: 'dev1',
+ from_port_id: 'p1',
+ to_device_id: 'dev2',
+ to_port_id: 'p2',
+ type: 'fiber',
+ color: '#f0a500',
+ label: 'SAN',
+}
+
+describe('API → domain', () => {
+ it('maps a rack, nesting the position', () => {
+ const rack = toRack(apiRack)
+ expect(rack).toMatchObject({
+ id: 'r1',
+ uHeight: 24,
+ widthStandard: '10',
+ numbering: 'top-down',
+ location: 'garage',
+ position: { x: 40, y: 60 },
+ })
+ })
+
+ it('fills style keys the server never wrote', () => {
+ const { style } = toRack(apiRack)
+ expect(style.frame).toBe('#111111')
+ expect(style.showNumbers).toBe(false)
+ expect(style.rail).toBe(DEFAULT_RACK_STYLE.rail)
+ expect(style.enclosed).toBe(DEFAULT_RACK_STYLE.enclosed)
+ })
+
+ it('falls back on unknown enum values rather than trusting the wire', () => {
+ const rack = toRack({ ...apiRack, width_standard: '23', numbering: 'sideways' })
+ expect(rack.widthStandard).toBe('19')
+ expect(rack.numbering).toBe('bottom-up')
+ })
+
+ it('maps a device with both inventory and node links', () => {
+ const device = toRackDevice(apiDevice)
+ expect(device).toMatchObject({
+ rackId: 'r1',
+ deviceId: 'inv1',
+ nodeId: 'node1',
+ uStart: 10,
+ faceplateId: 'switch-24',
+ status: 'online',
+ })
+ expect(device.ports[0].type).toBe('sfp+')
+ })
+
+ it('drops ports that are not usable and defaults unknown port types', () => {
+ const device = toRackDevice({
+ ...apiDevice,
+ ports: [null, { label: 'no id' }, { id: 'p9', type: 'usb', x: 0.1, y: 0.2 }],
+ })
+ expect(device.ports).toHaveLength(1)
+ expect(device.ports[0]).toMatchObject({ id: 'p9', label: 'p9', type: 'rj45' })
+ })
+
+ it('treats an unknown device status as unknown', () => {
+ expect(toRackDevice({ ...apiDevice, status: 'exploded' }).status).toBe('unknown')
+ })
+
+ it('maps a cable into nested endpoints', () => {
+ expect(toCable(apiCable)).toMatchObject({
+ type: 'fiber',
+ label: 'SAN',
+ from: { deviceId: 'dev1', portId: 'p1' },
+ to: { deviceId: 'dev2', portId: 'p2' },
+ })
+ })
+
+ it('takes inventory status from the linked node, not the inventory row', () => {
+ const item = toInventoryDevice({
+ id: 'inv1',
+ label: 'nas',
+ suggested_type: 'nas',
+ ip: '192.168.1.9',
+ status: 'approved',
+ discovery_source: 'arp',
+ node_id: 'node1',
+ node_status: 'online',
+ racked: false,
+ })
+ expect(item.status).toBe('online')
+ expect(item.nodeId).toBe('node1')
+ expect(item.suggestedFaceplateId).toBe('nas-2u')
+ })
+
+ it('leaves an inventory entry with no canvas node as unknown', () => {
+ const item = toInventoryDevice({
+ id: 'inv2',
+ label: 'patch panel',
+ suggested_type: null,
+ ip: null,
+ status: 'pending',
+ discovery_source: 'manual',
+ node_id: null,
+ node_status: null,
+ racked: true,
+ })
+ expect(item.status).toBe('unknown')
+ expect(item.racked).toBe(true)
+ })
+})
+
+describe('domain → API', () => {
+ it('round-trips a rack', () => {
+ expect(fromRack(toRack(apiRack))).toMatchObject({
+ id: 'r1',
+ u_height: 24,
+ width_standard: '10',
+ pos_x: 40,
+ pos_y: 60,
+ })
+ })
+
+ it('round-trips a device', () => {
+ const back = fromRackDevice(toRackDevice(apiDevice))
+ expect(back).toMatchObject({ id: 'dev1', rack_id: 'r1', device_id: 'inv1', u_start: 10 })
+ })
+
+ it('round-trips a cable', () => {
+ expect(fromCable(toCable(apiCable))).toMatchObject({
+ from_device_id: 'dev1',
+ to_port_id: 'p2',
+ type: 'fiber',
+ })
+ })
+
+ it('clamps a device back into the column grid', () => {
+ const device = { ...toRackDevice(apiDevice), colStart: 99, colSpan: 99 }
+ const back = fromRackDevice(device)
+ expect(back.col_start).toBe(11)
+ expect(back.col_span).toBe(12)
+ })
+})
+
+describe('buildSavePayload', () => {
+ const rack: Rack = toRack(apiRack)
+ const device: RackDevice = toRackDevice(apiDevice)
+ const viewport = { x: 1, y: 2, zoom: 1.5 }
+
+ it('carries racks, devices, cables and the viewport', () => {
+ const other: RackDevice = { ...device, id: 'dev2', ports: [{ id: 'p2', label: '2', type: 'rj45', x: 0.5, y: 0.5 }] }
+ const cable: Cable = toCable(apiCable)
+ const payload = buildSavePayload('d1', [rack], [device, other], [cable], viewport)
+ expect(payload.design_id).toBe('d1')
+ expect(payload.devices).toHaveLength(2)
+ expect(payload.cables).toHaveLength(1)
+ expect(payload.viewport).toEqual(viewport)
+ })
+
+ it('drops devices whose rack is gone, and the cables that hung off them', () => {
+ const orphan: RackDevice = { ...device, id: 'dev2', rackId: 'gone' }
+ const cable: Cable = {
+ ...toCable(apiCable),
+ to: { deviceId: 'dev2', portId: 'p2' },
+ }
+ const payload = buildSavePayload('d1', [rack], [device, orphan], [cable], viewport)
+ expect(payload.devices.map((d) => d.id)).toEqual(['dev1'])
+ // The backend rejects dangling cables, so they must not reach it.
+ expect(payload.cables).toEqual([])
+ })
+})
diff --git a/frontend/src/utils/rackSerializer.ts b/frontend/src/utils/rackSerializer.ts
new file mode 100644
index 0000000..744e47c
--- /dev/null
+++ b/frontend/src/utils/rackSerializer.ts
@@ -0,0 +1,285 @@
+/**
+ * Maps between the rack API payloads (snake_case, flat) and the domain shapes
+ * the rack store works with (camelCase, nested position/endpoints).
+ *
+ * Mirrors what `canvasSerializer` does for nodes and edges.
+ */
+import { DEFAULT_RACK_STYLE, PORT_CABLE_TYPE, CABLE_COLORS } from '@/rack/rackDefaults'
+import { suggestFaceplate } from '@/rack/faceplates'
+import { RACK_COLUMNS } from '@/types'
+import type {
+ Cable,
+ CableType,
+ DeviceStatus,
+ InventoryDevice,
+ Port,
+ PortType,
+ Rack,
+ RackDevice,
+ RackNumbering,
+ RackStyle,
+ RackWidthStandard,
+} from '@/types'
+
+// ── API shapes ───────────────────────────────────────────────────────────────
+
+export interface ApiRack {
+ id: string
+ design_id: string
+ name: string
+ u_height: number
+ width_standard: string
+ numbering: string
+ location: string | null
+ style: Record<string, unknown>
+ pos_x: number
+ pos_y: number
+}
+
+export interface ApiRackDevice {
+ id: string
+ design_id: string
+ rack_id: string
+ device_id: string | null
+ node_id: string | null
+ label: string
+ u_start: number
+ u_height: number
+ col_start: number
+ col_span: number
+ faceplate_id: string
+ color: string | null
+ status: string
+ ports: unknown[]
+}
+
+export interface ApiRackCable {
+ id: string
+ design_id: string
+ from_device_id: string
+ from_port_id: string
+ to_device_id: string
+ to_port_id: string
+ type: string
+ color: string
+ label: string | null
+}
+
+export interface ApiRackState {
+ racks: ApiRack[]
+ devices: ApiRackDevice[]
+ cables: ApiRackCable[]
+ viewport: { x?: number; y?: number; zoom?: number }
+}
+
+export interface ApiInventoryItem {
+ id: string
+ label: string
+ suggested_type: string | null
+ ip: string | null
+ status: string
+ discovery_source: string | null
+ node_id: string | null
+ node_status: string | null
+ racked: boolean
+}
+
+export interface RackSavePayload {
+ design_id: string
+ racks: Omit<ApiRack, 'design_id'>[]
+ devices: Omit<ApiRackDevice, 'design_id'>[]
+ cables: Omit<ApiRackCable, 'design_id'>[]
+ viewport: { x: number; y: number; zoom: number }
+}
+
+// ── Narrowing ────────────────────────────────────────────────────────────────
+
+const WIDTH_STANDARDS: RackWidthStandard[] = ['19', '10']
+const NUMBERINGS: RackNumbering[] = ['bottom-up', 'top-down']
+const PORT_TYPES: PortType[] = ['rj45', 'sfp', 'sfp+']
+const DEVICE_STATUSES: DeviceStatus[] = ['online', 'offline', 'unknown']
+
+function asWidthStandard(v: string): RackWidthStandard {
+ return (WIDTH_STANDARDS as string[]).includes(v) ? (v as RackWidthStandard) : '19'
+}
+
+function asNumbering(v: string): RackNumbering {
+ return (NUMBERINGS as string[]).includes(v) ? (v as RackNumbering) : 'bottom-up'
+}
+
+function asStatus(v: string | null): DeviceStatus {
+ return (DEVICE_STATUSES as (string | null)[]).includes(v) ? (v as DeviceStatus) : 'unknown'
+}
+
+/** Style is free-form JSON on the wire; fill any key the server never wrote. */
+function asStyle(raw: Record<string, unknown>): RackStyle {
+ const pick = (key: keyof RackStyle) => raw[key]
+ return {
+ frame: typeof pick('frame') === 'string' ? (raw.frame as string) : DEFAULT_RACK_STYLE.frame,
+ rail: typeof pick('rail') === 'string' ? (raw.rail as string) : DEFAULT_RACK_STYLE.rail,
+ interior:
+ typeof pick('interior') === 'string' ? (raw.interior as string) : DEFAULT_RACK_STYLE.interior,
+ showNumbers:
+ typeof pick('showNumbers') === 'boolean'
+ ? (raw.showNumbers as boolean)
+ : DEFAULT_RACK_STYLE.showNumbers,
+ enclosed:
+ typeof pick('enclosed') === 'boolean' ? (raw.enclosed as boolean) : DEFAULT_RACK_STYLE.enclosed,
+ }
+}
+
+/** Ports round-trip as opaque JSON; drop anything that is not a usable port. */
+function asPorts(raw: unknown[]): Port[] {
+ const ports: Port[] = []
+ for (const entry of raw) {
+ if (!entry || typeof entry !== 'object') continue
+ const p = entry as Record<string, unknown>
+ if (typeof p.id !== 'string') continue
+ const type = typeof p.type === 'string' && (PORT_TYPES as string[]).includes(p.type)
+ ? (p.type as PortType)
+ : 'rj45'
+ ports.push({
+ id: p.id,
+ label: typeof p.label === 'string' ? p.label : p.id,
+ type,
+ x: typeof p.x === 'number' ? p.x : 0.5,
+ y: typeof p.y === 'number' ? p.y : 0.5,
+ })
+ }
+ return ports
+}
+
+// ── API → domain ─────────────────────────────────────────────────────────────
+
+export function toRack(api: ApiRack): Rack {
+ return {
+ id: api.id,
+ name: api.name,
+ uHeight: api.u_height,
+ widthStandard: asWidthStandard(api.width_standard),
+ numbering: asNumbering(api.numbering),
+ style: asStyle(api.style ?? {}),
+ location: api.location ?? undefined,
+ position: { x: api.pos_x, y: api.pos_y },
+ }
+}
+
+export function toRackDevice(api: ApiRackDevice): RackDevice {
+ return {
+ id: api.id,
+ rackId: api.rack_id,
+ deviceId: api.device_id,
+ nodeId: api.node_id,
+ label: api.label,
+ uStart: api.u_start,
+ uHeight: api.u_height,
+ colStart: api.col_start,
+ colSpan: api.col_span,
+ faceplateId: api.faceplate_id,
+ color: api.color ?? undefined,
+ status: asStatus(api.status),
+ ports: asPorts(api.ports ?? []),
+ }
+}
+
+export function toCable(api: ApiRackCable): Cable {
+ const type: CableType = api.type === 'fiber' ? 'fiber' : 'ethernet'
+ return {
+ id: api.id,
+ type,
+ color: api.color || CABLE_COLORS[type],
+ label: api.label ?? undefined,
+ from: { deviceId: api.from_device_id, portId: api.from_port_id },
+ to: { deviceId: api.to_device_id, portId: api.to_port_id },
+ }
+}
+
+export function toInventoryDevice(api: ApiInventoryItem): InventoryDevice {
+ return {
+ id: api.id,
+ label: api.label,
+ type: api.suggested_type,
+ ip: api.ip,
+ // The inventory row itself is only pending/approved; live status comes from
+ // the linked canvas node, if any.
+ status: asStatus(api.node_status),
+ nodeId: api.node_id,
+ racked: api.racked,
+ suggestedFaceplateId: suggestFaceplate(api.suggested_type),
+ }
+}
+
+// ── Domain → API ─────────────────────────────────────────────────────────────
+
+export function fromRack(rack: Rack): Omit<ApiRack, 'design_id'> {
+ return {
+ id: rack.id,
+ name: rack.name,
+ u_height: rack.uHeight,
+ width_standard: rack.widthStandard,
+ numbering: rack.numbering,
+ location: rack.location ?? null,
+ style: { ...rack.style },
+ pos_x: rack.position.x,
+ pos_y: rack.position.y,
+ }
+}
+
+export function fromRackDevice(device: RackDevice): Omit<ApiRackDevice, 'design_id'> {
+ return {
+ id: device.id,
+ rack_id: device.rackId,
+ device_id: device.deviceId,
+ node_id: device.nodeId,
+ label: device.label,
+ u_start: device.uStart,
+ u_height: device.uHeight,
+ col_start: Math.min(Math.max(device.colStart, 0), RACK_COLUMNS - 1),
+ col_span: Math.min(Math.max(device.colSpan, 1), RACK_COLUMNS),
+ faceplate_id: device.faceplateId,
+ color: device.color ?? null,
+ status: device.status,
+ ports: device.ports,
+ }
+}
+
+export function fromCable(cable: Cable): Omit<ApiRackCable, 'design_id'> {
+ return {
+ id: cable.id,
+ from_device_id: cable.from.deviceId,
+ from_port_id: cable.from.portId,
+ to_device_id: cable.to.deviceId,
+ to_port_id: cable.to.portId,
+ type: cable.type,
+ color: cable.color || CABLE_COLORS[cable.type],
+ label: cable.label ?? null,
+ }
+}
+
+export function buildSavePayload(
+ designId: string,
+ racks: Rack[],
+ devices: RackDevice[],
+ cables: Cable[],
+ viewport: { x: number; y: number; zoom: number },
+): RackSavePayload {
+ const rackIds = new Set(racks.map((r) => r.id))
+ const keptDevices = devices.filter((d) => rackIds.has(d.rackId))
+ const deviceIds = new Set(keptDevices.map((d) => d.id))
+ return {
+ design_id: designId,
+ racks: racks.map(fromRack),
+ devices: keptDevices.map(fromRackDevice),
+ // The backend rejects a cable whose endpoints are not in the payload, so
+ // drop dangling ones here rather than failing the whole save.
+ cables: cables
+ .filter((c) => deviceIds.has(c.from.deviceId) && deviceIds.has(c.to.deviceId))
+ .map(fromCable),
+ viewport,
+ }
+}
+
+/** Cable type implied by the port a patch starts from. */
+export function cableTypeForPort(type: PortType): CableType {
+ return PORT_CABLE_TYPE[type]
+}
diff --git a/frontend/src/utils/standaloneStorage.ts b/frontend/src/utils/standaloneStorage.ts
index 2cb629e..31b1e76 100644
--- a/frontend/src/utils/standaloneStorage.ts
+++ b/frontend/src/utils/standaloneStorage.ts
@@ -5,19 +5,44 @@
* persisted directly to localStorage:
* - `homelable_designs` → Design[] (the canvas list)
* - `homelable_canvas:<id>` → { nodes, edges, theme_id, custom_style } per design
+ * - `homelable_rack:<id>` → { racks, devices, cables, viewport } per rack design
*
* Legacy single-canvas installs stored everything under `homelable_canvas`
* (no per-design key, no design list). `ensureSeed()` migrates that data into a
* default design on first run so existing users keep their canvas.
*/
import type { Node, Edge } from '@xyflow/react'
-import type { Design, DesignType, NodeData, EdgeData, CustomStyleDef } from '@/types'
+import type {
+ Cable,
+ CustomStyleDef,
+ Design,
+ DesignType,
+ EdgeData,
+ InventoryDevice,
+ NodeData,
+ Rack,
+ RackDevice,
+} from '@/types'
import type { ThemeId } from '@/utils/themes'
import { generateUUID } from '@/utils/uuid'
const DESIGNS_KEY = 'homelable_designs'
const LEGACY_CANVAS_KEY = 'homelable_canvas'
+const RACK_KEY = 'homelable_rack'
const canvasKey = (designId: string) => `${LEGACY_CANVAS_KEY}:${designId}`
+const rackKey = (designId: string) => `${RACK_KEY}:${designId}`
+
+export interface StandaloneRackCanvas {
+ racks: Rack[]
+ devices: RackDevice[]
+ cables: Cable[]
+ viewport?: { x: number; y: number; zoom: number }
+ /**
+ * Inventory entries created from the rack canvas. Standalone has no
+ * `pending_devices` table, so hardware documented here lives with the canvas.
+ */
+ inventory: InventoryDevice[]
+}
export interface StandaloneCanvas {
nodes: Node<NodeData>[]
@@ -115,13 +140,18 @@ export function listDesignsWithCounts(): Design[] {
/** Deep-copy a design's canvas into a new design. Returns the new design. */
export function copyDesign(sourceId: string, name: string, icon?: string | null): Design {
- const design = createDesign(name, icon)
+ const sourceType = listDesigns().find((d) => d.id === sourceId)?.design_type ?? 'network'
+ const design = createDesign(name, icon, sourceType)
const source = loadCanvas(sourceId)
if (source) {
// localStorage canvas already stores React Flow nodes/edges by value; a fresh
// JSON round-trip is enough to detach the copy from the source.
saveCanvas(design.id, JSON.parse(JSON.stringify(source)) as StandaloneCanvas)
}
+ const sourceRack = loadRackCanvas(sourceId)
+ if (sourceRack) {
+ saveRackCanvas(design.id, JSON.parse(JSON.stringify(sourceRack)) as StandaloneRackCanvas)
+ }
return design
}
@@ -138,6 +168,16 @@ export function updateDesign(id: string, patch: Partial<Pick<Design, 'name' | 'i
export function deleteDesign(id: string): void {
writeDesigns(listDesigns().filter((d) => d.id !== id))
localStorage.removeItem(canvasKey(id))
+ localStorage.removeItem(rackKey(id))
+}
+
+/** Load a design's rack canvas. Returns null when it has never been saved. */
+export function loadRackCanvas(designId: string): StandaloneRackCanvas | null {
+ return readJSON<StandaloneRackCanvas>(rackKey(designId))
+}
+
+export function saveRackCanvas(designId: string, data: StandaloneRackCanvas): void {
+ localStorage.setItem(rackKey(designId), JSON.stringify(data))
}
/** Load a design's canvas. Returns null when the design has never been saved. */