@liqweed/motion-kit 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +63 -10
  4. package/adapters/astro/AnimatedDiagram.astro +150 -24
  5. package/adapters/element/README.md +6 -1
  6. package/adapters/element/motion-diagram.mjs +4 -3
  7. package/adapters/page/README.md +8 -2
  8. package/adapters/slidev/AnimatedDiagram.vue +24 -0
  9. package/cli/motion-kit.mjs +85 -81
  10. package/docs/spec/technique.md +166 -63
  11. package/examples/custom-pulse.scene.mjs +3 -0
  12. package/examples/incident.json +18 -0
  13. package/examples/web-stack.json +17 -0
  14. package/lib/build.mjs +26 -12
  15. package/lib/bundle.mjs +9 -2
  16. package/lib/check.mjs +219 -15
  17. package/lib/export.mjs +135 -16
  18. package/lib/gate.mjs +90 -0
  19. package/lib/load.mjs +49 -19
  20. package/package.json +6 -3
  21. package/runtime/bake.mjs +18 -4
  22. package/runtime/kit.mjs +59 -0
  23. package/runtime/links.mjs +314 -0
  24. package/runtime/page.mjs +52 -0
  25. package/runtime/parts.mjs +15 -0
  26. package/runtime/patch.mjs +297 -0
  27. package/runtime/player.mjs +334 -130
  28. package/runtime/scene.mjs +82 -5
  29. package/runtime/style.mjs +64 -16
  30. package/runtime/types/hub-spoke.mjs +7 -7
  31. package/runtime/types/index.mjs +4 -0
  32. package/runtime/types/sequence.mjs +5 -5
  33. package/runtime/types/stack.mjs +227 -0
  34. package/runtime/types/timeline.mjs +405 -0
  35. package/skills/animated-diagram/SKILL.md +30 -7
  36. package/skills/animated-diagram/references/custom-scenes.md +64 -9
  37. package/skills/animated-diagram/references/interactivity.md +150 -15
  38. package/skills/animated-diagram/references/qc.md +5 -2
  39. package/skills/animated-diagram/references/scene-types.md +45 -2
  40. package/skills/animated-diagram/references/styles.md +45 -5
  41. package/skills/animated-diagram/references/targets.md +7 -5
  42. package/skills/animated-diagram/references/technique.md +14 -4
  43. package/skills/motion-render/SKILL.md +31 -8
  44. package/skills/motion-render/references/formats.md +8 -8
  45. package/skills/project-logo/SKILL.md +15 -4
  46. package/styles/neutral.json +2 -2
package/lib/load.mjs CHANGED
@@ -1,53 +1,83 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
1
3
  /**
2
4
  * motion-kit · load a scene from a spec (.json) or a custom module (.mjs).
3
5
  *
4
6
  * Custom modules: `export default (opts) => scene` with
5
- * opts = { format, locale, kit }. `kit` is the whole runtime in one flat
6
- * namespace (motion, svg, style, scene, wrap), so a scene that lives in
7
- * another repository (a project logo) needs no imports at all:
7
+ * opts = { ...options, format, locale, kit } (runtime/kit.mjs). `options` are
8
+ * the caller's scene options (`--options`), passed unchanged; `kit` is the
9
+ * whole runtime in one flat namespace, so a scene that lives in another
10
+ * repository (a project logo) needs no imports at all:
8
11
  *
9
- * export default ({ kit }) => { const { tok, el, num } = kit; … }
12
+ * export default ({ kit, labels }) => { const { tok, el, num } = kit; … }
10
13
  *
11
14
  * Scenes inside this repo (or a vendored copy) may import the runtime with
12
- * relative paths instead; `motion-kit build` (browser bundle) requires that.
15
+ * relative paths instead.
13
16
  */
14
17
  import { readFileSync } from "node:fs";
15
18
  import { resolve } from "node:path";
16
19
  import { pathToFileURL } from "node:url";
17
- import { validateScene } from "../runtime/scene.mjs";
20
+ import { KIT, sceneFromModule } from "../runtime/kit.mjs";
18
21
  import { normalizeStyle } from "../runtime/style.mjs";
