Compare commits
35 Commits
mai/picass
...
mai/escher
| Author | SHA1 | Date | |
|---|---|---|---|
| a675c499c3 | |||
| 78bce498b4 | |||
| 359ed892ac | |||
| 0ecd9c8b4a | |||
| fca9fb0a0f | |||
| 40ab3d2630 | |||
| 17e6b5e91c | |||
| 9107a9f7b2 | |||
| 89686d0c1f | |||
| 57a9154f18 | |||
| 6c31802522 | |||
| 46e8474c2b | |||
| 9aa395854d | |||
| f08c48e9b5 | |||
| 6cd5925f4c | |||
| 9773063008 | |||
| 61bc1dcf43 | |||
| 056777f1c1 | |||
| 2aff5eb04d | |||
| 5c11bf33cb | |||
| 86264d1284 | |||
| b28fc0c565 | |||
| 491db730eb | |||
| 90157dfd14 | |||
| f1af2820e1 | |||
| 3276cfeb17 | |||
| 82cf5a3052 | |||
| 5d055ad521 | |||
| 93b276875e | |||
| 205e9eab26 | |||
| fe6f86593e | |||
| a7835468a1 | |||
| 8a6e8c8406 | |||
| 275cb5a55a | |||
| a81dbe2f8c |
@@ -15,7 +15,7 @@ data
|
||||
|
||||
# Build artefacts
|
||||
bin
|
||||
mcables
|
||||
/mcables
|
||||
|
||||
# Editor cruft
|
||||
.vscode
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -8,7 +8,7 @@ data/*.db-shm
|
||||
|
||||
# Build artefacts
|
||||
bin/
|
||||
mcables
|
||||
/mcables
|
||||
|
||||
# Editor
|
||||
.vscode/
|
||||
|
||||
@@ -43,8 +43,9 @@ JSON API under `/api/`. SQLite lives at `./data/mcables.db` by default.
|
||||
|---|---|---|
|
||||
| `MCABLES_ADDR` | `0.0.0.0:7777` | Listen address. |
|
||||
| `MCABLES_DB` | `./data/mcables.db` | SQLite path. Parent dir is created on boot. |
|
||||
| `MEXDRAW_BASE_URL` | (unset) | Used by slice 5 export — not consumed yet. |
|
||||
| `MEXDRAW_TOKEN` | (unset) | Bearer for the mExDraw export. Not consumed yet. |
|
||||
| `MEXDRAW_BASE_URL` | `https://mxdrw.msbls.de` | Base URL for mExDraw export. |
|
||||
| `MEXDRAW_USER` | (unset) | Username for the mxdrw HTTP Basic Auth on export. Required. |
|
||||
| `MEXDRAW_PASS` | (unset) | Password for the mxdrw HTTP Basic Auth on export. Required. |
|
||||
|
||||
### Tests
|
||||
|
||||
|
||||
64
cmd/mcables/main.go
Normal file
64
cmd/mcables/main.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mgit.msbls.de/m/mcables/internal/db"
|
||||
"mgit.msbls.de/m/mcables/internal/server"
|
||||
"mgit.msbls.de/m/mcables/web"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := envOr("MCABLES_ADDR", "0.0.0.0:7777")
|
||||
dbPath := envOr("MCABLES_DB", "./data/mcables.db")
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil {
|
||||
log.Fatalf("mkdir data dir: %v", err)
|
||||
}
|
||||
|
||||
store, err := db.Open(dbPath)
|
||||
if err != nil {
|
||||
log.Fatalf("open db: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
if err := db.Migrate(store.DB()); err != nil {
|
||||
log.Fatalf("migrate: %v", err)
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: server.New(store, web.Static()),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
go func() {
|
||||
log.Printf("mcables listening on %s (db=%s)", addr, dbPath)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("listen: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
<-stop
|
||||
log.Printf("shutting down")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(ctx)
|
||||
}
|
||||
|
||||
func envOr(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -14,7 +14,7 @@ services:
|
||||
- MCABLES_ADDR=0.0.0.0:7777
|
||||
- MCABLES_DB=/app/data/mcables.db
|
||||
env_file:
|
||||
# Empty for slice 1. MEXDRAW_TOKEN lands here when slice 5 ships.
|
||||
# MEXDRAW_USER + MEXDRAW_PASS for the mxdrw HTTP Basic Auth on export.
|
||||
- /home/m/secrets/mcables/.env
|
||||
volumes:
|
||||
- /home/m/stacks/mcables/data:/app/data
|
||||
|
||||
250
docs/design.md
250
docs/design.md
@@ -453,18 +453,26 @@ Office setup template:
|
||||
| fritz | network | Power × 1; RJ45 × 4 |
|
||||
| ChromeCast | display | Power × 1; HDMI × 1 |
|
||||
| SteamLink | compute | Power × 1; HDMI × 1; USB × 2 |
|
||||
| IOx-3 | hub | Power × 1; (3× port slots — concrete cable type per slot is set at instantiation; defaults to USB × 3 for v0) |
|
||||
| IOx-6 | hub | Power × 1; USB × 6 |
|
||||
| IOx-8 | hub | Power × 1; USB × 8 |
|
||||
| IOx-3 | hub | Power In × 1 (top/back); Power Out × 3 (bottom/front) |
|
||||
| IOx-6 | hub | Power In × 1 (top/back); Power Out × 6 (bottom/front) |
|
||||
| IOx-8 | hub | Power In × 1 (top/back); Power Out × 8 (bottom/front) |
|
||||
| **Screen** | display | Power × 1; HDMI × 1 |
|
||||
| **Keyboard** | accessory | USB × 1 |
|
||||
| **Mouse** | accessory | USB × 1 |
|
||||
| **Multi-plug 3** | hub | Power In × 1 (top/back); Power Out × 3 (bottom/front) |
|
||||
| **Multi-plug 4** | hub | Power In × 1 (top/back); Power Out × 4 (bottom/front) |
|
||||
| **Multi-plug 5** | hub | Power In × 1 (top/back); Power Out × 5 (bottom/front) |
|
||||
| **Multi-plug 6** | hub | Power In × 1 (top/back); Power Out × 6 (bottom/front) |
|
||||
| **Wifi-plug** | accessory | Power In × 1 (top/back); Power Out × 1 (bottom/front) — pass-through outlet |
|
||||
|
||||
"Hub" devices like IOx-* have ambiguous port profiles (the seed drawing
|
||||
shows them in red because most carry Power, but they also hub USB). v0
|
||||
seeds them as USB hubs; m overrides per-instance. The catalog is editable
|
||||
in the UI (slice 4.5 — "Manage device types") so m can refine the IOx-3
|
||||
profile once and not re-override every instance.
|
||||
v5 (migration 005) added the Multi-plug 3–6 strips and the Wifi-plug
|
||||
pass-through outlet. v6 (migration 006) re-shaped the IOx-* and
|
||||
Multi-plug-* profiles to the "1 in on top / N out on bottom" layout —
|
||||
the IOx-* devices are physical power strips, not USB hubs (m's
|
||||
hardware), and the Multi-plug-* outputs are now visually distinct from
|
||||
the input. Convention: `top = back`, `bottom = front`. Existing device
|
||||
instances keep their already-seeded ports per §2.3 — to pick up the
|
||||
new layout, delete + re-create the instance.
|
||||
|
||||
m can also add **project-custom types** at any time (UI: "+ New device
|
||||
type" inside the device-create modal) with `project_id = current`.
|
||||
@@ -1430,4 +1438,228 @@ gitignored.
|
||||
|
||||
---
|
||||
|
||||
DESIGN v4.1 READY FOR REVIEW
|
||||
## 11. v5 — Cable routing via clamps
|
||||
|
||||
m's bundling primitive: a **clamp** is a physical anchor on the canvas
|
||||
(think cable tie / clip). A cable routes from its `from` endpoint,
|
||||
through zero or more clamps **in order**, to its `to` endpoint. Two
|
||||
cables that share an ordered pair of consecutive clamps are visibly
|
||||
bundled along that segment — no detection pass, no inference: the
|
||||
overlap *is* the bundle.
|
||||
|
||||
This replaces the abandoned waypoints + segment-detection approach.
|
||||
v0's straight-line schematic stays as the empty-clamps case
|
||||
(`cable_clamps` is empty for a fresh solver-emitted cable).
|
||||
|
||||
### 11.1 Schema (migration 007)
|
||||
|
||||
```sql
|
||||
CREATE TABLE clamps (
|
||||
id INTEGER PRIMARY KEY,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
x REAL NOT NULL,
|
||||
y REAL NOT NULL,
|
||||
label TEXT NOT NULL DEFAULT '',
|
||||
frame_id INTEGER REFERENCES frames(id) ON DELETE SET NULL,
|
||||
excalidraw_id TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
UNIQUE (project_id, excalidraw_id)
|
||||
);
|
||||
CREATE INDEX clamps_project_idx ON clamps(project_id);
|
||||
|
||||
CREATE TABLE cable_clamps (
|
||||
cable_id INTEGER NOT NULL REFERENCES cables(id) ON DELETE CASCADE,
|
||||
clamp_id INTEGER NOT NULL REFERENCES clamps(id) ON DELETE CASCADE,
|
||||
ord INTEGER NOT NULL, -- 1..N along from→to
|
||||
PRIMARY KEY (cable_id, ord),
|
||||
UNIQUE (cable_id, clamp_id) -- a cable can't visit the same clamp twice
|
||||
);
|
||||
CREATE INDEX cable_clamps_clamp_idx ON cable_clamps(clamp_id);
|
||||
```
|
||||
|
||||
`frame_id` on clamps mirrors devices + IO markers — m can put a clamp
|
||||
inside a frame and the frame-drag carries it.
|
||||
|
||||
`UNIQUE (cable_id, clamp_id)` blocks loops. `ord` is a small int, 1-based;
|
||||
nothing requires it to be contiguous (m can renumber 1, 2, 3 → 1, 3, 5
|
||||
during edits and the renderer is fine with that), but the UI keeps them
|
||||
contiguous on every mutation for sanity.
|
||||
|
||||
### 11.2 Cable rendering model
|
||||
|
||||
Each cable resolves to a polyline `[from-anchor, clamp₁, clamp₂, …, clampₙ, to-anchor]`
|
||||
where:
|
||||
- `from-anchor` / `to-anchor` come from the existing `anchorForEndpoint`
|
||||
resolver (port / device / IO).
|
||||
- clamp anchors are `(clamp.x, clamp.y)` directly — clamps don't have a
|
||||
width/height to centre.
|
||||
|
||||
For N=0 clamps the result is the v0 straight line. For N≥1 we render
|
||||
a `<polyline>` instead of a `<line>`.
|
||||
|
||||
The endpoint-replug handles from §10 (cable-replug) stay on the **first
|
||||
and last** vertices. Mid-polyline vertices get their own clamp-handle —
|
||||
small grab points only on the selected cable, which behave like
|
||||
clamp-detach when dragged onto empty canvas (drop a clamp off the
|
||||
cable's path).
|
||||
|
||||
### 11.3 Bundle visualisation — derived from shared segments
|
||||
|
||||
A **segment** is a directed pair `(A, B)` where A and B are consecutive
|
||||
nodes of a cable's polyline. Two cables share a segment when their
|
||||
polyline contains the same A→B (or B→A — segment matching is
|
||||
undirected).
|
||||
|
||||
For each segment, compute `cables[]` — the cables that traverse it.
|
||||
If `len(cables) ≥ 2`, render the segment as a single thick line on top
|
||||
of the individual ones:
|
||||
|
||||
- **Width**: `2 + N` px (N = cable count). Caps at ~12 px.
|
||||
- **Colour**: a striped pattern, one stripe per distinct cable type in
|
||||
the bundle, ordered by cable_type.id. SVG `<linearGradient>` with
|
||||
hard stops produces the stripe band cheaply; render it on a sibling
|
||||
`<polyline>` over the individual lines.
|
||||
- **Tooltip**: `<title>` child listing the cables ("Power · USB · HDMI").
|
||||
|
||||
At a clamp where ≥ 2 cables meet, the clamp icon (10×10 rounded square)
|
||||
shows a small count badge (`×N`) when N > 1. At fan-out points
|
||||
(endpoint with no clamp before it on the polyline) the individual
|
||||
coloured lines re-emerge, so m sees which port each strand goes to.
|
||||
|
||||
Shared-segment computation is O(C·N̄) where C = #cables and N̄ = average
|
||||
polyline length. For a v0-sized project (≤ ~30 cables, ≤ ~5 clamps per
|
||||
cable) this is trivial. We rebuild the segment map on every renderCanvas
|
||||
— no caching layer.
|
||||
|
||||
### 11.4 UI gestures
|
||||
|
||||
**+ Clamp tool (`C` shortcut, also a sidebar button):**
|
||||
- Click empty canvas → place a clamp at the cursor (POST `/clamps`).
|
||||
Standalone clamp — not on any cable yet.
|
||||
- Click a cable line → insert this clamp into that cable. The new clamp
|
||||
sits at the click position (snapped to the nearest point on the
|
||||
cable's polyline) and its `ord` is computed so it falls between the
|
||||
two existing vertices it lies between.
|
||||
|
||||
**Drag a cable's mid-segment:**
|
||||
- Pointerdown on a cable line (not on an endpoint handle) and drag.
|
||||
Live preview shows a bend at the cursor. Pointerup:
|
||||
- If the cursor is within snap-radius (~16 px) of an existing clamp:
|
||||
insert that clamp into the cable's polyline at the right `ord`.
|
||||
- Otherwise: create a fresh clamp at the release point and insert it.
|
||||
|
||||
**Clamp inspector** (selecting a clamp on the canvas):
|
||||
- Position (x, y editable + label)
|
||||
- "Cables through this clamp": list with each cable's two endpoints,
|
||||
click → select that cable
|
||||
- "Remove from this cable" (per row) → DELETE the matching cable_clamps
|
||||
row; cable's polyline collapses around the gap.
|
||||
- "Delete clamp" → cascade-removes from every cable_clamps row.
|
||||
|
||||
**Right-click on a clamp icon ON a cable** → "Remove from this cable"
|
||||
inline.
|
||||
|
||||
**Frame drag** carries clamps the same way it carries devices + IO
|
||||
markers (clamp.frame_id mirrors the existing pattern, drag handler
|
||||
already iterates frame-contained items).
|
||||
|
||||
### 11.5 Relationship to the existing `bundles` table
|
||||
|
||||
**Recommendation: keep `bundles` and `bundle_cables`, repurpose them.**
|
||||
|
||||
- Implicit/auto bundles → derived live from shared clamp segments. No
|
||||
DB rows. The §5 `GET /bundles/suggestions` endpoint stays useful as a
|
||||
"you might want to route these through the same clamps" hint.
|
||||
- Explicit named bundles → still in the `bundles` table. m names a
|
||||
group ("desk → wall trunk"), the UI offers "route all members through
|
||||
these clamps" as a one-click action. Useful for the case where m
|
||||
wants a stable label on a logical bundle that isn't yet routed.
|
||||
|
||||
Migration 007 leaves `bundles` + `bundle_cables` untouched. A v6 cleanup
|
||||
can drop them if m decides the explicit-named path isn't worth keeping.
|
||||
|
||||
### 11.6 Solver coupling
|
||||
|
||||
The v0 solver still emits **straight cables** — no clamp rows. m
|
||||
hand-routes after Solve. The solver's preview-diff is unaffected
|
||||
(solver compares endpoint pairs; clamp routing is independent of the
|
||||
endpoint identity).
|
||||
|
||||
Future v5.1: solver-suggested clamps based on shared paths between
|
||||
endpoint pairs. Out of scope here.
|
||||
|
||||
### 11.7 Export to mxdrw
|
||||
|
||||
Clamps map to small diamond elements (separate from IO markers — IO
|
||||
diamonds are red wall-outlets; clamps are grey routing points).
|
||||
`excalidraw_id` is stable across re-exports per the existing pattern.
|
||||
|
||||
Cable arrows become Excalidraw `arrow` elements with mid-points (the
|
||||
clamp positions) when N≥1 — Excalidraw supports multi-vertex arrows
|
||||
via the `points` array. Each `startBinding` / `endBinding` resolves to
|
||||
the from/to anchor's excalidraw_id; mid-vertices are unbound.
|
||||
|
||||
Bundle visualisation (thick striped lines on shared segments) is **not
|
||||
exported** in v0 — Excalidraw doesn't natively support gradient strokes,
|
||||
and the mxdrw round-trip would lose them. We export each cable as its
|
||||
own polyline; bundling is a viewer-only concept.
|
||||
|
||||
### 11.8 API additions
|
||||
|
||||
```
|
||||
POST /api/projects/:pid/clamps { x, y, label?, frame_id? } → Clamp
|
||||
PATCH /api/projects/:pid/clamps/:id { x?, y?, label?, frame_id? } → Clamp
|
||||
DELETE /api/projects/:pid/clamps/:id
|
||||
|
||||
POST /api/projects/:pid/cables/:cid/clamps { clamp_id, ord? } → CableClamp
|
||||
DELETE /api/projects/:pid/cables/:cid/clamps/:cmid
|
||||
|
||||
# Convenience: re-order clamps on a cable in one call
|
||||
PUT /api/projects/:pid/cables/:cid/clamps { clamp_ids: [int, int, …] }
|
||||
```
|
||||
|
||||
Snapshot endpoint grows two arrays:
|
||||
- `clamps: []Clamp`
|
||||
- `cable_clamps: []{ cable_id, clamp_id, ord }`
|
||||
|
||||
### 11.9 Open questions for m
|
||||
|
||||
1. **Clamp icon shape.** Diamond (overlaps visually with IO markers
|
||||
when zoomed out), small filled circle (overlaps with port circles),
|
||||
or rounded square `▢` 10×10? Recommend rounded square — distinct from
|
||||
everything else on the canvas today.
|
||||
2. **Snap radius when inserting onto a cable.** ~16 px world-units feels
|
||||
right at 1× zoom. Should it scale with zoom (visual constant) or stay
|
||||
world-constant (gesture stays the same regardless of zoom)? Recommend
|
||||
visual constant — divide by current zoom.
|
||||
3. **Clamp deletion when shared.** If a clamp is used by 4 cables and m
|
||||
clicks "Delete clamp", do we (a) refuse with a "still in use" prompt,
|
||||
(b) cascade-remove from all 4 cables, or (c) cascade silently? Current
|
||||
draft says cascade silently. Worth a confirmation?
|
||||
4. **Bundle stripe order.** Cable-type id is stable but arbitrary; visual
|
||||
order on a thick line affects readability. Order by stripe-count
|
||||
(Power first if 3 Power + 1 USB), or by cable-type-id (deterministic
|
||||
but unrelated to importance)? Recommend by-count, ties broken by id.
|
||||
5. **Solver respect for existing routing.** When m re-runs Solve after
|
||||
hand-routing, should the solver preserve existing clamp routing on
|
||||
user-owned (`auto=0`) cables? Auto cables are wiped + rebuilt, so
|
||||
their clamps disappear with them — that's expected. But manual cables
|
||||
with clamps should clearly keep them. Confirm.
|
||||
|
||||
### 11.10 Slice plan (post-design)
|
||||
|
||||
1. Schema migration + tx-aware store helpers (Create/Update/DeleteClamp,
|
||||
AttachClampToCable, DetachClampFromCable, ReorderClamps).
|
||||
2. HTTP endpoints + snapshot extension.
|
||||
3. Frontend: clamp render + + Clamp tool + canvas placement (no
|
||||
cable attach yet).
|
||||
4. Cable polyline render via clamps, mid-segment drag-to-clamp,
|
||||
clamp inspector.
|
||||
5. Shared-segment bundle visualisation (gradient stripe + count badge).
|
||||
6. Export pipeline extension — mxdrw arrows with mid-points + clamp
|
||||
diamonds. Bundle viz stays viewer-only.
|
||||
|
||||
---
|
||||
|
||||
DESIGN v5 READY FOR REVIEW
|
||||
|
||||
@@ -17,6 +17,7 @@ func TestSeed_BuiltInDeviceTypes(t *testing.T) {
|
||||
"NAS", "PC", "Mac", "Notebook", "TV", "Soundbar", "Switch", "fritz",
|
||||
"ChromeCast", "SteamLink", "IOx-3", "IOx-6", "IOx-8",
|
||||
"Screen", "Keyboard", "Mouse",
|
||||
"Multi-plug 3", "Multi-plug 4", "Multi-plug 5", "Multi-plug 6", "Wifi-plug",
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("built-in count = %d, want %d", len(got), len(want))
|
||||
@@ -54,12 +55,17 @@ func TestSeed_PortProfiles(t *testing.T) {
|
||||
"fritz": {5}, // Power 1 + RJ45 4
|
||||
"ChromeCast": {2}, // Power 1 + HDMI 1
|
||||
"SteamLink": {4}, // Power 1 + HDMI 1 + USB 2
|
||||
"IOx-3": {4}, // Power 1 + USB 3
|
||||
"IOx-6": {7}, // Power 1 + USB 6
|
||||
"IOx-8": {9}, // Power 1 + USB 8
|
||||
"Screen": {2}, // Power 1 + HDMI 1
|
||||
"Keyboard": {1}, // USB 1
|
||||
"Mouse": {1}, // USB 1
|
||||
"IOx-3": {4}, // Power In 1 + Power Out 3 (after v6)
|
||||
"IOx-6": {7}, // Power In 1 + Power Out 6 (after v6)
|
||||
"IOx-8": {9}, // Power In 1 + Power Out 8 (after v6)
|
||||
"Screen": {2}, // Power 1 + HDMI 1
|
||||
"Keyboard": {1}, // USB 1
|
||||
"Mouse": {1}, // USB 1
|
||||
"Multi-plug 3": {4}, // Power In 1 + Power Out 3 (after v6)
|
||||
"Multi-plug 4": {5}, // Power In 1 + Power Out 4 (after v6)
|
||||
"Multi-plug 5": {6}, // Power In 1 + Power Out 5 (after v6)
|
||||
"Multi-plug 6": {7}, // Power In 1 + Power Out 6 (after v6)
|
||||
"Wifi-plug": {2}, // Power In 1 + Power Out 1 (after v6)
|
||||
}
|
||||
for name, want := range cases {
|
||||
dt, ok := byName[name]
|
||||
@@ -77,6 +83,80 @@ func TestSeed_PortProfiles(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeed_PowerHubs locks down the post-migration-006 port profile for
|
||||
// every power-distribution device type: IOx-3/6/8, Multi-plug 3/4/5/6,
|
||||
// and Wifi-plug. Each carries exactly two profile rows — a single
|
||||
// "Power In" port on the top (back) edge and N "Power Out" ports on the
|
||||
// bottom (front) edge, where N is the device-specific output count.
|
||||
//
|
||||
// This test covers the v5 catalog identity (kind, icon, built-in) for
|
||||
// the 5 power-distribution types and the v6 port-profile fix for all
|
||||
// 8 hubs in one table.
|
||||
func TestSeed_PowerHubs(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
all, err := s.ListBuiltInDeviceTypes()
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
if len(all) != 21 {
|
||||
t.Errorf("built-in count = %d, want 21 (16 from v4 + 5 from v5)", len(all))
|
||||
}
|
||||
byName := map[string]DeviceType{}
|
||||
for _, d := range all {
|
||||
byName[d.Name] = d
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
// kind/icon are only set for the 5 v5-power types; empty means
|
||||
// "don't check" (the IOx-* keep their v4-seeded kind=hub icon=nil).
|
||||
kind string
|
||||
icon string
|
||||
outCount int // N — number of "Power Out" outlets on the bottom edge
|
||||
}{
|
||||
// v5 catalog (kind+icon checked)
|
||||
{name: "Multi-plug 3", kind: "hub", icon: "🔌", outCount: 3},
|
||||
{name: "Multi-plug 4", kind: "hub", icon: "🔌", outCount: 4},
|
||||
{name: "Multi-plug 5", kind: "hub", icon: "🔌", outCount: 5},
|
||||
{name: "Multi-plug 6", kind: "hub", icon: "🔌", outCount: 6},
|
||||
{name: "Wifi-plug", kind: "accessory", icon: "📶", outCount: 1},
|
||||
// v4 hubs re-shaped by v6 (kind/icon left blank → not checked)
|
||||
{name: "IOx-3", outCount: 3},
|
||||
{name: "IOx-6", outCount: 6},
|
||||
{name: "IOx-8", outCount: 8},
|
||||
}
|
||||
for _, c := range cases {
|
||||
dt, ok := byName[c.name]
|
||||
if !ok {
|
||||
t.Errorf("missing %q", c.name)
|
||||
continue
|
||||
}
|
||||
if !dt.BuiltIn {
|
||||
t.Errorf("%s: built_in should be true", c.name)
|
||||
}
|
||||
if dt.ProjectID != nil {
|
||||
t.Errorf("%s: project_id should be nil", c.name)
|
||||
}
|
||||
if c.kind != "" && dt.Kind != c.kind {
|
||||
t.Errorf("%s: kind = %q, want %q", c.name, dt.Kind, c.kind)
|
||||
}
|
||||
if c.icon != "" && (dt.Icon == nil || *dt.Icon != c.icon) {
|
||||
t.Errorf("%s: icon = %v, want %q", c.name, dt.Icon, c.icon)
|
||||
}
|
||||
if len(dt.Ports) != 2 {
|
||||
t.Errorf("%s: expected 2 port-profile rows, got %d", c.name, len(dt.Ports))
|
||||
continue
|
||||
}
|
||||
in := dt.Ports[0]
|
||||
out := dt.Ports[1]
|
||||
if in.CableTypeID != 1 || in.Count != 1 || in.Edge != "top" || in.LabelPrefix != "Power In" {
|
||||
t.Errorf("%s: Power In row mismatch: %+v", c.name, in)
|
||||
}
|
||||
if out.CableTypeID != 1 || out.Count != c.outCount || out.Edge != "bottom" || out.LabelPrefix != "Power Out" {
|
||||
t.Errorf("%s: Power Out row mismatch: %+v (want count=%d)", c.name, out, c.outCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------- CRUD (custom rows)
|
||||
|
||||
func TestCreateDeviceType_CustomBasic(t *testing.T) {
|
||||
|
||||
60
internal/db/excalidraw_ids.go
Normal file
60
internal/db/excalidraw_ids.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// PersistExcalidrawIDs writes the assignments returned by the exporter
|
||||
// back onto the corresponding rows. Idempotent: only updates rows whose
|
||||
// excalidraw_id is currently NULL (the first export "owns" the id; later
|
||||
// exports reuse it so mxdrw's collab cursors / undo history survive).
|
||||
//
|
||||
// Caller passes one map per kind; keys are the in-project row ids,
|
||||
// values are the 21-char Excalidraw element ids the exporter minted.
|
||||
func (s *Store) PersistExcalidrawIDs(projectID int64,
|
||||
frames, devices, ports, ios, cables map[int64]string,
|
||||
) error {
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if err := updateExIDs(tx, "frames", projectID, frames); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := updateExIDs(tx, "devices", projectID, devices); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := updateExIDs(tx, "ports", projectID, ports); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := updateExIDs(tx, "io_markers", projectID, ios); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := updateExIDs(tx, "cables", projectID, cables); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func updateExIDs(tx *sql.Tx, table string, projectID int64, m map[int64]string) error {
|
||||
if len(m) == 0 {
|
||||
return nil
|
||||
}
|
||||
stmt, err := tx.Prepare(
|
||||
`UPDATE ` + table + `
|
||||
SET excalidraw_id = ?
|
||||
WHERE id = ? AND project_id = ? AND excalidraw_id IS NULL`,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stmt.Close()
|
||||
for id, exID := range m {
|
||||
if _, err := stmt.Exec(exID, id, projectID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
32
internal/db/migrations/005_catalog_power.sql
Normal file
32
internal/db/migrations/005_catalog_power.sql
Normal file
@@ -0,0 +1,32 @@
|
||||
-- mCables v5 — catalog: power-distribution devices.
|
||||
-- Adds 5 built-in device_types (project_id NULL, built_in=1).
|
||||
--
|
||||
-- Multi-plug N exposes Power × (N+1) ports — one input + N outputs. The
|
||||
-- solver treats every Power port identically regardless of in/out
|
||||
-- direction; m knows which end is which from the physical setup.
|
||||
--
|
||||
-- Wifi-plug is a pass-through outlet (Power × 2: one in, one out).
|
||||
|
||||
INSERT INTO device_types (name, kind, icon, built_in, description) VALUES
|
||||
('Multi-plug 3', 'hub', '🔌', 1, '3-way power strip (1 in + 3 out)'),
|
||||
('Multi-plug 4', 'hub', '🔌', 1, '4-way power strip (1 in + 4 out)'),
|
||||
('Multi-plug 5', 'hub', '🔌', 1, '5-way power strip (1 in + 5 out)'),
|
||||
('Multi-plug 6', 'hub', '🔌', 1, '6-way power strip (1 in + 6 out)'),
|
||||
('Wifi-plug', 'accessory', '📶', 1, 'WiFi-controllable pass-through outlet');
|
||||
|
||||
-- Port profiles. cable_types id 1 = Power (seeded in 001).
|
||||
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power', 4, 'bottom', 0 FROM device_types WHERE name='Multi-plug 3' AND project_id IS NULL;
|
||||
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power', 5, 'bottom', 0 FROM device_types WHERE name='Multi-plug 4' AND project_id IS NULL;
|
||||
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power', 6, 'bottom', 0 FROM device_types WHERE name='Multi-plug 5' AND project_id IS NULL;
|
||||
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power', 7, 'bottom', 0 FROM device_types WHERE name='Multi-plug 6' AND project_id IS NULL;
|
||||
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power', 2, 'bottom', 0 FROM device_types WHERE name='Wifi-plug' AND project_id IS NULL;
|
||||
87
internal/db/migrations/006_fix_power_hubs.sql
Normal file
87
internal/db/migrations/006_fix_power_hubs.sql
Normal file
@@ -0,0 +1,87 @@
|
||||
-- mCables v6 — fix IOx-* and Multi-plug-* + Wifi-plug port profiles.
|
||||
--
|
||||
-- v4 seeded the IOx-3 / IOx-6 / IOx-8 as USB hubs (Power × 1 + USB × N),
|
||||
-- but m's physical IOx-* devices are power strips (1 power input on
|
||||
-- the back, N power outputs on the front). v5's Multi-plug 3/4/5/6
|
||||
-- profiles also lumped every Power port on the bottom edge without
|
||||
-- distinguishing the input from the outputs.
|
||||
--
|
||||
-- This migration replaces the port profile for the 8 power-distribution
|
||||
-- types with the canonical "1 in (top/back) + N out (bottom/front)"
|
||||
-- layout. Convention: top=back, bottom=front.
|
||||
--
|
||||
-- N for each type:
|
||||
-- IOx-3 / Multi-plug 3 → 3 outputs
|
||||
-- IOx-6 → 6 outputs
|
||||
-- IOx-8 → 8 outputs
|
||||
-- Multi-plug 4 → 4 outputs
|
||||
-- Multi-plug 5 → 5 outputs
|
||||
-- Multi-plug 6 → 6 outputs
|
||||
-- Wifi-plug → 1 output (it's a pass-through outlet)
|
||||
--
|
||||
-- Existing devices m may have created with the old profile keep their
|
||||
-- already-seeded ports — per design §2.3, ports are instance-owned. To
|
||||
-- get the new layout on an existing instance, delete it and re-create.
|
||||
--
|
||||
-- cable_types id 1 = Power (seeded in 001).
|
||||
|
||||
-- 1) Drop the existing port-profile rows for each affected type.
|
||||
DELETE FROM device_type_ports
|
||||
WHERE device_type_id IN (
|
||||
SELECT id FROM device_types
|
||||
WHERE project_id IS NULL
|
||||
AND name IN (
|
||||
'IOx-3', 'IOx-6', 'IOx-8',
|
||||
'Multi-plug 3', 'Multi-plug 4', 'Multi-plug 5', 'Multi-plug 6',
|
||||
'Wifi-plug'
|
||||
)
|
||||
);
|
||||
|
||||
-- 2) Insert the canonical (1 in on top, N out on bottom) profile.
|
||||
-- IOx-3 — 1 in + 3 out
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='IOx-3' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 3, 'bottom', 1 FROM device_types WHERE name='IOx-3' AND project_id IS NULL;
|
||||
|
||||
-- IOx-6 — 1 in + 6 out
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='IOx-6' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 6, 'bottom', 1 FROM device_types WHERE name='IOx-6' AND project_id IS NULL;
|
||||
|
||||
-- IOx-8 — 1 in + 8 out
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='IOx-8' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 8, 'bottom', 1 FROM device_types WHERE name='IOx-8' AND project_id IS NULL;
|
||||
|
||||
-- Multi-plug 3 — 1 in + 3 out
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='Multi-plug 3' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 3, 'bottom', 1 FROM device_types WHERE name='Multi-plug 3' AND project_id IS NULL;
|
||||
|
||||
-- Multi-plug 4 — 1 in + 4 out
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='Multi-plug 4' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 4, 'bottom', 1 FROM device_types WHERE name='Multi-plug 4' AND project_id IS NULL;
|
||||
|
||||
-- Multi-plug 5 — 1 in + 5 out
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='Multi-plug 5' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 5, 'bottom', 1 FROM device_types WHERE name='Multi-plug 5' AND project_id IS NULL;
|
||||
|
||||
-- Multi-plug 6 — 1 in + 6 out
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='Multi-plug 6' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 6, 'bottom', 1 FROM device_types WHERE name='Multi-plug 6' AND project_id IS NULL;
|
||||
|
||||
-- Wifi-plug — 1 in + 1 out (pass-through outlet)
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power In', 1, 'top', 0 FROM device_types WHERE name='Wifi-plug' AND project_id IS NULL;
|
||||
INSERT INTO device_type_ports (device_type_id, cable_type_id, label_prefix, count, edge, sort_order)
|
||||
SELECT id, 1, 'Power Out', 1, 'bottom', 1 FROM device_types WHERE name='Wifi-plug' AND project_id IS NULL;
|
||||
@@ -191,10 +191,11 @@ type UnsatisfiedReq struct {
|
||||
|
||||
// ApplyTemplateResult is the response from POST /apply-template.
|
||||
type ApplyTemplateResult struct {
|
||||
DevicesAdded []Device `json:"devices_added"`
|
||||
RequirementsAdded []ConnectionRequirement `json:"requirements_added"`
|
||||
SkippedDevices []SkippedTemplateDevice `json:"skipped_devices"`
|
||||
RequirementsSkipped []SkippedTemplateReq `json:"requirements_skipped"`
|
||||
FramesAdded []Frame `json:"frames_added"`
|
||||
DevicesAdded []Device `json:"devices_added"`
|
||||
RequirementsAdded []ConnectionRequirement `json:"requirements_added"`
|
||||
SkippedDevices []SkippedTemplateDevice `json:"skipped_devices"`
|
||||
RequirementsSkipped []SkippedTemplateReq `json:"requirements_skipped"`
|
||||
}
|
||||
|
||||
type SkippedTemplateDevice struct {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -161,6 +162,7 @@ func (s *Store) ApplyTemplate(projectID, templateID int64, opts ApplyTemplateOpt
|
||||
}
|
||||
|
||||
out := &ApplyTemplateResult{
|
||||
FramesAdded: []Frame{},
|
||||
DevicesAdded: []Device{},
|
||||
RequirementsAdded: []ConnectionRequirement{},
|
||||
SkippedDevices: []SkippedTemplateDevice{},
|
||||
@@ -171,8 +173,8 @@ func (s *Store) ApplyTemplate(projectID, templateID int64, opts ApplyTemplateOpt
|
||||
opts.OriginX, opts.OriginY = 200, 200
|
||||
}
|
||||
|
||||
// Pull existing device names in the project so we can pre-check
|
||||
// collisions without aborting the whole transaction.
|
||||
// Pull existing device + frame names in the project so we can
|
||||
// pre-check collisions without aborting the whole transaction.
|
||||
existing, err := s.ListDevices(projectID, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -181,6 +183,14 @@ func (s *Store) ApplyTemplate(projectID, templateID int64, opts ApplyTemplateOpt
|
||||
for _, d := range existing {
|
||||
nameTaken[d.Name] = true
|
||||
}
|
||||
existingFrames, err := s.ListFrames(projectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
frameNameTaken := map[string]bool{}
|
||||
for _, f := range existingFrames {
|
||||
frameNameTaken[f.Name] = true
|
||||
}
|
||||
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
@@ -188,6 +198,37 @@ func (s *Store) ApplyTemplate(projectID, templateID int64, opts ApplyTemplateOpt
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Plan a uniform grid for the template's devices inside a new frame
|
||||
// named after the template. The grid drives both frame size and
|
||||
// per-device (x, y). Devices that get skipped (name collision /
|
||||
// SkipDevices) leave their grid cell empty.
|
||||
const (
|
||||
devW, devH = 100.0, 35.0
|
||||
gapX, gapY = 30.0, 50.0
|
||||
padX, padY = 32.0, 48.0 // padY larger so the frame title clears row 1
|
||||
)
|
||||
n := len(tmpl.Devices)
|
||||
cols := 1
|
||||
if n > 0 {
|
||||
cols = min(int(math.Ceil(math.Sqrt(float64(n)))), 4)
|
||||
}
|
||||
rows := 1
|
||||
if n > 0 {
|
||||
rows = (n + cols - 1) / cols
|
||||
}
|
||||
frameW := padX*2 + float64(cols)*devW + float64(cols-1)*gapX
|
||||
frameH := padY + padX + float64(rows)*devH + float64(rows-1)*gapY
|
||||
frameName := pickFrameName(tmpl.Name, frameNameTaken)
|
||||
|
||||
frame, err := createFrameTx(tx, projectID, FrameCreate{
|
||||
Name: frameName, X: opts.OriginX, Y: opts.OriginY,
|
||||
Width: frameW, Height: frameH,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("seed frame %q: %w", frameName, err)
|
||||
}
|
||||
out.FramesAdded = append(out.FramesAdded, *frame)
|
||||
|
||||
// Map: template_device_id → newly-created device_id (or 0 if skipped).
|
||||
tmplToDevice := map[int64]int64{}
|
||||
|
||||
@@ -215,17 +256,22 @@ func (s *Store) ApplyTemplate(projectID, templateID int64, opts ApplyTemplateOpt
|
||||
tmplToDevice[td.ID] = 0
|
||||
continue
|
||||
}
|
||||
// Lay out devices in a horizontal row near the origin, 150 px apart.
|
||||
x := opts.OriginX + float64(i)*150
|
||||
y := opts.OriginY
|
||||
// Use createDeviceTx so the port-seeding share the same transaction.
|
||||
// Grid cell (col, row) within the frame. Cell anchor is the
|
||||
// top-left of the device rect; offsets are added to the frame's
|
||||
// own (x, y) so the device sits inside the frame.
|
||||
col := i % cols
|
||||
row := i / cols
|
||||
x := frame.X + padX + float64(col)*(devW+gapX)
|
||||
y := frame.Y + padY + float64(row)*(devH+gapY)
|
||||
// Use createDeviceTx so port-seeding shares the same transaction.
|
||||
d, err := s.createDeviceTx(tx, projectID, DeviceCreate{
|
||||
Name: name,
|
||||
TypeID: &td.DeviceTypeID,
|
||||
FrameID: &frame.ID,
|
||||
X: x,
|
||||
Y: y,
|
||||
Width: 100,
|
||||
Height: 35,
|
||||
Width: devW,
|
||||
Height: devH,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("seed %s: %w", name, err)
|
||||
@@ -294,6 +340,58 @@ func (s *Store) ApplyTemplate(projectID, templateID int64, opts ApplyTemplateOpt
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// pickFrameName returns a frame name that doesn't collide with anything
|
||||
// in `taken`. Tries the template name first, then "<name> 2", "<name> 3",
|
||||
// and so on.
|
||||
func pickFrameName(base string, taken map[string]bool) string {
|
||||
if !taken[base] {
|
||||
return base
|
||||
}
|
||||
for i := 2; ; i++ {
|
||||
candidate := fmt.Sprintf("%s %d", base, i)
|
||||
if !taken[candidate] {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// createFrameTx inserts a frame inside the caller's transaction. Mirrors
|
||||
// the validation in CreateFrame (name + positive size) but avoids the
|
||||
// s.db.Exec call so ApplyTemplate can keep everything on the same
|
||||
// connection under MaxOpenConns(1).
|
||||
func createFrameTx(tx *sql.Tx, projectID int64, f FrameCreate) (*Frame, error) {
|
||||
name := strings.TrimSpace(f.Name)
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("%w: name is required", ErrInvalidInput)
|
||||
}
|
||||
if f.Width <= 0 || f.Height <= 0 {
|
||||
return nil, fmt.Errorf("%w: width and height must be positive", ErrInvalidInput)
|
||||
}
|
||||
res, err := tx.Exec(
|
||||
`INSERT INTO frames (project_id, name, x, y, width, height)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
projectID, name, f.X, f.Y, f.Width, f.Height,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
var out Frame
|
||||
var ex sql.NullString
|
||||
err = tx.QueryRow(
|
||||
`SELECT id, project_id, name, x, y, width, height, excalidraw_id, created_at, updated_at
|
||||
FROM frames WHERE id = ? AND project_id = ?`, id, projectID,
|
||||
).Scan(&out.ID, &out.ProjectID, &out.Name, &out.X, &out.Y, &out.Width, &out.Height,
|
||||
&ex, &out.CreatedAt, &out.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ex.Valid {
|
||||
out.ExcalidrawID = &ex.String
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// createDeviceTx is a tx-aware variant of CreateDevice used by
|
||||
// ApplyTemplate so seeding the template's devices + their ports stays
|
||||
// inside one atomic apply.
|
||||
|
||||
@@ -234,6 +234,76 @@ func TestApplyTemplate_HomeOffice_ThenSolve(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTemplate_CreatesFrameAndPlacesDevicesInside(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
p, _ := s.CreateProject("LOFT", "", "")
|
||||
tmpls, _ := s.ListSetupTemplates()
|
||||
var lr SetupTemplate
|
||||
for _, tm := range tmpls {
|
||||
if tm.Name == "Living Room" {
|
||||
lr = tm
|
||||
break
|
||||
}
|
||||
}
|
||||
res, err := s.ApplyTemplate(p.ID, lr.ID, ApplyTemplateOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if len(res.FramesAdded) != 1 {
|
||||
t.Fatalf("frames added = %d, want 1", len(res.FramesAdded))
|
||||
}
|
||||
frame := res.FramesAdded[0]
|
||||
if frame.Name != "Living Room" {
|
||||
t.Errorf("frame name = %q, want %q", frame.Name, "Living Room")
|
||||
}
|
||||
for _, d := range res.DevicesAdded {
|
||||
if d.FrameID == nil || *d.FrameID != frame.ID {
|
||||
t.Errorf("device %q: frame_id = %v, want %d", d.Name, d.FrameID, frame.ID)
|
||||
}
|
||||
// Device top-left should be inside the frame rect.
|
||||
if d.X < frame.X || d.X+d.Width > frame.X+frame.Width {
|
||||
t.Errorf("device %q: x=%v width=%v outside frame [%v..%v]", d.Name, d.X, d.Width, frame.X, frame.X+frame.Width)
|
||||
}
|
||||
if d.Y < frame.Y || d.Y+d.Height > frame.Y+frame.Height {
|
||||
t.Errorf("device %q: y=%v height=%v outside frame [%v..%v]", d.Name, d.Y, d.Height, frame.Y, frame.Y+frame.Height)
|
||||
}
|
||||
}
|
||||
// No two devices share the same (X, Y) — the grid layout spreads them out.
|
||||
seen := map[[2]float64]string{}
|
||||
for _, d := range res.DevicesAdded {
|
||||
key := [2]float64{d.X, d.Y}
|
||||
if prev, ok := seen[key]; ok {
|
||||
t.Errorf("devices %q and %q share grid cell (%v, %v)", prev, d.Name, d.X, d.Y)
|
||||
}
|
||||
seen[key] = d.Name
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTemplate_FrameNameSuffixOnCollision(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
p, _ := s.CreateProject("LOFT", "", "")
|
||||
// Pre-create a frame called "Living Room" so the template's frame name collides.
|
||||
_, _ = s.CreateFrame(p.ID, FrameCreate{Name: "Living Room", X: 0, Y: 0, Width: 100, Height: 100})
|
||||
tmpls, _ := s.ListSetupTemplates()
|
||||
var lr SetupTemplate
|
||||
for _, tm := range tmpls {
|
||||
if tm.Name == "Living Room" {
|
||||
lr = tm
|
||||
break
|
||||
}
|
||||
}
|
||||
res, err := s.ApplyTemplate(p.ID, lr.ID, ApplyTemplateOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("apply: %v", err)
|
||||
}
|
||||
if len(res.FramesAdded) != 1 {
|
||||
t.Fatalf("frames added = %d, want 1", len(res.FramesAdded))
|
||||
}
|
||||
if res.FramesAdded[0].Name != "Living Room 2" {
|
||||
t.Errorf("frame name = %q, want %q (suffixed)", res.FramesAdded[0].Name, "Living Room 2")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTemplate_NameCollisionSkipped(t *testing.T) {
|
||||
s := newTestStore(t)
|
||||
p, _ := s.CreateProject("LOFT", "", "")
|
||||
|
||||
563
internal/exporter/exporter.go
Normal file
563
internal/exporter/exporter.go
Normal file
@@ -0,0 +1,563 @@
|
||||
// Package exporter builds an Excalidraw scene JSON from a project
|
||||
// snapshot per docs/design.md §4 ("Export — DB → Excalidraw").
|
||||
//
|
||||
// The exporter is a pure function on a *db.Snapshot — no DB access, no
|
||||
// IO — so it's trivial to unit-test against fixtures and gives the
|
||||
// caller (the HTTP handler) a clean handoff: build scene → upload.
|
||||
package exporter
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
"mgit.msbls.de/m/mcables/internal/db"
|
||||
)
|
||||
|
||||
// Scene is the top-level Excalidraw file format. Keys mirror what the
|
||||
// official Excalidraw JSON contains (we only emit the keys mxdrw cares
|
||||
// about for rendering — `appState`, `files`, `libraryItems` etc. can be
|
||||
// added later if m needs them).
|
||||
type Scene struct {
|
||||
Type string `json:"type"`
|
||||
Version int `json:"version"`
|
||||
Source string `json:"source"`
|
||||
Elements []Element `json:"elements"`
|
||||
AppState AppState `json:"appState"`
|
||||
Files Files `json:"files"`
|
||||
}
|
||||
|
||||
type AppState struct {
|
||||
GridSize *int `json:"gridSize"`
|
||||
ViewBackground string `json:"viewBackgroundColor"`
|
||||
}
|
||||
|
||||
type Files struct{}
|
||||
|
||||
// Element is one node in the scene. Excalidraw's wire format has a lot
|
||||
// of optional fields; we only emit the ones that matter for the shapes
|
||||
// we draw. Extra null/zero fields are fine in Excalidraw (it merges
|
||||
// defaults). Pointer fields stay nil-omitted via omitempty so the
|
||||
// payload stays clean.
|
||||
type Element struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
Width float64 `json:"width"`
|
||||
Height float64 `json:"height"`
|
||||
Angle float64 `json:"angle"`
|
||||
StrokeColor string `json:"strokeColor"`
|
||||
BackgroundColor string `json:"backgroundColor"`
|
||||
FillStyle string `json:"fillStyle"`
|
||||
StrokeWidth int `json:"strokeWidth"`
|
||||
StrokeStyle string `json:"strokeStyle"`
|
||||
Roughness int `json:"roughness"`
|
||||
Opacity int `json:"opacity"`
|
||||
GroupIDs []string `json:"groupIds"`
|
||||
FrameID *string `json:"frameId"`
|
||||
Roundness *Roundness `json:"roundness"`
|
||||
Seed int64 `json:"seed"`
|
||||
Version int `json:"version"`
|
||||
VersionNonce int64 `json:"versionNonce"`
|
||||
IsDeleted bool `json:"isDeleted"`
|
||||
BoundElements []BoundRef `json:"boundElements,omitempty"`
|
||||
Updated int64 `json:"updated"`
|
||||
Link *string `json:"link"`
|
||||
Locked bool `json:"locked"`
|
||||
|
||||
// Element-type-specific extras
|
||||
Name string `json:"name,omitempty"`
|
||||
|
||||
// Text-element fields
|
||||
Text string `json:"text,omitempty"`
|
||||
FontSize int `json:"fontSize,omitempty"`
|
||||
FontFamily int `json:"fontFamily,omitempty"`
|
||||
TextAlign string `json:"textAlign,omitempty"`
|
||||
VerticalAlign string `json:"verticalAlign,omitempty"`
|
||||
ContainerID *string `json:"containerId,omitempty"`
|
||||
OriginalText string `json:"originalText,omitempty"`
|
||||
LineHeight float64 `json:"lineHeight,omitempty"`
|
||||
|
||||
// Arrow-element fields
|
||||
Points [][2]float64 `json:"points,omitempty"`
|
||||
StartBinding *Binding `json:"startBinding,omitempty"`
|
||||
EndBinding *Binding `json:"endBinding,omitempty"`
|
||||
StartArrowhead *string `json:"startArrowhead,omitempty"`
|
||||
EndArrowhead *string `json:"endArrowhead,omitempty"`
|
||||
LastCommittedPoint *[2]float64 `json:"lastCommittedPoint,omitempty"`
|
||||
}
|
||||
|
||||
type Roundness struct {
|
||||
Type int `json:"type"`
|
||||
}
|
||||
|
||||
type BoundRef struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type Binding struct {
|
||||
ElementID string `json:"elementId"`
|
||||
Focus float64 `json:"focus"`
|
||||
Gap float64 `json:"gap"`
|
||||
}
|
||||
|
||||
// IDAssignment is the result of running BuildScene: the scene to upload
|
||||
// + the per-row excalidraw_id assignments that the caller should
|
||||
// persist so the next export reuses the same ids (Excalidraw collab
|
||||
// cursors / comments / undo history survive that way; design §4.2).
|
||||
type IDAssignment struct {
|
||||
Frames map[int64]string `json:"frames"`
|
||||
Devices map[int64]string `json:"devices"`
|
||||
Ports map[int64]string `json:"ports"`
|
||||
IOMarkers map[int64]string `json:"io_markers"`
|
||||
Cables map[int64]string `json:"cables"`
|
||||
}
|
||||
|
||||
// BuildScene transforms a project snapshot into an Excalidraw Scene +
|
||||
// the id-assignment side-table.
|
||||
//
|
||||
// nowMilli is the Updated timestamp (one millisecond stamp for every
|
||||
// element keeps re-exports consistent — mxdrw treats wildly-different
|
||||
// updateds as edit-noise).
|
||||
//
|
||||
// genID is a 21-char ID factory. Tests pass a deterministic generator
|
||||
// to lock element ids down across asserts. Production uses Generate21.
|
||||
func BuildScene(snap *db.Snapshot, nowMilli int64, genID func() string) (*Scene, *IDAssignment) {
|
||||
a := &IDAssignment{
|
||||
Frames: map[int64]string{},
|
||||
Devices: map[int64]string{},
|
||||
Ports: map[int64]string{},
|
||||
IOMarkers: map[int64]string{},
|
||||
Cables: map[int64]string{},
|
||||
}
|
||||
// idFor: reuse the existing excalidraw_id if present, else mint one.
|
||||
idFor := func(existing *string) string {
|
||||
if existing != nil && *existing != "" {
|
||||
return *existing
|
||||
}
|
||||
return genID()
|
||||
}
|
||||
|
||||
cableTypeColor := map[int64]string{}
|
||||
for _, t := range snap.CableTypes {
|
||||
cableTypeColor[t.ID] = t.Color
|
||||
}
|
||||
|
||||
// We'll need: device-id → element-id, port-id → element-id, io-id → element-id
|
||||
// for binding arrows.
|
||||
deviceElID := map[int64]string{}
|
||||
portElID := map[int64]string{}
|
||||
ioElID := map[int64]string{}
|
||||
frameElID := map[int64]string{}
|
||||
|
||||
var els []Element
|
||||
|
||||
// Frames first (Excalidraw renders later elements on top; frames are
|
||||
// containers that go on the bottom).
|
||||
for _, f := range snap.Frames {
|
||||
elID := idFor(f.ExcalidrawID)
|
||||
a.Frames[f.ID] = elID
|
||||
frameElID[f.ID] = elID
|
||||
els = append(els, Element{
|
||||
ID: elID,
|
||||
Type: "frame",
|
||||
X: f.X,
|
||||
Y: f.Y,
|
||||
Width: f.Width,
|
||||
Height: f.Height,
|
||||
StrokeColor: "#bbbbbb",
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 2,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
Name: f.Name,
|
||||
})
|
||||
}
|
||||
|
||||
// Devices: rectangle + bound text with the device's name. Excalidraw
|
||||
// uses a `containerId` pointer on the text to bind it to the rect,
|
||||
// and `boundElements` on the rect to point back at the text.
|
||||
for _, d := range snap.Devices {
|
||||
rectID := idFor(d.ExcalidrawID)
|
||||
a.Devices[d.ID] = rectID
|
||||
deviceElID[d.ID] = rectID
|
||||
textID := genID()
|
||||
var frameRef *string
|
||||
if d.FrameID != nil {
|
||||
if v, ok := frameElID[*d.FrameID]; ok {
|
||||
frameRef = &v
|
||||
}
|
||||
}
|
||||
// Rect
|
||||
els = append(els, Element{
|
||||
ID: rectID,
|
||||
Type: "rectangle",
|
||||
X: d.X,
|
||||
Y: d.Y,
|
||||
Width: d.Width,
|
||||
Height: d.Height,
|
||||
StrokeColor: d.Color,
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 2,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
FrameID: frameRef,
|
||||
Roundness: &Roundness{Type: 3},
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
BoundElements: []BoundRef{{ID: textID, Type: "text"}},
|
||||
})
|
||||
// Bound text — name centered on the rect.
|
||||
els = append(els, Element{
|
||||
ID: textID,
|
||||
Type: "text",
|
||||
X: d.X,
|
||||
Y: d.Y + d.Height/2 - 8,
|
||||
Width: d.Width,
|
||||
Height: 16,
|
||||
StrokeColor: d.Color,
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 2,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
FrameID: frameRef,
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
Text: d.Name,
|
||||
OriginalText: d.Name,
|
||||
FontSize: 16,
|
||||
FontFamily: 1,
|
||||
TextAlign: "center",
|
||||
VerticalAlign: "middle",
|
||||
ContainerID: &rectID,
|
||||
LineHeight: 1.25,
|
||||
})
|
||||
}
|
||||
|
||||
// Ports — small ellipses at device.x + port.x_offset (positional,
|
||||
// not containerId-bound per the seed drawing's grammar; design §4.1).
|
||||
for _, p := range snap.Ports {
|
||||
elID := idFor(p.ExcalidrawID)
|
||||
a.Ports[p.ID] = elID
|
||||
portElID[p.ID] = elID
|
||||
// Locate the parent device for absolute pos + frame ref.
|
||||
var dev *db.Device
|
||||
for i := range snap.Devices {
|
||||
if snap.Devices[i].ID == p.DeviceID {
|
||||
dev = &snap.Devices[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if dev == nil {
|
||||
continue
|
||||
}
|
||||
var frameRef *string
|
||||
if dev.FrameID != nil {
|
||||
if v, ok := frameElID[*dev.FrameID]; ok {
|
||||
frameRef = &v
|
||||
}
|
||||
}
|
||||
color := cableTypeColor[p.TypeID]
|
||||
if color == "" {
|
||||
color = "#1e1e1e"
|
||||
}
|
||||
els = append(els, Element{
|
||||
ID: elID,
|
||||
Type: "ellipse",
|
||||
X: dev.X + p.XOffset - 6,
|
||||
Y: dev.Y + p.YOffset - 4,
|
||||
Width: 12,
|
||||
Height: 9,
|
||||
StrokeColor: color,
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 2,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
FrameID: frameRef,
|
||||
Roundness: &Roundness{Type: 2},
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
})
|
||||
}
|
||||
|
||||
// IO markers — diamonds with bound "IO" (or m's label) text.
|
||||
powerColor := ""
|
||||
for _, t := range snap.CableTypes {
|
||||
if t.Name == "Power" {
|
||||
powerColor = t.Color
|
||||
break
|
||||
}
|
||||
}
|
||||
if powerColor == "" {
|
||||
powerColor = "#e03131"
|
||||
}
|
||||
for _, m := range snap.IOMarkers {
|
||||
elID := idFor(m.ExcalidrawID)
|
||||
a.IOMarkers[m.ID] = elID
|
||||
ioElID[m.ID] = elID
|
||||
textID := genID()
|
||||
var frameRef *string
|
||||
if m.FrameID != nil {
|
||||
if v, ok := frameElID[*m.FrameID]; ok {
|
||||
frameRef = &v
|
||||
}
|
||||
}
|
||||
els = append(els, Element{
|
||||
ID: elID,
|
||||
Type: "diamond",
|
||||
X: m.X,
|
||||
Y: m.Y,
|
||||
Width: 30,
|
||||
Height: 30,
|
||||
StrokeColor: powerColor,
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 2,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
FrameID: frameRef,
|
||||
Roundness: &Roundness{Type: 2},
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
BoundElements: []BoundRef{{ID: textID, Type: "text"}},
|
||||
})
|
||||
els = append(els, Element{
|
||||
ID: textID,
|
||||
Type: "text",
|
||||
X: m.X,
|
||||
Y: m.Y + 7,
|
||||
Width: 30,
|
||||
Height: 16,
|
||||
StrokeColor: powerColor,
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 2,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
FrameID: frameRef,
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
Text: m.Label,
|
||||
OriginalText: m.Label,
|
||||
FontSize: 11,
|
||||
FontFamily: 1,
|
||||
TextAlign: "center",
|
||||
VerticalAlign: "middle",
|
||||
ContainerID: &elID,
|
||||
LineHeight: 1.25,
|
||||
})
|
||||
}
|
||||
|
||||
// Cables — arrows with startBinding/endBinding to the port / device /
|
||||
// IO marker excalidraw_ids. Endpoint anchors (the visible "from" /
|
||||
// "to" points) come from the same anchor logic the canvas uses.
|
||||
for _, c := range snap.Cables {
|
||||
elID := idFor(c.ExcalidrawID)
|
||||
a.Cables[c.ID] = elID
|
||||
fromAnchor, fromRef := exportAnchor(c.FromPortID, c.FromDeviceID, c.FromIOID,
|
||||
snap, deviceElID, portElID, ioElID)
|
||||
toAnchor, toRef := exportAnchor(c.ToPortID, c.ToDeviceID, c.ToIOID,
|
||||
snap, deviceElID, portElID, ioElID)
|
||||
// fromRef/toRef are nil when the endpoint row vanished (manual
|
||||
// cable referencing a deleted port, say). Skip rather than emit
|
||||
// a half-bound arrow.
|
||||
if fromRef == nil || toRef == nil {
|
||||
continue
|
||||
}
|
||||
color := cableTypeColor[c.TypeID]
|
||||
if color == "" {
|
||||
color = "#1e1e1e"
|
||||
}
|
||||
startArr := ""
|
||||
endArr := "arrow"
|
||||
els = append(els, Element{
|
||||
ID: elID,
|
||||
Type: "arrow",
|
||||
X: fromAnchor[0],
|
||||
Y: fromAnchor[1],
|
||||
Width: toAnchor[0] - fromAnchor[0],
|
||||
Height: toAnchor[1] - fromAnchor[1],
|
||||
StrokeColor: color,
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 2,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
Points: [][2]float64{{0, 0}, {toAnchor[0] - fromAnchor[0], toAnchor[1] - fromAnchor[1]}},
|
||||
StartArrowhead: &startArr,
|
||||
EndArrowhead: &endArr,
|
||||
StartBinding: bindingPtr(fromRef),
|
||||
EndBinding: bindingPtr(toRef),
|
||||
})
|
||||
}
|
||||
|
||||
// Legend in the top-left of the first frame (or at 20,20 if there
|
||||
// are no frames). One text row per cable_type, stacked vertically.
|
||||
legendX, legendY := 20.0, 20.0
|
||||
if len(snap.Frames) > 0 {
|
||||
legendX = snap.Frames[0].X + 10
|
||||
legendY = snap.Frames[0].Y + 10
|
||||
}
|
||||
for i, t := range snap.CableTypes {
|
||||
els = append(els, Element{
|
||||
ID: genID(),
|
||||
Type: "text",
|
||||
X: legendX,
|
||||
Y: legendY + float64(i*18),
|
||||
Width: 80,
|
||||
Height: 16,
|
||||
StrokeColor: t.Color,
|
||||
BackgroundColor: "transparent",
|
||||
FillStyle: "solid",
|
||||
StrokeWidth: 1,
|
||||
StrokeStyle: "solid",
|
||||
Roughness: 0,
|
||||
Opacity: 100,
|
||||
GroupIDs: []string{},
|
||||
Seed: randInt(),
|
||||
Version: 1,
|
||||
VersionNonce: randInt(),
|
||||
Updated: nowMilli,
|
||||
Text: t.Name,
|
||||
OriginalText: t.Name,
|
||||
FontSize: 16,
|
||||
FontFamily: 1,
|
||||
TextAlign: "left",
|
||||
VerticalAlign: "top",
|
||||
LineHeight: 1.25,
|
||||
})
|
||||
}
|
||||
|
||||
scene := &Scene{
|
||||
Type: "excalidraw",
|
||||
Version: 2,
|
||||
Source: "mcables",
|
||||
Elements: els,
|
||||
AppState: AppState{
|
||||
GridSize: nil,
|
||||
ViewBackground: "#ffffff",
|
||||
},
|
||||
Files: Files{},
|
||||
}
|
||||
return scene, a
|
||||
}
|
||||
|
||||
func bindingPtr(b *Binding) *Binding {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// exportAnchor returns (x,y) + a Binding for the endpoint kind passed in.
|
||||
func exportAnchor(portID, deviceID, ioID *int64, snap *db.Snapshot,
|
||||
devElID, portElID, ioElID map[int64]string,
|
||||
) ([2]float64, *Binding) {
|
||||
if portID != nil {
|
||||
// Find the port + its parent device.
|
||||
for _, p := range snap.Ports {
|
||||
if p.ID != *portID {
|
||||
continue
|
||||
}
|
||||
for _, d := range snap.Devices {
|
||||
if d.ID == p.DeviceID {
|
||||
id := portElID[p.ID]
|
||||
return [2]float64{d.X + p.XOffset, d.Y + p.YOffset}, &Binding{ElementID: id, Focus: 0, Gap: 1}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if deviceID != nil {
|
||||
for _, d := range snap.Devices {
|
||||
if d.ID != *deviceID {
|
||||
continue
|
||||
}
|
||||
id := devElID[d.ID]
|
||||
return [2]float64{d.X + d.Width/2, d.Y + d.Height/2}, &Binding{ElementID: id, Focus: 0, Gap: 1}
|
||||
}
|
||||
}
|
||||
if ioID != nil {
|
||||
for _, m := range snap.IOMarkers {
|
||||
if m.ID != *ioID {
|
||||
continue
|
||||
}
|
||||
id := ioElID[m.ID]
|
||||
return [2]float64{m.X + 15, m.Y + 15}, &Binding{ElementID: id, Focus: 0, Gap: 1}
|
||||
}
|
||||
}
|
||||
return [2]float64{}, nil
|
||||
}
|
||||
|
||||
// Generate21 mints a 21-char base62 identifier, the shape Excalidraw
|
||||
// uses for element ids (nanoid-style). crypto/rand source.
|
||||
func Generate21() string {
|
||||
const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
buf := make([]byte, 21)
|
||||
max := big.NewInt(int64(len(alphabet)))
|
||||
for i := range buf {
|
||||
n, err := rand.Int(rand.Reader, max)
|
||||
if err != nil {
|
||||
// crypto/rand failure is unrecoverable in practice; fall back
|
||||
// to a deterministic alphabet position so callers see a panic-
|
||||
// adjacent symptom rather than a half-initialised id.
|
||||
return fmt.Sprintf("crypto-rand-failed-%d", i)
|
||||
}
|
||||
buf[i] = alphabet[n.Int64()]
|
||||
}
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
// randInt returns a non-negative int64 derived from crypto/rand for
|
||||
// Excalidraw's `seed` / `versionNonce`. Excalidraw treats these as
|
||||
// noise — only the IDs and the structural fields matter.
|
||||
func randInt() int64 {
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(1<<62))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return n.Int64()
|
||||
}
|
||||
|
||||
// MarshalScene returns the scene as Excalidraw-flavoured JSON.
|
||||
func MarshalScene(s *Scene) ([]byte, error) {
|
||||
return json.Marshal(s)
|
||||
}
|
||||
165
internal/exporter/exporter_test.go
Normal file
165
internal/exporter/exporter_test.go
Normal file
@@ -0,0 +1,165 @@
|
||||
package exporter
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"mgit.msbls.de/m/mcables/internal/db"
|
||||
)
|
||||
|
||||
// deterministic id generator for tests
|
||||
func newSeq() func() string {
|
||||
i := 0
|
||||
return func() string {
|
||||
i++
|
||||
return "id" + strings.Repeat("0", 19-len(itoa(i))) + itoa(i)
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(i int) string {
|
||||
if i == 0 {
|
||||
return "0"
|
||||
}
|
||||
buf := [20]byte{}
|
||||
pos := len(buf)
|
||||
for i > 0 {
|
||||
pos--
|
||||
buf[pos] = byte('0' + i%10)
|
||||
i /= 10
|
||||
}
|
||||
return string(buf[pos:])
|
||||
}
|
||||
|
||||
func sampleSnapshot() *db.Snapshot {
|
||||
pid := int64(1)
|
||||
devID := int64(10)
|
||||
devID2 := int64(11)
|
||||
portID := int64(100)
|
||||
portID2 := int64(101)
|
||||
ioID := int64(200)
|
||||
|
||||
return &db.Snapshot{
|
||||
Project: db.Project{ID: pid, Name: "LOFT", DrawingName: "LOFT.excalidraw"},
|
||||
Frames: []db.Frame{
|
||||
{ID: 1, ProjectID: pid, Name: "desk", X: 100, Y: 100, Width: 800, Height: 500},
|
||||
},
|
||||
Devices: []db.Device{
|
||||
{ID: devID, ProjectID: pid, Name: "NAS", Color: "#1e1e1e", X: 200, Y: 200, Width: 100, Height: 35, FrameID: ptr(int64(1))},
|
||||
{ID: devID2, ProjectID: pid, Name: "Switch", Color: "#1e1e1e", X: 400, Y: 200, Width: 100, Height: 35},
|
||||
},
|
||||
Ports: []db.Port{
|
||||
{ID: portID, ProjectID: pid, DeviceID: devID, TypeID: 5, XOffset: 50, YOffset: 35},
|
||||
{ID: portID2, ProjectID: pid, DeviceID: devID2, TypeID: 5, XOffset: 50, YOffset: 35},
|
||||
},
|
||||
IOMarkers: []db.IOMarker{
|
||||
{ID: ioID, ProjectID: pid, Label: "Wall A", X: 50, Y: 50},
|
||||
},
|
||||
Cables: []db.Cable{
|
||||
{ID: 1000, ProjectID: pid, TypeID: 5,
|
||||
FromPortID: &portID, ToPortID: &portID2, Auto: false},
|
||||
},
|
||||
CableTypes: []db.CableType{
|
||||
{ID: 1, Name: "Power", Color: "#e03131"},
|
||||
{ID: 2, Name: "USB", Color: "#2f9e44"},
|
||||
{ID: 3, Name: "HDMI", Color: "#1971c2"},
|
||||
{ID: 4, Name: "DP", Color: "#9c36b5"},
|
||||
{ID: 5, Name: "RJ45", Color: "#ffd500"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func ptr[T any](v T) *T { return &v }
|
||||
|
||||
func TestBuildScene_BasicShape(t *testing.T) {
|
||||
snap := sampleSnapshot()
|
||||
scene, ids := BuildScene(snap, 1700000000000, newSeq())
|
||||
|
||||
if scene.Type != "excalidraw" || scene.Version != 2 {
|
||||
t.Errorf("bad header: %+v", scene)
|
||||
}
|
||||
// frame(1) + device-rect+text(2 each) + ports(2) + io+text(2) +
|
||||
// cable(1) + legend(5) = 1 + 4 + 2 + 2 + 1 + 5 = 15.
|
||||
if len(scene.Elements) < 15 {
|
||||
t.Errorf("element count = %d, want ≥15", len(scene.Elements))
|
||||
}
|
||||
if len(ids.Frames) != 1 || len(ids.Devices) != 2 || len(ids.Ports) != 2 ||
|
||||
len(ids.IOMarkers) != 1 || len(ids.Cables) != 1 {
|
||||
t.Errorf("id assignment shape wrong: %+v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildScene_ReusesExistingExcalidrawIDs(t *testing.T) {
|
||||
snap := sampleSnapshot()
|
||||
// Pre-assign an excalidraw_id on the first device.
|
||||
preset := "preset0000000000000NAS"[:21]
|
||||
snap.Devices[0].ExcalidrawID = &preset
|
||||
_, ids := BuildScene(snap, 1700000000000, newSeq())
|
||||
if ids.Devices[snap.Devices[0].ID] != preset {
|
||||
t.Errorf("preset id not reused: got %q, want %q", ids.Devices[snap.Devices[0].ID], preset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildScene_ArrowsBindToPorts(t *testing.T) {
|
||||
snap := sampleSnapshot()
|
||||
scene, ids := BuildScene(snap, 1700000000000, newSeq())
|
||||
// The arrow's startBinding should reference the from-port's element id.
|
||||
fromPortElID := ids.Ports[100]
|
||||
toPortElID := ids.Ports[101]
|
||||
var found *Element
|
||||
for i := range scene.Elements {
|
||||
if scene.Elements[i].Type == "arrow" {
|
||||
found = &scene.Elements[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
t.Fatal("no arrow in scene")
|
||||
}
|
||||
if found.StartBinding == nil || found.StartBinding.ElementID != fromPortElID {
|
||||
t.Errorf("start binding wrong: %+v", found.StartBinding)
|
||||
}
|
||||
if found.EndBinding == nil || found.EndBinding.ElementID != toPortElID {
|
||||
t.Errorf("end binding wrong: %+v", found.EndBinding)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildScene_BundlesIgnored(t *testing.T) {
|
||||
snap := sampleSnapshot()
|
||||
// Snapshot.Bundles is unused in the exporter for v0 per design §4.1.
|
||||
// Add some and confirm no bundle elements appear in the scene.
|
||||
snap.Bundles = []db.Bundle{{ID: 1, Name: "trunk", CableIDs: []int64{1000}}}
|
||||
scene, _ := BuildScene(snap, 1700000000000, newSeq())
|
||||
for _, e := range scene.Elements {
|
||||
if strings.Contains(e.Type, "bundle") {
|
||||
t.Errorf("bundle element leaked into scene: %+v", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalScene_IsJSON(t *testing.T) {
|
||||
snap := sampleSnapshot()
|
||||
scene, _ := BuildScene(snap, 1700000000000, newSeq())
|
||||
b, err := MarshalScene(scene)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
var roundtrip map[string]any
|
||||
if err := json.Unmarshal(b, &roundtrip); err != nil {
|
||||
t.Fatalf("roundtrip: %v", err)
|
||||
}
|
||||
if roundtrip["type"] != "excalidraw" {
|
||||
t.Errorf("type field = %v, want excalidraw", roundtrip["type"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerate21(t *testing.T) {
|
||||
a := Generate21()
|
||||
b := Generate21()
|
||||
if len(a) != 21 || len(b) != 21 {
|
||||
t.Errorf("len wrong: %d / %d", len(a), len(b))
|
||||
}
|
||||
if a == b {
|
||||
t.Errorf("ids collide: %q == %q", a, b)
|
||||
}
|
||||
}
|
||||
122
internal/server/export.go
Normal file
122
internal/server/export.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mgit.msbls.de/m/mcables/internal/db"
|
||||
"mgit.msbls.de/m/mcables/internal/exporter"
|
||||
)
|
||||
|
||||
// syncExport runs the project's snapshot through the exporter, persists
|
||||
// the assigned excalidraw_ids, then PUTs the scene to mxdrw.msbls.de.
|
||||
func (h *handlers) syncExport(w http.ResponseWriter, r *http.Request) {
|
||||
pid, ok := parseInt64Path(r, "pid")
|
||||
if !ok {
|
||||
writeError(w, db.ErrInvalidInput, "pid must be a positive integer")
|
||||
return
|
||||
}
|
||||
|
||||
base := os.Getenv("MEXDRAW_BASE_URL")
|
||||
if base == "" {
|
||||
base = "https://mxdrw.msbls.de"
|
||||
}
|
||||
user := os.Getenv("MEXDRAW_USER")
|
||||
pass := os.Getenv("MEXDRAW_PASS")
|
||||
if user == "" || pass == "" {
|
||||
writeJSON(w, http.StatusBadRequest, errorBody{
|
||||
Error: "MEXDRAW_USER / MEXDRAW_PASS not set",
|
||||
Details: "Add MEXDRAW_USER and MEXDRAW_PASS to /home/m/secrets/mcables/.env on mDock and restart the container — mxdrw expects HTTP Basic Auth",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
snap, err := h.store.Snapshot(pid)
|
||||
if err != nil {
|
||||
writeError(w, err, nil)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
scene, ids := exporter.BuildScene(snap, now, exporter.Generate21)
|
||||
|
||||
// Persist the freshly-assigned ids so the next export reuses them.
|
||||
// We pass in the full maps; PersistExcalidrawIDs is idempotent (it
|
||||
// only updates rows whose excalidraw_id is still NULL).
|
||||
if err := h.store.PersistExcalidrawIDs(pid, ids.Frames, ids.Devices, ids.Ports, ids.IOMarkers, ids.Cables); err != nil {
|
||||
writeError(w, fmt.Errorf("persist excalidraw_ids: %w", err), nil)
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := exporter.MarshalScene(scene)
|
||||
if err != nil {
|
||||
writeError(w, fmt.Errorf("marshal scene: %w", err), nil)
|
||||
return
|
||||
}
|
||||
|
||||
drawingName := snap.Project.DrawingName
|
||||
if !strings.HasSuffix(drawingName, ".excalidraw") {
|
||||
drawingName += ".excalidraw"
|
||||
}
|
||||
url := strings.TrimSuffix(base, "/") + "/api/drawings/" + drawingName
|
||||
|
||||
// Sane network timeout; mxdrw is on the LAN so this should be quick.
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
writeError(w, fmt.Errorf("build PUT: %w", err), nil)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.SetBasicAuth(user, pass)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadGateway, errorBody{
|
||||
Error: "mxdrw unreachable",
|
||||
Details: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode >= 400 {
|
||||
writeJSON(w, http.StatusBadGateway, errorBody{
|
||||
Error: fmt.Sprintf("mxdrw rejected upload (%d)", resp.StatusCode),
|
||||
Details: map[string]any{
|
||||
"status": resp.StatusCode,
|
||||
"body": string(body),
|
||||
"url": url,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Best-effort parse — mxdrw returns whatever it returns; we surface
|
||||
// the public viewer URL no matter what.
|
||||
var serverEcho any
|
||||
_ = json.Unmarshal(body, &serverEcho)
|
||||
|
||||
viewerURL := strings.TrimSuffix(base, "/") + "/draw/" + strings.TrimSuffix(drawingName, ".excalidraw") + ".excalidraw"
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"drawing_name": drawingName,
|
||||
"url": viewerURL,
|
||||
"element_count": len(scene.Elements),
|
||||
"mxdrw_response": serverEcho,
|
||||
})
|
||||
}
|
||||
|
||||
// noLeak prevents unused-import errors if errors-pkg ever becomes unused
|
||||
// after a refactor — keeps the import light.
|
||||
var _ = errors.New
|
||||
@@ -90,6 +90,9 @@ func New(store *db.Store, frontend fs.FS) http.Handler {
|
||||
mux.HandleFunc("GET /api/setup-templates", h.listSetupTemplates)
|
||||
mux.HandleFunc("POST /api/projects/{pid}/apply-template", h.applyTemplate)
|
||||
|
||||
// Slice 8 — export to mxdrw.msbls.de
|
||||
mux.HandleFunc("POST /api/projects/{pid}/sync/export", h.syncExport)
|
||||
|
||||
// Frontend (embedded). Serve "/" → index.html via http.FileServerFS.
|
||||
// Wrap in noCache so the browser revalidates with the ETag/Last-Modified
|
||||
// the file server already emits — without this, browsers cache aggressively
|
||||
|
||||
@@ -22,9 +22,13 @@
|
||||
<div class="topbar-spacer"></div>
|
||||
<button type="button" id="btn-apply-template" class="btn">Apply template…</button>
|
||||
<button type="button" id="btn-solve" class="btn btn-primary">Solve</button>
|
||||
<button type="button" id="btn-export" class="btn" disabled title="Slice 8">
|
||||
Export
|
||||
</button>
|
||||
<button type="button" id="btn-export" class="btn">Export</button>
|
||||
<button type="button" id="btn-admin" class="btn" title="Admin: projects, cable types, device types, setup templates">⚙ Admin</button>
|
||||
<span class="zoom-cluster">
|
||||
<span id="zoom-pct" title="Zoom — scroll on canvas, or 0/Home to reset">100%</span>
|
||||
<button type="button" id="btn-fit" class="btn btn-tiny" title="Fit content to view">Fit</button>
|
||||
</span>
|
||||
<span id="toast" class="toast" hidden></span>
|
||||
</header>
|
||||
|
||||
<main class="layout">
|
||||
@@ -34,11 +38,6 @@
|
||||
<ul id="legend-list" class="legend-list"></ul>
|
||||
<button type="button" id="btn-add-type" class="btn btn-tiny">+ Type</button>
|
||||
</section>
|
||||
<section class="requirements">
|
||||
<h2 class="sidebar-heading">Requirements</h2>
|
||||
<ul id="requirement-list" class="requirement-list"></ul>
|
||||
<button type="button" id="btn-add-requirement" class="btn btn-tiny">+ Requirement</button>
|
||||
</section>
|
||||
<section class="tools">
|
||||
<h2 class="sidebar-heading">Tools</h2>
|
||||
<ul class="tool-list">
|
||||
@@ -225,6 +224,24 @@
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<!-- Admin: projects + cable types + device types + setup templates -->
|
||||
<dialog id="modal-admin" class="modal modal-wide" aria-labelledby="adm-title">
|
||||
<div class="admin-shell">
|
||||
<header class="admin-header">
|
||||
<h2 id="adm-title">Admin</h2>
|
||||
<button type="button" class="btn btn-link admin-close" data-close>✕</button>
|
||||
</header>
|
||||
<nav class="admin-tabs" role="tablist">
|
||||
<button type="button" class="admin-tab" data-admin-tab="projects" role="tab" aria-selected="true">Projects</button>
|
||||
<button type="button" class="admin-tab" data-admin-tab="cable-types" role="tab">Cable types</button>
|
||||
<button type="button" class="admin-tab" data-admin-tab="device-types" role="tab">Device types</button>
|
||||
<button type="button" class="admin-tab" data-admin-tab="setup-templates" role="tab">Setup templates</button>
|
||||
<button type="button" class="admin-tab" data-admin-tab="requirements" role="tab">Requirements</button>
|
||||
</nav>
|
||||
<section class="admin-body" id="admin-body" role="tabpanel"></section>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<script type="module" src="/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
1353
web/static/main.js
1353
web/static/main.js
File diff suppressed because it is too large
Load Diff
@@ -183,14 +183,27 @@ body {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Stroke + fill come from the device's user-set colour, written as
|
||||
inline style in renderCanvas — leaving them out of .device-rect so
|
||||
the author CSS doesn't override the inline style. */
|
||||
.device-rect {
|
||||
fill: #fff;
|
||||
stroke: var(--text);
|
||||
stroke-width: 1.5;
|
||||
}
|
||||
.device-rect.selected { stroke-width: 3; }
|
||||
.device-rect:hover { filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.15)); }
|
||||
|
||||
/* Bottom-right resize affordance per device. Subtle grey by default,
|
||||
stronger on hover so m can find it without it dominating the rect. */
|
||||
.device-resize-handle {
|
||||
fill: rgba(120, 120, 120, 0.35);
|
||||
stroke: rgba(60, 60, 60, 0.45);
|
||||
stroke-width: 1;
|
||||
cursor: nwse-resize;
|
||||
}
|
||||
.device-resize-handle:hover {
|
||||
fill: rgba(60, 60, 60, 0.65);
|
||||
}
|
||||
|
||||
.device-label {
|
||||
fill: var(--text);
|
||||
font-size: 12px;
|
||||
@@ -214,8 +227,6 @@ body {
|
||||
.canvas-wrap.tool-device #canvas *,
|
||||
.canvas-wrap.tool-io #canvas,
|
||||
.canvas-wrap.tool-io #canvas *,
|
||||
.canvas-wrap.tool-port #canvas,
|
||||
.canvas-wrap.tool-port #canvas *,
|
||||
.canvas-wrap.tool-cable #canvas,
|
||||
.canvas-wrap.tool-cable #canvas * { cursor: crosshair !important; }
|
||||
|
||||
@@ -236,6 +247,45 @@ body {
|
||||
filter: drop-shadow(0 0 4px var(--accent));
|
||||
}
|
||||
|
||||
/* Zoom cluster — % + Fit button next to Admin. */
|
||||
.zoom-cluster {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-left: 8px;
|
||||
padding-left: 12px;
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
#zoom-pct {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
min-width: 38px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.canvas-wrap.panning #canvas,
|
||||
.canvas-wrap.panning #canvas * { cursor: grabbing !important; }
|
||||
.canvas-wrap.space-pan-ready #canvas,
|
||||
.canvas-wrap.space-pan-ready #canvas * { cursor: grab !important; }
|
||||
|
||||
/* Header toast — slice 8 export feedback */
|
||||
.toast {
|
||||
display: inline-block;
|
||||
margin-left: 12px;
|
||||
font-size: 13px;
|
||||
padding: 4px 10px;
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface-2);
|
||||
color: var(--text);
|
||||
max-width: 420px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.toast.ok { background: #e8f5e9; color: #1b5e20; }
|
||||
.toast.error { background: #fdecea; color: #911313; }
|
||||
.toast a { color: inherit; text-decoration: underline; }
|
||||
|
||||
/* IO markers — diamonds. Power-by-convention, so the default fill is
|
||||
the Power cable_type colour (#e03131). Rotated 45° rect is the
|
||||
easiest way to draw a diamond that still hit-tests at the rotated
|
||||
@@ -259,16 +309,17 @@ body {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Ports — small circles laid out along the device edge. The fill is
|
||||
white so the port is visible regardless of the underlying device's
|
||||
stroke; the stroke colour comes from the cable_type the port carries
|
||||
(set inline in JS). */
|
||||
/* Ports — small circles laid out along the device edge. Both fill and
|
||||
stroke come from the cable_type the port carries (set inline in JS)
|
||||
so the port reads clearly as a coloured anchor on the device. */
|
||||
.port-circle {
|
||||
fill: #fff;
|
||||
stroke: var(--text);
|
||||
stroke-width: 2;
|
||||
cursor: crosshair;
|
||||
}
|
||||
.port-circle.selected {
|
||||
stroke-width: 3;
|
||||
filter: drop-shadow(0 0 4px var(--accent));
|
||||
}
|
||||
|
||||
.port-row {
|
||||
display: grid;
|
||||
@@ -276,13 +327,20 @@ body {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
padding: 2px 0;
|
||||
padding: 2px 4px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.port-row .swatch {
|
||||
.port-row:hover { background: var(--surface-2); }
|
||||
.port-row .swatch,
|
||||
.swatch {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid rgba(0, 0, 0, 0.15);
|
||||
margin-right: 6px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.port-row .label { color: var(--text); }
|
||||
.port-row .conn { color: var(--text-muted); font-size: 11px; }
|
||||
@@ -349,8 +407,121 @@ body {
|
||||
.cable-line:hover { stroke-width: 4; }
|
||||
.cable-line.selected { stroke-width: 4; }
|
||||
|
||||
/* Endpoint handles — only rendered for the currently-selected cable.
|
||||
Grab cursor on idle, grabbing while dragging (.replugging on root). */
|
||||
.cable-handle {
|
||||
cursor: grab;
|
||||
stroke-width: 2;
|
||||
filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.35));
|
||||
}
|
||||
.cable-handle:hover { stroke-width: 3; }
|
||||
.canvas-wrap.replugging .cable-handle,
|
||||
.canvas-wrap.replugging #canvas * { cursor: grabbing !important; }
|
||||
|
||||
/* Solve preview-diff modal */
|
||||
.modal-wide { width: 560px; }
|
||||
|
||||
/* Admin modal — wider, tabbed */
|
||||
.modal-wide.admin-shell-host { width: 760px; }
|
||||
#modal-admin { width: 760px; max-width: 90vw; }
|
||||
.admin-shell { padding: 16px; min-height: 460px; }
|
||||
.admin-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.admin-header h2 { margin: 0; }
|
||||
.admin-close { font-size: 16px; padding: 4px 8px; }
|
||||
.admin-tabs {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.admin-tab {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
padding: 8px 12px;
|
||||
font: inherit;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.admin-tab:hover { color: var(--text); }
|
||||
.admin-tab[aria-selected="true"] {
|
||||
color: var(--text);
|
||||
border-bottom-color: var(--accent);
|
||||
}
|
||||
.admin-body {
|
||||
font-size: 13px;
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.admin-row {
|
||||
display: grid;
|
||||
gap: 6px 12px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.admin-row:last-child { border-bottom: 0; }
|
||||
.admin-row .field { display: grid; grid-template-columns: 110px 1fr; align-items: center; }
|
||||
.admin-row .field span { color: var(--text-muted); font-size: 12px; }
|
||||
.admin-row .field input,
|
||||
.admin-row .field textarea,
|
||||
.admin-row .field select {
|
||||
width: 100%;
|
||||
font: inherit;
|
||||
padding: 4px 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
.admin-row .actions { display: flex; gap: 6px; justify-content: flex-end; }
|
||||
.admin-row.locked { opacity: 0.85; }
|
||||
.admin-row .locked-badge {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 3px;
|
||||
background: var(--surface-2);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.admin-row-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-weight: 600;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.admin-row-title .swatch { display: inline-block; }
|
||||
.admin-empty { color: var(--text-muted); padding: 16px 0; }
|
||||
.admin-add-row {
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.port-profile-list {
|
||||
margin: 4px 0 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.port-profile-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 2px 0;
|
||||
}
|
||||
.tmpl-detail {
|
||||
margin: 4px 0 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.tmpl-detail ul { margin: 4px 0 0 16px; padding: 0; }
|
||||
|
||||
.sv-body { font-size: 13px; }
|
||||
.sv-body h3 {
|
||||
font-size: 11px;
|
||||
|
||||
Reference in New Issue
Block a user