@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
@@ -1,128 +1,274 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Copyright (c) 2026 Ophir Radnitz
3
3
  /**
4
- * motion-kit · live player (browser only).
4
+ * motion-kit · live player (browser; the markup helpers also run on servers).
5
5
  *
6
6
  * mountPlayer(container, scene, options) → controller
7
+ * playerMarkup(scene, options) → the player's first state as HTML, for a server render
8
+ * themeCss(selector, style, theme?) → the style's tokens as CSS for a server render
9
+ * PLAYER_CSS → the player's stylesheet
7
10
  *
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
+ * - Server/no-JS fallback: render playerMarkup into the container, with
12
+ * PLAYER_CSS (in a `<style data-mk-player-css>`) and themeCss. It is the
13
+ * same markup the player builds, with the controls inert, so the final frame,
14
+ * the step list and the colours are there without JavaScript, and mounting
15
+ * moves nothing. A plain final-frame SVG also works as a fallback.
16
+ * - Plays once when ~40 % of the diagram, or of the viewport, shows, then
17
+ * holds the final frame. While the diagram is out of view or not rendered
18
+ * (display: none), the clock waits; it resumes where it stopped.
11
19
  * - Always shows pause/play (WCAG 2.2.2), one button per step (jumps, no
12
20
  * animation unless animateSteps is enabled), an optional scrubber, and captions.
21
+ * Every control is at least 44 × 44 px; captions and the play button reserve
22
+ * their largest size, so playback does not move the page either.
13
23
  * - prefers-reduced-motion: final frame immediately, no autoplay, no play button.
14
- * - Keyboard: ←/→ previous/next step, Space play/pause, Home/End.
24
+ * - Keyboard on the stage (a named group, described by a hint): ←/→ previous/next
25
+ * step, Space play/pause, Home/End.
15
26
  * - Capture hook: controller.seek(t), and window.__motionKit[id] for renderers.
27
+ * - Each frame updates the stage's SVG in place (runtime/patch.mjs): nodes that
28
+ * persist between frames are kept, only changed attributes and text are written.
16
29
  *
17
30
  * The player owns the clock (requestAnimationFrame); scenes stay pure.
18
31
  */
19
- import { cssVars, normalizeStyle } from "./style.mjs";
20
- import { renderSvg, stepIndexAt } from "./scene.mjs";
32
+ import { patchMarkup } from "./patch.mjs";
33
+ import { renderSvg, safeId, stepIndex, stepIndexAt } from "./scene.mjs";
34
+ import { cssVars, normalizeStyle, TOKENS } from "./style.mjs";
35
+ import { esc } from "./svg.mjs";
21
36
 
22
- const CSS = `
37
+ /** The player's stylesheet. Inject it yourself and pass `injectCss: false` to own it. */
38
+ export const PLAYER_CSS = `
23
39
  .mk-player{font-family:var(--mk-font);color:var(--mk-ink);background:transparent}
24
40
  .mk-stage svg{display:block;width:100%;height:auto}
41
+ .mk-stage:focus-visible,.mk-btn:focus-visible,.mk-scrub:focus-visible{outline:2px solid var(--mk-emphasis);outline-offset:2px}
25
42
  .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}
43
+ .mk-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;min-width:44px;min-height:44px;margin:0;font:inherit;font-size:13px;line-height:1.2;padding:6px 12px;border-radius:8px;border:1px solid var(--mk-line);background:var(--mk-surface);color:var(--mk-ink);cursor:pointer}
27
44
  .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}
45
+ .mk-controls[inert] .mk-btn{cursor:default}
46
+ .mk-play{flex-direction:column;min-width:72px}
47
+ .mk-play>[aria-hidden]{display:block;height:0;overflow:hidden;visibility:hidden}
48
+ .mk-scrub{flex:1 1 160px;box-sizing:border-box;min-height:44px;margin:0;accent-color:var(--mk-accent)}
49
+ .mk-caption{display:grid;margin:8px 0 0;font-size:15px;line-height:1.45;color:var(--mk-muted);min-height:1.45em}
50
+ .mk-caption>span{grid-area:1/1;visibility:hidden}
51
+ .mk-caption>.mk-on{visibility:visible}
32
52
  .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}
