@liqweed/motion-kit 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/runtime/style.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ /** @import { Motion } from "./motion.mjs" */
1
2
  // SPDX-License-Identifier: MIT
2
3
  // Copyright (c) 2026 Ophir Radnitz
3
4
  /**
@@ -10,12 +11,14 @@
10
11
  * viewers do not understand CSS variables.
11
12
  *
12
13
  * A style is plain data:
13
- * { name, font, radius, stroke, light: {token: color}, dark: {token: color} }
14
+ * { name, font, radius, stroke, motion, light: {token: color}, dark: {token: color} }
14
15
  */
16
+ import { DEFAULT_MOTION } from "./motion.mjs";
15
17
 
16
18
  /**
17
- * A visual style: font, shape constants and one colour per token, per theme.
18
- * @typedef {{ name?: string, font: string, radius: number, stroke: number, light: Record<string, string>, dark: Record<string, string> }} Style
19
+ * A visual style: font, shape constants, the entrance and movement curves and
20
+ * one colour per token, per theme.
21
+ * @typedef {{ name?: string, font: string, radius: number, stroke: number, motion: Motion, light: Record<string, string>, dark: Record<string, string> }} Style
19
22
  */
20
23
 
21
24
  export const TOKENS = [
@@ -34,6 +37,7 @@ export const NEUTRAL = Object.freeze({
34
37
  font: 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif',
35
38
  radius: 10,
36
39
  stroke: 2,
40
+ motion: DEFAULT_MOTION,
37
41
  light: Object.freeze({
38
42
  bg: "#ffffff",
39
43
  surface: "#f3f4f6",
@@ -61,6 +65,33 @@ export function tok(name) {
61
65
  return `var(--mk-${name})`;
62
66
  }
63
67
 
68
+ /**
69
+ * A style's `motion` with any missing curve taken from the defaults. A curve
70
+ * is four numbers, as in CSS `cubic-bezier(x1, y1, x2, y2)`: x between 0 and 1
71
+ * (CSS's own rule) and y between 0 and 1 too, because no motion-kit curve
72
+ * overshoots.
73
+ * @param {any} motion
74
+ * @param {string} name the style's name, for the error
75
+ * @returns {Motion}
76
+ */
77
+ function normalizeMotion(motion, name) {
78
+ if (motion === undefined) return DEFAULT_MOTION;
79
+ if (!motion || typeof motion !== "object" || Array.isArray(motion)) throw new Error(`style "${name}": motion must be an object with enter and move curves`);
80
+ for (const key of Object.keys(motion)) {
81
+ if (key !== "enter" && key !== "move") throw new Error(`style "${name}": unknown motion curve "${key}" (known: enter, move)`);
82
+ }
83
+ const out = { enter: DEFAULT_MOTION.enter, move: DEFAULT_MOTION.move };
84
+ for (const key of /** @type {const} */ (["enter", "move"])) {
85
+ const c = motion[key];
86
+ if (c === undefined) continue;
87
+ if (!Array.isArray(c) || c.length !== 4 || !c.every((n) => Number.isFinite(n) && n >= 0 && n <= 1)) {
88
+ throw new Error(`style "${name}": motion.${key} must be four numbers from 0 to 1 (a cubic-bezier that does not overshoot), got ${JSON.stringify(c)}`);
89
+ }
90
+ out[key] = Object.freeze(/** @type {[number, number, number, number]} */ ([...c]));
91
+ }
92
+ return Object.freeze(out);
93
+ }
94
+
64
95
  /** Fill in any missing fields from NEUTRAL and validate token names. */
65
96
  export function normalizeStyle(style) {
66
97
  if (!style || style === "neutral") return NEUTRAL;
@@ -69,6 +100,7 @@ export function normalizeStyle(style) {
69
100
  font: style.font ?? NEUTRAL.font,
70
101
  radius: style.radius ?? NEUTRAL.radius,
71
102
  stroke: style.stroke ?? NEUTRAL.stroke,
103
+ motion: normalizeMotion(style.motion, style.name ?? "custom"),
72
104
  light: { ...NEUTRAL.light, ...(style.light ?? {}) },
73
105
  dark: { ...NEUTRAL.dark, ...(style.dark ?? style.light ?? {}) },
74
106
  };
@@ -0,0 +1,403 @@
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 { progress, easings } 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 { easeOut, easeStandard } = easings(style.motion);
337
+ const enter = (/** @type {number} */ r) => progress(t, rankIndex(r) * ENTER_GAP, ENTER, easeOut);
338
+ const out = [];
339
+ const drawn = edges.map((_, i) => progress(t, backward[i] ? fillStart(edgeStep[i]) - 0.1 : drawStart(edgeStep[i]), backward[i] ? DRAW - 0.05 : DRAW, easeStandard));
340
+ edges.forEach((e, i) => {
341
+ const shown = Math.min(enter(nodes[index.get(e.from) ?? 0].rank), enter(nodes[index.get(e.to) ?? 0].rank));
342
+ if (shown <= 0) return;
343
+ const { pts, line } = G.paths[i];
344
+ const common = { d: line.d, fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round", "stroke-dasharray": e.dashed ? "6 5" : undefined };
345
+ out.push(el("path", { ...common, stroke: tok("line"), "stroke-width": style.stroke, opacity: shown }));
346
+ // A dashed connector turns accent whole; a solid one draws on.
347
+ if (e.dashed) {
348
+ if (drawn[i] > 0) out.push(el("path", { ...common, stroke: tok("accent"), "stroke-width": style.stroke * 1.5, opacity: drawn[i] }));
349
+ } else {
350
+ const dash = drawOn(line.length, drawn[i]);
351
+ if (dash) out.push(el("path", { ...common, stroke: tok("accent"), "stroke-width": style.stroke * 1.5, ...dash }));
352
+ }
353
+ if (e.arrow !== false) {
354
+ const tip = pts[pts.length - 1];
355
+ const prev = pts[pts.length - 2];
356
+ const len = Math.hypot(tip.x - prev.x, tip.y - prev.y) || 1;
357
+ const ux = (tip.x - prev.x) / len;
358
+ const uy = (tip.y - prev.y) / len;
359
+ 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)}`;
360
+ const head = { d, fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round" };
361
+ const on = progress(t, (backward[i] ? fillStart(edgeStep[i]) - 0.1 : drawStart(edgeStep[i])) + DRAW * 0.6, DRAW * 0.3, easeStandard);
362
+ out.push(fade(shown * (1 - on), {}, el("path", { ...head, stroke: tok("line"), "stroke-width": style.stroke })));
363
+ out.push(fade(on, {}, el("path", { ...head, stroke: tok("accent"), "stroke-width": style.stroke * 1.5 })));
364
+ }
365
+ const tag = G.tags[i];
366
+ if (tag) {
367
+ const attrs = { x: tag.x, y: tag.y, "text-anchor": "middle", "dominant-baseline": "central", "font-size": G.fs, "font-weight": 500 };
368
+ 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]))));
369
+ }
370
+ });
371
+ nodes.forEach((node, i) => {
372
+ const shown = enter(node.rank);
373
+ if (shown <= 0) return;
374
+ const active = progress(t, fillStart(stepOf[i]), FILL, easeStandard);
375
+ const c = G.centres[i];
376
+ 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]);
377
+ const pending = el("g", {}, shapeAt(i, 0, style.radius, { fill: tok("surface"), stroke: tok("line"), "stroke-width": style.stroke }), label(tok("ink")));
378
+ const on = el("g", {}, shapeAt(i, 0, style.radius, { fill: tok("accent"), stroke: tok("accent"), "stroke-width": style.stroke }), label(tok("onAccent")));
379
+ const dy = (1 - shown) * 8;
380
+ out.push(fade(shown, { transform: dy > 0.004 ? translate(0, dy) : undefined }, fade(1 - active, {}, pending), fade(active, {}, on)));
381
+ });
382
+ // Emphasis: an outline on the node reached last.
383
+ order.forEach((v, k) => {
384
+ const opacity = progress(t, fillStart(k), FILL, easeOut) * (k + 1 < n ? 1 - progress(t, drawStart(k + 1), FILL, easeStandard) : 1);
385
+ if (opacity > 0) out.push(fade(opacity, {}, shapeAt(v, RING, style.radius, { fill: "none", stroke: tok("emphasis"), "stroke-width": style.stroke * 1.5 })));
386
+ });
387
+ return out.join("");
388
+ }
389
+
390
+ return {
391
+ id: `${spec.id}-${format.replace(":", "x")}`,
392
+ type: "flowchart",
393
+ format,
394
+ locale,
395
+ width: G.W,
396
+ height: G.H,
397
+ duration,
398
+ title: localize(spec.title, locale),
399
+ description: localize(spec.description, locale),
400
+ steps: order.map((v, k) => withId({ at: stepAt(k), label: labels[v], detail: localize(nodes[v].detail, locale) }, nodes[v].id)),
401
+ frame,
402
+ };
403
+ }
@@ -17,7 +17,7 @@
17
17
  * direction?: "out" | "in", // default "out"
18
18
  * fontSize?: number }
19
19
  */
20
- import { easeOut, easeStandard, progress, window01 } from "../motion.mjs";
20
+ import { progress, window01, easings } from "../motion.mjs";
21
21
  import { boxNode, FONT_MIN, maxFontSize, rectEdge } from "../parts.mjs";
22
22
  import { FORMATS, localize, withId } from "../scene.mjs";
23
23
  import { NEUTRAL, tok } from "../style.mjs";
@@ -166,6 +166,7 @@ export function hubSpoke(spec, { format = "16:9", locale = "en" } = {}) {
166
166
 
167
167
  /** @param {number} t @param {{style?: Style}} [ctx] */
168
168
  function frame(t, { style = NEUTRAL } = {}) {
169
+ const { easeOut, easeStandard } = easings(style.motion);
169
170
  const out = [];
170
171
  const sEnter = (i) => progress(t, spokeEnter(i), ENTER, easeOut);
171
172
  links.forEach((link, i) => {
@@ -10,6 +10,7 @@
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";
@@ -23,6 +24,7 @@ export const SCENE_TYPES = {
23
24
  stack,
24
25
  "state-machine": walk,
25
26
  "request-journey": walk,
27
+ flowchart,
26
28
  };
27
29
 
28
30
  export function createScene(spec, opts = {}) {
@@ -17,7 +17,7 @@
17
17
  * fontSize?: number }
18
18
  * Strings may be localized objects: { en: "...", nl: "..." }.
19
19
  */
20
- import { easeOut, easeStandard, progress } from "../motion.mjs";
20
+ import { progress, easings } from "../motion.mjs";
21
21
  import { circleNode, FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
22
22
  import { FORMATS, localize, withId } from "../scene.mjs";
23
23
  import { NEUTRAL, tok } from "../style.mjs";
@@ -157,6 +157,7 @@ export function sequence(spec, { format = "16:9", locale = "en" } = {}) {
157
157
 
158
158
  /** @param {number} t @param {{style?: Style}} [ctx] */
159
159
  function frame(t, { style = NEUTRAL } = {}) {
160
+ const { easeOut, easeStandard } = easings(style.motion);
160
161
  const enter = (k) => progress(t, k * ENTER_GAP, ENTER, easeOut);
161
162
  const active = (k) => progress(t, fillStart(k), FILL, easeStandard);
162
163
  const out = [];
@@ -21,7 +21,7 @@
21
21
  * Layout: one column of full-width layers with the rail on their right, in
22
22
  * every format; layers get taller (up to a limit) where the format has room.
23
23
  */
24
- import { easeOut, easeStandard, lerp, progress } from "../motion.mjs";
24
+ import { lerp, progress, easings } from "../motion.mjs";
25
25
  import { FONT_MIN, maxFontSize } from "../parts.mjs";
26
26
  import { FORMATS, localize, withId } from "../scene.mjs";
27
27
  import { NEUTRAL, tok } from "../style.mjs";
@@ -169,7 +169,7 @@ export function stack(spec, { format = "16:9", locale = "en" } = {}) {
169
169
  const stepAt = (k) => fillStart(k) + FILL;
170
170
  const duration = stepAt(n - 1) + TAIL;
171
171
 
172
- function packetY(t) {
172
+ function packetY(t, easeStandard) {
173
173
  let y = stops[0];
174
174
  for (let k = 0; k < n; k++) {
175
175
  const p = progress(t, hopStart(k), HOP, easeStandard);
@@ -183,6 +183,7 @@ export function stack(spec, { format = "16:9", locale = "en" } = {}) {
183
183
 
184
184
  /** @param {number} t @param {{style?: Style}} [ctx] */
185
185
  function frame(t, { style = NEUTRAL } = {}) {
186
+ const { easeOut, easeStandard } = easings(style.motion);
186
187
  const out = [];
187
188
  const { railX } = fitted;
188
189
  // Rail: draws on from the entry end while the layers rise; an arrowhead marks the exit.
@@ -194,7 +195,7 @@ export function stack(spec, { format = "16:9", locale = "en" } = {}) {
194
195
  const s = direction === "down" ? -1 : 1;
195
196
  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 }));
196
197
  }
197
- const y = packetY(t);
198
+ const y = packetY(t, easeStandard);
198
199
  if (Math.abs(y - entryY) > 0.5) out.push(vline(railX, entryY, y, { stroke: tok("accent"), "stroke-width": style.stroke * 1.5 }));
199
200
  fitted.boxes.forEach((b, li) => {
200
201
  const enter = progress(t, riseAt(li), RISE, easeOut);
@@ -23,7 +23,7 @@
23
23
  * below when they need the width (wide aspects and square); a vertical axis
24
24
  * with labels on the right (9:16, tall).
25
25
  */
26
- import { easeOut, easeStandard, lerp, progress, springSettleTime, springStep } from "../motion.mjs";
26
+ import { lerp, progress, springSettleTime, springStep, easings } from "../motion.mjs";
27
27
  import { FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
28
28
  import { FORMATS, localize, withId } from "../scene.mjs";
29
29
  import { NEUTRAL, tok } from "../style.mjs";
@@ -296,7 +296,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
296
296
  if (now && L.nowAt) stops.push({ to: along(L.nowAt), at: nowStart });
297
297
  const axisLen = L.dir === "h" ? ax.x1 - ax.x0 : ax.y1 - ax.y0;
298
298
 
299
- function accentEnd(t) {
299
+ function accentEnd(t, easeStandard) {
300
300
  let end = start;
301
301
  let from = start;
302
302
  for (const s of stops) {
@@ -312,6 +312,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
312
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 });
313
313
 
314
314
  function milestone(t, it, k, style) {
315
+ const { easeOut, easeStandard } = easings(style.motion);
315
316
  const p = L.at(k);
316
317
  const b = beat(k);
317
318
  const drop = progress(t, b + 0.05, DROP, easeOut);
@@ -355,6 +356,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
355
356
  }
356
357
 
357
358
  function nowMarker(t, style) {
359
+ const { easeOut } = easings(style.motion);
358
360
  if (!now || !L.nowAt || !L.nowPill) return "";
359
361
  const shown = progress(t, nowStart, NOW_FADE, easeOut);
360
362
  if (shown <= 0) return "";
@@ -372,6 +374,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
372
374
 
373
375
  /** @param {number} t @param {{style?: Style}} [ctx] */
374
376
  function frame(t, { style = NEUTRAL } = {}) {
377
+ const { easeOut, easeStandard } = easings(style.motion);
375
378
  const out = [];
376
379
  // Axis: pending line draws on; an arrowhead at its end shows the direction of time.
377
380
  const axisDash = drawOn(axisLen, progress(t, 0, AXIS, easeStandard));
@@ -381,7 +384,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
381
384
  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)}`;
382
385
  out.push(el("path", { d, fill: "none", stroke: tok("line"), "stroke-width": style.stroke, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: head }));
383
386
  }
384
- const end = accentEnd(t);
387
+ const end = accentEnd(t, easeStandard);
385
388
  if (end - start > 0.5) out.push(line(start, end, { stroke: tok("accent"), "stroke-width": style.stroke * 1.5 }));
386
389
  items.forEach((it, k) => out.push(milestone(t, it, k, style)));
387
390
  out.push(nowMarker(t, style));
@@ -3,7 +3,7 @@
3
3
  // SPDX-License-Identifier: MIT
4
4
  // Copyright (c) 2026 Ophir Radnitz
5
5
  /** Small, explicitly narrated graphs. Layout is computed once, never in frame(). */
6
- import { easeOut, easeStandard, progress, lerp } from "../motion.mjs";
6
+ import { progress, lerp, easings } from "../motion.mjs";
7
7
  import { FONT_MIN, maxFontSize } from "../parts.mjs";
8
8
  import { FORMATS, localize } from "../scene.mjs";
9
9
  import { NEUTRAL, tok } from "../style.mjs";
@@ -117,6 +117,7 @@ export function walk(spec, { format = "16:9", locale = "en" } = {}) {
117
117
  const duration = stepAt(route.length - 1) + 0.3;
118
118
  /** @param {number} t @param {{style?: Style}} [ctx] */
119
119
  function frame(t, { style = NEUTRAL } = {}) {
120
+ const { easeOut, easeStandard } = easings(style.motion);
120
121
  const entrance = progress(t, 0, 0.5, easeOut);
121
122
  const active = nodes.map(() => 0);
122
123
  active[visits[0]] = progress(t, 0.5, 0.2, easeStandard);