@liqweed/motion-kit 0.5.0 → 0.7.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 (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +17 -2
  4. package/adapters/page/README.md +5 -0
  5. package/cli/motion-kit.mjs +91 -4
  6. package/docs/spec/technique.md +49 -25
  7. package/examples/checkout.json +104 -0
  8. package/examples/connection.json +80 -0
  9. package/examples/custom-pulse.scene.mjs +2 -0
  10. package/examples/player-states.json +97 -0
  11. package/examples/pull-request.json +93 -0
  12. package/examples/pull-request.mmd +15 -0
  13. package/lib/check.mjs +11 -8
  14. package/lib/export.mjs +12 -0
  15. package/lib/gate.mjs +4 -4
  16. package/lib/layout.mjs +236 -0
  17. package/lib/load.mjs +15 -0
  18. package/lib/mermaid.mjs +382 -0
  19. package/lib/outdated.mjs +122 -0
  20. package/package.json +6 -3
  21. package/runtime/links.mjs +5 -1
  22. package/runtime/player.mjs +40 -1
  23. package/runtime/scene.mjs +21 -8
  24. package/runtime/style.mjs +3 -0
  25. package/runtime/types/flowchart.mjs +402 -0
  26. package/runtime/types/hub-spoke.mjs +8 -6
  27. package/runtime/types/index.mjs +5 -0
  28. package/runtime/types/sequence.mjs +8 -6
  29. package/runtime/types/stack.mjs +13 -10
  30. package/runtime/types/timeline.mjs +14 -12
  31. package/runtime/types/walk.mjs +162 -0
  32. package/skills/animated-diagram/SKILL.md +8 -3
  33. package/skills/animated-diagram/references/custom-scenes.md +14 -0
  34. package/skills/animated-diagram/references/ecosystem.md +2 -2
  35. package/skills/animated-diagram/references/interactivity.md +18 -0
  36. package/skills/animated-diagram/references/motion-vocabulary.md +1 -1
  37. package/skills/animated-diagram/references/scene-types.md +118 -6
  38. package/skills/animated-diagram/references/styles.md +11 -2
  39. package/skills/animated-diagram/references/technique.md +6 -2
  40. package/skills/motion-render/SKILL.md +7 -0
  41. package/skills/motion-render/references/video.md +1 -1
@@ -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
+ }
@@ -53,8 +53,11 @@ from the system's package manager (`brew install ffmpeg`, `apt install ffmpeg`).
53
53
  Write the spec, then render the step contact sheet and show it:
54
54
  `motion-kit export spec.json -o <scratch>/sb --png --qc` → open `index.html`
55
55
  or show the PNGs. Get a yes on the *story* before polishing.
56
- 3. **Build.** Spec-driven types first (`sequence`, `hub-spoke`, `timeline`, `stack`). Only write a
57
- custom scene module when no type fits (`references/custom-scenes.md`).
56
+ 3. **Build.** Spec-driven types first (`sequence`, `hub-spoke`, `timeline`, `stack`,
57
+ `state-machine`, `request-journey`, `flowchart`). The user has a Mermaid
58
+ flowchart? `motion-kit import flow.mmd --out flow.json` writes the spec
59
+ (layout computed once). Only write a custom scene module when no type fits
60
+ (`references/custom-scenes.md`).
58
61
  4. **Gate.** `motion-kit check spec.json` must pass in every format/locale
59
62
  shipped: deterministic, settled steps, rounded numbers, token-only colours,
60
63
  escaped labels, labels fit, holds the final frame.
@@ -67,7 +70,7 @@ from the system's package manager (`brew install ffmpeg`, `apt install ffmpeg`).
67
70
  ## Hard rules
68
71
 
69
72
  - 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.
73
+ - 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
74
  - No bounce/elastic, no parallax, no ambient motion inside an explainer.
72
75
  - Every motion must answer "what does this help the viewer understand?".
73
76
  - Skeleton first, then fill: show the whole structure, then walk through it.
@@ -84,12 +87,14 @@ from the system's package manager (`brew install ffmpeg`, `apt install ffmpeg`).
84
87
  mk() { node "$MK/cli/motion-kit.mjs" "$@"; }
85
88
  mk types; mk formats
86
89
  mk check diagram.json # all formats × locales
90
+ mk import flow.mmd -o flow.json # Mermaid flowchart → sequence or flowchart spec, then checked
87
91
  mk check flow.scene.mjs -l en -l nl --options labels.mjs # a custom module, with its text from the caller
88
92
  mk build diagram.json -o diagram.html -f wide -l nl # Craft Page / standalone