53
+ @media (prefers-reduced-motion:reduce){.mk-play{display:none}}
54
+ @media (scripting:none){.mk-play,.mk-scrub{display:none}}
33
55
  `;
34
56
 
35
- const styledDocuments = new WeakSet();
57
+ const CSS_MARK = "data-mk-player-css";
58
+ const DEFAULT_LABELS = Object.freeze({ play: "Play", pause: "Pause", replay: "Replay", steps: "Steps", scrubber: "Timeline", keys: "Use the arrow keys to move between steps." });
59
+ /** Autoplay starts once this share of the diagram, or of the viewport, shows. */
60
+ const SHOWN = 0.4;
61
+ // Consecutive thresholds differ by at most 2.5×, so a diagram of any height
62
+ // reports a ratio between "fills 40 % of the viewport" and "fills all of it".
63
+ const THRESHOLDS = [0, 0.01, 0.02, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8, 1];
64
+
65
+ let instances = 0;
66
+
67
+ /** @type {WeakMap<HTMLElement, { destroy: () => void }>} */
68
+ const mounted = new WeakMap();
69
+
70
+ /** @import { Scene } from "./scene.mjs" */
71
+ /**
72
+ * @typedef {Record<string, string | Record<string, string>>} Labels
73
+ * @typedef {{ style?: any, labels?: Labels, locale?: string, theme?: string, id?: string, injectCss?: boolean, scrubber?: boolean, captions?: boolean, autoplay?: string, animateSteps?: boolean }} PlayerOptions
74
+ */
75
+
76
+ /**
77
+ * UI strings from `labels`: either a flat `{ play, pause, … }` object or a
78
+ * dictionary keyed by locale (`{ en: {…}, nl: {…} }`). A dictionary resolves
79
+ * `locale`, then its language subtag (`nl-BE` → `nl`), then `en`, then its
80
+ * first entry; keys it lacks keep the English defaults.
81
+ * @param {Labels | undefined} labels
82
+ * @param {string} [locale]
83
+ * @returns {Record<string, string>}
84
+ */
85
+ export function resolveLabels(labels, locale = "en") {
86
+ if (!labels) return {};
87
+ const entries = Object.entries(labels);
88
+ if (!entries.some(([, v]) => typeof v === "object" && v !== null)) return /** @type {Record<string, string>} */ (labels);
89
+ const dict = /** @type {Record<string, Record<string, string>>} */ (labels);
90
+ return dict[locale] ?? dict[locale.split("-")[0]] ?? dict.en ?? /** @type {Record<string, string>} */ (entries.find(([, v]) => typeof v === "object")?.[1]) ?? {};
91
+ }
92
+
93
+ /**
94
+ * The style's token values as CSS custom properties on `selector`: one theme
95
+ * when `theme` is "light" or "dark", else light with a dark override under
96
+ * `prefers-color-scheme: dark`. For server renders, so colours show before
97
+ * (and without) JavaScript; the mounted player sets the same values inline.
98
+ * @param {string} selector
99
+ * @param {any} style
100
+ * @param {string} [theme]
101
+ * @returns {string}
102
+ */
103
+ export function themeCss(selector, style, theme) {
104
+ const s = normalizeStyle(style);
105
+ /** @param {string} t */
106
+ const rule = (t) => `${selector}{${cssVars(s, t)};--mk-font:${s.font}}`;
107
+ return theme === "light" || theme === "dark" ? rule(theme) : `${rule("light")}@media (prefers-color-scheme:dark){${rule("dark")}}`;
108
+ }
109
+
110
+ /* ------------------------------------------------------------- the markup */
111
+
112
+ /**
113
+ * One element of the player's markup. `content` is text, trusted markup
114
+ * (`{ html }`) or child elements; `ref` names it for the live player.
115
+ * @typedef {{ tag: string, attrs: Record<string, string | undefined>, content?: string | { html: string } | (ViewNode | false | undefined)[], ref?: string }} ViewNode
116
+ */
117
+
118
+ /**
119
+ * @param {string} tag
120
+ * @param {Record<string, string | undefined>} attrs
121
+ * @param {ViewNode["content"]} [content]
122
+ * @param {string} [ref]
123
+ * @returns {ViewNode}
124
+ */
125
+ const h = (tag, attrs, content, ref) => ({ tag, attrs, content, ref });
126
+
127
+ /**
128
+ * The player's elements in their first state: the final frame, the last step
129
+ * current, the play button offering a replay.
130
+ * @param {Scene} scene
131
+ * @param {{ labels: Record<string, string>, prefix: string, svg: string, scrubber?: boolean, captions?: boolean, playButton: boolean, inert: boolean }} o
132
+ * @returns {(ViewNode | false | undefined)[]}
133
+ */
134
+ function view(scene, o) {
135
+ const { labels, prefix } = o;
136
+ const last = scene.steps.length - 1;
137
+ // Before mount (inert) the stage takes no focus and promises no keys.
138
+ const keys = o.inert ? undefined : `${prefix}-keys`;
139
+ return [
140
+ h("div", { class: "mk-stage", tabindex: o.inert ? undefined : "0", role: "group", "aria-label": scene.title, "aria-describedby": keys }, { html: o.svg }, "stage"),
141
+ h("div", { class: "mk-controls", role: "group", "aria-label": labels.steps, inert: o.inert ? "" : undefined }, [
142
+ o.playButton &&
143
+ h("button", { type: "button", class: "mk-btn mk-play" }, [
144
+ h("span", {}, labels.replay, "playLabel"),
145
+ // Hidden copies of every label reserve the widest one.
146
+ ...[labels.play, labels.pause, labels.replay].map((l) => h("span", { "aria-hidden": "true" }, l)),
147
+ ], "play"),
148
+ ...scene.steps.map((s, i) => h("button", { type: "button", class: "mk-btn", "aria-current": i === last ? "step" : undefined }, `${i + 1}. ${s.label}`, "steps[]")),
149
+ o.scrubber && h("input", { type: "range", class: "mk-scrub", min: "0", max: String(scene.duration), step: "0.01", value: String(scene.duration), "aria-label": labels.scrubber }, undefined, "scrub"),
150
+ ]),
151
+ // Every detail is laid out in one grid cell, so the caption keeps the height of the longest.
152
+ o.captions !== false && h("p", { class: "mk-caption", "aria-hidden": "true" }, scene.steps.map((s, i) => h("span", { class: i === last ? "mk-on" : undefined }, s.detail ?? "", "captions[]"))),
153
+ h("ol", { class: "mk-sr" }, scene.steps.map((s) => h("li", {}, s.detail ? `${s.label}: ${s.detail}` : s.label))),
154
+ !o.inert && h("p", { id: keys, class: "mk-sr" }, labels.keys),
155
+ // Keyboard step changes are announced; autoplay and pointer use stay silent.
156
+ h("div", { class: "mk-sr mk-live", role: "status", "aria-live": "polite", "aria-atomic": "true" }, "", "live"),
157
+ ];
158
+ }
159
+
160
+ /** @param {ViewNode | false | undefined} node @returns {string} */
161
+ function toHtml(node) {
162
+ if (!node) return "";
163
+ const attrs = Object.entries(node.attrs)
164
+ .filter(([, v]) => v !== undefined)
165
+ .map(([k, v]) => (v === "" ? ` ${k}` : ` ${k}="${esc(v)}"`))
166
+ .join("");
167
+ if (node.tag === "input") return `<input${attrs}>`;
168
+ const c = node.content;
169
+ const inner = typeof c === "string" ? esc(c) : Array.isArray(c) ? c.map(toHtml).join("") : (c?.html ?? "");
170
+ return `<${node.tag}${attrs}>${inner}</${node.tag}>`;
171
+ }
172
+
173
+ /**
174
+ * @param {Document} doc
175
+ * @param {ViewNode} node
176
+ * @param {Record<string, any>} refs
177
+ * @returns {HTMLElement}
178
+ */
179
+ function toDom(doc, node, refs) {
180
+ const el = doc.createElement(node.tag);
181
+ for (const [k, v] of Object.entries(node.attrs)) if (v !== undefined) el.setAttribute(k, v);
182
+ const c = node.content;
183
+ if (typeof c === "string") el.textContent = c;
184
+ else if (Array.isArray(c)) {
185
+ for (const child of c) if (child) el.appendChild(toDom(doc, child, refs));
186
+ } else if (c) el.innerHTML = c.html;
187
+ if (node.ref?.endsWith("[]")) (refs[node.ref.slice(0, -2)] ??= []).push(el);
188
+ else if (node.ref) refs[node.ref] = el;
189
+ return el;
190
+ }
191
+
192
+ /**
193
+ * Resolve what both the server render and the live player need.
194
+ * @param {Scene} scene
195
+ * @param {PlayerOptions} options
196
+ * @param {string} prefix
197
+ */
198
+ function setup(scene, options, prefix) {
199
+ const style = normalizeStyle(options.style);
200
+ const labels = { ...DEFAULT_LABELS, ...resolveLabels(options.labels, options.locale) };
201
+ const svg = renderSvg(scene, scene.duration, { style, idPrefix: prefix, live: true });
202
+ return { style, labels, svg };
203
+ }
204
+
205
+ /**
206
+ * The player's first state (final frame, controls, caption, step list) as
207
+ * HTML: put it inside a container with the class `mk-player`, beside
208
+ * PLAYER_CSS and themeCss. Until the player mounts, the controls are inert and
209
+ * the stage takes no focus; the player replaces the markup with live controls
210
+ * of the same size, so nothing moves.
211
+ * The play button stays out of view under reduced motion and without scripting.
212
+ * Pass the same options as to mountPlayer, including `id`, which is the id
213
+ * prefix and must be unique on the page.
214
+ * @param {Scene} scene
215
+ * @param {PlayerOptions & { id: string }} options
216
+ * @returns {string}
217
+ */
218
+ export function playerMarkup(scene, options) {
219
+ const prefix = safeId(options.id);
220
+ const { labels, svg } = setup(scene, options, prefix);
221
+ return view(scene, { labels, prefix, svg, scrubber: options.scrubber, captions: options.captions, playButton: true, inert: true }).map(toHtml).join("");
222
+ }
223
+
224
+ /** Add the player stylesheet unless the document has one (a page swap may have removed an earlier copy). @param {Document} doc */
225
+ function ensureStyle(doc) {
226
+ if (doc.querySelector(`style[${CSS_MARK}]`)) return;
227
+ const s = doc.createElement("style");
228
+ s.setAttribute(CSS_MARK, "");
229
+ s.textContent = PLAYER_CSS;
230
+ doc.head.appendChild(s);
231
+ }
232
+
233
+ /* ------------------------------------------------------------- the player */
36
234
 
37
235
  /**
38
236
  * Mount a scene with controls and a clock owned by this player.
39
237
  * @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]
238
+ * @param {Scene} scene
239
+ * @param {PlayerOptions} [options]
240
+ * `id`: the capture-hook key and the prefix of every id the player renders;
241
+ * unique on the page. Default: the hook key is scene.id, the prefix is
242
+ * scene.id plus a per-page counter.
42
243
  * @returns The player controller; call destroy() before removing or replacing it.
43
244
  */
44
245
  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
246
  const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
48
247
  /** @type {Document} */
49
248
  const doc = container.ownerDocument;
249
+ if (options.injectCss !== false) ensureStyle(doc);
50
250
 
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
-
251
+ // One player per container: mounting again releases the previous one.
252
+ mounted.get(container)?.destroy();
58
253
  const id = options.id ?? scene.id;
254
+ const prefix = safeId(options.id ?? `${scene.id}-${++instances}`);
255
+ const { style, labels } = setup(scene, options, prefix);
59
256
  container.classList.add("mk-player");
257
+ // Set each token as its own property: CSS the page put on the container stays.
60
258
  const applyTheme = () => {
61
259
  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}`);
