@liqweed/motion-kit 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +17 -2
  4. package/adapters/page/README.md +5 -0
  5. package/cli/motion-kit.mjs +91 -4
  6. package/docs/spec/technique.md +49 -25
  7. package/examples/checkout.json +104 -0
  8. package/examples/connection.json +80 -0
  9. package/examples/custom-pulse.scene.mjs +2 -0
  10. package/examples/player-states.json +97 -0
  11. package/examples/pull-request.json +93 -0
  12. package/examples/pull-request.mmd +15 -0
  13. package/lib/check.mjs +11 -8
  14. package/lib/export.mjs +12 -0
  15. package/lib/gate.mjs +4 -4
  16. package/lib/layout.mjs +236 -0
  17. package/lib/load.mjs +15 -0
  18. package/lib/mermaid.mjs +382 -0
  19. package/lib/outdated.mjs +122 -0
  20. package/package.json +6 -3
  21. package/runtime/links.mjs +5 -1
  22. package/runtime/player.mjs +40 -1
  23. package/runtime/scene.mjs +21 -8
  24. package/runtime/style.mjs +3 -0
  25. package/runtime/types/flowchart.mjs +402 -0
  26. package/runtime/types/hub-spoke.mjs +8 -6
  27. package/runtime/types/index.mjs +5 -0
  28. package/runtime/types/sequence.mjs +8 -6
  29. package/runtime/types/stack.mjs +13 -10
  30. package/runtime/types/timeline.mjs +14 -12
  31. package/runtime/types/walk.mjs +162 -0
  32. package/skills/animated-diagram/SKILL.md +8 -3
  33. package/skills/animated-diagram/references/custom-scenes.md +14 -0
  34. package/skills/animated-diagram/references/ecosystem.md +2 -2
  35. package/skills/animated-diagram/references/interactivity.md +18 -0
  36. package/skills/animated-diagram/references/motion-vocabulary.md +1 -1
  37. package/skills/animated-diagram/references/scene-types.md +118 -6
  38. package/skills/animated-diagram/references/styles.md +11 -2
  39. package/skills/animated-diagram/references/technique.md +6 -2
  40. package/skills/motion-render/SKILL.md +7 -0
  41. package/skills/motion-render/references/video.md +1 -1
