@liqweed/motion-kit 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +26 -6
  4. package/adapters/element/README.md +5 -0
  5. package/adapters/page/README.md +10 -0
  6. package/cli/motion-kit.mjs +14 -4
  7. package/docs/spec/technique.md +129 -51
  8. package/examples/checkout.json +104 -0
  9. package/examples/connection.json +80 -0
  10. package/examples/custom-pulse.scene.mjs +5 -0
  11. package/examples/incident.json +18 -0
  12. package/examples/player-states.json +97 -0
  13. package/examples/web-stack.json +17 -0
  14. package/lib/build.mjs +1 -1
  15. package/lib/check.mjs +215 -21
  16. package/lib/export.mjs +116 -7
  17. package/lib/gate.mjs +9 -7
  18. package/lib/load.mjs +15 -0
  19. package/package.json +6 -3
  20. package/runtime/kit.mjs +2 -2
  21. package/runtime/links.mjs +318 -0
  22. package/runtime/parts.mjs +15 -0
  23. package/runtime/patch.mjs +297 -0
  24. package/runtime/player.mjs +45 -2
  25. package/runtime/scene.mjs +24 -9
  26. package/runtime/style.mjs +65 -16
  27. package/runtime/types/hub-spoke.mjs +10 -8
  28. package/runtime/types/index.mjs +7 -0
  29. package/runtime/types/sequence.mjs +10 -8
  30. package/runtime/types/stack.mjs +230 -0
  31. package/runtime/types/timeline.mjs +407 -0
  32. package/runtime/types/walk.mjs +162 -0
  33. package/skills/animated-diagram/SKILL.md +28 -7
  34. package/skills/animated-diagram/references/custom-scenes.md +20 -1
  35. package/skills/animated-diagram/references/interactivity.md +129 -6
  36. package/skills/animated-diagram/references/motion-vocabulary.md +1 -1
  37. package/skills/animated-diagram/references/qc.md +3 -0
  38. package/skills/animated-diagram/references/scene-types.md +100 -4
  39. package/skills/animated-diagram/references/styles.md +55 -6
  40. package/skills/animated-diagram/references/technique.md +15 -6
  41. package/skills/motion-render/SKILL.md +31 -6
  42. package/skills/motion-render/references/formats.md +8 -8
  43. package/skills/motion-render/references/video.md +1 -1
  44. package/skills/project-logo/SKILL.md +15 -4
  45. package/styles/neutral.json +2 -2
