@liqweed/motion-kit 0.5.0 → 0.6.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.
package/runtime/links.mjs CHANGED
@@ -29,7 +29,7 @@ const STEP_ATTR = "data-mk-step";
29
29
  /** @import { Scene } from "./scene.mjs" */
30
30
  /**
31
31
  * The part of the player controller the helpers use.
32
- * @typedef {{ scene: Scene, time: number, seek: (t: number) => void, seekStep: (ref: number | string) => void, playToStep: (ref: number | string) => void }} StepController
32
+ * @typedef {{ scene: Scene, time: number, onStep?: (listener: (index: number) => void) => (() => void), seek: (t: number) => void, seekStep: (ref: number | string) => void, playToStep: (ref: number | string) => void }} StepController
33
33
  */
34
34
  /**
35
35
  * @typedef {object} ScrollStepsOptions
@@ -177,6 +177,7 @@ export function scrollSteps(controller, sections, options = {}) {
177
177
  };
178
178
 
179
179
  if (typeof IntersectionObserver !== "function") return () => {};
180
+ const unsubscribe = mark ? c.onStep?.((index) => els.forEach((el, i) => markCurrent(el, steps[i] === index))) : undefined;
180
181
  // The root, cut off at the line: a section enters or leaves it exactly
181
182
  // when its top crosses the line, which is when the active one can change.
182
183
  const below = `${(1 - line) * 100}%`;
@@ -202,6 +203,7 @@ export function scrollSteps(controller, sections, options = {}) {
202
203
  if (disposed) return;
203
204
  disposed = true;
204
205
  observer.disconnect();
206
+ unsubscribe?.();
205
207
  scroller.removeEventListener?.("scroll", onScroll);
206
208
  if (mark) for (const el of els) markCurrent(el, false);
207
209
  };
@@ -304,10 +306,12 @@ export function linkSteps(controller, target, options = {}) {
304
306
  bound.push([el, name, fn]);
305
307
  }
306
308
  });
309
+ const unsubscribe = mark ? c.onStep?.((index) => els.forEach((el, i) => markCurrent(el, steps[i] === index))) : undefined;
307
310
  let disposed = false;
308
311
  return () => {
309
312
  if (disposed) return;
310
313
  disposed = true;
314
+ unsubscribe?.();
311
315
  for (const [el, name, fn] of bound) el.removeEventListener(name, fn);
312
316
  if (mark) for (const el of els) markCurrent(el, false);
313
317
  };
@@ -270,6 +270,12 @@ export function mountPlayer(container, scene, options = {}) {
270
270
  for (const node of nodes) if (node) container.appendChild(toDom(doc, node, ui));
271
271
  const { stage, live } = ui;
272
272
 
273
+ /** @type {Set<(index: number) => void>} */
274
+ const stepListeners = new Set();
275
+ let lastStep = -2;
276
+ // Bumped on every published step change, so a dispatch knows a newer one ran even
277
+ // when nested seeks came back to its own step.
278
+ let publication = 0;
273
279
  let t = 0;
274
280
  let playing = false;
275
281
  let raf = 0;