260
+ const theme = dark ? "dark" : "light";
261
+ for (const token of TOKENS) container.style.setProperty(`--mk-${token}`, style[theme][token]);
262
+ container.style.setProperty("--mk-font", style.font);
63
263
  };
64
264
  applyTheme();
65
265
 
66
266
  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);
267
+ /** @type {{ stage: HTMLElement, play?: HTMLButtonElement, playLabel?: HTMLElement, steps: HTMLButtonElement[], scrub?: HTMLInputElement, captions?: HTMLElement[], live: HTMLElement }} */
268
+ const ui = /** @type {any} */ ({});
269
+ const nodes = view(scene, { labels, prefix, svg: "", scrubber: options.scrubber, captions: options.captions, playButton: !reduced, inert: false });
270
+ for (const node of nodes) if (node) container.appendChild(toDom(doc, node, ui));
271
+ const { stage, live } = ui;
126
272
 
127
273
  let t = 0;
128
274
  let playing = false;
@@ -132,105 +278,160 @@ export function mountPlayer(container, scene, options = {}) {
132
278
  let stopAt = scene.duration;
133
279
  let autoplayPending = false;
134
280
  let destroyed = false;
281
+ let liveRaf = 0;
282
+ // Last visibility the observer reported; until it reports, assume in view.
283
+ let inView = true;
284
+ // Playing, but out of view: the clock waits for the diagram to show again.
285
+ let suspended = false;
135
286
  /** @type {IntersectionObserver | undefined} */
136
287
  let visibilityObserver;
137
288
 
138
289
  function draw() {
139
- stage.innerHTML = renderSvg(scene, t, { style, idPrefix: id, live: true });
290
+ // In place: nodes that persist keep their identity, only what changed is written.
291
+ patchMarkup(stage, renderSvg(scene, t, { style, idPrefix: prefix, live: true }));
140
292
  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;
293
+ ui.steps.forEach((b, i) => (i === idx ? b.setAttribute("aria-current", "step") : b.removeAttribute("aria-current")));
294
+ ui.captions?.forEach((c, i) => (i === idx ? c.setAttribute("class", "mk-on") : c.removeAttribute("class")));
295
+ if (ui.scrub) ui.scrub.value = String(t);
296
+ if (ui.playLabel) ui.playLabel.textContent = playing ? labels.pause : t >= scene.duration ? labels.replay : labels.play;
145
297
  }
298
+ /** @param {number} time */
146
299
  function seek(time) {
147
300
  if (destroyed) return;
148
301
  playing = false;
302
+ suspended = false;
149
303
  cancelAnimationFrame(raf);
150
304
  t = Math.min(Math.max(time, 0), scene.duration);
151
305
  draw();
152
306
  }
307
+ /** @param {number} now */
153
308
  function tick(now) {
154
- if (destroyed || !playing) return;
309
+ if (destroyed || !playing || suspended) return;
155
310
  t = Math.min(tStart + (now - wallStart) / 1000, stopAt);
156
311
  if (t >= stopAt) playing = false;
157
312
  draw();
158
313
  if (playing) raf = requestAnimationFrame(tick);
159
314
  }
315
+ /** Run the clock from the current time (or wait, while out of view). */
316
+ function run() {
317
+ cancelAnimationFrame(raf);
318
+ suspended = !inView;
319
+ if (suspended) return;
320
+ tStart = t;
321
+ wallStart = performance.now();
322
+ raf = requestAnimationFrame(tick);
323
+ }
160
324
  function play() {
161
325
  if (reduced || destroyed) return;
162
326
  if (t >= scene.duration) t = 0;
163
327
  start(scene.duration);
164
328
  }
329
+ /** @param {number} target */
165
330
  function start(target) {
166
331
  autoplayPending = false;
167
- visibilityObserver?.disconnect();
168
332
  stopAt = target;
169
333
  playing = true;
170
- tStart = t;
171
- wallStart = performance.now();
172
- cancelAnimationFrame(raf);
173
- raf = requestAnimationFrame(tick);
334
+ run();
174
335
  }
175
336
  function pause() {
176
337
  playing = false;
338
+ suspended = false;
177
339
  cancelAnimationFrame(raf);
178
340
  if (!destroyed) draw();
179
341
  }
180
- playBtn?.addEventListener("click", () => (playing ? pause() : play()));
342
+ ui.play?.addEventListener("click", () => (playing ? pause() : play()));
343
+ ui.steps.forEach((b, i) => b.addEventListener("click", () => selectStep(i)));
344
+ ui.scrub?.addEventListener("input", () => {
345
+ pause();
346
+ seek(Number(ui.scrub?.value));
347
+ });
181
348
  stage.addEventListener("keydown", (e) => {
182
349
  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);
350
+ /** @param {number} i */
351
+ const step = (i) => {
352
+ selectStep(i);
353
+ announce(i);
354
+ };
355
+ if (e.key === "ArrowRight") step(Math.min(idx + 1, scene.steps.length - 1));
356
+ else if (e.key === "ArrowLeft") step(Math.max(idx - 1, 0));
357
+ else if (e.key === "Home") step(0);
358
+ else if (e.key === "End") step(scene.steps.length - 1);
187
359
  else if (e.key === " " && !reduced) playing ? pause() : play();
188
360
  else return;
189
361
  e.preventDefault();
190
362
  });
