@liqweed/motion-kit 0.0.0-stage → 0.2.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 (55) hide show
  1. package/.claude-plugin/marketplace.json +13 -0
  2. package/.claude-plugin/plugin.json +9 -0
  3. package/LICENSE +21 -0
  4. package/README.md +119 -2
  5. package/adapters/astro/AnimatedDiagram.astro +55 -0
  6. package/adapters/page/README.md +22 -0
  7. package/adapters/slidev/AnimatedDiagram.vue +137 -0
  8. package/brand/logo.scene.mjs +115 -0
  9. package/cli/motion-kit.mjs +239 -0
  10. package/docs/spec/technique.md +447 -0
  11. package/examples/agent-loop.json +18 -0
  12. package/examples/custom-pulse.scene.mjs +141 -0
  13. package/examples/integrations.json +20 -0
  14. package/examples/order-flow.json +17 -0
  15. package/examples/release-pipeline.json +17 -0
  16. package/examples/smart-home.json +17 -0
  17. package/lib/build.mjs +62 -0
  18. package/lib/bundle.mjs +68 -0
  19. package/lib/check.mjs +86 -0
  20. package/lib/export.mjs +113 -0
  21. package/lib/icon.mjs +41 -0
  22. package/lib/load.mjs +53 -0
  23. package/lib/raster.mjs +69 -0
  24. package/lib/video.mjs +77 -0
  25. package/package.json +69 -5
  26. package/runtime/bake.mjs +61 -0
  27. package/runtime/motion.mjs +154 -0
  28. package/runtime/parts.mjs +123 -0
  29. package/runtime/player.mjs +207 -0
  30. package/runtime/scene.mjs +101 -0
  31. package/runtime/style.mjs +142 -0
  32. package/runtime/svg.mjs +165 -0
  33. package/runtime/types/hub-spoke.mjs +215 -0
  34. package/runtime/types/index.mjs +25 -0
  35. package/runtime/types/sequence.mjs +201 -0
  36. package/runtime/wrap.mjs +44 -0
  37. package/skills/animated-diagram/SKILL.md +90 -0
  38. package/skills/animated-diagram/references/custom-scenes.md +56 -0
  39. package/skills/animated-diagram/references/ecosystem.md +28 -0
  40. package/skills/animated-diagram/references/interactivity.md +38 -0
  41. package/skills/animated-diagram/references/motion-vocabulary.md +70 -0
  42. package/skills/animated-diagram/references/qc.md +41 -0
  43. package/skills/animated-diagram/references/scene-types.md +59 -0
  44. package/skills/animated-diagram/references/styles.md +55 -0
  45. package/skills/animated-diagram/references/targets.md +27 -0
  46. package/skills/animated-diagram/references/technique.md +148 -0
  47. package/skills/motion-render/SKILL.md +68 -0
  48. package/skills/motion-render/references/formats.md +18 -0
  49. package/skills/motion-render/references/slides.md +18 -0
  50. package/skills/motion-render/references/video.md +61 -0
  51. package/skills/project-logo/SKILL.md +72 -0
  52. package/skills/project-logo/references/design.md +22 -0
  53. package/skills/project-logo/references/discovery.md +15 -0
  54. package/skills/project-logo/references/external-prompt.md +23 -0
  55. package/styles/neutral.json +26 -0