@@ -0,0 +1,382 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · import a Mermaid flowchart as a spec (Node, build time).
5
+ *
6
+ * parseMermaid(source) → { direction, title, description, nodes, edges, warnings }
7
+ * mermaidToSpec(source, { id, title, description }) → { spec, warnings }
8
+ *
9
+ * A flowchart that is one chain (every node has at most one link in and one
10
+ * out, no link labels, no dotted links) becomes a `sequence` spec. Anything
11
+ * else becomes a `flowchart` spec with its layout computed here, once
12
+ * (lib/layout.mjs), and stored as ranks and positions, so the runtime never
13
+ * lays a graph out.
14
+ *
15
+ * Supported: `flowchart`/`graph` with TB, TD, BT, LR or RL; nodes with
16
+ * `[box]`, `(round)`, `([pill])`, `{decision}` and `{{decision}}` shapes,
17
+ * quoted labels, `<br>` and `#entity;` codes; links `-->`, `---`, `-.->`,
18
+ * `-.-`, `==>`, `===` of any length, with `|text|` or `-- text -->` labels;
19
+ * chains (`A --> B --> C`) and `&` groups; `accTitle`, `accDescr` and a
20
+ * front-matter `title`. Styling (`classDef`, `class`, `style`, `linkStyle`,
21
+ * `:::name`, `%%{init}%%`, front-matter `config`) is ignored with a warning:
22
+ * colours come from the motion-kit style. Everything else fails with an
23
+ * error that names it and its line.
24
+ */
25
+ import { layered } from "./layout.mjs";
26
+
27
+ /**
28
+ * @typedef {{ id: string, label: string, shape: "box" | "round" | "pill" | "decision" }} MermaidNode
29
+ * @typedef {{ from: string, to: string, label: string, arrow: boolean, dashed: boolean }} MermaidEdge
30
+ * @typedef {{ direction: "down" | "up" | "right" | "left", title: string, description: string, nodes: MermaidNode[], edges: MermaidEdge[], warnings: string[] }} MermaidGraph
31
+ */
32
+
33
+ const DIRECTIONS = { TB: "down", TD: "down", BT: "up", LR: "right", RL: "left" };
34
+
35
+ /**
36
+ * Node shapes: opener, closer (null: several), and the built shape it becomes
37
+ * or a description of the unsupported one.
38
+ * @type {[string, string | null, string][]}
39
+ */
40
+ const SHAPES = [
41
+ ["(((", ")))", "the (((double circle))) shape"],
42
+ ["((", "))", "the ((circle)) shape"],
43
+ ["([", "])", "pill"],
44
+ ["[[", "]]", "the [[subroutine]] shape"],
45
+ ["[(", ")]", "the [(database)] shape"],
46
+ ["[/", null, "the [/parallelogram/] and [/trapezoid\\] shapes"],
47
+ ["[\\", null, "the [\\parallelogram\\] and [\\trapezoid/] shapes"],
48
+ ["{{", "}}", "decision"],
49
+ ["[", "]", "box"],
50
+ ["(", ")", "round"],
51
+ ["{", "}", "decision"],
52
+ [">", "]", "the >asymmetric] shape"],
53
+ ];
54
+ const BUILT_SHAPES = new Set(["box", "round", "pill", "decision"]);
55
+
56
+ /** Plain links: pattern, arrow, dashed, thick. Longer patterns first. */
57
+ const LINKS = [
58
+ [/^-\.+->/, true, true, false],
59
+ [/^-\.+-/, false, true, false],
60
+ [/^-{2,}>/, true, false, false],
61
+ [/^-{3,}/, false, false, false],
62
+ [/^={2,}>/, true, false, true],
63
+ [/^={3,}/, false, false, true],
64
+ ];
65
+ /** Links with the label inside: `-- text -->`, `-. text .->`, `== text ==>`. */
66
+ const TEXT_LINKS = [
67
+ [/^--(?![->])\s*(.+?)\s*(-{2,}>|-{3,})/, false, false],
68
+ [/^-\.(?![-.])\s*(.+?)\s*(\.+->|\.+-)/, true, false],
69
+ [/^==(?![=>])\s*(.+?)\s*(={2,}>|={3,})/, false, true],
70
+ ];
71
+
72
+ const OTHER_DIAGRAMS = /^(sequenceDiagram|classDiagram|stateDiagram(?:-v2)?|erDiagram|journey|gantt|pie|gitGraph|mindmap|timeline|quadrantChart|requirementDiagram|C4\w*|sankey(?:-beta)?|xychart(?:-beta)?|block(?:-beta)?|packet(?:-beta)?|architecture(?:-beta)?|kanban|radar(?:-beta)?|zenuml)\b/;
73
+
74
+ /**
75
+ * Split one line into statements at `;`, outside quotes, brackets and |labels|.
76
+ * @param {string} line
77
+ */
78
+ function statements(line) {
79
+ const out = [];
80
+ let cur = "";
81
+ let quote = false;
82
+ let pipe = false;
83
+ let depth = 0;
84
+ for (const c of line) {
85
+ if (c === '"') quote = !quote;
86
+ else if (!quote && c === "|") pipe = !pipe;
87
+ else if (!quote && !pipe && "[({".includes(c)) depth++;
88
+ else if (!quote && !pipe && "])}".includes(c)) depth = Math.max(0, depth - 1);
89
+ if (c === ";" && !quote && !pipe && depth === 0) {
90
+ out.push(cur);
91
+ cur = "";
92
+ } else cur += c;
93
+ }
94
+ out.push(cur);
95
+ return out.map((s) => s.trim()).filter(Boolean);
96
+ }
97
+
98
+ const ENTITIES = { quot: '"', amp: "&", lt: "<", gt: ">", nbsp: " ", apos: "'", num: "#", semi: ";" };
99
+
100
+ /**
101
+ * Label text as plain text: entity codes decoded, `<br>` as a space.
102
+ * @param {string} raw
103
+ * @param {(why: string) => never} fail
104
+ */
105
+ function cleanLabel(raw, fail) {
106
+ let s = raw.trim();
107
+ if (s.startsWith('"') && s.endsWith('"') && s.length >= 2) s = s.slice(1, -1);
108
+ if (s.startsWith("`")) fail("markdown strings (\"`…`\") are not supported; write the label as plain text");
109
+ s = s.replace(/<br\s*\/?>/gi, " ");
110
+ if (/<\/?[a-z][^>]*>/i.test(s)) fail(`HTML in the label "${s}" is not supported; write plain text`);
111
+ if (/\bfa:fa-[\w-]+/.test(s)) fail(`Font Awesome icons in the label "${s}" are not supported`);
112
+ s = s.replace(/#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/#([a-z]+);/gi, (m, k) => ENTITIES[/** @type {keyof typeof ENTITIES} */ (k.toLowerCase())] ?? m);
113
+ return s.replace(/\s+/g, " ").trim();
114
+ }
115
+
116
+ /**
117
+ * Parse a Mermaid flowchart. Throws on anything it cannot convert faithfully.
118
+ * @param {string} source
119
+ * @returns {MermaidGraph}
120
+ */
121
+ export function parseMermaid(source) {
122
+ const lines = String(source).replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
123
+ /** @type {string[]} */
124
+ const warnings = [];
125
+ let title = "";
126
+ let description = "";
127
+ let n = 0;
128
+ // Front matter: only `title` carries meaning here.
129
+ while (n < lines.length && !lines[n].trim()) n++;
130
+ if (lines[n]?.trim() === "---") {
131
+ const close = lines.findIndex((l, i) => i > n && l.trim() === "---");
132
+ if (close < 0) throw new Error(`line ${n + 1}: front matter is not closed with ---`);
133
+ for (let i = n + 1; i < close; i++) {
134
+ const m = lines[i].match(/^(\w+)\s*:\s*(.*)$/);
135
+ if (!m) continue;
136
+ if (m[1] === "title") title = m[2].trim().replace(/^(["'])(.*)\1$/, "$2");
137
+ else warnings.push(`line ${i + 1}: front matter "${m[1]}" ignored: colours and layout come from motion-kit`);
138
+ }
139
+ n = close + 1;
140
+ }
141
+
142
+ /** @type {"down" | "up" | "right" | "left" | ""} */
143
+ let direction = "";
144
+ /** @type {Map<string, MermaidNode>} */
145
+ const nodes = new Map();
146
+ /** @type {MermaidEdge[]} */
147
+ const edges = [];
148
+ let thickWarned = false;
149
+
150
+ for (; n < lines.length; n++) {
151
+ const lineNo = n + 1;
152
+ /** @param {string} why @returns {never} */
153
+ const fail = (why) => {
154
+ throw new Error(`line ${lineNo}: ${why}`);
155
+ };
156
+ const raw = lines[n].trim();
157
+ if (!raw) continue;
158
+ if (raw.startsWith("%%")) {
159
+ if (raw.startsWith("%%{")) warnings.push(`line ${lineNo}: directive ignored: colours and layout come from motion-kit`);
160
+ continue;
161
+ }
162
+ if (!direction) {
163
+ const first = raw.split(/[\s;]/)[0];
164
+ const head = raw.match(/^(flowchart|graph)(?:\s+(TB|TD|BT|LR|RL))?\s*;?\s*(.*)$/i);
165
+ if (!head) {
166
+ throw new Error(`line ${lineNo}: ${OTHER_DIAGRAMS.test(raw) ? `"${first}" is not a flowchart: only Mermaid flowcharts ("flowchart" or "graph") can be imported` : `expected "flowchart" or "graph" with a direction, got "${raw}"`}`);
167
+ }
168
+ direction = /** @type {"down" | "up" | "right" | "left"} */ (DIRECTIONS[/** @type {keyof typeof DIRECTIONS} */ ((head[2] ?? "TB").toUpperCase())]);
169
+ if (!head[3]) continue;
170
+ lines[n] = head[3];
171
+ n--;
172
+ continue;
173
+ }
174
+ const acc = raw.match(/^acc(Title|Descr)\s*(:|\{)\s*(.*)$/);
175
+ if (acc) {
176
+ let value = acc[3];
177
+ if (acc[2] === "{") {
178
+ const parts = [value.replace(/\}\s*$/, "")];
179
+ while (!/\}\s*$/.test(lines[n]) && n + 1 < lines.length) parts.push(lines[++n].trim().replace(/\}\s*$/, ""));
180
+ value = parts.join(" ");
181
+ }
182
+ if (acc[1] === "Title") title = value.trim();
183
+ else description = value.replace(/\s+/g, " ").trim();
184
+ continue;
185
+ }
186
+ for (const stmt of statements(raw)) {
187
+ const word = stmt.split(/\s/)[0];
188
+ if (word === "subgraph" || word === "end" || word === "direction") fail(`"${word}" is not supported: subgraphs have no motion-kit equivalent; remove the subgraph lines or split the chart`);
189
+ if (word === "click") fail(`"click" is not supported: interaction comes from the player, not the chart`);
190
+ if (["classDef", "class", "style", "linkStyle"].includes(word)) {
191
+ warnings.push(`line ${lineNo}: "${word}" ignored: colours come from the motion-kit style`);
192
+ continue;
193
+ }
194
+ parseChain(stmt, lineNo, fail);
195
+ }
196
+ }
197
+ if (!direction) throw new Error(`no "flowchart" or "graph" header found`);
198
+
199
+ /**
200
+ * `A --> B & C -- yes --> D`: nodes and links, left to right.
201
+ * @param {string} s @param {number} lineNo @param {(why: string) => never} fail
202
+ */
203
+ function parseChain(s, lineNo, fail) {
204
+ let i = 0;
205
+ const ws = () => {
206
+ while (i < s.length && /\s/.test(s[i])) i++;
207
+ };
208
+ const node = () => {
209
+ ws();
210
+ const m = s.slice(i).match(/^[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)*/);
211
+ if (!m) fail(`expected a node id at "${s.slice(i)}"`);
212
+ const id = m[0];
213
+ if (id === "end") fail(`"end" is a Mermaid keyword and cannot be a node id`);
214
+ i += id.length;
215
+ if (s.startsWith("@{", i)) fail(`node ${id}: the @{ shape: … } syntax is not supported; use [box], (round), ([pill]) or {decision}`);
216
+ const shape = SHAPES.find(([open]) => s.startsWith(open, i));
217
+ if (shape) {
218
+ const [open, close, what] = shape;
219
+ if (!BUILT_SHAPES.has(what) || !close) fail(`node ${id} uses ${what}, which is not supported; use [box], (round), ([pill]) or {decision}`);
220
+ i += open.length;
221
+ ws();
222
+ let end;
223
+ if (s[i] === '"') {
224
+ const q = s.indexOf('"', i + 1);
225
+ if (q < 0) fail(`node ${id}: the quoted label is not closed`);
226
+ end = s.indexOf(close, q + 1);
227
+ } else end = s.indexOf(close, i);
228
+ if (end < 0) fail(`node ${id}: "${open}" is not closed with "${close}"`);
229
+ const label = cleanLabel(s.slice(i, end), fail);
230
+ i = end + close.length;
231
+ nodes.set(id, { id, label: label || id, shape: /** @type {MermaidNode["shape"]} */ (what) });
232
+ } else if (!nodes.has(id)) nodes.set(id, { id, label: id, shape: "box" });
233
+ const cls = s.slice(i).match(/^:::[\w-]+/);
234
+ if (cls) {
235
+ warnings.push(`line ${lineNo}: "${cls[0]}" on ${id} ignored: colours come from the motion-kit style`);
236
+ i += cls[0].length;
237
+ }
238
+ return id;
239
+ };
240
+ const group = () => {
241
+ const ids = [node()];
242
+ for (ws(); s[i] === "&"; ws()) {
243
+ i++;
244
+ ids.push(node());
245
+ }
246
+ return ids;
247
+ };
248
+ const link = () => {
249
+ ws();
250
+ const rest = s.slice(i);
251
+ if (rest.startsWith("~~~")) fail(`invisible links (~~~) are not supported`);
252
+ if (/^(<|o|x)(-|=|\.)/.test(rest) || /^(-{2,}|={2,}|-\.+-)[ox]/.test(rest)) fail(`two-way, circle and cross links (<-->, --o, --x) are not supported; use --> or ---`);
253
+ if (/^[A-Za-z_]+@(-|=)/.test(rest)) fail(`link ids (e1@-->) are not supported`);
254
+ for (const [re, arrow, dashed, thick] of LINKS) {
255
+ const m = rest.match(/** @type {RegExp} */ (re));
256
+ if (!m) continue;
257
+ i += m[0].length;
258
+ ws();
259
+ let label = "";
260
+ if (s[i] === "|") {
261
+ const close = s.indexOf("|", i + 1);
262
+ if (close < 0) fail(`a link label "|…" is not closed with "|"`);
263
+ label = cleanLabel(s.slice(i + 1, close), fail);
264
+ i = close + 1;
265
+ }
266
+ return { arrow: /** @type {boolean} */ (arrow), dashed: /** @type {boolean} */ (dashed), thick: /** @type {boolean} */ (thick), label };
267
+ }
268
+ for (const [re, dashed, thick] of TEXT_LINKS) {
269
+ const m = rest.match(/** @type {RegExp} */ (re));
270
+ if (!m) continue;
271
+ i += m[0].length;
272
+ return { arrow: m[2].endsWith(">"), dashed: /** @type {boolean} */ (dashed), thick: /** @type {boolean} */ (thick), label: cleanLabel(m[1], fail) };
273
+ }
274
+ fail(`expected a link (-->, ---, -.->, ==>) at "${rest}"`);
275
+ };
276
+ let from = group();
277
+ for (ws(); i < s.length; ws()) {
278
+ const l = link();
279
+ if (l.thick && !thickWarned) {
280
+ thickWarned = true;
281
+ warnings.push(`line ${lineNo}: thick links (==>) are drawn like other links`);
282
+ }
283
+ const to = group();
284
+ for (const a of from) {
285
+ for (const b of to) {
286
+ if (a === b) fail(`${a} links to itself; flowcharts draw no self-loops`);
287
+ edges.push({ from: a, to: b, label: l.label, arrow: l.arrow, dashed: l.dashed });
288
+ }
289
+ }
290
+ from = to;
291
+ }
292
+ }
293
+
294
+ return { direction, title, description, nodes: [...nodes.values()], edges, warnings };
295
+ }
296
+
297
+ /**
298
+ * The nodes in chain order when the graph is one plain chain, else null.
299
+ * @param {MermaidGraph} g
300
+ * @returns {MermaidNode[] | null}
301
+ */
302
+ export function chainOrder(g) {
303
+ if (g.edges.length !== g.nodes.length - 1 || g.edges.some((e) => e.label || e.dashed)) return null;
304
+ const next = new Map();
305
+ const into = new Set();
306
+ for (const e of g.edges) {
307
+ if (next.has(e.from) || into.has(e.to)) return null;
308
+ next.set(e.from, e.to);
309
+ into.add(e.to);
310
+ }
311
+ const starts = g.nodes.filter((nd) => !into.has(nd.id));
312
+ if (starts.length !== 1) return null;
313
+ const byId = new Map(g.nodes.map((nd) => [nd.id, nd]));
314
+ const out = [];
315
+ for (let id = starts[0].id; id !== undefined; id = next.get(id)) out.push(byId.get(id));
316
+ return out.length === g.nodes.length ? /** @type {MermaidNode[]} */ (out) : null;
317
+ }
318
+
319
+ /** "order-review" → "Order review" */
320
+ function humanize(/** @type {string} */ id) {
321
+ const s = id.replace(/[-_]+/g, " ").trim();
322
+ return s ? s[0].toUpperCase() + s.slice(1) : "Flowchart";
323
+ }
324
+
325
+ /** "a", "a and b", "a, b and c" */
326
+ function list(/** @type {string[]} */ items, word = "and") {
327
+ return items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} ${word} ${items[items.length - 1]}`;
328
+ }
329
+
330
+ /**
331
+ * A Mermaid flowchart as a motion-kit spec.
332
+ * @param {string} source
333
+ * @param {{ id?: string, title?: string, description?: string }} [o]
334
+ * @returns {{ spec: Record<string, any>, warnings: string[] }}
335
+ */
336
+ export function mermaidToSpec(source, o = {}) {
337
+ const g = parseMermaid(source);
338
+ const id = o.id ?? "flowchart";
339
+ if (!/^[A-Za-z][\w-]*$/.test(id)) throw new Error(`id "${id}" must start with a letter and use only letters, digits, "-" and "_"`);
340
+ if (g.nodes.length < 2) throw new Error(`the chart has ${g.nodes.length} node(s); a scene needs at least 2`);
341
+ if (g.nodes.length > 12) throw new Error(`the chart has ${g.nodes.length} nodes; motion-kit draws at most 12 in one scene: split it`);
342
+ if (g.edges.length > 20) throw new Error(`the chart has ${g.edges.length} links; motion-kit draws at most 20 in one scene: split it`);
343
+ const title = o.title ?? (g.title || humanize(id));
344
+ const label = new Map(g.nodes.map((nd) => [nd.id, nd.label]));
345
+ const chain = chainOrder(g);
346
+ if (chain) {
347
+ const description = o.description ?? (g.description || `${chain.length} stages in order: ${list(chain.map((nd) => nd.label))}.`);
348
+ return {
349
+ spec: { type: "sequence", id, title, description, nodes: chain.map((nd) => ({ id: nd.id, label: nd.label })) },
350
+ warnings: g.warnings,
351
+ };
352
+ }
353
+ const { ranks, pos, via } = layered(g.nodes.map((nd) => nd.id), g.edges);
354
+ const shape = new Map(g.nodes.map((nd) => [nd.id, nd.shape]));
355
+ const order = [...g.nodes].sort((a, b) => /** @type {number} */ (ranks.get(a.id)) - /** @type {number} */ (ranks.get(b.id)) || /** @type {number} */ (pos.get(a.id)) - /** @type {number} */ (pos.get(b.id)));
356
+ const sentences = order
357
+ .map((nd) => {
358
+ const outs = g.edges.filter((e) => e.from === nd.id).map((e) => `${label.get(e.to)}${e.label ? ` (${e.label})` : ""}`);
359
+ return outs.length ? `${nd.label} leads to ${list(outs, shape.get(nd.id) === "decision" ? "or" : "and")}.` : "";
360
+ })
361
+ .filter(Boolean);
362
+ const description = o.description ?? (g.description || sentences.join(" "));
363
+ return {
364
+ spec: {
365
+ type: "flowchart",
366
+ id,
367
+ title,
368
+ description,
369
+ direction: g.direction,
370
+ nodes: g.nodes.map((nd) => ({ id: nd.id, label: nd.label, ...(nd.shape === "box" ? {} : { shape: nd.shape }), rank: ranks.get(nd.id), pos: pos.get(nd.id) })),
371
+ edges: g.edges.map((e, i) => ({
372
+ from: e.from,
373
+ to: e.to,
374
+ ...(e.label ? { label: e.label } : {}),
375
+ ...(e.dashed ? { dashed: true } : {}),
376
+ ...(e.arrow ? {} : { arrow: false }),
377
+ ...(via[i].length ? { via: via[i] } : {}),
378
+ })),
379
+ },
380
+ warnings: g.warnings,
381
+ };
382
+ }
@@ -0,0 +1,122 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · is a vendored copy behind the latest release? (Node only.)
5
+ *
6
+ * vendoredVersion(dir) → { version, adapter } from <dir>/MOTION_KIT_VERSION
7
+ * latestVersion({ registry, fetch }) → "X.Y.Z" the npm `latest` dist-tag
8
+ * compareVersions(a, b) → -1 | 0 | 1 semver precedence
9
+ *
10
+ * `motion-kit outdated <dir>` combines them. The registry is npm's unless
11
+ * `npm_config_registry` names a mirror.
12
+ */
13
+ import { readFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+
16
+ export const PACKAGE = "@liqweed/motion-kit";
17
+
18
+ /**
19
+ * @param {string} dir a directory written by `motion-kit vendor`
20
+ * @returns {{ version: string, adapter: string }}
21
+ */
22
+ export function vendoredVersion(dir) {
23
+ let text;
24
+ try {
25
+ text = readFileSync(join(dir, "MOTION_KIT_VERSION"), "utf8");
26
+ } catch {
27
+ throw new Error(`${dir} has no MOTION_KIT_VERSION: is it a directory written by motion-kit vendor?`);
28
+ }
29
+ const version = text.match(/^motion-kit (\S+)$/m)?.[1];
30
+ if (!version || !parseVersion(version)) throw new Error(`${join(dir, "MOTION_KIT_VERSION")} names no version`);
31
+ // An absent field defaults to "page"; a present but malformed one is rejected, not defaulted.
32
+ const field = text.match(/^adapter\b(.*)$/m);
33
+ const adapter = field ? (field[1].match(/^ (\S+)$/)?.[1] ?? "") : "page";
34
+ if (!isAdapterName(adapter)) throw new Error(`${join(dir, "MOTION_KIT_VERSION")} names an invalid adapter`);
35
+ return { version, adapter };
36
+ }
37
+
38
+ /**
39
+ * An adapter is a directory name under adapters/: letters, digits, `_` and `-`.
40
+ * @param {string} name
41
+ */
42
+ export function isAdapterName(name) {
43
+ return /^[A-Za-z][\w-]*$/.test(name);
44
+ }
45
+
46
+ /**
47
+ * Quote one argument for a POSIX shell, only when it needs it.
48
+ * @param {string} arg
49
+ */
50
+ export function shellQuote(arg) {
51
+ return /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
52
+ }
53
+
54
+ /** @param {string} v */
55
+ function parseVersion(v) {
56
+ const m = v.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
57
+ return m ? { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split(".") : [] } : null;
58
+ }
59
+
60
+ /**
61
+ * Semver precedence: -1 when a is older than b, 1 when newer, 0 when equal.
62
+ * @param {string} a @param {string} b
63
+ * @returns {-1 | 0 | 1}
64
+ */
65
+ export function compareVersions(a, b) {
66
+ const x = parseVersion(a);
67
+ const y = parseVersion(b);
68
+ if (!x || !y) throw new Error(`not a version: ${x ? b : a}`);
69
+ for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] < y.core[i] ? -1 : 1;
70
+ // A pre-release sorts before its release.
71
+ if (!x.pre.length || !y.pre.length) return x.pre.length === y.pre.length ? 0 : x.pre.length ? -1 : 1;
72
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
73
+ const p = x.pre[i];
74
+ const q = y.pre[i];
75
+ if (p === undefined) return -1;
76
+ if (q === undefined) return 1;
77
+ if (p === q) continue;
78
+ const pn = /^\d+$/.test(p);
79
+ const qn = /^\d+$/.test(q);
80
+ if (pn && qn) return Number(p) < Number(q) ? -1 : 1;
81
+ if (pn !== qn) return pn ? -1 : 1;
82
+ return p < q ? -1 : 1;
83
+ }
84
+ return 0;
85
+ }
86
+
87
+ /**
88
+ * The version npm serves as `latest`.
89
+ * @param {{ registry?: string, fetch?: typeof globalThis.fetch }} [o]
90
+ * @returns {Promise<string>}
91
+ */
92
+ export async function latestVersion({ registry = process.env.npm_config_registry || "https://registry.npmjs.org/", fetch = globalThis.fetch } = {}) {
93
+ let base;
94
+ try {
95
+ base = new URL(registry);
96
+ } catch {
97
+ throw new Error("the npm registry setting is not a URL");
98
+ }
99
+ // Credentials in the URL would reach stderr through the fetch error or the message below.
100
+ if (base.username || base.password) throw new Error("the npm registry URL carries credentials; use a registry URL without them");
101
+ if (base.search || base.hash) throw new Error("the npm registry URL carries a query or fragment; use a plain registry URL");
102
+ // Plain HTTP lets an intermediary change the version this check trusts; only a loopback mirror may use it.
103
+ if (base.protocol !== "https:" && !(base.protocol === "http:" && ["127.0.0.1", "[::1]", "localhost"].includes(base.hostname))) throw new Error("the npm registry URL must use https");
104
+ base.pathname = `${base.pathname.replace(/\/+$/, "")}/${PACKAGE.replace("/", "%2F")}/latest`;
105
+ const url = base.href;
106
+ let res;
107
+ try {
108
+ // A redirect could leave HTTPS, so none is followed.
109
+ res = await fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(15000), redirect: "error" });
110
+ } catch {
111
+ throw new Error(`cannot reach the npm registry at ${base.origin}`);
112
+ }
113
+ if (!res.ok) throw new Error(`${base.origin} answered ${res.status}`);
114
+ let body;
115
+ try {
116
+ body = await res.json();
117
+ } catch {
118
+ throw new Error(`${base.origin} sent a body that is not JSON`);
119
+ }
120
+ if (typeof body?.version !== "string" || !parseVersion(body.version)) throw new Error(`${base.origin} names no version`);
121
+ return body.version;
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqweed/motion-kit",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Deterministic animated diagrams: scenes as pure functions of time, for live pages, slides, baked SVG and video.",
5
5
  "keywords": [
6
6
  "animation",
@@ -47,7 +47,7 @@
47
47
  "prepare": "lefthook install || true",
48
48
  "test": "node --test test/*.test.mjs",
49
49
  "typecheck": "tsc -p .",
50
- "check": "node cli/motion-kit.mjs check examples/order-flow.json examples/smart-home.json examples/release-pipeline.json examples/agent-loop.json examples/integrations.json examples/incident.json examples/web-stack.json examples/custom-pulse.scene.mjs brand/logo.scene.mjs",
50
+ "check": "node cli/motion-kit.mjs check examples/order-flow.json examples/smart-home.json examples/release-pipeline.json examples/agent-loop.json examples/integrations.json examples/incident.json examples/web-stack.json examples/custom-pulse.scene.mjs brand/logo.scene.mjs examples/player-states.json examples/checkout.json examples/connection.json examples/pull-request.json",
51
51
  "media": "scripts/render-media.sh",
52
52
  "media:check": "scripts/render-media.sh --check",
53
53
  "site": "npm run -w website build",
@@ -69,5 +69,8 @@
69
69
  },
70
70
  "workspaces": [
71
71
  "website"
72
- ]
72
+ ],
73
+ "overrides": {
74
+ "picomatch": "npm:@ryotsu/picomatch@4.0.7-a"
75
+ }
73
76
  }
package/runtime/links.mjs CHANGED
@@ -29,7 +29,7 @@ const STEP_ATTR = "data-mk-step";
29
29
  /** @import { Scene } from "./scene.mjs" */
30
30
  /**
31
31
  * The part of the player controller the helpers use.
32
- * @typedef {{ scene: Scene, time: number, seek: (t: number) => void, seekStep: (ref: number | string) => void, playToStep: (ref: number | string) => void }} StepController
32
+ * @typedef {{ scene: Scene, time: number, onStep?: (listener: (index: number) => void) => (() => void), seek: (t: number) => void, seekStep: (ref: number | string) => void, playToStep: (ref: number | string) => void }} StepController
33
33
  */
34
34
  /**
35
35
  * @typedef {object} ScrollStepsOptions
@@ -177,6 +177,7 @@ export function scrollSteps(controller, sections, options = {}) {
177
177
  };
178
178
 
179
179
  if (typeof IntersectionObserver !== "function") return () => {};
180
+ const unsubscribe = mark ? c.onStep?.((index) => els.forEach((el, i) => markCurrent(el, steps[i] === index))) : undefined;
180
181
  // The root, cut off at the line: a section enters or leaves it exactly
181
182
  // when its top crosses the line, which is when the active one can change.
182
183
  const below = `${(1 - line) * 100}%`;
@@ -202,6 +203,7 @@ export function scrollSteps(controller, sections, options = {}) {
202
203
  if (disposed) return;
203
204
  disposed = true;
204
205
  observer.disconnect();
206
+ unsubscribe?.();
205
207
  scroller.removeEventListener?.("scroll", onScroll);
206
208
  if (mark) for (const el of els) markCurrent(el, false);
207
209
  };
@@ -304,10 +306,12 @@ export function linkSteps(controller, target, options = {}) {
304
306
  bound.push([el, name, fn]);
305
307
  }
306
308
  });
309
+ const unsubscribe = mark ? c.onStep?.((index) => els.forEach((el, i) => markCurrent(el, steps[i] === index))) : undefined;
307
310
  let disposed = false;
308
311
  return () => {
309
312
  if (disposed) return;
310
313
  disposed = true;
314
+ unsubscribe?.();
311
315
  for (const [el, name, fn] of bound) el.removeEventListener(name, fn);
312
316
  if (mark) for (const el of els) markCurrent(el, false);
313
317
  };
@@ -270,6 +270,12 @@ export function mountPlayer(container, scene, options = {}) {
270
270
  for (const node of nodes) if (node) container.appendChild(toDom(doc, node, ui));
271
271
  const { stage, live } = ui;
272
272
 
273
+ /** @type {Set<(index: number) => void>} */
274
+ const stepListeners = new Set();
275
+ let lastStep = -2;
276
+ // Bumped on every published step change, so a dispatch knows a newer one ran even
277
+ // when nested seeks came back to its own step.
278
+ let publication = 0;
273
279
  let t = 0;
274
280
  let playing = false;
275
281
  let raf = 0;
@@ -286,6 +292,11 @@ export function mountPlayer(container, scene, options = {}) {
286
292
  /** @type {IntersectionObserver | undefined} */
287
293
  let visibilityObserver;
288
294
 
295
+ /** @param {unknown} e */
296
+ function reportListenerError(e) {
297
+ if (typeof reportError === "function") reportError(e);
298
+ else queueMicrotask(() => { throw e; });
299
+ }
289
300
  function draw() {
290
301
  // In place: nodes that persist keep their identity, only what changed is written.
291
302
  patchMarkup(stage, renderSvg(scene, t, { style, idPrefix: prefix, live: true }));
@@ -294,10 +305,24 @@ export function mountPlayer(container, scene, options = {}) {
294
305
  ui.captions?.forEach((c, i) => (i === idx ? c.setAttribute("class", "mk-on") : c.removeAttribute("class")));
295
306
  if (ui.scrub) ui.scrub.value = String(t);
296
307
  if (ui.playLabel) ui.playLabel.textContent = playing ? labels.pause : t >= scene.duration ? labels.replay : labels.play;
308
+ if (idx !== lastStep) {
309
+ lastStep = idx;
310
+ const mine = ++publication;
311
+ // One throwing listener must not skip the rest or stop the clock: report it
312
+ // out of band (reportError, else a rethrow on a microtask) and carry on.
313
+ for (const listener of [...stepListeners]) {
314
+ // A listener may destroy the player, or seek: a nested draw has then already
315
+ // told everyone about the newer step, so this stale dispatch ends.
316
+ if (destroyed || publication !== mine) break;
317
+ try { listener(idx); } catch (e) { reportListenerError(e); }
318
+ }
319
+ }
297
320
  }
298
321
  /** @param {number} time */
299
322
  function seek(time) {
300
323
  if (destroyed) return;
324
+ if (!Number.isFinite(time)) throw new RangeError("seek time must be finite");
325
+ autoplayPending = false;
301
326
  playing = false;
302
327
  suspended = false;
303
328
  cancelAnimationFrame(raf);
@@ -439,9 +464,23 @@ export function mountPlayer(container, scene, options = {}) {
439
464
  const themeQuery = typeof matchMedia === "function" && !options.theme ? matchMedia("(prefers-color-scheme: dark)") : null;
440
465
  themeQuery?.addEventListener?.("change", applyTheme);
441
466
 
467
+ /**
468
+ * Subscribe to settled-step changes (including -1 before the first).
469
+ * Calls immediately with the current index, then once per changed index
470
+ * from playback, seeking or controls. Unsubscribe or destroy to release.
471
+ * @param {(index: number) => void} listener
472
+ * @returns {() => void}
473
+ */
474
+ function onStep(listener) {
475
+ if (destroyed) return () => {};
476
+ stepListeners.add(listener);
477
+ listener(stepIndexAt(scene, t));
478
+ return () => { stepListeners.delete(listener); };
479
+ }
442
480
  function destroy() {
443
481
  if (destroyed) return;
444
482
  destroyed = true;
483
+ stepListeners.clear();
445
484
  if (mounted.get(container) === controller) mounted.delete(container);
446
485
  playing = false;
447
486
  cancelAnimationFrame(raf);
@@ -450,7 +489,7 @@ export function mountPlayer(container, scene, options = {}) {
450
489
  themeQuery?.removeEventListener?.("change", applyTheme);
451
490
  if (g.__motionKit[id] === controller) delete g.__motionKit[id];
452
491
  }
453
- const controller = { seek, play, pause, seekStep, playToStep, destroy, get time() { return t; }, scene };
492
+ const controller = { seek, play, pause, seekStep, playToStep, onStep, destroy, get time() { return t; }, scene };
454
493
  const g = /** @type {any} */ (globalThis);
455
494
  g.__motionKit = g.__motionKit ?? {};
456
495
  g.__motionKit[id] = controller;