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