191
- function seekStep(i) {
192
- autoplayPending = false;
193
- visibilityObserver?.disconnect();
194
- seek(stepTime(i));
195
- }
196
363
  /** @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;
364
+ function announce(i) {
365
+ const s = scene.steps[i];
366
+ const text = `${i + 1}. ${s.detail ? `${s.label}: ${s.detail}` : s.label}`;
367
+ cancelAnimationFrame(liveRaf);
368
+ liveRaf = 0;
369
+ if (live.textContent !== text) {
370
+ live.textContent = text;
371
+ return;
372
+ }
373
+ // Identical text may be coalesced by screen readers: clear now, rewrite next frame.
374
+ live.textContent = "";
375
+ liveRaf = requestAnimationFrame(() => {
376
+ liveRaf = 0;
377
+ if (!destroyed) live.textContent = text;
378
+ });
200
379
  }
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);
380
+ /** Jump to a step, by index or by step id. @param {number | string} ref */
381
+ function seekStep(ref) {
382
+ const target = scene.steps[stepIndex(scene, ref)].at;
383
+ autoplayPending = false;
384
+ seek(target);
385
+ }
386
+ /** Play forward to a settled step, by index or by step id; backward/reduced-motion calls jump. @param {number | string} ref */
387
+ function playToStep(ref) {
388
+ const target = scene.steps[stepIndex(scene, ref)].at;
204
389
  autoplayPending = false;
205
- visibilityObserver?.disconnect();
206
390
  if (destroyed) return;
207
391
  if (reduced || target <= t) seek(target);
208
392
  else start(target);
209
393
  }