@@ -0,0 +1,407 @@
1
+ /** @import { Style } from "../style.mjs" */
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) 2026 Ophir Radnitz
4
+ /**
5
+ * motion-kit · scene type "timeline".
6
+ *
7
+ * Helps the viewer understand: events in time, and where "now" falls among
8
+ * them. Storyboard: the axis draws on, then the milestones drop onto it in
9
+ * order; each event that has happened fills with the accent colour and the
10
+ * axis behind it turns accent, while planned events stay pending. Last, a
11
+ * "now" marker (the one emphasis element) settles on the axis after the last
12
+ * event that has happened.
13
+ *
14
+ * Spec:
15
+ * { type: "timeline", id, title, description,
16
+ * events: [{ when, label, detail?, id?, planned? }], // 2–8, in time order; id names the step
17
+ * now?: { label, detail?, id? }, // marker after the last event that is not planned
18
+ * fontSize?: number }
19
+ * `planned: true` marks an event still to come; planned events come after all
20
+ * the others. Strings may be localized objects: { en: "...", nl: "..." }.
21
+ *
22
+ * Layouts: a horizontal axis with labels below it, or alternating above and
23
+ * below when they need the width (wide aspects and square); a vertical axis
24
+ * with labels on the right (9:16, tall).
25
+ */
26
+ import { easeOut, easeStandard, lerp, progress, springSettleTime, springStep } from "../motion.mjs";
27
+ import { FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
28
+ import { FORMATS, localize, withId } from "../scene.mjs";
29
+ import { NEUTRAL, tok } from "../style.mjs";
30
+ import { drawOn, el, fade, num, text, translate } from "../svg.mjs";
31
+ import { wrapLabel } from "../wrap.mjs";
32
+
33
+ /** @import { Scene } from "../scene.mjs" */
34
+
35
+ // Timeline (seconds). Each beat ends (step) before the next one starts.
36
+ const AXIS = 0.6; // the axis draws on
37
+ const EXTEND = 0.3; // the accent axis reaches an event
38
+ const DROP = 0.35; // a milestone drops onto the axis
39
+ const LABEL = 0.3; // its label fades in
40
+ const FILL = 0.25; // a past event turns accent
41
+ const BEAT = 0.6; // one event: EXTEND/DROP/LABEL/FILL all end by 0.55
42
+ const SETTLE_AT = 0.55;
43
+ const NOW_OMEGA = 14; // the "now" marker settles on a critically damped spring
44
+ const NOW_FADE = 0.2;
45
+ const NOW_DROP = 18;
46
+ const TAIL = 0.4;
47
+
48
+ const PAD = 24;
49
+ const CHAR = 0.56;
50
+ const GAP = 16; // horizontal room between two labels on the same side
51
+ const DOT = 7; // milestone dot radius
52
+ const MAX_EVENTS = 8;
53
+
54
+ /**
55
+ * One localized event; `lines` is its label wrapped to the layout's budget.
56
+ * @typedef {{ label: string, when: string, planned: boolean, detail: string, id?: string, lines?: string[] }} Item
57
+ */
58
+ /**
59
+ * The localized "now" marker; `index` is the number of events before it.
60
+ * @typedef {{ label: string, detail: string, id?: string, index: number }} Now
61
+ */
62
+
63
+ /** Size of the "now" pill for a label at font size `fs`. */
64
+ function pill(label, fs) {
65
+ const h = Math.round(fs * 1.25 + 10);
66
+ return { w: Math.round(label.length * fs * CHAR + 22), h, fs };
67
+ }
68
+
69
+ function overlaps(a, b, gap = 4) {
70
+ return a.x < b.x + b.w + gap && b.x < a.x + a.w + gap && a.y < b.y + b.h + gap && b.y < a.y + a.h + gap;
71
+ }
72
+
73
+ /**
74
+ * Horizontal axis. `mode` "below" puts every label under the axis; "alternate"
75
+ * puts even events below and odd ones above, which doubles each label's width.
76
+ */
77
+ function horizontal(f, items, now, fs, mode) {
78
+ const W = f.width;
79
+ const fixed = f.height > 0;
80
+ const n = items.length;
81
+ const whenFs = Math.max(FONT_MIN, fs - 3);
82
+ const lineH = fs * 1.25;
83
+ const whenH = whenFs * 1.25;
84
+ const nowU = now ? now.index - 0.5 : null; // between two events, or half a cell beyond an end
85
+ const uMin = Math.min(0, nowU ?? 0);
86
+ const uMax = Math.max(n - 1, nowU ?? 0);
87
+ const U = uMax - uMin;
88
+ const sides = mode === "alternate" ? 2 : 1;
89
+ // Same-side labels sit `sides` cells apart; the outermost labels end at the padding.
90
+ let cell = (W - 2 * PAD + GAP) / (U + sides);
91
+ cell = Math.min(cell, fs * (sides === 2 ? 9 : 13));
92
+ const labelW = sides * cell - GAP;
93
+ const span = U * cell + labelW;
94
+ const x0 = (W - span) / 2 + labelW / 2 - uMin * cell;
95
+ const xs = items.map((_, k) => x0 + k * cell);
96
+ const maxChars = Math.floor(labelW / (fs * CHAR));
97
+ const whenChars = Math.floor(labelW / (whenFs * CHAR));
98
+ const nowPill = now ? pill(now.label, whenFs) : null;
99
+ const stem = Math.max(28, (nowPill?.h ?? 0) / 2 + 14);
100
+ const blockH = whenH + 4 + 2 * lineH; // budget: one "when" line, two label lines
101
+ const reach = stem + 6 + blockH; // axis → far edge of a label block
102
+ const above = mode === "alternate" ? reach : Math.max(nowPill ? nowPill.h / 2 : 0, DOT + NOW_DROP);
103
+ const contentH = above + reach;
104
+ const H = fixed ? f.height : Math.ceil(contentH + 2 * PAD);
105
+ const axisY = (H - contentH) / 2 + above;
106
+ const axisX0 = Math.max(PAD, x0 + uMin * cell - cell / 2);
107
+ const axisX1 = Math.min(W - PAD, x0 + uMax * cell + cell / 2);
108
+ return {
109
+ dir: "h", W, H, fs, whenFs, lineH, whenH, maxChars, whenChars, maxLines: 2, labelW, cell, stem,
110
+ axis: { x0: axisX0, y0: axisY, x1: axisX1, y1: axisY },
111
+ at: (k) => ({ x: xs[k], y: axisY }),
112
+ nowAt: nowU == null ? null : { x: x0 + nowU * cell, y: axisY },
113
+ side: (k) => (mode === "alternate" && k % 2 === 1 ? -1 : 1),
114
+ nowPill,
115
+ };
116
+ }
117
+
118
+ /** Vertical axis near the left edge, labels on the right, "now" in its own slot. */
119
+ function vertical(f, items, now, fs) {
120
+ const W = f.width;
121
+ const fixed = f.height > 0;
122
+ const n = items.length;
123
+ const whenFs = Math.max(FONT_MIN, fs - 3);
124
+ const lineH = fs * 1.25;
125
+ const whenH = whenFs * 1.25;
126
+ const axisX = PAD + DOT + 4;
127
+ const labelX = axisX + DOT + 14;
128
+ const labelW = W - PAD - labelX;
129
+ const maxChars = Math.floor(labelW / (fs * CHAR));
130
+ const whenChars = Math.floor(labelW / (whenFs * CHAR));
131
+ const nowPill = now ? pill(now.label, whenFs) : null;
132
+ // A row is as tall as its label (two lines until the labels are wrapped).
133
+ const rowH = (it) => whenH + 4 + (it.lines?.length ?? 2) * lineH;
134
+ // Slots in order: events, with the "now" slot inserted at its place.
135
+ const slots = items.map((it, k) => ({ k, h: rowH(it) }));
136
+ if (now && nowPill) slots.splice(now.index, 0, { k: -1, h: nowPill.h });
137
+ const used = slots.reduce((s, x) => s + x.h, 0);
138
+ const gap = fixed ? Math.max(16, Math.min(fs * 2.4, (f.height - 2 * PAD - 2 * DOT - used) / Math.max(1, slots.length - 1))) : 18;
139
+ const contentH = used + gap * (slots.length - 1);
140
+ const H = fixed ? f.height : Math.ceil(contentH + 2 * PAD + 2 * DOT);
141
+ let y = (H - contentH) / 2;
142
+ const ys = new Array(n);
143
+ /** @type {number | null} */
144
+ let nowY = null;
145
+ for (const s of slots) {
146
+ // An event's dot sits on its "when" line; the pill is centred in its slot.
147
+ if (s.k < 0) nowY = y + s.h / 2;
148
+ else ys[s.k] = y + whenH / 2;
149
+ y += s.h + gap;
150
+ }
151
+ const first = Math.min(ys[0], nowY ?? Infinity);
152
+ const last = Math.max(ys[n - 1], nowY ?? -Infinity);
153
+ return {
154
+ dir: "v", W, H, fs, whenFs, lineH, whenH, maxChars, whenChars, maxLines: 2, labelW, labelX,
155
+ axis: { x0: axisX, y0: Math.max(PAD / 2, first - gap), x1: axisX, y1: Math.min(H - PAD / 2, last + rowH(items[n - 1]) + gap / 2) },
156
+ at: (k) => ({ x: axisX, y: ys[k] }),
157
+ nowAt: nowY == null ? null : { x: axisX, y: nowY },
158
+ side: () => 1,
159
+ nowPill,
160
+ };
161
+ }
162
+
163
+ /** Label blocks, dots and the pill as boxes, for the overlap check. */
164
+ function boxes(L, items) {
165
+ const out = [];
166
+ items.forEach((it, k) => {
167
+ const p = L.at(k);
168
+ const w = Math.max(it.when.length * L.whenFs, Math.max(...it.lines.map((l) => l.length)) * L.fs) * CHAR;
169
+ const h = L.whenH + 4 + it.lines.length * L.lineH;
170
+ out.push({ x: p.x - DOT, y: p.y - DOT, w: 2 * DOT, h: 2 * DOT, what: "dot" });
171
+ if (L.dir === "h") {
172
+ const top = L.side(k) > 0 ? p.y + L.stem + 6 : p.y - L.stem - 6 - h;
173
+ out.push({ x: p.x - w / 2, y: top, w, h, what: `label "${it.label}"` });
174
+ } else {
175
+ out.push({ x: L.labelX, y: p.y - L.whenH / 2, w, h, what: `label "${it.label}"` });
176
+ }
177
+ });
178
+ if (L.nowAt && L.nowPill) {
179
+ const { w, h } = L.nowPill;
180
+ const x = L.dir === "h" ? L.nowAt.x - w / 2 : L.nowAt.x - h / 2;
181
+ out.push({ x, y: L.nowAt.y - h / 2, w, h, what: "the now marker" });
182
+ }
183
+ return out;
184
+ }
185
+
186
+ function layoutProblem(L, items) {
187
+ const all = boxes(L, items);
188
+ for (let i = 0; i < all.length; i++) {
189
+ const b = all[i];
190
+ if (b.x < 0 || b.y < 0 || b.x + b.w > L.W + 0.01 || b.y + b.h > L.H + 0.01) return `${b.what} falls outside the canvas`;
191
+ for (let j = i + 1; j < all.length; j++) {
192
+ if (b.what === "dot" && all[j].what === "dot") continue;
193
+ if (overlaps(b, all[j])) return `${b.what} overlaps ${all[j].what}`;
194
+ }
195
+ }
196
+ return null;
197
+ }
198
+
199
+ /**
200
+ * The validated, localized events and "now" of a spec.
201
+ * @param {any} spec
202
+ * @param {string} locale
203
+ */
204
+ function readSpec(spec, locale) {
205
+ const name = `timeline "${spec.id}"`;
206
+ const events = spec.events;
207
+ if (!Array.isArray(events)) throw new Error(`${name}: needs "events", a list of { when, label }`);
208
+ if (events.length < 2 || events.length > MAX_EVENTS) throw new Error(`${name}: needs 2–${MAX_EVENTS} events, got ${events.length}`);
209
+ let seenPlanned = false;
210
+ const items = events.map((e, i) => {
211
+ const label = localize(e?.label, locale);
212
+ const when = localize(e?.when, locale);
213
+ if (!label) throw new Error(`${name}: event ${i + 1} needs a "label"`);
214
+ if (!when) throw new Error(`${name}: event ${i + 1} ("${label}") needs a "when", e.g. "09:02" or "Q3 2026"`);
215
+ if (e.planned !== undefined && typeof e.planned !== "boolean") throw new Error(`${name}: event ${i + 1} ("${label}"): "planned" must be true or false`);
216
+ const planned = e.planned === true;
217
+ if (seenPlanned && !planned) throw new Error(`${name}: event ${i + 1} ("${label}") has happened but comes after a planned event; planned events go last`);
218
+ seenPlanned ||= planned;
219
+ return { label, when, planned, detail: localize(e.detail, locale), id: e.id };
220
+ });
221
+ /** @type {Now | null} */
222
+ let now = null;
223
+ if (spec.now != null) {
224
+ const label = localize(spec.now.label, locale);
225
+ if (!label) throw new Error(`${name}: "now" needs a "label", e.g. "Now" or "Today"`);
226
+ const index = items.filter((it) => !it.planned).length;
227
+ now = { label, detail: localize(spec.now.detail, locale), id: spec.now.id, index };
228
+ } else if (seenPlanned) {
229
+ throw new Error(`${name}: planned events need a "now" marker to separate them from the past`);
230
+ }
231
+ return { items, now };
232
+ }
233
+
234
+ /**
235
+ * Largest font (≤ max) at which the layout fits and every label wraps. At one
236
+ * font size, labels below the axis win over alternating ones unless
237
+ * alternating needs fewer lines (no orphaned words).
238
+ */
239
+ function fit(f, items, now, maxFs, name) {
240
+ const narrow = f.name === "tall" || (f.height > 0 && f.width / f.height < 0.8);
241
+ let why = "";
242
+ for (let fs = maxFs; fs >= FONT_MIN; fs--) {
243
+ /** @type {{ L: any, items: Item[], lines: number } | null} */
244
+ let best = null;
245
+ for (const mode of narrow ? ["v"] : ["below", "alternate"]) {
246
+ let L = mode === "v" ? vertical(f, items, now, fs) : horizontal(f, items, now, fs, mode);
247
+ try {
248
+ const wrapped = items.map((it) => {
249
+ wrapLabel(it.when, L.whenChars, 1);
250
+ return { ...it, lines: wrapLabel(it.label, L.maxChars, L.maxLines) };
251
+ });
252
+ if (now) wrapLabel(now.label, L.dir === "h" ? Math.floor((L.cell - 2 * DOT - 12) / (L.whenFs * CHAR)) : L.maxChars, 1);
253
+ if (mode === "v") L = vertical(f, wrapped, now, fs);
254
+ const problem = layoutProblem(L, wrapped);
255
+ if (problem) {
256
+ why = problem;
257
+ continue;
258
+ }
259
+ const lines = wrapped.reduce((s, it) => s + it.lines.length, 0);
260
+ if (!best || lines < best.lines) best = { L, items: wrapped, lines };
261
+ } catch (e) {
262
+ why = e instanceof Error ? e.message : String(e);
263
+ }
264
+ }
265
+ if (best) return best;
266
+ }
267
+ throw new Error(`${name}: ${items.length} events do not fit format ${f.name} at ≥ ${FONT_MIN}px (${why}); use fewer events, shorter labels or a larger format`);
268
+ }
269
+
270
+ /**
271
+ * Build a timeline scene from its spec.
272
+ * @param {any} spec
273
+ * @param {{ format?: string | { name: string, width: number, height: number }, locale?: string }} [opts]
274
+ * @returns {Scene}
275
+ */
276
+ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
277
+ const f = typeof format === "string" ? { name: format, ...FORMATS[format] } : format;
278
+ if (!f.width) throw new Error(`unknown format "${format}"`);
279
+ const { items: raw, now } = readSpec(spec, locale);
280
+ const n = raw.length;
281
+ const maxFs = maxFontSize(spec, f.height > 0 ? 22 : 16, `timeline "${spec.id}"`);
282
+ const { L, items } = fit(f, raw, now, maxFs, `timeline "${spec.id}"`);
283
+
284
+ // Event k's beat; then the "now" beat.
285
+ const beat = (k) => AXIS + 0.1 + k * BEAT;
286
+ const stepAt = (k) => beat(k) + SETTLE_AT;
287
+ const nowStart = beat(n);
288
+ const nowAt = nowStart + springSettleTime(NOW_OMEGA) + 0.01;
289
+ const duration = (now ? nowAt : stepAt(n - 1)) + TAIL;
290
+
291
+ // The accent axis: from the axis start through every past event, then to "now".
292
+ const ax = L.axis;
293
+ const along = (p) => (L.dir === "h" ? p.x : p.y);
294
+ const start = L.dir === "h" ? ax.x0 : ax.y0;
295
+ const stops = items.flatMap((it, k) => (it.planned ? [] : [{ to: along(L.at(k)), at: beat(k) }]));
296
+ if (now && L.nowAt) stops.push({ to: along(L.nowAt), at: nowStart });
297
+ const axisLen = L.dir === "h" ? ax.x1 - ax.x0 : ax.y1 - ax.y0;
298
+
299
+ function accentEnd(t) {
300
+ let end = start;
301
+ let from = start;
302
+ for (const s of stops) {
303
+ const p = progress(t, s.at, EXTEND, easeStandard);
304
+ if (p <= 0) break;
305
+ end = lerp(from, s.to, p);
306
+ from = s.to;
307
+ }
308
+ return end;
309
+ }
310
+
311
+ const line = (a, b, attrs) =>
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
+
314
+ function milestone(t, it, k, style) {
315
+ const p = L.at(k);
316
+ const b = beat(k);
317
+ const drop = progress(t, b + 0.05, DROP, easeOut);
318
+ if (drop <= 0) return "";
319
+ const shown = progress(t, b + 0.15, LABEL, easeOut);
320
+ const active = it.planned ? 0 : progress(t, b + 0.3, FILL, easeStandard);
321
+ const out = [];
322
+ const s = L.side(k);
323
+ if (L.dir === "h") {
324
+ // Stem from the dot to the label block, drawn as the label arrives.
325
+ const y0 = p.y + s * (DOT + 3);
326
+ const y1 = p.y + s * L.stem;
327
+ const len = Math.abs(y1 - y0);
328
+ const dash = drawOn(len, progress(t, b + 0.15, LABEL, easeStandard));
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 }));
330
+ }
331
+ const dy = (1 - drop) * -14;
332
+ const dot = (fill, stroke) => el("circle", { cx: p.x, cy: p.y, r: DOT, fill, stroke, "stroke-width": style.stroke });
333
+ out.push(
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")))),
335
+ );
336
+ // Label block: the "when" line (muted) and the wrapped label (muted → ink once it has happened).
337
+ const h = L.whenH + 4 + it.lines.length * L.lineH;
338
+ let x;
339
+ let top;
340
+ let anchor;
341
+ if (L.dir === "h") {
342
+ x = p.x;
343
+ top = s > 0 ? p.y + L.stem + 6 : p.y - L.stem - 6 - h;
344
+ anchor = "middle";
345
+ } else {
346
+ x = L.labelX;
347
+ top = p.y - L.whenH / 2;
348
+ anchor = "start";
349
+ }
350
+ if (shown > 0) {
351
+ out.push(fade(shown, {}, text({ x, y: top, "text-anchor": anchor, "dominant-baseline": "hanging", "font-size": L.whenFs, "font-weight": 600, fill: tok("muted") }, it.when)));
352
+ out.push(stateLabel({ x, y: top + L.whenH + 4, lines: it.lines, fontSize: L.fs, anchor, baseline: "hanging", enter: shown, active }));
353
+ }
354
+ return out.join("");
355
+ }
356
+
357
+ function nowMarker(t, style) {
358
+ if (!now || !L.nowAt || !L.nowPill) return "";
359
+ const shown = progress(t, nowStart, NOW_FADE, easeOut);
360
+ if (shown <= 0) return "";
361
+ const dy = -(1 - springStep(t - nowStart, NOW_OMEGA)) * NOW_DROP;
362
+ const { w, h, fs } = L.nowPill;
363
+ const x = L.dir === "h" ? L.nowAt.x - w / 2 : L.nowAt.x - h / 2;
364
+ const y = L.nowAt.y - h / 2;
365
+ return fade(
366
+ shown,
367
+ { transform: Math.abs(dy) > 0.004 ? translate(0, dy) : undefined },
368
+ el("rect", { x, y, width: w, height: h, rx: h / 2, fill: tok("bg"), stroke: tok("emphasis"), "stroke-width": style.stroke * 1.25 }),
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),
370
+ );
371
+ }
372
+
373
+ /** @param {number} t @param {{style?: Style}} [ctx] */
374
+ function frame(t, { style = NEUTRAL } = {}) {
375
+ const out = [];
376
+ // Axis: pending line draws on; an arrowhead at its end shows the direction of time.
377
+ const axisDash = drawOn(axisLen, progress(t, 0, AXIS, easeStandard));
378
+ if (axisDash) out.push(line(start, L.dir === "h" ? ax.x1 : ax.y1, { stroke: tok("line"), "stroke-width": style.stroke, ...axisDash }));
379
+ const head = progress(t, AXIS - 0.15, 0.2, easeOut);
380
+ if (head > 0) {
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)}`;
382
+ out.push(el("path", { d, fill: "none", stroke: tok("line"), "stroke-width": style.stroke, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: head }));
383
+ }
384
+ const end = accentEnd(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));
388
+ return out.join("");
389
+ }
390
+
391
+ const steps = items.map((it, k) => withId({ at: stepAt(k), label: it.label, detail: it.detail }, it.id));
392
+ if (now) steps.push(withId({ at: nowAt, label: now.label, detail: now.detail }, now.id));
393
+
394
+ return {
395
+ id: `${spec.id}-${f.name.replace(":", "x")}`,
396
+ type: "timeline",
397
+ format: f.name,
398
+ locale,
399
+ width: L.W,
400
+ height: L.H,
401
+ duration,
402
+ title: localize(spec.title, locale),
403
+ description: localize(spec.description, locale),
404
+ steps,
405
+ frame,
406
+ };
407
+ }
@@ -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
+ }
@@ -11,12 +11,32 @@ clock; exporters sample exact times; video samples `t = f / fps`. Read
11
11
 
12
12
  ## Locate the toolkit
13
13
 
14
+ `$MK` is where the toolkit's files are (examples, styles, `brand/`); `mk` runs
15
+ the CLI. Take the first that works:
16
+
17
+ 1. `MOTION_KIT_HOME`: a clone or install the user chose (run `npm install`
18
+ there for PNG and video).
19
+ 2. The npm package through `npx`, at the version of these skills. `npx`
20
+ installs the PNG renderer with it.
21
+ 3. The plugin copy, two levels above this skill: `check`, `build`, `bake` and
22
+ SVG `export` work; PNG and video do not.
23
+
14
24
  ```bash
