@entro314labs/iso-engine 0.0.0-stage → 0.5.1

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +165 -2
  3. package/THIRD_PARTY_NOTICES.md +39 -0
  4. package/dist/engine/anim.js +225 -0
  5. package/dist/engine/behaviors.js +105 -0
  6. package/dist/engine/diagram.js +80 -0
  7. package/dist/engine/draw.js +117 -0
  8. package/dist/engine/export.js +81 -0
  9. package/dist/engine/figure.js +35 -0
  10. package/dist/engine/global.js +4 -0
  11. package/dist/engine/index.d.ts +278 -0
  12. package/dist/engine/index.js +164 -0
  13. package/dist/engine/math.js +190 -0
  14. package/dist/engine/node.js +290 -0
  15. package/dist/engine/paths.js +76 -0
  16. package/dist/engine/prefabs/architecture.js +136 -0
  17. package/dist/engine/prefabs/basics.js +131 -0
  18. package/dist/engine/prefabs/devices.js +295 -0
  19. package/dist/engine/prefabs/icons.js +49 -0
  20. package/dist/engine/prefabs/index.js +12 -0
  21. package/dist/engine/prefabs/logistics.js +156 -0
  22. package/dist/engine/scene.js +466 -0
  23. package/dist/engine/shapes.js +781 -0
  24. package/dist/engine/sort.js +153 -0
  25. package/dist/engine/spec.js +81 -0
  26. package/dist/engine/style.js +87 -0
  27. package/dist/engine.css +1 -0
  28. package/dist/figure.css +93 -0
  29. package/dist/figure.d.ts +22 -0
  30. package/dist/figure.js +73 -0
  31. package/dist/filters.d.ts +9 -0
  32. package/dist/filters.js +22 -0
  33. package/dist/index.d.ts +9 -0
  34. package/dist/index.js +8 -0
  35. package/dist/iso.global.js +7990 -0
  36. package/dist/kernel.d.ts +102 -0
  37. package/dist/kernel.js +172 -0
  38. package/dist/loops.d.ts +49 -0
  39. package/dist/loops.js +64 -0
  40. package/dist/patterns.d.ts +44 -0
  41. package/dist/patterns.js +97 -0
  42. package/dist/theme.css +19 -0
  43. package/dist/types.d.ts +86 -0
  44. package/dist/types.js +1 -0
  45. package/package.json +50 -4
  46. package/skills/iso-engine/SKILL.md +143 -0
  47. package/skills/iso-engine/examples/engine.html +42 -0
  48. package/skills/iso-engine/examples/figure.html +51 -0
  49. package/skills/iso-engine/examples/loop.html +68 -0
  50. package/skills/iso-engine/examples/loop.js +36 -0
  51. package/skills/iso-engine/examples/matcher.js +134 -0
  52. package/skills/iso-engine/examples/spec.html +42 -0
  53. package/skills/iso-engine/references/animation.md +116 -0
  54. package/skills/iso-engine/references/api.md +207 -0
  55. package/skills/iso-engine/references/composition.md +66 -0
  56. package/skills/iso-engine/references/diagrams.md +68 -0
  57. package/skills/iso-engine/references/figures.md +359 -0
  58. package/skills/iso-engine/references/loops.md +126 -0
  59. package/skills/iso-engine/references/prefabs.md +103 -0
  60. package/skills/iso-engine/references/spec.md +66 -0
  61. package/skills/iso-engine/references/style.md +76 -0
  62. package/skills/iso-engine/references/troubleshooting.md +49 -0
  63. package/skills/iso-engine/scripts/build.mjs +35 -0