@@ -286,6 +292,11 @@ export function mountPlayer(container, scene, options = {}) {
286
292
  /** @type {IntersectionObserver | undefined} */
287
293
  let visibilityObserver;
288
294
 
295
+ /** @param {unknown} e */
296
+ function reportListenerError(e) {
297
+ if (typeof reportError === "function") reportError(e);
298
+ else queueMicrotask(() => { throw e; });
299
+ }
289
300
  function draw() {
290
301
  // In place: nodes that persist keep their identity, only what changed is written.
291
302
  patchMarkup(stage, renderSvg(scene, t, { style, idPrefix: prefix, live: true }));
@@ -294,10 +305,24 @@ export function mountPlayer(container, scene, options = {}) {
294
305
  ui.captions?.forEach((c, i) => (i === idx ? c.setAttribute("class", "mk-on") : c.removeAttribute("class")));
295
306
  if (ui.scrub) ui.scrub.value = String(t);
296
307
  if (ui.playLabel) ui.playLabel.textContent = playing ? labels.pause : t >= scene.duration ? labels.replay : labels.play;
308
+ if (idx !== lastStep) {
309
+ lastStep = idx;
310
+ const mine = ++publication;
311
+ // One throwing listener must not skip the rest or stop the clock: report it
312
+ // out of band (reportError, else a rethrow on a microtask) and carry on.
313
+ for (const listener of [...stepListeners]) {
314
+ // A listener may destroy the player, or seek: a nested draw has then already
315
+ // told everyone about the newer step, so this stale dispatch ends.
316
+ if (destroyed || publication !== mine) break;
317
+ try { listener(idx); } catch (e) { reportListenerError(e); }
318
+ }
319
+ }
297
320
  }
298
321
  /** @param {number} time */
299
322
  function seek(time) {
300
323
  if (destroyed) return;
324
+ if (!Number.isFinite(time)) throw new RangeError("seek time must be finite");
325
+ autoplayPending = false;
301
326
  playing = false;
302
327
  suspended = false;
303
328
  cancelAnimationFrame(raf);
@@ -439,9 +464,23 @@ export function mountPlayer(container, scene, options = {}) {
439
464
  const themeQuery = typeof matchMedia === "function" && !options.theme ? matchMedia("(prefers-color-scheme: dark)") : null;
440
465
  themeQuery?.addEventListener?.("change", applyTheme);
441
466
 
467
+ /**
468
+ * Subscribe to settled-step changes (including -1 before the first).
469
+ * Calls immediately with the current index, then once per changed index
470
+ * from playback, seeking or controls. Unsubscribe or destroy to release.
471
+ * @param {(index: number) => void} listener
472
+ * @returns {() => void}
473
+ */
474
+ function onStep(listener) {
475
+ if (destroyed) return () => {};
476
+ stepListeners.add(listener);
477
+ listener(stepIndexAt(scene, t));
478
+ return () => { stepListeners.delete(listener); };
479
+ }
442
480
  function destroy() {
443
481
  if (destroyed) return;
444
482
  destroyed = true;
483
+ stepListeners.clear();
445
484
  if (mounted.get(container) === controller) mounted.delete(container);
446
485
  playing = false;
447
486
  cancelAnimationFrame(raf);
@@ -450,7 +489,7 @@ export function mountPlayer(container, scene, options = {}) {
450
489
  themeQuery?.removeEventListener?.("change", applyTheme);
451
490
  if (g.__motionKit[id] === controller) delete g.__motionKit[id];
452
491
  }
453
- const controller = { seek, play, pause, seekStep, playToStep, destroy, get time() { return t; }, scene };
492
+ const controller = { seek, play, pause, seekStep, playToStep, onStep, destroy, get time() { return t; }, scene };
454
493
  const g = /** @type {any} */ (globalThis);
455
494
  g.__motionKit = g.__motionKit ?? {};
456
495
  g.__motionKit[id] = controller;
package/runtime/scene.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ /** @import { Style } from "./style.mjs" */
1
2
  // SPDX-License-Identifier: MIT
2
3
  // Copyright (c) 2026 Ophir Radnitz
3
4
  /**
@@ -9,6 +10,7 @@
9
10
  * id, width, height, // viewBox
10
11
  * duration, // seconds until the final state
11
12
  * title, description, // accessible name + description
13
+ * stepLabelsInFrame?: boolean, // false for narrative steps (default true)
12
14
  * steps: [{ at, label, detail?, id? }], // build steps; last = finished diagram
13
15
  * frame(t, { idPrefix }) → string // inner SVG markup at time t
14
16
  * }
@@ -32,7 +34,7 @@ import { normalizeStyle, cssVars, resolveTokens } from "./style.mjs";
32
34
  */
33
35
  /**
34
36
  * What `renderSvg` passes to `frame` besides the time.
35
- * @typedef {{ idPrefix: string }} FrameContext
37
+ * @typedef {{ idPrefix: string, style?: Style }} FrameContext
36
38
  */
37
39
  /**
38
40
  * An animated diagram as a pure function of time (see the module comment).
@@ -51,14 +53,20 @@ export const FORMATS = {
51
53
  tall: { width: 360, height: 0 }, // phone column: height computed by the scene type
52
54
  };
53
55
 
54
- /** Pick a localized string: plain string, or { en, nl, ... }. */
56
+ /**
57
+ * Resolve copy exactly; plain strings are shared by every locale. Missing
58
+ * translations must never silently publish a different language.
59
+ * @param {string | Record<string, string> | null | undefined} value
60
+ * @param {string} [locale]
61
+ * @returns {string}
62
+ */
55
63
  export function localize(value, locale = "en") {
56
64
  if (value == null) return "";
57
65
  if (typeof value === "string") return value;
58
- if (value[locale] != null) return value[locale];
59
- const first = Object.values(value)[0];
60
- if (first == null) return "";
61
- return first;
66
+ if (typeof value !== "object" || Array.isArray(value) || !Object.hasOwn(value, locale) || typeof value[locale] !== "string" || !value[locale]) {
67
+ throw new Error(`missing translation for locale "${locale}"`);
68
+ }
69
+ return value[locale];
62
70
  }
63
71
 
64
72
  /**
@@ -82,10 +90,15 @@ export function validateScene(scene) {
82
90
  for (const k of ["id", "width", "height", "duration", "title", "description", "steps", "frame"]) {
83
91
  if (scene[k] === undefined || scene[k] === "") throw new Error(`scene ${scene.id ?? "?"} is missing "${k}"`);
84
92
  }
85
- if (!scene.steps.length) throw new Error(`scene ${scene.id}: needs at least one step`);
93
+ for (const key of ["width", "height", "duration"]) {
94
+ if (!Number.isFinite(scene[key]) || scene[key] <= 0) throw new Error(`scene ${scene.id}: ${key} must be a positive finite number`);
95
+ }
96
+ if (typeof scene.frame !== "function") throw new Error(`scene ${scene.id}: frame must be a function`);
97
+ if (!Array.isArray(scene.steps) || !scene.steps.length) throw new Error(`scene ${scene.id}: needs at least one step`);
86
98
  let prev = -Infinity;
87
99
  const ids = new Set();
88
100
  for (const s of scene.steps) {
101
+ if (!Number.isFinite(s.at) || s.at < 0) throw new Error(`scene ${scene.id}: step time must be finite and non-negative`);
89
102
  if (!(s.at > prev)) throw new Error(`scene ${scene.id}: steps must be strictly increasing in time`);
90
103
  if (s.at > scene.duration + 1e-9) throw new Error(`scene ${scene.id}: step "${s.label}" is after the duration`);
91
104
  if (!s.label) throw new Error(`scene ${scene.id}: every step needs a label`);
@@ -158,7 +171,7 @@ export function renderSvg(scene, t, options = {}) {
158
171
  `<title id="${id}-title">${esc(scene.title)}</title>` +
159
172
  `<desc id="${id}-desc">${esc(scene.description)}</desc>` +
160
173
  bg +
161
- scene.frame(time, { idPrefix: id }) +
174
+ scene.frame(time, { idPrefix: id, style }) +
162
175
  `</svg>`;
163
176
  return options.standalone ? resolveTokens(markup, style, options.theme ?? "light") : markup;
164
177
  }
package/runtime/style.mjs CHANGED
@@ -72,6 +72,9 @@ export function normalizeStyle(style) {
72
72
  light: { ...NEUTRAL.light, ...(style.light ?? {}) },
73
73
  dark: { ...NEUTRAL.dark, ...(style.dark ?? style.light ?? {}) },
74
74
  };
75
+ for (const [key, min, max] of [["radius", 0, 24], ["stroke", 1, 4]]) {
76
+ if (!Number.isFinite(out[key]) || out[key] < min || out[key] > max) throw new Error(`style "${out.name}": ${key} must be a number from ${min} to ${max}`);
77
+ }
75
78
  // The font goes into CSS and markup: a family list never needs these characters.
76
79
  if (typeof out.font !== "string" || /[<>{};\\]/.test(out.font)) throw new Error(`style "${out.name}": font must be a CSS font-family list, got ${JSON.stringify(out.font)}`);
77
80
  for (const theme of ["light", "dark"]) {
@@ -1,3 +1,4 @@
1
+ /** @import { Style } from "../style.mjs" */
1
2
  // SPDX-License-Identifier: MIT
2
3
  // Copyright (c) 2026 Ophir Radnitz
3
4
  /**
@@ -19,7 +20,7 @@
19
20
  import { easeOut, easeStandard, progress, window01 } from "../motion.mjs";
20
21
  import { boxNode, FONT_MIN, maxFontSize, rectEdge } from "../parts.mjs";
21
22
  import { FORMATS, localize, withId } from "../scene.mjs";
22
- import { tok } from "../style.mjs";
23
+ import { NEUTRAL, tok } from "../style.mjs";
23
24
  import { drawOn, el, pointOnLine } from "../svg.mjs";
24
25
  import { wrapLabel } from "../wrap.mjs";
25
26
 
@@ -163,25 +164,26 @@ export function hubSpoke(spec, { format = "16:9", locale = "en" } = {}) {
163
164
  }
164
165
  const pathD = (link) => link.pts.map((p, i) => `${i === 0 ? "M" : "L"}${Math.round(p.x * 100) / 100} ${Math.round(p.y * 100) / 100}`).join(" ");
165
166
 
166
- function frame(t) {
167
+ /** @param {number} t @param {{style?: Style}} [ctx] */
168
+ function frame(t, { style = NEUTRAL } = {}) {
167
169
  const out = [];
168
170
  const sEnter = (i) => progress(t, spokeEnter(i), ENTER, easeOut);
169
171
  links.forEach((link, i) => {
170
172
  const shown = sEnter(i);
171
173
  if (shown > 0) {
172
- out.push(el("path", { d: pathD(link), fill: "none", stroke: tok("line"), "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: shown }));
174
+ out.push(el("path", { d: pathD(link), fill: "none", stroke: tok("line"), "stroke-width": style.stroke, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: shown }));
173
175
  }
174
176
  const ls = dirIn ? linkStartIn(i) : linkStart(i);
175
177
  const p = progress(t, ls, LINK, easeStandard);
176
178
  const dash = drawOn(link.len, p);
177
179
  if (dash) {
178
- out.push(el("path", { d: pathD(link), fill: "none", stroke: tok("accent"), "stroke-width": 3, "stroke-linecap": "round", "stroke-linejoin": "round", ...dash }));
180
+ out.push(el("path", { d: pathD(link), fill: "none", stroke: tok("accent"), "stroke-width": style.stroke * 1.5, "stroke-linecap": "round", "stroke-linejoin": "round", ...dash }));
179
181
  }
180
182
  });
181
- out.push(boxNode({ ...L.hub, lines: hubLines, fontSize: fs + 1, enter: progress(t, hubEnter, ENTER, easeOut), active: progress(t, HUB_ON, FILL, easeStandard), weight: 600 }));
183
+ out.push(boxNode({ radius: style.radius, strokeWidth: style.stroke, ...L.hub, lines: hubLines, fontSize: fs + 1, enter: progress(t, hubEnter, ENTER, easeOut), active: progress(t, HUB_ON, FILL, easeStandard), weight: 600 }));
182
184
  spokes.forEach((s, i) => {
183
185
  const fill = dirIn ? fillStartIn(i) : spokeFill(i);
184
- out.push(boxNode({ ...L.spokes[i], lines: s.lines, fontSize: fs, enter: sEnter(i), active: progress(t, fill, FILL, easeStandard) }));
186
+ out.push(boxNode({ radius: style.radius, strokeWidth: style.stroke, ...L.spokes[i], lines: s.lines, fontSize: fs, enter: sEnter(i), active: progress(t, fill, FILL, easeStandard) }));
185
187
  });
186
188
  // Emphasis dot riding the active link; gone by the step's time.
187
189
  links.forEach((link, i) => {
@@ -13,6 +13,7 @@ import { validateScene } from "../scene.mjs";
13
13
  import { hubSpoke } from "./hub-spoke.mjs";
14
14
  import { sequence } from "./sequence.mjs";
15
15
  import { stack } from "./stack.mjs";
16
+ import { walk } from "./walk.mjs";
16
17
  import { timeline } from "./timeline.mjs";
17
18
 
18
19
  export const SCENE_TYPES = {
@@ -20,6 +21,8 @@ export const SCENE_TYPES = {
20
21
  "hub-spoke": hubSpoke,
21
22
  timeline,
22
23
  stack,
24
+ "state-machine": walk,
25
+ "request-journey": walk,
23
26
  };
24
27
 
25
28
  export function createScene(spec, opts = {}) {
@@ -1,3 +1,4 @@
1
+ /** @import { Style } from "../style.mjs" */
1
2
  // SPDX-License-Identifier: MIT
2
3
  // Copyright (c) 2026 Ophir Radnitz
3
4
  /**
@@ -19,7 +20,7 @@
19
20
  import { easeOut, easeStandard, progress } from "../motion.mjs";
20
21
  import { circleNode, FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
21
22
  import { FORMATS, localize, withId } from "../scene.mjs";
22
- import { tok } from "../style.mjs";
23
+ import { NEUTRAL, tok } from "../style.mjs";
23
24
  import { drawOn, el, polyline, trimSegment } from "../svg.mjs";
24
25
  import { wrapLabel } from "../wrap.mjs";
25
26
 
@@ -154,7 +155,8 @@ export function sequence(spec, { format = "16:9", locale = "en" } = {}) {
154
155
  // never crosses a label.
155
156
  const segs = L.centers.slice(1).map((c, i) => connector(L.centers[i], c, L.r, L.W, L.cols > 1, L.cellW));
156
157
 
157
- function frame(t) {
158
+ /** @param {number} t @param {{style?: Style}} [ctx] */
159
+ function frame(t, { style = NEUTRAL } = {}) {
158
160
  const enter = (k) => progress(t, k * ENTER_GAP, ENTER, easeOut);
159
161
  const active = (k) => progress(t, fillStart(k), FILL, easeStandard);
160
162
  const out = [];
@@ -162,13 +164,13 @@ export function sequence(spec, { format = "16:9", locale = "en" } = {}) {
162
164
  segs.forEach((s, k) => {
163
165
  const shown = Math.min(enter(k), enter(k + 1));
164
166
  const common = { d: s.path.d, fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round" };
165
- if (shown > 0) out.push(el("path", { ...common, stroke: tok("line"), "stroke-width": 2, opacity: shown }));
167
+ if (shown > 0) out.push(el("path", { ...common, stroke: tok("line"), "stroke-width": style.stroke, opacity: shown }));
166
168
  const dash = drawOn(s.path.length, progress(t, hopStart(k), HOP, easeStandard));
167
- if (dash) out.push(el("path", { ...common, stroke: tok("accent"), "stroke-width": 3, ...dash }));
169
+ if (dash) out.push(el("path", { ...common, stroke: tok("accent"), "stroke-width": style.stroke * 1.5, ...dash }));
168
170
  });
169
171
  items.forEach((it, k) => {
170
172
  const c = L.centers[k];
171
- out.push(circleNode({ cx: c.x, cy: c.y, r: L.r, enter: enter(k), active: active(k), node: it.node }));
173
+ out.push(circleNode({ strokeWidth: style.stroke, cx: c.x, cy: c.y, r: L.r, enter: enter(k), active: active(k), node: it.node }));
172
174
  out.push(stateLabel({ ...L.label(c), lines: it.lines, fontSize: L.fs, enter: enter(k), active: active(k) }));
173
175
  });
174
176
  // Emphasis ring: appears on node 1, then hops.
@@ -180,7 +182,7 @@ export function sequence(spec, { format = "16:9", locale = "en" } = {}) {
180
182
  if (p <= 0) break;
181
183
  pos = segs[k].ring.at(p);
182
184
  }
183
- out.push(el("circle", { cx: pos.x, cy: pos.y, r: ringR * (0.85 + 0.15 * appear), fill: "none", stroke: tok("emphasis"), "stroke-width": 3, opacity: appear }));
185
+ out.push(el("circle", { cx: pos.x, cy: pos.y, r: ringR * (0.85 + 0.15 * appear), fill: "none", stroke: tok("emphasis"), "stroke-width": style.stroke * 1.5, opacity: appear }));
184
186
  }
185
187
  return out.join("");
186
188
  }
@@ -1,3 +1,4 @@
1
+ /** @import { Style } from "../style.mjs" */
1
2
  // SPDX-License-Identifier: MIT
2
3
  // Copyright (c) 2026 Ophir Radnitz
3
4
  /**
@@ -23,7 +24,7 @@
23
24
  import { easeOut, easeStandard, lerp, progress } from "../motion.mjs";
24
25
  import { FONT_MIN, maxFontSize } from "../parts.mjs";
25
26
  import { FORMATS, localize, withId } from "../scene.mjs";
26
- import { tok } from "../style.mjs";
27
+ import { NEUTRAL, tok } from "../style.mjs";
27
28
  import { drawOn, el, fade, num, text, translate } from "../svg.mjs";
28
29
  import { wrapLabel } from "../wrap.mjs";
29
30
 
@@ -58,12 +59,13 @@ const RISE_BY = 14; // a layer rises this far into place
58
59
  * @param {number} enter
59
60
  * @param {number} active
60
61
  * @param {number} passed
62
+ * @param {Style} style
61
63
  */
62
- function layer(b, lines, fs, enter, active, passed) {
64
+ function layer(b, lines, fs, enter, active, passed, style) {
63
65
  if (enter <= 0) return "";
64
66
  const dy = (1 - enter) * RISE_BY;
65
67
  const label = (fill) => text({ x: b.x + b.w / 2, y: b.y + b.h / 2, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fs, "font-weight": 500, fill }, lines);
66
- const box = (fill, stroke, width) => el("rect", { x: b.x, y: b.y, width: b.w, height: b.h, rx: 10, fill, stroke, "stroke-width": width });
68
+ const box = (fill, stroke, width) => el("rect", { x: b.x, y: b.y, width: b.w, height: b.h, rx: style.radius, fill, stroke, "stroke-width": width * style.stroke / 2 });
67
69
  return fade(
68
70
  enter,
69
71
  { transform: dy > 0.004 ? translate(0, dy) : undefined },
@@ -179,20 +181,21 @@ export function stack(spec, { format = "16:9", locale = "en" } = {}) {
179
181
 
180
182
  const vline = (x, y0, y1, attrs) => el("path", { d: `M${num(x)} ${num(y0)} V${num(y1)}`, fill: "none", "stroke-linecap": "round", ...attrs });
181
183
 
182
- function frame(t) {
184
+ /** @param {number} t @param {{style?: Style}} [ctx] */
185
+ function frame(t, { style = NEUTRAL } = {}) {
183
186
  const out = [];
184
187
  const { railX } = fitted;
185
188
  // Rail: draws on from the entry end while the layers rise; an arrowhead marks the exit.
186
189
  const railLen = Math.abs(exitY - entryY);
187
190
  const railDash = drawOn(railLen, progress(t, 0.2, RAIL, easeStandard));
188
- if (railDash) out.push(vline(railX, entryY, exitY, { stroke: tok("line"), "stroke-width": 2, ...railDash }));
191
+ if (railDash) out.push(vline(railX, entryY, exitY, { stroke: tok("line"), "stroke-width": style.stroke, ...railDash }));
189
192
  const head = progress(t, 0.2 + RAIL - 0.15, 0.2, easeOut);
190
193
  if (head > 0) {
191
194
  const s = direction === "down" ? -1 : 1;
192
- out.push(el("path", { d: `M${num(railX - 6)} ${num(exitY + s * 9)} L${num(railX)} ${num(exitY)} L${num(railX + 6)} ${num(exitY + s * 9)}`, fill: "none", stroke: tok("line"), "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: head }));
195
+ out.push(el("path", { d: `M${num(railX - 6)} ${num(exitY + s * 9)} L${num(railX)} ${num(exitY)} L${num(railX + 6)} ${num(exitY + s * 9)}`, fill: "none", stroke: tok("line"), "stroke-width": style.stroke, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: head }));
193
196
  }
194
197
  const y = packetY(t);
195
- if (Math.abs(y - entryY) > 0.5) out.push(vline(railX, entryY, y, { stroke: tok("accent"), "stroke-width": 3 }));
198
+ if (Math.abs(y - entryY) > 0.5) out.push(vline(railX, entryY, y, { stroke: tok("accent"), "stroke-width": style.stroke * 1.5 }));
196
199
  fitted.boxes.forEach((b, li) => {
197
200
  const enter = progress(t, riseAt(li), RISE, easeOut);
198
201
  const k = visit[li];
@@ -201,9 +204,9 @@ export function stack(spec, { format = "16:9", locale = "en" } = {}) {
201
204
  const passed = k < n - 1 ? progress(t, hopStart(k + 1), FILL, easeStandard) : 0;
202
205
  // Tick from the layer to the rail: pending once the layer is in, accent once reached.
203
206
  const cy = b.y + b.h / 2;
204
- if (enter > 0) out.push(el("path", { d: `M${num(b.x + b.w + 4)} ${num(cy)} H${num(railX - 4)}`, stroke: tok("line"), "stroke-width": 2, "stroke-linecap": "round", opacity: enter * (1 - active) }));
205
- if (active > 0) out.push(el("path", { d: `M${num(b.x + b.w + 4)} ${num(cy)} H${num(railX - 4)}`, stroke: tok("accent"), "stroke-width": 3, "stroke-linecap": "round", opacity: active }));
206
- out.push(layer(b, wrapped[li], fitted.fs, enter, active, passed));
207
+ if (enter > 0) out.push(el("path", { d: `M${num(b.x + b.w + 4)} ${num(cy)} H${num(railX - 4)}`, stroke: tok("line"), "stroke-width": style.stroke, "stroke-linecap": "round", opacity: enter * (1 - active) }));
208
+ if (active > 0) out.push(el("path", { d: `M${num(b.x + b.w + 4)} ${num(cy)} H${num(railX - 4)}`, stroke: tok("accent"), "stroke-width": style.stroke * 1.5, "stroke-linecap": "round", opacity: active }));
209
+ out.push(layer(b, wrapped[li], fitted.fs, enter, active, passed, style));
207
210
  });
208
211
  // The packet: appears at the entry, then rides the rail.
209
212
  const appear = progress(t, START, APPEAR, easeOut);
@@ -1,3 +1,4 @@
1
+ /** @import { Style } from "../style.mjs" */
1
2
  // SPDX-License-Identifier: MIT
2
3
  // Copyright (c) 2026 Ophir Radnitz
3
4
  /**
@@ -25,7 +26,7 @@
25
26
  import { easeOut, easeStandard, lerp, progress, springSettleTime, springStep } from "../motion.mjs";
26
27
  import { FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
27
28
  import { FORMATS, localize, withId } from "../scene.mjs";
28
- import { tok } from "../style.mjs";
29
+ import { NEUTRAL, tok } from "../style.mjs";
29
30
  import { drawOn, el, fade, num, text, translate } from "../svg.mjs";
30
31
  import { wrapLabel } from "../wrap.mjs";
31
32
 
@@ -310,7 +311,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
310
311
  const line = (a, b, attrs) =>
311
312
  el("path", { d: L.dir === "h" ? `M${num(a)} ${num(ax.y0)} H${num(b)}` : `M${num(ax.x0)} ${num(a)} V${num(b)}`, fill: "none", "stroke-linecap": "round", ...attrs });
312
313
 
313
- function milestone(t, it, k) {
314
+ function milestone(t, it, k, style) {
314
315
  const p = L.at(k);
315
316
  const b = beat(k);
316
317
  const drop = progress(t, b + 0.05, DROP, easeOut);
@@ -325,10 +326,10 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
325
326
  const y1 = p.y + s * L.stem;
326
327
  const len = Math.abs(y1 - y0);
327
328
  const dash = drawOn(len, progress(t, b + 0.15, LABEL, easeStandard));
328
- if (dash) out.push(el("path", { d: `M${num(p.x)} ${num(y0)} V${num(y1)}`, stroke: tok("line"), "stroke-width": 1.5, fill: "none", ...dash }));
329
+ if (dash) out.push(el("path", { d: `M${num(p.x)} ${num(y0)} V${num(y1)}`, stroke: tok("line"), "stroke-width": style.stroke * 0.75, fill: "none", ...dash }));
329
330
  }
330
331
  const dy = (1 - drop) * -14;
331
- const dot = (fill, stroke) => el("circle", { cx: p.x, cy: p.y, r: DOT, fill, stroke, "stroke-width": 2 });
332
+ const dot = (fill, stroke) => el("circle", { cx: p.x, cy: p.y, r: DOT, fill, stroke, "stroke-width": style.stroke });
332
333
  out.push(
333
334
  fade(drop, { transform: Math.abs(dy) > 0.004 ? translate(0, dy) : undefined }, fade(1 - active, {}, dot(tok("surface"), tok("line"))), fade(active, {}, dot(tok("accent"), tok("accent")))),
334
335
  );
@@ -353,7 +354,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
353
354
  return out.join("");
354
355
  }
355
356
 
356
- function nowMarker(t) {
357
+ function nowMarker(t, style) {
357
358
  if (!now || !L.nowAt || !L.nowPill) return "";
358
359
  const shown = progress(t, nowStart, NOW_FADE, easeOut);
359
360
  if (shown <= 0) return "";
@@ -364,25 +365,26 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
364
365
  return fade(
365
366
  shown,
366
367
  { transform: Math.abs(dy) > 0.004 ? translate(0, dy) : undefined },
367
- el("rect", { x, y, width: w, height: h, rx: h / 2, fill: tok("bg"), stroke: tok("emphasis"), "stroke-width": 2.5 }),
368
+ el("rect", { x, y, width: w, height: h, rx: h / 2, fill: tok("bg"), stroke: tok("emphasis"), "stroke-width": style.stroke * 1.25 }),
368
369
  text({ x: x + w / 2, y: L.nowAt.y, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fs, "font-weight": 600, fill: tok("ink") }, now.label),
369
370
  );
370
371
  }
371
372
 
372
- function frame(t) {
373
+ /** @param {number} t @param {{style?: Style}} [ctx] */
374
+ function frame(t, { style = NEUTRAL } = {}) {
373
375
  const out = [];
374
376
  // Axis: pending line draws on; an arrowhead at its end shows the direction of time.
375
377
  const axisDash = drawOn(axisLen, progress(t, 0, AXIS, easeStandard));
376
- if (axisDash) out.push(line(start, L.dir === "h" ? ax.x1 : ax.y1, { stroke: tok("line"), "stroke-width": 2, ...axisDash }));
378
+ if (axisDash) out.push(line(start, L.dir === "h" ? ax.x1 : ax.y1, { stroke: tok("line"), "stroke-width": style.stroke, ...axisDash }));
377
379
  const head = progress(t, AXIS - 0.15, 0.2, easeOut);
378
380
  if (head > 0) {
379
381
  const d = L.dir === "h" ? `M${num(ax.x1 - 9)} ${num(ax.y1 - 6)} L${num(ax.x1)} ${num(ax.y1)} L${num(ax.x1 - 9)} ${num(ax.y1 + 6)}` : `M${num(ax.x1 - 6)} ${num(ax.y1 - 9)} L${num(ax.x1)} ${num(ax.y1)} L${num(ax.x1 + 6)} ${num(ax.y1 - 9)}`;
380
- out.push(el("path", { d, fill: "none", stroke: tok("line"), "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: head }));
382
+ out.push(el("path", { d, fill: "none", stroke: tok("line"), "stroke-width": style.stroke, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: head }));
381
383
  }
382
384
  const end = accentEnd(t);
383
- if (end - start > 0.5) out.push(line(start, end, { stroke: tok("accent"), "stroke-width": 3 }));
384
- items.forEach((it, k) => out.push(milestone(t, it, k)));
385
- out.push(nowMarker(t));
385
+ if (end - start > 0.5) out.push(line(start, end, { stroke: tok("accent"), "stroke-width": style.stroke * 1.5 }));
386
+ items.forEach((it, k) => out.push(milestone(t, it, k, style)));
387
+ out.push(nowMarker(t, style));
386
388
  return out.join("");
387
389
  }
388
390
 
@@ -0,0 +1,162 @@
1
+ /** @import { Scene } from "../scene.mjs" */
2
+ /** @import { Style } from "../style.mjs" */
3
+ // SPDX-License-Identifier: MIT
4
+ // Copyright (c) 2026 Ophir Radnitz
5
+ /** Small, explicitly narrated graphs. Layout is computed once, never in frame(). */
6
+ import { easeOut, easeStandard, progress, lerp } from "../motion.mjs";
7
+ import { FONT_MIN, maxFontSize } from "../parts.mjs";
8
+ import { FORMATS, localize } from "../scene.mjs";
9
+ import { NEUTRAL, tok } from "../style.mjs";
10
+ import { el, fade, num, text } from "../svg.mjs";
11
+ import { wrapLabel } from "../wrap.mjs";
12
+
13
+ /**
14
+ * Build the common graph walk used by state-machine and request-journey.
15
+ * Nodes are in reading order; connectors use separate outside lanes. The
16
+ * narrated path is explicit, so branching and cycles never choose randomly.
17
+ * @param {any} spec
18
+ * @param {{format?: string, locale?: string}} [opts]
19
+ * @returns {Scene}
20
+ */
21
+ export function walk(spec, { format = "16:9", locale = "en" } = {}) {
22
+ const journey = spec.type === "request-journey";
23
+ const name = `${spec.type} "${spec.id}"`;
24
+ const nodes = journey ? spec.components : spec.states;
25
+ const edges = journey ? spec.hops : spec.transitions;
26
+ const f = FORMATS[format];
27
+ if (!f) throw new Error(`unknown format "${format}"`);
28
+ const fail = (why) => { throw new Error(`${name}: ${why}`); };
29
+ if (!Array.isArray(nodes) || nodes.length < 2 || nodes.length > 8) fail(`needs 2–8 ${journey ? "components" : "states"}`);
30
+ if (!Array.isArray(edges) || edges.length < 1 || edges.length > 12) fail(`needs 1–12 ${journey ? "hops" : "transitions"}`);
31
+ const nodeIds = new Map();
32
+ const labels = nodes.map((node, i) => {
33
+ if (!node || typeof node.id !== "string" || !node.id || nodeIds.has(node.id)) fail(`node ${i + 1} needs a unique non-empty id`);
34
+ nodeIds.set(node.id, i);
35
+ const label = localize(node.label, locale);
36
+ if (!label) fail(`node ${node.id} needs a label`);
37
+ return label;
38
+ });
39
+ const edgeIds = new Map();
40
+ edges.forEach((edge, i) => {
41
+ if (!edge || typeof edge.id !== "string" || !edge.id || edgeIds.has(edge.id)) fail(`edge ${i + 1} needs a unique non-empty id`);
42
+ if (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)) fail(`edge ${edge.id} has an unknown from/to node`);
43
+ if (!localize(edge.label, locale)) fail(`edge ${edge.id} needs a label`);
44
+ if (edge.async !== undefined && typeof edge.async !== "boolean") fail(`edge ${edge.id}: async must be boolean`);
45
+ edgeIds.set(edge.id, i);
46
+ });
47
+ if (!nodeIds.has(spec.initial)) fail("initial must name a node");
48
+ if (!Array.isArray(spec.path) || spec.path.length < 1 || spec.path.length > 10) fail("path needs 1–10 edge ids");
49
+ let current = spec.initial;
50
+ const visits = [nodeIds.get(current)];
51
+ const route = spec.path.map((id) => {
52
+ const e = edgeIds.get(id);
53
+ if (e === undefined) fail(`path names unknown edge "${id}"`);
54
+ const edge = edges[e];
55
+ if (edge.from !== current) fail(`path edge "${id}" starts at ${edge.from}, expected ${current}`);
56
+ current = edge.to;
57
+ visits.push(nodeIds.get(current));
58
+ return e;
59
+ });
60
+ const regions = journey ? nodes.map((n) => localize(n.region, locale)) : nodes.map(() => "");
61
+ const n = nodes.length;
62
+ const W = f.width;
63
+ const laneGap = 7;
64
+ const rightSpace = 28 + edges.length * laneGap;
65
+ const boxW = Math.min(360, W - 48 - rightSpace);
66
+ let fitted;
67
+ let why = "labels do not fit";
68
+ for (let fs = maxFontSize(spec, f.height ? 22 : 16, name); fs >= FONT_MIN; fs--) {
69
+ try {
70
+ const chars = Math.floor((boxW - 24) / (fs * 0.56));
71
+ const wrapped = labels.map((s) => wrapLabel(s, chars, 2));
72
+ const regionLines = regions.map((s) => s ? wrapLabel(s, chars, 1) : []);
73
+ const boxH = Math.max(...wrapped.map((l) => l.length)) * fs * 1.25 + 18;
74
+ const regionH = regions.some(Boolean) ? fs * 1.5 : 0;
75
+ const pitch = boxH + regionH + 16;
76
+ const needed = pitch * n - 16 + 48;
77
+ if (f.height && needed > f.height) { why = `needs ${Math.ceil(needed)}px height`; continue; }
78
+ const H = f.height || Math.ceil(needed);
79
+ const x = (W - boxW - rightSpace) / 2;
80
+ const top = (H - (pitch * n - 16)) / 2;
81
+ fitted = { fs, wrapped, regionLines, boxH, H, x, ys: nodes.map((_, i) => top + pitch * i + regionH), regionH };
82
+ break;
83
+ } catch (e) { why = e instanceof Error ? e.message : String(e); }
84
+ }
85
+ if (!fitted) throw new Error(`${name}: does not fit ${format} at ≥ ${FONT_MIN}px (${why}); use fewer nodes, shorter labels or a larger format`);
86
+ const L = fitted;
87
+ const right = L.x + boxW;
88
+ const cy = (i) => L.ys[i] + L.boxH / 2;
89
+ // Each edge has its own port and lane. Self-transitions leave and return
90
+ // through separate ports instead of degenerating to a zero-length path.
91
+ const paths = edges.map((edge, i) => {
92
+ const from = nodeIds.get(edge.from);
93
+ const to = nodeIds.get(edge.to);
94
+ const offset = (i - (edges.length - 1) / 2) * Math.min(2, L.boxH / (edges.length + 2));
95
+ const y0 = cy(from) + (from === to ? -L.boxH / 4 : offset);
96
+ const y1 = cy(to) + (from === to ? L.boxH / 4 : offset);
97
+ const lane = right + 20 + (i + 1) * laneGap;
98
+ return [[right, y0], [lane, y0], [lane, y1], [right, y1]];
99
+ });
100
+ const pathD = (pts) => pts.map(([x, y], i) => `${i ? "L" : "M"}${num(x)} ${num(y)}`).join(" ");
101
+ const position = (pts, p) => {
102
+ const lengths = pts.slice(1).map(([x, y], i) => Math.hypot(x - pts[i][0], y - pts[i][1]));
103
+ let distance = p * lengths.reduce((a, b) => a + b, 0);
104
+ for (let i = 0; i < lengths.length; i++) {
105
+ if (distance <= lengths[i] || i === lengths.length - 1) {
106
+ const q = lengths[i] ? distance / lengths[i] : 1;
107
+ return [lerp(pts[i][0], pts[i + 1][0], q), lerp(pts[i][1], pts[i + 1][1], q)];
108
+ }
109
+ distance -= lengths[i];
110
+ }
111
+ return pts[0];
112
+ };
113
+ const firstAt = 0.75;
114
+ const period = 0.8;
115
+ const hopAt = (k) => firstAt + 0.1 + k * period;
116
+ const stepAt = (k) => firstAt + (k + 1) * period;
117
+ const duration = stepAt(route.length - 1) + 0.3;
118
+ /** @param {number} t @param {{style?: Style}} [ctx] */
119
+ function frame(t, { style = NEUTRAL } = {}) {
120
+ const entrance = progress(t, 0, 0.5, easeOut);
121
+ const active = nodes.map(() => 0);
122
+ active[visits[0]] = progress(t, 0.5, 0.2, easeStandard);
123
+ let dot = [right + 7, cy(visits[0])];
124
+ const passed = new Set();
125
+ for (let k = 0; k < route.length; k++) {
126
+ const p = progress(t, hopAt(k), 0.45, easeStandard);
127
+ if (p <= 0) break;
128
+ dot = position([[right + 7, cy(visits[k])], ...paths[route[k]], [right + 7, cy(visits[k + 1])]], p);
129
+ active[visits[k]] *= 1 - progress(t, hopAt(k), 0.2, easeStandard);
130
+ active[visits[k + 1]] = Math.max(active[visits[k + 1]], progress(t, hopAt(k) + 0.45, 0.2, easeStandard));
131
+ if (p === 1) passed.add(route[k]);
132
+ }
133
+ const out = [];
134
+ paths.forEach((pts, i) => {
135
+ const stroke = tok(passed.has(i) ? "accent" : "line");
136
+ const width = style.stroke * (passed.has(i) ? 1.5 : 1);
137
+ out.push(el("path", { d: pathD(pts), fill: "none", stroke, "stroke-width": width, "stroke-dasharray": edges[i].async ? "5 4" : undefined, "stroke-linejoin": "round" }));
138
+ const [x, y] = pts[3];
139
+ out.push(el("path", { d: `M${num(x + 6)} ${num(y - 4)} L${num(x)} ${num(y)} L${num(x + 6)} ${num(y + 4)}`, fill: "none", stroke, "stroke-width": width }));
140
+ });
141
+ nodes.forEach((node, i) => {
142
+ if (regions[i]) {
143
+ out.push(el("rect", { x: L.x - 8, y: L.ys[i] - L.regionH, width: boxW + 16, height: L.boxH + L.regionH + 6, rx: 6, fill: "none", stroke: tok("line"), "stroke-dasharray": "4 4" }));
144
+ out.push(text({ x: L.x + 8, y: L.ys[i] - L.regionH / 2, "dominant-baseline": "central", "font-size": L.fs, fill: tok("muted") }, L.regionLines[i]));
145
+ }
146
+ const box = (fill, stroke) => el("rect", { x: L.x, y: L.ys[i], width: boxW, height: L.boxH, rx: style.radius, fill, stroke, "stroke-width": style.stroke });
147
+ const label = (fill) => text({ x: L.x + boxW / 2, y: cy(i), "text-anchor": "middle", "dominant-baseline": "central", "font-size": L.fs, fill }, L.wrapped[i]);
148
+ out.push(fade(1 - active[i], {}, box(tok("surface"), tok("line")), label(tok("ink"))));
149
+ out.push(fade(active[i], {}, box(tok("accent"), tok("accent")), label(tok("onAccent"))));
150
+ });
151
+ out.push(el("circle", { cx: dot[0], cy: dot[1], r: 6, fill: tok("emphasis") }));
152
+ return fade(entrance, {}, ...out);
153
+ }
154
+ return {
155
+ id: `${spec.id}-${format.replace(":", "x")}`, type: spec.type, format, locale,
156
+ width: W, height: L.H, duration, title: localize(spec.title, locale), description: localize(spec.description, locale),
157
+ stepLabelsInFrame: false,
158
+ steps: [{ id: "initial", at: firstAt, label: labels[visits[0]], detail: localize(nodes[visits[0]].detail, locale) },
159
+ ...route.map((e, k) => ({ id: `visit-${k + 1}`, at: stepAt(k), label: localize(edges[e].label, locale), detail: localize(edges[e].detail, locale) || `${labels[visits[k]]} → ${labels[visits[k + 1]]}` }))],
160
+ frame,
161
+ };
162
+ }
@@ -67,7 +67,7 @@ from the system's package manager (`brew install ffmpeg`, `apt install ffmpeg`).
67
67
  ## Hard rules
68
68
 
69
69
  - Plays once and holds the final frame (loops only for ambient status displays).
70
- - One entrance ≤ 600 ms, siblings staggered 80–150 ms, whole scene ≤ ~8 s.
70
+ - Motion guidance (reviewed, not mechanically timed): one entrance ≤ 600 ms, siblings staggered 80–150 ms, aim for a whole scene ≤ 8 s. The gate’s hard duration limit is 12 s.
71
71
  - No bounce/elastic, no parallax, no ambient motion inside an explainer.
72
72
  - Every motion must answer "what does this help the viewer understand?".
73
73
  - Skeleton first, then fill: show the whole structure, then walk through it.