19
22
  import { createScene } from "../runtime/types/index.mjs";
20
- import * as motion from "../runtime/motion.mjs";
21
- import * as scene from "../runtime/scene.mjs";
22
- import * as style from "../runtime/style.mjs";
23
- import * as svg from "../runtime/svg.mjs";
24
- import * as wrap from "../runtime/wrap.mjs";
25
23
 
26
- /** The runtime, flat, handed to custom scene modules as `opts.kit`. */
27
- export const KIT = Object.freeze({ ...motion, ...svg, ...style, ...scene, ...wrap });
24
+ export { KIT };
28
25
 
29
26
  /**
30
27
  * @typedef {{scene: any, spec?: any, kind: "spec" | "module", file: string}} LoadedScene
31
28
  */
29
+ /**
30
+ * Scene options for one format and locale (see loadOptions).
31
+ * @typedef {(ctx: { format: string, locale: string }) => Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined>} OptionsSource
32
+ */
33
+
34
+ /** True for a file the CLI treats as a custom scene module rather than a spec. */
35
+ export function isModule(file) {
36
+ return !file.endsWith(".json");
37
+ }
32
38
 
33
39
  /**
34
40
  * @param {string} file path to a .json spec or an .mjs module
35
- * @param {{format?: string, locale?: string}} [opts]
41
+ * @param {{format?: string, locale?: string, options?: Record<string, unknown>}} [opts]
42
+ * `options` reach a module's factory unchanged; a spec takes none.
36
43
  * @returns {Promise<LoadedScene>}
37
44
  */