@@ -0,0 +1,466 @@
1
+ /* Scene: owns the view, the node tree, the SVG element, the clock and the animations. */
2
+ import { makeView, fmt, box3, cssClass, cssValue } from './math.js';
3
+ import { IDENTITY } from './draw.js';
4
+ import { Node, Group } from './node.js';
5
+ import { makeItem, compareItems, depthSort, hexOverlap, Placer } from './sort.js';
6
+ import { injectCSS } from './style.js';
7
+ import { Timeline } from './anim.js';
8
+
9
+ /* ── global clock ── */
10
+ export const clock = {
11
+ scenes: new Set(),
12
+ manual: typeof window !== 'undefined' && (!!window.__ISO_MANUAL__ || /[?&]iso-manual\b/.test(window.location ? window.location.search : '')),
13
+ raf: 0,
14
+ last: 0,
15
+ inFrame: false,
16
+ kicked: false,
17
+ add(s) { this.scenes.add(s); this.kick(); },
18
+ remove(s) { this.scenes.delete(s); },
19
+ kick() {
20
+ /* A node touched during a tick (travel, packets, loops) only marks the frame: frame() schedules the next one.
21
+ Scheduling here as well would leave two callbacks pending, and every frame would double them. */
22
+ if (this.inFrame) { this.kicked = true; return; }
23
+ if (this.manual || this.raf || typeof requestAnimationFrame === 'undefined') return;
24
+ this.last = 0;
25
+ this.raf = requestAnimationFrame((t) => this.frame(t));
26
+ },
27
+ frame(ts) {
28
+ this.raf = 0;
29
+ const dt = this.last ? Math.min(0.1, (ts - this.last) / 1000) : 1 / 60;
30
+ this.last = ts;
31
+ let again = false;
32
+ this.inFrame = true;
33
+ this.kicked = false;
34
+ try {
35
+ for (const s of this.scenes) { if (s._wantsFrame()) { s.tick(dt); again = again || s._wantsFrame(); } }
36
+ } finally {
37
+ this.inFrame = false;
38
+ }
39
+ if (again || this.kicked) { this.raf = requestAnimationFrame((t) => this.frame(t)); this.last = ts; }
40
+ else this.last = 0;
41
+ },
42
+ /* manual stepping (export, tests) */
43
+ advance(dt) { for (const s of this.scenes) s.tick(dt); },
44
+ };
45
+
46
+ const reducedQuery = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
47
+
48
+ export class Scene {
49
+ constructor(host, opts = {}) {
50
+ if (host && !(typeof host === 'string' || (typeof Element !== 'undefined' && host instanceof Element))) { opts = host; host = opts.host; }
51
+ this.opts = { theme: 'dark', angle: 30, padding: 24, autoplay: true, reducedMotion: 'static', ...opts };
52
+ this.view = makeView(this.opts.angle);
53
+ this.root = new Group({ sort: this.opts.sort || 'auto' });
54
+ this.root._scene = this;
55
+ this.byUid = new Map();
56
+ this.time = 0;
57
+ this.timeScale = 1;
58
+ this.playing = this.opts.autoplay !== false;
59
+ this.timelines = [];
60
+ this.behaviors = [];
61
+ this.pending = new Set();
62
+ this.touchedA = new Set();
63
+ this.visible = true;
64
+ this.built = false;
65
+ this.listeners = {};
66
+ this.host = typeof host === 'string' ? document.querySelector(host) : host || null;
67
+ this.reduced = this.opts.reducedMotion !== 'ignore' && reducedQuery();
68
+ this._byUid(this.root);
69
+ if (typeof document !== 'undefined') injectCSS(document);
70
+ clock.add(this);
71
+ if (this.host && this.opts.autoRender !== false && typeof queueMicrotask !== 'undefined') queueMicrotask(() => { if (!this.built && !this.destroyed) this.render(); });
72
+ }
73
+
74
+ /* ── tree ── */
75
+ _byUid(n) { this.byUid.set(n.uid, n); }
76
+ _register(n) {
77
+ const mount = (x) => { this._byUid(x); if (x.onMount && !x._mounted) { x._mounted = true; x.onMount(this); } };
78
+ mount(n); if (n.isGroup) n.each(mount);
79
+ }
80
+ _unregister(n) { this.byUid.delete(n.uid); if (n.isGroup) n.each((c) => this.byUid.delete(c.uid)); if (n.el && n.el.parentNode) n.el.parentNode.removeChild(n.el); }
81
+ _structure() { if (this.built) { this.needsRender = true; this._wake(); } }
82
+ add(node, opts) {
83
+ if (typeof node === 'string') return this.root[node](opts);
84
+ return this.root.add(node);
85
+ }
86
+ group(opts, fn) { return this.root.group(opts, fn); }
87
+ get(id) { if (id instanceof Node) return id; return this.root.find((n) => n.id === id) || null; }
88
+ find(pred) { return this.root.find(pred); }
89
+ all(pred = () => true) { return this.root.findAll(pred); }
90
+ /* target: node | id | '.class' | '#id' | 'prefix*' | array | predicate */
91
+ resolve(target) {
92
+ if (!target) return [];
93
+ if (Array.isArray(target)) return target.flatMap((t) => this.resolve(t));
94
+ if (target instanceof Node) return [target];
95
+ if (typeof target === 'function') return this.all(target);
96
+ if (typeof target === 'string') {
97
+ if (target[0] === '.') { const c = target.slice(1); return this.all((n) => (' ' + (n.opts.class || '') + ' ').includes(' ' + c + ' ')); }
98
+ const id = target[0] === '#' ? target.slice(1) : target;
99
+ if (id.endsWith('*')) { const p = id.slice(0, -1); return this.all((n) => n.id && n.id.startsWith(p)); }
100
+ const n = this.get(id);
101
+ return n ? [n] : [];
102
+ }
103
+ if (target.node) return [target.node];
104
+ return [];
105
+ }
106
+
107
+ /* ── layout without DOM (bounds for staggers, fitting) ── */
108
+ measure() { this.root.content(this.view, IDENTITY); this.measured = true; return this.root.sb; }
109
+
110
+ /* ── DOM ── */
111
+ render() {
112
+ const v = this.view, html = this.root.content(v, IDENTITY);
113
+ this.measured = true;
114
+ if (!this.vb || this.opts.refit) this.vb = this._viewBox();
115
+ const o = this.opts, vb = this.vb;
116
+ const label = o.label || o.title || 'Isometric illustration';
117
+ const css = [];
118
+ if (o.height) css.push('height:' + o.height + (typeof o.height === 'number' ? 'px' : ''), 'width:100%');
119
+ if (o.colors) for (const k in o.colors) if (/^[\w-]+$/.test(k)) css.push('--iso-' + k + ':' + cssValue(o.colors[k]));
120
+ const svgOpen = '<svg xmlns="http://www.w3.org/2000/svg" class="iso iso-' + cssClass(o.theme) + (o.class ? ' ' + cssClass(o.class) : '') + '" viewBox="' + vb.map(fmt).join(' ') + '" role="img" aria-label="' + escAttr(label) + '"' + (css.length ? ' style="' + escAttr(css.join(';')) + '"' : '') + ' preserveAspectRatio="xMidYMid meet">';
121
+ const markup = svgOpen + (o.title ? '<title>' + escAttr(o.title) + '</title>' : '') + '<g class="iso-root">' + html + '</g></svg>';
122
+ if (!this.host || typeof document === 'undefined') { this._markup = markup; return markup; }
123
+ if (this.svg && this.svg.parentNode === this.host) {
124
+ const tmp = document.createElement('div'); tmp.innerHTML = markup;
125
+ const fresh = tmp.firstChild; this.host.replaceChild(fresh, this.svg); this.svg = fresh;
126
+ } else {
127
+ const tmp = document.createElement('div'); tmp.innerHTML = markup;
128
+ this.svg = tmp.firstChild;
129
+ if (o.replace !== false) { const old = this.host.querySelector(':scope > svg.iso'); if (old) old.remove(); }
130
+ this.host.appendChild(this.svg);
131
+ }
132
+ this.rootEl = this.svg.querySelector('.iso-root');
133
+ this.root.el = this.rootEl;
134
+ this._mapEls(this.svg);
135
+ this._containers = new Map();
136
+ this._bindEvents();
137
+ this._observe();
138
+ this.built = true;
139
+ this.needsRender = false;
140
+ if (this.reduced && !this.reducedApplied) { this.reducedApplied = true; this.playing = false; this.seek(o.restTime ?? this.settleTime()); }
141
+ else this.update(0);
142
+ this.emit('render');
143
+ clock.kick();
144
+ return this;
145
+ }
146
+ _viewBox() {
147
+ const o = this.opts;
148
+ if (o.view) return o.view.slice();
149
+ const b = this.root.sb, p = o.padding;
150
+ if (!b || !isFinite(b[0])) return [0, 0, 100, 100];
151
+ const ex = o.extend || [0, 0, 0, 0]; // [top, right, bottom, left] extra room for motion
152
+ let x = b[0] - p - ex[3], y = b[1] - p - ex[0], w = b[2] - b[0] + 2 * p + ex[1] + ex[3], h = b[3] - b[1] + 2 * p + ex[0] + ex[2];
153
+ if (o.aspect) { const a = o.aspect; if (w / h > a) { const nh = w / a; y -= (nh - h) / 2; h = nh; } else { const nw = h * a; x -= (nw - w) / 2; w = nw; } }
154
+ if (o.zoom && o.zoom !== 1) { const cx = x + w / 2, cy = y + h / 2; w /= o.zoom; h /= o.zoom; x = cx - w / 2; y = cy - h / 2; }
155
+ return [x, y, w, h];
156
+ }
157
+ refit() { this.measure(); this.vb = this._viewBox(); if (this.svg) this.svg.setAttribute('viewBox', this.vb.map(fmt).join(' ')); return this; }
158
+ _mapEls(scope) {
159
+ const els = scope.querySelectorAll('[data-uid]');
160
+ for (const el of els) { const n = this.byUid.get(+el.getAttribute('data-uid')); if (n) n.el = el; }
161
+ this.flows = Array.from(this.svg.querySelectorAll('[data-flow]'));
162
+ }
163
+ /* SVG markup of the scene at rest (works without a DOM) */
164
+ toString() {
165
+ if (this.svg) return this.svg.outerHTML;
166
+ const host = this.host; this.host = null;
167
+ const m = this.render(); this.host = host;
168
+ return m;
169
+ }
170
+
171
+ /* ── events (delegated) ── */
172
+ _nodeFrom(el, evt) {
173
+ while (el && el !== this.svg) {
174
+ if (el.hasAttribute && el.hasAttribute('data-uid')) {
175
+ const n = this.byUid.get(+el.getAttribute('data-uid'));
176
+ if (n && n.handlers && (n.handlers[evt] || (evt === 'click' && n.handlers.press))) return n;
177
+ }
178
+ el = el.parentNode;
179
+ }
180
+ return null;
181
+ }
182
+ _bindEvents() {
183
+ const svg = this.svg;
184
+ svg.addEventListener('click', (e) => { const n = this._nodeFrom(e.target, 'click'); if (n) { n.emit('click', e); n.emit('press', e); } });
185
+ svg.addEventListener('keydown', (e) => {
186
+ if (e.key !== 'Enter' && e.key !== ' ') return;
187
+ const n = this._nodeFrom(e.target, 'click');
188
+ if (n && e.target.getAttribute('data-uid') == n.uid) { e.preventDefault(); n.emit('click', e); n.emit('press', e); }
189
+ });
190
+ let hover = null;
191
+ svg.addEventListener('pointerover', (e) => {
192
+ const n = this._nodeFrom(e.target, 'hover');
193
+ if (n !== hover) { if (hover) hover.emit('leave', e); hover = n; if (n) n.emit('hover', e); }
194
+ });
195
+ svg.addEventListener('pointerleave', (e) => { if (hover) { hover.emit('leave', e); hover = null; } });
196
+ svg.addEventListener('focusin', (e) => { const n = this._nodeFrom(e.target, 'focus'); if (n) n.emit('focus', e); });
197
+ svg.addEventListener('pointerdown', (e) => { const n = this._nodeFrom(e.target, 'down'); if (n) n.emit('down', e); });
198
+ svg.addEventListener('pointerup', (e) => { const n = this._nodeFrom(e.target, 'up'); if (n) n.emit('up', e); });
199
+ }
200
+ _observe() {
201
+ if (this._io || typeof IntersectionObserver === 'undefined') return;
202
+ this._io = new IntersectionObserver((es) => { for (const e of es) this.visible = e.isIntersecting; if (this.visible) clock.kick(); });
203
+ this._io.observe(this.svg);
204
+ }
205
+
206
+ /* ── animation API ── */
207
+ timeline(opt = {}) { const tl = new Timeline(this, opt); this.timelines.push(tl); this._wake(); return tl; }
208
+ _removeTimeline(tl) { const i = this.timelines.indexOf(tl); if (i >= 0) this.timelines.splice(i, 1); }
209
+ /* reactive tween from current values */
210
+ to(target, props, opt = {}) {
211
+ const nodes = this.resolve(target);
212
+ const dur = this.reduced ? 0 : opt.duration ?? 0.3;
213
+ /* overwrite running reactive tweens on the same properties */
214
+ for (const tl of this.timelines) if (tl.reactive && !tl.done) for (const [k, tr] of tl.tracks) if (nodes.includes(tr.node) && tr.prop in props) tl.tracks.delete(k);
215
+ const tl = new Timeline(this, { reactive: true, start: this.time + (opt.delay || 0) });
216
+ tl.to(nodes, props, { ...opt, duration: dur, ease: opt.ease ?? 'out' }, 0);
217
+ this.timelines.push(tl);
218
+ this._wake();
219
+ return tl;
220
+ }
221
+ /* per-frame function fn(time, dt, scene); return handle with stop() */
222
+ loop(fn) {
223
+ const b = { fn, stopped: false, stop: () => { b.stopped = true; this.behaviors = this.behaviors.filter((x) => x !== b); } };
224
+ this.behaviors.push(b); this._wake();
225
+ return b;
226
+ }
227
+ /* time at which every finite timeline has finished (rest pose for reduced motion / posters) */
228
+ settleTime() {
229
+ let t = 0;
230
+ for (const tl of this.timelines) if (tl.repeat >= 0 && !tl.reactive) t = Math.max(t, tl.start + tl.total);
231
+ return t;
232
+ }
233
+ play() { this.playing = true; this._wake(); return this; }
234
+ pause() { this.playing = false; return this; }
235
+ toggle() { return this.playing ? this.pause() : this.play(); }
236
+ /* jump to absolute time (timelines and behaviours are functions of time) */
237
+ seek(t) {
238
+ for (const tl of this.timelines) { tl.reset(); if (tl.lastT !== null) tl.lastT = null; }
239
+ this.time = t;
240
+ this.update(0, true);
241
+ return this;
242
+ }
243
+ reset() { return this.seek(0); }
244
+ tick(dt) {
245
+ if (this.destroyed) return;
246
+ if (this.needsRender) { this.render(); }
247
+ if (!this.built) return;
248
+ if (this.playing) this.time += dt * this.timeScale;
249
+ this.update(dt);
250
+ this.emit('tick', this.time);
251
+ }
252
+ _wantsFrame() {
253
+ if (this.destroyed || !this.visible) return false;
254
+ if (this.needsRender || this.pending.size) return true;
255
+ if (!this.playing) return false;
256
+ return this.behaviors.length > 0 || (this.flows && this.flows.length > 0) || this.timelines.some((t) => !t.done && !t.paused);
257
+ }
258
+ _wake() { clock.kick(); }
259
+ _touch(n) { this.pending.add(n); clock.kick(); }
260
+
261
+ update(dt = 0, seeking = false) {
262
+ this._frame = (this._frame || 0) + 1;
263
+ /* reset additive channels */
264
+ for (const n of this.touchedA) {
265
+ const a = n.a;
266
+ if (a.x || a.y || a.z || a.scale !== 1) n.moved = true;
267
+ if (a.opacity !== 1) n.fade = true;
268
+ a.x = a.y = a.z = 0; a.scale = a.opacity = 1; this.pending.add(n);
269
+ }
270
+ this.touchedA.clear();
271
+ for (const tl of this.timelines.slice()) {
272
+ tl.apply(this.time);
273
+ if (tl.done && tl.reactive) this._removeTimeline(tl);
274
+ }
275
+ for (const b of this.behaviors.slice()) if (!b.stopped) b.fn(this.time, dt, this);
276
+ if (this.flows) for (const el of this.flows) {
277
+ const sp = +el.getAttribute('data-flow') || 0;
278
+ el.style.strokeDashoffset = fmt(-sp * this.time);
279
+ }
280
+ this.sync();
281
+ this._settle();
282
+ }
283
+ /* additive offset helper for behaviours */
284
+ nudge(node, key, value) {
285
+ if (key === 'scale' || key === 'opacity') node.a[key] *= value; else node.a[key] += value;
286
+ if (key === 'opacity') node.fade = true; else node.moved = true;
287
+ this.touchedA.add(node);
288
+ this.pending.add(node);
289
+ }
290
+
291
+ /* push node changes to the DOM */
292
+ sync() {
293
+ if (!this.built || !this.pending.size) { this.pending.clear(); return; }
294
+ const v = this.view, place = new Set();
295
+ const nodes = Array.from(this.pending);
296
+ this.pending.clear();
297
+ /* outermost dirty nodes first so a group re-render covers its children */
298
+ const dirty = nodes.filter((n) => n.dirty && n.el !== undefined);
299
+ const isCovered = (n) => { let p = n.parent; while (p) { if (p.dirty && dirty.includes(p)) return true; p = p.parent; } return false; };
300
+ for (const n of dirty) {
301
+ if (isCovered(n)) continue;
302
+ if (n.isGroup && n.flat) { this._rerenderFlat(n, place); continue; }
303
+ if (!n.el) continue;
304
+ const html = n.content(v, n.frame);
305
+ n.el.innerHTML = html;
306
+ if (n.isGroup) { this._mapEls(n.el); const c = this._containers.get(n); if (c) c.stale = true; }
307
+ else if (this.flows && n.el.querySelector('[data-flow]')) this.flows = Array.from(this.svg.querySelectorAll('[data-flow]'));
308
+ n.restyle = true; n.sync(v);
309
+ place.add(n);
310
+ }
311
+ for (const n of nodes) {
312
+ if (n.isGroup && n.flat) {
313
+ if (n.moved || n.restyle || n.fade) for (const it of n.items()) { it.sync(v); if (n.moved || n.restyle) place.add(it); }
314
+ n.moved = false; n.restyle = false; n.fade = false;
315
+ continue;
316
+ }
317
+ if (n.moved || n.restyle || n.fade) { n.sync(v); if (n.moved) place.add(n); n.moved = false; n.fade = false; }
318
+ }
319
+ /* propagate bound changes to atomic ancestors and place */
320
+ const containers = new Map();
321
+ for (const n of place) {
322
+ let cur = n;
323
+ for (;;) {
324
+ const c = containerOf(cur);
325
+ if (!c) break;
326
+ if (!containers.has(c)) containers.set(c, new Set());
327
+ containers.get(c).add(cur);
328
+ if (c === this.root || c.isGroup === false) break;
329
+ /* the container's own bounds changed: it may need placing in its parent */
330
+ c.rest = c.aabb();
331
+ cur = c;
332
+ }
333
+ }
334
+ for (const [c, movers] of containers) this._place(c, movers);
335
+ }
336
+ _rerenderFlat(g, place) {
337
+ const v = this.view, cf = g.childFrame(g.frame || IDENTITY);
338
+ for (const c of g.children) {
339
+ if (c.isGroup && c.flat) { c.frame = cf; c.dirty = true; this._rerenderFlat(c, place); continue; }
340
+ if (!c.el) continue;
341
+ c.el.innerHTML = c.content(v, cf);
342
+ if (c.isGroup) this._mapEls(c.el);
343
+ c.sync(v); place.add(c);
344
+ }
345
+ g.dirty = false;
346
+ }
347
+ _place(container, movers) {
348
+ if (container.sortMode === 'none') return;
349
+ let st = this._containers.get(container);
350
+ const zs = this.view.ZS;
351
+ if (!st || st.stale) {
352
+ st = { dyn: new Set(), last: new Map(), slotOf: new Map(), bySlot: new Map(), placer: null, statics: null, stale: false, lastResort: this._frame || 0, parent: container === this.root ? this.rootEl : container.el };
353
+ this._containers.set(container, st);
354
+ }
355
+ if (!st.parent) return;
356
+ let rebuild = !st.placer;
357
+ for (const m of movers) { if (!st.dyn.has(m)) { st.dyn.add(m); rebuild = true; } st.last.set(m, this._frame || 0); }
358
+ const touched = new Set();
359
+ const assign = (d) => {
360
+ if (!d.el || d.el.parentNode !== st.parent) return;
361
+ const slot = st.placer.slot(makeItem(d, d.sortBox(), zs, d.order));
362
+ const old = st.slotOf.get(d);
363
+ if (old === slot) { touched.add(slot); return; }
364
+ if (old !== undefined) { const set = st.bySlot.get(old); if (set) set.delete(d); touched.add(old); }
365
+ st.slotOf.set(d, slot);
366
+ let set = st.bySlot.get(slot); if (!set) st.bySlot.set(slot, (set = new Set()));
367
+ set.add(d); touched.add(slot);
368
+ };
369
+ if (rebuild) {
370
+ const order = (container.sorted || []).filter((n) => !st.dyn.has(n) && !n.hidden && n.el);
371
+ st.statics = order.map((n) => makeItem(n, n.sortBox(), zs, n.order));
372
+ st.placer = new Placer(st.statics);
373
+ st.slotOf.clear(); st.bySlot.clear();
374
+ for (const d of st.dyn) assign(d);
375
+ } else for (const m of movers) assign(m);
376
+ /* moving items that overlap each other must also respect each other */
377
+ if (st.dyn.size > 1 && st.dyn.size <= 160) {
378
+ const list = [];
379
+ for (const d of st.dyn) if (st.slotOf.has(d)) list.push({ d, it: makeItem(d, d.sortBox(), zs, d.order) });
380
+ const move = (d, slot) => {
381
+ const old = st.slotOf.get(d); const a = st.bySlot.get(old); if (a) a.delete(d);
382
+ st.slotOf.set(d, slot); let b = st.bySlot.get(slot); if (!b) st.bySlot.set(slot, (b = new Set()));
383
+ b.add(d); touched.add(old); touched.add(slot);
384
+ };
385
+ for (let pass = 0; pass < 3; pass++) {
386
+ let changed = false;
387
+ for (let i = 0; i < list.length; i++) for (let j = i + 1; j < list.length; j++) {
388
+ const A = list[i], B = list[j];
389
+ if (!A.it.hex || !B.it.hex || !hexOverlap(A.it.hex, B.it.hex)) continue;
390
+ const c = compareItems(A.it, B.it), sa = st.slotOf.get(A.d), sb = st.slotOf.get(B.d);
391
+ if (c < 0 && sa > sb) { move(B.d, sa); changed = true; } else if (c > 0 && sb > sa) { move(A.d, sb); changed = true; }
392
+ }
393
+ if (!changed) break;
394
+ }
395
+ }
396
+ for (const slot of touched) {
397
+ const set = st.bySlot.get(slot);
398
+ if (!set || !set.size) continue;
399
+ let items = Array.from(set).map((d) => makeItem(d, d.sortBox(), zs, d.order));
400
+ if (items.length === 2) items.sort(compareItems);
401
+ else if (items.length > 2) items = depthSort(items);
402
+ const refItem = st.statics[slot + 1];
403
+ /* back to front: each element must sit immediately before its successor */
404
+ let next = refItem ? refItem.node.el : null;
405
+ for (let i = items.length - 1; i >= 0; i--) {
406
+ const el = items[i].node.el;
407
+ if (el.nextSibling !== next) st.parent.insertBefore(el, next);
408
+ next = el;
409
+ }
410
+ }
411
+ }
412
+
413
+ /* Items that stopped moving go back into the static order: one full depth sort of the container. */
414
+ _settle() {
415
+ if (!this._containers) return;
416
+ const f = this._frame;
417
+ for (const [c, st] of this._containers) {
418
+ if (!st.dyn.size || st.stale || f - st.lastResort < 30) continue;
419
+ let settled = 0;
420
+ for (const d of st.dyn) if (f - (st.last.get(d) ?? 0) > 20) settled++;
421
+ if (settled && (settled >= Math.max(8, st.dyn.size * 0.2) || st.dyn.size > 160)) this._resort(c, st);
422
+ }
423
+ }
424
+ _resort(container, st) {
425
+ const zs = this.view.ZS, f = this._frame;
426
+ const nodes = (container.sorted || []).filter((n) => n.el && n.el.parentNode === st.parent);
427
+ const ordered = depthSort(nodes.map((n) => makeItem(n, n.sortBox(), zs, n.order))).map((it) => it.node);
428
+ container.sorted = ordered;
429
+ let cursor = st.parent.firstElementChild;
430
+ for (const n of ordered) { if (n.el === cursor) cursor = cursor.nextElementSibling; else st.parent.insertBefore(n.el, cursor); }
431
+ for (const d of Array.from(st.dyn)) if (f - (st.last.get(d) ?? 0) > 20) { st.dyn.delete(d); st.last.delete(d); }
432
+ st.placer = null; st.slotOf.clear(); st.bySlot.clear(); st.lastResort = f;
433
+ if (st.dyn.size) this._place(container, new Set());
434
+ }
435
+
436
+ /* ── utilities ── */
437
+ /* world point → CSS pixels relative to the SVG's top-left (for HTML overlays) */
438
+ project(p) {
439
+ const q = this.view.P(p[0], p[1], p[2] || 0), vb = this.vb;
440
+ if (!this.svg || !vb) return { x: q[0], y: q[1] };
441
+ const r = this.svg.getBoundingClientRect();
442
+ const s = Math.min(r.width / vb[2], r.height / vb[3]);
443
+ const ox = (r.width - vb[2] * s) / 2, oy = (r.height - vb[3] * s) / 2;
444
+ return { x: ox + (q[0] - vb[0]) * s, y: oy + (q[1] - vb[1]) * s };
445
+ }
446
+ on(evt, fn) { (this.listeners[evt] || (this.listeners[evt] = [])).push(fn); return this; }
447
+ emit(evt, arg) { (this.listeners[evt] || []).forEach((f) => f(arg, this)); }
448
+ setTheme(theme) {
449
+ theme = cssClass(theme);
450
+ const old = 'iso-' + this.opts.theme, nu = 'iso-' + theme;
451
+ if (this.svg) { this.svg.classList.remove(old); this.svg.classList.add(nu); }
452
+ if (this.figure) { this.figure.el.classList.remove(old); this.figure.el.classList.add(nu); }
453
+ this.opts.theme = theme;
454
+ return this;
455
+ }
456
+ destroy() {
457
+ this.destroyed = true; clock.remove(this);
458
+ if (this._io) this._io.disconnect();
459
+ if (this.svg) this.svg.remove();
460
+ if (this.figure) this.figure.el.remove();
461
+ this.emit('destroy');
462
+ }
463
+ }
464
+
465
+ function containerOf(n) { let p = n.parent; while (p && p.flat) p = p.parent; return p; }
466
+ function escAttr(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])); }