394
+ /** @param {number} i */
210
395
  function selectStep(i) {
211
396
  options.animateSteps ? playToStep(i) : seekStep(i);
212
397
  }
398
+ /** @param {IntersectionObserverEntry} e */
399
+ function shown(e) {
400
+ if (!e.isIntersecting) return false;
401
+ if (e.intersectionRatio >= SHOWN) return true;
402
+ const viewport = e.rootBounds?.height;
403
+ return Boolean(viewport) && e.intersectionRect.height >= SHOWN * /** @type {number} */ (viewport);
404
+ }
405
+ /** @param {IntersectionObserverEntry[]} entries */
406
+ function onVisibility(entries) {
407
+ const e = entries[entries.length - 1];
408
+ if (destroyed || !e) return;
409
+ inView = e.isIntersecting;
410
+ if (!inView) {
411
+ if (playing && !suspended) {
412
+ cancelAnimationFrame(raf);
413
+ suspended = true;
414
+ }
415
+ return;
416
+ }
417
+ if (playing && suspended) run();
418
+ if (autoplayPending && shown(e)) {
419
+ autoplayPending = false;
420
+ seek(0);
421
+ play();
422
+ }
423
+ }
213
424
 
214
425
  // Initial state: final frame (also what reduced motion and no-autoplay keep).