89
93
  mk export diagram.json -o out/ --png --qc # slides + review sheet
90
94
  mk bake diagram.json -o diagram.svg -f wide # zero-JS animated SVG
91
95
  mk video diagram.json -f 9:16 -o reel.mp4 --sheet sheet.png
92
96
  mk vendor <repo>/components/motion-kit --adapter slidev # or astro / page / element
97
+ mk outdated <repo>/components/motion-kit # newer release on npm? exit 1 + the re-vendor command
93
98
  node <repo>/components/motion-kit/check.mjs flow.scene.mjs -l en -l nl --style brand.json --options labels.mjs # the vendored gate, same checks
94
99
  ```
95
100
 
@@ -109,3 +109,17 @@ export default function make({ format = "1:1", kit }) {
109
109
  Every command supports this, `motion-kit build` included (it bundles the whole
110
110
  runtime and passes it as `kit`). A module that imports instead must use
111
111
  relative imports to a vendored runtime.
112
+
113
+ ## Declared locales and narrative steps
114
+
115
+ Export `const locales = ["en", "nl"]` alongside the default factory so both
116
+ CLI and vendored checks test every shipped locale. Without a declaration the
117
+ check uses `en`; explicit `--locale` flags override the declaration.
118
+ `localize()` accepts shared plain strings or an exact locale translation;
119
+ a missing dictionary entry throws. It never silently selects another language.
120
+
121
+ A scene whose step labels narrate actions rather than name visible objects
122
+ sets `stepLabelsInFrame: false`. Those labels still belong in the player's
123
+ controls and accessible transcript; G10 otherwise requires each label in the
124
+ final frame. `frame(t, { idPrefix, style })` also receives the normalized style
125
+ when called through `renderSvg`; custom shape styling is opt-in.
@@ -9,8 +9,8 @@ Checked Nov 2026. Re-verify licences before commercial use.
9
9
  | **GSAP** (incl. DrawSVG, MorphSVG, MotionPath, SplitText) | free incl. commercial since 3.13 (not for competing no-code builders) | Rich page motion, morphing, text splitting | Paused timelines are seekable (`tl.seek(t)`), so determinism holds. ~70 KB must be inlined for Craft Pages. Use for website polish; keep explainers in motion-kit |
10
10
  | **Motion Canvas / Revideo** | MIT | Hand-crafted technical explainer *videos* with generator timelines | Good for one-off videos; no live-page reuse |
11
11
  | **Manim CE** | MIT | Mathematics and science visuals, equations | Python; video only |
12
- | **Mermaid** | MIT | Static diagrams from text; quick structure | Use as *input notation* (flowchart/state), then lay out and animate in motion-kit |
13
- | **ELK.js / dagre** | EPL-2.0 / MIT | Automatic layout of larger graphs | Run at build time in Node, store coordinates in the spec |
12
+ | **Mermaid** | MIT | Static diagrams from text; quick structure | Flowcharts import directly: `motion-kit import flow.mmd` (layout at build time). State diagrams: write a `state-machine` spec |
13
+ | **ELK.js / dagre** | EPL-2.0 / MIT | Automatic layout of graphs larger than a scene's 12 nodes | `motion-kit import` has its own small layered layout; for more, run one at build time in Node and store coordinates in the spec |
14
14
  | **Lottie / Rive** | MIT runtimes | Designer-authored animation assets | Embed as media; not data-driven |
15
15
  | **resvg-js** | MPL-2.0 | SVG → PNG without a browser | motion-kit's rasterizer |
16
16
 
@@ -184,3 +184,21 @@ animate, reduced })` (`"play"`, `"seek"` or null).
184
184
  - Don't hide information only in hover states; touch devices have no hover.
185
185
  - Test: keyboard only, a screen reader pass (VoiceOver: the step list is read),
186
186
  phone width, reduced motion, dark mode.
187
+
188
+ ## Step notifications
189
+
190
+ `controller.onStep(index => { … })` calls immediately with the current settled
191
+ step index, then once whenever it changes through playback, seek, scrubber,
192
+ buttons or keyboard. The index is `-1` before the first step. It returns an
193
+ unsubscribe function; `destroy()` releases every subscription. `scrollSteps`
194
+ and `linkSteps` subscribe when available so marks also follow player controls.
195
+ No polling or extra animation loop is needed. Callbacks should observe state,
196
+ not seek the player recursively.
197
+
198
+ For outside drivers, use the returned controller or the adapter element's
199
+ `.controller` after `motion-ready`. `seek(t)` is public, requires a finite time,
200
+ clamps to the scene, pauses playback and cancels pending autoplay. Mount with
201
+ `autoplay: "none"`; honor reduced motion in the driver. Visibility pauses the
202
+ player's clock, not explicit seeks. Capture tools may use
203
+ `globalThis.__motionKit[options.id ?? scene.id]`; default scene ids contain the
204
+ format suffix, while Astro generates an instance key unless given `id`.
@@ -18,7 +18,7 @@
18
18
  | State fill (pending → active) | 200–300 ms |
