@liqweed/motion-kit 0.2.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 +74 -7
- package/adapters/astro/AnimatedDiagram.astro +150 -24
- package/adapters/element/README.md +49 -0
- package/adapters/element/motion-diagram.mjs +124 -0
- package/adapters/page/README.md +3 -2
- package/adapters/slidev/AnimatedDiagram.vue +24 -0
- package/cli/motion-kit.mjs +77 -79
- package/docs/spec/technique.md +102 -44
- 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 +375 -127
- 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 +50 -7
- 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 +18 -2
package/runtime/player.mjs
CHANGED
|
@@ -1,207 +1,455 @@
|
|
|
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
|
-
* animation), an optional scrubber, and
|
|
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
|
-
|
|
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];
|
|
36
61
|
|
|
37
|
-
|
|
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) {
|
|
38
196
|
const style = normalizeStyle(options.style);
|
|
39
|
-
const labels = {
|
|
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 */
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Mount a scene with controls and a clock owned by this player.
|
|
234
|
+
* @param {HTMLElement} container
|
|
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.
|
|
240
|
+
* @returns The player controller; call destroy() before removing or replacing it.
|
|
241
|
+
*/
|
|
242
|
+
export function mountPlayer(container, scene, options = {}) {
|
|
40
243
|
const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
41
244
|
/** @type {Document} */
|
|
42
245
|
const doc = container.ownerDocument;
|
|
246
|
+
if (options.injectCss !== false) ensureStyle(doc);
|
|
43
247
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
s.textContent = CSS;
|
|
47
|
-
doc.head.appendChild(s);
|
|
48
|
-
styleInjected = true;
|
|
49
|
-
}
|
|
50
|
-
|
|
248
|
+
// One player per container: mounting again releases the previous one.
|
|
249
|
+
mounted.get(container)?.destroy();
|
|
51
250
|
const id = options.id ?? scene.id;
|
|
251
|
+
const prefix = safeId(options.id ?? `${scene.id}-${++instances}`);
|
|
252
|
+
const { style, labels } = setup(scene, options, prefix);
|
|
52
253
|
container.classList.add("mk-player");
|
|
254
|
+
// Set each token as its own property: CSS the page put on the container stays.
|
|
53
255
|
const applyTheme = () => {
|
|
54
256
|
const dark = options.theme === "dark" || (options.theme !== "light" && typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches);
|
|
55
|
-
|
|
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);
|
|
56
260
|
};
|
|
57
261
|
applyTheme();
|
|
58
262
|
|
|
59
263
|
container.innerHTML = "";
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const controls = doc.createElement("div");
|
|
67
|
-
controls.className = "mk-controls";
|
|
68
|
-
controls.setAttribute("role", "group");
|
|
69
|
-
controls.setAttribute("aria-label", scene.title);
|
|
70
|
-
container.appendChild(controls);
|
|
71
|
-
|
|
72
|
-
/** @type {HTMLButtonElement | null} */
|
|
73
|
-
let playBtn = null;
|
|
74
|
-
if (!reduced) {
|
|
75
|
-
playBtn = doc.createElement("button");
|
|
76
|
-
playBtn.type = "button";
|
|
77
|
-
playBtn.className = "mk-btn mk-play";
|
|
78
|
-
controls.appendChild(playBtn);
|
|
79
|
-
}
|
|
80
|
-
const stepBtns = scene.steps.map((s, i) => {
|
|
81
|
-
const b = doc.createElement("button");
|
|
82
|
-
b.type = "button";
|
|
83
|
-
b.className = "mk-btn";
|
|
84
|
-
b.textContent = `${i + 1}. ${s.label}`;
|
|
85
|
-
b.addEventListener("click", () => {
|
|
86
|
-
pause();
|
|
87
|
-
seek(s.at);
|
|
88
|
-
});
|
|
89
|
-
controls.appendChild(b);
|
|
90
|
-
return b;
|
|
91
|
-
});
|
|
92
|
-
/** @type {HTMLInputElement | null} */
|
|
93
|
-
let scrub = null;
|
|
94
|
-
if (options.scrubber) {
|
|
95
|
-
const input = doc.createElement("input");
|
|
96
|
-
input.type = "range";
|
|
97
|
-
input.className = "mk-scrub";
|
|
98
|
-
input.min = "0";
|
|
99
|
-
input.max = String(scene.duration);
|
|
100
|
-
input.step = "0.01";
|
|
101
|
-
input.setAttribute("aria-label", options.labels?.scrubber ?? "Timeline");
|
|
102
|
-
input.addEventListener("input", () => {
|
|
103
|
-
pause();
|
|
104
|
-
seek(Number(input.value));
|
|
105
|
-
});
|
|
106
|
-
controls.appendChild(input);
|
|
107
|
-
scrub = input;
|
|
108
|
-
}
|
|
109
|
-
const caption = doc.createElement("p");
|
|
110
|
-
caption.className = "mk-caption";
|
|
111
|
-
caption.setAttribute("aria-hidden", "true");
|
|
112
|
-
if (options.captions !== false) container.appendChild(caption);
|
|
113
|
-
|
|
114
|
-
const sr = doc.createElement("ol");
|
|
115
|
-
sr.className = "mk-sr";
|
|
116
|
-
for (const s of scene.steps) {
|
|
117
|
-
const li = doc.createElement("li");
|
|
118
|
-
li.textContent = s.detail ? `${s.label}: ${s.detail}` : s.label;
|
|
119
|
-
sr.appendChild(li);
|
|
120
|
-
}
|
|
121
|
-
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;
|
|
122
269
|
|
|
123
270
|
let t = 0;
|
|
124
271
|
let playing = false;
|
|
125
272
|
let raf = 0;
|
|
126
273
|
let wallStart = 0;
|
|
127
274
|
let tStart = 0;
|
|
275
|
+
let stopAt = scene.duration;
|
|
276
|
+
let autoplayPending = false;
|
|
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;
|
|
283
|
+
/** @type {IntersectionObserver | undefined} */
|
|
284
|
+
let visibilityObserver;
|
|
128
285
|
|
|
129
286
|
function draw() {
|
|
130
|
-
stage.innerHTML = renderSvg(scene, t, { style, idPrefix:
|
|
287
|
+
stage.innerHTML = renderSvg(scene, t, { style, idPrefix: prefix, live: true });
|
|
131
288
|
const idx = stepIndexAt(scene, t);
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
if (scrub) scrub.value = String(t);
|
|
135
|
-
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;
|
|
136
293
|
}
|
|
294
|
+
/** @param {number} time */
|
|
137
295
|
function seek(time) {
|
|
296
|
+
if (destroyed) return;
|
|
297
|
+
playing = false;
|
|
298
|
+
suspended = false;
|
|
299
|
+
cancelAnimationFrame(raf);
|
|
138
300
|
t = Math.min(Math.max(time, 0), scene.duration);
|
|
139
301
|
draw();
|
|
140
302
|
}
|
|
303
|
+
/** @param {number} now */
|
|
141
304
|
function tick(now) {
|
|
142
|
-
|
|
143
|
-
|
|
305
|
+
if (destroyed || !playing || suspended) return;
|
|
306
|
+
t = Math.min(tStart + (now - wallStart) / 1000, stopAt);
|
|
307
|
+
if (t >= stopAt) playing = false;
|
|
144
308
|
draw();
|
|
145
309
|
if (playing) raf = requestAnimationFrame(tick);
|
|
146
310
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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;
|
|
151
316
|
tStart = t;
|
|
152
317
|
wallStart = performance.now();
|
|
153
|
-
cancelAnimationFrame(raf);
|
|
154
318
|
raf = requestAnimationFrame(tick);
|
|
155
319
|
}
|
|
320
|
+
function play() {
|
|
321
|
+
if (reduced || destroyed) return;
|
|
322
|
+
if (t >= scene.duration) t = 0;
|
|
323
|
+
start(scene.duration);
|
|
324
|
+
}
|
|
325
|
+
/** @param {number} target */
|
|
326
|
+
function start(target) {
|
|
327
|
+
autoplayPending = false;
|
|
328
|
+
stopAt = target;
|
|
329
|
+
playing = true;
|
|
330
|
+
run();
|
|
331
|
+
}
|
|
156
332
|
function pause() {
|
|
157
333
|
playing = false;
|
|
334
|
+
suspended = false;
|
|
158
335
|
cancelAnimationFrame(raf);
|
|
159
|
-
draw();
|
|
336
|
+
if (!destroyed) draw();
|
|
160
337
|
}
|
|
161
|
-
|
|
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
|
+
});
|
|
162
344
|
stage.addEventListener("keydown", (e) => {
|
|
163
345
|
const idx = stepIndexAt(scene, t);
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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);
|
|
168
355
|
else if (e.key === " " && !reduced) playing ? pause() : play();
|
|
169
356
|
else return;
|
|
170
357
|
e.preventDefault();
|
|
171
358
|
});
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
359
|
+
/** @param {number} i */
|
|
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
|
+
});
|
|
375
|
+
}
|
|
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;
|
|
385
|
+
autoplayPending = false;
|
|
386
|
+
if (destroyed) return;
|
|
387
|
+
if (reduced || target <= t) seek(target);
|
|
388
|
+
else start(target);
|
|
389
|
+
}
|
|
390
|
+
/** @param {number} i */
|
|
391
|
+
function selectStep(i) {
|
|
392
|
+
options.animateSteps ? playToStep(i) : seekStep(i);
|
|
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
|
+
}
|
|
175
419
|
}
|
|
176
420
|
|
|
177
421
|
// Initial state: final frame (also what reduced motion and no-autoplay keep).
|
|
178
422
|
seek(scene.duration);
|
|
179
423
|
const autoplay = options.autoplay ?? "visible";
|
|
180
|
-
if (!reduced
|
|
181
|
-
if (
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
play();
|
|
188
|
-
}
|
|
189
|
-
},
|
|
190
|
-
{ threshold: 0.4 },
|
|
191
|
-
);
|
|
192
|
-
io.observe(container);
|
|
193
|
-
} else {
|
|
424
|
+
if (!reduced) {
|
|
425
|
+
if (typeof IntersectionObserver === "function") {
|
|
426
|
+
autoplayPending = autoplay === "visible";
|
|
427
|
+
visibilityObserver = new IntersectionObserver(onVisibility, { threshold: THRESHOLDS });
|
|
428
|
+
visibilityObserver.observe(container);
|
|
429
|
+
}
|
|
430
|
+
if (autoplay !== "none" && !autoplayPending) {
|
|
194
431
|
seek(0);
|
|
195
432
|
play();
|
|
196
433
|
}
|
|
197
434
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
}
|
|
435
|
+
const themeQuery = typeof matchMedia === "function" && !options.theme ? matchMedia("(prefers-color-scheme: dark)") : null;
|
|
436
|
+
themeQuery?.addEventListener?.("change", applyTheme);
|
|
201
437
|
|
|
202
|
-
|
|
203
|
-
|
|
438
|
+
function destroy() {
|
|
439
|
+
if (destroyed) return;
|
|
440
|
+
destroyed = true;
|
|
441
|
+
if (mounted.get(container) === controller) mounted.delete(container);
|
|
442
|
+
playing = false;
|
|
443
|
+
cancelAnimationFrame(raf);
|
|
444
|
+
cancelAnimationFrame(liveRaf);
|
|
445
|
+
visibilityObserver?.disconnect();
|
|
446
|
+
themeQuery?.removeEventListener?.("change", applyTheme);
|
|
447
|
+
if (g.__motionKit[id] === controller) delete g.__motionKit[id];
|
|
448
|
+
}
|
|
449
|
+
const controller = { seek, play, pause, seekStep, playToStep, destroy, get time() { return t; }, scene };
|
|
450
|
+
const g = /** @type {any} */ (globalThis);
|
|
204
451
|
g.__motionKit = g.__motionKit ?? {};
|
|
205
452
|
g.__motionKit[id] = controller;
|
|
453
|
+
mounted.set(container, controller);
|
|
206
454
|
return controller;
|
|
207
455
|
}
|