215
426
  seek(scene.duration);
216
427
  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
- );
428
+ if (!reduced) {
429
+ if (typeof IntersectionObserver === "function") {
430
+ autoplayPending = autoplay === "visible";
431
+ visibilityObserver = new IntersectionObserver(onVisibility, { threshold: THRESHOLDS });
232
432
  visibilityObserver.observe(container);
233
- } else {
433
+ }
434
+ if (autoplay !== "none" && !autoplayPending) {
234
435
  seek(0);
235
436
  play();
236
437
  }
@@ -241,15 +442,18 @@ export function mountPlayer(container, scene, options = {}) {
241
442
  function destroy() {
242
443
  if (destroyed) return;
243
444
  destroyed = true;
445
+ if (mounted.get(container) === controller) mounted.delete(container);
244
446
  playing = false;
245
447
  cancelAnimationFrame(raf);
448
+ cancelAnimationFrame(liveRaf);
246
449
  visibilityObserver?.disconnect();
247
450
  themeQuery?.removeEventListener?.("change", applyTheme);
248
451
  if (g.__motionKit[id] === controller) delete g.__motionKit[id];
249
452
  }
250
453
  const controller = { seek, play, pause, seekStep, playToStep, destroy, get time() { return t; }, scene };
251
- const g = globalThis;
454
+ const g = /** @type {any} */ (globalThis);
252
455
  g.__motionKit = g.__motionKit ?? {};
253
456
  g.__motionKit[id] = controller;
457
+ mounted.set(container, controller);
254
458
  return controller;
255
459
  }