@@ -0,0 +1,101 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · the scene contract.
5
+ *
6
+ * A scene is an animated diagram as a pure function of time:
7
+ *
8
+ * {
9
+ * id, width, height, // viewBox
10
+ * duration, // seconds until the final state
11
+ * title, description, // accessible name + description
12
+ * steps: [{ at, label, detail? }], // build steps; last = finished diagram
13
+ * frame(t) → string // inner SVG markup at time t
14
+ * }
15
+ *
16
+ * frame(t) may depend on nothing but t and the scene's own constants: no Date,
17
+ * no Math.random(), no performance.now(), no state from earlier frames. That is
18
+ * what lets a player jump anywhere, an exporter write exactly the frame a slide
19
+ * needs, and a video renderer sample frame f at t = f / fps.
20
+ */
21
+ import { esc, num } from "./svg.mjs";
22
+ import { normalizeStyle, cssVars, resolveTokens } from "./style.mjs";
23
+
24
+ /** Formats: name → viewBox. Layouts are computed per format, never cropped. */
25
+ export const FORMATS = {
26
+ "16:9": { width: 960, height: 540 },
27
+ "4:3": { width: 960, height: 720 },
28
+ "1:1": { width: 720, height: 720 },
29
+ "9:16": { width: 540, height: 960 },
30
+ wide: { width: 960, height: 0 }, // strip: height computed by the scene type
31
+ tall: { width: 360, height: 0 }, // phone column: height computed by the scene type
32
+ };
33
+
34
+ /** Pick a localized string: plain string, or { en, nl, ... }. */
35
+ export function localize(value, locale = "en") {
36
+ if (value == null) return "";
37
+ if (typeof value === "string") return value;
38
+ if (value[locale] != null) return value[locale];
39
+ const first = Object.values(value)[0];
40
+ if (first == null) return "";
41
+ return first;
42
+ }
43
+
44
+ export function validateScene(scene) {
45
+ for (const k of ["id", "width", "height", "duration", "title", "description", "steps", "frame"]) {
46
+ if (scene[k] === undefined || scene[k] === "") throw new Error(`scene ${scene.id ?? "?"} is missing "${k}"`);
47
+ }
48
+ if (!scene.steps.length) throw new Error(`scene ${scene.id}: needs at least one step`);
49
+ let prev = -Infinity;
50
+ for (const s of scene.steps) {
51
+ if (!(s.at > prev)) throw new Error(`scene ${scene.id}: steps must be strictly increasing in time`);
52
+ if (s.at > scene.duration + 1e-9) throw new Error(`scene ${scene.id}: step "${s.label}" is after the duration`);
53
+ if (!s.label) throw new Error(`scene ${scene.id}: every step needs a label`);
54
+ prev = s.at;
55
+ }
56
+ return scene;
57
+ }
58
+
59
+ /**
60
+ * Complete, accessible <svg> for `scene` at time t (clamped to the scene).
61
+ *
62
+ * options:
63
+ * standalone resolve tokens to literal colours, write width/height (exports)
64
+ * theme "light" | "dark" (standalone only)
65
+ * style style object or "neutral"
66
+ * background paint the style's bg colour behind the diagram (video, PNG for slides)
67
+ * scale width/height multiplier for standalone output
68
+ * idPrefix unique prefix for <title>/<desc> ids when several diagrams share a page
69
+ */
70
+ export function renderSvg(scene, t, options = {}) {
71
+ const style = normalizeStyle(options.style);
72
+ const time = Math.min(Math.max(t, 0), scene.duration);
73
+ const id = esc(options.idPrefix ?? scene.id);
74
+ const scale = options.scale ?? 1;
75
+ const size = options.standalone ? ` width="${num(scene.width * scale)}" height="${num(scene.height * scale)}"` : "";
76
+ const vars = options.standalone ? "" : ` style="${cssVars(style, options.theme ?? "light")}"`;
77
+ const bg = options.background ? `<rect width="100%" height="100%" fill="var(--mk-bg)"/>` : "";
78
+ const markup =
79
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${num(scene.width)} ${num(scene.height)}"${size}` +
80
+ ` font-family="${esc(style.font)}" role="img" aria-labelledby="${id}-title ${id}-desc"${options.live ? "" : vars}>` +
81
+ `<title id="${id}-title">${esc(scene.title)}</title>` +
82
+ `<desc id="${id}-desc">${esc(scene.description)}</desc>` +
83
+ bg +
84
+ scene.frame(time) +
85
+ `</svg>`;
86
+ return options.standalone ? resolveTokens(markup, style, options.theme ?? "light") : markup;
87
+ }
88
+
89
+ /** Time of each step (convenience). */
90
+ export function stepTimes(scene) {
91
+ return scene.steps.map((s) => s.at);
92
+ }
93
+
94
+ /** Index of the step shown at time t (last step whose at ≤ t), or -1 before the first. */
95
+ export function stepIndexAt(scene, t) {
96
+ let idx = -1;
97
+ scene.steps.forEach((s, i) => {
98
+ if (t >= s.at - 1e-9) idx = i;
99
+ });
100
+ return idx;
101
+ }
@@ -0,0 +1,142 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · visual styles.
5
+ *
6
+ * Scenes never contain colour literals. They reference tokens — `tok("accent")`
7
+ * → `var(--mk-accent)` — and a style supplies the values. Live players set the
8
+ * custom properties on their container (light + dark); standalone exports
9
+ * resolve them to literal values, because slide apps, rasterizers and image
10
+ * viewers do not understand CSS variables.
11
+ *
12
+ * A style is plain data:
13
+ * { name, font, radius, stroke, light: {token: color}, dark: {token: color} }
14
+ */
15
+
16
+ /**
17
+ * A visual style: font, shape constants and one colour per token, per theme.
18
+ * @typedef {{ name?: string, font: string, radius: number, stroke: number, light: Record<string, string>, dark: Record<string, string> }} Style
19
+ */
20
+
21
+ export const TOKENS = [
22
+ "bg", // canvas behind the diagram (exports, video)
23
+ "surface", // pending node fill
24
+ "ink", // primary text
25
+ "muted", // secondary text, pending labels
26
+ "line", // pending strokes and connectors
27
+ "accent", // active / reached state fill and path
28
+ "onAccent", // text and glyphs on accent
29
+ "emphasis", // the single emphasis element (marker, highlight)
30
+ ];
31
+
32
+ export const NEUTRAL = Object.freeze({
33
+ name: "neutral",
34
+ font: 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif',
35
+ radius: 10,
36
+ stroke: 2,
37
+ light: Object.freeze({
38
+ bg: "#ffffff",
39
+ surface: "#f3f4f6",
40
+ ink: "#111827",
41
+ muted: "#4b5563",
42
+ line: "#8b929c",
43
+ accent: "#2563eb",
44
+ onAccent: "#ffffff",
45
+ emphasis: "#d97706",
46
+ }),
47
+ dark: Object.freeze({
48
+ bg: "#0f1115",
49
+ surface: "#1c2029",
50
+ ink: "#f3f4f6",
51
+ muted: "#a7adb8",
52
+ line: "#6b7280",
53
+ accent: "#2563eb",
54
+ onAccent: "#ffffff",
55
+ emphasis: "#f59e0b",
56
+ }),
57
+ });
58
+
59
+ export function tok(name) {
60
+ if (!TOKENS.includes(name)) throw new Error(`unknown style token "${name}"`);
61
+ return `var(--mk-${name})`;
62
+ }
63
+
64
+ /** Fill in any missing fields from NEUTRAL and validate token names. */
65
+ export function normalizeStyle(style) {
66
+ if (!style || style === "neutral") return NEUTRAL;
67
+ const out = {
68
+ name: style.name ?? "custom",
69
+ font: style.font ?? NEUTRAL.font,
70
+ radius: style.radius ?? NEUTRAL.radius,
71
+ stroke: style.stroke ?? NEUTRAL.stroke,
72
+ light: { ...NEUTRAL.light, ...(style.light ?? {}) },
73
+ dark: { ...NEUTRAL.dark, ...(style.dark ?? style.light ?? {}) },
74
+ };
75
+ for (const theme of ["light", "dark"]) {
76
+ for (const key of Object.keys(out[theme])) {
77
+ if (!TOKENS.includes(key)) throw new Error(`style "${out.name}": unknown token "${key}" in ${theme}`);
78
+ if (!/^#[0-9a-f]{6}$/i.test(out[theme][key])) {
79
+ throw new Error(`style "${out.name}": ${theme}.${key} must be a #rrggbb colour, got "${out[theme][key]}"`);
80
+ }
81
+ }
82
+ }
83
+ return out;
84
+ }
85
+
86
+ /** CSS custom-property declarations for one theme. */
87
+ export function cssVars(style, theme = "light") {
88
+ const s = normalizeStyle(style);
89
+ return TOKENS.map((t) => `--mk-${t}:${s[theme][t]}`).join(";");
90
+ }
91
+
92
+ /** Replace every var(--mk-token) with its literal value. Unknown tokens throw. */
93
+ export function resolveTokens(markup, style, theme = "light") {
94
+ const s = normalizeStyle(style);
95
+ return markup.replace(/var\(--mk-([a-zA-Z]+)\)/g, (_, name) => {
96
+ const v = s[theme][name];
97
+ if (!v) throw new Error(`unknown style token "${name}"`);
98
+ return v;
99
+ });
100
+ }
101
+
102
+ /* ---------------------------------------------------------------- contrast */
103
+
104
+ function channel(c) {
105
+ const v = c / 255;
106
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
107
+ }
108
+ function luminance(hex) {
109
+ const n = Number.parseInt(hex.slice(1), 16);
110
+ return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255);
111
+ }
112
+ export function contrast(a, b) {
113
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
114
+ return (hi + 0.05) / (lo + 0.05);
115
+ }
116
+
117
+ /**
118
+ * WCAG checks a style must pass: text ≥ 4.5:1, strokes and shapes ≥ 3:1.
119
+ * @returns {string[]} problems (empty = ok)
120
+ */
121
+ export function checkContrast(style) {
122
+ const s = normalizeStyle(style);
123
+ /** @type {[string, string, number][]} */
124
+ const rules = [
125
+ ["ink", "bg", 4.5],
126
+ ["ink", "surface", 4.5],
127
+ ["muted", "bg", 4.5],
128
+ ["muted", "surface", 4.5],
129
+ ["onAccent", "accent", 4.5],
130
+ ["line", "bg", 3],
131
+ ["accent", "bg", 3],
132
+ ["emphasis", "bg", 3],
133
+ ];
134
+ const problems = [];
135
+ for (const theme of ["light", "dark"]) {
136
+ for (const [fg, bg, min] of rules) {
137
+ const r = contrast(s[theme][fg], s[theme][bg]);
138
+ if (r < min) problems.push(`${s.name} ${theme}: ${fg} on ${bg} is ${r.toFixed(2)}:1, needs ${min}:1`);
139
+ }
140
+ }
141
+ return problems;
142
+ }
@@ -0,0 +1,165 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · SVG string builder and geometry.
5
+ *
6
+ * Scenes return strings, so one frame can be mounted in a browser, written to a
7
+ * standalone .svg, rasterized, or baked. Text and attribute values are escaped
8
+ * here; numbers are rounded here. Numbers you interpolate into a template
9
+ * string yourself (transform, points, path d) must go through `num()`.
10
+ */
11
+
12
+ const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
13
+
14
+ export function esc(value) {
15
+ return String(value).replace(/[&<>"']/g, (c) => ESCAPES[c]);
16
+ }
17
+
18
+ /** Round to `digits` decimals (default 2). Never returns "-0". */
19
+ export function num(n, digits = 2) {
20
+ if (!Number.isFinite(n)) throw new Error(`num(): not a finite number: ${n}`);
21
+ const f = 10 ** digits;
22
+ const r = Math.round(n * f) / f;
23
+ return String(Object.is(r, -0) ? 0 : r);
24
+ }
25
+
26
+ export function attrString(attrs) {
27
+ let out = "";
28
+ for (const [name, value] of Object.entries(attrs)) {
29
+ if (value === undefined || value === null || value === false) continue;
30
+ if (name === "opacity" && typeof value === "number" && Math.round(value * 1000) >= 1000) continue;
31
+ const v = typeof value === "number" ? num(value, name === "opacity" ? 3 : 2) : esc(value);
32
+ out += ` ${name}="${v}"`;
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** Element whose children are already-built (trusted) markup. */
38
+ export function el(tag, attrs = {}, ...children) {
39
+ // An element whose opacity rounds to 0 is invisible: drop it, so frames that
40
+ // look identical are byte-identical.
41
+ if (typeof attrs.opacity === "number" && Math.round(attrs.opacity * 1000) <= 0) return "";
42
+ const body = children.flat().filter(Boolean).join("");
43
+ return body === "" ? `<${tag}${attrString(attrs)}/>` : `<${tag}${attrString(attrs)}>${body}</${tag}>`;
44
+ }
45
+
46
+ /** `<text>` with escaped content. A string[] becomes stacked <tspan> lines. */
47
+ export function text(attrs, content, lineHeight = 1.25) {
48
+ if (Array.isArray(content)) {
49
+ if (content.length === 1) return `<text${attrString(attrs)}>${esc(content[0])}</text>`;
50
+ const size = Number(attrs["font-size"] ?? 14);
51
+ const x = attrs.x ?? 0;
52
+ const first = -((content.length - 1) * lineHeight * size) / 2;
53
+ const spans = content
54
+ .map((line, i) => `<tspan x="${typeof x === "number" ? num(x) : esc(x)}" dy="${num(i === 0 ? first : lineHeight * size)}">${esc(line)}</tspan>`)
55
+ .join("");
56
+ return `<text${attrString(attrs)}>${spans}</text>`;
57
+ }
58
+ return `<text${attrString(attrs)}>${esc(content)}</text>`;
59
+ }
60
+
61
+ /** `translate(x y)` / `scale(s)` with rounding. */
62
+ export function translate(x, y) {
63
+ return `translate(${num(x)} ${num(y)})`;
64
+ }
65
+ export function scaleAbout(s, cx, cy) {
66
+ return `translate(${num(cx)} ${num(cy)}) scale(${num(s, 4)}) translate(${num(-cx)} ${num(-cy)})`;
67
+ }
68
+
69
+ /** Group with opacity; returns "" when fully transparent (keeps frames small). */
70
+ export function fade(opacity, attrs, ...children) {
71
+ const o = Math.round(opacity * 1000) / 1000; // decide on the rounded value, so 0.9999 ≡ 1
72
+ if (o <= 0) return "";
73
+ return el("g", { ...attrs, opacity: o >= 1 ? undefined : o }, ...children);
74
+ }
75
+
76
+ /* ---------------------------------------------------------------- geometry */
77
+
78
+ export function dist(a, b) {
79
+ return Math.hypot(b.x - a.x, b.y - a.y);
80
+ }
81
+
82
+ export function pointOnLine(a, b, p) {
83
+ return { x: a.x + (b.x - a.x) * p, y: a.y + (b.y - a.y) * p };
84
+ }
85
+
86
+ /** Shorten a segment by `ra` at the start and `rb` at the end (e.g. node radii). */
87
+ export function trimSegment(a, b, ra, rb = ra) {
88
+ const d = dist(a, b);
89
+ if (d <= ra + rb) return [a, a];
90
+ return [pointOnLine(a, b, ra / d), pointOnLine(a, b, 1 - rb / d)];
91
+ }
92
+
93
+ /** Polyline helpers: total length and point at a fraction of arc length. */
94
+ export function polyline(points) {
95
+ const segs = [];
96
+ let total = 0;
97
+ for (let i = 1; i < points.length; i++) {
98
+ const len = dist(points[i - 1], points[i]);
99
+ segs.push({ a: points[i - 1], b: points[i], start: total, len });
100
+ total += len;
101
+ }
102
+ return {
103
+ length: total,
104
+ d: points.map((p, i) => `${i === 0 ? "M" : "L"}${num(p.x)} ${num(p.y)}`).join(" "),
105
+ at(f) {
106
+ const target = Math.min(Math.max(f, 0), 1) * total;
107
+ for (const s of segs) {
108
+ if (target <= s.start + s.len || s === segs[segs.length - 1]) {
109
+ return pointOnLine(s.a, s.b, s.len === 0 ? 0 : (target - s.start) / s.len);
110
+ }
111
+ }
112
+ return points[0];
113
+ },
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Cubic Bézier with an arc-length lookup table, computed without a DOM, so a
119
+ * marker can travel along a curve at constant speed in Node and the browser.
120
+ */
121
+ export function cubic(p0, p1, p2, p3, samples = 64) {
122
+ const pt = (s) => {
123
+ const u = 1 - s;
124
+ return {
125
+ x: u * u * u * p0.x + 3 * u * u * s * p1.x + 3 * u * s * s * p2.x + s * s * s * p3.x,
126
+ y: u * u * u * p0.y + 3 * u * u * s * p1.y + 3 * u * s * s * p2.y + s * s * s * p3.y,
127
+ };
128
+ };
129
+ const lut = [0];
130
+ let prev = p0;
131
+ for (let i = 1; i <= samples; i++) {
132
+ const p = pt(i / samples);
133
+ lut.push(lut[i - 1] + dist(prev, p));
134
+ prev = p;
135
+ }
136
+ const length = lut[samples];
137
+ return {
138
+ length,
139
+ d: `M${num(p0.x)} ${num(p0.y)} C${num(p1.x)} ${num(p1.y)} ${num(p2.x)} ${num(p2.y)} ${num(p3.x)} ${num(p3.y)}`,
140
+ at(f) {
141
+ const target = Math.min(Math.max(f, 0), 1) * length;
142
+ let lo = 0;
143
+ let hi = samples;
144
+ while (hi - lo > 1) {
145
+ const mid = (lo + hi) >> 1;
146
+ if (lut[mid] < target) lo = mid;
147
+ else hi = mid;
148
+ }
149
+ const span = lut[hi] - lut[lo];
150
+ const s = (lo + (span === 0 ? 0 : (target - lut[lo]) / span)) / samples;
151
+ return pt(s);
152
+ },
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Draw-on stroke: dasharray/dashoffset for progress p of a path of `length`.
158
+ * Returns null while p ≤ 0 — a zero-length dash with round caps still paints a
159
+ * dot, so callers must skip the element entirely.
160
+ */
161
+ export function drawOn(length, p) {
162
+ if (p <= 0) return null;
163
+ if (p >= 1) return {};
164
+ return { "stroke-dasharray": `${num(length)} ${num(length)}`, "stroke-dashoffset": num(length * (1 - p)) };
165
+ }
@@ -0,0 +1,215 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · scene type "hub-spoke".
5
+ *
6
+ * Helps the viewer understand: one central thing connects to several others
7
+ * (integrations, data sources, stakeholders, outputs). Storyboard: the hub and
8
+ * every spoke appear (skeleton first), the hub activates, then one link at a
9
+ * time draws from the hub to a spoke (direction "out") or from a spoke to the
10
+ * hub ("in"), carrying an emphasis dot; the spoke turns accent when reached.
11
+ *
12
+ * Spec:
13
+ * { type: "hub-spoke", id, title, description,
14
+ * hub: { label, detail? },
15
+ * spokes: [{ label, detail? }], // 2–10
16
+ * direction?: "out" | "in", // default "out"
17
+ * fontSize?: number }
18
+ */
19
+ import { easeOut, easeStandard, progress, window01 } from "../motion.mjs";
20
+ import { boxNode, FONT_MIN, rectEdge } from "../parts.mjs";
21
+ import { FORMATS, localize } from "../scene.mjs";
22
+ import { tok } from "../style.mjs";
23
+ import { drawOn, el, pointOnLine } from "../svg.mjs";
24
+ import { wrapLabel } from "../wrap.mjs";
25
+
26
+ const ENTER = 0.4;
27
+ const ENTER_GAP = 0.08;
28
+ const FILL = 0.25;
29
+ const LINK = 0.45;
30
+ const PERIOD = LINK + FILL + 0.05;
31
+ const TAIL = 0.4;
32
+ const PAD = 24;
33
+ const CHAR = 0.56;
34
+
35
+ function overlaps(a, b, gap = 6) {
36
+ 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;
37
+ }
38
+
39
+ function layout(f, n, fs) {
40
+ const W = f.width;
41
+ const fixed = f.height > 0;
42
+ const narrow = f.name === "tall" || (fixed && W / f.height < 0.8);
43
+ const lineH = fs * 1.25;
44
+ const boxH = 2 * lineH + 20;
45
+ if (narrow) {
46
+ // Tree: hub on top (left-aligned), a trunk down the left edge, one
47
+ // branch into each spoke. The trunk never crosses a box.
48
+ const trunkX = PAD + 14;
49
+ const hubW = Math.min(W - 2 * PAD, Math.max(200, W * 0.6));
50
+ const boxX = trunkX + 26;
51
+ const boxW = W - PAD - boxX;
52
+ const minGap = 14;
53
+ const gap = fixed ? Math.max(minGap, Math.min(48, (f.height - 2 * PAD - (n + 1) * boxH - 40) / n)) : minGap;
54
+ const used = boxH + 40 + n * (boxH + gap);
55
+ const H = fixed ? f.height : used + 2 * PAD - gap;
56
+ const top = (H - used + gap) / 2;
57
+ const hub = { x: PAD, y: top, w: hubW, h: boxH };
58
+ const spokes = Array.from({ length: n }, (_, i) => ({ x: boxX, y: top + boxH + 40 + i * (boxH + gap), w: boxW, h: boxH }));
59
+ return { W, H, hub, spokes, boxH, lineH, trunkX, hubChars: Math.floor((hubW - 20) / (fs * CHAR)), spokeChars: Math.floor((boxW - 20) / (fs * CHAR)), narrow };
60
+ }
61
+ const H = fixed ? f.height : Math.round(W * 0.5625);
62
+ const boxW = Math.min(fs * 12, (W - 2 * PAD) / 4.2);
63
+ const hubW = Math.min(fs * 15, boxW * 1.25);
64
+ const cx = W / 2;
65
+ const cy = H / 2;
66
+ const rx = W / 2 - PAD - boxW / 2;
67
+ const ry = H / 2 - PAD - boxH / 2;
68
+ const hub = { x: cx - hubW / 2, y: cy - boxH / 2, w: hubW, h: boxH };
69
+ const spokes = Array.from({ length: n }, (_, i) => {
70
+ const a = -Math.PI / 2 + (2 * Math.PI * i) / n;
71
+ const x = cx + rx * Math.cos(a);
72
+ const y = cy + ry * Math.sin(a);
73
+ return { x: x - boxW / 2, y: y - boxH / 2, w: boxW, h: boxH };
74
+ });
75
+ return { W, H, hub, spokes, boxH, lineH, hubChars: Math.floor((hubW - 20) / (fs * CHAR)), spokeChars: Math.floor((boxW - 20) / (fs * CHAR)), narrow };
76
+ }
77
+
78
+ function layoutProblem(L) {
79
+ const all = [L.hub, ...L.spokes];
80
+ for (let i = 0; i < all.length; i++) {
81
+ const b = all[i];
82
+ if (b.x < 0 || b.y < 0 || b.x + b.w > L.W + 0.01 || b.y + b.h > L.H + 0.01) return "a node falls outside the canvas";
83
+ for (let j = i + 1; j < all.length; j++) if (overlaps(all[i], all[j])) return "nodes overlap";
84
+ }
85
+ return null;
86
+ }
87
+
88
+ export function hubSpoke(spec, { format = "16:9", locale = "en" } = {}) {
89
+ const spokesSpec = spec.spokes ?? [];
90
+ const n = spokesSpec.length;
91
+ if (!spec.hub) throw new Error(`hub-spoke "${spec.id}": needs a hub`);
92
+ if (n < 2 || n > 10) throw new Error(`hub-spoke "${spec.id}": needs 2–10 spokes, got ${n}`);
93
+ const f = typeof format === "string" ? { name: format, ...FORMATS[format] } : format;
94
+ if (!f.width) throw new Error(`unknown format "${format}"`);
95
+ const dirIn = spec.direction === "in";
96
+ const hubLabel = localize(spec.hub.label, locale);
97
+ const labels = spokesSpec.map((s) => localize(s.label, locale));
98
+ // Largest font (≤ max) at which the layout fits and every label wraps.
99
+ const maxFs = spec.fontSize ?? (f.height > 0 ? 20 : 16);
100
+ let L;
101
+ let fs;
102
+ let hubLines;
103
+ let spokeLines;
104
+ let why = "";
105
+ for (fs = maxFs; fs >= FONT_MIN; fs--) {
106
+ const cand = layout(f, n, fs);
107
+ const problem = layoutProblem(cand);
108
+ if (problem) {
109
+ why = problem;
110
+ continue;
111
+ }
112
+ try {
113
+ hubLines = wrapLabel(hubLabel, cand.hubChars, 2);
114
+ spokeLines = labels.map((l) => wrapLabel(l, cand.spokeChars, 2));
115
+ L = cand;
116
+ break;
117
+ } catch (e) {
118
+ why = e instanceof Error ? e.message : String(e);
119
+ }
120
+ }
121
+ if (!L) throw new Error(`hub-spoke "${spec.id}": ${n} spokes do not fit format ${f.name} (${why}); use fewer spokes, shorter labels or a larger format`);
122
+ const spokes = spokesSpec.map((s, i) => ({ label: labels[i], detail: localize(s.detail, locale), lines: spokeLines[i] }));
123
+
124
+ // Link geometry: hub edge ↔ spoke edge (narrow: from hub bottom to spoke left).
125
+ const hc = { x: L.hub.x + L.hub.w / 2, y: L.hub.y + L.hub.h / 2 };
126
+ const links = L.spokes.map((b) => {
127
+ const sc = { x: b.x + b.w / 2, y: b.y + b.h / 2 };
128
+ let a;
129
+ let z;
130
+ if (L.narrow) {
131
+ a = { x: L.trunkX, y: L.hub.y + L.hub.h + 4 };
132
+ z = { x: b.x - 6, y: sc.y };
133
+ } else {
134
+ a = rectEdge(hc.x, hc.y, L.hub.w / 2, L.hub.h / 2, sc, 6);
135
+ z = rectEdge(sc.x, sc.y, b.w / 2, b.h / 2, hc, 6);
136
+ }
137
+ const pts = L.narrow ? (dirIn ? [z, { x: a.x, y: z.y }, a] : [a, { x: a.x, y: z.y }, z]) : dirIn ? [z, a] : [a, z];
138
+ let len = 0;
139
+ for (let i = 1; i < pts.length; i++) len += Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
140
+ return { pts, len };
141
+ });
142
+
143
+ const hubEnter = 0;
144
+ const spokeEnter = (i) => 0.2 + i * ENTER_GAP;
145
+ const HUB_ON = spokeEnter(n - 1) + ENTER + 0.1;
146
+ const linkStart = (i) => HUB_ON + FILL + 0.2 + i * PERIOD;
147
+ const spokeFill = (i) => (dirIn ? linkStart(i) - 0.0 : linkStart(i) + LINK);
148
+ // "in": the spoke lights first, then its link travels to the hub.
149
+ const fillStartIn = (i) => linkStart(i);
150
+ const linkStartIn = (i) => linkStart(i) + FILL;
151
+ const stepAt = (i) => (dirIn ? linkStartIn(i) + LINK : spokeFill(i) + FILL);
152
+ const duration = stepAt(n - 1) + TAIL;
153
+
154
+ function pointAlong(link, p) {
155
+ const target = p * link.len;
156
+ let acc = 0;
157
+ for (let i = 1; i < link.pts.length; i++) {
158
+ const seg = Math.hypot(link.pts[i].x - link.pts[i - 1].x, link.pts[i].y - link.pts[i - 1].y);
159
+ if (acc + seg >= target || i === link.pts.length - 1) return pointOnLine(link.pts[i - 1], link.pts[i], seg === 0 ? 0 : (target - acc) / seg);
160
+ acc += seg;
161
+ }
162
+ return link.pts[0];
163
+ }
164
+ const pathD = (link) => link.pts.map((p, i) => `${i === 0 ? "M" : "L"}${Math.round(p.x * 100) / 100} ${Math.round(p.y * 100) / 100}`).join(" ");
165
+
166
+ function frame(t) {
167
+ const out = [];
168
+ const sEnter = (i) => progress(t, spokeEnter(i), ENTER, easeOut);
169
+ links.forEach((link, i) => {
170
+ const shown = sEnter(i);
171
+ if (shown > 0) {
172
+ out.push(el("path", { d: pathD(link), fill: "none", stroke: tok("line"), "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: shown }));
173
+ }
174
+ const ls = dirIn ? linkStartIn(i) : linkStart(i);
175
+ const p = progress(t, ls, LINK, easeStandard);
176
+ const dash = drawOn(link.len, p);
177
+ if (dash) {
178
+ out.push(el("path", { d: pathD(link), fill: "none", stroke: tok("accent"), "stroke-width": 3, "stroke-linecap": "round", "stroke-linejoin": "round", ...dash }));
179
+ }
180
+ });
181
+ out.push(boxNode({ ...L.hub, lines: hubLines, fontSize: fs + 1, enter: progress(t, hubEnter, ENTER, easeOut), active: progress(t, HUB_ON, FILL, easeStandard), weight: 600 }));
182
+ spokes.forEach((s, i) => {
183
+ const fill = dirIn ? fillStartIn(i) : spokeFill(i);
184
+ out.push(boxNode({ ...L.spokes[i], lines: s.lines, fontSize: fs, enter: sEnter(i), active: progress(t, fill, FILL, easeStandard) }));
185
+ });
186
+ // Emphasis dot riding the active link; gone by the step's time.
187
+ links.forEach((link, i) => {
188
+ const ls = dirIn ? linkStartIn(i) : linkStart(i);
189
+ const p = progress(t, ls, LINK, easeStandard);
190
+ if (p <= 0) return;
191
+ const fadeOut = dirIn ? 1 - window01(t, ls + LINK - 0.12, ls + LINK) : 1 - progress(t, spokeFill(i), FILL, easeOut);
192
+ if (fadeOut <= 0) return;
193
+ const pos = pointAlong(link, p);
194
+ out.push(el("circle", { cx: pos.x, cy: pos.y, r: 6, fill: tok("emphasis"), opacity: fadeOut }));
195
+ });
196
+ return out.join("");
197
+ }
198
+
199
+ return {
200
+ id: `${spec.id}-${f.name.replace(":", "x")}`,
201
+ type: "hub-spoke",
202
+ format: f.name,
203
+ locale,
204
+ width: L.W,
205
+ height: L.H,
206
+ duration,
207
+ title: localize(spec.title, locale),
208
+ description: localize(spec.description, locale),
209
+ steps: [
210
+ { at: HUB_ON + FILL, label: hubLabel, detail: localize(spec.hub.detail, locale) },
211
+ ...spokes.map((s, i) => ({ at: stepAt(i), label: s.label, detail: s.detail })),
212
+ ],
213
+ frame,
214
+ };
215
+ }
@@ -0,0 +1,25 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · scene type registry.
5
+ *
6
+ * createScene(spec, { format, locale }) → validated scene
7
+ *
8
+ * New scene types: add a module exporting (spec, opts) → scene and register it
9
+ * here. A one-off diagram can skip the registry: write a module whose default
10
+ * export is (opts) → scene (see examples/custom-*.scene.mjs).
11
+ */
12
+ import { validateScene } from "../scene.mjs";
13
+ import { hubSpoke } from "./hub-spoke.mjs";
14
+ import { sequence } from "./sequence.mjs";
15
+
16
+ export const SCENE_TYPES = {
17
+ sequence,
18
+ "hub-spoke": hubSpoke,
19
+ };
20
+
21
+ export function createScene(spec, opts = {}) {
22
+ const make = SCENE_TYPES[spec.type];
23
+ if (!make) throw new Error(`unknown scene type "${spec.type}" (known: ${Object.keys(SCENE_TYPES).join(", ")})`);
24
+ return validateScene(make(spec, opts));
25
+ }