@liqweed/motion-kit 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +6 -3
- package/cli/motion-kit.mjs +86 -3
- package/docs/spec/technique.md +12 -2
- package/examples/pull-request.json +93 -0
- package/examples/pull-request.mmd +15 -0
- package/lib/layout.mjs +236 -0
- package/lib/mermaid.mjs +382 -0
- package/lib/outdated.mjs +122 -0
- package/package.json +8 -4
- package/runtime/kit.mjs +2 -2
- package/runtime/motion.mjs +61 -0
- package/runtime/style.mjs +35 -3
- package/runtime/types/flowchart.mjs +403 -0
- package/runtime/types/hub-spoke.mjs +2 -1
- package/runtime/types/index.mjs +2 -0
- package/runtime/types/sequence.mjs +2 -1
- package/runtime/types/stack.mjs +4 -3
- package/runtime/types/timeline.mjs +6 -3
- package/runtime/types/walk.mjs +2 -1
- package/skills/animated-diagram/SKILL.md +8 -3
- package/skills/animated-diagram/references/custom-scenes.md +4 -1
- package/skills/animated-diagram/references/ecosystem.md +3 -2
- package/skills/animated-diagram/references/motion-vocabulary.md +29 -0
- package/skills/animated-diagram/references/scene-types.md +63 -4
- package/skills/animated-diagram/references/styles.md +19 -0
- package/styles/neutral.json +4 -0
package/lib/mermaid.mjs
ADDED
|
@@ -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
|
+
}
|
package/lib/outdated.mjs
ADDED
|
@@ -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.
|
|
3
|
+
"version": "0.8.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 examples/player-states.json examples/checkout.json examples/connection.json",
|
|
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",
|
|
@@ -57,7 +57,8 @@
|
|
|
57
57
|
"bench:player": "node scripts/bench-player.mjs",
|
|
58
58
|
"snapshots:update": "node scripts/update-snapshots.mjs",
|
|
59
59
|
"gate:core": "npm run -s typecheck && npm run -s versions && npm test && npm run -s check && npm run -s media:check",
|
|
60
|
-
"gate": "npm run -s gate:core && npm run -s site"
|
|
60
|
+
"gate": "npm run -s gate:core && npm run -s site",
|
|
61
|
+
"skills:design": "DISABLE_TELEMETRY=1 npx -y skills@1.9.0 experimental_install --frozen-lockfile -a claude-code -a codex"
|
|
61
62
|
},
|
|
62
63
|
"optionalDependencies": {
|
|
63
64
|
"@resvg/resvg-js": "^2.6.2"
|
|
@@ -69,5 +70,8 @@
|
|
|
69
70
|
},
|
|
70
71
|
"workspaces": [
|
|
71
72
|
"website"
|
|
72
|
-
]
|
|
73
|
+
],
|
|
74
|
+
"overrides": {
|
|
75
|
+
"picomatch": "npm:@ryotsu/picomatch@4.0.7-a"
|
|
76
|
+
}
|
|
73
77
|
}
|
package/runtime/kit.mjs
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* from `motion-kit build` calls the factory the same way, with the bundled
|
|
22
22
|
* runtime as `kit`, after the CLI built it here once.
|
|
23
23
|
*/
|
|
24
|
-
import { ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 } from "./motion.mjs";
|
|
24
|
+
import { DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 } from "./motion.mjs";
|
|
25
25
|
import { FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId } from "./scene.mjs";
|
|
26
26
|
import { CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok } from "./style.mjs";
|
|
27
27
|
import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment } from "./svg.mjs";
|
|
@@ -34,7 +34,7 @@ import { estimateWidth, wrapLabel } from "./wrap.mjs";
|
|
|
34
34
|
* in one of those modules is added here (test/runtime.test.mjs checks).
|
|
35
35
|
*/
|
|
36
36
|
export const KIT = Object.freeze({
|
|
37
|
-
...{ ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
|
|
37
|
+
...{ DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
|
|
38
38
|
...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
|
|
39
39
|
...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
|
|
40
40
|
...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment },
|
package/runtime/motion.mjs
CHANGED
|
@@ -152,3 +152,64 @@ export function splitEdge(t, start, duration, lag = 0.07, ease = easeStandard) {
|
|
|
152
152
|
export function stagger(count, start, gap) {
|
|
153
153
|
return Array.from({ length: count }, (_, i) => start + i * gap);
|
|
154
154
|
}
|
|
155
|
+
|
|
156
|
+
/* ----------------------------------------------------- style curves */
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The two curves a style may name: `enter` for entrances, `move` for movement
|
|
160
|
+
* between two visible states, each as the four numbers of a CSS
|
|
161
|
+
* `cubic-bezier(x1, y1, x2, y2)`. The defaults are `easeOut` and `easeStandard`.
|
|
162
|
+
* @typedef {{ enter: readonly [number, number, number, number], move: readonly [number, number, number, number] }} Motion
|
|
163
|
+
*/
|
|
164
|
+
/** @type {Readonly<Motion>} */
|
|
165
|
+
export const DEFAULT_MOTION = Object.freeze({
|
|
166
|
+
enter: Object.freeze(/** @type {[number, number, number, number]} */ ([0, 0, 0.2, 1])),
|
|
167
|
+
move: Object.freeze(/** @type {[number, number, number, number]} */ ([0.4, 0, 0.2, 1])),
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A step frame must equal the frame 1 ms before it (the gate's settled-frame
|
|
172
|
+
* rule), and the shortest built-in move lasts about 0.2 s, so a curve has to be
|
|
173
|
+
* within rounding of 1 at 0.5 % of its duration before the end. The defaults are
|
|
174
|
+
* (about 1e-5 short of 1 there); a linear curve is 5e-3 short.
|
|
175
|
+
*/
|
|
176
|
+
const SETTLE_PROBE = 0.005;
|
|
177
|
+
const SETTLE_TOLERANCE = 2e-5;
|
|
178
|
+
/** Share of a curve's duration held at 1 when the curve does not settle by itself. */
|
|
179
|
+
const SETTLE_WINDOW = 0.05;
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* `curve` as it is, when it ends flat enough to settle on its own; otherwise
|
|
183
|
+
* the same curve finished in the first 95 % of its duration, so the last 5 % is
|
|
184
|
+
* held at exactly 1 and every step frame is settled whatever the curve.
|
|
185
|
+
* @param {(p: number) => number} curve
|
|
186
|
+
* @returns {(p: number) => number}
|
|
187
|
+
*/
|
|
188
|
+
function settled(curve) {
|
|
189
|
+
if (1 - curve(1 - SETTLE_PROBE) <= SETTLE_TOLERANCE) return curve;
|
|
190
|
+
return (p) => curve(Math.min(1, p / (1 - SETTLE_WINDOW)));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** @type {Map<string, { easeOut: (p: number) => number, easeStandard: (p: number) => number }>} */
|
|
194
|
+
const easingCache = new Map();
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* The entrance and movement curves of a style's `motion` (or the defaults).
|
|
198
|
+
* Scene types call this with `style.motion` once per frame, so a diagram moves
|
|
199
|
+
* on the page's own curve. The result is cached by curve. The endpoints stay
|
|
200
|
+
* fixed, and a curve that does not end flat (a linear one) finishes in the first
|
|
201
|
+
* 95 % of each move, so step frames are settled for every permitted curve.
|
|
202
|
+
* @param {Motion} [motion]
|
|
203
|
+
* @returns {{ easeOut: (p: number) => number, easeStandard: (p: number) => number }}
|
|
204
|
+
*/
|
|
205
|
+
export function easings(motion = DEFAULT_MOTION) {
|
|
206
|
+
if (motion === DEFAULT_MOTION) return { easeOut, easeStandard };
|
|
207
|
+
const key = `${motion.enter.join()}|${motion.move.join()}`;
|
|
208
|
+
let found = easingCache.get(key);
|
|
209
|
+
if (!found) {
|
|
210
|
+
if (easingCache.size >= 32) easingCache.clear();
|
|
211
|
+
found = { easeOut: settled(cubicBezier(...motion.enter)), easeStandard: settled(cubicBezier(...motion.move)) };
|
|
212
|
+
easingCache.set(key, found);
|
|
213
|
+
}
|
|
214
|
+
return found;
|
|
215
|
+
}
|