@johnoscott/isometric-engine 0.14.1 → 0.16.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 (81) hide show
  1. package/README.md +1 -1
  2. package/iso-editor.js +249 -203
  3. package/iso-render.js +200 -154
  4. package/iso-systems.js +210 -162
  5. package/isometric-diagram.js +389 -0
  6. package/js/iso-core/index.js +5 -0
  7. package/js/iso-core/mono.js +242 -0
  8. package/js/iso-editor/ui/canvas.js +23 -1
  9. package/js/iso-objects/ants.js +36 -0
  10. package/js/iso-objects/index.js +55 -1
  11. package/js/iso-objects/looks.js +25 -0
  12. package/js/iso-objects/mono-paint.js +96 -0
  13. package/js/iso-objects/motion-builder.js +130 -0
  14. package/js/iso-objects/motion-doc.js +421 -0
  15. package/js/iso-objects/motion-entry.js +34 -0
  16. package/js/iso-objects/motion-schema.js +83 -0
  17. package/js/iso-objects/motion.js +640 -0
  18. package/js/iso-objects/resolve.js +238 -0
  19. package/js/iso-objects/scene.js +15 -13
  20. package/js/iso-objects/timeline.js +593 -0
  21. package/js/iso-systems/compile.js +83 -1
  22. package/js/iso-systems/index.js +4 -1
  23. package/js/iso-systems/render.js +20 -0
  24. package/js/iso-systems/schema.json +40 -0
  25. package/js/iso-viewer/index.js +6 -0
  26. package/js/iso-viewer/page.js +40 -16
  27. package/js/iso-viewer/play.js +340 -0
  28. package/js/iso-viewer/player.js +149 -175
  29. package/js/iso-viewer/transport.js +289 -0
  30. package/package.json +84 -2
  31. package/src/iso-core/index.ts +1 -0
  32. package/src/iso-core/mono.ts +306 -0
  33. package/src/iso-core/theme.ts +2 -1
  34. package/src/iso-editor/ui/canvas.ts +14 -1
  35. package/src/iso-objects/ants.ts +53 -0
  36. package/src/iso-objects/compile.ts +4 -1
  37. package/src/iso-objects/index.ts +16 -1
  38. package/src/iso-objects/looks.ts +21 -0
  39. package/src/iso-objects/mono-paint.ts +97 -0
  40. package/src/iso-objects/motion-builder.ts +79 -0
  41. package/src/iso-objects/motion-doc.ts +309 -0
  42. package/src/iso-objects/motion-entry.ts +13 -0
  43. package/src/iso-objects/motion-schema.ts +55 -0
  44. package/src/iso-objects/motion.ts +617 -0
  45. package/src/iso-objects/resolve.ts +196 -0
  46. package/src/iso-objects/scene.ts +32 -13
  47. package/src/iso-objects/timeline.ts +493 -0
  48. package/src/iso-objects/types.ts +22 -2
  49. package/src/iso-systems/compile.ts +86 -4
  50. package/src/iso-systems/index.ts +4 -1
  51. package/src/iso-systems/render.ts +45 -0
  52. package/src/iso-systems/schema.json +40 -0
  53. package/src/iso-viewer/index.ts +4 -0
  54. package/src/iso-viewer/page.ts +28 -11
  55. package/src/iso-viewer/play.ts +280 -0
  56. package/src/iso-viewer/player.ts +132 -150
  57. package/src/iso-viewer/transport.ts +272 -0
  58. package/types/iso-core/index.d.ts +1 -0
  59. package/types/iso-core/mono.d.ts +61 -0
  60. package/types/iso-core/theme.d.ts +2 -0
  61. package/types/iso-objects/ants.d.ts +34 -0
  62. package/types/iso-objects/compile.d.ts +3 -0
  63. package/types/iso-objects/index.d.ts +16 -1
  64. package/types/iso-objects/looks.d.ts +4 -0
  65. package/types/iso-objects/mono-paint.d.ts +20 -0
  66. package/types/iso-objects/motion-builder.d.ts +105 -0
  67. package/types/iso-objects/motion-doc.d.ts +193 -0
  68. package/types/iso-objects/motion-entry.d.ts +11 -0
  69. package/types/iso-objects/motion-schema.d.ts +594 -0
  70. package/types/iso-objects/motion.d.ts +202 -0
  71. package/types/iso-objects/resolve.d.ts +20 -0
  72. package/types/iso-objects/scene.d.ts +14 -0
  73. package/types/iso-objects/timeline.d.ts +66 -0
  74. package/types/iso-objects/types.d.ts +34 -0
  75. package/types/iso-systems/compile.d.ts +25 -3
  76. package/types/iso-systems/index.d.ts +4 -1
  77. package/types/iso-systems/render.d.ts +25 -0
  78. package/types/iso-viewer/index.d.ts +4 -0
  79. package/types/iso-viewer/play.d.ts +37 -0
  80. package/types/iso-viewer/transport.d.ts +73 -0
  81. package/types/player/isometric-diagram.d.ts +24 -0
