@liqweed/motion-kit 0.4.0 → 0.5.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 (38) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +13 -5
  4. package/adapters/element/README.md +5 -0
  5. package/adapters/page/README.md +5 -0
  6. package/cli/motion-kit.mjs +9 -3
  7. package/docs/spec/technique.md +93 -30
  8. package/examples/custom-pulse.scene.mjs +3 -0
  9. package/examples/incident.json +18 -0
  10. package/examples/web-stack.json +17 -0
  11. package/lib/build.mjs +1 -1
  12. package/lib/check.mjs +207 -16
  13. package/lib/export.mjs +104 -7
  14. package/lib/gate.mjs +5 -3
  15. package/package.json +6 -3
  16. package/runtime/kit.mjs +2 -2
  17. package/runtime/links.mjs +314 -0
  18. package/runtime/parts.mjs +15 -0
  19. package/runtime/patch.mjs +297 -0
  20. package/runtime/player.mjs +5 -1
  21. package/runtime/scene.mjs +3 -1
  22. package/runtime/style.mjs +62 -16
  23. package/runtime/types/hub-spoke.mjs +2 -2
  24. package/runtime/types/index.mjs +4 -0
  25. package/runtime/types/sequence.mjs +2 -2
  26. package/runtime/types/stack.mjs +227 -0
  27. package/runtime/types/timeline.mjs +405 -0
  28. package/skills/animated-diagram/SKILL.md +27 -6
  29. package/skills/animated-diagram/references/custom-scenes.md +6 -1
  30. package/skills/animated-diagram/references/interactivity.md +111 -6
  31. package/skills/animated-diagram/references/qc.md +3 -0
  32. package/skills/animated-diagram/references/scene-types.md +45 -2
  33. package/skills/animated-diagram/references/styles.md +45 -5
  34. package/skills/animated-diagram/references/technique.md +9 -4
  35. package/skills/motion-render/SKILL.md +24 -6
  36. package/skills/motion-render/references/formats.md +8 -8
  37. package/skills/project-logo/SKILL.md +15 -4
  38. package/styles/neutral.json +2 -2