15
- MK="$HOME/workspace/motion-kit" # canonical clone (has node_modules)
16
- [ -d "$MK" ] || MK="$(cd "<this skill's base directory>/../.." && pwd)" # plugin copy
17
- node "$MK/cli/motion-kit.mjs" --help
25
+ PLUGIN="$(cd -P "<this skill's base directory>" && cd ../.. && pwd -P)" # -P: the base may be a symlink to a clone
26
+ V="$(node -p "require(process.argv[1] + '/package.json').version" "$PLUGIN")"
27
+ if [ -n "${MOTION_KIT_HOME:-}" ]; then
28
+ MK="$MOTION_KIT_HOME"; mk() { node "$MK/cli/motion-kit.mjs" "$@"; }
29
+ elif npx -y "@liqweed/motion-kit@$V" --help >/dev/null 2>&1; then
30
+ MK="$PLUGIN"; mk() { npx -y "@liqweed/motion-kit@$V" "$@"; }
31
+ else
32
+ MK="$PLUGIN"; mk() { node "$MK/cli/motion-kit.mjs" "$@"; }
33
+ fi
34
+ mk --help
18
35
  ```
19
- Node ≥ 22. PNG/video need `@resvg/resvg-js` (`npm install` in `$MK`) and `ffmpeg`.
36
+ Node ≥ 22. PNG and video need `@resvg/resvg-js`; video also needs `ffmpeg`.
37
+ When one is missing, the CLI names it: install `@resvg/resvg-js` with
38
+ `npm install` in `$MOTION_KIT_HOME` (or use the `npx` route), and `ffmpeg`
39
+ from the system's package manager (`brew install ffmpeg`, `apt install ffmpeg`).
20
40
 
21
41
  ## Workflow
22
42
 
@@ -33,7 +53,7 @@ Node ≥ 22. PNG/video need `@resvg/resvg-js` (`npm install` in `$MK`) and `ffmp
33
53
  Write the spec, then render the step contact sheet and show it:
