iso-explainer 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +119 -2
  3. package/README.pt-BR.md +89 -0
  4. package/bin/iso-explainer.mjs +75 -0
  5. package/package.json +37 -4
  6. package/skills/iso-explainer/SKILL.md +99 -0
  7. package/skills/iso-explainer/assets/figure/figure.mjs +93 -0
  8. package/skills/iso-explainer/assets/fonts/OFL.txt +93 -0
  9. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-400-normal.woff2 +0 -0
  10. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-500-normal.woff2 +0 -0
  11. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-600-normal.woff2 +0 -0
  12. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-700-normal.woff2 +0 -0
  13. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-800-normal.woff2 +0 -0
  14. package/skills/iso-explainer/assets/runtime/ANATOMY-LICENSE.txt +21 -0
  15. package/skills/iso-explainer/assets/runtime/LUCIDE-LICENSE.txt +43 -0
  16. package/skills/iso-explainer/assets/runtime/app.js +727 -0
  17. package/skills/iso-explainer/assets/runtime/engine.js +1224 -0
  18. package/skills/iso-explainer/assets/runtime/icons.js +205 -0
  19. package/skills/iso-explainer/assets/runtime/kit.js +676 -0
  20. package/skills/iso-explainer/assets/runtime/looks-core.js +162 -0
  21. package/skills/iso-explainer/assets/runtime/looks.js +508 -0
  22. package/skills/iso-explainer/assets/runtime/styles.css +461 -0
  23. package/skills/iso-explainer/assets/runtime/template.html +29 -0
  24. package/skills/iso-explainer/assets/templates/starter.course.json +134 -0
  25. package/skills/iso-explainer/examples/arquitetura-pedidos.docs.json +1745 -0
  26. package/skills/iso-explainer/examples/catalogo-looks.course.json +599 -0
  27. package/skills/iso-explainer/examples/engenharia-na-pratica.course.json +2079 -0
  28. package/skills/iso-explainer/examples/figures/token-bucket.build.mjs +111 -0
  29. package/skills/iso-explainer/examples/figures/token-bucket.html +962 -0
  30. package/skills/iso-explainer/examples/historia-pedidos.story.json +1874 -0
  31. package/skills/iso-explainer/references/architecture-mode.md +82 -0
  32. package/skills/iso-explainer/references/design-system.md +58 -0
  33. package/skills/iso-explainer/references/engine.md +64 -0
  34. package/skills/iso-explainer/references/entities.md +72 -0
  35. package/skills/iso-explainer/references/figure-craft.md +62 -0
  36. package/skills/iso-explainer/references/flows.md +67 -0
  37. package/skills/iso-explainer/references/inside.md +74 -0
  38. package/skills/iso-explainer/references/layout.md +134 -0
  39. package/skills/iso-explainer/references/looks.md +60 -0
  40. package/skills/iso-explainer/references/schema.md +157 -0
  41. package/skills/iso-explainer/references/story-mode.md +72 -0
  42. package/skills/iso-explainer/references/storytelling.md +56 -0
  43. package/skills/iso-explainer/scripts/build.mjs +82 -0
  44. package/skills/iso-explainer/scripts/harvest.mjs +240 -0
  45. package/skills/iso-explainer/scripts/lib/layout.mjs +111 -0
  46. package/skills/iso-explainer/scripts/lib/resolve.mjs +269 -0
  47. package/skills/iso-explainer/scripts/snapshot.mjs +159 -0
  48. package/skills/iso-explainer/scripts/validate.mjs +58 -0