@@ -2,36 +2,37 @@
2
2
  // It reads the scene data from <script type="application/json" id="diagram-steps"> and the rendered SVG.
3
3
  //
4
4
  // Hash flags (for screenshots and links): #theme=light|dark, #still (no motion: tokens frozen mid-route),
5
- // #scene=ID&step=N (open a scene at a step), #t=0.6 (where frozen tokens sit, 0..1), #motion (ignore reduced motion),
5
+ // #scene=ID&step=N (open a scene at a step), #t=0.6 (where frozen tokens sit, 0..1), #motion (no Motion off button),
6
6
  // #grid (show the floor grid), #assemble (play the assemble intro) and #assemble&at=MS (freeze it at that moment).
7
7
 
8
- import { focusView } from '../iso-objects/focus.ts';
8
+ //
9
+ // Motion plays, also for a reader who asked their machine for less (docs/design/MOTION.md, 6.2): they get a Motion off button in each figure.
10
+ //
11
+ // One clock: a transport (transport.ts) over the scene's Timeline, for the steps, their tokens, pulses and camera, and another over the
12
+ // assemble intro's plan. What a step dims, hides and lights is the page's stylesheet's, by classes, when its beat begins.
13
+
14
+ import { paint, planOf, type SceneState } from '../iso-objects/motion.ts';
15
+ import { bindMotion, type MotionSource, type Timeline } from '../iso-objects/timeline.ts';
16
+ import type { MotionDoc } from '../iso-objects/motion-doc.ts';
17
+ import { transport } from './transport.ts';
9
18
 
10
19
  interface Token { route: string; kind: string; color: string }
11
20
  interface Step {
12
21
  n: number; num: number; kind: string; color: string; heading: string; caption: string; command: string;
13
22
  phases: Token[][]; pulses: [number, number, number, number][]; lit: string[]; duration: number;
14
- focus?: [number, number, number, number];
15
23
  }
16
- interface Piece { id: string; kind: 'region' | 'node'; dx: number; dy: number; delay: number; dur: number }
17
- interface Assembly { pieces: Piece[]; routes: { id: string; delay: number; dur: number }[]; labels: { delay: number; dur: number }; total: number }
18
24
  interface SceneData {
19
25
  id: string; loop: boolean; dim: 'flows' | 'all'; steps: Step[]; vis: Record<string, boolean[]>;
20
- assemble: boolean; grid: boolean; assembly: Assembly;
26
+ assemble: boolean; grid: boolean; source: MotionSource;
27
+ /** the steps as a motion document, or the scene's own */
28
+ doc?: MotionDoc;
29
+ /** the scene's own motion: everything is the Timeline's, what is dimmed and hidden too */
30
+ own?: boolean;
21
31
  }
22
32
  interface Data { scenes: SceneData[] }
23
33
 
24
- const NS = 'http://www.w3.org/2000/svg';
25
- const TRAVEL = 1150;
26
- const EASE_IN = 'cubic-bezier(.16,.84,.3,1)';
27
-
28
- function svgEl(tag: string, attrs: Record<string, string | number>, parent: Element): SVGElement {
29
- const e = document.createElementNS(NS, tag);
30
- for (const k in attrs) e.setAttribute(k, String(attrs[k]));
31
- parent.appendChild(e);
32
- return e;
33
- }
34
34
  const ease = (f: number) => (f < 0.5 ? 2 * f * f : 1 - Math.pow(-2 * f + 2, 2) / 2);