34
54
  `motion-kit export spec.json -o <scratch>/sb --png --qc` → open `index.html`
35
55
  or show the PNGs. Get a yes on the *story* before polishing.
36
- 3. **Build.** Spec-driven types first (`sequence`, `hub-spoke`). Only write a
56
+ 3. **Build.** Spec-driven types first (`sequence`, `hub-spoke`, `timeline`, `stack`). Only write a
37
57
  custom scene module when no type fits (`references/custom-scenes.md`).
38
58
  4. **Gate.** `motion-kit check spec.json` must pass in every format/locale
39
59
  shipped: deterministic, settled steps, rounded numbers, token-only colours,
@@ -47,12 +67,13 @@ Node ≥ 22. PNG/video need `@resvg/resvg-js` (`npm install` in `$MK`) and `ffmp
47
67
  ## Hard rules
48
68
 
49
69
  - Plays once and holds the final frame (loops only for ambient status displays).
50
- - One entrance ≤ 600 ms, siblings staggered 80–150 ms, whole scene ≤ ~8 s.
70
+ - Motion guidance (reviewed, not mechanically timed): one entrance ≤ 600 ms, siblings staggered 80–150 ms, aim for a whole scene ≤ 8 s. The gate’s hard duration limit is 12 s.
51
71
  - No bounce/elastic, no parallax, no ambient motion inside an explainer.
52
72
  - Every motion must answer "what does this help the viewer understand?".
53
73
  - Skeleton first, then fill: show the whole structure, then walk through it.
54
74
  - One emphasis colour, one emphasis element.
55
- - Step frames are settled: the next motion starts at or after the step's `at`.
75
+ - Step frames are settled: motion comes to rest by the step's `at`, and the
76
+ next motion starts no earlier than 50 ms after it.
56
77
  - Long text belongs in HTML captions (`detail`), not in the SVG.
57
78
  - Always a pause control (WCAG 2.2.2); reduced motion = final frame, no autoplay.
58
79
  - No `Date`, `Math.random`, `performance.now` inside a scene.
@@ -30,7 +30,12 @@ Rules:
30
30
 
31
31
  - Pure: the frame depends only on `t` and constants. No clock, no randomness,
32
32
  no module-level mutable state.
33
- - Colours only via `tok()`; numbers in strings via `num()`.
33
+ - Colours only via `tok()`; numbers in strings via `num()`. Named colours
34
+ (`"red"`) are literals too.
35
+ - Drawing a token pair the scene types don't (accent on surface, emphasis on
36
+ onAccent)? Declare it so the gate checks the style against it:
37
+ `contrastPairs: [{ fg: "accent", bg: "surface", min: 3, use: "bar on its track" }]`
38
+ (4.5 for text, 3 for shapes; `references/styles.md`).
34
39
  - Use `fade()`/`el()` so invisible elements disappear; `drawOn()` for lines.
35
40
  - Ids (clip paths, gradients, masks, markers, filters) MUST be built from
36
41
  `idPrefix`, the second argument's field: `${idPrefix}-clip`, referenced as
@@ -104,3 +109,17 @@ export default function make({ format = "1:1", kit }) {
104
109
  Every command supports this, `motion-kit build` included (it bundles the whole
105
110
  runtime and passes it as `kit`). A module that imports instead must use
106
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.