@@ -0,0 +1,1224 @@
1
+ // iso-explainer · engine.js
2
+ // Isometric SVG stage: projection, primitives, entity renderers, dark-theme remap,
3
+ // and the Stage class (scene diff -> tween timeline, auto camera, link labels, packets).
4
+ // Original implementation. Depends on icons.js and looks.js (object looks built with the vendored anatomy kit).
5
+ import { ICONS } from './icons.js';
6
+ import { LOOKS, lookOf } from './looks.js';
7
+ import { lookP, PX_PER_Z, darkHex } from './looks-core.js';
8
+
9
+ /* ───────────────────────── numbers & projection ───────────────────────── */
10
+
11
+ export const r2 = (v) => Math.round(v * 100) / 100;
12
+ export const clamp01 = (v) => Math.max(0, Math.min(1, v));
13
+ export const lerp = (a, b, t) => a + (b - a) * t;
14
+ export const EASE = {
15
+ inOut: (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2),
16
+ out: (t) => 1 - (1 - t) ** 3,
17
+ back: (t) => 1 + 2.35 * (t - 1) ** 3 + 1.35 * (t - 1) ** 2,
18
+ };
19
+
20
+ // 2:1 dimetric projection. One grid unit = 28px wide x 14px tall tile.
21
+ // +x goes screen ↘ (down-right), +y goes screen ↗ (up-right), z lifts straight up.
22
+ export const iso = (x, y, z = 0) => [r2(14 * (x + y)), r2(7 * (x - y) - z)];
23
+ // Screen-aligned helper: col = one tile (28px) to the right, row = half a tile (14px) down.
24
+ export const fromColRow = (col, row) => [col + row, col - row];
25
+
26
+ // Affine maps for drawing flat 2D artwork onto planes (origin at iso(x,y,z)).
27
+ const mapRightFace = (x, y, z) => { const [a, b] = iso(x, y, z); return `matrix(1 -0.5 0 1 ${a} ${b})`; }; // plane x=const: u→+y, v→down
28
+ const mapTop = (x, y, z) => { const [a, b] = iso(x, y, z); return `matrix(1 -0.5 1 0.5 ${a} ${b})`; }; // floor: u→+y, v→+x
29
+ const mapTopX = (x, y, z) => { const [a, b] = iso(x, y, z); return `matrix(1 0.5 -1 0.5 ${a} ${b})`; }; // floor: u→+x, v→-y
30
+
31
+ /* ───────────────────────── colours ───────────────────────── */
32
+
33
+ export const INK = '#211e1b';
34
+ export const DROP = '#1c1a17';
35
+ // Block palette: top & side gradients (light → dark). Lowercase hex = remapped in dark theme.
36
+ export const PALETTE = {
37
+ orange: { top: ['#fee6cc', '#fcd4ad'], side: ['#f9c697', '#f3b47f'] },
38
+ green: { top: ['#e2f2d7', '#d1e9c2'], side: ['#c3e1b2', '#b3d79f'] },
39
+ blue: { top: ['#dfebf9', '#cde0f5'], side: ['#bcd3ef', '#a9c5e8'] },
40
+ yellow: { top: ['#fff3d6', '#fee7b8'], side: ['#fcdb9c', '#f6cd82'] },
41
+ purple: { top: ['#f2eaf9', '#e6dbf4'], side: ['#d9cbef', '#cbbae6'] },
42
+ teal: { top: ['#dcf3ef', '#c7ebe4'], side: ['#b2e0d7', '#9dd3c8'] },
43
+ rose: { top: ['#fde4e8', '#f9d0d8'], side: ['#f3bcc7', '#eaa8b6'] },
44
+ gray: { top: ['#f1ede7', '#e5dfd6'], side: ['#d9d2c7', '#cbc3b7'] },
45
+ slab: { top: ['#f7f0e7', '#f0e7dc'], side: ['#ece2d5', '#e3d7c8'] },
46
+ };
47
+ export const TONES = {
48
+ paper: { bg: '#fbf6ef', fg: INK },
49
+ red: { bg: '#f8d5cf', fg: '#8f2a22' },
50
+ green: { bg: '#dcefd2', fg: '#24521c' },
51
+ amber: { bg: '#fbe5bd', fg: '#6d4a0c' },
52
+ violet: { bg: '#e7ddf5', fg: '#47306f' },
53
+ blue: { bg: '#dbe8f7', fg: '#1f4f80' },
54
+ gray: { bg: '#ebe5dc', fg: '#5f5850' },
55
+ };
56
+ const LEVEL = (v) => (v < 0.6 ? '#7fc278' : v < 0.85 ? '#efb041' : '#e5534b');
57
+
58
+ // Dark theme remap (darkHex) lives in looks-core.js so figures share it.
59
+ export const isDark = () => typeof document !== 'undefined' && document.documentElement.dataset.theme === 'dark';
60
+ export const themed = (svg) => (!svg || !isDark() ? svg : svg.replace(/#[0-9a-f]{6}\b|#[0-9a-f]{3}\b/g, darkHex));
61
+
62
+ /* ───────────────────────── text & icons ───────────────────────── */
63
+
64
+ const esc = (s) => String(s ?? '').replace(/&(?![a-z#0-9]+;)/gi, '&amp;').replace(/</g, '&lt;');
65
+ let measureCtx = null;
66
+ const MONO_SAFE = /^[\u0000-ɏ -⯿]*$/;
67
+ export function textWidth(text, size, weight = 700) {
68
+ text = String(text);
69
+ if (MONO_SAFE.test(text) || typeof document === 'undefined') return text.length * size * 0.6; // JetBrains Mono advance = 0.6em
70
+ measureCtx ||= document.createElement('canvas').getContext('2d');
71
+ measureCtx.font = `${weight} ${size}px "JetBrains Mono", monospace`;
72
+ return measureCtx.measureText(text).width;
73
+ }
74
+ const svgText = (x, y, s, size = 12.5, weight = 700, fill = INK, extra = '') =>
75
+ `<text x="${r2(x)}" y="${r2(y)}" text-anchor="middle" font-size="${size}" font-weight="${weight}" fill="${fill}" ${extra}>${esc(s)}</text>`;
76
+
77
+ const attrs = (o) => Object.entries(o).map(([k, v]) => `${k}="${v}"`).join(' ');
78
+ const iconNodes = (name) => (ICONS[name] || ICONS.box).map(([t, a]) => `<${t} ${attrs(a)}/>`).join('');
79
+ // Icon as inline <svg> for HTML.
80
+ export function iconHTML(name, { size = 16, stroke = 1.9, cls = '' } = {}) {
81
+ return `<svg class="i ${cls}" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${stroke}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${iconNodes(name)}</svg>`;
82
+ }
83
+ // Icon as <g> centred on (cx, cy) inside the stage SVG.
84
+ export function iconSVG(name, cx, cy, size = 22, { stroke = 1.9, color = INK } = {}) {
85
+ const k = size / 24;
86
+ return `<g transform="translate(${r2(cx - size / 2)} ${r2(cy - size / 2)}) scale(${r2(k)})" fill="none" stroke="${color}" stroke-width="${r2(stroke / k)}" stroke-linecap="round" stroke-linejoin="round">${iconNodes(name)}</g>`;
87
+ }
88
+
89
+ /* ───────────────────────── path primitives ───────────────────────── */
90
+
91
+ // Closed polygon with rounded corners (r: number or per-vertex array).
92
+ export function roundPoly(pts, r) {
93
+ const n = pts.length, R = (i) => (Array.isArray(r) ? r[i] : r);
94
+ const toward = (a, b, d) => { const dx = b[0] - a[0], dy = b[1] - a[1], L = Math.hypot(dx, dy) || 1, k = Math.min(d, L / 2) / L; return [a[0] + dx * k, a[1] + dy * k]; };
95
+ let d = '';
96
+ for (let i = 0; i < n; i++) {
97
+ const p = pts[(i - 1 + n) % n], c = pts[i], q = pts[(i + 1) % n];
98
+ const a = toward(c, p, R(i)), b = toward(c, q, R(i));
99
+ d += `${i ? 'L' : 'M'}${r2(a[0])},${r2(a[1])} Q${r2(c[0])},${r2(c[1])} ${r2(b[0])},${r2(b[1])} `;
100
+ }
101
+ return d + 'Z';
102
+ }
103
+ // Open polyline with rounded joints.
104
+ export function roundLine(pts, r = 9) {
105
+ let d = `M${r2(pts[0][0])},${r2(pts[0][1])}`;
106
+ for (let i = 1; i < pts.length - 1; i++) {
107
+ const [ax, ay] = pts[i - 1], [bx, by] = pts[i], [cx, cy] = pts[i + 1];
108
+ const l1 = Math.hypot(bx - ax, by - ay), l2 = Math.hypot(cx - bx, cy - by);
109
+ if (l1 < 0.01 || l2 < 0.01) continue;
110
+ const k = Math.min(r, l1 / 2, l2 / 2);
111
+ d += ` L${r2(bx + ((ax - bx) / l1) * k)},${r2(by + ((ay - by) / l1) * k)} Q${r2(bx)},${r2(by)} ${r2(bx + ((cx - bx) / l2) * k)},${r2(by + ((cy - by) / l2) * k)}`;
112
+ }
113
+ const z = pts[pts.length - 1];
114
+ return d + ` L${r2(z[0])},${r2(z[1])}`;
115
+ }
116
+ export function pointInPoly([x, y], poly) {
117
+ let inside = false;
118
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
119
+ const [xi, yi] = poly[i], [xj, yj] = poly[j];
120
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
121
+ }
122
+ return inside;
123
+ }
124
+ // Trim the start of a polyline so it begins `gap` px outside `poly`.
125
+ export function clipStart(pts, poly, gap) {
126
+ if (!poly || !pointInPoly(pts[0], poly)) return pts;
127
+ for (let i = 0; i < pts.length - 1; i++) {
128
+ const a = pts[i], b = pts[i + 1];
129
+ if (pointInPoly(b, poly)) continue;
130
+ let lo = 0, hi = 1;
131
+ for (let k = 0; k < 28; k++) { const m = (lo + hi) / 2; pointInPoly([a[0] + (b[0] - a[0]) * m, a[1] + (b[1] - a[1]) * m], poly) ? (lo = m) : (hi = m); }
132
+ const L = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1, t = Math.min(1, hi + gap / L);
133
+ return [[a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], ...pts.slice(i + 1)];
134
+ }
135
+ return pts;
136
+ }
137
+ export const clipEnd = (pts, poly, gap) => clipStart([...pts].reverse(), poly, gap).reverse();
138
+ const boxOf = (pts, pad = [0, 0, 0, 0]) => {
139
+ const xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1]);
140
+ return [Math.min(...xs) - pad[0], Math.min(...ys) - pad[1], Math.max(...xs) + pad[2], Math.max(...ys) + pad[3]];
141
+ };
142
+ const overlap = (a, b) => Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0])) * Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1]));
143
+ const hits = (a, b) => a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1];
144
+ function pointAt(pts, t) {
145
+ const seg = []; let total = 0;
146
+ for (let i = 0; i < pts.length - 1; i++) { const L = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); seg.push(L); total += L; }
147
+ let d = total * t;
148
+ for (let i = 0; i < seg.length; i++) {
149
+ if (d <= seg[i] || i === seg.length - 1) {
150
+ const k = seg[i] ? Math.min(1, d / seg[i]) : 0, [ax, ay] = pts[i], [bx, by] = pts[i + 1];
151
+ return { x: ax + (bx - ax) * k, y: ay + (by - ay) * k, dx: (bx - ax) / (seg[i] || 1), dy: (by - ay) / (seg[i] || 1) };
152
+ }
153
+ d -= seg[i];
154
+ }
155
+ return { x: pts[0][0], y: pts[0][1], dx: 1, dy: 0 };
156
+ }
157
+ const samplePath = (pts, step = 12) => {
158
+ const out = [];
159
+ for (let i = 0; i < pts.length - 1; i++) {
160
+ const [ax, ay] = pts[i], [bx, by] = pts[i + 1], n = Math.max(1, Math.round(Math.hypot(bx - ax, by - ay) / step));
161
+ for (let k = 0; k <= n; k++) out.push([ax + ((bx - ax) * k) / n, ay + ((by - ay) * k) / n]);
162
+ }
163
+ return out;
164
+ };
165
+
166
+ /* ───────────────────────── iso prism ───────────────────────── */
167
+
168
+ // Rounded box from (x0,y0) to (x1,y1), height h. Returns paths + outline polygon.
169
+ export function prism({ x0, x1, y0, y1, h, radius = 9 }) {
170
+ const T = iso(x0, y1, h), R = iso(x1, y1, h), B = iso(x1, y0, h), L = iso(x0, y0, h);
171
+ const Rd = iso(x1, y1, 0), Bd = iso(x1, y0, 0), Ld = iso(x0, y0, 0);
172
+ const p = Math.max(1, Math.min(radius, h / 2 - 0.5));
173
+ const ty = iso((x0 + x1) / 2, (y0 + y1) / 2, h)[1];
174
+ const outline = [T, R, Rd, Bd, Ld, L];
175
+ return {
176
+ T, R, B, L, Rd, Bd, Ld, ty, outline,
177
+ sil: roundPoly(outline, [radius + 1, p, p, radius + 3, p, p]),
178
+ top: roundPoly([T, R, B, L], [radius + 1, p, 6, p]),
179
+ sheen: roundPoly([T, R, B, L].map(([x, y]) => [x, y - 3 + (y - ty) * -0.25]), [radius + 1, p, 6, p]),
180
+ right: roundPoly([B, R, Rd, Bd], [6, p, p, radius + 3]),
181
+ bevel: roundLine([L, B, R], 8),
182
+ };
183
+ }
184
+ function paintPrism(g, color, { stroke = '#484139', sw = 1 } = {}) {
185
+ return `
186
+ <path d="${g.sil}" fill="url(#g-${color}-side)"/>
187
+ <path d="${g.right}" fill="#3a2a14" opacity=".06"/>
188
+ <path d="${g.top}" fill="url(#g-${color}-top)"/>
189
+ <path d="${g.sheen}" fill="#ffffff" opacity=".22" filter="url(#blur-sm)"/>
190
+ <path class="prism-bevel" d="${g.bevel}" transform="translate(0 1.4)" fill="none" stroke="#ffffff" stroke-opacity=".55" stroke-width="1" stroke-linecap="round"/>
191
+ <path class="prism-outline" d="${g.sil}" fill="none" stroke="${stroke}" stroke-width="${sw}" stroke-linejoin="round"/>`;
192
+ }
193
+ const shadowOf = (g, h, lift, alpha) => {
194
+ const dy = Math.min(9, 3 + h * 0.15), fade = 1 - Math.min(1, lift / 140) * 0.85;
195
+ return `<path d="${g.sil}" transform="translate(0 ${r2(dy + lift)})" fill="#6b5236" opacity="${r2(alpha * fade)}" filter="url(#blur-lg)"/>`;
196
+ };
197
+
198
+ /* ───────────────────────── pills ───────────────────────── */
199
+
200
+ export const PILL_H = 21;
201
+ export const pillWidth = (text, size = 10.5, icon = null) =>
202
+ Math.max(...String(text).split('\n').map((l) => textWidth(l, size))) + 18 + (icon ? 15 : 0);
203
+ export function pill(cx, cy, text, { tone = 'paper', size = 10.5, icon = null } = {}) {
204
+ const t = TONES[tone] || TONES.paper, lines = String(text).split('\n');
205
+ const lh = Math.round(size * 1.3), h = PILL_H + (lines.length - 1) * lh;
206
+ const tw = Math.max(...lines.map((l) => textWidth(l, size))), w = tw + 18 + (icon ? 15 : 0);
207
+ const x = cx - w / 2, y = cy - h / 2, tx = x + 9 + (icon ? 15 : 0) + tw / 2;
208
+ const body = lines.map((l, i) => svgText(tx, cy + size * 0.36 + (i - (lines.length - 1) / 2) * lh, l, size, 700, t.fg)).join('');
209
+ return `<g class="pill">
210
+ <rect x="${r2(x)}" y="${r2(y + 1.5)}" width="${r2(w)}" height="${h}" rx="10.5" fill="${DROP}" opacity=".16"/>
211
+ <rect x="${r2(x)}" y="${r2(y)}" width="${r2(w)}" height="${h}" rx="10.5" fill="${t.bg}" stroke="#82776b" stroke-width=".85"/>
212
+ ${icon ? iconSVG(icon, x + 15, cy, 12, { stroke: 2.2, color: t.fg }) : ''}${body}</g>`;
213
+ }
214
+ function meterPill(cx, cy, v, icon = 'cpu') {
215
+ const x = cx - 43, y = cy - PILL_H / 2, bx = x + 23;
216
+ return `<g class="pill">
217
+ <rect x="${r2(x)}" y="${r2(y + 2)}" width="86" height="${PILL_H}" rx="10.5" fill="${DROP}"/>
218
+ <rect x="${r2(x)}" y="${r2(y)}" width="86" height="${PILL_H}" rx="10.5" fill="#fbf6ef" stroke="${INK}" stroke-width="1.3"/>
219
+ ${iconSVG(icon, x + 13, cy, 11, { stroke: 2.2, color: '#6f6961' })}
220
+ <rect x="${r2(bx)}" y="${r2(cy - 3.5)}" width="28" height="7" rx="3.5" fill="#e6ddd0"/>
221
+ <rect x="${r2(bx)}" y="${r2(cy - 3.5)}" width="${r2(Math.max(3, 28 * clamp01(v)))}" height="7" rx="3.5" fill="${LEVEL(v)}"/>
222
+ <text x="${r2(x + 77)}" y="${r2(cy + 3.6)}" text-anchor="end" font-size="10.5" font-weight="800" fill="${INK}">${Math.round(clamp01(v) * 100)}%</text></g>`;
223
+ }
224
+ // Stack of meter + tags above (or below) an anchor point.
225
+ function pillStack(e, cx, y0, below) {
226
+ const items = [];
227
+ if (e.cpu >= 0) items.push(meterPill(cx, 0, e.cpu, e.meterIcon || 'cpu'));
228
+ for (const t of e.tags || []) items.push(`<g opacity="${r2(e.tagFade ?? 1)}">${pill(cx, 0, t.text, t)}</g>`);
229
+ let y = y0, out = '';
230
+ for (const it of items) { out += `<g transform="translate(0 ${r2(y)})">${it}</g>`; y += below ? 26 : -26; }
231
+ return { svg: out, n: items.length };
232
+ }
233
+ const pillRect = (cx, cy, text, icon, size = 10.5) => { const w = pillWidth(text, size, icon); return [cx - w / 2, cy - PILL_H / 2, cx + w / 2, cy + PILL_H / 2 + 2]; };
234
+ function stackRects(e, cx, y0, below) {
235
+ const out = []; let y = y0;
236
+ if (e.cpu >= 0) { out.push([cx - 43, y - PILL_H / 2, cx + 43, y + PILL_H / 2 + 2]); y += below ? 26 : -26; }
237
+ for (const t of e.tags || []) { out.push(pillRect(cx, y, t.text, t.icon)); y += below ? 26 : -26; }
238
+ return out;
239
+ }
240
+ const stackHalfWidth = (e) => Math.max(0, e.cpu >= 0 ? 43 : 0, ...(e.tags || []).map((t) => pillWidth(t.text, 10.5, t.icon) / 2));
241
+ const widen = (b, cx, half) => (half ? [Math.min(b[0], cx - half - 5), b[1], Math.max(b[2], cx + half + 5), b[3]] : b);
242
+
243
+ /* ───────────────────────── entity renderers ─────────────────────────
244
+ Each returns { body, over, poly, bounds }:
245
+ body → depth-sorted geometry layer over → labels/pills (always on top)
246
+ poly → screen outline (links clip to it) bounds → [x0,y0,x1,y1] incl. pills */
247
+
248
+ const GLYPHS = {
249
+ server: (x, y, k = 1) => `<g transform="translate(${r2(x)} ${r2(y)}) scale(${k})" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linecap="round">
250
+ <rect x="-11" y="-10" width="22" height="8.5" rx="2.2"/><rect x="-11" y="1.5" width="22" height="8.5" rx="2.2"/>
251
+ <path d="M-6.5 -5.75h.01M-6.5 5.75h.01" stroke-width="2.6"/><path d="M1 -5.75h5.5M1 5.75h5.5"/></g>`,
252
+ balancer: (x, y, k = 1) => `<g transform="translate(${r2(x)} ${r2(y)}) scale(${k})" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
253
+ <circle cx="-8" cy="0" r="3" fill="${INK}"/><path d="M-5 0h4M-1 0C3 0 3-8 8-8M-1 0C3 0 3 8 8 8M-1 0h9"/>
254
+ <path d="M5.5-10.5l3 2.5-3 2.5M5.5-2.5l3 2.5-3 2.5M5.5 5.5l3 2.5-3 2.5"/></g>`,
255
+ };
256
+
257
+ export const DEFAULTS = {
258
+ block: { s: 4, h: 46, color: 'blue', glyph: 'server', label: [], sub: '', heat: 0, dead: 0, dim: 0, opacity: 1, lift: 0, cpu: -1, tags: [], pills: 'above' },
259
+ device: { form: 'laptop', w: 6, d: 6, dim: 0, label: '', tags: [], opacity: 1, lift: 0 },
260
+ db: { r: 1.7, h: 38, dim: 0, color: 'purple', glyph: 'database', label: '', tags: [], opacity: 1, lift: 0, heat: 0, dead: 0, cpu: -1 },
261
+ crowd: { count: 0, dim: 0, label: '', opacity: 1, lift: 0 },
262
+ queue: { n: 0, dim: 0, gap: 1, dir: [0, -1], opacity: 1, color: '#efb041' },
263
+ zone: { label: '', dim: 0, tone: 'paper', opacity: 1 },
264
+ ghost: { s: 6, dim: 0, h: 90, opacity: 1, label: '' },
265
+ panel: { title: '', icon: 'sparkles', lines: [], bars: [], w: 0, opacity: 1, lift: 0, corner: null },
266
+ };
267
+
268
+ // A block drawn as a look: the object stands on a plinth in the block's colour; state overlays
269
+ // (heat, dead, dim) and pills work as for plain blocks; the label moves to a plate below.
270
+ const lookCache = new Map();
271
+ const lookKey = (name, e) => `${name}|${e.d ?? e.s ?? e.r * 2}|${e.w ?? e.s ?? e.r * 2}|${e.color}|${e.items ?? ''}`;
272
+ function renderLook(e, name, se) {
273
+ const L = LOOKS[name], d = e.d ?? e.s ?? e.r * 2, w = e.w ?? e.s ?? e.r * 2, key = lookKey(name, e);
274
+ if (!lookCache.has(key)) lookCache.set(key, L.build(e, lookP([0, 0]), PALETTE[e.color] || PALETTE.blue));
275
+ const built = lookCache.get(key), st = se ? (se.look?.name === name ? se.look : (se.look = { name, s: L.state() })) : { s: L.state() };
276
+ const hx = d / 2, hy = w / 2, topPx = built.env.top * PX_PER_Z, lift = e.lift;
277
+ const g = prism({ x0: e.x - hx, x1: e.x + hx, y0: e.y - hy, y1: e.y + hy, h: topPx, radius: 9 });
278
+ const [ox, oy] = iso(e.x, e.y, 0);
279
+ const layers = built.layers.map((l) => (typeof l === 'string' ? l : `<g data-live="${l.live}">${l.draw(st.s, e)}</g>`)).join('');
280
+ const fade = 1 - e.dead * 0.5 - e.dim * 0.35;
281
+ const X = iso(e.x, e.y, 0)[0];
282
+ const body = `<g opacity="${r2(e.opacity)}">
283
+ ${shadowOf(g, topPx * 0.5, lift, 0.14)}
284
+ <g transform="translate(0 ${r2(-lift)})">
285
+ ${e.heat > 0.01 ? `<g class="pulse"><path d="${g.sil}" fill="#f0552f" opacity="${r2(e.heat * 0.55)}" filter="url(#glow)"/></g>` : ''}
286
+ <g class="look look--${name}" transform="translate(${r2(ox)} ${r2(oy)})" opacity="${r2(fade)}">${layers}</g>
287
+ ${e.heat > 0.01 ? `<path d="${g.sil}" fill="#f0552f" opacity="${r2(e.heat * 0.18)}"/>` : ''}
288
+ ${e.dead > 0.01 ? `<path d="${g.sil}" fill="#b9b2a8" opacity="${r2(e.dead * 0.55)}"/>` : ''}
289
+ ${e.dim > 0.01 ? `<path d="${g.sil}" fill="#f4ebe0" opacity="${r2(e.dim * 0.5)}"/>` : ''}
290
+ ${e.dead > 0.01 ? `<g opacity="${r2(e.dead)}" stroke="#c0392b" stroke-width="3.2" stroke-linecap="round"><path d="M${r2(X - 9)},${r2(g.ty - 10)} L${r2(X + 9)},${r2(g.ty + 8)} M${r2(X + 9)},${r2(g.ty - 10)} L${r2(X - 9)},${r2(g.ty + 8)}"/></g>` : ''}
291
+ </g></g>`;
292
+ const labels = Array.isArray(e.label) ? e.label : e.label ? [e.label] : [];
293
+ // name plate under the plinth: bold name in a pill, the sub line as quiet text beneath it
294
+ const name1 = labels.join(' '), ly = g.Bd[1] - lift + 15, subW = e.sub ? textWidth(e.sub, 9.5, 600) : 0;
295
+ let over = '';
296
+ const boxes = [boxOf(g.outline.map(([x, y]) => [x, y - lift]))];
297
+ if (name1) {
298
+ over += `<g opacity="${r2(e.labelFade ?? 1)}">${pill(X, ly, name1, { size: 11 })}${e.sub ? svgText(X, ly + 22, e.sub, 9.5, 600, '#6f6961', 'stroke="#f4ebe0" stroke-width="1.6" paint-order="stroke" stroke-linejoin="round"') : ''}</g>`;
299
+ const half = Math.max(pillWidth(name1, 11), subW) / 2;
300
+ boxes.push([X - half, ly - PILL_H / 2, X + half, ly + PILL_H / 2 + (e.sub ? 16 : 2)]);
301
+ }
302
+ const below = e.pills === 'below', y0 = below ? ly + 34 : g.T[1] - lift - 17;
303
+ const pe = name === 'database' ? { ...e, cpu: -1 } : e; // the database shows its level in the glass gauge
304
+ const stk = pillStack(pe, X, y0, below);
305
+ over = over || stk.svg ? `<g opacity="${r2(e.opacity)}">${over}${stk.svg}</g>` : '';
306
+ const poly = g.outline.map(([x, y]) => [x, y - lift]);
307
+ const bottom = (name1 ? (e.sub ? 46 : 32) : 14) + (below ? stk.n * 26 : 0);
308
+ return {
309
+ body, over, poly, live: !!L.tick,
310
+ boxes: [...boxes, ...stackRects(pe, X, y0, below)],
311
+ bounds: widen(boxOf(g.outline, [8, below ? 8 : 8 + Math.max(stk.n, 1) * 26, 8, bottom]), X, Math.max(stackHalfWidth(pe), name1 ? Math.max(pillWidth(name1, 11), subW) / 2 : 0)),
312
+ };
313
+ }
314
+
315
+ function renderBlock(e, se) {
316
+ const look = lookOf(e);
317
+ if (look) return renderLook(e, look, se);
318
+ const hx = (e.d ?? e.s) / 2, hy = (e.w ?? e.s) / 2;
319
+ const g = prism({ x0: e.x - hx, x1: e.x + hx, y0: e.y - hy, y1: e.y + hy, h: e.h, radius: e.radius ?? 9 });
320
+ const lift = e.lift, ty = g.ty;
321
+ const X = (iso(e.x - hx, e.y + hy, e.h)[0] + iso(e.x + hx, e.y - hy, e.h)[0]) / 2;
322
+ const labels = Array.isArray(e.label) ? e.label : e.label ? [e.label] : [];
323
+ const ly = ty + ((hx + hy) * 7 * 0.5 + e.h) * 0.4;
324
+ let text = '';
325
+ if (labels.length === 1 && !e.sub) text = svgText(X, ly + 4.5, labels[0], 13.5, 800);
326
+ else if (labels.length === 1) text = svgText(X, ly, labels[0], 13.5, 800) + svgText(X, ly + 14, e.sub, 10, 600);
327
+ else if (labels.length >= 2 && e.sub) text = svgText(X, ly - 9, labels[0], 13, 800) + svgText(X, ly + 6.5, labels[1], 13, 800) + svgText(X, ly + 20.5, e.sub, 10, 600);
328
+ else if (labels.length >= 2) text = svgText(X, ly - 3.5, labels[0], 13, 800) + svgText(X, ly + 12, labels[1], 13, 800);
329
+ const k = e.s >= 6 ? 1.15 : e.s < 3.5 ? 0.8 : 1;
330
+ const gy = labels.length ? ty - 1 : ty + 2;
331
+ const glyph = GLYPHS[e.glyph] ? GLYPHS[e.glyph](X, gy, k) : e.glyph ? iconSVG(e.glyph, X, gy, 24 * k, { stroke: 1.9 }) : '';
332
+ const fade = 1 - e.dead * 0.5 - e.dim * 0.35;
333
+ const cross = e.dead > 0.01 ? `<g opacity="${r2(e.dead)}" stroke="#c0392b" stroke-width="3.2" stroke-linecap="round"><path d="M${r2(X - 9)},${r2(ty - 10)} L${r2(X + 9)},${r2(ty + 8)} M${r2(X + 9)},${r2(ty - 10)} L${r2(X - 9)},${r2(ty + 8)}"/></g>` : '';
334
+ const body = `<g opacity="${r2(e.opacity)}">
335
+ ${shadowOf(g, e.h, lift, 0.18)}
336
+ <g transform="translate(0 ${r2(-lift)})">
337
+ ${e.heat > 0.01 ? `<g class="pulse"><path d="${g.sil}" fill="#f0552f" opacity="${r2(e.heat * 0.7)}" filter="url(#glow)"/></g>` : ''}
338
+ ${paintPrism(g, PALETTE[e.color] ? e.color : 'blue')}
339
+ ${e.heat > 0.01 ? `<path d="${g.sil}" fill="#f0552f" opacity="${r2(e.heat * 0.3)}"/>` : ''}
340
+ ${e.dead > 0.01 ? `<path d="${g.sil}" fill="#b9b2a8" opacity="${r2(e.dead * 0.62)}"/><path d="${g.sil}" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linejoin="round"/>` : ''}
341
+ ${e.dim > 0.01 ? `<path d="${g.sil}" fill="#f4ebe0" opacity="${r2(e.dim * 0.45)}"/>` : ''}
342
+ <g opacity="${r2(fade)}">${e.dead > 0.5 ? '' : glyph}<g opacity="${r2(e.labelFade ?? 1)}">${text}</g></g>
343
+ ${cross}
344
+ </g></g>`;
345
+ const below = e.pills === 'below';
346
+ const y0 = below ? g.Bd[1] - lift + 20 : g.T[1] - lift - 17;
347
+ const st = pillStack(e, X, y0, below);
348
+ const over = st.svg ? `<g opacity="${r2(e.opacity)}">${st.svg}</g>` : '';
349
+ const poly = g.outline.map(([x, y]) => [x, y - lift]);
350
+ return {
351
+ body, over, poly,
352
+ boxes: [boxOf(poly), ...stackRects(e, X, y0, below)],
353
+ bounds: widen(boxOf(g.outline, below ? [8, 8, 8, 14 + st.n * 26] : [8, 8 + Math.max(st.n, 1) * 26, 8, 14]), X, stackHalfWidth(e)),
354
+ };
355
+ }
356
+
357
+ // small flat box with three visible faces (used for laptop parts)
358
+ function boxFaces({ x0, x1, y0, y1, z0, z1 }, { top, front, left, sw = 1.5, r = 2 }) {
359
+ const T = [iso(x0, y0, z1), iso(x0, y1, z1), iso(x1, y1, z1), iso(x1, y0, z1)];
360
+ const F = [iso(x1, y0, z1), iso(x1, y1, z1), iso(x1, y1, z0), iso(x1, y0, z0)];
361
+ const Lf = [iso(x0, y0, z1), iso(x1, y0, z1), iso(x1, y0, z0), iso(x0, y0, z0)];
362
+ const O = [iso(x0, y0, z1), iso(x0, y1, z1), iso(x1, y1, z1), iso(x1, y1, z0), iso(x1, y0, z0), iso(x0, y0, z0)];
363
+ return `<path d="${roundPoly(Lf, r)}" fill="${left}"/><path d="${roundPoly(F, r)}" fill="${front}"/><path d="${roundPoly(T, r)}" fill="${top}"/>
364
+ <path d="${roundPoly(O, r)}" fill="none" stroke="${INK}" stroke-width="${sw}" stroke-linejoin="round"/>`;
365
+ }
366
+ const tagStackBounds = (tags = [], ax, outline) => {
367
+ const half = Math.max(0, ...tags.map((t) => pillWidth(t.text, 10.5, t.icon) / 2));
368
+ const xs = outline.map((p) => p[0]);
369
+ return [Math.max(8, Math.min(...xs) - (ax - half) + 8), 18 + tags.length * 26, Math.max(8, ax + half + 8 - Math.max(...xs)), 40];
370
+ };
371
+
372
+ function renderDevice(e) {
373
+ const x0 = e.x - e.d / 2, x1 = e.x + e.d / 2, y0 = e.y - e.w / 2, y1 = e.y + e.w / 2, lift = e.lift;
374
+ const base = prism({ x0, x1, y0, y1, h: 16, radius: 9 });
375
+ let art, anchor;
376
+ if (e.form === 'phone') {
377
+ const P = { x0: e.x - 0.2, x1: e.x + 0.25, y0: e.y - 1.2, y1: e.y + 1.2, z0: 17, z1: 80 };
378
+ const sw = (P.y1 - P.y0) * 14, sh = P.z1 - P.z0, iw = sw - 5;
379
+ const screen = `<rect x="2.5" y="2.5" width="${r2(iw)}" height="${r2(sh - 5)}" rx="3.5" fill="#FBF8F4"/>
380
+ <rect x="${r2(sw / 2 - 4)}" y="3.6" width="8" height="2.2" rx="1.1" fill="#3D3935"/>
381
+ <rect x="2.5" y="8" width="${r2(iw)}" height="7" fill="#E4D9CB"/>
382
+ <rect x="5" y="19" width="${r2(iw * 0.62)}" height="7" rx="3" fill="#ECE6DC"/>
383
+ <rect x="${r2(2.5 + iw * 0.32)}" y="29" width="${r2(iw * 0.6)}" height="7" rx="3" fill="#CBBAE6"/>
384
+ <rect x="5" y="39" width="${r2(iw * 0.5)}" height="7" rx="3" fill="#ECE6DC"/>
385
+ <rect x="5" y="${r2(sh - 12)}" width="${r2(iw - 5)}" height="5" rx="2.5" fill="#E4D9CB"/>
386
+ <rect x="2.5" y="2.5" width="${r2(iw)}" height="${r2(sh - 5)}" rx="3.5" fill="url(#screen-glare)"/>`;
387
+ art = `<path d="${roundPoly([iso(P.x0 - 0.5, P.y0 - 0.3, 16), iso(P.x0 - 0.5, P.y1 + 0.3, 16), iso(P.x1 + 0.9, P.y1 + 0.3, 16), iso(P.x1 + 0.9, P.y0 - 0.3, 16)], 5)}" fill="#6b5236" opacity=".16" filter="url(#blur-sm)"/>
388
+ ${boxFaces(P, { top: '#8B8580', front: '#3D3935', left: '#6E6862', r: 3.5 })}
389
+ <g transform="${mapRightFace(P.x1, P.y0, P.z1)}">${screen}</g>`;
390
+ anchor = iso(P.x0, e.y, P.z1);
391
+ } else {
392
+ const S = { x0: x0 + 0.7, x1: x0 + 1.05, y0: y0 + 0.9, y1: y1 - 0.9, z0: 19, z1: 66 }; // lid
393
+ const K = { x0: S.x1, x1: S.x1 + 2.7, y0: S.y0, y1: S.y1, z0: 16, z1: 19 }; // keyboard deck
394
+ const sw = (S.y1 - S.y0) * 14, sh = S.z1 - S.z0, cols = Math.floor((sw - 6) / 4.7);
395
+ let keys = '';
396
+ for (let r = 0; r < 4; r++) for (let c = 0; c < cols; c++) keys += `<rect x="${r2(3 + c * 4.7)}" y="${r2(2.5 + r * 4.3)}" width="3.8" height="3.3" rx=".7"/>`;
397
+ const iw = sw - 6.8, ih = sh - 8;
398
+ const screen = `<rect x="3.4" y="3.4" width="${r2(iw)}" height="${r2(ih)}" rx="1.5" fill="#FBF8F4"/>
399
+ <rect x="3.4" y="3.4" width="${r2(iw)}" height="7" rx="1.5" fill="#E4D9CB"/>
400
+ <circle cx="6.6" cy="6.9" r="1" fill="#E5534B"/><circle cx="9.6" cy="6.9" r="1" fill="#EFB041"/><circle cx="12.6" cy="6.9" r="1" fill="#7FC278"/>
401
+ <rect x="16" y="5" width="${r2(iw - 16)}" height="3.8" rx="1.9" fill="#FBF8F4"/>
402
+ <rect x="7" y="14.5" width="${r2(iw - 7.2)}" height="12" rx="1.5" fill="url(#screen)"/>
403
+ <rect x="7" y="29.5" width="${r2((iw - 7.2) * 0.62)}" height="2.6" rx="1.3" fill="#D6CCBF"/>
404
+ <rect x="7" y="34" width="${r2((iw - 7.2) * 0.8)}" height="2.6" rx="1.3" fill="#D6CCBF"/>
405
+ <rect x="3.4" y="3.4" width="${r2(iw)}" height="${r2(ih)}" rx="1.5" fill="url(#screen-glare)"/>`;
406
+ art = `<path d="${roundPoly([iso(S.x0 - 0.3, S.y0 - 0.3, 16), iso(S.x0 - 0.3, S.y1 + 0.3, 16), iso(K.x1 + 0.3, K.y1 + 0.3, 16), iso(K.x1 + 0.3, K.y0 - 0.3, 16)], 6)}" fill="#6b5236" opacity=".14" filter="url(#blur-sm)"/>
407
+ ${boxFaces(K, { top: '#efeae4', front: '#cfc8c0', left: '#ddd6ce', r: 2.5, sw: 1.4 })}
408
+ <g transform="${mapTop(K.x0 + 0.15, K.y0, K.z1)}" fill="#fbf8f4" stroke="#b9b1a7" stroke-width=".55">${keys}<rect x="${r2(sw / 2 - 10)}" y="21.5" width="20" height="9" rx="1.6"/></g>
409
+ ${boxFaces(S, { top: '#8B8580', front: '#3D3935', left: '#6E6862', r: 3 })}
410
+ <g transform="${mapRightFace(S.x1, S.y0, S.z1)}">${screen}</g>`;
411
+ anchor = iso(S.x0, (S.y0 + S.y1) / 2, S.z1);
412
+ }
413
+ const body = `<g opacity="${r2(e.opacity)}">${shadowOf(base, 16, lift, 0.2)}<g transform="translate(0 ${r2(-lift)})">${paintPrism(base, 'slab', { stroke: '#3b3631', sw: 1.5 })}${art}</g></g>`;
414
+ const [lx, ly] = iso(x1, y0, 0), [ax, ay] = anchor;
415
+ let over = e.label ? `<g opacity="${r2(e.labelFade ?? 1)}">${pill(lx, ly + 22, e.label, { icon: e.labelIcon || 'user' })}</g>` : '';
416
+ let ty = ay - 22;
417
+ for (const t of e.tags || []) { over += `<g transform="translate(0 ${r2(ty)})" opacity="${r2(e.tagFade ?? 1)}">${pill(ax, 0, t.text, t)}</g>`; ty -= 26; }
418
+ over = over ? `<g opacity="${r2(e.opacity)}" transform="translate(0 ${r2(-lift)})">${over}</g>` : '';
419
+ const dpoly = base.outline.map(([x, y]) => [x, y - lift]);
420
+ const dboxes = [boxOf([...dpoly, [anchor[0], anchor[1] - lift]])];
421
+ if (e.label) dboxes.push(pillRect(lx, ly + 22 - lift, e.label, 'x'));
422
+ (e.tags || []).forEach((tg, i) => dboxes.push(pillRect(ax, ay - 22 - i * 26 - lift, tg.text, tg.icon)));
423
+ return { body, over, poly: dpoly, boxes: dboxes, bounds: boxOf([...base.outline, anchor], tagStackBounds(e.tags, ax, base.outline)) };
424
+ }
425
+
426
+ function renderDb(e, se) {
427
+ const look = lookOf(e);
428
+ if (look) return renderLook(e, look, se);
429
+ const rx = Math.SQRT2 * 14 * e.r, ry = rx / 2, [cx, cy] = iso(e.x, e.y, 0), lift = e.lift;
430
+ const bot = cy - lift, top = bot - e.h;
431
+ const col = PALETTE[e.color] ? e.color : 'purple';
432
+ const shape = `M${r2(cx - rx)},${r2(top)} V${r2(bot)} A${r2(rx)},${r2(ry)} 0 0 0 ${r2(cx + rx)},${r2(bot)} V${r2(top)} Z`;
433
+ const edge = `M${r2(cx - rx)},${r2(top)} V${r2(bot)} A${r2(rx)},${r2(ry)} 0 0 0 ${r2(cx + rx)},${r2(bot)} V${r2(top)}`;
434
+ const fadeShadow = 1 - Math.min(1, lift / 140) * 0.85, f = e.cpu >= 0 ? clamp01(e.cpu) : 0;
435
+ let fill = '';
436
+ if (f > 0.004) {
437
+ const fy = bot - f * e.h, [c1, c2] = e.cpu < 0.6 ? ['#cfe8c0', '#5fa95a'] : e.cpu < 0.85 ? ['#f9dca3', '#d99a2b'] : ['#f5bdb2', '#d9473d'];
438
+ fill = `<path d="M${r2(cx - rx)},${r2(fy)} A${r2(rx)},${r2(ry)} 0 0 0 ${r2(cx + rx)},${r2(fy)} V${r2(bot)} A${r2(rx)},${r2(ry)} 0 0 1 ${r2(cx - rx)},${r2(bot)} Z" fill="${c1}" opacity=".92"/>
439
+ ${f < 0.995 ? `<path d="M${r2(cx - rx + 1)},${r2(fy)} A${r2(rx - 1)},${r2(ry - 0.5)} 0 0 0 ${r2(cx + rx - 1)},${r2(fy)}" fill="none" stroke="${c2}" stroke-width="1.6" stroke-linecap="round"/>` : ''}`;
440
+ }
441
+ const body = `<g opacity="${r2(e.opacity)}">
442
+ <ellipse cx="${r2(cx)}" cy="${r2(cy + 5)}" rx="${r2(rx + 3)}" ry="${r2(ry + 1)}" fill="#6b5236" opacity="${r2(0.22 * fadeShadow)}" filter="url(#blur-md)"/>
443
+ ${e.heat > 0.01 ? `<g class="pulse"><path d="${shape}" fill="#f0552f" opacity="${r2(e.heat * 0.7)}" filter="url(#glow)"/></g>` : ''}
444
+ <path d="${shape}" fill="url(#g-${col}-side)"/>${fill}<path d="${shape}" fill="url(#cyl-sheen)"/>
445
+ <ellipse cx="${r2(cx)}" cy="${r2(top)}" rx="${r2(rx)}" ry="${r2(ry)}" fill="url(#g-${col}-top)"/>
446
+ <path d="M${r2(cx - rx + 3)},${r2(top + 2.5)} A${r2(rx - 3)},${r2(ry - 2)} 0 0 0 ${r2(cx + rx - 3)},${r2(top + 2.5)}" fill="none" stroke="#ffffff" stroke-opacity=".7" stroke-width="1.4"/>
447
+ ${e.dead > 0.01 ? `<path d="${shape}" fill="#b9b2a8" opacity="${r2(e.dead * 0.62)}"/>` : ''}
448
+ <path d="${edge}" fill="none" stroke="${INK}" stroke-width="1.9" stroke-linejoin="round"/>
449
+ <ellipse cx="${r2(cx)}" cy="${r2(top)}" rx="${r2(rx)}" ry="${r2(ry)}" fill="none" stroke="${INK}" stroke-width="1.9"/>
450
+ ${e.glyph ? iconSVG(e.glyph, cx, top + ry + e.h / 2, 19, { stroke: 1.8 }) : ''}
451
+ ${e.dead > 0.01 ? `<g opacity="${r2(e.dead)}" stroke="#c0392b" stroke-width="3.2" stroke-linecap="round"><path d="M${r2(cx - 9)},${r2(top + 8)} L${r2(cx + 9)},${r2(top + 26)} M${r2(cx + 9)},${r2(top + 8)} L${r2(cx - 9)},${r2(top + 26)}"/></g>` : ''}
452
+ </g>`;
453
+ const lw = e.label ? pillWidth(e.label, 10.5, 'x') : 0;
454
+ let over = e.label ? `<g opacity="${r2(e.labelFade ?? 1)}">${pill(cx + rx + 10 + lw / 2, bot - e.h * 0.35, e.label, { icon: e.labelIcon || 'database' })}</g>` : '';
455
+ const st = pillStack(e, cx, top - ry - 15, false);
456
+ over += st.svg;
457
+ over = over ? `<g opacity="${r2(e.opacity)}">${over}</g>` : '';
458
+ const poly = [];
459
+ for (let i = 0; i <= 8; i++) poly.push([cx - rx * Math.cos((Math.PI * i) / 8), top - ry * Math.sin((Math.PI * i) / 8)]);
460
+ for (let i = 0; i <= 8; i++) poly.push([cx + rx * Math.cos((Math.PI * i) / 8), bot + ry * Math.sin((Math.PI * i) / 8)]);
461
+ const boxes = [[cx - rx, top - ry, cx + rx, bot + ry], ...stackRects(e, cx, top - ry - 15, false)];
462
+ if (e.label) boxes.push([cx + rx + 10, bot - e.h * 0.35 - PILL_H / 2, cx + rx + 10 + lw, bot - e.h * 0.35 + PILL_H / 2 + 2]);
463
+ return { body, over, poly, boxes, bounds: widen([cx - rx - 8, top - ry - 12 - st.n * 26, cx + rx + (e.label ? lw + 18 : 8), bot + ry + 10], cx, stackHalfWidth(e)) };
464
+ }
465
+
466
+ const PEOPLE = ['#F3B47F', '#A9C5E8', '#B3D79F', '#CBBAE6', '#F6CD82'];
467
+ const hash2 = (a, b) => { const n = Math.sin(a * 127.1 + b * 311.7) * 43758.5453; return n - Math.floor(n); };
468
+ function person(x, y, z, a, color) {
469
+ const [px, py] = iso(x, y, z), k = (0.35 + 0.65 * a) * 1.3;
470
+ return `<g opacity="${r2(a)}" transform="translate(${r2(px)} ${r2(py - (1 - a) * 10)}) scale(${r2(k)})">
471
+ <ellipse cx="0" cy="0" rx="5.6" ry="2.8" fill="#6b5236" opacity=".18"/>
472
+ <path d="M-5.2,0 V-9 A5.2,5.2 0 0 1 5.2,-9 V0 A5.2,2.4 0 0 1 -5.2,0 Z" fill="${color}" stroke="${INK}" stroke-width="1.25"/>
473
+ <circle cx="0" cy="-17.6" r="4.3" fill="#fdf6ec" stroke="${INK}" stroke-width="1.25"/></g>`;
474
+ }
475
+ function renderCrowd(e) {
476
+ const g = prism({ x0: e.x0, x1: e.x1, y0: e.y0, y1: e.y1, h: 10, radius: 8 });
477
+ const mx = (e.x0 + e.x1) / 2, my = (e.y0 + e.y1) / 2, sp = 1.75;
478
+ const ni = Math.floor(((e.x1 - e.x0) / 2 - 0.85) / sp), nj = Math.floor(((e.y1 - e.y0) / 2 - 0.85) / sp);
479
+ const cells = [];
480
+ for (let i = -ni; i <= ni; i++) for (let j = -nj; j <= nj; j++) cells.push({ i, j, key: Math.abs(i) + hash2(i, j) * 1.6 });
481
+ cells.sort((a, b) => a.key - b.key);
482
+ const people = cells.map((c, n) => ({ ...c, a: clamp01(e.count - n) })).filter((c) => c.a > 0.01)
483
+ .sort((a, b) => a.i - a.j - (b.i - b.j))
484
+ .map((c) => person(mx + c.i * sp, my + c.j * sp, 10, c.a, PEOPLE[Math.abs(c.i * 3 + c.j * 7) % PEOPLE.length])).join('');
485
+ const lift = e.lift, [lx, ly] = iso(e.x1, e.y0, 0);
486
+ return {
487
+ body: `<g opacity="${r2(e.opacity)}">${shadowOf(g, 10, lift, 0.2)}<g transform="translate(0 ${r2(-lift)})">${paintPrism(g, 'slab', { stroke: '#3b3631', sw: 1.5 })}${people}</g></g>`,
488
+ over: e.label ? `<g opacity="${r2(e.opacity * (e.labelFade ?? 1))}" transform="translate(0 ${r2(-lift)})">${pill(lx, ly + 22, e.label, { icon: 'users' })}</g>` : '',
489
+ poly: g.outline.map(([x, y]) => [x, y - lift]),
490
+ boxes: [boxOf(g.outline, [0, 30, 0, 0]), ...(e.label ? [pillRect(lx, ly + 22, e.label, 'x')] : [])],
491
+ bounds: boxOf(g.outline, [8, 34, 8, 40]),
492
+ };
493
+ }
494
+ function renderQueue(e) {
495
+ let body = ''; const pts = [];
496
+ for (let i = Math.ceil(e.n) - 1; i >= 0; i--) {
497
+ const a = clamp01(e.n - i), [x, y] = iso(e.x + e.dir[0] * e.gap * i, e.y + e.dir[1] * e.gap * i, 0);
498
+ pts.push([x, y]);
499
+ body += `<g opacity="${r2(a * e.opacity)}" transform="translate(${r2(x)} ${r2(y - (1 - a) * 8)}) scale(${r2(0.5 + a * 0.5)})"><circle r="4.6" fill="${e.color}" stroke="${INK}" stroke-width="1.5"/></g>`;
500
+ }
501
+ return { body, over: '', poly: null, bounds: pts.length ? boxOf(pts, [8, 8, 8, 8]) : [0, 0, 0, 0] };
502
+ }
503
+ function renderZone(e) {
504
+ const pts = [iso(e.x0, e.y0), iso(e.x0, e.y1), iso(e.x1, e.y1), iso(e.x1, e.y0)];
505
+ const fill = e.tone && e.tone !== 'paper' && TONES[e.tone] ? TONES[e.tone].bg : '#fffaf2';
506
+ const label = e.label ? `<text transform="${mapTopX(e.x0 + 0.9, e.y0 + 0.55, 0)}" font-size="10.5" font-weight="800" letter-spacing="1.6" fill="#6f6961">${esc(String(e.label).toUpperCase())}</text>` : '';
507
+ return {
508
+ body: `<g opacity="${r2(e.opacity)}"><path d="${roundPoly(pts, 8)}" fill="${fill}" fill-opacity=".55" stroke="${INK}" stroke-opacity=".55" stroke-width="1.5" stroke-dasharray="6 5"/>${label}</g>`,
509
+ over: '', poly: pts, bounds: boxOf(pts, [6, 6, 6, 6]),
510
+ };
511
+ }
512
+ function renderGhost(e) {
513
+ const x0 = e.x - e.s / 2, x1 = e.x + e.s / 2, y0 = e.y - e.s / 2, y1 = e.y + e.s / 2;
514
+ const t = [iso(x0, y0, e.h), iso(x0, y1, e.h), iso(x1, y1, e.h), iso(x1, y0, e.h)], b = [iso(x0, y0), iso(x0, y1), iso(x1, y1), iso(x1, y0)];
515
+ const ln = (p, q, back) => `<path d="M${p[0]},${p[1]} L${q[0]},${q[1]}" stroke="${INK}" stroke-opacity="${back ? 0.22 : 0.55}" stroke-width="1.4" stroke-dasharray="5 4" fill="none"/>`;
516
+ const lines = [ln(t[0], t[1]), ln(t[1], t[2]), ln(t[2], t[3]), ln(t[3], t[0]), ln(b[0], b[3]), ln(b[3], b[2]), ln(t[0], b[0]), ln(t[2], b[2]), ln(t[3], b[3]), ln(b[0], b[1], 1), ln(b[1], b[2], 1), ln(t[1], b[1], 1)].join('');
517
+ const [ux, uy] = t[2], lw = pillWidth(e.label || '', 10.5, 'x');
518
+ return {
519
+ body: `<g opacity="${r2(e.opacity)}">${lines}</g>`,
520
+ over: e.label ? `<g opacity="${r2(e.opacity)}">${pill(ux + 14 + lw / 2, uy + 18, e.label, { tone: 'gray', icon: e.icon || 'triangle' })}</g>` : '',
521
+ poly: null, bounds: boxOf([...t, ...b, [ux + 22 + lw, uy]], [8, 30, 8, 8]),
522
+ };
523
+ }
524
+ // Panel = a docked "info card" (lines with markers, optional bar chart). Lives in screen space.
525
+ // Line markers: "= " good row, "! " bad row, "# " muted comment, **bold** inline.
526
+ function richLine(s) {
527
+ return esc(s).split('**').map((p, i) => (i % 2 ? `<tspan font-weight="800" fill="${INK}">${p}</tspan>` : p)).join('');
528
+ }
529
+ const BAR = { green: '#9FD28F', amber: '#EFB041', red: '#E5534B', gray: '#B5AB9E', violet: '#CBBAE6', blue: '#A9C5E8' };
530
+ export function renderPanel(e) {
531
+ const strip = (l) => l.replace(/\*\*/g, '').replace(/^[=#!] /, '');
532
+ const labW = e.bars.length ? Math.max(...e.bars.map((b) => textWidth(b.label, 10.5))) + 14 : 0;
533
+ const noteW = e.bars.length ? Math.max(46, ...e.bars.map((b) => textWidth(b.note || '', 10) + 12)) : 0;
534
+ const W = Math.max(e.w, textWidth(e.title, 10) + e.title.length + 48, ...e.lines.map((l) => textWidth(strip(l), 11.5) + 30), e.bars.length ? labW + 184 + noteW : 0);
535
+ const chartH = e.bars.length * 19;
536
+ const H = 34 + e.lines.length * 18 + (e.bars.length ? chartH + 12 : 0) + 6;
537
+ const w = e.boxW ?? W, h = e.boxH ?? H, x = 0, y = 0;
538
+ let rows = '';
539
+ e.lines.forEach((l, i) => {
540
+ const ly = y + 34 + i * 18 + 12;
541
+ if (l.startsWith('= ')) rows += `<rect x="${x + 10}" y="${ly - 13}" width="${W - 20}" height="18" rx="5" fill="#dcefd2"/><text x="${x + 16}" y="${ly}" font-size="11.5" font-weight="800" fill="#24521c">${richLine(l.slice(2))}</text>`;
542
+ else if (l.startsWith('! ')) rows += `<rect x="${x + 10}" y="${ly - 13}" width="${W - 20}" height="18" rx="5" fill="#f8d5cf"/><text x="${x + 16}" y="${ly}" font-size="11.5" font-weight="800" fill="#8f2a22">${richLine(l.slice(2))}</text>`;
543
+ else if (l.startsWith('# ')) rows += `<text x="${x + 16}" y="${ly}" font-size="10.5" font-weight="500" fill="#8b847a">${richLine(l.slice(2))}</text>`;
544
+ else rows += `<text x="${x + 16}" y="${ly}" font-size="11.5" font-weight="500" fill="#34302b">${richLine(l)}</text>`;
545
+ });
546
+ let bars = '';
547
+ if (e.bars.length) {
548
+ const top = y + 34 + e.lines.length * 18 + 8, bx = x + 16 + labW, bw = W - 32 - labW - noteW;
549
+ e.bars.forEach((b, i) => {
550
+ const by = top + i * 19, from = b.from || 0, to = b.to ?? b.value ?? 1, ax = bx + from * bw, aw = Math.max(3, (to - from) * bw);
551
+ bars += `<text x="${x + 16}" y="${r2(by + 12)}" font-size="10.5" font-weight="${b.bold ? 800 : 500}" fill="#34302b">${esc(b.label)}</text>
552
+ <rect x="${r2(bx)}" y="${r2(by + 3)}" width="${r2(bw)}" height="11" rx="3" fill="#f1e8db"/>
553
+ <rect x="${r2(ax)}" y="${r2(by + 3)}" width="${r2(aw)}" height="11" rx="3" fill="${BAR[b.tone || 'gray']}" stroke="${INK}" stroke-opacity=".55" stroke-width="1"/>
554
+ <text x="${r2(ax + aw + 6)}" y="${r2(by + 12)}" font-size="10" font-weight="800" fill="${INK}">${esc(b.note || '')}</text>`;
555
+ });
556
+ }
557
+ const svg = `<g opacity="${r2(e.opacity)}">
558
+ <rect x="${x}" y="${y + 2.5}" width="${r2(w)}" height="${r2(h)}" rx="10" fill="${DROP}"/>
559
+ <rect x="${x}" y="${y}" width="${r2(w)}" height="${r2(h)}" rx="10" fill="#fbf7f1" stroke="${INK}" stroke-width="1.4"/>
560
+ <path d="M${x + 12},${y + 30} H${r2(x + w - 12)}" stroke="#e6ddd0" stroke-width="1"/>
561
+ <g opacity="${r2(e.fade ?? 1)}">
562
+ ${iconSVG(e.icon, x + 20, y + 18, 13, { stroke: 2.1, color: '#6f6961' })}
563
+ <text x="${x + 33}" y="${y + 21.5}" font-size="10" font-weight="800" letter-spacing="1" fill="#6f6961">${esc(String(e.title).toUpperCase())}</text>
564
+ ${rows}${bars}
565
+ </g></g>`;
566
+ return { body: '', over: svg, poly: null, bounds: null, size: { w: W, h: H } };
567
+ }
568
+
569
+ export const RENDER = { block: renderBlock, device: renderDevice, db: renderDb, crowd: renderCrowd, queue: renderQueue, zone: renderZone, ghost: renderGhost, panel: renderPanel };
570
+ const FLOOR = new Set(['zone']);
571
+ export const withDefaults = (e) => ({ ...DEFAULTS[e.type], ...e });
572
+ export function footprint(e) { // iso-space rect [x0,x1,y0,y1]
573
+ if (e.type === 'crowd' || e.type === 'zone') return [e.x0, e.x1, e.y0, e.y1];
574
+ if (e.type === 'device') return [e.x - e.d / 2, e.x + e.d / 2, e.y - e.w / 2, e.y + e.w / 2];
575
+ if (e.type === 'db') return [e.x - e.r, e.x + e.r, e.y - e.r, e.y + e.r];
576
+ const hx = (e.d ?? e.s ?? 4) / 2, hy = (e.w ?? e.s ?? 4) / 2;
577
+ return [e.x - hx, e.x + hx, e.y - hy, e.y + hy];
578
+ }
579
+ export const centerOf = (e) => (e.type === 'crowd' || e.type === 'zone' ? [(e.x0 + e.x1) / 2, (e.y0 + e.y1) / 2] : [e.x, e.y]);
580
+ const depthKey = (e) => (e.type === 'zone' ? -1e4 : e.type === 'queue' ? -1e3 : e.type === 'panel' ? 1e4 : centerOf(e)[0] - centerOf(e)[1] - (e.type === 'ghost' ? 0.5 : 0));
581
+
582
+ // Resolve a link waypoint: "id", "id+2", [x,y], ["idA","idB"] (x of A, y of B), ["id+1", 4]…
583
+ export function resolvePoint(p, centerOfId) {
584
+ const one = (s, axis) => { const m = /^([\w.-]+?)([+-][\d.]+)?$/.exec(s); const c = centerOfId(m[1]); if (!c) throw new Error(`unknown entity "${m[1]}" in link point`); return c[axis] + (m[2] ? parseFloat(m[2]) : 0); };
585
+ if (typeof p === 'string') return [one(p, 0), one(p, 1)];
586
+ return [typeof p[0] === 'string' ? one(p[0], 0) : p[0], typeof p[1] === 'string' ? one(p[1], 1) : p[1]];
587
+ }
588
+
589
+ /* ───────────────────────── link labels ───────────────────────── */
590
+
591
+ const LABEL_SIZE = 9.5;
592
+ const labelBox = (text) => { const lines = String(text).split('\n'); return { w: pillWidth(text, LABEL_SIZE), h: PILL_H + (lines.length - 1) * Math.round(LABEL_SIZE * 1.3) }; };
593
+ // Candidate label spots along a path (screen px). Each: { key, cx, cy, rect }.
594
+ function labelSpots(pts, t0, w, h) {
595
+ const out = [];
596
+ [0, -0.08, 0.08, -0.16, 0.16, -0.24, 0.24, -0.32, 0.32, -0.4, 0.4].forEach((dt, k) => {
597
+ const t = t0 + dt;
598
+ if (k && (t < 0.06 || t > 0.94)) return;
599
+ const p = pointAt(pts, t), nx = -p.dy, ny = p.dx;
600
+ // on the line itself (pill has an opaque fill), then beside it, near and far
601
+ out.push({ t, side: 0, gap: 0, cx: p.x, cy: p.y, rect: [p.x - w / 2, p.y - h / 2, p.x + w / 2, p.y + h / 2], drift: Math.abs(dt) + 0.1, onLine: true });
602
+ [7, 19].forEach((gap, gi) => {
603
+ const off = Math.abs(nx) * (w / 2) + Math.abs(ny) * (h / 2) + gap;
604
+ [1, -1].forEach((side) => {
605
+ const cx = p.x + nx * off * side, cy = p.y + ny * off * side;
606
+ out.push({ t, side, gap, cx, cy, rect: [cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], drift: Math.abs(dt) + gi * 0.12 });
607
+ });
608
+ });
609
+ });
610
+ return out;
611
+ }
612
+ function spotAt(pts, pick, w, h) {
613
+ const p = pointAt(pts, pick.t), nx = -p.dy, ny = p.dx, off = Math.abs(nx) * (w / 2) + Math.abs(ny) * (h / 2) + (pick.gap ?? 7);
614
+ if (!pick.side) return [p.x, p.y];
615
+ return [p.x + nx * off * pick.side, p.y + ny * off * pick.side];
616
+ }
617
+
618
+ /* ───────────────────────── Stage ───────────────────────── */
619
+
620
+ const NS = 'http://www.w3.org/2000/svg';
621
+ const el = (tag, a = {}) => { const n = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(a)) n.setAttribute(k, v); return n; };
622
+ export const TIMING = { exit: 420, move: 820, enter: 680, stagger: 130, draw: 560 };
623
+ const MAX_ZOOM = 1.6, MIN_ZOOM = 0.3, PAD = 16, HEAD_GAP = 16;
624
+ const PKT_SPEED = 155, KIND_SPEED = { heavy: 0.7, ping: 0.85, slow: 0.32 };
625
+ const ENTER_FROM = { crowd: { count: 0, lift: 26 }, device: { lift: 40 }, ghost: {}, zone: {}, queue: { n: 0, opacity: 1 }, panel: { lift: -14 } };
626
+ const EXIT_TO = { crowd: { count: 0 }, queue: { n: 0, opacity: 1 }, ghost: {}, zone: {}, panel: { lift: -10 } };
627
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
628
+
629
+ function defsSVG(gridPatternId) {
630
+ let g = '';
631
+ for (const [k, c] of Object.entries(PALETTE)) {
632
+ g += `<linearGradient id="g-${k}-top" x1="0" y1="0" x2="0.35" y2="1"><stop offset="0" stop-color="${c.top[0]}"/><stop offset="1" stop-color="${c.top[1]}"/></linearGradient>
633
+ <linearGradient id="g-${k}-side" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${c.side[0]}"/><stop offset="1" stop-color="${c.side[1]}"/></linearGradient>`;
634
+ }
635
+ return `${g}
636
+ <linearGradient id="screen" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#E3D6F3"/><stop offset="1" stop-color="#C9B5E6"/></linearGradient>
637
+ <linearGradient id="screen-glare" x1="0" y1="0" x2="1" y2="0.6"><stop offset="0" stop-color="#FFFFFF" stop-opacity=".35"/><stop offset=".45" stop-color="#FFFFFF" stop-opacity="0"/></linearGradient>
638
+ <linearGradient id="cyl-sheen" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#ffffff" stop-opacity="0"/><stop offset=".3" stop-color="#ffffff" stop-opacity=".35"/><stop offset=".55" stop-color="#ffffff" stop-opacity=".05"/><stop offset="1" stop-color="#4b2f6b" stop-opacity=".08"/></linearGradient>
639
+ <filter id="blur-sm" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="2.2"/></filter>
640
+ <filter id="blur-md" x="-30%" y="-30%" width="160%" height="160%"><feGaussianBlur stdDeviation="4"/></filter>
641
+ <filter id="blur-lg" x="-30%" y="-30%" width="160%" height="160%"><feGaussianBlur stdDeviation="6.5"/></filter>
642
+ <filter id="glow" x="-40%" y="-40%" width="180%" height="180%"><feGaussianBlur stdDeviation="9"/></filter>
643
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.6" refY="5" markerWidth="5.2" markerHeight="5.2" orient="auto-start-reverse" markerUnits="strokeWidth"><path d="M1,1.2 L9,5 L1,8.8 Z" fill="${INK}" stroke="${INK}" stroke-width="1" stroke-linejoin="round"/></marker>
644
+ <marker id="arrow-muted" viewBox="0 0 10 10" refX="8.6" refY="5" markerWidth="5.2" markerHeight="5.2" orient="auto-start-reverse" markerUnits="strokeWidth"><path d="M1,1.2 L9,5 L1,8.8 Z" fill="#a59c90" stroke="#a59c90" stroke-width="1" stroke-linejoin="round"/></marker>
645
+ <marker id="arrow-red" viewBox="0 0 10 10" refX="8.6" refY="5" markerWidth="5.2" markerHeight="5.2" orient="auto-start-reverse" markerUnits="strokeWidth"><path d="M1,1.2 L9,5 L1,8.8 Z" fill="#c0392b" stroke="#c0392b" stroke-width="1" stroke-linejoin="round"/></marker>
646
+ <pattern id="${gridPatternId}" patternUnits="userSpaceOnUse" x="0" y="-7" width="28" height="14"><path d="M0 7 L14 0 L28 7 L14 14 Z" fill="none" stroke="#a8916f" stroke-opacity=".3" stroke-width=".8"/></pattern>`;
647
+ }
648
+
649
+ let stageCount = 0;
650
+ export class Stage {
651
+ constructor(host, { reducedMotion = false } = {}) {
652
+ this.host = host;
653
+ this.reduced = reducedMotion;
654
+ // Fragment IDs resolve across the document, including when two SVG stages are open.
655
+ const gridId = `isx-grid-${++stageCount}`, fadeId = `${gridId}-fade`, maskId = `${gridId}-mask`;
656
+ this.gridPatternId = `${gridId}-pattern`;
657
+ this.svg = el('svg', { class: 'stage-svg', xmlns: NS, preserveAspectRatio: 'xMidYMid meet', role: 'img' });
658
+ this.svg.innerHTML = `<defs class="defs-theme">${themed(defsSVG(this.gridPatternId))}</defs>
659
+ <defs><radialGradient id="${fadeId}" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff"/><stop offset=".42" stop-color="#fff" stop-opacity=".92"/><stop offset=".78" stop-color="#fff" stop-opacity=".35"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></radialGradient>
660
+ <mask id="${maskId}" maskUnits="userSpaceOnUse" x="-6000" y="-6000" width="12000" height="12000"><rect x="-6000" y="-6000" width="12000" height="12000" fill="url(#${fadeId})"/></mask></defs>
661
+ <rect class="stage-grid" x="-6000" y="-6000" width="12000" height="12000" fill="url(#${this.gridPatternId})" mask="url(#${maskId})"/>
662
+ <g class="layer-floor"></g><g class="layer-links"></g><g class="layer-packets"></g><g class="layer-ents"></g><g class="layer-over"></g><g class="layer-hud"></g>`;
663
+ host.appendChild(this.svg);
664
+ const q = (s) => this.svg.querySelector(s);
665
+ this.L = { floor: q('.layer-floor'), links: q('.layer-links'), packets: q('.layer-packets'), ents: q('.layer-ents'), over: q('.layer-over'), hud: q('.layer-hud') };
666
+ this.fadeGrad = q(`#${fadeId}`);
667
+ this.defs = q('.defs-theme');
668
+ this.ents = new Map(); this.links = new Map(); this.plans = new Map();
669
+ this.scenes = []; this.scene = null; this.flows = []; this.packets = [];
670
+ this.anim = null; this.paused = false; this.view = null; this.blend = null;
671
+ this.showCards = true; this.hudScale = 1.12; this.last = performance.now();
672
+ this.onCards = null; this.onView = null; this.onSwipe = null; this.onSettle = null;
673
+ this.size = '';
674
+ this.onInspect = null;
675
+ this.ro = new ResizeObserver(() => { const s = `${host.clientWidth}x${host.clientHeight}`; if (s !== this.size) { this.size = s; this.refit(); } });
676
+ this.ro.observe(host);
677
+ this.gestures();
678
+ // entities with `inside` open their drill-down on click / Enter
679
+ const pick = (ev) => { const g = ev.target.closest?.('[data-id]'); const e = g && this.ents.get(g.dataset.id); return e && e.cur.inside ? e : null; };
680
+ this.svg.addEventListener('click', (ev) => {
681
+ const e = pick(ev);
682
+ if (e) { ev.stopPropagation(); this.onInspect?.(e.id, e.cur); return; }
683
+ const g = ev.target.closest?.('[data-id]'), other = g && this.ents.get(g.dataset.id);
684
+ if (other && !['zone', 'queue', 'panel'].includes(other.cur.type)) this.onPlainClick?.(other.id, other.cur);
685
+ });
686
+ this.svg.addEventListener('keydown', (ev) => { if (ev.key !== 'Enter' && ev.key !== ' ') return; const e = pick(ev); if (e) { ev.preventDefault(); ev.stopPropagation(); this.onInspect?.(e.id, e.cur); } });
687
+ const loop = (t) => { if (this.dead) return; this.tick(t); requestAnimationFrame(loop); };
688
+ requestAnimationFrame(loop);
689
+ }
690
+ destroy() { this.dead = true; this.ro.disconnect(); this.clear(); this.svg.remove(); }
691
+ // Zoom the camera into one entity (used before opening its inside view).
692
+ focusOn(id, k = 2.4) {
693
+ const e = this.ents.get(id); if (!e?.bounds) return;
694
+ const [x0, y0, x1, y1] = e.poly ? [Math.min(...e.poly.map((p) => p[0])), Math.min(...e.poly.map((p) => p[1])), Math.max(...e.poly.map((p) => p[0])), Math.max(...e.poly.map((p) => p[1]))] : e.bounds;
695
+ this.setView({ k, cx: (x0 + x1) / 2, cy: (y0 + y1) / 2 }, true);
696
+ }
697
+
698
+ /* ── layout & camera ── */
699
+ layoutOf(scene) {
700
+ const ents = Object.fromEntries(Object.entries(scene.entities || {}).map(([k, v]) => [k, withDefaults(v)]));
701
+ const center = (id) => ents[id] && centerOf(ents[id]);
702
+ const boxes = [], polys = [], obstacles = [], texts = [], labelRects = [];
703
+ let b = [Infinity, Infinity, -Infinity, -Infinity], panel = null;
704
+ const grow = (r) => { b = [Math.min(b[0], r[0]), Math.min(b[1], r[1]), Math.max(b[2], r[2]), Math.max(b[3], r[3])]; };
705
+ const shapes = {};
706
+ // Focus steps (docs/story "dim" pattern): the camera frames what is in focus; dimmed context stays
707
+ // visible around it but does not shrink the picture. Without focus, everything is framed.
708
+ const inFocus = (e) => (e.dim || 0) < 0.5;
709
+ const focusing = Object.values(ents).filter((e) => e.type !== 'panel' && e.type !== 'zone').some((e) => !inFocus(e))
710
+ && Object.values(ents).filter((e) => e.type !== 'panel' && e.type !== 'zone' && inFocus(e)).length >= 2;
711
+ for (const [id, e] of Object.entries(ents)) {
712
+ if (e.type === 'panel') { if (this.showCards) panel = { ...renderPanel(e).size, corner: e.corner }; continue; }
713
+ const r = RENDER[e.type](e);
714
+ shapes[id] = r.poly; if (!focusing || (inFocus(e) && e.type !== 'zone')) grow(r.bounds); boxes.push(r.bounds);
715
+ if (e.type !== 'zone') { const bx = r.boxes || [r.bounds]; obstacles.push(bx[0]); texts.push(...bx.slice(1)); }
716
+ if (r.poly && e.type !== 'zone') polys.push(r.poly);
717
+ }
718
+ const paths = {}; const samples = [];
719
+ for (const [id, l] of Object.entries(scene.links || {})) {
720
+ if (!ents[l.from] || (l.to && !ents[l.to])) continue;
721
+ let pts = l.pts.map((p) => iso(...resolvePoint(p, center)));
722
+ pts = clipStart(pts, shapes[l.from], 3);
723
+ if (l.to) pts = clipEnd(pts, shapes[l.to], l.heads === 'none' ? 3 : 4);
724
+ paths[id] = pts;
725
+ const framed = !focusing || (!l.dim && inFocus(ents[l.from]) && (!l.to || inFocus(ents[l.to])));
726
+ for (const [x, y] of samplePath(pts)) { samples.push([x, y, id]); if (framed) grow([x - 3, y - 3, x + 3, y + 3]); }
727
+ }
728
+ const picks = {};
729
+ for (const [id, l] of Object.entries(scene.links || {})) {
730
+ if (!l.label || !paths[id]) continue;
731
+ const { w, h } = labelBox(l.label);
732
+ let best = null;
733
+ for (const s of labelSpots(paths[id], l.labelAt ?? 0.5, w, h)) {
734
+ let cost = s.drift * 90 + (s.side < 0 ? 2 : 0) + (s.onLine ? 12 : 0);
735
+ const pad = [s.rect[0] - 3, s.rect[1] - 3, s.rect[2] + 3, s.rect[3] + 3];
736
+ for (const o of obstacles) { const a = overlap(pad, o); if (a) cost += 240 + a / 2; } // a label on an object hides the object: as bad as two labels on each other
737
+ for (const o of texts) { const a = overlap(pad, o); if (a) cost += 260 + a / 2; }
738
+ for (const o of labelRects) { const a = overlap([s.rect[0] - 4, s.rect[1] - 4, s.rect[2] + 4, s.rect[3] + 4], o); if (a) cost += 300 + a / 2; }
739
+ for (const [x, y, lid] of samples) if (lid !== id && x > s.rect[0] - 3 && x < s.rect[2] + 3 && y > s.rect[1] - 3 && y < s.rect[3] + 3) cost += 14;
740
+ if (!best || cost < best.cost) best = { ...s, cost };
741
+ }
742
+ picks[id] = { t: best.t, side: best.side, gap: best.gap };
743
+ labelRects.push(best.rect); if (!focusing || !l.dim) grow([best.rect[0] - 2, best.rect[1] - 2, best.rect[2] + 2, best.rect[3] + 4]);
744
+ }
745
+ if (b[0] === Infinity) b = [-100, -60, 100, 60];
746
+ return { b, boxes: [...obstacles, ...texts, ...labelRects], polys, panel, picks };
747
+ }
748
+ panelRect(corner, size) {
749
+ const W = this.host.clientWidth, H = this.host.clientHeight, w = size.w * this.hudScale, h = (size.h + 4) * this.hudScale;
750
+ const x = corner[1] === 'l' ? 10 : W - 10 - w, y = corner[0] === 't' ? HEAD_GAP : H - 10 - h;
751
+ return [x, y, x + w, y + h];
752
+ }
753
+ planFor(scene, prev) {
754
+ const lay = this.layoutOf(scene), W = Math.max(1, this.host.clientWidth), H = Math.max(1, this.host.clientHeight);
755
+ const [x0, y0, x1, y1] = lay.b, bw = Math.max(1, x1 - x0), bh = Math.max(1, y1 - y0);
756
+ const camFor = (z, ax, ay) => {
757
+ const sx = ax === 0 ? (W - bw * z) / 2 : ax < 0 ? PAD : W - PAD - bw * z;
758
+ const sy = ay === 0 ? (H - bh * z) / 2 : ay < 0 ? PAD : H - PAD - bh * z;
759
+ return { x: x0 - sx / z, y: y0 - sy / z, w: W / z, h: H / z };
760
+ };
761
+ const snap = (z) => Math.max(MIN_ZOOM, Math.floor(z * 20 + 1e-6) / 20);
762
+ const fit = Math.min(MAX_ZOOM, (W - 2 * PAD) / bw, (H - 2 * PAD) / bh);
763
+ const clear = (cam, corner) => {
764
+ const k = W / cam.w, r = this.panelRect(corner, lay.panel);
765
+ const wr = [cam.x + (r[0] - 12) / k, cam.y + (r[1] - 12) / k, cam.x + (r[2] + 12) / k, cam.y + (r[3] + 12) / k];
766
+ return !lay.boxes.some((bx) => hits(bx, wr));
767
+ };
768
+ let pick = null;
769
+ if (!lay.panel) pick = { zoom: snap(fit), ax: 0, ay: 0, corner: null };
770
+ else {
771
+ const corners = lay.panel.corner ? [lay.panel.corner] : ['tr', 'br', 'tl', 'bl'];
772
+ corners.forEach((corner, ci) => {
773
+ const ax = corner[1] === 'l' ? 1 : -1, ay = corner[0] === 't' ? 1 : -1;
774
+ const aligns = [[0, 0], [ax, 0], [0, ay], [ax, ay]];
775
+ let found = null;
776
+ for (let z = snap(fit); z >= MIN_ZOOM - 1e-6 && !found; z = Math.round((z - 0.05) * 100) / 100)
777
+ for (const [ai, [a, c]] of aligns.entries())
778
+ if (clear(camFor(z, a, c), corner)) { found = { zoom: z, ax: a, ay: c, corner, score: z - ai * 0.004 - ci * 0.001 + (prev && prev.corner === corner ? 0.045 : 0) }; break; }
779
+ if (found && (!pick || found.score > pick.score)) pick = found;
780
+ });
781
+ pick ||= { zoom: snap(fit * 0.7), ax: -1, ay: 1, corner: lay.panel.corner || 'tr' };
782
+ }
783
+ let cam = camFor(pick.zoom, pick.ax, pick.ay), corner = pick.corner;
784
+ // Camera stability: if the new content still fits the previous framing, keep it (no jitter between steps).
785
+ if (prev) {
786
+ const sameZ = Math.abs(prev.zoom - pick.zoom) < 1e-6, near = prev.zoom < pick.zoom && prev.zoom >= pick.zoom * 0.9;
787
+ if (sameZ || near) {
788
+ const c = prev.cam, m = 12 / prev.zoom;
789
+ const inside = x0 >= c.x + m && y0 >= c.y + m && x1 <= c.x + c.w - m && y1 <= c.y + c.h - m;
790
+ const dx = Math.abs((x0 + x1) / 2 - (c.x + c.w / 2)) / c.w, dy = Math.abs((y0 + y1) / 2 - (c.y + c.h / 2)) / c.h, lim = sameZ ? 0.12 : 0.18;
791
+ if (inside && dx < lim && dy < lim) {
792
+ const keep = lay.panel ? [prev.corner, 'tr', 'br', 'tl', 'bl'].filter(Boolean).find((k) => clear(c, k)) : null;
793
+ if (!lay.panel || keep) { cam = c; corner = lay.panel ? keep : null; pick = { ...pick, zoom: prev.zoom }; }
794
+ }
795
+ }
796
+ }
797
+ const dock = lay.panel ? this.panelRect(corner, lay.panel) : null;
798
+ return { cam, zoom: pick.zoom, corner, dock: dock && { x: dock[0], y: dock[1], corner }, picks: lay.picks, bounds: lay.b };
799
+ }
800
+ measure() {
801
+ const W = this.host.clientWidth; if (!W) return false;
802
+ this.hudScale = Math.min(1.12, Math.max(0.86, W / 780));
803
+ const show = W >= 520;
804
+ if (show !== this.showCards) { this.showCards = show; this.onCards?.(show); return true; }
805
+ return false;
806
+ }
807
+ frame(scenes) { // precompute camera plans for a whole lesson so framing is stable across steps
808
+ this.measure(); this.scenes = scenes; this.plans = new Map();
809
+ let prev = null;
810
+ for (const s of scenes) { prev = this.planFor(s, prev); this.plans.set(s, prev); }
811
+ this.scene = scenes[0]; this.setCam(this.plans.get(scenes[0]).cam);
812
+ }
813
+ plan(scene) { if (!this.plans.has(scene)) this.plans.set(scene, this.planFor(scene, null)); return this.plans.get(scene); }
814
+ displayCam(c = this.cam) {
815
+ let t = c;
816
+ if (this.view) { const w = c.w / this.view.k, h = c.h / this.view.k; t = { x: this.view.cx - w / 2, y: this.view.cy - h / 2, w, h }; }
817
+ const b = this.blend; if (!b) return t;
818
+ const k = EASE.inOut(clamp01((performance.now() - b.start) / b.dur));
819
+ if (k >= 1) { this.blend = null; return t; }
820
+ return { x: lerp(b.from.x, t.x, k), y: lerp(b.from.y, t.y, k), w: lerp(b.from.w, t.w, k), h: lerp(b.from.h, t.h, k) };
821
+ }
822
+ setCam(c) {
823
+ this.cam = c;
824
+ const d = this.displayCam(c);
825
+ const pixelWidth = Math.max(1, this.host.clientWidth);
826
+ this.svg.classList.toggle('is-magnified', pixelWidth > d.w);
827
+ this.svg.setAttribute('viewBox', `${r2(d.x)} ${r2(d.y)} ${r2(d.w)} ${r2(d.h)}`);
828
+ this.L.hud.setAttribute('transform', `translate(${r2(d.x)} ${r2(d.y)}) scale(${(d.w / pixelWidth).toFixed(5)})`);
829
+ const cx = d.x + d.w / 2, cy = d.y + d.h / 2;
830
+ this.fadeGrad.setAttribute('cx', r2(cx)); this.fadeGrad.setAttribute('cy', r2(cy)); this.fadeGrad.setAttribute('r', r2(d.w * 0.56));
831
+ this.fadeGrad.setAttribute('gradientTransform', `translate(${r2(cx)} ${r2(cy)}) scale(1 0.6) translate(${r2(-cx)} ${r2(-cy)})`);
832
+ }
833
+ refit() {
834
+ if (!this.scene) return;
835
+ this.clearView();
836
+ const changed = this.measure(), list = this.scenes.length ? this.scenes : [this.scene];
837
+ this.plans = new Map(); let prev = null;
838
+ for (const s of list) { prev = this.planFor(s, prev); this.plans.set(s, prev); }
839
+ const p = this.plan(this.scene);
840
+ if (changed) { this.goTo(this.scene, { instant: true }); return; }
841
+ if (this.anim) this.anim.cam.to = p.cam; else this.setCam(p.cam);
842
+ for (const e of this.ents.values()) {
843
+ if (e.cur.type !== 'panel' || !p.dock) continue;
844
+ const d = { sx: p.dock.x, sy: p.dock.y, corner: p.dock.corner };
845
+ e.cur = { ...e.cur, ...d }; if (e.tween && !e.tween.remove) e.tween.to = { ...e.tween.to, ...d };
846
+ this.renderEntity(e);
847
+ }
848
+ this.updateLinks(true);
849
+ }
850
+
851
+ /* ── zoom & gestures ── */
852
+ clampView(v) {
853
+ if (!v) return null;
854
+ const c = this.cam, px = this.host.clientWidth / c.w, maxK = Math.max(1.5, Math.min(6, 3.2 / px)), k = Math.max(1, Math.min(maxK, v.k));
855
+ if (k <= 1.001) return null;
856
+ const w = c.w / k, h = c.h / k;
857
+ return { k, cx: Math.max(c.x + w / 2, Math.min(c.x + c.w - w / 2, v.cx)), cy: Math.max(c.y + h / 2, Math.min(c.y + c.h - h / 2, v.cy)) };
858
+ }
859
+ setView(v, animate = false) {
860
+ const had = !!this.view, from = animate ? { ...this.displayCam() } : null;
861
+ this.view = this.clampView(v);
862
+ this.blend = animate ? { from, start: performance.now(), dur: 360 } : null;
863
+ this.setCam(this.cam);
864
+ if (had !== !!this.view) { this.host.classList.toggle('is-zoomed', !!this.view); this.onView?.(!!this.view); }
865
+ }
866
+ clearView() { if (!this.view && !this.blend) return; const had = !!this.view; this.view = null; this.blend = null; if (had) { this.host.classList.remove('is-zoomed'); this.onView?.(false); } }
867
+ zoomAt(fx, fy, f) {
868
+ const d = this.displayCam(), px = d.x + fx * d.w, py = d.y + fy * d.h, k = (this.view ? this.view.k : 1) * f, w = this.cam.w / k, h = this.cam.h / k;
869
+ this.setView({ k, cx: px - fx * w + w / 2, cy: py - fy * h + h / 2 });
870
+ }
871
+ panBy(fx, fy) { if (!this.view) return; const d = this.displayCam(); this.setView({ ...this.view, cx: this.view.cx - fx * d.w, cy: this.view.cy - fy * d.h }); }
872
+ toggleZoomAt(fx, fy) {
873
+ if (this.view) { this.setView(null, true); return; }
874
+ const c = this.cam, w = c.w / 2, h = c.h / 2, px = c.x + fx * c.w, py = c.y + fy * c.h;
875
+ this.setView({ k: 2, cx: px - fx * w + w / 2, cy: py - fy * h + h / 2 }, true);
876
+ }
877
+ fit() { if (this.view) this.setView(null, true); }
878
+ gestures() {
879
+ const host = this.host, rect = () => host.getBoundingClientRect();
880
+ const frac = (x, y) => { const r = rect(); return [(x - r.left) / r.width, (y - r.top) / r.height]; };
881
+ const two = (t) => ({ d: Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY), x: (t[0].clientX + t[1].clientX) / 2, y: (t[0].clientY + t[1].clientY) / 2 });
882
+ let g = null, tap = { at: 0, x: 0, y: 0 };
883
+ host.addEventListener('touchstart', (ev) => {
884
+ if (ev.touches.length >= 2) { ev.preventDefault(); g = { mode: 'two', ...two(ev.touches), pinched: true }; }
885
+ else if (ev.touches.length === 1) { const t = ev.touches[0]; g = { mode: 'one', x: t.clientX, y: t.clientY, x0: t.clientX, y0: t.clientY, t0: performance.now(), moved: false, pinched: false }; }
886
+ }, { passive: false });
887
+ host.addEventListener('touchmove', (ev) => {
888
+ if (!g) return;
889
+ if (ev.touches.length >= 2) {
890
+ ev.preventDefault(); const p = two(ev.touches);
891
+ if (g.mode !== 'two') g = { mode: 'two', ...p, pinched: true };
892
+ const [fx, fy] = frac(p.x, p.y); if (g.d > 0) this.zoomAt(fx, fy, p.d / g.d);
893
+ const r = rect(); this.panBy((p.x - g.x) / r.width, (p.y - g.y) / r.height); Object.assign(g, { d: p.d, x: p.x, y: p.y }); return;
894
+ }
895
+ if (g.mode !== 'one') return;
896
+ const t = ev.touches[0];
897
+ if (Math.hypot(t.clientX - g.x0, t.clientY - g.y0) > 8) g.moved = true;
898
+ if (this.view) { ev.preventDefault(); const r = rect(); this.panBy((t.clientX - g.x) / r.width, (t.clientY - g.y) / r.height); }
899
+ g.x = t.clientX; g.y = t.clientY;
900
+ }, { passive: false });
901
+ host.addEventListener('touchend', (ev) => {
902
+ if (!g) return;
903
+ if (ev.touches.length === 1 && g.mode === 'two') { const t = ev.touches[0]; g = { mode: 'one', x: t.clientX, y: t.clientY, x0: t.clientX, y0: t.clientY, t0: 0, moved: true, pinched: true }; return; }
904
+ if (ev.touches.length) return;
905
+ const now = performance.now();
906
+ if (g.mode === 'one' && !g.pinched) {
907
+ const t = ev.changedTouches[0], dx = t.clientX - g.x0, dy = t.clientY - g.y0;
908
+ if (!this.view && now - g.t0 < 700 && Math.abs(dx) > 50 && Math.abs(dy) < Math.abs(dx) * 0.6) this.onSwipe?.(dx < 0 ? 1 : -1);
909
+ else if (!g.moved && now - g.t0 < 300) {
910
+ if (now - tap.at < 320 && Math.hypot(t.clientX - tap.x, t.clientY - tap.y) < 40) { ev.preventDefault(); const [fx, fy] = frac(t.clientX, t.clientY); this.toggleZoomAt(fx, fy); tap = { at: 0, x: 0, y: 0 }; }
911
+ else tap = { at: now, x: t.clientX, y: t.clientY };
912
+ }
913
+ }
914
+ g = null;
915
+ });
916
+ host.addEventListener('touchcancel', () => (g = null));
917
+ let drag = null;
918
+ host.addEventListener('pointerdown', (ev) => { if (ev.pointerType === 'mouse' && ev.button === 0 && this.view) { drag = { x: ev.clientX, y: ev.clientY }; host.setPointerCapture(ev.pointerId); host.classList.add('is-dragging'); } });
919
+ host.addEventListener('pointermove', (ev) => { if (!drag) return; const r = rect(); this.panBy((ev.clientX - drag.x) / r.width, (ev.clientY - drag.y) / r.height); drag = { x: ev.clientX, y: ev.clientY }; });
920
+ const up = () => { drag = null; host.classList.remove('is-dragging'); };
921
+ host.addEventListener('pointerup', up); host.addEventListener('pointercancel', up);
922
+ host.addEventListener('dblclick', (ev) => { const [fx, fy] = frac(ev.clientX, ev.clientY); this.toggleZoomAt(fx, fy); });
923
+ host.addEventListener('wheel', (ev) => {
924
+ const unit = ev.deltaMode === 1 ? 16 : 1;
925
+ if (ev.ctrlKey || ev.metaKey) { ev.preventDefault(); const [fx, fy] = frac(ev.clientX, ev.clientY); this.zoomAt(fx, fy, Math.exp(-ev.deltaY * unit * 0.01)); }
926
+ else if (this.view) { ev.preventDefault(); const r = rect(); this.panBy((-ev.deltaX * unit) / r.width, (-ev.deltaY * unit) / r.height); }
927
+ }, { passive: false });
928
+ }
929
+
930
+ /* ── scene transitions ── */
931
+ clear() {
932
+ this.finish(true);
933
+ for (const e of this.ents.values()) { e.el.remove(); e.overEl.remove(); }
934
+ for (const l of this.links.values()) { l.el.remove(); l.label.remove(); }
935
+ this.ents.clear(); this.links.clear(); this.clearPackets(true); this.flows = []; this.L.floor.innerHTML = '';
936
+ }
937
+ goTo(scene, { instant = false } = {}) {
938
+ this.finish(true); this.clearPackets(); this.flows = [];
939
+ const now = performance.now(), plan = this.plan(scene), T = TIMING;
940
+ const next = {};
941
+ for (const [id, e] of Object.entries(scene.entities || {})) {
942
+ if (e.type === 'panel') { if (!this.showCards || !plan.dock) continue; next.__panel = { ...withDefaults(e), sx: plan.dock.x, sy: plan.dock.y, corner: plan.dock.corner }; }
943
+ else next[id] = withDefaults(e);
944
+ }
945
+ const leaving = [...this.ents.keys()].filter((id) => !next[id]);
946
+ const moving = Object.keys(next).filter((id) => this.ents.has(id) && !same(this.ents.get(id).cur, next[id]));
947
+ const entering = Object.keys(next).filter((id) => !this.ents.has(id)).sort((a, b) => depthKey(next[a]) - depthKey(next[b]));
948
+ const moveDelay = leaving.length ? T.exit * 0.55 : 0;
949
+ const enterAt = moving.length ? moveDelay + T.move * 0.75 : leaving.length ? T.exit * 0.7 : 0;
950
+ const ready = {}; let end = 0;
951
+ for (const id of leaving) {
952
+ const e = this.ents.get(id);
953
+ e.tween = { from: { ...e.cur }, to: { ...e.cur, opacity: 0, ...(EXIT_TO[e.cur.type] || { lift: -22 }) }, start: now, delay: 0, dur: T.exit, ease: EASE.inOut, remove: true };
954
+ end = Math.max(end, T.exit);
955
+ }
956
+ for (const id of Object.keys(next)) {
957
+ if (!this.ents.has(id)) continue;
958
+ const e = this.ents.get(id);
959
+ if (moving.includes(id)) {
960
+ e.tween = { from: { ...e.cur }, to: next[id], start: now, delay: moveDelay, dur: T.move, ease: EASE.inOut, ...this.swapInfo(e.cur, next[id]) };
961
+ ready[id] = moveDelay + T.move; end = Math.max(end, ready[id]);
962
+ } else ready[id] = 0;
963
+ }
964
+ entering.forEach((id, i) => {
965
+ const to = next[id], from = { ...to, opacity: 0, ...(ENTER_FROM[to.type] || { lift: 120 }) };
966
+ const e = this.addEntity(id, from), delay = enterAt + i * T.stagger;
967
+ e.tween = { from, to, start: now, delay, dur: T.enter, ease: EASE.out, liftEase: EASE.back, countEase: EASE.inOut };
968
+ ready[id] = delay + T.enter * 0.8; end = Math.max(end, delay + T.enter);
969
+ });
970
+ for (const [id, l] of this.links) if (!scene.links?.[id]) l.tween = { from: l.opacity, to: 0, key: 'opacity', start: now, delay: 0, dur: 300, remove: true };
971
+ let k = 0;
972
+ for (const [id, spec] of Object.entries(scene.links || {})) {
973
+ if (this.links.has(id)) { const l = this.links.get(id); l.spec = spec; this.linkClass(l); continue; }
974
+ const l = this.addLink(id, spec), delay = Math.max(ready[spec.from] ?? 0, ready[spec.to] ?? 0, moveDelay + (moving.length ? T.move * 0.6 : 0)) + 60 + k * 90;
975
+ k++; l.draw = 0; l.tween = { from: 0, to: 1, key: 'draw', start: now, delay, dur: T.draw };
976
+ end = Math.max(end, delay + T.draw);
977
+ }
978
+ this.scene = scene;
979
+ const camDelay = leaving.length ? T.exit * 0.4 : 0;
980
+ end = Math.max(end, camDelay + T.move);
981
+ const from = { ...this.displayCam() }; this.clearView();
982
+ this.anim = { cam: { from, to: plan.cam, delay: camDelay, dur: T.move }, start: now, end: now + end, flows: scene.flows || [], spot: [...entering, ...moving.filter((id) => !next[id].dead || this.ents.get(id).cur.dead !== next[id].dead)] };
983
+ if (instant || this.reduced) this.finish();
984
+ }
985
+ swapInfo(a, b) {
986
+ const o = {};
987
+ if (!same(a.tags, b.tags)) o.tagSwap = true;
988
+ if (!same(a.label, b.label) || (a.sub || '') !== (b.sub || '')) o.labelSwap = true;
989
+ if (a.type === 'panel') {
990
+ const key = (p) => [p.title, p.icon, p.lines, p.bars, p.w];
991
+ const s0 = renderPanel({ ...a, boxW: undefined, boxH: undefined }).size, s1 = renderPanel({ ...b, boxW: undefined, boxH: undefined }).size;
992
+ o.card = { swap: !same(key(a), key(b)), w0: s0.w, h0: s0.h, w1: s1.w, h1: s1.h };
993
+ }
994
+ return o;
995
+ }
996
+ finish(silent = false) {
997
+ if (!this.anim) return;
998
+ for (const [id, e] of [...this.ents]) if (e.tween) { if (e.tween.remove) this.removeEntity(id); else { e.cur = e.tween.to; e.tween = null; this.renderEntity(e); } }
999
+ for (const [id, l] of [...this.links]) if (l.tween) { if (l.tween.remove) { l.el.remove(); l.label.remove(); this.links.delete(id); } else { l[l.tween.key] = l.tween.to; l.tween = null; } }
1000
+ this.setCam(this.anim.cam.to); this.sortDepth(); this.updateLinks(true);
1001
+ const a = this.anim; this.anim = null;
1002
+ if (!silent) this.settle(a);
1003
+ }
1004
+ settle(a) {
1005
+ this.flows = a.flows.map((f) => ({ ...f, acc: 0.6, n: 0, rr: 0 }));
1006
+ for (const id of a.spot) this.spotlight(id);
1007
+ this.onSettle?.();
1008
+ }
1009
+ retheme() {
1010
+ this.defs.innerHTML = themed(defsSVG(this.gridPatternId));
1011
+ for (const e of this.ents.values()) this.renderEntity(e);
1012
+ for (const l of this.links.values()) l.labelKey = null;
1013
+ this.updateLinks(true);
1014
+ }
1015
+ addEntity(id, cur) {
1016
+ const g = el('g', { 'data-id': id, class: `ent ent--${cur.type}` }), o = el('g', { 'data-id': id });
1017
+ (FLOOR.has(cur.type) ? this.L.floor : this.L.ents).appendChild(g);
1018
+ (cur.type === 'panel' ? this.L.hud : this.L.over).appendChild(o);
1019
+ const e = { id, cur: { ...cur }, el: g, overEl: o, poly: null, tween: null };
1020
+ this.ents.set(id, e); this.renderEntity(e); return e;
1021
+ }
1022
+ removeEntity(id) { const e = this.ents.get(id); e.el.remove(); e.overEl.remove(); this.ents.delete(id); }
1023
+ renderEntity(e) {
1024
+ if (e.cur.type === 'panel') {
1025
+ const p = renderPanel(e.cur);
1026
+ e.overEl.innerHTML = `<g transform="translate(${r2(e.cur.sx || 0)} ${r2((e.cur.sy || 0) - (e.cur.lift || 0))}) scale(${r2(this.hudScale)})">${themed(p.over)}</g>`;
1027
+ e.poly = null; return;
1028
+ }
1029
+ const r = RENDER[e.cur.type](e.cur, e);
1030
+ let over = r.over;
1031
+ const insp = !!e.cur.inside && !!r.poly;
1032
+ if (insp) { // magnifier badge on the right-top corner of the outline
1033
+ const tip = r.poly.reduce((a, p) => (p[0] > a[0] + 0.5 || (Math.abs(p[0] - a[0]) <= 0.5 && p[1] < a[1]) ? p : a), r.poly[0]);
1034
+ over += `<g class="inspect-badge" opacity="${r2(e.cur.opacity ?? 1)}" transform="translate(${r2(tip[0] - 2)} ${r2(tip[1] - 6)})"><circle class="inspect-badge__ring" r="11" fill="none" stroke="#5fae57" stroke-width="1"/><circle r="10" fill="#dcefd2" stroke="#66835c" stroke-width=".9"/>${iconSVG('zoom-in', 0, 0, 12, { stroke: 1.45, color: INK })}</g>`;
1035
+ }
1036
+ e.el.innerHTML = themed(r.body); e.overEl.innerHTML = themed(over); e.poly = r.poly; e.bounds = r.bounds;
1037
+ e.liveEls = r.live ? Object.fromEntries([...e.el.querySelectorAll('[data-live]')].map((n) => [n.dataset.live, n])) : null;
1038
+ if (insp !== !!e.insp) {
1039
+ e.insp = insp;
1040
+ for (const n of [e.el, e.overEl]) { n.classList.toggle('is-inspectable', insp); if (insp) { n.setAttribute('tabindex', '0'); n.setAttribute('role', 'button'); } else { n.removeAttribute('tabindex'); n.removeAttribute('role'); } }
1041
+ }
1042
+ const dim = clamp01(e.cur.dim || 0);
1043
+ e.el.style.opacity = dim && e.cur.type !== 'block' ? r2(1 - dim * 0.55) : '';
1044
+ e.overEl.style.opacity = dim ? r2(1 - dim * 0.6) : '';
1045
+ }
1046
+ sortDepth() {
1047
+ const list = [...this.ents.values()].filter((e) => !FLOOR.has(e.cur.type) && e.cur.type !== 'panel').sort((a, b) => depthKey(a.cur) - depthKey(b.cur));
1048
+ const kids = [...this.L.ents.children];
1049
+ if (list.some((e, i) => kids[i] !== e.el)) for (const e of list) this.L.ents.appendChild(e.el);
1050
+ }
1051
+ spotlight(id) {
1052
+ const e = this.ents.get(id);
1053
+ if (!e || ['panel', 'queue', 'zone'].includes(e.cur.type)) return;
1054
+ const [x0, x1, y0, y1] = footprint(e.cur), m = 0.6;
1055
+ const p = el('path', { class: 'spot', d: roundPoly([iso(x0 - m, y0 - m), iso(x0 - m, y1 + m), iso(x1 + m, y1 + m), iso(x1 + m, y0 - m)], 7) });
1056
+ this.L.floor.appendChild(p); setTimeout(() => p.remove(), 1600);
1057
+ }
1058
+
1059
+ /* ── links ── */
1060
+ linkClass(l) {
1061
+ l.el.setAttribute('class', `link link--${l.spec.style || 'solid'}${l.spec.dim ? ' is-dim' : ''}`);
1062
+ l.label.setAttribute('class', `link-label${l.spec.dim ? ' is-dim' : ''}`);
1063
+ }
1064
+ addLink(id, spec) {
1065
+ const p = el('path', { class: `link link--${spec.style || 'solid'}${spec.dim ? ' is-dim' : ''}` }), g = el('g', { class: `link-label${spec.dim ? ' is-dim' : ''}` });
1066
+ this.L.links.appendChild(p); this.L.over.appendChild(g);
1067
+ const l = { id, spec, el: p, label: g, draw: 1, opacity: 1, tween: null, len: 0 };
1068
+ this.links.set(id, l); return l;
1069
+ }
1070
+ updateLinks(force = false) {
1071
+ const center = (id) => this.ents.has(id) && centerOf(this.ents.get(id).cur);
1072
+ const picks = this.plans.get(this.scene)?.picks || {};
1073
+ for (const l of this.links.values()) {
1074
+ const s = l.spec;
1075
+ if (!this.ents.has(s.from) || (s.to && !this.ents.has(s.to))) continue;
1076
+ let pts = s.pts.map((p) => iso(...resolvePoint(p, center)));
1077
+ pts = clipStart(pts, this.ents.get(s.from).poly, 3);
1078
+ if (s.to) pts = clipEnd(pts, this.ents.get(s.to).poly, s.heads === 'none' ? 3 : 4);
1079
+ l.pts = pts; l.el.setAttribute('d', roundLine(pts, 9)); l.len = l.el.getTotalLength();
1080
+ const style = s.style || 'solid', marker = style === 'off' ? 'url(#arrow-muted)' : style === 'cut' ? 'url(#arrow-red)' : 'url(#arrow)';
1081
+ const heads = l.draw > 0.97 && style !== 'beat';
1082
+ l.el.setAttribute('marker-end', heads && s.heads !== 'none' ? marker : '');
1083
+ l.el.setAttribute('marker-start', heads && s.heads === 'both' ? marker : '');
1084
+ if (l.draw < 1 && style === 'solid') { l.el.style.strokeDasharray = `${r2(l.len)} ${r2(l.len)}`; l.el.style.strokeDashoffset = r2(l.len * (1 - l.draw)); l.el.style.opacity = 1; }
1085
+ else { l.el.style.strokeDasharray = ''; l.el.style.strokeDashoffset = ''; l.el.style.opacity = r2(l.opacity * (style === 'solid' ? 1 : clamp01(l.draw * 1.4))); }
1086
+ if (s.label) {
1087
+ const key = `${s.label}|${s.labelTone || ''}|${isDark()}`;
1088
+ if (l.labelKey !== key) { if (l.labelKey) l.labelBorn = performance.now(); l.label.innerHTML = themed(pill(0, 0, s.label, { tone: s.labelTone || 'paper', size: LABEL_SIZE, icon: s.labelIcon || null })); l.labelKey = key; }
1089
+ const born = l.labelBorn ? clamp01((performance.now() - l.labelBorn) / 320) : 1;
1090
+ l.label.style.opacity = r2(clamp01((l.draw - 0.6) / 0.4) * l.opacity * born);
1091
+ const { w, h } = labelBox(s.label), pick = picks[l.id] || { t: s.labelAt ?? 0.5, side: 1 };
1092
+ const [cx, cy] = spotAt(pts, pick, w + (s.labelIcon ? 15 : 0), h);
1093
+ l.lpos = l.lpos && this.anim && !force ? [lerp(l.lpos[0], cx, 0.16), lerp(l.lpos[1], cy, 0.16)] : [cx, cy];
1094
+ l.label.setAttribute('transform', `translate(${r2(l.lpos[0])} ${r2(l.lpos[1])})`);
1095
+ } else if (l.labelKey) { l.label.innerHTML = ''; l.labelKey = null; }
1096
+ }
1097
+ }
1098
+
1099
+ /* ── packets ── */
1100
+ clearPackets(now = false) {
1101
+ for (const p of this.packets) { if (now) p.el.remove(); else { p.el.classList.add('pkt--leave'); setTimeout(() => p.el.remove(), 260); } }
1102
+ this.packets = [];
1103
+ }
1104
+ pickRoute(f) {
1105
+ const kind = f.pattern ? f.pattern[f.n % f.pattern.length] : f.kind || 'req';
1106
+ if (f.routes) {
1107
+ let i;
1108
+ if (f.pick === 'weights') { const w = f.routes.map((r) => r.weight ?? 1); let x = Math.random() * w.reduce((a, b) => a + b, 0); i = w.findIndex((v) => (x -= v) <= 0); if (i < 0) i = w.length - 1; }
1109
+ else { i = f.rr % f.routes.length; f.rr++; }
1110
+ f.n++; return { route: f.routes[i].path, kind: f.routes[i].kind || kind };
1111
+ }
1112
+ const route = f.route.map((seg) => {
1113
+ if (typeof seg === 'string') return seg;
1114
+ if (f.pick === 'weights') { let x = Math.random() * f.weights.reduce((a, b) => a + b, 0); for (let i = 0; i < seg.length; i++) if ((x -= f.weights[i]) <= 0) return seg[i]; return seg[seg.length - 1]; }
1115
+ const s = seg[f.rr % seg.length]; f.rr++; return s;
1116
+ });
1117
+ f.n++; return { route, kind };
1118
+ }
1119
+ spawn(f) {
1120
+ if (f.fanout) { f.n++; for (const r of f.routes) this.launch(r.path, r.kind || f.kind || 'req', f); return; }
1121
+ const { route, kind } = this.pickRoute(f); this.launch(route, kind, f);
1122
+ }
1123
+ launch(route, kind, f) {
1124
+ if (!route.every((id) => this.links.has(id))) return;
1125
+ const g = el('g', { class: `pkt pkt--${kind}` });
1126
+ g.innerHTML = kind === 'ping' || kind === 'kill' ? '<circle r="4.4"/>' : kind === 'heavy' ? '<rect x="-7" y="-7" width="14" height="14" rx="3.5"/>'
1127
+ : kind === 'write' ? '<rect x="-4.9" y="-4.9" width="9.8" height="9.8" rx="2"/>' : kind === 'msg' || kind === 'poison' ? '<rect x="-5.8" y="-5.8" width="11.6" height="11.6" rx="2.6"/>' : '<circle r="5.3"/>';
1128
+ this.L.packets.appendChild(g);
1129
+ this.packets.push({ route, seg: 0, d: 0, kind, el: g, back: false, bounce: !!f.bounce, dwell: 0, speed: f.speed || 1, hold: f.hold || 0 });
1130
+ }
1131
+ burst(x, y, kind) {
1132
+ const g = el('g', { class: `fx fx--${kind}`, transform: `translate(${r2(x)} ${r2(y)})` });
1133
+ g.innerHTML = kind === 'fail' ? '<circle r="5" class="fx-ring"/><path d="M-3.6,-3.6 L3.6,3.6 M3.6,-3.6 L-3.6,3.6" class="fx-x"/>' : '<circle r="4.3" class="fx-ring"/>';
1134
+ this.L.packets.appendChild(g); setTimeout(() => g.remove(), 700);
1135
+ }
1136
+ stepPackets(dt) {
1137
+ for (const f of this.flows) for (f.acc += dt * (f.rate ?? 1) * (this.reduced ? 0.5 : 1); f.acc >= 1; ) { f.acc--; this.spawn(f); }
1138
+ const keep = [];
1139
+ for (const p of this.packets) {
1140
+ if (p.dwell > 0) { p.dwell -= dt; if (p.dwell > 0) { keep.push(p); continue; } p.el.style.opacity = 1; if (p.back) { p.el.classList.remove('pkt--held'); p.el.classList.add('pkt--back'); } }
1141
+ const l = this.links.get(p.route[p.seg]);
1142
+ if (!l) { p.el.remove(); continue; }
1143
+ p.d += PKT_SPEED * p.speed * (KIND_SPEED[p.kind] || 1) * dt;
1144
+ const len = l.len || l.el.getTotalLength(), style = l.spec.style || 'solid', heads = style === 'beat' ? 'none' : l.spec.heads;
1145
+ let a = heads === 'both' ? 16 : 0, b = len - (heads === 'none' ? 0 : 16);
1146
+ if (b - a < 10) { a = 0; b = len; }
1147
+ const span = b - a;
1148
+ if (p.d >= span) {
1149
+ const end = l.el.getPointAtLength(p.back ? a : b);
1150
+ if (!p.back && Math.random() < (l.spec.fail || 0)) { this.burst(end.x, end.y, 'fail'); this.ping(l.spec.to, p.kind, true); p.el.remove(); continue; }
1151
+ if (!p.back) this.ping(l.spec.to, p.kind, false);
1152
+ if (!p.back && p.seg < p.route.length - 1) { p.seg++; p.d = 0; p.dwell = 0.16; p.el.style.opacity = 0; keep.push(p); continue; }
1153
+ if (p.bounce && !p.back) { p.back = true; p.d = 0; if (p.hold) { p.dwell = p.hold; p.el.classList.add('pkt--held'); } else p.el.classList.add('pkt--back'); keep.push(p); continue; }
1154
+ if (p.back && p.seg > 0) { p.seg--; p.d = 0; p.dwell = 0.16; p.el.style.opacity = 0; keep.push(p); continue; }
1155
+ this.burst(end.x, end.y, 'ok'); p.el.remove(); continue;
1156
+ }
1157
+ const pt = l.el.getPointAtLength(p.back ? b - p.d : a + p.d);
1158
+ p.el.setAttribute('transform', `translate(${r2(pt.x)} ${r2(pt.y)})`);
1159
+ keep.push(p);
1160
+ }
1161
+ this.packets = keep;
1162
+ }
1163
+
1164
+ /* ── looks: live parts ── */
1165
+ ping(id, kind, failed) {
1166
+ const e = id && this.ents.get(id);
1167
+ if (e?.look && LOOKS[e.look.name].ping) LOOKS[e.look.name].ping(e.look.s, kind, failed);
1168
+ }
1169
+ stepLooks(dt) {
1170
+ if (this.reduced) return;
1171
+ for (const e of this.ents.values()) {
1172
+ if (!e.liveEls || !e.look) continue;
1173
+ const L = LOOKS[e.look.name], dirty = L.tick(e.look.s, dt, e.cur);
1174
+ if (!dirty) continue;
1175
+ const built = lookCache.get(lookKey(e.look.name, e.cur));
1176
+ if (!built) continue;
1177
+ for (const l of built.layers) if (typeof l !== 'string' && dirty[l.live] && e.liveEls[l.live]) e.liveEls[l.live].innerHTML = themed(l.draw(e.look.s, e.cur));
1178
+ }
1179
+ }
1180
+
1181
+ /* ── frame loop ── */
1182
+ tick(t) {
1183
+ const dt = Math.min(0.05, (t - this.last) / 1000); this.last = t;
1184
+ if (this.anim) {
1185
+ const c = this.anim.cam, k = EASE.inOut(clamp01((t - this.anim.start - c.delay) / c.dur));
1186
+ this.setCam({ x: lerp(c.from.x, c.to.x, k), y: lerp(c.from.y, c.to.y, k), w: lerp(c.from.w, c.to.w, k), h: lerp(c.from.h, c.to.h, k) });
1187
+ let moved = false;
1188
+ for (const [id, e] of [...this.ents]) {
1189
+ const tw = e.tween; if (!tw) continue;
1190
+ const raw = (t - tw.start - tw.delay) / tw.dur;
1191
+ if (raw < 0 && !tw.started) continue;
1192
+ tw.started = true;
1193
+ const p = clamp01(raw), s = tw.ease(p), cur = tw.remove || p >= 0.5 ? { ...tw.to } : { ...tw.from };
1194
+ if (!tw.remove && p < 0.5) cur.cpu = tw.from.cpu;
1195
+ for (const key in tw.to) {
1196
+ const a = tw.from[key], b = tw.to[key];
1197
+ if (typeof a !== 'number' || typeof b !== 'number' || (key === 'cpu' && (a < 0 || b < 0))) continue;
1198
+ cur[key] = lerp(a, b, key === 'lift' && tw.liftEase ? tw.liftEase(p) : (key === 'count' || key === 'n') && tw.countEase ? tw.countEase(p) : s);
1199
+ }
1200
+ const out = 1 - clamp01(p / 0.42), inn = clamp01((p - 0.55) / 0.4);
1201
+ if (tw.tagSwap) cur.tagFade = p < 0.5 ? out : inn;
1202
+ if (tw.labelSwap) cur.labelFade = p < 0.5 ? out : inn;
1203
+ if (tw.card && tw.card.swap) {
1204
+ const q = EASE.inOut(clamp01((p - 0.24) / 0.48));
1205
+ cur.boxW = lerp(tw.card.w0, tw.card.w1, q); cur.boxH = lerp(tw.card.h0, tw.card.h1, q);
1206
+ cur.fade = p < 0.5 ? 1 - clamp01(p / 0.24) : clamp01((p - 0.72) / 0.28);
1207
+ }
1208
+ e.cur = cur; this.renderEntity(e); moved = true;
1209
+ if (p >= 1) { if (tw.remove) this.removeEntity(id); else { e.cur = tw.to; e.tween = null; this.renderEntity(e); } }
1210
+ }
1211
+ for (const [id, l] of [...this.links]) {
1212
+ const tw = l.tween; if (!tw) continue;
1213
+ const p = clamp01((t - tw.start - tw.delay) / tw.dur);
1214
+ l[tw.key] = lerp(tw.from, tw.to, EASE.inOut(p));
1215
+ if (p >= 1) { if (tw.remove) { l.el.remove(); l.label.remove(); this.links.delete(id); } else l.tween = null; }
1216
+ }
1217
+ if (moved) this.sortDepth();
1218
+ this.updateLinks();
1219
+ if (t >= this.anim.end) { const a = this.anim; this.anim = null; this.updateLinks(true); this.settle(a); }
1220
+ }
1221
+ if (this.blend && !this.anim) this.setCam(this.cam);
1222
+ if (!this.paused) { this.stepPackets(dt); this.stepLooks(dt); }
1223
+ }
1224
+ }