@@ -0,0 +1,405 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · scene type "timeline".
5
+ *
6
+ * Helps the viewer understand: events in time, and where "now" falls among
7
+ * them. Storyboard: the axis draws on, then the milestones drop onto it in
8
+ * order; each event that has happened fills with the accent colour and the
9
+ * axis behind it turns accent, while planned events stay pending. Last, a
10
+ * "now" marker (the one emphasis element) settles on the axis after the last
11
+ * event that has happened.
12
+ *
13
+ * Spec:
14
+ * { type: "timeline", id, title, description,
15
+ * events: [{ when, label, detail?, id?, planned? }], // 2–8, in time order; id names the step
16
+ * now?: { label, detail?, id? }, // marker after the last event that is not planned
17
+ * fontSize?: number }
18
+ * `planned: true` marks an event still to come; planned events come after all
19
+ * the others. Strings may be localized objects: { en: "...", nl: "..." }.
20
+ *
21
+ * Layouts: a horizontal axis with labels below it, or alternating above and
22
+ * below when they need the width (wide aspects and square); a vertical axis
23
+ * with labels on the right (9:16, tall).
24
+ */
25
+ import { easeOut, easeStandard, lerp, progress, springSettleTime, springStep } from "../motion.mjs";
26
+ import { FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
27
+ import { FORMATS, localize, withId } from "../scene.mjs";
28
+ import { tok } from "../style.mjs";
29
+ import { drawOn, el, fade, num, text, translate } from "../svg.mjs";
30
+ import { wrapLabel } from "../wrap.mjs";
31
+
32
+ /** @import { Scene } from "../scene.mjs" */
33
+
34
+ // Timeline (seconds). Each beat ends (step) before the next one starts.
35
+ const AXIS = 0.6; // the axis draws on
36
+ const EXTEND = 0.3; // the accent axis reaches an event
37
+ const DROP = 0.35; // a milestone drops onto the axis
38
+ const LABEL = 0.3; // its label fades in
39
+ const FILL = 0.25; // a past event turns accent
40
+ const BEAT = 0.6; // one event: EXTEND/DROP/LABEL/FILL all end by 0.55
41
+ const SETTLE_AT = 0.55;
42
+ const NOW_OMEGA = 14; // the "now" marker settles on a critically damped spring
43
+ const NOW_FADE = 0.2;
44
+ const NOW_DROP = 18;
45
+ const TAIL = 0.4;
46
+
47
+ const PAD = 24;
48
+ const CHAR = 0.56;
49
+ const GAP = 16; // horizontal room between two labels on the same side
50
+ const DOT = 7; // milestone dot radius
51
+ const MAX_EVENTS = 8;
52
+
53
+ /**
54
+ * One localized event; `lines` is its label wrapped to the layout's budget.
55
+ * @typedef {{ label: string, when: string, planned: boolean, detail: string, id?: string, lines?: string[] }} Item
56
+ */
57
+ /**
58
+ * The localized "now" marker; `index` is the number of events before it.
59
+ * @typedef {{ label: string, detail: string, id?: string, index: number }} Now
60
+ */
61
+
62
+ /** Size of the "now" pill for a label at font size `fs`. */
63
+ function pill(label, fs) {
64
+ const h = Math.round(fs * 1.25 + 10);
65
+ return { w: Math.round(label.length * fs * CHAR + 22), h, fs };
66
+ }
67
+
68
+ function overlaps(a, b, gap = 4) {
69
+ 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;
70
+ }
71
+
72
+ /**
73
+ * Horizontal axis. `mode` "below" puts every label under the axis; "alternate"
74
+ * puts even events below and odd ones above, which doubles each label's width.
75
+ */
76
+ function horizontal(f, items, now, fs, mode) {
77
+ const W = f.width;
78
+ const fixed = f.height > 0;
79
+ const n = items.length;
80
+ const whenFs = Math.max(FONT_MIN, fs - 3);
81
+ const lineH = fs * 1.25;
82
+ const whenH = whenFs * 1.25;
83
+ const nowU = now ? now.index - 0.5 : null; // between two events, or half a cell beyond an end
84
+ const uMin = Math.min(0, nowU ?? 0);
85
+ const uMax = Math.max(n - 1, nowU ?? 0);
86
+ const U = uMax - uMin;
87
+ const sides = mode === "alternate" ? 2 : 1;
88
+ // Same-side labels sit `sides` cells apart; the outermost labels end at the padding.
89
+ let cell = (W - 2 * PAD + GAP) / (U + sides);
90
+ cell = Math.min(cell, fs * (sides === 2 ? 9 : 13));
91
+ const labelW = sides * cell - GAP;
92
+ const span = U * cell + labelW;
93
+ const x0 = (W - span) / 2 + labelW / 2 - uMin * cell;
94
+ const xs = items.map((_, k) => x0 + k * cell);
95
+ const maxChars = Math.floor(labelW / (fs * CHAR));
96
+ const whenChars = Math.floor(labelW / (whenFs * CHAR));
97
+ const nowPill = now ? pill(now.label, whenFs) : null;
98
+ const stem = Math.max(28, (nowPill?.h ?? 0) / 2 + 14);
99
+ const blockH = whenH + 4 + 2 * lineH; // budget: one "when" line, two label lines
100
+ const reach = stem + 6 + blockH; // axis → far edge of a label block
101
+ const above = mode === "alternate" ? reach : Math.max(nowPill ? nowPill.h / 2 : 0, DOT + NOW_DROP);
102
+ const contentH = above + reach;
103
+ const H = fixed ? f.height : Math.ceil(contentH + 2 * PAD);
104
+ const axisY = (H - contentH) / 2 + above;
105
+ const axisX0 = Math.max(PAD, x0 + uMin * cell - cell / 2);
106
+ const axisX1 = Math.min(W - PAD, x0 + uMax * cell + cell / 2);
107
+ return {
108
+ dir: "h", W, H, fs, whenFs, lineH, whenH, maxChars, whenChars, maxLines: 2, labelW, cell, stem,
109
+ axis: { x0: axisX0, y0: axisY, x1: axisX1, y1: axisY },
110
+ at: (k) => ({ x: xs[k], y: axisY }),
111
+ nowAt: nowU == null ? null : { x: x0 + nowU * cell, y: axisY },
112
+ side: (k) => (mode === "alternate" && k % 2 === 1 ? -1 : 1),
113
+ nowPill,
114
+ };
115
+ }
116
+
117
+ /** Vertical axis near the left edge, labels on the right, "now" in its own slot. */
118
+ function vertical(f, items, now, fs) {
119
+ const W = f.width;
120
+ const fixed = f.height > 0;
121
+ const n = items.length;
122
+ const whenFs = Math.max(FONT_MIN, fs - 3);
123
+ const lineH = fs * 1.25;
124
+ const whenH = whenFs * 1.25;
125
+ const axisX = PAD + DOT + 4;
126
+ const labelX = axisX + DOT + 14;
127
+ const labelW = W - PAD - labelX;
128
+ const maxChars = Math.floor(labelW / (fs * CHAR));
129
+ const whenChars = Math.floor(labelW / (whenFs * CHAR));
130
+ const nowPill = now ? pill(now.label, whenFs) : null;
131
+ // A row is as tall as its label (two lines until the labels are wrapped).
132
+ const rowH = (it) => whenH + 4 + (it.lines?.length ?? 2) * lineH;
133
+ // Slots in order: events, with the "now" slot inserted at its place.
134
+ const slots = items.map((it, k) => ({ k, h: rowH(it) }));
135
+ if (now && nowPill) slots.splice(now.index, 0, { k: -1, h: nowPill.h });
136
+ const used = slots.reduce((s, x) => s + x.h, 0);
137
+ 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;
138
+ const contentH = used + gap * (slots.length - 1);
139
+ const H = fixed ? f.height : Math.ceil(contentH + 2 * PAD + 2 * DOT);
140
+ let y = (H - contentH) / 2;
141
+ const ys = new Array(n);
142
+ /** @type {number | null} */
143
+ let nowY = null;
144
+ for (const s of slots) {
145
+ // An event's dot sits on its "when" line; the pill is centred in its slot.
146
+ if (s.k < 0) nowY = y + s.h / 2;
147
+ else ys[s.k] = y + whenH / 2;
148
+ y += s.h + gap;
149
+ }
150
+ const first = Math.min(ys[0], nowY ?? Infinity);
151
+ const last = Math.max(ys[n - 1], nowY ?? -Infinity);
152
+ return {
153
+ dir: "v", W, H, fs, whenFs, lineH, whenH, maxChars, whenChars, maxLines: 2, labelW, labelX,
154
+ 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) },
155
+ at: (k) => ({ x: axisX, y: ys[k] }),
156
+ nowAt: nowY == null ? null : { x: axisX, y: nowY },
157
+ side: () => 1,
158
+ nowPill,
159
+ };
160
+ }
161
+
162
+ /** Label blocks, dots and the pill as boxes, for the overlap check. */
163
+ function boxes(L, items) {
164
+ const out = [];
165
+ items.forEach((it, k) => {
166
+ const p = L.at(k);
167
+ const w = Math.max(it.when.length * L.whenFs, Math.max(...it.lines.map((l) => l.length)) * L.fs) * CHAR;
168
+ const h = L.whenH + 4 + it.lines.length * L.lineH;
169
+ out.push({ x: p.x - DOT, y: p.y - DOT, w: 2 * DOT, h: 2 * DOT, what: "dot" });
170
+ if (L.dir === "h") {
171
+ const top = L.side(k) > 0 ? p.y + L.stem + 6 : p.y - L.stem - 6 - h;
172
+ out.push({ x: p.x - w / 2, y: top, w, h, what: `label "${it.label}"` });
173
+ } else {
174
+ out.push({ x: L.labelX, y: p.y - L.whenH / 2, w, h, what: `label "${it.label}"` });
175
+ }
176
+ });
177
+ if (L.nowAt && L.nowPill) {
178
+ const { w, h } = L.nowPill;
179
+ const x = L.dir === "h" ? L.nowAt.x - w / 2 : L.nowAt.x - h / 2;
180
+ out.push({ x, y: L.nowAt.y - h / 2, w, h, what: "the now marker" });
181
+ }
182
+ return out;
183
+ }
184
+
185
+ function layoutProblem(L, items) {
186
+ const all = boxes(L, items);
187
+ for (let i = 0; i < all.length; i++) {
188
+ const b = all[i];
189
+ 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`;
190
+ for (let j = i + 1; j < all.length; j++) {
191
+ if (b.what === "dot" && all[j].what === "dot") continue;
192
+ if (overlaps(b, all[j])) return `${b.what} overlaps ${all[j].what}`;
193
+ }
194
+ }
195
+ return null;
196
+ }
197
+
198
+ /**
199
+ * The validated, localized events and "now" of a spec.
200
+ * @param {any} spec
201
+ * @param {string} locale
202
+ */
203
+ function readSpec(spec, locale) {
204
+ const name = `timeline "${spec.id}"`;
205
+ const events = spec.events;
206
+ if (!Array.isArray(events)) throw new Error(`${name}: needs "events", a list of { when, label }`);
207
+ if (events.length < 2 || events.length > MAX_EVENTS) throw new Error(`${name}: needs 2–${MAX_EVENTS} events, got ${events.length}`);
208
+ let seenPlanned = false;
209
+ const items = events.map((e, i) => {
210
+ const label = localize(e?.label, locale);
211
+ const when = localize(e?.when, locale);
212
+ if (!label) throw new Error(`${name}: event ${i + 1} needs a "label"`);
213
+ if (!when) throw new Error(`${name}: event ${i + 1} ("${label}") needs a "when", e.g. "09:02" or "Q3 2026"`);
214
+ if (e.planned !== undefined && typeof e.planned !== "boolean") throw new Error(`${name}: event ${i + 1} ("${label}"): "planned" must be true or false`);
215
+ const planned = e.planned === true;
216
+ if (seenPlanned && !planned) throw new Error(`${name}: event ${i + 1} ("${label}") has happened but comes after a planned event; planned events go last`);
217
+ seenPlanned ||= planned;
218
+ return { label, when, planned, detail: localize(e.detail, locale), id: e.id };
219
+ });
220
+ /** @type {Now | null} */
221
+ let now = null;
222
+ if (spec.now != null) {
223
+ const label = localize(spec.now.label, locale);
224
+ if (!label) throw new Error(`${name}: "now" needs a "label", e.g. "Now" or "Today"`);
225
+ const index = items.filter((it) => !it.planned).length;
226
+ now = { label, detail: localize(spec.now.detail, locale), id: spec.now.id, index };
227
+ } else if (seenPlanned) {
228
+ throw new Error(`${name}: planned events need a "now" marker to separate them from the past`);
229
+ }
230
+ return { items, now };
231
+ }
232
+
233
+ /**
234
+ * Largest font (≤ max) at which the layout fits and every label wraps. At one
235
+ * font size, labels below the axis win over alternating ones unless
236
+ * alternating needs fewer lines (no orphaned words).
237
+ */
238
+ function fit(f, items, now, maxFs, name) {
239
+ const narrow = f.name === "tall" || (f.height > 0 && f.width / f.height < 0.8);
240
+ let why = "";
241
+ for (let fs = maxFs; fs >= FONT_MIN; fs--) {
242
+ /** @type {{ L: any, items: Item[], lines: number } | null} */
243
+ let best = null;
244
+ for (const mode of narrow ? ["v"] : ["below", "alternate"]) {
245
+ let L = mode === "v" ? vertical(f, items, now, fs) : horizontal(f, items, now, fs, mode);
246
+ try {
247
+ const wrapped = items.map((it) => {
248
+ wrapLabel(it.when, L.whenChars, 1);
249
+ return { ...it, lines: wrapLabel(it.label, L.maxChars, L.maxLines) };
250
+ });
251
+ if (now) wrapLabel(now.label, L.dir === "h" ? Math.floor((L.cell - 2 * DOT - 12) / (L.whenFs * CHAR)) : L.maxChars, 1);
252
+ if (mode === "v") L = vertical(f, wrapped, now, fs);
253
+ const problem = layoutProblem(L, wrapped);
254
+ if (problem) {
255
+ why = problem;
256
+ continue;
257
+ }
258
+ const lines = wrapped.reduce((s, it) => s + it.lines.length, 0);
259
+ if (!best || lines < best.lines) best = { L, items: wrapped, lines };
260
+ } catch (e) {
261
+ why = e instanceof Error ? e.message : String(e);
262
+ }
263
+ }
264
+ if (best) return best;
265
+ }
266
+ 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`);
267
+ }
268
+
269
+ /**
270
+ * Build a timeline scene from its spec.
271
+ * @param {any} spec
272
+ * @param {{ format?: string | { name: string, width: number, height: number }, locale?: string }} [opts]
273
+ * @returns {Scene}
274
+ */
275
+ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
276
+ const f = typeof format === "string" ? { name: format, ...FORMATS[format] } : format;
277
+ if (!f.width) throw new Error(`unknown format "${format}"`);
278
+ const { items: raw, now } = readSpec(spec, locale);
279
+ const n = raw.length;
280
+ const maxFs = maxFontSize(spec, f.height > 0 ? 22 : 16, `timeline "${spec.id}"`);
281
+ const { L, items } = fit(f, raw, now, maxFs, `timeline "${spec.id}"`);
282
+
283
+ // Event k's beat; then the "now" beat.
284
+ const beat = (k) => AXIS + 0.1 + k * BEAT;
285
+ const stepAt = (k) => beat(k) + SETTLE_AT;
286
+ const nowStart = beat(n);
287
+ const nowAt = nowStart + springSettleTime(NOW_OMEGA) + 0.01;
288
+ const duration = (now ? nowAt : stepAt(n - 1)) + TAIL;
289
+
290
+ // The accent axis: from the axis start through every past event, then to "now".
291
+ const ax = L.axis;
292
+ const along = (p) => (L.dir === "h" ? p.x : p.y);
293
+ const start = L.dir === "h" ? ax.x0 : ax.y0;
294
+ const stops = items.flatMap((it, k) => (it.planned ? [] : [{ to: along(L.at(k)), at: beat(k) }]));
295
+ if (now && L.nowAt) stops.push({ to: along(L.nowAt), at: nowStart });
296
+ const axisLen = L.dir === "h" ? ax.x1 - ax.x0 : ax.y1 - ax.y0;
297
+
298
+ function accentEnd(t) {
299
+ let end = start;
300
+ let from = start;
301
+ for (const s of stops) {
302
+ const p = progress(t, s.at, EXTEND, easeStandard);
303
+ if (p <= 0) break;
304
+ end = lerp(from, s.to, p);
305
+ from = s.to;
306
+ }
307
+ return end;
308
+ }
309
+
310
+ const line = (a, b, attrs) =>
311
+ el("path", { d: L.dir === "h" ? `M${num(a)} ${num(ax.y0)} H${num(b)}` : `M${num(ax.x0)} ${num(a)} V${num(b)}`, fill: "none", "stroke-linecap": "round", ...attrs });
312
+
313
+ function milestone(t, it, k) {
314
+ const p = L.at(k);
315
+ const b = beat(k);
316
+ const drop = progress(t, b + 0.05, DROP, easeOut);
317
+ if (drop <= 0) return "";
318
+ const shown = progress(t, b + 0.15, LABEL, easeOut);
319
+ const active = it.planned ? 0 : progress(t, b + 0.3, FILL, easeStandard);
320
+ const out = [];
321
+ const s = L.side(k);
322
+ if (L.dir === "h") {
323
+ // Stem from the dot to the label block, drawn as the label arrives.
324
+ const y0 = p.y + s * (DOT + 3);
325
+ const y1 = p.y + s * L.stem;
326
+ const len = Math.abs(y1 - y0);
327
+ const dash = drawOn(len, progress(t, b + 0.15, LABEL, easeStandard));
328
+ if (dash) out.push(el("path", { d: `M${num(p.x)} ${num(y0)} V${num(y1)}`, stroke: tok("line"), "stroke-width": 1.5, fill: "none", ...dash }));
329
+ }
330
+ const dy = (1 - drop) * -14;
331
+ const dot = (fill, stroke) => el("circle", { cx: p.x, cy: p.y, r: DOT, fill, stroke, "stroke-width": 2 });
332
+ out.push(
333
+ fade(drop, { transform: Math.abs(dy) > 0.004 ? translate(0, dy) : undefined }, fade(1 - active, {}, dot(tok("surface"), tok("line"))), fade(active, {}, dot(tok("accent"), tok("accent")))),
334
+ );
335
+ // Label block: the "when" line (muted) and the wrapped label (muted → ink once it has happened).
336
+ const h = L.whenH + 4 + it.lines.length * L.lineH;
337
+ let x;
338
+ let top;
339
+ let anchor;
340
+ if (L.dir === "h") {
341
+ x = p.x;
342
+ top = s > 0 ? p.y + L.stem + 6 : p.y - L.stem - 6 - h;
343
+ anchor = "middle";
344
+ } else {
345
+ x = L.labelX;
346
+ top = p.y - L.whenH / 2;
347
+ anchor = "start";
348
+ }
349
+ if (shown > 0) {
350
+ 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)));
351
+ out.push(stateLabel({ x, y: top + L.whenH + 4, lines: it.lines, fontSize: L.fs, anchor, baseline: "hanging", enter: shown, active }));
352
+ }
353
+ return out.join("");
354
+ }
355
+
356
+ function nowMarker(t) {
357
+ if (!now || !L.nowAt || !L.nowPill) return "";
358
+ const shown = progress(t, nowStart, NOW_FADE, easeOut);
359
+ if (shown <= 0) return "";
360
+ const dy = -(1 - springStep(t - nowStart, NOW_OMEGA)) * NOW_DROP;
361
+ const { w, h, fs } = L.nowPill;
362
+ const x = L.dir === "h" ? L.nowAt.x - w / 2 : L.nowAt.x - h / 2;
363
+ const y = L.nowAt.y - h / 2;
364
+ return fade(
365
+ shown,
366
+ { transform: Math.abs(dy) > 0.004 ? translate(0, dy) : undefined },
367
+ el("rect", { x, y, width: w, height: h, rx: h / 2, fill: tok("bg"), stroke: tok("emphasis"), "stroke-width": 2.5 }),
368
+ text({ x: x + w / 2, y: L.nowAt.y, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fs, "font-weight": 600, fill: tok("ink") }, now.label),
369
+ );
370
+ }
371
+
372
+ function frame(t) {
373
+ const out = [];
374
+ // Axis: pending line draws on; an arrowhead at its end shows the direction of time.
375
+ const axisDash = drawOn(axisLen, progress(t, 0, AXIS, easeStandard));
376
+ if (axisDash) out.push(line(start, L.dir === "h" ? ax.x1 : ax.y1, { stroke: tok("line"), "stroke-width": 2, ...axisDash }));
377
+ const head = progress(t, AXIS - 0.15, 0.2, easeOut);
378
+ if (head > 0) {
379
+ const d = L.dir === "h" ? `M${num(ax.x1 - 9)} ${num(ax.y1 - 6)} L${num(ax.x1)} ${num(ax.y1)} L${num(ax.x1 - 9)} ${num(ax.y1 + 6)}` : `M${num(ax.x1 - 6)} ${num(ax.y1 - 9)} L${num(ax.x1)} ${num(ax.y1)} L${num(ax.x1 + 6)} ${num(ax.y1 - 9)}`;
380
+ out.push(el("path", { d, fill: "none", stroke: tok("line"), "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: head }));
381
+ }
382
+ const end = accentEnd(t);
383
+ if (end - start > 0.5) out.push(line(start, end, { stroke: tok("accent"), "stroke-width": 3 }));
384
+ items.forEach((it, k) => out.push(milestone(t, it, k)));
385
+ out.push(nowMarker(t));
386
+ return out.join("");
387
+ }
388
+
389
+ const steps = items.map((it, k) => withId({ at: stepAt(k), label: it.label, detail: it.detail }, it.id));
390
+ if (now) steps.push(withId({ at: nowAt, label: now.label, detail: now.detail }, now.id));
391
+
392
+ return {
393
+ id: `${spec.id}-${f.name.replace(":", "x")}`,
394
+ type: "timeline",
395
+ format: f.name,
396
+ locale,
397
+ width: L.W,
398
+ height: L.H,
399
+ duration,
400
+ title: localize(spec.title, locale),
401
+ description: localize(spec.description, locale),
402
+ steps,
403
+ frame,
404
+ };
405
+ }
@@ -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,
@@ -52,7 +72,8 @@ Node ≥ 22. PNG/video need `@resvg/resvg-js` (`npm install` in `$MK`) and `ffmp
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
@@ -26,6 +26,11 @@
26
26
  scene id plus a counter), so scenes that define ids can share a page.
27
27
  - The stylesheet is added to the document whenever a player mounts and none is
28
28
  there, so a page swap (Astro view transitions) cannot leave players unstyled.
29
+ - Each frame updates the SVG in place (`patchMarkup`, `runtime/patch.mjs`):
30
+ nodes that persist keep their identity and only changed attributes and text
31
+ are written, so hover state survives playback. Page CSS must not put
32
+ transitions or animations on the diagram's SVG: with persistent nodes they
33
+ would run between frames, and exports would no longer match what plays.
29
34
  - Capture hook: `window.__motionKit[id].seek(t)` (for Playwright/HyperFrames-
30
35
  style renderers).
31
36
 
@@ -56,15 +61,115 @@ const go = (c) => c.playToStep("payment");
56
61
  el.controller ? go(el.controller) : el.addEventListener("motion-ready", (e) => go(e.detail.controller), { once: true });
57
62
  ```
58
63
 
64
+ ## Linking the page to the diagram (`runtime/links.mjs`)
65
+
66
+ Two helpers bind a controller to the page around the player. Both are
67
+ dependency-free browser code (no DOM at import), take a step by `id` or index,
68
+ throw `RangeError` for an unknown id when they bind (not when the reader gets
69
+ there), never move focus or layout, and return a `dispose()` that removes
70
+ their listeners, observers and marks. Call it before removing the elements or
71
+ the player (Astro: on `astro:before-swap`).
72
+
73
+ - **Hover/focus linking:** `linkSteps(controller, rootOrElements, options)`.
74
+ Every element with `data-mk-step` under the root (or the elements given)
75
+ selects its step on hover (mouse and pen), keyboard focus (also focus inside
76
+ it) and click; touch selects on tap, so nothing is hover-only. Make terms
77
+ `<button type="button" data-mk-step="payment">` so the keyboard reaches
78
+ them. A selection jumps to the settled step; `animate: true` plays forward
79
+ to a later step, except under reduced motion. The step stays when the
80
+ pointer or focus leaves; `restore: true` turns hover and focus into a
81
+ preview: once neither is on a term, the diagram returns to the frame it
82
+ showed before, and a click keeps its step. The terms of the selected step
83
+ get `aria-current="step"` (`mark: false` to style them yourself);
84
+ `onChange(step, element)` reports each selection (`-1, null` on restore).
85
+ Terms are collected when binding; bind again for terms added later. When
86
+ scroll sections carry `data-mk-step` as well, pass the terms themselves
87
+ rather than a root that contains the sections.
88
+ - **Scroll-driven steps:** `scrollSteps(controller, sections, options)`.
89
+ Each section names its step with `data-mk-step`, else by order (the third
90
+ section shows step 2). The active section is the last one whose top has
91
+ crossed a line across the viewport (`line`, a share of its height from the
92
+ top, default 0.5; `root` for a scrolling container), found with an
93
+ IntersectionObserver whose root ends at that line. It stays active through
94
+ the gap after it, and the last section stays active below it. Moving one
95
+ section forward plays to its step (`playToStep`); moving back, skipping
96
+ sections, the first section and reduced motion jump (`seekStep`);
97
+ `animate: false` always jumps. Above the first section the diagram keeps its
98
+ frame. The active section gets `aria-current="step"` (style it without
99
+ changing its size, e.g. opacity); `onChange(index, section)` reports each
100
+ change (`-1, null` above the first). It never scrubs continuously: the
101
+ diagram only ever rests on settled steps. Mount the player with
102
+ `autoplay: "none"`, and leave room below the last section (e.g.
103
+ `padding-bottom: 50vh`) so its top can reach the line. Without
104
+ IntersectionObserver it does nothing and the text still reads.
105
+
106
+ Plain HTML (`motion-kit vendor … --adapter page`):
107
+
108
+ ```html
109
+ <article id="story">
110
+ <section data-mk-step="order"><h2>The order</h2><p>…</p></section>
111
+ <section data-mk-step="payment"><h2>Payment</h2><p>The <button type="button" data-mk-step="payment">card check</button> …</p></section>
112
+ <section data-mk-step="shipping"><h2>Shipping</h2><p>…</p></section>
113
+ </article>
114
+ <div id="flow"></div>
115
+ <script type="module">
116
+ import { mountPlayer } from "./motion-kit/runtime/player.mjs";
117
+ import { linkSteps, scrollSteps } from "./motion-kit/runtime/links.mjs";
118
+ const player = mountPlayer(document.getElementById("flow"), scene, { autoplay: "none" });
119
+ const story = document.getElementById("story");
120
+ const stopScroll = scrollSteps(player, story.querySelectorAll("section"));
121
+ // The sections carry data-mk-step too: pass the terms, not the article.
122
+ const stopLinks = linkSteps(player, story.querySelectorAll("button[data-mk-step]"));
123
+ </script>
124
+ ```
125
+
126
+ `<motion-diagram>` (`--adapter element`): wait for the controller.
127
+
128
+ ```js
129
+ import { scrollSteps } from "./motion-kit/runtime/links.mjs";
130
+ const el = document.querySelector("motion-diagram");
131
+ const bind = (c) => scrollSteps(c, document.querySelectorAll("#story section"));
132
+ el.controller ? bind(el.controller) : el.addEventListener("motion-ready", (e) => bind(e.detail.controller), { once: true });
133
+ ```
134
+
135
+ The element remounts when an attribute changes, which makes a new controller:
136
+ listen to every `motion-ready` (not `once`) and dispose the previous binding
137
+ first if the page changes attributes.
138
+
139
+ Astro (`--adapter astro`), with `id` on the diagram:
140
+
141
+ ```astro
142
+ <AnimatedDiagram spec={spec} format="tall" id="flow" />
143
+ <script>
144
+ import { linkSteps, scrollSteps } from "../motion-kit/runtime/links.mjs";
145
+ const el = document.getElementById("flow");
146
+ const bind = (c) => {
147
+ const stops = [scrollSteps(c, document.querySelectorAll("#story section")), linkSteps(c, document.querySelectorAll("#story button[data-mk-step]"))];
148
+ document.addEventListener("astro:before-swap", () => stops.forEach((stop) => stop()), { once: true });
149
+ };
150
+ el.controller ? bind(el.controller) : el.addEventListener("motion-ready", (e) => bind(e.detail.controller), { once: true });
151
+ </script>
152
+ ```
153
+
154
+ Module scripts run once per load: with view transitions (`<ClientRouter />`),
155
+ run the binding code in an `astro:page-load` listener so each page binds its
156
+ own diagram; the `astro:before-swap` dispose releases the previous one.
157
+
158
+ A page from `motion-kit build` has them on the `MotionKitRuntime` global.
159
+
160
+ The step mapping is pure and exported for tests and custom bindings:
161
+ `stepRef(scene, ref)` (id first, then a whole-number index),
162
+ `sectionSteps(scene, refs)` (a section's reference, else its position),
163
+ `activeSection(tops, line)` and `scrollMove({ from, to, fromStep, toStep,
164
+ animate, reduced })` (`"play"`, `"seek"` or null).
165
+
59
166
  ## Patterns worth adding per diagram (in the page around the player)
60
167
 
61
168
  - **Hover/focus linking:** terms in the surrounding text highlight the matching
62
- part of the diagram (and back). Wrap the term in
63
- `<span data-mk-step="payment">`; on hover and on focus,
64
- `controller.seekStep("payment")`. Use step ids, not positions.
65
- - **Scroll-driven steps:** for long-form explainers, map section visibility to
66
- steps (IntersectionObserver per text section → `seekStep(i)`). Don't scrub
67
- continuously on scroll; jump to settled steps.
169
+ part of the diagram: `linkSteps` above. Use step ids, not positions.
170
+ - **Scroll-driven steps:** for long-form explainers, one text section per step:
171
+ `scrollSteps` above. Don't scrub continuously on scroll; jump to settled
172
+ steps.
68
173
  - **Details on demand:** step buttons + caption first; tooltips only for
69
174
  secondary facts.
70
175
  - **Explorables:** a parameter slider can change the *spec* (e.g. number of
@@ -20,6 +20,9 @@ Model screenshots are evidence, not approval. **A human signs off on the look.**
20
20
  reads the step list.
21
21
  - Video: `video --sheet` contact sheet; duration, aspect and size via the
22
22
  printed probe; watch it once at full size.
23
+ - Exports: `manifest.json` names the source commit and says
24
+ `"sourceDirty": false`; a `true` means the frames come from uncommitted
25
+ changes. Re-exporting into a folder replaces what the last export wrote.
23
26
 
24
27
  **Don't trust virtual time.** Headless `--virtual-time-budget` doesn't advance
25
28
  the player's animation clock faithfully. Use `--timeout=<ms>` (real time) or a