@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
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"]) {
@@ -0,0 +1,402 @@
1
+ /** @import { Scene } from "../scene.mjs" */
2
+ /** @import { Style } from "../style.mjs" */
3
+ // SPDX-License-Identifier: MIT
4
+ // Copyright (c) 2026 Ophir Radnitz
5
+ /**
6
+ * motion-kit · scene type "flowchart".
7
+ *
8
+ * Helps the viewer understand: a process with branches and joins, as drawn in
9
+ * a flowchart. Storyboard: the whole chart appears rank by rank in pending
10
+ * colours, so the structure is visible first; then the nodes fill accent one
11
+ * at a time in flow order, each incoming connector drawing on in accent just
12
+ * before its node fills, and an emphasis outline marks the node just reached.
13
+ *
14
+ * The layout is data: every node carries a `rank` (its layer along the flow)
15
+ * and a `pos` (its place across the flow, in node pitches), and an edge that
16
+ * spans ranks carries a waypoint per rank between (`via`). `motion-kit import`
17
+ * computes them once at build time from a Mermaid flowchart (lib/layout.mjs);
18
+ * this module only scales them to each format and never lays the graph out.
19
+ *
20
+ * Spec:
21
+ * { type: "flowchart", id, title, description,
22
+ * direction?: "down" | "up" | "right" | "left", // default "down"
23
+ * nodes: [{ id, label, rank, pos, shape?, detail? }], // 2–12 nodes
24
+ * edges: [{ from, to, label?, via?: [[rank, pos], …], dashed?, arrow? }], // 1–20 edges
25
+ * fontSize? }
26
+ * shape: "box" (default) | "round" | "pill" | "decision".
27
+ * Strings may be localized objects: { en: "...", nl: "..." }.
28
+ */
29
+ import { easeOut, easeStandard, progress } from "../motion.mjs";
30
+ import { FONT_MIN, maxFontSize, rectEdge } from "../parts.mjs";
31
+ import { FORMATS, localize, withId } from "../scene.mjs";
32
+ import { NEUTRAL, tok } from "../style.mjs";
33
+ import { drawOn, el, fade, num, polyline, text, translate } from "../svg.mjs";
34
+ import { estimateWidth, wrapLabel } from "../wrap.mjs";
35
+
36
+ export const FLOWCHART_SHAPES = ["box", "round", "pill", "decision"];
37
+ export const FLOWCHART_DIRECTIONS = ["down", "up", "right", "left"];
38
+
39
+ // Timeline (seconds). Steps settle: a step's fill ends at its `at`, and the
40
+ // next connector starts drawing BEAT later.
41
+ const ENTER_GAP = 0.1;
42
+ const ENTER = 0.4;
43
+ const DRAW = 0.35;
44
+ const FILL = 0.25;
45
+ const BEAT = 0.05;
46
+ const PERIOD = DRAW + FILL + BEAT;
47
+ const TAIL = 0.4;
48
+
49
+ const BOX_MAX = 220;
50
+ const GAP_Y = 20; // between neighbouring boxes across a horizontal flow
51
+ const MAX_LINES = 3;
52
+ const RING = 5; // emphasis outline distance from the node
53
+
54
+ /**
55
+ * @typedef {{ x: number, y: number }} Pt
56
+ * @typedef {{ x0: number, y0: number, x1: number, y1: number }} Box
57
+ */
58
+
59
+ /** @param {Box} a @param {Box} b */
60
+ const overlaps = (a, b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
61
+
62
+ /**
63
+ * Does segment a–b pass through box r? (Liang–Barsky clipping.)
64
+ * @param {Pt} a @param {Pt} b @param {Box} r
65
+ */
66
+ function segmentHits(a, b, r) {
67
+ let lo = 0;
68
+ let hi = 1;
69
+ const dx = b.x - a.x;
70
+ const dy = b.y - a.y;
71
+ for (const [p, q] of [[-dx, a.x - r.x0], [dx, r.x1 - a.x], [-dy, a.y - r.y0], [dy, r.y1 - a.y]]) {
72
+ if (p === 0) {
73
+ if (q < 0) return false;
74
+ } else {
75
+ const s = q / p;
76
+ if (p < 0) lo = Math.max(lo, s);
77
+ else hi = Math.min(hi, s);
78
+ if (lo > hi) return false;
79
+ }
80
+ }
81
+ return true;
82
+ }
83
+
84
+ /**
85
+ * @param {any} spec
86
+ * @param {{ format?: string, locale?: string }} [opts]
87
+ * @returns {Scene}
88
+ */
89
+ export function flowchart(spec, { format = "16:9", locale = "en" } = {}) {
90
+ const name = `flowchart "${spec.id}"`;
91
+ /** @param {string} why @returns {never} */
92
+ const fail = (why) => {
93
+ throw new Error(`${name}: ${why}`);
94
+ };
95
+ const f = FORMATS[format];
96
+ if (!f) throw new Error(`unknown format "${format}"`);
97
+ const nodes = spec.nodes;
98
+ const edges = spec.edges;
99
+ if (!Array.isArray(nodes) || nodes.length < 2 || nodes.length > 12) fail(`needs 2–12 nodes, got ${Array.isArray(nodes) ? nodes.length : "none"}`);
100
+ if (!Array.isArray(edges) || edges.length < 1 || edges.length > 20) fail(`needs 1–20 edges, got ${Array.isArray(edges) ? edges.length : "none"}`);
101
+ const direction = spec.direction ?? "down";
102
+ if (!FLOWCHART_DIRECTIONS.includes(direction)) fail(`direction must be one of ${FLOWCHART_DIRECTIONS.join(", ")}`);
103
+
104
+ /** @type {Map<string, number>} */
105
+ const index = new Map();
106
+ const labels = nodes.map((node, i) => {
107
+ if (!node || typeof node.id !== "string" || !node.id || index.has(node.id)) fail(`node ${i + 1} needs a unique non-empty id`);
108
+ index.set(node.id, i);
109
+ const label = localize(node.label, locale);
110
+ if (!label) fail(`node ${node.id} needs a label`);
111
+ if (!Number.isInteger(node.rank) || node.rank < 0) fail(`node ${node.id}: rank must be a whole number ≥ 0`);
112
+ if (!Number.isFinite(node.pos) || node.pos < 0) fail(`node ${node.id}: pos must be a number ≥ 0`);
113
+ if (node.shape !== undefined && !FLOWCHART_SHAPES.includes(node.shape)) fail(`node ${node.id}: shape must be one of ${FLOWCHART_SHAPES.join(", ")}`);
114
+ return label;
115
+ });
116
+ const minRank = Math.min(...nodes.map((n) => n.rank));
117
+ const maxRank = Math.max(...nodes.map((n) => n.rank));
118
+ const R = maxRank - minRank + 1;
119
+ const edgeLabels = edges.map((edge, i) => {
120
+ const what = `edge ${i + 1} (${edge?.from} → ${edge?.to})`;
121
+ if (!edge || !index.has(edge.from) || !index.has(edge.to)) fail(`${what} has an unknown from/to node`);
122
+ if (edge.from === edge.to) fail(`${what} is a self-loop; flowcharts draw none`);
123
+ for (const key of ["dashed", "arrow"]) if (edge[key] !== undefined && typeof edge[key] !== "boolean") fail(`${what}: ${key} must be boolean`);
124
+ const via = edge.via ?? [];
125
+ if (!Array.isArray(via) || via.some((p) => !Array.isArray(p) || p.length !== 2 || !Number.isInteger(p[0]) || !Number.isFinite(p[1]) || p[1] < 0)) fail(`${what}: via must be a list of [rank, pos] pairs`);
126
+ const ranks = [nodes[index.get(edge.from) ?? 0].rank, ...via.map((p) => p[0]), nodes[index.get(edge.to) ?? 0].rank];
127
+ const sign = Math.sign(ranks[1] - ranks[0]);
128
+ if (!sign || ranks.some((r, k) => k > 0 && r - ranks[k - 1] !== sign)) fail(`${what}: from, via and to must be on consecutive ranks (one waypoint per rank between)`);
129
+ return localize(edge.label, locale);
130
+ });
131
+ // Positions must leave room: boxes on a rank one pitch apart, waypoints
132
+ // clear of boxes.
133
+ for (let i = 0; i < nodes.length; i++) {
134
+ for (let j = i + 1; j < nodes.length; j++) {
135
+ if (nodes[i].rank === nodes[j].rank && Math.abs(nodes[i].pos - nodes[j].pos) < 1 - 1e-6) fail(`nodes ${nodes[i].id} and ${nodes[j].id} overlap on rank ${nodes[i].rank} (pos must differ by ≥ 1)`);
136
+ }
137
+ for (const edge of edges) {
138
+ for (const [r, p] of edge.via ?? []) {
139
+ if (r === nodes[i].rank && Math.abs(p - nodes[i].pos) < 0.5 - 1e-6) fail(`edge ${edge.from} → ${edge.to} passes through node ${nodes[i].id} on rank ${r}`);
140
+ }
141
+ }
142
+ }
143
+ const minPos = Math.min(...nodes.map((n) => n.pos), ...edges.flatMap((e) => (e.via ?? []).map((p) => p[1])));
144
+ const P = Math.max(...nodes.map((n) => n.pos), ...edges.flatMap((e) => (e.via ?? []).map((p) => p[1]))) - minPos;
145
+ const shapes = nodes.map((n) => n.shape ?? "box");
146
+ const anyEdgeLabel = edgeLabels.some(Boolean);
147
+
148
+ // Step order: along the flow, then across it.
149
+ const order = nodes.map((_, i) => i).sort((a, b) => nodes[a].rank - nodes[b].rank || nodes[a].pos - nodes[b].pos || a - b);
150
+ const stepOf = new Array(nodes.length);
151
+ order.forEach((v, k) => (stepOf[v] = k));
152
+
153
+ const vertical = direction === "down" || direction === "up";
154
+ const narrow = format === "tall" || (f.height > 0 && f.width / f.height < 0.8);
155
+ const tries = narrow || vertical ? [true, false] : [false, true];
156
+ const maxFs = maxFontSize(spec, f.height ? 20 : 16, name);
157
+
158
+ /**
159
+ * Place the chart with the flow vertical or horizontal at font size fs.
160
+ * Throws a reason when it does not fit.
161
+ * @param {boolean} down flow runs vertically
162
+ * @param {number} fs
163
+ */
164
+ function place(down, fs) {
165
+ const W = f.width;
166
+ // Phone widths keep a smaller margin and gap, so three boxes fit side by side.
167
+ const PAD = narrow ? 16 : 24;
168
+ const GAP_X = narrow ? 14 : 24; // between neighbouring boxes across a vertical flow
169
+ const lineH = fs * 1.25;
170
+ const labelW = Math.max(0, ...edgeLabels.map((s) => (s ? estimateWidth(s, fs) + 8 : 0)));
171
+ const labelH = lineH + 4;
172
+ const flowGap = down ? (anyEdgeLabel ? labelH + 28 : 36) : anyEdgeLabel ? labelW + 28 : 40;
173
+ const bw = Math.min(BOX_MAX, down ? (W - 2 * PAD - P * GAP_X) / (P + 1) : (W - 2 * PAD - (R - 1) * flowGap) / R);
174
+ const inset = fs * 0.8;
175
+ // A decision's pointed ends and a pill's round ends take one inset of the text width.
176
+ const chars = (/** @type {number} */ i) => Math.floor((bw - 16 - (shapes[i] === "decision" || shapes[i] === "pill" ? inset : 0)) / (fs * 0.56));
177
+ if (nodes.some((_, i) => chars(i) < 6)) throw new Error(`boxes would be ${Math.floor(bw)}px wide`);
178
+ const wrapped = labels.map((s, i) => wrapLabel(s, chars(i), MAX_LINES));
179
+ const bh = Math.max(...wrapped.map((l) => l.length)) * lineH + 18;
180
+ /** @type {number} */ let H;
181
+ /** @type {number} */ let flowPitch;
182
+ /** @type {number} */ let crossUnit;
183
+ if (down) {
184
+ crossUnit = P ? Math.min((W - 2 * PAD - bw) / P, bw + 64) : 0;
185
+ if (f.height) {
186
+ H = f.height;
187
+ flowPitch = Math.min((H - 2 * PAD - bh) / (R - 1), bh + 96);
188
+ if (flowPitch - bh < flowGap) throw new Error(`needs ${Math.ceil((R - 1) * (bh + flowGap) + bh + 2 * PAD)}px height`);
189
+ } else {
190
+ flowPitch = bh + Math.max(flowGap, 48);
191
+ H = Math.ceil(2 * PAD + (R - 1) * flowPitch + bh);
192
+ }
193
+ } else {
194
+ flowPitch = R > 1 ? Math.min((W - 2 * PAD - bw) / (R - 1), bw + flowGap + 64) : 0;
195
+ if (f.height) {
196
+ H = f.height;
197
+ crossUnit = P ? Math.min((H - 2 * PAD - bh) / P, bh + 48) : 0;
198
+ if (P && crossUnit < bh + GAP_Y) throw new Error(`needs ${Math.ceil(P * (bh + GAP_Y) + bh + 2 * PAD)}px height`);
199
+ } else {
200
+ crossUnit = bh + GAP_Y + 4;
201
+ H = Math.ceil(2 * PAD + P * crossUnit + bh);
202
+ }
203
+ }
204
+ const flowSpan = (R - 1) * flowPitch;
205
+ const crossSpan = P * crossUnit;
206
+ const reverse = direction === "up" || direction === "left";
207
+ /** @param {number} rank @param {number} pos @returns {Pt} */
208
+ const at = (rank, pos) => {
209
+ const r = reverse ? maxRank - rank : rank - minRank;
210
+ const along = r * flowPitch - flowSpan / 2;
211
+ const across = (pos - minPos) * crossUnit - crossSpan / 2;
212
+ return down ? { x: W / 2 + across, y: H / 2 + along } : { x: W / 2 + along, y: H / 2 + across };
213
+ };
214
+ const centres = nodes.map((n) => at(n.rank, n.pos));
215
+ const boxes = centres.map((c) => ({ x0: c.x - bw / 2, y0: c.y - bh / 2, x1: c.x + bw / 2, y1: c.y + bh / 2 }));
216
+
217
+ // Connectors: centre → waypoints → centre, trimmed to the boxes. Edges
218
+ // joining the same two nodes run side by side.
219
+ const pairCount = new Map();
220
+ const pairKey = (/** @type {any} */ e) => [e.from, e.to].sort().join("\u0000");
221
+ edges.forEach((e) => pairCount.set(pairKey(e), (pairCount.get(pairKey(e)) ?? 0) + 1));
222
+ const pairSeen = new Map();
223
+ const paths = edges.map((e) => {
224
+ const a = /** @type {number} */ (index.get(e.from));
225
+ const b = /** @type {number} */ (index.get(e.to));
226
+ const key = pairKey(e);
227
+ const k = pairSeen.get(key) ?? 0;
228
+ pairSeen.set(key, k + 1);
229
+ const shift = (k - ((pairCount.get(key) ?? 1) - 1) / 2) * 12;
230
+ const off = (/** @type {Pt} */ p) => (down ? { x: p.x + shift, y: p.y } : { x: p.x, y: p.y + shift });
231
+ const pts = [off(centres[a]), ...(e.via ?? []).map((/** @type {number[]} */ p) => off(at(p[0], p[1]))), off(centres[b])];
232
+ const start = rectEdge(pts[0].x, pts[0].y, bw / 2, bh / 2, pts[1], 2);
233
+ const end = rectEdge(pts[pts.length - 1].x, pts[pts.length - 1].y, bw / 2, bh / 2, pts[pts.length - 2], 3);
234
+ return [start, ...pts.slice(1, -1), end];
235
+ });
236
+ // Every connector stays clear of the boxes it does not join.
237
+ edges.forEach((e, i) => {
238
+ const ends = [index.get(e.from), index.get(e.to)];
239
+ const pts = paths[i];
240
+ boxes.forEach((box, j) => {
241
+ if (ends.includes(j)) return;
242
+ const inner = { x0: box.x0 + 2, y0: box.y0 + 2, x1: box.x1 - 2, y1: box.y1 - 2 };
243
+ if (pts.some((p, s) => s > 0 && segmentHits(pts[s - 1], p, inner))) throw new Error(`edge ${e.from} → ${e.to} crosses node ${nodes[j].id}`);
244
+ });
245
+ });
246
+ // Edge labels sit beside the first segment, on the outside of the turn.
247
+ /** @type {({ x: number, y: number, box: Box } | null)[]} */
248
+ const tags = edges.map((e, i) => {
249
+ const s = edgeLabels[i];
250
+ if (!s) return null;
251
+ const [a, b] = paths[i];
252
+ const m = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
253
+ const w = estimateWidth(s, fs) + 4;
254
+ let box;
255
+ if (down) {
256
+ const slope = Math.abs(b.y - a.y) < 1e-6 ? 0 : Math.abs((b.x - a.x) / (b.y - a.y));
257
+ const reach = slope * labelH / 2 + 6;
258
+ const left = b.x < a.x - 0.5;
259
+ box = left ? { x0: m.x - reach - w, x1: m.x - reach } : { x0: m.x + reach, x1: m.x + reach + w };
260
+ box = { ...box, y0: m.y - labelH / 2, y1: m.y + labelH / 2 };
261
+ } else {
262
+ const slope = Math.abs(b.x - a.x) < 1e-6 ? 0 : Math.abs((b.y - a.y) / (b.x - a.x));
263
+ const reach = slope * w / 2 + 4;
264
+ const below = b.y > a.y + 0.5;
265
+ box = below ? { y0: m.y + reach, y1: m.y + reach + labelH } : { y0: m.y - reach - labelH, y1: m.y - reach };
266
+ box = { ...box, x0: m.x - w / 2, x1: m.x + w / 2 };
267
+ }
268
+ return { x: (box.x0 + box.x1) / 2, y: (box.y0 + box.y1) / 2, box };
269
+ });
270
+ tags.forEach((tag, i) => {
271
+ if (!tag) return;
272
+ const { box } = tag;
273
+ if (box.x0 < 2 || box.y0 < 2 || box.x1 > W - 2 || box.y1 > H - 2) throw new Error(`the label of edge ${edges[i].from} → ${edges[i].to} leaves the canvas`);
274
+ boxes.forEach((nb, j) => {
275
+ if (overlaps(box, { x0: nb.x0 - 3, y0: nb.y0 - 3, x1: nb.x1 + 3, y1: nb.y1 + 3 })) throw new Error(`the label of edge ${edges[i].from} → ${edges[i].to} covers node ${nodes[j].id}`);
276
+ });
277
+ tags.forEach((other, j) => {
278
+ if (j > i && other && overlaps(box, other.box)) throw new Error(`the labels of edges ${edges[i].from} → ${edges[i].to} and ${edges[j].from} → ${edges[j].to} overlap`);
279
+ });
280
+ paths.forEach((pts, j) => {
281
+ if (j !== i && pts.some((p, s) => s > 0 && segmentHits(pts[s - 1], p, box))) throw new Error(`the label of edge ${edges[i].from} → ${edges[i].to} crosses edge ${edges[j].from} → ${edges[j].to}`);
282
+ });
283
+ });
284
+ return { fs, W, H, bw, bh, inset, wrapped, centres, paths: paths.map((pts) => ({ pts, line: polyline(pts) })), tags };
285
+ }
286
+
287
+ let L;
288
+ let why = "";
289
+ for (const down of tries) {
290
+ for (let fs = maxFs; fs >= FONT_MIN && !L; fs--) {
291
+ try {
292
+ L = place(down, fs);
293
+ } catch (e) {
294
+ why ||= e instanceof Error ? e.message : String(e);
295
+ }
296
+ }
297
+ if (L) break;
298
+ }
299
+ if (!L) fail(`does not fit ${format} at ≥ ${FONT_MIN}px (${why}); use fewer nodes or ranks, shorter labels or a larger format`);
300
+ const G = L;
301
+
302
+ // Each connector turns accent at the later of its two nodes' steps: before
303
+ // that node fills when it is the target, while it fills when it is the source.
304
+ const edgeStep = edges.map((e) => Math.max(stepOf[index.get(e.from) ?? 0], stepOf[index.get(e.to) ?? 0]));
305
+ const backward = edges.map((e, i) => stepOf[index.get(e.to) ?? 0] !== edgeStep[i]);
306
+ const rankIndex = (/** @type {number} */ r) => r - minRank;
307
+ const START = ENTER_GAP * (R - 1) + ENTER + 0.1;
308
+ const stepAt = (/** @type {number} */ k) => START + DRAW + FILL + k * PERIOD;
309
+ const fillStart = (/** @type {number} */ k) => stepAt(k) - FILL;
310
+ const drawStart = (/** @type {number} */ k) => fillStart(k) - DRAW;
311
+ const duration = stepAt(nodes.length - 1) + TAIL;
312
+ const n = nodes.length;
313
+
314
+ /**
315
+ * Node outline for its shape, grown by `grow` px (the emphasis outline).
316
+ * @param {number} i @param {number} grow @param {number} radius the style's corner radius
317
+ * @param {Record<string, string | number>} attrs
318
+ */
319
+ function shapeAt(i, grow, radius, attrs) {
320
+ const c = G.centres[i];
321
+ const w = G.bw + 2 * grow;
322
+ const h = G.bh + 2 * grow;
323
+ const x = c.x - w / 2;
324
+ const y = c.y - h / 2;
325
+ if (shapes[i] === "decision") {
326
+ const k = Math.min(h / 2, G.inset + grow);
327
+ const pts = [[x + k, y], [x + w - k, y], [x + w, c.y], [x + w - k, y + h], [x + k, y + h], [x, c.y]];
328
+ return el("polygon", { points: pts.map(([px, py]) => `${num(px)},${num(py)}`).join(" "), "stroke-linejoin": "round", ...attrs });
329
+ }
330
+ const rx = shapes[i] === "pill" ? h / 2 : shapes[i] === "round" ? Math.min(h / 2, Math.max(radius, 14) + grow) : radius + grow;
331
+ return el("rect", { x, y, width: w, height: h, rx, ...attrs });
332
+ }
333
+
334
+ /** @param {number} t @param {{ style?: Style }} [ctx] */
335
+ function frame(t, { style = NEUTRAL } = {}) {
336
+ const enter = (/** @type {number} */ r) => progress(t, rankIndex(r) * ENTER_GAP, ENTER, easeOut);
337
+ const out = [];
338
+ const drawn = edges.map((_, i) => progress(t, backward[i] ? fillStart(edgeStep[i]) - 0.1 : drawStart(edgeStep[i]), backward[i] ? DRAW - 0.05 : DRAW, easeStandard));
339
+ edges.forEach((e, i) => {
340
+ const shown = Math.min(enter(nodes[index.get(e.from) ?? 0].rank), enter(nodes[index.get(e.to) ?? 0].rank));
341
+ if (shown <= 0) return;
342
+ const { pts, line } = G.paths[i];
343
+ const common = { d: line.d, fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round", "stroke-dasharray": e.dashed ? "6 5" : undefined };
344
+ out.push(el("path", { ...common, stroke: tok("line"), "stroke-width": style.stroke, opacity: shown }));
345
+ // A dashed connector turns accent whole; a solid one draws on.
346
+ if (e.dashed) {
347
+ if (drawn[i] > 0) out.push(el("path", { ...common, stroke: tok("accent"), "stroke-width": style.stroke * 1.5, opacity: drawn[i] }));
348
+ } else {
349
+ const dash = drawOn(line.length, drawn[i]);
350
+ if (dash) out.push(el("path", { ...common, stroke: tok("accent"), "stroke-width": style.stroke * 1.5, ...dash }));
351
+ }
352
+ if (e.arrow !== false) {
353
+ const tip = pts[pts.length - 1];
354
+ const prev = pts[pts.length - 2];
355
+ const len = Math.hypot(tip.x - prev.x, tip.y - prev.y) || 1;
356
+ const ux = (tip.x - prev.x) / len;
357
+ const uy = (tip.y - prev.y) / len;
358
+ const d = `M${num(tip.x - 8 * ux - 5 * uy)} ${num(tip.y - 8 * uy + 5 * ux)} L${num(tip.x)} ${num(tip.y)} L${num(tip.x - 8 * ux + 5 * uy)} ${num(tip.y - 8 * uy - 5 * ux)}`;
359
+ const head = { d, fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round" };
360
+ const on = progress(t, (backward[i] ? fillStart(edgeStep[i]) - 0.1 : drawStart(edgeStep[i])) + DRAW * 0.6, DRAW * 0.3, easeStandard);
361
+ out.push(fade(shown * (1 - on), {}, el("path", { ...head, stroke: tok("line"), "stroke-width": style.stroke })));
362
+ out.push(fade(on, {}, el("path", { ...head, stroke: tok("accent"), "stroke-width": style.stroke * 1.5 })));
363
+ }
364
+ const tag = G.tags[i];
365
+ if (tag) {
366
+ const attrs = { x: tag.x, y: tag.y, "text-anchor": "middle", "dominant-baseline": "central", "font-size": G.fs, "font-weight": 500 };
367
+ out.push(fade(shown, {}, fade(1 - drawn[i], {}, text({ ...attrs, fill: tok("muted") }, edgeLabels[i])), fade(drawn[i], {}, text({ ...attrs, fill: tok("ink") }, edgeLabels[i]))));
368
+ }
369
+ });
370
+ nodes.forEach((node, i) => {
371
+ const shown = enter(node.rank);
372
+ if (shown <= 0) return;
373
+ const active = progress(t, fillStart(stepOf[i]), FILL, easeStandard);
374
+ const c = G.centres[i];
375
+ const label = (/** @type {string} */ fill) => text({ x: c.x, y: c.y, "text-anchor": "middle", "dominant-baseline": "central", "font-size": G.fs, "font-weight": 500, fill }, G.wrapped[i]);
376
+ const pending = el("g", {}, shapeAt(i, 0, style.radius, { fill: tok("surface"), stroke: tok("line"), "stroke-width": style.stroke }), label(tok("ink")));
377
+ const on = el("g", {}, shapeAt(i, 0, style.radius, { fill: tok("accent"), stroke: tok("accent"), "stroke-width": style.stroke }), label(tok("onAccent")));
378
+ const dy = (1 - shown) * 8;
379
+ out.push(fade(shown, { transform: dy > 0.004 ? translate(0, dy) : undefined }, fade(1 - active, {}, pending), fade(active, {}, on)));
380
+ });
381
+ // Emphasis: an outline on the node reached last.
382
+ order.forEach((v, k) => {
383
+ const opacity = progress(t, fillStart(k), FILL, easeOut) * (k + 1 < n ? 1 - progress(t, drawStart(k + 1), FILL, easeStandard) : 1);
384
+ if (opacity > 0) out.push(fade(opacity, {}, shapeAt(v, RING, style.radius, { fill: "none", stroke: tok("emphasis"), "stroke-width": style.stroke * 1.5 })));
385
+ });
386
+ return out.join("");
387
+ }
388
+
389
+ return {
390
+ id: `${spec.id}-${format.replace(":", "x")}`,
391
+ type: "flowchart",
392
+ format,
393
+ locale,
394
+ width: G.W,
395
+ height: G.H,
396
+ duration,
397
+ title: localize(spec.title, locale),
398
+ description: localize(spec.description, locale),
399
+ steps: order.map((v, k) => withId({ at: stepAt(k), label: labels[v], detail: localize(nodes[v].detail, locale) }, nodes[v].id)),
400
+ frame,
401
+ };
402
+ }
@@ -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) => {
@@ -10,9 +10,11 @@
10
10
  * export is (opts) → scene (see examples/custom-*.scene.mjs).
11
11
  */
12
12
  import { validateScene } from "../scene.mjs";
13
+ import { flowchart } from "./flowchart.mjs";
13
14
  import { hubSpoke } from "./hub-spoke.mjs";
14
15
  import { sequence } from "./sequence.mjs";
15
16
  import { stack } from "./stack.mjs";
17
+ import { walk } from "./walk.mjs";
16
18
  import { timeline } from "./timeline.mjs";
17
19
 
18
20
  export const SCENE_TYPES = {
@@ -20,6 +22,9 @@ export const SCENE_TYPES = {
20
22
  "hub-spoke": hubSpoke,
21
23
  timeline,
22
24
  stack,
25
+ "state-machine": walk,
26
+ "request-journey": walk,
27
+ flowchart,
23
28
  };
24
29
 
25
30
  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
  }