19
19
  | Travel between nodes | 350–500 ms |
20
20
  | Pause between beats | ≥ 50 ms, so step frames settle |
21
- | Whole explainer | ≤ ~8 s, then hold |
21
+ | Whole explainer | aim for ≤ 8 s, then hold; gate limit 12 s |
22
22
 
23
23
  ## Springs, without breaking random access (derived)
24
24
 
@@ -83,6 +83,120 @@ for `down`, bottom → top for `up`). Layout: one column of layers with the rail
83
83
  on the right in every format; labels take one line, two when needed. Throws
84
84
  when the layers do not fit: fewer layers, shorter labels or a larger format.
85
85
 
86
+ ### `state-machine`: states and explicit transitions
87
+
88
+ ```json
89
+ { "type": "state-machine", "id": "connection",
90
+ "title": "A connection", "description": "Connect and disconnect.",
91
+ "states": [{ "id": "off", "label": "Offline" }, { "id": "on", "label": "Online" }],
92
+ "transitions": [
93
+ { "id": "connect", "from": "off", "to": "on", "label": "Connect" },
94
+ { "id": "close", "from": "on", "to": "off", "label": "Disconnect" }
95
+ ],
96
+ "initial": "off", "path": ["connect", "close"] }
97
+ ```
98
+
99
+ 2–8 states, 1–12 transitions and 1–10 narrated transitions in `path`.
100
+ State and transition ids are required and unique within their list. `initial`
101
+ names a state. Each path edge must start where the previous one ended; branches,
102
+ cycles, repeated transitions and self-transitions are supported. The path is
103
+ explicit: the runtime never decides which branch to take. All states appear
104
+ pending, the initial state fills, then a single token follows the path while
105
+ the current state fills accent. Completed edges retain their accent.
106
+
107
+ Layouts use a column in reading order with separate connector lanes outside
108
+ the labels; each fixed format centers the fitted graph, and strips grow to
109
+ fit. Labels auto-fit to two lines at 14 px or above. Oversized graphs and labels
110
+ fail with a remedy. `fontSize` sets the optional maximum.
111
+
112
+ Steps are the initial state (`initial`), then one per path entry (`visit-1`,
113
+ `visit-2`, …). Transition labels and optional `detail` sentences appear in
114
+ controls, captions and the accessible transcript; they are narrative steps
115
+ (`stepLabelsInFrame: false`), not labels drawn on every edge. State labels stay
116
+ visible in every settled frame. Labels, title, description and details accept
117
+ localized strings. See `examples/player-states.json` and `connection.json`.
118
+
119
+ ### `request-journey`: a request crossing components
120
+
121
+ Uses the same explicit walk, timing, bounds and step ids as `state-machine`,
122
+ with `components` instead of `states` and `hops` instead of `transitions`:
123
+
124
+ ```json
125
+ { "type": "request-journey", "id": "request",
126
+ "title": "Queue a job", "description": "The API queues work asynchronously.",
127
+ "components": [
128
+ { "id": "api", "label": "API", "region": "Service" },
129
+ { "id": "queue", "label": "Queue", "region": "Worker" }
130
+ ],
131
+ "hops": [{ "id": "send", "from": "api", "to": "queue", "label": "Enqueue", "async": true }],
132
+ "initial": "api", "path": ["send"] }
133
+ ```
134
+
135
+ A component's optional localized `region` names its boundary, shown as a
136
+ one-line heading above a dashed enclosure. Components sharing a region keep
137
+ separate enclosures with the same name. Hops with `async: true` stay dashed,
138
+ including after activation. Return paths are ordinary hops in the opposite
139
+ direction. See `examples/checkout.json`.
140
+
141
+ ### `flowchart`: a process with branches and joins
142
+
143
+ Usually imported from Mermaid rather than written by hand:
144
+
145
+ ```bash
146
+ motion-kit import flow.mmd --out flow.json # also checks flow.json in every format (or only the --format ones)
147
+ ```
148
+
149
+ ```json
150
+ { "type": "flowchart", "id": "pull-request",
151
+ "title": "…", "description": "…",
152
+ "direction": "down", // "up", "right", "left"
153
+ "nodes": [ { "id": "ci", "label": "CI passes?", "shape": "decision", "rank": 1, "pos": 0.25 }, … ],
154
+ "edges": [ { "from": "ci", "to": "fix", "label": "No" },
155
+ { "from": "a", "to": "d", "via": [[1, 0.75]] },
156
+ { "from": "login", "to": "auth", "dashed": true }, … ] }
157
+ ```
158
+
159
+ 2–12 nodes, 1–20 edges. The layout is stored in the spec: `rank` is a node's
160
+ layer along the flow (whole numbers), `pos` its place across the flow in node
161
+ pitches (nodes on one rank ≥ 1 apart), and an edge spanning several ranks has
162
+ one `via` waypoint per rank between. The importer computes these once at build
163
+ time (`lib/layout.mjs`, a layered layout); the scene type only scales them to
164
+ each format, so the runtime never lays a graph out. Shapes: `box` (default),
165
+ `round`, `pill`, `decision`. Edges may carry a short one-line `label`, be
166
+ `dashed`, or have no arrowhead (`"arrow": false`). Nodes may carry `detail`.
167
+
168
+ Storyboard: the chart appears rank by rank in pending colours → nodes fill
169
+ accent one at a time in flow order (rank, then across), each incoming connector
170
+ drawing on in accent just before its node fills → an emphasis outline marks the
171
+ node just reached. A connector that points back (a retry loop) turns accent
172
+ while its source fills. Steps = one per node; step ids are the node ids.
173
+ `direction` is the flow in wide formats; 9:16 and `tall` flow downward, and a
174
+ format falls back to the other axis when the preferred one does not fit. Throws
175
+ when labels, edge labels or connectors would collide: shorter labels, fewer
176
+ ranks or a larger format. See `examples/pull-request.mmd` and its spec.
177
+
178
+ ### Importing Mermaid
179
+
180
+ `motion-kit import <file.mmd | ->` turns a Mermaid flowchart into a spec
181
+ (stdout, or `--out`; `--id`, `--title`, `--description` override what the
182
+ chart says). A plain chain (each node one link in and one out, no link labels,
183
+ no dotted links) becomes a `sequence`; anything else becomes a `flowchart`.
184
+
185
+ - Read: `flowchart`/`graph` with `TB`/`TD`/`BT`/`LR`/`RL`; `[box]`, `(round)`,
186
+ `([pill])`, `{decision}`, `{{decision}}`; quoted labels, `<br>`, `#quot;`
187
+ codes; `-->`, `---`, `-.->`, `-.-`, `==>`, `===` with `|text|` or
188
+ `-- text -->` labels; chains and `&` groups; `accTitle`, `accDescr`, a
189
+ front-matter `title`. The title and description become the scene's
190
+ accessible name and description; without `accDescr` the description lists
191
+ every link in words.
192
+ - Ignored with a warning (colours come from the motion-kit style): `classDef`,
193
+ `class`, `style`, `linkStyle`, `:::name`, `%%{init}%%`, front-matter `config`.
194
+ - Errors naming the line: subgraphs and `direction`, `click`, other shapes
195
+ (circle, database, subroutine, parallelogram, …), `@{ shape }`, two-way,
196
+ circle and cross links, `~~~`, link ids, self-loops, markdown strings, HTML
197
+ in labels, and more than 12 nodes or 20 links. Sequence, state and ER
198
+ diagrams are not converted.
199
+
86
200
  ## Storyboards for types not built yet
