@liqweed/motion-kit 0.4.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.
Files changed (45) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +26 -6
  4. package/adapters/element/README.md +5 -0
  5. package/adapters/page/README.md +10 -0
  6. package/cli/motion-kit.mjs +14 -4
  7. package/docs/spec/technique.md +129 -51
  8. package/examples/checkout.json +104 -0
  9. package/examples/connection.json +80 -0
  10. package/examples/custom-pulse.scene.mjs +5 -0
  11. package/examples/incident.json +18 -0
  12. package/examples/player-states.json +97 -0
  13. package/examples/web-stack.json +17 -0
  14. package/lib/build.mjs +1 -1
  15. package/lib/check.mjs +215 -21
  16. package/lib/export.mjs +116 -7
  17. package/lib/gate.mjs +9 -7
  18. package/lib/load.mjs +15 -0
  19. package/package.json +6 -3
  20. package/runtime/kit.mjs +2 -2
  21. package/runtime/links.mjs +318 -0
  22. package/runtime/parts.mjs +15 -0
  23. package/runtime/patch.mjs +297 -0
  24. package/runtime/player.mjs +45 -2
  25. package/runtime/scene.mjs +24 -9
  26. package/runtime/style.mjs +65 -16
  27. package/runtime/types/hub-spoke.mjs +10 -8
  28. package/runtime/types/index.mjs +7 -0
  29. package/runtime/types/sequence.mjs +10 -8
  30. package/runtime/types/stack.mjs +230 -0
  31. package/runtime/types/timeline.mjs +407 -0
  32. package/runtime/types/walk.mjs +162 -0
  33. package/skills/animated-diagram/SKILL.md +28 -7
  34. package/skills/animated-diagram/references/custom-scenes.md +20 -1
  35. package/skills/animated-diagram/references/interactivity.md +129 -6
  36. package/skills/animated-diagram/references/motion-vocabulary.md +1 -1
  37. package/skills/animated-diagram/references/qc.md +3 -0
  38. package/skills/animated-diagram/references/scene-types.md +100 -4
  39. package/skills/animated-diagram/references/styles.md +55 -6
  40. package/skills/animated-diagram/references/technique.md +15 -6
  41. package/skills/motion-render/SKILL.md +31 -6
  42. package/skills/motion-render/references/formats.md +8 -8
  43. package/skills/motion-render/references/video.md +1 -1
  44. package/skills/project-logo/SKILL.md +15 -4
  45. package/styles/neutral.json +2 -2