35
+ const none: Timeline = { ok: true, diags: [], duration: 0, beats: [], markers: {}, ambient: 'on', loops: false, at: () => ({}), cues: () => undefined, beatAt: () => undefined, startOf: () => undefined };
35
36
 
36
37
  function init() {
37
38
  const dataEl = document.getElementById('diagram-steps');
@@ -39,8 +40,9 @@ function init() {
39
40
  const data = JSON.parse(dataEl.textContent || '{}') as Data;
40
41
  const hash = location.hash;
41
42
  const still = /still/.test(hash);
42
- const reduceMedia = matchMedia('(prefers-reduced-motion: reduce)').matches && !/motion/.test(hash);
43
- const reduce = still || reduceMedia;
43
+ const asked = matchMedia('(prefers-reduced-motion: reduce)').matches && !still && !/motion/.test(hash);
44
+ /** nothing moves: a still page, or Motion off pressed */
45
+ let reduce = still;
44
46
  const frozenT = Math.max(0, Math.min(1, Number((/[#&]t=([\d.]+)/.exec(hash) || [])[1] ?? 0.6)));
45
47
  const wantScene = (/[#&]scene=([\w-]+)/.exec(hash) || [])[1];
46
48
  const wantStep = Number((/[#&]step=?(\d+)/.exec(hash) || [])[1] || 0);
@@ -52,7 +54,8 @@ function init() {
52
54
  // #scene=ID opens the page at that scene (screenshots use #still, which keeps the page at the top)
53
55
  if (wantScene && !still) document.getElementById('scene-' + wantScene)?.scrollIntoView({ block: 'start' });
54
56
 
55
- const runners: { fig: Element; setActive(on: boolean): void }[] = [];
57
+ const runners: { fig: Element; setActive(on: boolean): void; setMotion(): void }[] = [];
58
+ const offBtns: HTMLButtonElement[] = [];
56
59
  for (const sd of data.scenes) {
57
60
  const sec = document.getElementById('scene-' + sd.id);
58
61
  if (sec) runners.push(makeRunner(sec, sd));
@@ -61,7 +64,6 @@ function init() {
61
64
  function makeRunner(sec: HTMLElement, sd: SceneData) {
62
65
  const STEPS = sd.steps, N = STEPS.length;
63
66
  const svg = sec.querySelector('svg')!, fig = sec.querySelector('.figure')!;
64
- const anim = svg.querySelector('.g-anim')!;
65
67
  const q = <T extends Element>(s: string) => sec.querySelector(s) as T | null;
66
68
  const num = q<HTMLElement>('.cap-h .num'), hEl = q<HTMLElement>('.cap-h .h'), cnt = q<HTMLElement>('.cap-h .cnt');
67
69
  const capT = q<HTMLElement>('.cap-t'), capC = q<HTMLElement>('.cap-c'), prog = q<HTMLElement>('.prog i'), dots = q<HTMLElement>('.dots');
@@ -73,12 +75,13 @@ function init() {
73
75
  const visEls = new Map<string, SVGElement[]>();
74
76
  for (const e of idEls) if (sd.vis[e.dataset.id!]) { const l = visEls.get(e.dataset.id!) ?? []; l.push(e); visEls.set(e.dataset.id!, l); }
75
77
  for (const e of hlEls) { const id = e.dataset.hl!; if (sd.vis[id] && !e.dataset.id) { const l = visEls.get(id) ?? []; l.push(e); visEls.set(id, l); } }
76
- const flowPath = (id: string) => svg.querySelector<SVGPathElement>(`[data-hl="${CSS.escape(id)}"] path.flow`);
77
78
  if (sd.dim === 'all') svg.classList.add('dim-all');
78
79
 
79
- let cur = 0, playing = false, userPaused = false, active = false, timer = 0, raf = 0, groups = 0, t0 = 0;
80
- let assembling = false, assembled = false, animations: Animation[] = [];
81
- let tokens: { path: SVGPathElement; len: number; gi: number; stop: boolean; c: SVGElement }[] = [];
80
+ const bound = sd.doc ? bindMotion(sd.source, sd.doc) : none, tl = bound.ok ? bound : none;
81
+ const tr = transport(tl, { loop: sd.loop });
82
+ tr.active = false;
83
+ let cur = 0, userPaused = false, active = false, stepping = false;
84
+ let assembling = false, assembled = false;
82
85
 
83
86
  // ---- grid ----
84
87
  const setGrid = (on: boolean) => { svg.classList.toggle('show-grid', on); gridBtn?.setAttribute('aria-pressed', String(on)); };
@@ -88,179 +91,158 @@ function init() {
88
91
  STEPS.forEach((s, i) => {
89
92
  const b = document.createElement('button');
90
93
  b.className = 'dot'; b.type = 'button'; b.setAttribute('aria-label', `Step ${s.num}: ${s.heading}`);
91
- b.addEventListener('click', () => { userPause(); finishAssemble(); show(i); });
94
+ b.addEventListener('click', () => { userPause(); finishAssemble(); show(i, true); });
92
95
  dots?.appendChild(b);
93
96
  });
94
97
 
95
- function clearAnim() { anim.textContent = ''; tokens = []; if (raf) cancelAnimationFrame(raf); raf = 0; }
96
- function tick(now: number) {
97
- const per = TRAVEL * groups + 700, tt = (now - t0) % per;
98
- for (const tk of tokens) {
99
- // frozen: every phase's token sits at the same point, so one picture shows them all
100
- const f = reduce ? frozenT : Math.max(0, Math.min(1, (tt - tk.gi * TRAVEL) / TRAVEL));
101
- let e = ease(f);
102
- if (tk.stop) e = f < 0.7 ? f / 0.7 : 1 - ((f - 0.7) / 0.3) * 0.25; // a blocked token stalls and falls back
103
- const p = tk.path.getPointAtLength(Math.max(0, Math.min(1, e)) * tk.len);
104
- tk.c.setAttribute('cx', String(p.x)); tk.c.setAttribute('cy', String(p.y));
105
- tk.c.style.opacity = reduce ? '1' : f <= 0 || f >= 1 ? '0' : '1';
106
- }
107
- if (!reduce && active) raf = requestAnimationFrame(tick);
98
+ // ---- what is drawn now ----
99
+ const inkOf = new Map(STEPS.flatMap(s => s.phases.flat().map(t => [t.kind, t.color] as const)));
100
+ /** the Timeline's state as the page draws it: its tokens and pulses in the step's colours; the rest is its classes' */
101
+ function drawn(): SceneState {
102
+ const S: SceneState = reduce ? frozen() : tr.state(), s = STEPS[cur];
103
+ if (sd.own || !s) return S;
104
+ const out: SceneState = {};
105
+ if (S.camera && !svg.classList.contains('all')) out.camera = S.camera;
106
+ if (S.tokens) out.tokens = S.tokens.map(k => ({ ...k, color: k.color ?? (k.kind === undefined ? undefined : inkOf.get(k.kind)) }));
107
+ // (each ring grows from a third of its size to half as much again, and fades)
108
+ if (reduce) { if (s.pulses.length) out.pulses = s.pulses.map(([x, y, rx, ry]) => ({ x, y, rx, ry, opacity: 0.85, color: s.color })); }
109
+ else if (S.pulses) out.pulses = s.pulses.flatMap(([x, y, rx, ry], k) => { const p = S.pulses![k]; if (!p) return []; const f = 1 - Math.pow(p.opacity ?? 1, 2), z = 0.35 + 1.15 * f; return [{ x, y, rx: rx * z, ry: ry * z, opacity: 0.95 * (1 - f), color: s.color }]; });
110
+ return out;
108
111
  }
109
- // ---- focus: ease the viewBox to a step's focus box (keeping the drawing's proportions), and back ----
110
- const FULL = svg.getAttribute('viewBox')!.split(/\s+/).map(Number);
111
- let view = FULL.slice(), zoomTimer = 0;
112
- const viewFor = (s: Step) => focusView(FULL, s.focus);
113
- function zoomTo(target: number[]) {
114
- clearTimeout(zoomTimer);
115
- if (target.every((v, k) => Math.abs(v - view[k]) < 0.5)) return;
116
- const from = view.slice(), t0z = performance.now(), D = reduce ? 0 : 900;
117
- // a timer, not a frame callback, so it also finishes where no frames are drawn
118
- const step = () => {
119
- const f = D ? Math.min(1, (performance.now() - t0z) / D) : 1, e = ease(f);
120
- view = from.map((v, k) => v + (target[k] - v) * e);
121
- svg.setAttribute('viewBox', view.map(v => v.toFixed(1)).join(' '));
122
- if (f < 1) zoomTimer = window.setTimeout(step, 16);
123
- };
124
- step();
112
+ /** frozen: every phase's token at the same point, so one picture shows them all; the camera where the step leaves it */
113
+ function frozen(): SceneState {
114
+ const s = STEPS[cur], b = tl.beats[cur];
115
+ if (!s || !b) return {};
116
+ const S = tl.at(Math.max(b.start, b.end - 1), { ambient: 'off' });
117
+ if (sd.own) return S;
118
+ const at = (kind: string) => (kind === 'blocked' ? (frozenT < 0.7 ? frozenT / 0.7 : 1 - ((frozenT - 0.7) / 0.3) * 0.25) : ease(frozenT));
119
+ return { ...(S.camera ? { camera: S.camera } : {}), tokens: s.phases.flat().map(t => ({ route: t.route, at: at(t.kind), kind: t.kind })) };
125
120
  }
121
+ const draw = () => {
122
+ if (assembling) return;
123
+ paint(svg, drawn());
124
+ if (prog && N) prog.style.width = (going() ? (tl.cues(tr.time)?.progress ?? 0) * 100 : ((cur + 1) / N) * 100) + '%';
125
+ };
126
+ const going = () => tr.playing && !stepping;
126
127
 
127
- function show(i: number) {
128
- if (!N) return;
129
- clearAnim();
130
- cur = i;
128
+ /** the page at a step: what is lit, dimmed and hidden, the words; nothing moves by this */
129
+ function look(i: number) {
131
130
  const s = STEPS[i], n = s.n;
132
- zoomTo(svg.classList.contains("all") ? FULL : viewFor(s));
131
+ cur = i;
133
132
  const lit = new Set(s.lit);
134
- svg.classList.add('focus');
135
- for (const e of hlEls) e.classList.toggle('hl', e.dataset.hl!.split(' ').some(x => lit.has(x)));
136
- if (sd.dim === 'all') for (const e of idEls) if (e.hasAttribute('data-dim')) e.classList.toggle('hl', lit.has(e.dataset.id!));
133
+ if (!sd.own) {
134
+ svg.classList.add('focus');
135
+ for (const e of hlEls) e.classList.toggle('hl', e.dataset.hl!.split(' ').some(x => lit.has(x)));
136
+ if (sd.dim === 'all') for (const e of idEls) if (e.hasAttribute('data-dim')) e.classList.toggle('hl', lit.has(e.dataset.id!));
137
+ for (const [id, els] of visEls) { const v = sd.vis[id][i]; for (const e of els) e.classList.toggle('pre', !v); }
138
+ }
137
139
  for (const e of stepEls) e.classList.toggle('on', e.dataset.step === String(n));
138
140
  svg.querySelectorAll<SVGElement>('[data-badge]').forEach(b => b.classList.toggle('on', b.dataset.badge === String(n)));
139
- for (const [id, els] of visEls) { const v = sd.vis[id][i]; for (const e of els) e.classList.toggle('pre', !v); }
140
- for (const [x, y, rx, ry] of s.pulses) svgEl('ellipse', { cx: x, cy: y, rx, ry, class: 'pulse', style: `stroke:${s.color}` }, anim);
141
- groups = s.phases.length;
142
- s.phases.forEach((ph, gi) => ph.forEach(tk => {
143
- const path = flowPath(tk.route);
144
- if (!path) return;
145
- tokens.push({ path, len: path.getTotalLength(), gi, stop: tk.kind === 'blocked', c: svgEl('circle', { r: 7, class: 'tok', style: `fill:${tk.color}` }, anim) });
146
- }));
147
- t0 = performance.now(); tick(t0);
148
- if (!reduce && active && !raf) raf = requestAnimationFrame(tick);
149
141
  num!.textContent = String(s.num); num!.style.background = s.color;
150
142
  hEl!.textContent = s.heading; cnt!.textContent = `${i + 1} / ${N}`;
151
143
  capT!.innerHTML = s.caption; capC!.textContent = s.command;
152
144
  prog!.style.setProperty('--c', s.color);
153
145
  [...dots!.children].forEach((d, j) => { d.classList.toggle('on', j === i); d.classList.toggle('done', j < i); });
154
- restartProg();
155
- }
156
- function restartProg() {
157
- if (!prog) return;
158
- prog.style.transition = 'none';
159
- prog.style.width = playing ? '0%' : ((cur + 1) / N * 100) + '%';
160
- if (playing) { void prog.offsetWidth; prog.style.transition = `width ${STEPS[cur].duration}ms linear`; prog.style.width = '100%'; }
161
146
  }
162
- function schedule() {
163
- clearTimeout(timer);
164
- if (!playing) return;
165
- timer = window.setTimeout(() => {
166
- if (cur === N - 1 && !sd.loop) { stop(); return; }
167
- show((cur + 1) % N); schedule();
168
- }, STEPS[cur].duration);
147
+ /** to a step's start; `through`: and through it, to a stop in it */
148
+ function show(i: number, through = false) {
149
+ const b = tl.beats[i];
150
+ if (!N || !b) return;
151
+ tr.pause();
152
+ look(i);
153
+ tr.seek(b.start, { join: true });
154
+ if (through && !reduce && active) { stepping = true; tr.play({ until: Math.max(b.start + 1, b.end - 1) }); setBtn(); }
155
+ draw();
169
156
  }
170
157
  function setBtn() {
171
158
  if (!playBtn) return;
172
- playBtn.textContent = playing ? '❚❚ Pause' : '▶ Play';
173
- playBtn.setAttribute('aria-label', playing ? 'Pause' : 'Play');
174
- capBox?.setAttribute('aria-live', playing ? 'off' : 'polite');
159
+ playBtn.disabled = reduce;
160
+ if (reduce) { playBtn.textContent = 'Motion off'; return; }
161
+ const on = going();
162
+ playBtn.textContent = on ? '❚❚ Pause' : '▶ Play';
163
+ playBtn.setAttribute('aria-label', on ? 'Pause' : 'Play');
164
+ capBox?.setAttribute('aria-live', on ? 'off' : 'polite');
175
165
  }
176
- function play() { if (reduce || !N || assembling) return; playing = true; setBtn(); restartProg(); schedule(); }
177
- function stop() { playing = false; clearTimeout(timer); setBtn(); restartProg(); }
166
+ function play() { if (reduce || !N || assembling) return; if (stepping) tr.pause(); stepping = false; tr.play(); setBtn(); draw(); }
167
+ function stop() { tr.pause(); }
178
168
  function userPause() { userPaused = true; stop(); }
169
+ tr.on('time', draw);
170
+ tr.on('beat', b => { if (b.index !== cur) look(b.index); });
171
+ tr.on('pause', () => { stepping = false; setBtn(); draw(); });
179
172
 
180
- // ---- assemble: regions and nodes fly in from the nearest edge, routes draw in, labels fade in ----
181
- const A = sd.assembly;
182
- const layer = (name: string) => svg.querySelector(`.g-${name}`);
173
+ // ---- assemble: the motion core's plan (the same a video is made from), on a transport of its own ----
174
+ const plan = planOf(sd.source.model, 'assemble');
175
+ let intro: ReturnType<typeof transport> | undefined;
183
176
  function finishAssemble() {
184
- if (!assembling) return;
185
- for (const a of animations) a.finish();
177
+ if (!assembling || !intro) return;
178
+ intro.dispose(); intro = undefined;
179
+ assembling = false; assembled = true;
180
+ paint(svg, {});
181
+ if (N) show(cur);
182
+ if (active && !userPaused) play();
186
183
  }
187
184
  function assemble(freezeAt?: number) {
188
- for (const a of animations) a.cancel();
189
- animations = [];
185
+ intro?.dispose(); intro = undefined;
190
186
  stop();
191
187
  if (N) show(cur); // set what is visible at this step; focus comes back at the end
192
- clearAnim();
193
188
  svg.classList.remove('focus', 'pre-assemble', 'all');
194
189
  assembling = true;
195
- const run = (el: Element, frames: Keyframe[], delay: number, dur: number, easing = EASE_IN) =>
196
- animations.push(el.animate(frames, { delay, duration: dur, easing, fill: 'backwards' }));
197
- const solid = ['base', 'blocks', 'air'].map(layer).filter(Boolean) as Element[];
198
- for (const p of A.pieces) {
199
- const from = `translate(${p.dx}px, ${p.dy}px)`;
200
- for (const L of solid) L.querySelectorAll(`[data-id="${CSS.escape(p.id)}"]`).forEach(el =>
201
- run(el, [{ transform: from }, { transform: 'translate(0px, 0px)' }], p.delay, p.dur));
202
- }
203
- for (const r of A.routes) {
204
- const g = layer('flows')?.querySelector(`[data-hl="${CSS.escape(r.id)}"]`);
205
- const path = g?.querySelector<SVGPathElement>('path.flow');
206
- if (!g || !path) continue;
207
- const len = path.getTotalLength();
208
- run(g, [{ opacity: 0 }, { opacity: 1 }], r.delay, 80, 'linear');
209
- run(path, [{ strokeDasharray: `${len} ${len}`, strokeDashoffset: len }, { strokeDasharray: `${len} ${len}`, strokeDashoffset: 0 }], r.delay, r.dur, 'ease-out');
210
- }
211
- for (const name of ['floor', 'labels', 'badges']) {
212
- const L = layer(name);
213
- if (L) run(L, [{ opacity: 0 }, { opacity: 1 }], A.labels.delay, A.labels.dur, 'ease-out');
214
- }
215
- if (freezeAt !== undefined) {
216
- for (const a of animations) { a.pause(); a.currentTime = freezeAt; }
217
- return;
218
- }
219
- Promise.all(animations.map(a => a.finished)).then(() => {
220
- assembling = false; assembled = true; animations = [];
221
- if (N) show(cur);
222
- if (active && !userPaused) play();
223
- }, () => { /* replaced by a newer run */ });
190
+ if (freezeAt !== undefined) { paint(svg, plan.at(freezeAt)); return; }
191
+ const run = intro = transport({ ...none, duration: plan.duration, at: t => plan.at(t) });
192
+ run.on('time', t => paint(svg, plan.at(t)));
193
+ run.on('end', finishAssemble);
194
+ paint(svg, plan.at(0));
195
+ run.play();
224
196
  }
225
197
  asmBtn?.addEventListener('click', () => { userPaused = false; assemble(); });
226
198
 
227
199
  function setActive(on: boolean) {
228
200
  if (on === active) return;
229
201
  active = on;
230
- if (on) {
231
- if (!reduce) { t0 = performance.now(); raf = requestAnimationFrame(tick); }
232
- if (!userPaused) play();
233
- } else { stop(); if (raf) cancelAnimationFrame(raf); raf = 0; }
202
+ tr.active = on && !reduce;
203
+ if (on) { if (!userPaused) play(); } else stop();
234
204
  }
235
205
  playBtn?.addEventListener('click', () => {
236
- if (playing) userPause();
237
- else { userPaused = false; finishAssemble(); if (cur === N - 1) show(0); play(); }
206
+ if (going()) userPause();
207
+ else { userPaused = false; finishAssemble(); if (cur === N - 1 && !going()) show(0); play(); }
238
208
  });
239
- q('[data-a=next]')?.addEventListener('click', () => { userPause(); finishAssemble(); show(Math.min(N - 1, cur + 1)); });
240
- q('[data-a=prev]')?.addEventListener('click', () => { userPause(); finishAssemble(); show(Math.max(0, cur - 1)); });
209
+ q('[data-a=next]')?.addEventListener('click', () => { userPause(); finishAssemble(); show(Math.min(N - 1, cur + 1), true); });
210
+ q('[data-a=prev]')?.addEventListener('click', () => { userPause(); finishAssemble(); show(Math.max(0, cur - 1), true); });
241
211
  fig.addEventListener('keydown', e => {
242
212
  const k = (e as KeyboardEvent).key;
243
213
  if (!N) return;
244
- if (k === 'ArrowRight') { e.preventDefault(); userPause(); finishAssemble(); show(Math.min(N - 1, cur + 1)); }
245
- if (k === 'ArrowLeft') { e.preventDefault(); userPause(); finishAssemble(); show(Math.max(0, cur - 1)); }
214
+ if (k === 'ArrowRight') { e.preventDefault(); userPause(); finishAssemble(); show(Math.min(N - 1, cur + 1), true); }
215
+ if (k === 'ArrowLeft') { e.preventDefault(); userPause(); finishAssemble(); show(Math.max(0, cur - 1), true); }
246
216
  });
247
217
  svg.querySelectorAll<SVGElement>('.badge').forEach(b => {
248
- const go = () => { userPause(); finishAssemble(); show(Number(b.dataset.go) - 1); };
218
+ const go = () => { userPause(); finishAssemble(); show(Number(b.dataset.go) - 1, true); };
249
219
  b.addEventListener('click', go);
250
220
  b.addEventListener('keydown', e => { const k = (e as KeyboardEvent).key; if (k === 'Enter' || k === ' ') { e.preventDefault(); go(); } });
251
221
  });
252
222
 
253
223
  const forced = wantStep && (!wantScene || wantScene === sd.id) ? Math.min(N, wantStep) - 1 : -1;
254
224
  const frozenAssemble = wantAssemble && assembleAt !== undefined && (!wantScene || wantScene === sd.id);
255
- if (reduce && forced < 0 && !still && !frozenAssemble) {
256
- // reduced motion: the whole diagram, everything lit, the step list open, no assembly
257
- if (N) { svg.classList.add('all'); show(N - 1); }
258
- if (playBtn) { playBtn.disabled = true; playBtn.textContent = 'Motion off'; }
259
- if (asmBtn) asmBtn.disabled = true;
260
- sec.querySelector('details.steps')?.setAttribute('open', '');
261
- } else {
262
- if (N) show(forced >= 0 ? forced : 0);
263
- if (reduce && playBtn) { playBtn.disabled = true; playBtn.textContent = 'Motion off'; }
225
+ if (N) show(forced >= 0 ? forced : 0);
226
+ setBtn();
227
+ /** off: the whole diagram, everything lit, the step list open, no intro; on again: from the first step */
228
+ function setMotion() {
229
+ svg.classList.remove('pre-assemble');
230
+ if (reduce) { assembled = true; finishAssemble(); stop(); }
231
+ svg.classList.toggle('all', reduce && N > 0);
232
+ tr.active = active && !reduce;
233
+ if (asmBtn) asmBtn.disabled = reduce;
234
+ if (reduce) sec.querySelector('details.steps')?.setAttribute('open', '');
235
+ if (N) show(reduce ? N - 1 : 0);
236
+ setBtn();
237
+ if (!reduce && active && !userPaused) play();
238
+ }
239
+ const tools = q<HTMLElement>('.tools');
240
+ if (asked && tools) {
241
+ const b = document.createElement('button');
242
+ b.type = 'button'; b.className = 'pbtn small'; b.dataset.a = 'motion'; b.textContent = 'Motion off'; b.title = 'Draw everything in place, with nothing moving';
243
+ b.setAttribute('aria-pressed', 'false');
244
+ b.addEventListener('click', () => { reduce = !reduce; for (const x of offBtns) x.setAttribute('aria-pressed', String(reduce)); for (const r of runners) r.setMotion(); });
245
+ offBtns.push(b); tools.appendChild(b);
264
246
  }
265
247
  if (frozenAssemble) assemble(Number(assembleAt));
266
248
  else if ((sd.assemble || wantAssemble) && !reduce && !(window as unknown as { __diagramNoIntro?: boolean }).__diagramNoIntro) {
@@ -284,11 +266,11 @@ function init() {
284
266
  addEventListener('scroll', check, { passive: true });
285
267
  setTimeout(check, 60);
286
268
  }
287
- return { fig, setActive };
269
+ return { fig, setActive, setMotion };
288
270
  }
289
271
 
290
272
  // only the most visible scene animates
291
- if (!reduce) {
273
+ if (!still) {
292
274
  const ratio = new Map<Element, number>();
293
275
  const pick = () => {
294
276
  let best: typeof runners[number] | undefined, br = 0;