38
45
  export async function loadScene(file, opts = {}) {
39
46
  const abs = resolve(file);
40
- if (abs.endsWith(".json")) {
47
+ const { options, ...where } = opts;
48
+ if (!isModule(abs)) {
49
+ if (options != null) throw new Error(`${file}: scene options apply to custom scene modules, not to specs`);
41
50
  const spec = JSON.parse(readFileSync(abs, "utf8"));
42
- return { scene: createScene(spec, opts), spec, kind: "spec", file: abs };
51
+ return { scene: createScene(spec, where), spec, kind: "spec", file: abs };
43
52
  }
44
53
  const mod = await import(pathToFileURL(abs).href);
45
- const make = mod.default;
46
- if (typeof make !== "function") throw new Error(`${file}: default export must be (opts) => scene`);
47
- return { scene: validateScene(make({ ...opts, kit: KIT })), kind: "module", file: abs };
54
+ if (typeof mod.default !== "function") throw new Error(`${file}: default export must be (opts) => scene`);
55
+ return { scene: sceneFromModule(mod.default, { ...where, options }), kind: "module", file: abs };
48
56
  }
49
57
 
50
58
  export function loadStyle(arg) {
51
59
  if (!arg || arg === "neutral") return normalizeStyle("neutral");
52
60
  return normalizeStyle(JSON.parse(readFileSync(resolve(arg), "utf8")));
53
61
  }
62
+
63
+ /**
64
+ * Scene options from `--options`: inline JSON (`{"view":"short"}`), a .json
65
+ * file, or a module whose default export is the options or
66
+ * `({ format, locale }) => options` (to pick a locale's dictionary).
67
+ * @param {string | undefined} arg
68
+ * @returns {Promise<OptionsSource | undefined>}
69
+ */
70
+ export async function loadOptions(arg) {
71
+ if (arg == null) return undefined;
72
+ /** @param {unknown} v */
73
+ const fixed = (v) => {
74
+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error(`--options ${arg}: scene options must be a JSON object`);
75
+ return () => /** @type {Record<string, unknown>} */ (v);
76
+ };
77
+ if (arg.trim().startsWith("{")) return fixed(JSON.parse(arg));
78
+ const abs = resolve(arg);
79
+ if (abs.endsWith(".json")) return fixed(JSON.parse(readFileSync(abs, "utf8")));
80
+ const mod = await import(pathToFileURL(abs).href);
81
+ if (typeof mod.default === "function") return (ctx) => mod.default(ctx);
82
+ return fixed(mod.default);
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqweed/motion-kit",
3
- "version": "0.3.0",
3
+ "version": "0.5.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,14 +47,17 @@
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/custom-pulse.scene.mjs brand/logo.scene.mjs",
50
+ "check": "node cli/motion-kit.mjs check examples/order-flow.json examples/smart-home.json examples/release-pipeline.json examples/agent-loop.json examples/integrations.json examples/incident.json examples/web-stack.json examples/custom-pulse.scene.mjs brand/logo.scene.mjs",
51
51
  "media": "scripts/render-media.sh",
52
52
  "media:check": "scripts/render-media.sh --check",
53
53
  "site": "npm run -w website build",
54
54
  "site:dev": "npm run -w website dev",
55
55
  "site:deploy": "npm run -w website deploy",
56
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"
57
+ "bench:player": "node scripts/bench-player.mjs",
58
+ "snapshots:update": "node scripts/update-snapshots.mjs",
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"
58
61
  },
59
62
  "optionalDependencies": {
60
63
  "@resvg/resvg-js": "^2.6.2"
package/runtime/bake.mjs CHANGED
@@ -16,22 +16,36 @@
16
16
  import { renderSvg } from "./scene.mjs";
17
17
  import { num } from "./svg.mjs";
18
18
 
19
+ /**
20
+ * @param {import("./scene.mjs").Scene} scene
21
+ * @param {{ fps?: number, delay?: number, idPrefix?: string, style?: any, theme?: string, background?: boolean }} [options]
22
+ * idPrefix: prefix for the file's ids (default "mk-bake"); give each baked
23
+ * SVG inlined into one page its own.
24
+ * @returns {string}
25
+ */
19
26
  export function bake(scene, options = {}) {
20
27
  const fps = options.fps ?? 15;
21
28
  const delay = options.delay ?? 0.3;
29
+ const base = options.idPrefix ?? "mk-bake";
22
30
  const total = Math.ceil(scene.duration * fps);
31
+ /** @param {number} t @param {string} idPrefix */
32
+ const render = (t, idPrefix) => renderSvg(scene, t, { ...options, standalone: true, idPrefix });
23
33
  const frames = [];
24
34
  for (let f = 0; f <= total; f++) {
25
35
  const t = Math.min(f / fps, scene.duration);
26
- const inner = innerOf(renderSvg(scene, t, { ...options, standalone: true, idPrefix: "mk-bake" }));
36
+ const inner = innerOf(render(t, base));
27
37
  const last = frames[frames.length - 1];
28
38
  if (last && last.body === inner) last.end = t;
29
39
  else frames.push({ start: t, end: t, body: inner });
30
40
  }
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;
41
+ // Each slice lasts until the next one starts. Slices sit in one document,
42
+ // so a scene that defines ids gets a prefix per slice.
43
+ for (let i = 0; i < frames.length; i++) {
44
+ if (i < frames.length - 1) frames[i].end = frames[i + 1].start;
45
+ if (/\sid="/.test(frames[i].body)) frames[i].body = innerOf(render(frames[i].start, `${base}-${i + 1}`));
46
+ }
33
47
 
34
- const full = renderSvg(scene, scene.duration, { ...options, standalone: true, idPrefix: "mk-bake" });
48
+ const full = render(scene.duration, base);
35
49
  const open = full.slice(0, full.indexOf(">") + 1);
36
50
  const head = full.slice(open.length, full.indexOf("</desc>") + "</desc>".length);
37
51
  const css = [
@@ -0,0 +1,59 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · custom scene modules.
5
+ *
6
+ * A custom scene module's default export is a factory, `(opts) => scene`, for
7
+ * diagrams no scene type draws. It is called with
8
+ *
9
+ * opts = { ...options, format, locale, kit }
10
+ *
11
+ * - `options`: the caller's serializable scene options, unchanged (text from a
12
+ * site's dictionary, a view to draw). Keys `format`, `locale` and `kit` are
13
+ * reserved.
14
+ * - `format`, `locale`: what to build (see FORMATS).
15
+ * - `kit`: the whole runtime in one flat namespace, so a scene kept in another
16
+ * repository needs no imports: `const { tok, el, num } = kit`.
17
+ *
18
+ * The CLI and the vendored gate (lib/load.mjs) and the Astro adapter, on the
19
+ * server and in the browser, go through sceneFromModule, so one module, given
20
+ * the same options, format and locale, draws the same scene everywhere. A page
21
+ * from `motion-kit build` calls the factory the same way, with the bundled
22
+ * runtime as `kit`, after the CLI built it here once.
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";
25
+ import { FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId } from "./scene.mjs";
26
+ import { CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok } from "./style.mjs";
27
+ import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment } from "./svg.mjs";
28
+ import { estimateWidth, wrapLabel } from "./wrap.mjs";
29
+
30
+ /**
31
+ * The runtime, flat, handed to custom scene modules as `opts.kit`: the exports
32
+ * of motion, scene, style, svg and wrap (not the scene types or the player).
33
+ * Named imports, because lib/bundle.mjs inlines only that form; a new export
34
+ * in one of those modules is added here (test/runtime.test.mjs checks).
35
+ */
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 },
38
+ ...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
39
+ ...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
40
+ ...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment },
41
+ ...{ estimateWidth, wrapLabel },
42
+ });
43
+
44
+ const RESERVED = ["format", "locale", "kit"];
45
+
46
+ /**
47
+ * Build and validate a scene from a module's default export.
48
+ * @param {unknown} make the module's default export
49
+ * @param {{ format?: string, locale?: string, options?: Record<string, unknown> | null }} [opts]
50
+ * @returns {import("./scene.mjs").Scene}
51
+ */
52
+ export function sceneFromModule(make, { format = "16:9", locale = "en", options } = {}) {
53
+ if (typeof make !== "function") throw new TypeError("a scene module's default export must be (opts) => scene");
54
+ if (options != null && (typeof options !== "object" || Array.isArray(options))) throw new TypeError("scene options must be a plain object");
55
+ for (const key of RESERVED) {
56
+ if (options && Object.hasOwn(options, key)) throw new Error(`scene options must not set "${key}": it is passed separately`);
57
+ }
58
+ return validateScene(make({ ...options, format, locale, kit: KIT }));
59
+ }
@@ -0,0 +1,314 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · page links: drive a player from the page around it (browser;
5
+ * the step mapping is pure and also runs in Node).
6
+ *
7
+ * scrollSteps(controller, sections, options) → dispose
8
+ * Each text section names a step; as the reader scrolls, the section
9
+ * crossing a line across the viewport selects its step. One settled step
10
+ * per section, down and up; never scrubs continuously.
11
+ * linkSteps(controller, rootOrElements, options) → dispose
12
+ * Elements with `data-mk-step` select their step on hover (mouse, pen),
13
+ * keyboard focus and click.
14
+ *
15
+ * `controller` is what mountPlayer returns (or `.controller` of
16
+ * `<motion-diagram>` / the Astro adapter's root element). A step is named by
17
+ * its id or its zero-based index; an unknown id throws RangeError when the
18
+ * helper binds, not when the reader gets there.
19
+ *
20
+ * Nothing touches the DOM at import time, and neither helper moves focus or
21
+ * layout: the active section or term gets `aria-current="step"`, which the
22
+ * page styles without changing sizes.
23
+ */
24
+ import { stepIndex } from "./scene.mjs";
25
+
26
+ /** The attribute that names an element's step. */
27
+ const STEP_ATTR = "data-mk-step";
28
+
29
+ /** @import { Scene } from "./scene.mjs" */
30
+ /**
31
+ * The part of the player controller the helpers use.
32
+ * @typedef {{ scene: Scene, time: number, seek: (t: number) => void, seekStep: (ref: number | string) => void, playToStep: (ref: number | string) => void }} StepController
33
+ */
34
+ /**
35
+ * @typedef {object} ScrollStepsOptions
36
+ * @property {number} [line] where the line sits, as a share of the root's height from its top (0–1, default 0.5)
37
+ * @property {Element | Document | null} [root] the scroll container; default the viewport
38
+ * @property {boolean} [animate] play forward to the next section's step (default true); other moves jump
39
+ * @property {boolean} [mark] set `aria-current="step"` on the active section (default true)
40
+ * @property {(index: number, section: Element | null) => void} [onChange] called when the active section changes; -1 and null before the first
41
+ */
42
+ /**
43
+ * @typedef {object} LinkStepsOptions
44
+ * @property {boolean} [animate] play forward to a later step instead of jumping (default false)
45
+ * @property {boolean} [restore] when hover and focus leave every term, return to the frame shown before (default false: the step stays); a click keeps its step
46
+ * @property {boolean} [mark] set `aria-current="step"` on the terms of the selected step (default true)
47
+ * @property {(step: number, element: Element | null) => void} [onChange] called when a term selects a step, and with -1 and null on restore
48
+ */
49
+
50
+ /* ------------------------------------------------------- pure step mapping */
51
+
52
+ /**
53
+ * The step index a reference names: a step id, else a whole-number index
54
+ * (a number, or digits as `data-mk-step` gives them). An id wins over an index
55
+ * when a step's id is digits. Throws RangeError for an unknown id or an index
56
+ * out of range.
57
+ * @param {Scene} scene
58
+ * @param {number | string} ref
59
+ * @returns {number}
60
+ */
61
+ export function stepRef(scene, ref) {
62
+ if (typeof ref === "string") {
63
+ const trimmed = ref.trim();
64
+ if (scene.steps.some((s) => s.id === trimmed)) return stepIndex(scene, trimmed);
65
+ if (/^\d+$/.test(trimmed)) return stepIndex(scene, Number(trimmed));
66
+ return stepIndex(scene, trimmed);
67
+ }
68
+ return stepIndex(scene, ref);
69
+ }
70
+
71
+ /**
72
+ * The step of each section, in order: its own reference (`data-mk-step`) when
73
+ * it has one, else its position (the third section shows step 2). Throws
74
+ * RangeError when a reference is unknown or a section has no step to take.
75
+ * @param {Scene} scene
76
+ * @param {(number | string | null | undefined)[]} refs one per section; null or undefined to go by order
77
+ * @returns {number[]}
78
+ */
79
+ export function sectionSteps(scene, refs) {
80
+ return refs.map((ref, i) => {
81
+ if (ref != null && ref !== "") return stepRef(scene, ref);
82
+ if (i >= scene.steps.length) throw new RangeError(`Section ${i + 1} has no ${STEP_ATTR} and the scene has only ${scene.steps.length} steps`);
83
+ return i;
84
+ });
85
+ }
86
+
87
+ /**
88
+ * The active section: the last one, in order, whose top has reached the line
89
+ * (top ≤ line). A section stays active through the gap after it until the next
90
+ * one reaches the line, and the last one stays active below it. -1 while no
91
+ * section has reached the line.
92
+ * @param {number[]} tops each section's top, in the same coordinates as `line`
93
+ * @param {number} line
94
+ * @returns {number}
95
+ */
96
+ export function activeSection(tops, line) {
97
+ let active = -1;
98
+ tops.forEach((top, i) => {
99
+ if (top <= line) active = i;
100
+ });
101
+ return active;
102
+ }
103
+
104
+ /**
105
+ * How to move between sections: "play" to the next section's step when it is
106
+ * one section further and a later step (animation allowed, no reduced motion),
107
+ * "seek" for every other change (back, skipping, the first section), and null
108
+ * when there is nothing to do (no section, or the same step).
109
+ * @param {{ from: number, to: number, fromStep: number, toStep: number, animate?: boolean, reduced?: boolean }} move
110
+ * @returns {"play" | "seek" | null}
111
+ */
112
+ export function scrollMove({ from, to, fromStep, toStep, animate = true, reduced = false }) {
113
+ if (to < 0 || (from >= 0 && toStep === fromStep)) return null;
114
+ return animate && !reduced && from >= 0 && to === from + 1 && toStep > fromStep ? "play" : "seek";
115
+ }
116
+
117
+ /* ---------------------------------------------------------------- the DOM */
118
+
119
+ const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
120
+
121
+ /** @param {Element} el @param {boolean} on */
122
+ function markCurrent(el, on) {
123
+ if (on) el.setAttribute("aria-current", "step");
124
+ else if (el.getAttribute("aria-current") === "step") el.removeAttribute("aria-current");
125
+ }
126
+
127
+ /** @param {unknown} controller @returns {StepController} */
128
+ function needController(controller) {
129
+ const c = /** @type {any} */ (controller);
130
+ if (!c || typeof c.seekStep !== "function" || !c.scene) throw new TypeError("expected a player controller (mountPlayer, or .controller of <motion-diagram> / the Astro adapter)");
131
+ return c;
132
+ }
133
+
134
+ /**
135
+ * Bind a player to a list of text sections: as each section's top crosses a
136
+ * line across the viewport (or `root`), the diagram goes to that section's
137
+ * settled step. A section names its step with `data-mk-step` (step id or
138
+ * index), else by order. Moving one section forward plays to the next step;
139
+ * moving back, skipping sections and reduced motion jump. Without
140
+ * IntersectionObserver it does nothing.
141
+ *
142
+ * Give the page room below the last section (e.g. `padding-bottom: 50vh`), so
143
+ * the last section's top can reach the line. Mount the player with
144
+ * `autoplay: "none"`; the first section's step replaces any pending autoplay.
145
+ * @param {StepController} controller
146
+ * @param {Iterable<Element> | ArrayLike<Element>} sections in reading order
147
+ * @param {ScrollStepsOptions} [options]
148
+ * @returns {() => void} dispose: stops observing and clears the marks
149
+ */
150
+ export function scrollSteps(controller, sections, options = {}) {
151
+ const c = needController(controller);
152
+ const els = Array.from(sections);
153
+ const steps = sectionSteps(c.scene, els.map((el) => el.getAttribute(STEP_ATTR)));
154
+ const line = Math.min(Math.max(options.line ?? 0.5, 0), 1);
155
+ const { root = null, animate = true, mark = true, onChange } = options;
156
+ let current = -1;
157
+ let disposed = false;
158
+
159
+ /** The line's position in viewport coordinates. */
160
+ const lineY = () => {
161
+ if (root && "getBoundingClientRect" in root) {
162
+ const r = root.getBoundingClientRect();
163
+ return r.top + line * r.height;
164
+ }
165
+ return line * (globalThis.innerHeight ?? 0);
166
+ };
167
+ const update = () => {
168
+ if (disposed) return;
169
+ const next = activeSection(els.map((el) => el.getBoundingClientRect().top), lineY());
170
+ if (next === current) return;
171
+ const move = scrollMove({ from: current, to: next, fromStep: steps[current] ?? -1, toStep: steps[next] ?? -1, animate, reduced: reducedMotion() });
172
+ if (move === "play") c.playToStep(steps[next]);
173
+ else if (move === "seek") c.seekStep(steps[next]);
174
+ if (mark) els.forEach((el, i) => markCurrent(el, i === next));
175
+ current = next;
176
+ onChange?.(next, els[next] ?? null);
177
+ };
178
+
179
+ if (typeof IntersectionObserver !== "function") return () => {};
180
+ // The root, cut off at the line: a section enters or leaves it exactly
181
+ // when its top crosses the line, which is when the active one can change.
182
+ const below = `${(1 - line) * 100}%`;
183
+ const observer = new IntersectionObserver(update, { root, rootMargin: `0px 0px -${below} 0px`, threshold: 0 });
184
+ for (const el of els) observer.observe(el);
185
+ // A jump that moves every section across the line without changing which
186
+ // are inside the observed area sends no notification, so scrolling asks
187
+ // again, at most once per frame.
188
+ const scroller = root && "addEventListener" in root ? root : globalThis;
189
+ const raf = globalThis.requestAnimationFrame?.bind(globalThis);
190
+ let queued = false;
191
+ const onScroll = () => {
192
+ if (queued || disposed) return;
193
+ if (!raf) return update();
194
+ queued = true;
195
+ raf(() => {
196
+ queued = false;
197
+ update();
198
+ });
199
+ };
200
+ scroller.addEventListener?.("scroll", onScroll, { passive: true });
201
+ return () => {
202
+ if (disposed) return;
203
+ disposed = true;
204
+ observer.disconnect();
205
+ scroller.removeEventListener?.("scroll", onScroll);
206
+ if (mark) for (const el of els) markCurrent(el, false);
207
+ };
208
+ }
209
+
210
+ /**
211
+ * Bind a player to terms in the page: every element with `data-mk-step` (step
212
+ * id or index) under `root`, or the elements given, selects its step on
213
+ * pointer hover (mouse and pen; touch selects on click instead), on keyboard
214
+ * focus (also focus inside it) and on click. Make terms focusable, e.g.
215
+ * `<button type="button" data-mk-step="payment">`, so keyboard users get the
216
+ * same step as pointer users. A selection jumps; `animate: true` plays forward
217
+ * to a later step unless the reader prefers reduced motion.
218
+ *
219
+ * By default the selected step stays when the pointer or focus leaves.
220
+ * `restore: true` makes hover and focus a preview: once neither is on a term,
221
+ * the diagram returns to the frame it showed before; a click keeps its step.
222
+ * Terms are collected when binding; bind again for terms added later.
223
+ * @param {StepController} controller
224
+ * @param {ParentNode | Iterable<Element> | ArrayLike<Element>} target a root to search, or the terms
225
+ * @param {LinkStepsOptions} [options]
226
+ * @returns {() => void} dispose: removes the listeners and clears the marks
227
+ */
228
+ export function linkSteps(controller, target, options = {}) {
229
+ const c = needController(controller);
230
+ const { animate = false, restore = false, mark = true, onChange } = options;
231
+ const t = /** @type {any} */ (target);
232
+ /** @type {Element[]} */
233
+ const els = typeof t?.querySelectorAll === "function" ? Array.from(t.querySelectorAll(`[${STEP_ATTR}]`)) : Array.from(t);
234
+ const steps = els.map((el) => {
235
+ const ref = el.getAttribute(STEP_ATTR);
236
+ if (ref == null || ref === "") throw new RangeError(`linkSteps: an element has no ${STEP_ATTR}`);
237
+ return stepRef(c.scene, ref);
238
+ });
239
+ /** @type {Element | null} */
240
+ let hovered = null;
241
+ /** @type {Element | null} */
242
+ let focused = null;
243
+ /** The time before a preview began, to restore; null when nothing is previewed. @type {number | null} */
244
+ let before = null;
245
+ let selected = -1;
246
+
247
+ /** @param {number} step @param {Element | null} el */
248
+ const show = (step, el) => {
249
+ selected = step;
250
+ if (mark) els.forEach((e, i) => markCurrent(e, steps[i] === step));
251
+ onChange?.(step, el);
252
+ };
253
+ /** @param {number} i */
254
+ const select = (i) => {
255
+ const step = steps[i];
256
+ if (animate && !reducedMotion()) c.playToStep(step);
257
+ else c.seekStep(step);
258
+ show(step, els[i]);
259
+ };
260
+ /** @param {number} i */
261
+ const preview = (i) => {
262
+ if (restore && before === null) before = c.time;
263
+ select(i);
264
+ };
265
+ const leave = () => {
266
+ if (!restore || hovered || focused || before === null) return;
267
+ c.seek(before);
268
+ before = null;
269
+ if (selected !== -1) show(-1, null);
270
+ };
271
+
272
+ /** @type {[Element, string, (e: any) => void][]} */
273
+ const bound = [];
274
+ els.forEach((el, i) => {
275
+ /** @type {Record<string, (e: any) => void>} */
276
+ const on = {
277
+ pointerenter: (e) => {
278
+ if (e?.pointerType === "touch") return;
279
+ hovered = el;
280
+ preview(i);
281
+ },
282
+ pointerleave: (e) => {
283
+ if (e?.pointerType === "touch" || hovered !== el) return;
284
+ hovered = null;
285
+ leave();
286
+ },
287
+ focusin: () => {
288
+ focused = el;
289
+ preview(i);
290
+ },
291
+ focusout: () => {
292
+ if (focused !== el) return;
293
+ focused = null;
294
+ leave();
295
+ },
296
+ click: () => {
297
+ // A click commits: nothing to restore afterwards.
298
+ before = null;
299
+ select(i);
300
+ },
301
+ };
302
+ for (const [name, fn] of Object.entries(on)) {
303
+ el.addEventListener(name, fn);
304
+ bound.push([el, name, fn]);
305
+ }
306
+ });
307
+ let disposed = false;
308
+ return () => {
309
+ if (disposed) return;
310
+ disposed = true;
311
+ for (const [el, name, fn] of bound) el.removeEventListener(name, fn);
312
+ if (mark) for (const el of els) markCurrent(el, false);
313
+ };
314
+ }
@@ -0,0 +1,52 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · per-page bookkeeping for server-rendering adapters.
5
+ *
6
+ * DOM-free decisions an adapter shares: which id an instance gets, and whether
7
+ * the player stylesheet is out yet. The adapter owns where the page state lives
8
+ * (Astro: `Astro.locals`) and what it does with the answer.
9
+ */
10
+ import { safeId } from "./scene.mjs";
11
+
12
+ /**
13
+ * @typedef {{ count: number, ids: Set<string>, css: boolean }} PageState
14
+ */
15
+
16
+ /** @returns {PageState} */
17
+ export function newPageState() {
18
+ return { count: 0, ids: new Set(), css: false };
19
+ }
20
+
21
+ /**
22
+ * Take an id for one instance on the page: the requested one, validated, or a
23
+ * generated one from the scene id and the page's counter. Throws on a malformed
24
+ * or already used id.
25
+ * @param {PageState} page
26
+ * @param {string | undefined | null} requested
27
+ * @param {string} sceneId
28
+ * @returns {string}
29
+ */
30
+ export function claimId(page, requested, sceneId) {
31
+ if (requested != null && safeId(requested) !== requested) throw new Error(`id "${requested}" must be letters, digits, "_" and "-", starting with a letter`);
32
+ let id = requested;
33
+ if (id == null) {
34
+ // Skip ids an explicit request already took.
35
+ do id = safeId(`mk-${sceneId}-${++page.count}`);
36
+ while (page.ids.has(id));
37
+ }
38
+ if (page.ids.has(id)) throw new Error(`id "${id}" is already used on this page; give each instance (the wide and the tall one too) its own`);
39
+ page.ids.add(id);
40
+ return id;
41
+ }
42
+
43
+ /**
44
+ * True once per page: the first caller emits the player stylesheet.
45
+ * @param {PageState} page
46
+ * @returns {boolean}
47
+ */
48
+ export function claimStylesheet(page) {
49
+ if (page.css) return false;
50
+ page.css = true;
51
+ return true;
52
+ }
package/runtime/parts.mjs CHANGED
@@ -12,6 +12,21 @@ import { attrString, el, esc, fade, num, text, translate } from "./svg.mjs";
12
12
  import { tok } from "./style.mjs";
13
13
 
14
14
  export const FONT_MIN = 14; // smallest label size at 1× (viewBox units)
15
+ export const FONT_MAX = 200; // largest `fontSize` a scene may ask for
16
+
17
+ /**
18
+ * The largest label size a scene type tries: its `fontSize`, else `dflt`. The
19
+ * fit searches count down from it, so it must be a finite number in range.
20
+ * @param {{ fontSize?: number }} spec
21
+ * @param {number} dflt
22
+ * @param {string} name for the error
23
+ * @returns {number}
24
+ */
25
+ export function maxFontSize(spec, dflt, name) {
26
+ const fs = spec.fontSize ?? dflt;
27
+ if (!Number.isFinite(fs) || fs < FONT_MIN || fs > FONT_MAX) throw new Error(`${name}: fontSize must be a number from ${FONT_MIN} to ${FONT_MAX}, got ${fs}`);
28
+ return fs;
29
+ }
15
30
 
16
31
  /**
17
32
  * Optional icon: SVG path data drawn on a 24×24 grid with round strokes