87
201
 
88
202
  Build these as custom scenes (`custom-scenes.md`) first. Promote one to a type
@@ -92,11 +206,9 @@ once it has been used twice.
92
206
  |---|---|---|
93
207
  | `before-after` | what changes | left state fully shown → a divider sweeps → right state builds; differences highlighted with the emphasis colour |
94
208
  | `comparison` | option A vs B on criteria | two columns appear → criteria rows fill one at a time → the deciding row emphasised |
95
- | `state-machine` | states and transitions | all states (pending) → a token walks a path of transitions, the current state accent |
96
- | `request-journey` | a request crossing system components | components in regions/boundaries → a dot travels the path, each hop lights, async edges dashed |
97
209
  | `funnel` / `data-flow` | volume or data narrowing/merging | sources appear → streams draw on and merge → result fills |
98
210
 
99
- Auto-layout for larger graphs: lay out with ELK.js or dagre once (Node, at
100
- build time), store coordinates in the spec, then animate. Mermaid flowchart or
101
- state syntax can serve as input notation (parse nodes/edges, recompute layout).
102
- Don't convert sequence or ER diagrams lossily.
211
+ Auto-layout happens at build time, never in `frame()`: `motion-kit import`
212
+ lays out Mermaid flowcharts as `flowchart` specs (above). State diagrams are
213
+ not imported yet; write a `state-machine` spec. Don't convert sequence or ER
214
+ diagrams lossily.
@@ -32,8 +32,17 @@ properties (light + dark); standalone exports resolve them to literals.
32
32
  }
