@liqweed/motion-kit 0.0.0-stage → 0.3.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 (57) 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 +141 -2
  5. package/adapters/astro/AnimatedDiagram.astro +55 -0
  6. package/adapters/element/README.md +49 -0
  7. package/adapters/element/motion-diagram.mjs +123 -0
  8. package/adapters/page/README.md +22 -0
  9. package/adapters/slidev/AnimatedDiagram.vue +137 -0
  10. package/brand/logo.scene.mjs +115 -0
  11. package/cli/motion-kit.mjs +239 -0
  12. package/docs/spec/technique.md +465 -0
  13. package/examples/agent-loop.json +18 -0
  14. package/examples/custom-pulse.scene.mjs +141 -0
  15. package/examples/integrations.json +20 -0
  16. package/examples/order-flow.json +17 -0
  17. package/examples/release-pipeline.json +17 -0
  18. package/examples/smart-home.json +17 -0
  19. package/lib/build.mjs +62 -0
  20. package/lib/bundle.mjs +68 -0
  21. package/lib/check.mjs +86 -0
  22. package/lib/export.mjs +113 -0
  23. package/lib/icon.mjs +41 -0
  24. package/lib/load.mjs +53 -0
  25. package/lib/raster.mjs +69 -0
  26. package/lib/video.mjs +77 -0
  27. package/package.json +69 -5
  28. package/runtime/bake.mjs +61 -0
  29. package/runtime/motion.mjs +154 -0
  30. package/runtime/parts.mjs +123 -0
  31. package/runtime/player.mjs +255 -0
  32. package/runtime/scene.mjs +101 -0
  33. package/runtime/style.mjs +142 -0
  34. package/runtime/svg.mjs +165 -0
  35. package/runtime/types/hub-spoke.mjs +215 -0
  36. package/runtime/types/index.mjs +25 -0
  37. package/runtime/types/sequence.mjs +201 -0
  38. package/runtime/wrap.mjs +44 -0
  39. package/skills/animated-diagram/SKILL.md +90 -0
  40. package/skills/animated-diagram/references/custom-scenes.md +56 -0
  41. package/skills/animated-diagram/references/ecosystem.md +28 -0
  42. package/skills/animated-diagram/references/interactivity.md +51 -0
  43. package/skills/animated-diagram/references/motion-vocabulary.md +70 -0
  44. package/skills/animated-diagram/references/qc.md +41 -0
  45. package/skills/animated-diagram/references/scene-types.md +59 -0
  46. package/skills/animated-diagram/references/styles.md +55 -0
  47. package/skills/animated-diagram/references/targets.md +27 -0
  48. package/skills/animated-diagram/references/technique.md +148 -0
  49. package/skills/motion-render/SKILL.md +79 -0
  50. package/skills/motion-render/references/formats.md +18 -0
  51. package/skills/motion-render/references/slides.md +18 -0
  52. package/skills/motion-render/references/video.md +61 -0
  53. package/skills/project-logo/SKILL.md +72 -0
  54. package/skills/project-logo/references/design.md +22 -0
  55. package/skills/project-logo/references/discovery.md +15 -0
  56. package/skills/project-logo/references/external-prompt.md +23 -0
  57. package/styles/neutral.json +26 -0
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
- "name": "@liqweed/motion-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@liqweed/motion-kit",
3
+ "version": "0.3.0",
4
+ "description": "Deterministic animated diagrams: scenes as pure functions of time, for live pages, slides, baked SVG and video.",
5
+ "keywords": [
6
+ "animation",
7
+ "diagrams",
8
+ "svg",
9
+ "slides",
10
+ "video",
11
+ "explainer",
12
+ "slidev",
13
+ "claude-code"
14
+ ],
15
+ "homepage": "https://github.com/liqweed/motion-kit#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/liqweed/motion-kit.git"
19
+ },
20
+ "bugs": "https://github.com/liqweed/motion-kit/issues",
21
+ "author": "Ophir Radnitz",
22
+ "type": "module",
23
+ "license": "MIT",
24
+ "files": [
25
+ "cli/",
26
+ "lib/",
27
+ "runtime/",
28
+ "adapters/",
29
+ "styles/",
30
+ "examples/",
31
+ "brand/",
32
+ "skills/",
33
+ ".claude-plugin/",
34
+ "docs/spec/"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "provenance": true
39
+ },
40
+ "engines": {
41
+ "node": ">=22"
42
+ },
43
+ "bin": {
44
+ "motion-kit": "cli/motion-kit.mjs"
45
+ },
46
+ "scripts": {
47
+ "prepare": "lefthook install || true",
48
+ "test": "node --test test/*.test.mjs",
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/custom-pulse.scene.mjs brand/logo.scene.mjs",
51
+ "media": "scripts/render-media.sh",
52
+ "media:check": "scripts/render-media.sh --check",
53
+ "site": "npm run -w website build",
54
+ "site:dev": "npm run -w website dev",
55
+ "site:deploy": "npm run -w website deploy",
56
+ "versions": "node scripts/check-versions.mjs",
57
+ "gate": "npm run -s typecheck && npm run -s versions && npm test && npm run -s check && npm run -s media:check && npm run -s site"
58
+ },
59
+ "optionalDependencies": {
60
+ "@resvg/resvg-js": "^2.6.2"
61
+ },
62
+ "devDependencies": {
63
+ "@types/node": "^22.20.5",
64
+ "lefthook": "^2.2.2",
65
+ "typescript": "^7.0.2"
66
+ },
67
+ "workspaces": [
68
+ "website"
69
+ ]
70
+ }
@@ -0,0 +1,61 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · bake: a scene → one zero-JavaScript animated SVG.
5
+ *
6
+ * For places that do not run scripts (Craft html-preview, GitHub READMEs,
7
+ * Obsidian notes, email, most embeds). The scene is sampled at `fps`; each
8
+ * distinct frame becomes a <g> that a CSS animation makes visible for exactly
9
+ * its time slice. Identical consecutive frames (holds) are merged, so a scene
10
+ * that rests between steps costs little. It plays once and holds the final
11
+ * frame; with prefers-reduced-motion the final frame shows immediately.
12
+ *
13
+ * Trade-off: file size grows with fps × duration (a 6 s scene at 15 fps is
14
+ * typically 150–400 KB). Use the live player where scripts are allowed.
15
+ */
16
+ import { renderSvg } from "./scene.mjs";
17
+ import { num } from "./svg.mjs";
18
+
19
+ export function bake(scene, options = {}) {
20
+ const fps = options.fps ?? 15;
21
+ const delay = options.delay ?? 0.3;
22
+ const total = Math.ceil(scene.duration * fps);
23
+ const frames = [];
24
+ for (let f = 0; f <= total; f++) {
25
+ const t = Math.min(f / fps, scene.duration);
26
+ const inner = innerOf(renderSvg(scene, t, { ...options, standalone: true, idPrefix: "mk-bake" }));
27
+ const last = frames[frames.length - 1];
28
+ if (last && last.body === inner) last.end = t;
29
+ else frames.push({ start: t, end: t, body: inner });
30
+ }
31
+ // Each slice lasts until the next one starts.
32
+ for (let i = 0; i < frames.length - 1; i++) frames[i].end = frames[i + 1].start;
33
+
34
+ const full = renderSvg(scene, scene.duration, { ...options, standalone: true, idPrefix: "mk-bake" });
35
+ const open = full.slice(0, full.indexOf(">") + 1);
36
+ const head = full.slice(open.length, full.indexOf("</desc>") + "</desc>".length);
37
+ const css = [
38
+ "@keyframes mk-show{from{visibility:visible}to{visibility:hidden}}",
39
+ "@keyframes mk-hold{from,to{visibility:visible}}",
40
+ ".mk-f{visibility:hidden;animation-timing-function:steps(1,end);animation-fill-mode:forwards}",
41
+ "@media (prefers-reduced-motion: reduce){.mk-f{animation:none!important;visibility:hidden}.mk-last{visibility:visible}}",
42
+ ];
43
+ const groups = frames.map((fr, i) => {
44
+ const isLast = i === frames.length - 1;
45
+ const name = isLast ? "mk-hold" : "mk-show";
46
+ const dur = isLast ? 0.001 : fr.end - fr.start;
47
+ const style = `animation-name:${name};animation-duration:${num(dur, 3)}s;animation-delay:${num(delay + fr.start, 3)}s`;
48
+ return `<g class="mk-f${isLast ? " mk-last" : ""}" style="${style}">${fr.body}</g>`;
49
+ });
50
+ return `${open}${head}<style>${css.join("")}</style>${groups.join("")}</svg>`;
51
+ }
52
+
53
+ function innerOf(svg) {
54
+ const start = svg.indexOf("</desc>") + "</desc>".length;
55
+ return svg.slice(start, svg.lastIndexOf("</svg>"));
56
+ }
57
+
58
+ /** How many distinct frames a bake will contain (for size budgeting). */
59
+ export function bakeStats(svg) {
60
+ return { frames: (svg.match(/class="mk-f/g) ?? []).length, bytes: svg.length };
61
+ }
@@ -0,0 +1,154 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · time helpers.
5
+ *
6
+ * A scene is a pure function of time. Everything in this module maps numbers to
7
+ * numbers with no state, so any frame can be computed without its predecessors.
8
+ * None of the curves overshoot: no bounce, no elastic.
9
+ */
10
+
11
+ /** Longest single entrance, in seconds. A whole scene may be longer. */
12
+ export const ENTRANCE_MAX = 0.6;
13
+
14
+ export function clamp01(x) {
15
+ return x <= 0 ? 0 : x >= 1 ? 1 : x;
16
+ }
17
+
18
+ export function lerp(from, to, p) {
19
+ return from + (to - from) * p;
20
+ }
21
+
22
+ /**
23
+ * CSS `cubic-bezier(x1, y1, x2, y2)` as a function of linear progress 0..1.
24
+ * Solves x(s) = p for the curve parameter s (Newton, then bisection), returns y(s).
25
+ */
26
+ export function cubicBezier(x1, y1, x2, y2) {
27
+ const cx = 3 * x1;
28
+ const bx = 3 * (x2 - x1) - cx;
29
+ const ax = 1 - cx - bx;
30
+ const cy = 3 * y1;
31
+ const by = 3 * (y2 - y1) - cy;
32
+ const ay = 1 - cy - by;
33
+ const x = (s) => ((ax * s + bx) * s + cx) * s;
34
+ const y = (s) => ((ay * s + by) * s + cy) * s;
35
+ const dx = (s) => (3 * ax * s + 2 * bx) * s + cx;
36
+ return (p) => {
37
+ if (p <= 0) return 0;
38
+ if (p >= 1) return 1;
39
+ let s = p;
40
+ for (let i = 0; i < 8; i++) {
41
+ const err = x(s) - p;
42
+ if (Math.abs(err) < 1e-7) return y(s);
43
+ const d = dx(s);
44
+ if (Math.abs(d) < 1e-7) break;
45
+ s -= err / d;
46
+ }
47
+ let lo = 0;
48
+ let hi = 1;
49
+ s = p;
50
+ for (let i = 0; i < 60 && hi - lo > 1e-9; i++) {
51
+ if (x(s) < p) lo = s;
52
+ else hi = s;
53
+ s = (lo + hi) / 2;
54
+ }
55
+ return y(s);
56
+ };
57
+ }
58
+
59
+ export const linear = (p) => clamp01(p);
60
+ /** Entrances: fast start, gentle landing. */
61
+ export const easeOut = cubicBezier(0, 0, 0.2, 1);
62
+ /** Movement between two visible states. */
63
+ export const easeStandard = cubicBezier(0.4, 0, 0.2, 1);
64
+ /** Exits. */
65
+ export const easeIn = cubicBezier(0.4, 0, 1, 1);
66
+
67
+ /**
68
+ * Eased progress 0..1 of an event that starts at `start` and lasts `duration`
69
+ * seconds. Holds 0 before, 1 after.
70
+ */
71
+ export function progress(t, start, duration, ease = easeOut) {
72
+ if (duration <= 0) return t >= start ? 1 : 0;
73
+ return ease(clamp01((t - start) / duration));
74
+ }
75
+
76
+ /** Linear 0..1 progress between two times (no easing). */
77
+ export function window01(t, start, end) {
78
+ return end <= start ? (t >= start ? 1 : 0) : clamp01((t - start) / (end - start));
79
+ }
80
+
81
+ /* ------------------------------------------------------------------ springs */
82
+
83
+ /**
84
+ * ωτ at which a critically damped step response is within 0.1 % of its target.
85
+ * Solves (1 + x)·e^(−x) = 0.001, so the final snap moves a 100 px travel by
86
+ * at most 0.1 px.
87
+ */
88
+ export const SPRING_SETTLE_X = 9.24;
89
+
90
+ /**
91
+ * Unit step response of a critically damped spring, closed form:
92
+ * s(τ) = 1 − (1 + ωτ)·e^(−ωτ) for τ > 0, else 0.
93
+ * Monotonic, never overshoots. Snaps to exactly 1 once ωτ ≥ SPRING_SETTLE_X so
94
+ * that "settled" frames are byte-identical.
95
+ *
96
+ * @param {number} tau seconds since the target changed
97
+ * @param {number} omega natural angular frequency (rad/s); higher = snappier
98
+ */
99
+ export function springStep(tau, omega = 12) {
100
+ if (tau <= 0) return 0;
101
+ const x = omega * tau;
102
+ if (x >= SPRING_SETTLE_X) return 1;
103
+ return 1 - (1 + x) * Math.exp(-x);
104
+ }
105
+
106
+ /** Seconds until a spring with this ω counts as settled. */
107
+ export function springSettleTime(omega = 12) {
108
+ return SPRING_SETTLE_X / omega;
109
+ }
110
+
111
+ /**
112
+ * Retargetable spring value at time t, by superposition. The spring is a linear
113
+ * time-invariant system, so the response to a piecewise-constant target is the
114
+ * exact sum of step responses. No frame depends on the previous one.
115
+ *
116
+ * value(t) = from + Σ (to_i − to_{i−1}) · s(t − at_i)
117
+ *
118
+ * @param {number} t
119
+ * @param {number} from initial value
120
+ * @param {{at:number,to:number}[]} changes target changes in time order
121
+ * @param {number} omega
122
+ */
123
+ export function springTo(t, from, changes, omega = 12) {
124
+ let value = from;
125
+ let prev = from;
126
+ for (const c of changes) {
127
+ value += (c.to - prev) * springStep(t - c.at, omega);
128
+ prev = c.to;
129
+ }
130
+ return value;
131
+ }
132
+
133
+ /**
134
+ * Split-edge motion for a moving shape: the leading edge moves first, the
135
+ * trailing edge follows `lag` seconds later with the same curve. The shape
136
+ * stretches during the move and settles to its original length, without
137
+ * overshoot.
138
+ *
139
+ * @returns {{lead:number, trail:number}} two eased progress values 0..1
140
+ */
141
+ export function splitEdge(t, start, duration, lag = 0.07, ease = easeStandard) {
142
+ return {
143
+ lead: progress(t, start, duration, ease),
144
+ trail: progress(t, start + lag, duration, ease),
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Staggered start times for `count` siblings in reading order.
150
+ * @returns {number[]}
151
+ */
152
+ export function stagger(count, start, gap) {
153
+ return Array.from({ length: count }, (_, i) => start + i * gap);
154
+ }
@@ -0,0 +1,123 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · shared drawing parts for scene types.
5
+ *
6
+ * Every part draws a two-state element (pending → active) as a cross-fade of
7
+ * two overlapping layers with opacities 1 − p and p. Interpolating between two
8
+ * colour tokens would need literal colours; cross-fading keeps scenes
9
+ * token-only and works the same in every renderer.
10
+ */
11
+ import { attrString, el, esc, fade, num, text, translate } from "./svg.mjs";
12
+ import { tok } from "./style.mjs";
13
+
14
+ export const FONT_MIN = 14; // smallest label size at 1× (viewBox units)
15
+
16
+ /**
17
+ * Optional icon: SVG path data drawn on a 24×24 grid with round strokes
18
+ * (Lucide/Feather style). `icon` is a string or string[] of path `d` values.
19
+ * Supply the path data in the spec; motion-kit ships no icon set.
20
+ */
21
+ export function iconPaths(icon, cx, cy, size, color, strokeWidth = 2) {
22
+ const paths = Array.isArray(icon) ? icon : [icon];
23
+ const s = size / 24;
24
+ return el(
25
+ "g",
26
+ {
27
+ transform: `translate(${num(cx - size / 2)} ${num(cy - size / 2)}) scale(${num(s, 4)})`,
28
+ fill: "none",
29
+ stroke: color,
30
+ "stroke-width": num(strokeWidth / s),
31
+ "stroke-linecap": "round",
32
+ "stroke-linejoin": "round",
33
+ },
34
+ ...paths.map((d) => el("path", { d })),
35
+ );
36
+ }
37
+
38
+ /** Content inside a node: icon, short glyph (≤ 3 chars), or nothing. */
39
+ function glyph(node, cx, cy, size, color) {
40
+ if (node.icon) return iconPaths(node.icon, cx, cy, size * 0.9, color);
41
+ if (node.glyph) {
42
+ return text(
43
+ { x: cx, y: cy, "text-anchor": "middle", "dominant-baseline": "central", "font-size": size * 0.62, "font-weight": 600, fill: color },
44
+ String(node.glyph).slice(0, 3),
45
+ );
46
+ }
47
+ return "";
48
+ }
49
+
50
+ /**
51
+ * Circular node with pending and active layers.
52
+ * @param {{ cx: number, cy: number, r: number, enter: number, active: number, node: string, strokeWidth?: number }} o
53
+ */
54
+ export function circleNode({ cx, cy, r, enter, active, node, strokeWidth = 2 }) {
55
+ if (enter <= 0) return "";
56
+ const dy = (1 - enter) * 8;
57
+ const g = r * 0.95;
58
+ const pending = el(
59
+ "g",
60
+ {},
61
+ el("circle", { cx, cy, r, fill: tok("surface"), stroke: tok("line"), "stroke-width": strokeWidth }),
62
+ glyph(node, cx, cy, g, tok("muted")),
63
+ );
64
+ const on = el(
65
+ "g",
66
+ {},
67
+ el("circle", { cx, cy, r, fill: tok("accent"), stroke: tok("accent"), "stroke-width": strokeWidth }),
68
+ glyph(node, cx, cy, g, tok("onAccent")),
69
+ );
70
+ return fade(enter, { transform: dy > 0.004 ? translate(0, dy) : undefined }, fade(1 - active, {}, pending), fade(active, {}, on));
71
+ }
72
+
73
+ /**
74
+ * Rounded box node with a wrapped label inside.
75
+ * @param {{ x: number, y: number, w: number, h: number, lines: string[], fontSize: number, enter: number, active: number, radius?: number, strokeWidth?: number, weight?: number }} o
76
+ */
77
+ export function boxNode({ x, y, w, h, lines, fontSize, enter, active, radius = 10, strokeWidth = 2, weight = 500 }) {
78
+ if (enter <= 0) return "";
79
+ const dy = (1 - enter) * 8;
80
+ const cx = x + w / 2;
81
+ const cy = y + h / 2;
82
+ const label = (fill) =>
83
+ text({ x: cx, y: cy, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fontSize, "font-weight": weight, fill }, lines);
84
+ const pending = el(
85
+ "g",
86
+ {},
87
+ el("rect", { x, y, width: w, height: h, rx: radius, fill: tok("surface"), stroke: tok("line"), "stroke-width": strokeWidth }),
88
+ label(tok("ink")),
89
+ );
90
+ const on = el(
91
+ "g",
92
+ {},
93
+ el("rect", { x, y, width: w, height: h, rx: radius, fill: tok("accent"), stroke: tok("accent"), "stroke-width": strokeWidth }),
94
+ label(tok("onAccent")),
95
+ );
96
+ return fade(enter, { transform: dy > 0.004 ? translate(0, dy) : undefined }, fade(1 - active, {}, pending), fade(active, {}, on));
97
+ }
98
+
99
+ /** Label text with a pending (muted) → active (ink) cross-fade. */
100
+ export function stateLabel({ x, y, lines, fontSize, anchor = "middle", baseline = "hanging", enter, active, weight = 500 }) {
101
+ if (enter <= 0) return "";
102
+ const attrs = (fill) => ({ x, y, "text-anchor": anchor, "dominant-baseline": baseline, "font-size": fontSize, "font-weight": weight, fill });
103
+ const block = (fill) => {
104
+ if (baseline === "central" || lines.length === 1) return text(attrs(fill), lines);
105
+ // hanging: stack downward from y
106
+ const spans = lines
107
+ .map((line, i) => `<tspan x="${num(x)}" dy="${num(i === 0 ? 0 : fontSize * 1.25)}">${esc(line)}</tspan>`)
108
+ .join("");
109
+ return `<text${attrString(attrs(fill))}>${spans}</text>`;
110
+ };
111
+ return fade(enter, {}, fade(1 - active, {}, block(tok("muted"))), fade(active, {}, block(tok("ink"))));
112
+ }
113
+
114
+ /** Point where the ray from a rect's centre toward `to` leaves the rect (+gap). */
115
+ export function rectEdge(cx, cy, hw, hh, to, gap = 0) {
116
+ const dx = to.x - cx;
117
+ const dy = to.y - cy;
118
+ if (dx === 0 && dy === 0) return { x: cx, y: cy };
119
+ const sx = dx === 0 ? Infinity : (hw + gap) / Math.abs(dx);
120
+ const sy = dy === 0 ? Infinity : (hh + gap) / Math.abs(dy);
121
+ const s = Math.min(sx, sy);
122
+ return { x: cx + dx * s, y: cy + dy * s };
123
+ }
@@ -0,0 +1,255 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · live player (browser only).
5
+ *
6
+ * mountPlayer(container, scene, options) → controller
7
+ *
8
+ * - Server/no-JS fallback: put the final frame in the container; the player
9
+ * replaces it on mount.
10
+ * - Plays once when ~40 % visible, then holds the final frame.
11
+ * - Always shows pause/play (WCAG 2.2.2), one button per step (jumps, no
12
+ * animation unless animateSteps is enabled), an optional scrubber, and captions.
13
+ * - prefers-reduced-motion: final frame immediately, no autoplay, no play button.
14
+ * - Keyboard: ←/→ previous/next step, Space play/pause, Home/End.
15
+ * - Capture hook: controller.seek(t), and window.__motionKit[id] for renderers.
16
+ *
17
+ * The player owns the clock (requestAnimationFrame); scenes stay pure.
18
+ */
19
+ import { cssVars, normalizeStyle } from "./style.mjs";
20
+ import { renderSvg, stepIndexAt } from "./scene.mjs";
21
+
22
+ const CSS = `
23
+ .mk-player{font-family:var(--mk-font);color:var(--mk-ink);background:transparent}
24
+ .mk-stage svg{display:block;width:100%;height:auto}
25
+ .mk-controls{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-top:10px}
26
+ .mk-btn{font:inherit;font-size:13px;line-height:1.2;padding:6px 10px;border-radius:8px;border:1px solid var(--mk-line);background:var(--mk-surface);color:var(--mk-ink);cursor:pointer}
27
+ .mk-btn[aria-current="step"]{background:var(--mk-accent);border-color:var(--mk-accent);color:var(--mk-onAccent)}
28
+ .mk-btn:focus-visible,.mk-scrub:focus-visible{outline:2px solid var(--mk-emphasis);outline-offset:2px}
29
+ .mk-play{min-width:72px}
30
+ .mk-scrub{flex:1 1 160px;accent-color:var(--mk-accent)}
31
+ .mk-caption{margin:8px 0 0;font-size:15px;line-height:1.45;color:var(--mk-muted);min-height:1.45em}
32
+ .mk-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
33
+ `;
34
+
35
+ const styledDocuments = new WeakSet();
36
+
37
+ /**
38
+ * Mount a scene with controls and a clock owned by this player.
39
+ * @param {HTMLElement} container
40
+ * @param {{ id: string, title: string, description: string, width: number, height: number, duration: number, steps: { at: number, label: string, detail?: string }[], frame: (t: number) => string }} scene
41
+ * @param {{ style?: Parameters<typeof normalizeStyle>[0], labels?: Record<string, string>, theme?: string, id?: string, injectCss?: boolean, scrubber?: boolean, captions?: boolean, autoplay?: string, animateSteps?: boolean }} [options]
42
+ * @returns The player controller; call destroy() before removing or replacing it.
43
+ */
44
+ export function mountPlayer(container, scene, options = {}) {
45
+ const style = normalizeStyle(options.style);
46
+ const labels = { play: "Play", pause: "Pause", replay: "Replay", steps: "Steps", ...(options.labels ?? {}) };
47
+ const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
48
+ /** @type {Document} */
49
+ const doc = container.ownerDocument;
50
+
51
+ if (!styledDocuments.has(doc) && options.injectCss !== false) {
52
+ const s = doc.createElement("style");
53
+ s.textContent = CSS;
54
+ doc.head.appendChild(s);
55
+ styledDocuments.add(doc);
56
+ }
57
+
58
+ const id = options.id ?? scene.id;
59
+ container.classList.add("mk-player");
60
+ const applyTheme = () => {
61
+ const dark = options.theme === "dark" || (options.theme !== "light" && typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches);
62
+ container.setAttribute("style", `${cssVars(style, dark ? "dark" : "light")};--mk-font:${style.font}`);
63
+ };
64
+ applyTheme();
65
+
66
+ container.innerHTML = "";
67
+ const stage = doc.createElement("div");
68
+ stage.className = "mk-stage";
69
+ stage.tabIndex = 0;
70
+ stage.setAttribute("aria-label", scene.title);
71
+ container.appendChild(stage);
72
+
73
+ const controls = doc.createElement("div");
74
+ controls.className = "mk-controls";
75
+ controls.setAttribute("role", "group");
76
+ controls.setAttribute("aria-label", scene.title);
77
+ container.appendChild(controls);
78
+
79
+ /** @type {HTMLButtonElement | null} */
80
+ let playBtn = null;
81
+ if (!reduced) {
82
+ playBtn = doc.createElement("button");
83
+ playBtn.type = "button";
84
+ playBtn.className = "mk-btn mk-play";
85
+ controls.appendChild(playBtn);
86
+ }
87
+ const stepBtns = scene.steps.map((s, i) => {
88
+ const b = doc.createElement("button");
89
+ b.type = "button";
90
+ b.className = "mk-btn";
91
+ b.textContent = `${i + 1}. ${s.label}`;
92
+ b.addEventListener("click", () => selectStep(i));
93
+ controls.appendChild(b);
94
+ return b;
95
+ });
96
+ /** @type {HTMLInputElement | null} */
97
+ let scrub = null;
98
+ if (options.scrubber) {
99
+ const input = doc.createElement("input");
100
+ input.type = "range";
101
+ input.className = "mk-scrub";
102
+ input.min = "0";
103
+ input.max = String(scene.duration);
104
+ input.step = "0.01";
105
+ input.setAttribute("aria-label", options.labels?.scrubber ?? "Timeline");
106
+ input.addEventListener("input", () => {
107
+ pause();
108
+ seek(Number(input.value));
109
+ });
110
+ controls.appendChild(input);
111
+ scrub = input;
112
+ }
113
+ const caption = doc.createElement("p");
114
+ caption.className = "mk-caption";
115
+ caption.setAttribute("aria-hidden", "true");
116
+ if (options.captions !== false) container.appendChild(caption);
117
+
118
+ const sr = doc.createElement("ol");
119
+ sr.className = "mk-sr";
120
+ for (const s of scene.steps) {
121
+ const li = doc.createElement("li");
122
+ li.textContent = s.detail ? `${s.label}: ${s.detail}` : s.label;
123
+ sr.appendChild(li);
124
+ }
125
+ container.appendChild(sr);
126
+
127
+ let t = 0;
128
+ let playing = false;
129
+ let raf = 0;
130
+ let wallStart = 0;
131
+ let tStart = 0;
132
+ let stopAt = scene.duration;
133
+ let autoplayPending = false;
134
+ let destroyed = false;
135
+ /** @type {IntersectionObserver | undefined} */
136
+ let visibilityObserver;
137
+
138
+ function draw() {
139
+ stage.innerHTML = renderSvg(scene, t, { style, idPrefix: id, live: true });
140
+ const idx = stepIndexAt(scene, t);
141
+ stepBtns.forEach((b, i) => (i === idx ? b.setAttribute("aria-current", "step") : b.removeAttribute("aria-current")));
142
+ caption.textContent = idx >= 0 ? (scene.steps[idx].detail ?? "") : "";
143
+ if (scrub) scrub.value = String(t);
144
+ if (playBtn) playBtn.textContent = playing ? labels.pause : t >= scene.duration ? labels.replay : labels.play;
145
+ }
146
+ function seek(time) {
147
+ if (destroyed) return;
148
+ playing = false;
149
+ cancelAnimationFrame(raf);
150
+ t = Math.min(Math.max(time, 0), scene.duration);
151
+ draw();
152
+ }
153
+ function tick(now) {
154
+ if (destroyed || !playing) return;
155
+ t = Math.min(tStart + (now - wallStart) / 1000, stopAt);
156
+ if (t >= stopAt) playing = false;
157
+ draw();
158
+ if (playing) raf = requestAnimationFrame(tick);
159
+ }
160
+ function play() {
161
+ if (reduced || destroyed) return;
162
+ if (t >= scene.duration) t = 0;
163
+ start(scene.duration);
164
+ }
165
+ function start(target) {
166
+ autoplayPending = false;
167
+ visibilityObserver?.disconnect();
168
+ stopAt = target;
169
+ playing = true;
170
+ tStart = t;
171
+ wallStart = performance.now();
172
+ cancelAnimationFrame(raf);
173
+ raf = requestAnimationFrame(tick);
174
+ }
175
+ function pause() {
176
+ playing = false;
177
+ cancelAnimationFrame(raf);
178
+ if (!destroyed) draw();
179
+ }
180
+ playBtn?.addEventListener("click", () => (playing ? pause() : play()));
181
+ stage.addEventListener("keydown", (e) => {
182
+ const idx = stepIndexAt(scene, t);
183
+ if (e.key === "ArrowRight") selectStep(Math.min(idx + 1, scene.steps.length - 1));
184
+ else if (e.key === "ArrowLeft") selectStep(Math.max(idx - 1, 0));
185
+ else if (e.key === "Home") selectStep(0);
186
+ else if (e.key === "End") selectStep(scene.steps.length - 1);
187
+ else if (e.key === " " && !reduced) playing ? pause() : play();
188
+ else return;
189
+ e.preventDefault();
190
+ });
191
+ function seekStep(i) {
192
+ autoplayPending = false;
193
+ visibilityObserver?.disconnect();
194
+ seek(stepTime(i));
195
+ }
196
+ /** @param {number} i */
197
+ function stepTime(i) {
198
+ if (!Number.isInteger(i) || i < 0 || i >= scene.steps.length) throw new RangeError(`Invalid step index: ${i}`);
199
+ return scene.steps[i].at;
200
+ }
201
+ /** Play forward to an exact settled step; backward/reduced-motion calls jump. @param {number} i */
202
+ function playToStep(i) {
203
+ const target = stepTime(i);
204
+ autoplayPending = false;
205
+ visibilityObserver?.disconnect();
206
+ if (destroyed) return;
207
+ if (reduced || target <= t) seek(target);
208
+ else start(target);
209
+ }
210
+ function selectStep(i) {
211
+ options.animateSteps ? playToStep(i) : seekStep(i);
212
+ }
213
+
214
+ // Initial state: final frame (also what reduced motion and no-autoplay keep).
215
+ seek(scene.duration);
216
+ const autoplay = options.autoplay ?? "visible";
217
+ if (!reduced && autoplay !== "none") {
218
+ if (autoplay === "visible" && typeof IntersectionObserver === "function") {
219
+ autoplayPending = true;
220
+ visibilityObserver = new IntersectionObserver(
221
+ (entries) => {
222
+ if (autoplayPending && entries.some((e) => e.isIntersecting)) {
223
+ autoplayPending = false;
224
+ visibilityObserver?.disconnect();
225
+ if (destroyed) return;
226
+ seek(0);
227
+ play();
228
+ }
229
+ },
230
+ { threshold: 0.4 },
231
+ );
232
+ visibilityObserver.observe(container);
233
+ } else {
234
+ seek(0);
235
+ play();
236
+ }
237
+ }
238
+ const themeQuery = typeof matchMedia === "function" && !options.theme ? matchMedia("(prefers-color-scheme: dark)") : null;
239
+ themeQuery?.addEventListener?.("change", applyTheme);
240
+
241
+ function destroy() {
242
+ if (destroyed) return;
243
+ destroyed = true;
244
+ playing = false;
245
+ cancelAnimationFrame(raf);
246
+ visibilityObserver?.disconnect();
247
+ themeQuery?.removeEventListener?.("change", applyTheme);
248
+ if (g.__motionKit[id] === controller) delete g.__motionKit[id];
249
+ }
250
+ const controller = { seek, play, pause, seekStep, playToStep, destroy, get time() { return t; }, scene };
251
+ const g = globalThis;
252
+ g.__motionKit = g.__motionKit ?? {};
253
+ g.__motionKit[id] = controller;
254
+ return controller;
255
+ }