@@ -0,0 +1,297 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · update rendered SVG in place (browser; the parser runs anywhere).
5
+ *
6
+ * patchMarkup(parent, markup) → true when updated in place, false when it fell back to innerHTML
7
+ *
8
+ * The live player draws each frame by handing the frame's markup to
9
+ * patchMarkup instead of assigning innerHTML. Nodes that persist between
10
+ * frames are kept; only changed attributes and text are written; nodes are
11
+ * added or removed only where the markup's structure changes. The browser
12
+ * then restyles and lays out what changed, and hover and other node state
13
+ * survive.
14
+ *
15
+ * Children are matched by position: a child whose tag differs from the one
16
+ * drawn before is replaced with its subtree, and a child whose markup is
17
+ * byte-identical to the one drawn before is not visited at all.
18
+ *
19
+ * The parser takes the markup scenes emit (one or more `<svg>` elements;
20
+ * double-quoted attributes; text with the entities `esc()` writes and numeric
21
+ * ones) and builds the nodes the HTML parser would build from the same string:
22
+ * names lowercased then SVG-cased, `xlink:`/`xml:`/`xmlns` attributes in their
23
+ * namespaces. Anything else (comments, CDATA, single-quoted or bare
24
+ * attributes, named entities beyond the XML five, elements inside `<title>`,
25
+ * `<desc>` or `<foreignObject>`, HTML elements that leave SVG) is left to the
26
+ * HTML parser: patchMarkup then assigns innerHTML for that call.
27
+ *
28
+ * The patch owns the parent's content: change it only through patchMarkup. If
29
+ * the parent's children were replaced by other code, the next call rebuilds.
30
+ */
31
+
32
+ const SVG_NS = "http://www.w3.org/2000/svg";
33
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
34
+ const XML_NS = "http://www.w3.org/XML/1998/namespace";
35
+ const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
36
+
37
+ /** @param {string} names @returns {Map<string, string>} lowercased → SVG-cased */
38
+ const caseMap = (names) => new Map(names.split(" ").map((n) => [n.toLowerCase(), n]));
39
+
40
+ // The HTML parser's "adjust SVG tag names" and "adjust SVG attributes" tables.
41
+ const SVG_TAGS = caseMap(
42
+ "altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer " +
43
+ "feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR " +
44
+ "feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence " +
45
+ "foreignObject glyphRef linearGradient radialGradient textPath",
46
+ );
47
+ const SVG_ATTRS = caseMap(
48
+ "attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits diffuseConstant edgeMode filterUnits glyphRef " +
49
+ "gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle " +
50
+ "markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform " +
51
+ "patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur " +
52
+ "requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles " +
53
+ "surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan",
54
+ );
55
+ /** The HTML parser's "adjust foreign attributes": name → [namespace, local name]. @type {Map<string, [string, string]>} */
56
+ const FOREIGN_ATTRS = new Map([
57
+ ...["actuate", "arcrole", "href", "role", "show", "title", "type"].map((n) => /** @type {[string, [string, string]]} */ ([`xlink:${n}`, [XLINK_NS, n]])),
58
+ ["xml:lang", [XML_NS, "lang"]],
59
+ ["xml:space", [XML_NS, "space"]],
60
+ ["xmlns", [XMLNS_NS, "xmlns"]],
61
+ ["xmlns:xlink", [XMLNS_NS, "xlink"]],
62
+ ]);
63
+ // Start tags that take the HTML parser out of SVG, and the SVG elements whose
64
+ // child elements it parses as HTML.
65
+ const LEAVES_SVG = new Set(
66
+ "b big blockquote body br center code dd div dl dt em embed font h1 h2 h3 h4 h5 h6 head hr i img li listing math menu meta nobr ol p pre ruby s small span strike strong sub sup table tt u ul var".split(" "),
67
+ );
68
+ const HTML_INSIDE = new Set(["title", "desc", "foreignObject"]);
69
+
70
+ // Whitespace is the HTML parser's: tab, line feed, form feed, space.
71
+ const TAG = /<(\/?)([A-Za-z][^\t\n\f />]*)((?:[\t\n\f ]+[^\t\n\f "'<>/=]+="[^"]*")*)[\t\n\f ]*(\/?)>/y;
72
+ const ATTR = /([^\t\n\f "'<>/=]+)="([^"]*)"/g;
73
+ const ENTITY = /&(?:#(\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|(amp|lt|gt|quot|apos));|&/g;
74
+ const NAMED = /** @type {Record<string, string>} */ ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" });
75
+
76
+ /**
77
+ * One parsed node. Elements have a tag, attributes as a flat
78
+ * `[name, value, …]` list and children; text nodes have the tag `#text` and
79
+ * their decoded `text`. `src` is the node's own markup; `dom` the live node
80
+ * once drawn.
81
+ * @typedef {{ tag: string, attrs: string[], kids: MarkupNode[], src: string, text: string, dom: Node | null }} MarkupNode
82
+ */
83
+
84
+ // Shared empty lists: a node's attributes when it has none, and a text node's
85
+ // children (never patched).
86
+ /** @type {string[]} */
87
+ const NO_ATTRS = [];
88
+ /** @type {MarkupNode[]} */
89
+ const NO_KIDS = [];
90
+
91
+ /** Decode entities as the HTML parser does; null for an `&` it might read differently. @param {string} s */
92
+ function decode(s) {
93
+ if (!s.includes("&")) return s;
94
+ let ok = true;
95
+ const out = s.replace(ENTITY, (m, dec, hex, name) => {
96
+ if (name) return NAMED[name];
97
+ const cp = dec ? Number(dec) : hex ? parseInt(hex, 16) : -1;
98
+ // Code points the HTML parser remaps or rejects are left to it.
99
+ if (cp < 0x20 ? cp !== 9 && cp !== 10 : (cp >= 0x7f && cp <= 0x9f) || (cp >= 0xd800 && cp <= 0xdfff) || cp > 0x10ffff) ok = false;
100
+ return ok ? String.fromCodePoint(cp) : m;
101
+ });
102
+ return ok ? out : null;
103
+ }
104
+
105
+ /** @param {string} s */
106
+ function parseAttrs(s) {
107
+ /** @type {string[]} */
108
+ const attrs = [];
109
+ for (const m of s.matchAll(ATTR)) {
110
+ const lower = m[1].toLowerCase();
111
+ const name = SVG_ATTRS.get(lower) ?? lower;
112
+ const value = decode(m[2]);
113
+ if (value === null) return null;
114
+ // The HTML parser keeps the first of a repeated attribute.
115
+ if (find(attrs, name) < 0) attrs.push(name, value);
116
+ }
117
+ return attrs;
118
+ }
119
+
120
+ /**
121
+ * Parse markup into nodes, or return null when it is outside the subset this
122
+ * module reproduces exactly (see the module comment). Exported for tests.
123
+ * @param {string} markup
124
+ * @returns {MarkupNode[] | null}
125
+ */
126
+ export function parseMarkup(markup) {
127
+ if (/[\r\0]/.test(markup)) return null;
128
+ /** @type {MarkupNode[]} */
129
+ const root = [];
130
+ /** @type {MarkupNode[]} */
131
+ const open = [];
132
+ /** @type {number[]} */
133
+ const starts = [];
134
+ let kids = root;
135
+ let pos = 0;
136
+ while (pos < markup.length) {
137
+ if (markup.charCodeAt(pos) !== 60 /* < */) {
138
+ let end = markup.indexOf("<", pos);
139
+ if (end < 0) end = markup.length;
140
+ const src = markup.slice(pos, end);
141
+ const text = decode(src);
142
+ if (text === null) return null;
143
+ kids.push({ tag: "#text", attrs: NO_ATTRS, kids: NO_KIDS, src, text, dom: null });
144
+ pos = end;
145
+ continue;
146
+ }
147
+ TAG.lastIndex = pos;
148
+ const m = TAG.exec(markup);
149
+ if (!m) return null;
150
+ const lower = m[2].toLowerCase();
151
+ const tag = SVG_TAGS.get(lower) ?? lower;
152
+ if (m[1]) {
153
+ if (m[3] || m[4]) return null;
154
+ const el = open.pop();
155
+ if (!el || el.tag !== tag) return null;
156
+ el.src = markup.slice(/** @type {number} */ (starts.pop()), TAG.lastIndex);
157
+ kids = open.length ? open[open.length - 1].kids : root;
158
+ } else {
159
+ const parent = open[open.length - 1];
160
+ if (parent ? HTML_INSIDE.has(parent.tag) || LEAVES_SVG.has(tag) : tag !== "svg") return null;
161
+ const attrs = m[3] ? parseAttrs(m[3]) : NO_ATTRS;
162
+ if (!attrs) return null;
163
+ /** @type {MarkupNode} */
164
+ const el = { tag, attrs, kids: [], src: m[0], text: "", dom: null };
165
+ kids.push(el);
166
+ if (!m[4]) {
167
+ open.push(el);
168
+ starts.push(pos);
169
+ kids = el.kids;
170
+ }
171
+ }
172
+ pos = TAG.lastIndex;
173
+ }
174
+ return open.length ? null : root;
175
+ }
176
+
177
+ /** @param {Element} el @param {string} name @param {string} value */
178
+ function setAttr(el, name, value) {
179
+ const f = FOREIGN_ATTRS.get(name);
180
+ if (f) el.setAttributeNS(f[0], name, value);
181
+ else el.setAttribute(name, value);
182
+ }
183
+
184
+ /** @param {Element} el @param {string} name */
185
+ function removeAttr(el, name) {
186
+ const f = FOREIGN_ATTRS.get(name);
187
+ if (f) el.removeAttributeNS(f[0], f[1]);
188
+ else el.removeAttribute(name);
189
+ }
190
+
191
+ /** Write the attributes that changed. @param {Element} el @param {string[]} from @param {string[]} to */
192
+ function patchAttrs(el, from, to) {
193
+ let same = from.length === to.length;
194
+ for (let i = 0; same && i < to.length; i += 2) same = from[i] === to[i];
195
+ if (same) {
196
+ // Same names in the same order: the usual case for an animated element.
197
+ for (let i = 1; i < to.length; i += 2) if (from[i] !== to[i]) setAttr(el, to[i - 1], to[i]);
198
+ return;
199
+ }
200
+ for (let i = 0; i < from.length; i += 2) if (find(to, from[i]) < 0) removeAttr(el, from[i]);
201
+ for (let i = 0; i < to.length; i += 2) {
202
+ const j = find(from, to[i]);
203
+ if (j < 0 || from[j + 1] !== to[i + 1]) setAttr(el, to[i], to[i + 1]);
204
+ }
205
+ }
206
+
207
+ /** Index of an attribute's name in a flat `[name, value, …]` list, or -1. @param {string[]} attrs @param {string} name */
208
+ function find(attrs, name) {
209
+ for (let i = 0; i < attrs.length; i += 2) if (attrs[i] === name) return i;
210
+ return -1;
211
+ }
212
+
213
+ /** Build a node's subtree, detached. @param {Document} doc @param {MarkupNode} node @returns {Node} */
214
+ function create(doc, node) {
215
+ if (node.tag === "#text") return (node.dom = doc.createTextNode(node.text));
216
+ const el = doc.createElementNS(SVG_NS, node.tag);
217
+ for (let i = 0; i < node.attrs.length; i += 2) setAttr(el, node.attrs[i], node.attrs[i + 1]);
218
+ for (const kid of node.kids) el.appendChild(create(doc, kid));
219
+ return (node.dom = el);
220
+ }
221
+
222
+ /**
223
+ * Make `parent`'s children, drawn from `from`, match `to`. Children of `to`
224
+ * whose markup did not change are replaced by their `from` node, which keeps
225
+ * its live node and its children.
226
+ * @param {Document} doc @param {Node} parent @param {MarkupNode[]} from @param {MarkupNode[]} to
227
+ */
228
+ function patchKids(doc, parent, from, to) {
229
+ for (let i = 0; i < to.length; i++) {
230
+ const next = to[i];
231
+ const prev = from[i];
232
+ if (!prev) {
233
+ parent.appendChild(create(doc, next));
234
+ } else if (prev.src === next.src) {
235
+ to[i] = prev;
236
+ } else if (prev.tag !== next.tag) {
237
+ parent.replaceChild(create(doc, next), /** @type {Node} */ (prev.dom));
238
+ } else if (next.tag === "#text") {
239
+ next.dom = prev.dom;
240
+ if (prev.text !== next.text) /** @type {Text} */ (next.dom).data = next.text;
241
+ } else {
242
+ const el = /** @type {Element} */ (prev.dom);
243
+ next.dom = el;
244
+ patchAttrs(el, prev.attrs, next.attrs);
245
+ patchKids(doc, el, prev.kids, next.kids);
246
+ }
247
+ }
248
+ for (let i = from.length - 1; i >= to.length; i--) parent.removeChild(/** @type {Node} */ (from[i].dom));
249
+ }
250
+
251
+ /** What each parent shows: its nodes and the markup they came from. @type {WeakMap<Node, { kids: MarkupNode[], markup: string }>} */
252
+ const drawn = new WeakMap();
253
+
254
+ /** Whether the parent still holds exactly the nodes drawn last time. @param {Node} parent @param {MarkupNode[]} kids */
255
+ function intact(parent, kids) {
256
+ const nodes = parent.childNodes;
257
+ if (nodes.length !== kids.length) return false;
258
+ for (let i = 0; i < kids.length; i++) if (nodes[i] !== kids[i].dom) return false;
259
+ return true;
260
+ }
261
+
262
+ /**
263
+ * Show `markup` in `parent`, updating the nodes already there instead of
264
+ * replacing them. The result is the DOM `parent.innerHTML = markup` would
265
+ * build. Falls back to that assignment when the markup is outside the subset
266
+ * described in the module comment.
267
+ * @param {Element} parent an HTML element whose content only patchMarkup changes
268
+ * @param {string} markup one frame's SVG markup (renderSvg output)
269
+ * @returns {boolean} true when the DOM was updated in place, false when innerHTML was assigned
270
+ */
271
+ export function patchMarkup(parent, markup) {
272
+ const last = drawn.get(parent);
273
+ const kept = last !== undefined && intact(parent, last.kids);
274
+ if (kept && last.markup === markup) return true;
275
+ const kids = parseMarkup(markup);
276
+ if (kids) {
277
+ const doc = /** @type {Document} */ (parent.ownerDocument);
278
+ try {
279
+ if (kept) patchKids(doc, parent, last.kids, kids);
280
+ else {
281
+ parent.textContent = "";
282
+ for (const kid of kids) parent.appendChild(create(doc, kid));
283
+ }
284
+ drawn.set(parent, { kids, markup });
285
+ return true;
286
+ } catch (e) {
287
+ // A name the DOM refuses (createElementNS, setAttribute) but the HTML
288
+ // parser accepts: let it decide. Anything else is a bug; surface it.
289
+ // A DOMException, possibly from another realm (an iframe's document).
290
+ const name = typeof e === "object" && e !== null && "name" in e ? e.name : "";
291
+ if (name !== "InvalidCharacterError" && name !== "NamespaceError") throw e;
292
+ }
293
+ }
294
+ drawn.delete(parent);
295
+ parent.innerHTML = markup;
296
+ return false;
297
+ }
@@ -24,9 +24,12 @@
24
24
  * - Keyboard on the stage (a named group, described by a hint): ←/→ previous/next
25
25
  * step, Space play/pause, Home/End.
26
26
  * - Capture hook: controller.seek(t), and window.__motionKit[id] for renderers.
27
+ * - Each frame updates the stage's SVG in place (runtime/patch.mjs): nodes that
28
+ * persist between frames are kept, only changed attributes and text are written.
27
29
  *
28
30
  * The player owns the clock (requestAnimationFrame); scenes stay pure.
29
31
  */
32
+ import { patchMarkup } from "./patch.mjs";
30
33
  import { renderSvg, safeId, stepIndex, stepIndexAt } from "./scene.mjs";
31
34
  import { cssVars, normalizeStyle, TOKENS } from "./style.mjs";
32
35
  import { esc } from "./svg.mjs";
@@ -267,6 +270,12 @@ export function mountPlayer(container, scene, options = {}) {
267
270
  for (const node of nodes) if (node) container.appendChild(toDom(doc, node, ui));
268
271
  const { stage, live } = ui;
269
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;
270
279
  let t = 0;
271
280
  let playing = false;
272
281
  let raf = 0;
@@ -283,17 +292,37 @@ export function mountPlayer(container, scene, options = {}) {
283
292
  /** @type {IntersectionObserver | undefined} */
284
293
  let visibilityObserver;
285
294
 
295
+ /** @param {unknown} e */
296
+ function reportListenerError(e) {
297
+ if (typeof reportError === "function") reportError(e);
298
+ else queueMicrotask(() => { throw e; });
299
+ }
286
300
  function draw() {
287
- stage.innerHTML = renderSvg(scene, t, { style, idPrefix: prefix, live: true });
301
+ // In place: nodes that persist keep their identity, only what changed is written.
302
+ patchMarkup(stage, renderSvg(scene, t, { style, idPrefix: prefix, live: true }));
288
303
  const idx = stepIndexAt(scene, t);
289
304
  ui.steps.forEach((b, i) => (i === idx ? b.setAttribute("aria-current", "step") : b.removeAttribute("aria-current")));
290
305
  ui.captions?.forEach((c, i) => (i === idx ? c.setAttribute("class", "mk-on") : c.removeAttribute("class")));
291
306
  if (ui.scrub) ui.scrub.value = String(t);
292
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
+ }
293
320
  }
294
321
  /** @param {number} time */
295
322
  function seek(time) {
296
323
  if (destroyed) return;
324
+ if (!Number.isFinite(time)) throw new RangeError("seek time must be finite");
325
+ autoplayPending = false;
297
326
  playing = false;
298
327
  suspended = false;
299
328
  cancelAnimationFrame(raf);
@@ -435,9 +464,23 @@ export function mountPlayer(container, scene, options = {}) {
435
464
  const themeQuery = typeof matchMedia === "function" && !options.theme ? matchMedia("(prefers-color-scheme: dark)") : null;
436
465
  themeQuery?.addEventListener?.("change", applyTheme);
437
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
+ }
438
480
  function destroy() {
439
481
  if (destroyed) return;
440
482
  destroyed = true;
483
+ stepListeners.clear();
441
484
  if (mounted.get(container) === controller) mounted.delete(container);
442
485
  playing = false;
443
486
  cancelAnimationFrame(raf);
@@ -446,7 +489,7 @@ export function mountPlayer(container, scene, options = {}) {
446
489
  themeQuery?.removeEventListener?.("change", applyTheme);
447
490
  if (g.__motionKit[id] === controller) delete g.__motionKit[id];
448
491
  }
449
- 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 };
450
493
  const g = /** @type {any} */ (globalThis);
451
494
  g.__motionKit = g.__motionKit ?? {};
452
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,11 +34,13 @@ 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).
39
- * @typedef {{ id: string, width: number, height: number, duration: number, title: string, description: string, steps: Step[], frame: (t: number, ctx: FrameContext) => string, stepLabelsInFrame?: boolean, type?: string, format?: string, locale?: string }} Scene
41
+ * `contrastPairs`: token pairs the scene draws beyond CONTRAST_PAIRS
42
+ * (runtime/style.mjs), which the gate checks the style against.
43
+ * @typedef {{ id: string, width: number, height: number, duration: number, title: string, description: string, steps: Step[], frame: (t: number, ctx: FrameContext) => string, stepLabelsInFrame?: boolean, contrastPairs?: { fg: string, bg: string, min: number, use?: string }[], type?: string, format?: string, locale?: string }} Scene
40
44
  */
41
45
 
42
46
  /** Formats: name → viewBox. Layouts are computed per format, never cropped. */
@@ -49,14 +53,20 @@ export const FORMATS = {
49
53
  tall: { width: 360, height: 0 }, // phone column: height computed by the scene type
50
54
  };
51
55
 
52
- /** 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
+ */
53
63
  export function localize(value, locale = "en") {
54
64
  if (value == null) return "";
55
65
  if (typeof value === "string") return value;
56
- if (value[locale] != null) return value[locale];
57
- const first = Object.values(value)[0];
58
- if (first == null) return "";
59
- 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];
60
70
  }
61
71
 
62
72
  /**
@@ -80,10 +90,15 @@ export function validateScene(scene) {
80
90
  for (const k of ["id", "width", "height", "duration", "title", "description", "steps", "frame"]) {
81
91
  if (scene[k] === undefined || scene[k] === "") throw new Error(`scene ${scene.id ?? "?"} is missing "${k}"`);
82
92
  }
83
- 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`);
84
98
  let prev = -Infinity;
85
99
  const ids = new Set();
86
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`);
87
102
  if (!(s.at > prev)) throw new Error(`scene ${scene.id}: steps must be strictly increasing in time`);
88
103
  if (s.at > scene.duration + 1e-9) throw new Error(`scene ${scene.id}: step "${s.label}" is after the duration`);
89
104
  if (!s.label) throw new Error(`scene ${scene.id}: every step needs a label`);
@@ -156,7 +171,7 @@ export function renderSvg(scene, t, options = {}) {
156
171
  `<title id="${id}-title">${esc(scene.title)}</title>` +
157
172
  `<desc id="${id}-desc">${esc(scene.description)}</desc>` +
158
173
  bg +
159
- scene.frame(time, { idPrefix: id }) +
174
+ scene.frame(time, { idPrefix: id, style }) +
160
175
  `</svg>`;
161
176
  return options.standalone ? resolveTokens(markup, style, options.theme ?? "light") : markup;
162
177
  }
package/runtime/style.mjs CHANGED
@@ -40,7 +40,7 @@ export const NEUTRAL = Object.freeze({
40
40
  ink: "#111827",
41
41
  muted: "#4b5563",
42
42
  line: "#8b929c",
43
- accent: "#2563eb",
43
+ accent: "#1d36a8",
44
44
  onAccent: "#ffffff",
45
45
  emphasis: "#d97706",
46
46
  }),
@@ -52,7 +52,7 @@ export const NEUTRAL = Object.freeze({
52
52
  line: "#6b7280",
53
53
  accent: "#2563eb",
54
54
  onAccent: "#ffffff",
55
- emphasis: "#f59e0b",
55
+ emphasis: "#fbbf24",
56
56
  }),
57
57
  });
58
58
 
@@ -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"]) {
@@ -117,25 +120,71 @@ export function contrast(a, b) {
117
120
  }
118
121
 
119
122
  /**
120
- * WCAG checks a style must pass: text ≥ 4.5:1, strokes and shapes ≥ 3:1.
123
+ * Two tokens drawn one against the other, and the contrast the pair needs in
124
+ * both themes: 4.5 for text (WCAG 1.4.3), 3 for shapes and strokes (WCAG
125
+ * 1.4.11). `use` says where it is drawn.
126
+ * @typedef {{ fg: string, bg: string, min: number, use?: string }} ContrastPair
127
+ */
128
+ /**
129
+ * A token pair the check leaves out on purpose, and why.
130
+ * @typedef {{ fg: string, bg: string, why: string }} ContrastExemption
131
+ */
132
+
133
+ /**
134
+ * Every token pair the scene types and shared parts draw where the pair
135
+ * carries meaning in a step frame (runtime/types/*, runtime/parts.mjs). A
136
+ * scene that draws other pairs declares them in `scene.contrastPairs`; the
137
+ * gate checks those too (lib/check.mjs).
138
+ * @type {readonly ContrastPair[]}
139
+ */
140
+ export const CONTRAST_PAIRS = Object.freeze([
141
+ { fg: "ink", bg: "bg", min: 4.5, use: "labels of reached nodes, on the canvas (stateLabel)" },
142
+ { fg: "ink", bg: "surface", min: 4.5, use: "labels inside pending boxes (boxNode)" },
143
+ { fg: "muted", bg: "bg", min: 4.5, use: "labels of pending nodes, on the canvas (stateLabel)" },
144
+ { fg: "muted", bg: "surface", min: 4.5, use: "glyphs and icons inside pending circles (circleNode)" },
145
+ { fg: "onAccent", bg: "accent", min: 4.5, use: "labels, glyphs and icons inside reached nodes (boxNode, circleNode)" },
146
+ { fg: "line", bg: "bg", min: 3, use: "connectors and the outlines of pending nodes" },
147
+ { fg: "accent", bg: "bg", min: 3, use: "reached nodes and drawn connectors" },
148
+ { fg: "emphasis", bg: "bg", min: 3, use: "the emphasis ring (sequence) and dot (hub-spoke) on the canvas" },
149
+ {
150
+ fg: "emphasis",
151
+ bg: "accent",
152
+ min: 3,
153
+ use: "the emphasis ring around the reached node it marks (sequence): 3.5 units apart, so adjacent at phone size. It tells the current node from the reached ones without relying on hue",
154
+ },
155
+ ]);
156
+
157
+ /**
158
+ * Pairs that are drawn (by the scene types, only in motion; or by the
159
+ * motion-kit logo) but that CONTRAST_PAIRS leaves out, and why.
160
+ * @type {readonly ContrastExemption[]}
161
+ */
162
+ export const CONTRAST_EXEMPT = Object.freeze([
163
+ { fg: "line", bg: "surface", why: "a pending node's outline is its edge: it is told from the canvas outside it (line on bg), not from the node's own fill (WCAG 1.4.11)" },
164
+ { fg: "accent", bg: "surface", why: "the reached layer covers the pending one only while a node fills; never side by side in a step frame. A scene that draws accent on surface (a bar on a track) declares the pair" },
165
+ { fg: "emphasis", bg: "surface", why: "the sequence ring crosses pending nodes only mid-hop: in motion, never in a step frame" },
166
+ { fg: "accent", bg: "line", why: "a connector's accent draw-on covers its pending line; they meet only at the moving tip, mid-draw" },
167
+ { fg: "onAccent", bg: "emphasis", why: "no scene type draws it; the motion-kit logo's end keyframe does, and logos are exempt from WCAG 1.4.11" },
168
+ ]);
169
+
170
+ /**
171
+ * WCAG contrast checks a style must pass, in both themes.
172
+ * @param {any} style style data or "neutral"; normalizeStyle fills the rest
173
+ * @param {readonly ContrastPair[]} [pairs] default CONTRAST_PAIRS; a scene's
174
+ * own pairs (`scene.contrastPairs`) are checked with the same function
121
175
  * @returns {string[]} problems (empty = ok)
122
176
  */
123
- export function checkContrast(style) {
177
+ export function checkContrast(style, pairs = CONTRAST_PAIRS) {
124
178
  const s = normalizeStyle(style);
125
- /** @type {[string, string, number][]} */
126
- const rules = [
127
- ["ink", "bg", 4.5],
128
- ["ink", "surface", 4.5],
129
- ["muted", "bg", 4.5],
130
- ["muted", "surface", 4.5],
131
- ["onAccent", "accent", 4.5],
132
- ["line", "bg", 3],
133
- ["accent", "bg", 3],
134
- ["emphasis", "bg", 3],
135
- ];
179
+ if (!Array.isArray(pairs)) return [`${s.name}: contrast pairs must be an array of { fg, bg, min }`];
136
180
  const problems = [];
181
+ for (const [i, p] of pairs.entries()) {
182
+ const bad = !p || typeof p !== "object" ? "is not an object" : !TOKENS.includes(p.fg) ? `has unknown fg token "${p.fg}"` : !TOKENS.includes(p.bg) ? `has unknown bg token "${p.bg}"` : !(typeof p.min === "number" && p.min >= 1 && p.min <= 21) ? "needs a min contrast between 1 and 21" : "";
183
+ if (bad) problems.push(`${s.name}: contrast pair ${i} ${bad}`);
184
+ }
185
+ if (problems.length) return problems;
137
186
  for (const theme of ["light", "dark"]) {
138
- for (const [fg, bg, min] of rules) {
187
+ for (const { fg, bg, min } of pairs) {
139
188
  const r = contrast(s[theme][fg], s[theme][bg]);
140
189
  if (r < min) problems.push(`${s.name} ${theme}: ${fg} on ${bg} is ${r.toFixed(2)}:1, needs ${min}:1`);
141
190
  }
@@ -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
  /**
@@ -17,9 +18,9 @@
17
18
  * fontSize?: number }
18
19
  */
19
20
  import { easeOut, easeStandard, progress, window01 } from "../motion.mjs";
20
- import { boxNode, FONT_MIN, rectEdge } from "../parts.mjs";
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
 
@@ -96,7 +97,7 @@ export function hubSpoke(spec, { format = "16:9", locale = "en" } = {}) {
96
97
  const hubLabel = localize(spec.hub.label, locale);
97
98
  const labels = spokesSpec.map((s) => localize(s.label, locale));
98
99
  // Largest font (≤ max) at which the layout fits and every label wraps.
99
- const maxFs = spec.fontSize ?? (f.height > 0 ? 20 : 16);
100
+ const maxFs = maxFontSize(spec, f.height > 0 ? 20 : 16, `hub-spoke "${spec.id}"`);
100
101
  let L;
101
102
  let fs;
102
103
  let hubLines;
@@ -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) => {
@@ -12,10 +12,17 @@
12
12
  import { validateScene } from "../scene.mjs";
13
13
  import { hubSpoke } from "./hub-spoke.mjs";
14
14
  import { sequence } from "./sequence.mjs";
15
+ import { stack } from "./stack.mjs";
16
+ import { walk } from "./walk.mjs";
17
+ import { timeline } from "./timeline.mjs";
15
18
 
16
19
  export const SCENE_TYPES = {
17
20
  sequence,
18
21
  "hub-spoke": hubSpoke,
22
+ timeline,
23
+ stack,
24
+ "state-machine": walk,
25
+ "request-journey": walk,
19
26
  };
20
27
 
21
28
  export function createScene(spec, opts = {}) {