33
33
  ```
34
34
 
35
- Missing tokens fall back to neutral. Colours must be `#rrggbb`. Unknown tokens
36
- throw.
35
+ Missing tokens fall back to neutral within each theme. If the entire `dark`
36
+ object is absent, the light overrides are also applied over neutral dark;
37
+ provide both theme objects when they need different values. Colours must be
38
+ `#rrggbb`; unknown tokens throw.
39
+
40
+ `radius` (0–24, default 10) sets built-in rectangular node corners; circles,
41
+ region borders and timeline pills retain their geometry. `stroke` (1–4,
42
+ default 2) sets the base line width, with accent lines at 1.5× and timeline
43
+ stems at 0.75×. These settings affect live, SVG, PNG, bake and video rendering.
44
+ Custom scenes receive the normalized style through `frame(t, { style })` and
45
+ may use it explicitly; their own geometry is not rewritten.
37
46
 
38
47
  ## Contrast
39
48
 
@@ -20,7 +20,11 @@ authoring a timeline and recording it. Consequences:
20
20
 
21
21
  Video maps frame `f` at `fps` to `t = f / fps` (30 fps × 25 s = 750 frames).
22
22
 
23
- ## 2. Determinism rules (enforced by `motion-kit check`)
23
+ ## 2. Determinism rules (sampled by `motion-kit check`)
24
+
25
+ The gate samples outputs and stubs clocks; this is evidence, not a proof of
26
+ purity. Aliases captured at import time, unsampled code paths, CSS motion and
27
+ cross-call state still require code review.
24
28
 
25
29
  1. No dependence on previous frames.
26
30
  2. No uncontrolled randomness (derive variation from a seed and `t` if needed).
@@ -97,7 +101,7 @@ Never crop one master. Timings and the spec are shared; geometry is a function
97
101
  of the format (`16:9`, `4:3`, `1:1`, `9:16`, `wide` strip, `tall` column):
98
102
 
99
103
  - Row for wide aspects, snake grid for square-ish, column or tree for tall.
100
- - **Auto-fit text:** try the largest font (fixed formats ≤ 22 px, strips ≤ 16 px)
104
+ - **Auto-fit text:** try the largest font (fixed formats ≤ 22 px (hub-spoke: 20 px), strips ≤ 16 px)
101
105
  and step down to 14 px until every label wraps into its budget; fail if even
102
106
  14 px doesn't fit. Never shrink below 14 px at 1×.
103
107
  - **Collision checks:** nodes must not overlap or leave the canvas; the layout
@@ -100,3 +100,10 @@ Re-exporting into the same folder replaces the previous export: files its
100
100
  `manifest.json` listed that the new export does not write are deleted, so the
101
101
  folder holds exactly what the new manifest lists. Files no export wrote are
102
102
  left alone and named in a warning; keep notes and review files elsewhere.
103
+
104
+ The CLI gates `build`, `export`, `bake`, `video` and `icon` before writing
105
+ output, including shared style contrast and scene-specific pairs. Exports
106
+ include `runtimeHash`, a SHA-256 of runtime module paths and bytes, in the
107
+ manifest and in `inputHash`, together with format, locale and render settings.
108
+ A changed runtime invalidates the hash even before its package version changes.
109
+ The hash does not recursively fingerprint arbitrary imports of custom scenes.
@@ -6,7 +6,7 @@
6
6
  frame f → t = f/fps − lead → renderSvg(standalone, opaque bg) → PNG (resvg) → ffmpeg stdin
7
7
  ```
8
8
 
9
- - No browser, no per-frame files; identical consecutive frames are rasterized once.
9
+ - No browser, no per-frame files; repeated timestamps (lead and final hold) reuse their PNG.
10
10
  - `--hold` (default 1.5 s) keeps the final frame readable; `lead` 0.25 s.
11
11
  - Encoders: MP4 `libx264 -preset slow -crf 18 -pix_fmt yuv420p -movflags +faststart`
12
12
  (even dimensions padded); WebM `libvpx-vp9 -crf 32`; GIF two-pass palette,