@liqweed/motion-kit 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +24 -2
- package/adapters/element/README.md +49 -0
- package/adapters/element/motion-diagram.mjs +123 -0
- package/cli/motion-kit.mjs +1 -1
- package/docs/spec/technique.md +30 -12
- package/package.json +1 -1
- package/runtime/player.mjs +74 -26
- package/skills/animated-diagram/references/interactivity.md +15 -2
- package/skills/motion-render/SKILL.md +11 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "motion-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Deterministic animated diagrams: scenes as pure functions of time for live pages, Slidev, slide frames, baked SVG and video; plus project logos/icons.",
|
|
5
5
|
"author": { "name": "Ophir Radnitz" },
|
|
6
6
|
"repository": "https://github.com/liqweed/motion-kit",
|
package/README.md
CHANGED
|
@@ -64,7 +64,7 @@ runtime/ dependency-free ES modules (browser + Node)
|
|
|
64
64
|
bake.mjs zero-JS animated SVG
|
|
65
65
|
player.mjs live player (controls, a11y, reduced motion, capture hook)
|
|
66
66
|
lib/ Node-side: check (gate), export, build (HTML inliner), raster, video, icon
|
|
67
|
-
adapters/ slidev (Vue), astro, page (README)
|
|
67
|
+
adapters/ slidev (Vue), astro, element (custom element), page (README)
|
|
68
68
|
skills/ animated-diagram, motion-render, project-logo (Claude Code / Craft skills)
|
|
69
69
|
examples/ order-flow (sequence), smart-home (hub-spoke), custom-pulse (custom module)
|
|
70
70
|
brand/ logo scene (built with motion-kit); renders go to assets/ + .idea/ (npm run media)
|
|
@@ -89,7 +89,7 @@ The skills look for this clone at `~/workspace/motion-kit` first (it has
|
|
|
89
89
|
## Use in another repo (vendor)
|
|
90
90
|
|
|
91
91
|
```bash
|
|
92
|
-
node cli/motion-kit.mjs vendor <repo>/components/motion-kit --adapter slidev # or astro / page
|
|
92
|
+
node cli/motion-kit.mjs vendor <repo>/components/motion-kit --adapter slidev # or astro / page / element
|
|
93
93
|
```
|
|
94
94
|
|
|
95
95
|
Copies `runtime/`, the adapter, `lib/check.mjs` and `LICENSE`; writes a gate
|
|
@@ -97,6 +97,28 @@ script and `MOTION_KIT_VERSION`. Don't edit vendored files; change motion-kit
|
|
|
97
97
|
and re-vendor. Vendoring keeps consumer CI
|
|
98
98
|
self-contained (no install step, no network).
|
|
99
99
|
|
|
100
|
+
### Plain HTML and framework-independent custom element
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
node cli/motion-kit.mjs vendor public/motion-kit --adapter element
|
|
104
|
+
cp diagram.json public/diagram.json
|
|
105
|
+
cp diagram-final.svg public/diagram-final.svg # the final-frame fallback image
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```html
|
|
109
|
+
<motion-diagram src="./diagram.json" format="wide" locale="en">
|
|
110
|
+
<img src="./diagram-final.svg" alt="The complete diagram and its explanation">
|
|
111
|
+
</motion-diagram>
|
|
112
|
+
<script type="module" src="./motion-kit/adapter/motion-diagram.mjs"></script>
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Serve the files over HTTP; no build step is needed. The supplied final-frame
|
|
116
|
+
fallback stays visible without JavaScript, while loading and on errors. Specs
|
|
117
|
+
can also be inline JSON. `theme` and JSON `style-spec` attributes configure
|
|
118
|
+
the appearance, and `element.controller` exposes the live player after the
|
|
119
|
+
`motion-ready` event. See [the element adapter](adapters/element/README.md)
|
|
120
|
+
for inline specs, styles, lifecycle and error handling.
|
|
121
|
+
|
|
100
122
|
## Rules (the gate enforces them)
|
|
101
123
|
|
|
102
124
|
Deterministic bytes · settled step frames · rounded numbers · token-only colours ·
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Custom element (unbuilt ES module)
|
|
2
|
+
|
|
3
|
+
```bash
|
|
4
|
+
node cli/motion-kit.mjs vendor public/motion-kit --adapter element
|
|
5
|
+
node cli/motion-kit.mjs export diagram.json -o public/frames -f wide
|
|
6
|
+
cp diagram.json public/diagram.json
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Serve `public/` over HTTP. Copy the final exported SVG path into the fallback:
|
|
10
|
+
|
|
11
|
+
```html
|
|
12
|
+
<style>motion-diagram { display: block; }</style>
|
|
13
|
+
<motion-diagram src="./diagram.json" format="wide" locale="en" theme="light">
|
|
14
|
+
<img src="./frames/06-final.svg" alt="The complete diagram and its explanation">
|
|
15
|
+
</motion-diagram>
|
|
16
|
+
<script type="module" src="./motion-kit/adapter/motion-diagram.mjs"></script>
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Use the actual final SVG filename from the export manifest. The child markup
|
|
20
|
+
is the no-JavaScript fallback; it can also be a server-rendered final-frame SVG.
|
|
21
|
+
The adapter retains it while loading, restores it on errors and disconnection,
|
|
22
|
+
and hides it only after the live player mounts. Supply meaningful alternative
|
|
23
|
+
text and size the fallback to match the live diagram to avoid layout shifts.
|
|
24
|
+
|
|
25
|
+
Instead of `src`, supply JSON in a `spec` attribute or a child
|
|
26
|
+
`<script type="application/json">…</script>`. Precedence: `spec`, child JSON,
|
|
27
|
+
then `src`. Escape JSON for its HTML context (in a script, escape `<` as
|
|
28
|
+
`\u003c`). `src` resolves relative to the page, including its `<base>` URL.
|
|
29
|
+
|
|
30
|
+
Observed attributes are `spec`, `src`, `format` (default `16:9`), `locale`
|
|
31
|
+
(default `en`), `theme` (`light`/`dark`, absent follows the OS), and
|
|
32
|
+
`style-spec` (JSON visual-style tokens, default neutral). The standard `style`
|
|
33
|
+
attribute remains CSS, for example `style="max-width: 960px"`. Attribute
|
|
34
|
+
changes rebuild the player. Inline script text changes require a remount
|
|
35
|
+
(remove and reinsert the element).
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
const diagram = document.querySelector("motion-diagram");
|
|
39
|
+
diagram.addEventListener("motion-ready", ({ detail }) => detail.controller.play());
|
|
40
|
+
diagram.addEventListener("motion-error", ({ detail }) => console.error(detail.error));
|
|
41
|
+
// null until mounted; exposes seek, seekStep, playToStep, play, pause, destroy, time, scene.
|
|
42
|
+
diagram.controller?.seek(2);
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The player follows its normal visible autoplay and reduced-motion rules.
|
|
46
|
+
Removing the element destroys its player, cancels pending loading and restores
|
|
47
|
+
the fallback; reconnecting mounts a fresh controller. Events are dispatched
|
|
48
|
+
on the element. Loading failures leave `controller` null. Scripts and JSON
|
|
49
|
+
must be served from origins allowed by the page's CSP and CORS policy.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Ophir Radnitz
|
|
3
|
+
/**
|
|
4
|
+
* Unbuilt custom element adapter. Vendor this directory beside runtime/:
|
|
5
|
+
* <script type="module" src="./motion-kit/adapter/motion-diagram.mjs"></script>
|
|
6
|
+
* <motion-diagram src="./diagram.json"><img src="./final.svg" alt="…"></motion-diagram>
|
|
7
|
+
*
|
|
8
|
+
* The light-DOM fallback stays visible until a player mounts successfully.
|
|
9
|
+
* `style-spec` is JSON token data; the standard HTML `style` attribute stays CSS.
|
|
10
|
+
*/
|
|
11
|
+
import { mountPlayer } from "../runtime/player.mjs";
|
|
12
|
+
import { createScene } from "../runtime/types/index.mjs";
|
|
13
|
+
|
|
14
|
+
let nextId = 0;
|
|
15
|
+
|
|
16
|
+
export class MotionDiagram extends HTMLElement {
|
|
17
|
+
static get observedAttributes() {
|
|
18
|
+
return ["spec", "src", "format", "locale", "theme", "style-spec"];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
constructor() {
|
|
22
|
+
super();
|
|
23
|
+
/** @type {ReturnType<typeof mountPlayer> | null} */
|
|
24
|
+
this.controller = null;
|
|
25
|
+
this._id = `mk-element-${++nextId}`;
|
|
26
|
+
this._revision = 0;
|
|
27
|
+
this._queued = false;
|
|
28
|
+
/** @type {AbortController | null} */
|
|
29
|
+
this._request = null;
|
|
30
|
+
/** @type {HTMLDivElement | null} */
|
|
31
|
+
this._fallback = null;
|
|
32
|
+
/** @type {HTMLDivElement | null} */
|
|
33
|
+
this._player = null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
connectedCallback() {
|
|
37
|
+
this._schedule();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
disconnectedCallback() {
|
|
41
|
+
this._revision++;
|
|
42
|
+
this._reset();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
attributeChangedCallback() {
|
|
46
|
+
// Invalidate before the queued remount: a resolved fetch may already
|
|
47
|
+
// have its continuation ahead of that microtask.
|
|
48
|
+
this._revision++;
|
|
49
|
+
this._request?.abort();
|
|
50
|
+
this._schedule();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
_schedule() {
|
|
54
|
+
if (this._queued) return;
|
|
55
|
+
this._queued = true;
|
|
56
|
+
queueMicrotask(() => {
|
|
57
|
+
this._queued = false;
|
|
58
|
+
if (this.isConnected) void this._mount();
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
_reset() {
|
|
63
|
+
this._request?.abort();
|
|
64
|
+
this._request = null;
|
|
65
|
+
this.controller?.destroy();
|
|
66
|
+
this.controller = null;
|
|
67
|
+
this._player?.remove();
|
|
68
|
+
this._player = null;
|
|
69
|
+
if (this._fallback) this._fallback.hidden = false;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async _mount() {
|
|
73
|
+
const revision = ++this._revision;
|
|
74
|
+
this._reset();
|
|
75
|
+
if (!this._fallback) {
|
|
76
|
+
const fallback = this.ownerDocument.createElement("div");
|
|
77
|
+
fallback.setAttribute("data-mk-fallback", "");
|
|
78
|
+
for (const child of [...this.childNodes]) {
|
|
79
|
+
// Keep inline JSON available for attribute-driven remounts.
|
|
80
|
+
if (child instanceof Element && child.matches('script[type="application/json"]')) continue;
|
|
81
|
+
fallback.appendChild(child);
|
|
82
|
+
}
|
|
83
|
+
this.appendChild(fallback);
|
|
84
|
+
this._fallback = fallback;
|
|
85
|
+
}
|
|
86
|
+
const request = new AbortController();
|
|
87
|
+
this._request = request;
|
|
88
|
+
/** @type {HTMLDivElement | null} */
|
|
89
|
+
let player = null;
|
|
90
|
+
try {
|
|
91
|
+
const inline = this.getAttribute("spec") ?? this.querySelector('script[type="application/json"]')?.textContent;
|
|
92
|
+
const src = this.getAttribute("src");
|
|
93
|
+
let spec;
|
|
94
|
+
if (inline != null) spec = JSON.parse(inline);
|
|
95
|
+
else if (src) {
|
|
96
|
+
const response = await fetch(new URL(src, this.baseURI), { signal: request.signal });
|
|
97
|
+
if (!response.ok) throw new Error(`motion-diagram: spec request failed (${response.status})`);
|
|
98
|
+
spec = await response.json();
|
|
99
|
+
} else throw new Error("motion-diagram: provide spec, inline application/json, or src");
|
|
100
|
+
if (!this.isConnected || revision !== this._revision) return;
|
|
101
|
+
const theme = this.getAttribute("theme");
|
|
102
|
+
if (theme && theme !== "light" && theme !== "dark") throw new Error('motion-diagram: theme must be "light" or "dark"');
|
|
103
|
+
const scene = createScene(spec, { format: this.getAttribute("format") ?? "16:9", locale: this.getAttribute("locale") ?? "en" });
|
|
104
|
+
const style = JSON.parse(this.getAttribute("style-spec") ?? "null");
|
|
105
|
+
player = this.ownerDocument.createElement("div");
|
|
106
|
+
// Mount inside a child so player CSS cannot overwrite the host's CSS.
|
|
107
|
+
this.appendChild(player);
|
|
108
|
+
this.controller = mountPlayer(player, scene, { id: this._id, style, theme: theme || undefined });
|
|
109
|
+
this._player = player;
|
|
110
|
+
this._fallback.hidden = true;
|
|
111
|
+
this.dispatchEvent(new CustomEvent("motion-ready", { detail: { controller: this.controller } }));
|
|
112
|
+
} catch (error) {
|
|
113
|
+
player?.remove();
|
|
114
|
+
if (this.isConnected && revision === this._revision) {
|
|
115
|
+
this.dispatchEvent(new CustomEvent("motion-error", { detail: { error } }));
|
|
116
|
+
}
|
|
117
|
+
} finally {
|
|
118
|
+
if (this._request === request) this._request = null;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (!customElements.get("motion-diagram")) customElements.define("motion-diagram", MotionDiagram);
|
package/cli/motion-kit.mjs
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* motion-kit bake <scene> --out x.svg [--fps 15] [--theme ...] [--style S]
|
|
9
9
|
* motion-kit video <scene> --out x.mp4|.gif|.webm [--fps 30] [--scale 2] [--hold 1.5] [--sheet sheet.png]
|
|
10
10
|
* motion-kit icon <scene> --out <repo> [--size 512] [--style S] [--no-png] project icon set (assets/, .idea/)
|
|
11
|
-
* motion-kit vendor <dir> [--adapter page|slidev|astro]
|
|
11
|
+
* motion-kit vendor <dir> [--adapter page|slidev|astro|element]
|
|
12
12
|
* motion-kit formats | types
|
|
13
13
|
*
|
|
14
14
|
* <scene> is a spec (.json, any registered type) or a custom module (.mjs).
|
package/docs/spec/technique.md
CHANGED
|
@@ -305,21 +305,39 @@ Every target goes through this one function. It MUST emit `<svg>` with
|
|
|
305
305
|
|
|
306
306
|
| Requirement | Source |
|
|
307
307
|
|---|---|
|
|
308
|
-
| MUST touch the DOM only when mounted; scenes stay pure, the player owns the clock (`requestAnimationFrame`, wall time). | `runtime/player.mjs
|
|
309
|
-
| Initial state MUST be the final frame; a server/no-JS fallback SHOULD put the final frame in the container. |
|
|
310
|
-
| Autoplay `visible` (default): plays once from 0 when ≥ 40 % in view, then holds; `none` disables. MUST NOT loop. |
|
|
311
|
-
| Play/pause MUST always be present when motion can play (WCAG 2.2.2); label shows Play/Pause/Replay. |
|
|
312
|
-
| One `<button>` per step, labelled `N. label`; activating it
|
|
313
|
-
| Optional range scrubber (`aria-label`, default "Timeline"); input pauses and seeks. |
|
|
314
|
-
| Caption shows the active step's `detail` and is `aria-hidden`; a visually hidden ordered list of all steps (`label: detail`) MUST be present for screen readers. |
|
|
315
|
-
| Keyboard on the focusable stage: ←/→ step, Home/End first/last, Space play/pause. |
|
|
316
|
-
| Visible focus style for every control. |
|
|
317
|
-
| `prefers-reduced-motion: reduce`: final frame, no autoplay, no play button, Space ignored. |
|
|
318
|
-
| Theme: `options.theme`, else follows `prefers-color-scheme` live. |
|
|
319
|
-
|
|
|
308
|
+
| MUST touch the DOM only when mounted; scenes stay pure, the player owns the clock (`requestAnimationFrame`, wall time). | `runtime/player.mjs` (`mountPlayer`, `tick`), `AGENTS.md` |
|
|
309
|
+
| Initial state MUST be the final frame; a server/no-JS fallback SHOULD put the final frame in the container. | `runtime/player.mjs` (initial-state block), `lib/build.mjs:25`, `adapters/astro/AnimatedDiagram.astro:31` |
|
|
310
|
+
| Autoplay `visible` (default): plays once from 0 when ≥ 40 % in view, then holds; `none` disables. MUST NOT loop. | `runtime/player.mjs` (`autoplay`, `autoplayPending`) |
|
|
311
|
+
| Play/pause MUST always be present when motion can play (WCAG 2.2.2); label shows Play/Pause/Replay. | `runtime/player.mjs` (`playBtn`, `draw`) |
|
|
312
|
+
| One `<button>` per step, labelled `N. label`; activating it jumps by default. `animateSteps: true` opts buttons and keyboard navigation into `playToStep`. `aria-current="step"` marks the active step. | `runtime/player.mjs` |
|
|
313
|
+
| Optional range scrubber (`aria-label`, default "Timeline"); input pauses and seeks. | `runtime/player.mjs` (`options.scrubber`) |
|
|
314
|
+
| Caption shows the active step's `detail` and is `aria-hidden`; a visually hidden ordered list of all steps (`label: detail`) MUST be present for screen readers. | `runtime/player.mjs` (`caption`, `sr`) |
|
|
315
|
+
| Keyboard on the focusable stage: ←/→ step, Home/End first/last, Space play/pause. | `runtime/player.mjs` (`stage.tabIndex`, `keydown` handler) |
|
|
316
|
+
| Visible focus style for every control. | `runtime/player.mjs` (`.mk-btn:focus-visible` rule) |
|
|
317
|
+
| `prefers-reduced-motion: reduce`: final frame, no autoplay, no play button, Space ignored. | `runtime/player.mjs` (`reduced`) |
|
|
318
|
+
| Theme: `options.theme`, else follows `prefers-color-scheme` live. | `runtime/player.mjs` (`applyTheme`, `themeQuery`) |
|
|
319
|
+
| `playToStep(i)` MUST play forward from the current time, clamp to the target step's exact `at` and hold. Backward, same-time and reduced-motion calls MUST jump. Indices are zero-based; invalid indices throw `RangeError`. Retargeting replaces the target; `play()` continues to duration; `seek(t)` cancels playback. | `runtime/player.mjs`, `test/player.test.mjs` |
|
|
320
|
+
| `destroy()` MUST cancel the animation frame, disconnect visibility observation, remove theme listening and remove this controller's capture entry. | `runtime/player.mjs`, `test/player.test.mjs` |
|
|
321
|
+
| **Capture hook**: the controller `{seek, play, pause, seekStep, playToStep, destroy, time, scene}` MUST be exposed at `globalThis.__motionKit[options.id ?? scene.id]`. | `runtime/player.mjs` |
|
|
320
322
|
|
|
321
323
|
UI strings MAY be localized via `options.labels`.
|
|
322
324
|
|
|
325
|
+
### 10.2.1 Custom element (`adapters/element/motion-diagram.mjs`)
|
|
326
|
+
|
|
327
|
+
- Vendoring with `--adapter element` MUST copy an unbuilt module importing the
|
|
328
|
+
adjacent vendored runtime. Importing it in a browser defines `<motion-diagram>`.
|
|
329
|
+
- The spec MUST come from the `spec` JSON attribute, a child
|
|
330
|
+
`script[type="application/json"]`, or a `src` URL, in that order. URLs resolve
|
|
331
|
+
against the document base URI. `format` and `locale` select the scene;
|
|
332
|
+
`theme` and JSON `style-spec` configure the player; HTML `style` remains CSS.
|
|
333
|
+
- Supplied final-frame child markup MUST remain visible without JavaScript,
|
|
334
|
+
while loading and on errors. Only a successful mount hides the fallback.
|
|
335
|
+
- `controller` MUST expose the mounted player, or be null when unmounted.
|
|
336
|
+
`motion-ready` carries `detail.controller`; `motion-error` carries `detail.error`.
|
|
337
|
+
- Observed attribute changes MUST remount. Disconnection MUST abort loading,
|
|
338
|
+
destroy the player and restore the fallback; reconnection mounts afresh.
|
|
339
|
+
Superseded asynchronous loads MUST NOT mount or publish errors.
|
|
340
|
+
|
|
323
341
|
### 10.3 Self-contained HTML (`motion-kit build`, `lib/build.mjs`)
|
|
324
342
|
|
|
325
343
|
- MUST be one document with the runtime inlined by `lib/bundle.mjs`, no
|
package/package.json
CHANGED
package/runtime/player.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* replaces it on mount.
|
|
10
10
|
* - Plays once when ~40 % visible, then holds the final frame.
|
|
11
11
|
* - Always shows pause/play (WCAG 2.2.2), one button per step (jumps, no
|
|
12
|
-
* animation), an optional scrubber, and
|
|
12
|
+
* animation unless animateSteps is enabled), an optional scrubber, and captions.
|
|
13
13
|
* - prefers-reduced-motion: final frame immediately, no autoplay, no play button.
|
|
14
14
|
* - Keyboard: ←/→ previous/next step, Space play/pause, Home/End.
|
|
15
15
|
* - Capture hook: controller.seek(t), and window.__motionKit[id] for renderers.
|
|
@@ -32,8 +32,15 @@ const CSS = `
|
|
|
32
32
|
.mk-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
|
|
33
33
|
`;
|
|
34
34
|
|
|
35
|
-
|
|
35
|
+
const styledDocuments = new WeakSet();
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Mount a scene with controls and a clock owned by this player.
|
|
39
|
+
* @param {HTMLElement} container
|
|
40
|
+
* @param {{ id: string, title: string, description: string, width: number, height: number, duration: number, steps: { at: number, label: string, detail?: string }[], frame: (t: number) => string }} scene
|
|
41
|
+
* @param {{ style?: Parameters<typeof normalizeStyle>[0], labels?: Record<string, string>, theme?: string, id?: string, injectCss?: boolean, scrubber?: boolean, captions?: boolean, autoplay?: string, animateSteps?: boolean }} [options]
|
|
42
|
+
* @returns The player controller; call destroy() before removing or replacing it.
|
|
43
|
+
*/
|
|
37
44
|
export function mountPlayer(container, scene, options = {}) {
|
|
38
45
|
const style = normalizeStyle(options.style);
|
|
39
46
|
const labels = { play: "Play", pause: "Pause", replay: "Replay", steps: "Steps", ...(options.labels ?? {}) };
|
|
@@ -41,11 +48,11 @@ export function mountPlayer(container, scene, options = {}) {
|
|
|
41
48
|
/** @type {Document} */
|
|
42
49
|
const doc = container.ownerDocument;
|
|
43
50
|
|
|
44
|
-
if (!
|
|
51
|
+
if (!styledDocuments.has(doc) && options.injectCss !== false) {
|
|
45
52
|
const s = doc.createElement("style");
|
|
46
53
|
s.textContent = CSS;
|
|
47
54
|
doc.head.appendChild(s);
|
|
48
|
-
|
|
55
|
+
styledDocuments.add(doc);
|
|
49
56
|
}
|
|
50
57
|
|
|
51
58
|
const id = options.id ?? scene.id;
|
|
@@ -82,10 +89,7 @@ export function mountPlayer(container, scene, options = {}) {
|
|
|
82
89
|
b.type = "button";
|
|
83
90
|
b.className = "mk-btn";
|
|
84
91
|
b.textContent = `${i + 1}. ${s.label}`;
|
|
85
|
-
b.addEventListener("click", () =>
|
|
86
|
-
pause();
|
|
87
|
-
seek(s.at);
|
|
88
|
-
});
|
|
92
|
+
b.addEventListener("click", () => selectStep(i));
|
|
89
93
|
controls.appendChild(b);
|
|
90
94
|
return b;
|
|
91
95
|
});
|
|
@@ -125,6 +129,11 @@ export function mountPlayer(container, scene, options = {}) {
|
|
|
125
129
|
let raf = 0;
|
|
126
130
|
let wallStart = 0;
|
|
127
131
|
let tStart = 0;
|
|
132
|
+
let stopAt = scene.duration;
|
|
133
|
+
let autoplayPending = false;
|
|
134
|
+
let destroyed = false;
|
|
135
|
+
/** @type {IntersectionObserver | undefined} */
|
|
136
|
+
let visibilityObserver;
|
|
128
137
|
|
|
129
138
|
function draw() {
|
|
130
139
|
stage.innerHTML = renderSvg(scene, t, { style, idPrefix: id, live: true });
|
|
@@ -135,18 +144,28 @@ export function mountPlayer(container, scene, options = {}) {
|
|
|
135
144
|
if (playBtn) playBtn.textContent = playing ? labels.pause : t >= scene.duration ? labels.replay : labels.play;
|
|
136
145
|
}
|
|
137
146
|
function seek(time) {
|
|
147
|
+
if (destroyed) return;
|
|
148
|
+
playing = false;
|
|
149
|
+
cancelAnimationFrame(raf);
|
|
138
150
|
t = Math.min(Math.max(time, 0), scene.duration);
|
|
139
151
|
draw();
|
|
140
152
|
}
|
|
141
153
|
function tick(now) {
|
|
142
|
-
|
|
143
|
-
|
|
154
|
+
if (destroyed || !playing) return;
|
|
155
|
+
t = Math.min(tStart + (now - wallStart) / 1000, stopAt);
|
|
156
|
+
if (t >= stopAt) playing = false;
|
|
144
157
|
draw();
|
|
145
158
|
if (playing) raf = requestAnimationFrame(tick);
|
|
146
159
|
}
|
|
147
160
|
function play() {
|
|
148
|
-
if (reduced) return;
|
|
161
|
+
if (reduced || destroyed) return;
|
|
149
162
|
if (t >= scene.duration) t = 0;
|
|
163
|
+
start(scene.duration);
|
|
164
|
+
}
|
|
165
|
+
function start(target) {
|
|
166
|
+
autoplayPending = false;
|
|
167
|
+
visibilityObserver?.disconnect();
|
|
168
|
+
stopAt = target;
|
|
150
169
|
playing = true;
|
|
151
170
|
tStart = t;
|
|
152
171
|
wallStart = performance.now();
|
|
@@ -156,22 +175,40 @@ export function mountPlayer(container, scene, options = {}) {
|
|
|
156
175
|
function pause() {
|
|
157
176
|
playing = false;
|
|
158
177
|
cancelAnimationFrame(raf);
|
|
159
|
-
draw();
|
|
178
|
+
if (!destroyed) draw();
|
|
160
179
|
}
|
|
161
180
|
playBtn?.addEventListener("click", () => (playing ? pause() : play()));
|
|
162
181
|
stage.addEventListener("keydown", (e) => {
|
|
163
182
|
const idx = stepIndexAt(scene, t);
|
|
164
|
-
if (e.key === "ArrowRight")
|
|
165
|
-
else if (e.key === "ArrowLeft")
|
|
166
|
-
else if (e.key === "Home")
|
|
167
|
-
else if (e.key === "End")
|
|
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);
|
|
168
187
|
else if (e.key === " " && !reduced) playing ? pause() : play();
|
|
169
188
|
else return;
|
|
170
189
|
e.preventDefault();
|
|
171
190
|
});
|
|
172
191
|
function seekStep(i) {
|
|
173
|
-
|
|
174
|
-
|
|
192
|
+
autoplayPending = false;
|
|
193
|
+
visibilityObserver?.disconnect();
|
|
194
|
+
seek(stepTime(i));
|
|
195
|
+
}
|
|
196
|
+
/** @param {number} i */
|
|
197
|
+
function stepTime(i) {
|
|
198
|
+
if (!Number.isInteger(i) || i < 0 || i >= scene.steps.length) throw new RangeError(`Invalid step index: ${i}`);
|
|
199
|
+
return scene.steps[i].at;
|
|
200
|
+
}
|
|
201
|
+
/** Play forward to an exact settled step; backward/reduced-motion calls jump. @param {number} i */
|
|
202
|
+
function playToStep(i) {
|
|
203
|
+
const target = stepTime(i);
|
|
204
|
+
autoplayPending = false;
|
|
205
|
+
visibilityObserver?.disconnect();
|
|
206
|
+
if (destroyed) return;
|
|
207
|
+
if (reduced || target <= t) seek(target);
|
|
208
|
+
else start(target);
|
|
209
|
+
}
|
|
210
|
+
function selectStep(i) {
|
|
211
|
+
options.animateSteps ? playToStep(i) : seekStep(i);
|
|
175
212
|
}
|
|
176
213
|
|
|
177
214
|
// Initial state: final frame (also what reduced motion and no-autoplay keep).
|
|
@@ -179,27 +216,38 @@ export function mountPlayer(container, scene, options = {}) {
|
|
|
179
216
|
const autoplay = options.autoplay ?? "visible";
|
|
180
217
|
if (!reduced && autoplay !== "none") {
|
|
181
218
|
if (autoplay === "visible" && typeof IntersectionObserver === "function") {
|
|
182
|
-
|
|
219
|
+
autoplayPending = true;
|
|
220
|
+
visibilityObserver = new IntersectionObserver(
|
|
183
221
|
(entries) => {
|
|
184
|
-
if (entries.some((e) => e.isIntersecting)) {
|
|
185
|
-
|
|
222
|
+
if (autoplayPending && entries.some((e) => e.isIntersecting)) {
|
|
223
|
+
autoplayPending = false;
|
|
224
|
+
visibilityObserver?.disconnect();
|
|
225
|
+
if (destroyed) return;
|
|
186
226
|
seek(0);
|
|
187
227
|
play();
|
|
188
228
|
}
|
|
189
229
|
},
|
|
190
230
|
{ threshold: 0.4 },
|
|
191
231
|
);
|
|
192
|
-
|
|
232
|
+
visibilityObserver.observe(container);
|
|
193
233
|
} else {
|
|
194
234
|
seek(0);
|
|
195
235
|
play();
|
|
196
236
|
}
|
|
197
237
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
}
|
|
238
|
+
const themeQuery = typeof matchMedia === "function" && !options.theme ? matchMedia("(prefers-color-scheme: dark)") : null;
|
|
239
|
+
themeQuery?.addEventListener?.("change", applyTheme);
|
|
201
240
|
|
|
202
|
-
|
|
241
|
+
function destroy() {
|
|
242
|
+
if (destroyed) return;
|
|
243
|
+
destroyed = true;
|
|
244
|
+
playing = false;
|
|
245
|
+
cancelAnimationFrame(raf);
|
|
246
|
+
visibilityObserver?.disconnect();
|
|
247
|
+
themeQuery?.removeEventListener?.("change", applyTheme);
|
|
248
|
+
if (g.__motionKit[id] === controller) delete g.__motionKit[id];
|
|
249
|
+
}
|
|
250
|
+
const controller = { seek, play, pause, seekStep, playToStep, destroy, get time() { return t; }, scene };
|
|
203
251
|
const g = globalThis;
|
|
204
252
|
g.__motionKit = g.__motionKit ?? {};
|
|
205
253
|
g.__motionKit[id] = controller;
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
- Starts on the **final frame** (also the no-JS / server-rendered fallback).
|
|
6
6
|
- Replays once when ~40 % visible, then holds.
|
|
7
|
-
- Controls: play/pause (always present, WCAG 2.2.2), one button per step (jumps
|
|
8
|
-
|
|
7
|
+
- Controls: play/pause (always present, WCAG 2.2.2), one button per step (jumps
|
|
8
|
+
by default), optional scrubber, caption with the active step's `detail`.
|
|
9
9
|
- Keyboard on the diagram: ← / → step, Home / End, Space play/pause.
|
|
10
10
|
- `prefers-reduced-motion`: final frame, no autoplay, no play button.
|
|
11
11
|
- `prefers-color-scheme`: light/dark tokens switch live.
|
|
@@ -14,6 +14,19 @@
|
|
|
14
14
|
- Capture hook: `window.__motionKit[id].seek(t)` (for Playwright/HyperFrames-
|
|
15
15
|
style renderers).
|
|
16
16
|
|
|
17
|
+
The controller's step indices are zero-based. `controller.seekStep(i)` jumps;
|
|
18
|
+
`controller.playToStep(i)` plays forward from the current time and stops at the
|
|
19
|
+
step's exact settled time. Backward and same-step calls jump, and reduced
|
|
20
|
+
motion always jumps. A new call replaces the previous target; `pause()` holds
|
|
21
|
+
the current frame, `seek(t)` cancels playback, and `play()` continues to the end.
|
|
22
|
+
Invalid indices throw `RangeError`.
|
|
23
|
+
|
|
24
|
+
Pass `{ animateSteps: true }` to `mountPlayer(container, scene, options)` to
|
|
25
|
+
enable this behavior for the step buttons and arrow/Home/End keys. The default
|
|
26
|
+
keeps instant navigation. Call `controller.destroy()` before removing or
|
|
27
|
+
replacing a player: it cancels playback, visibility observation, theme listening
|
|
28
|
+
and its capture-hook entry.
|
|
29
|
+
|
|
17
30
|
## Patterns worth adding per diagram (in the page around the player)
|
|
18
31
|
|
|
19
32
|
- **Hover/focus linking:** terms in the surrounding text highlight the matching
|
|
@@ -53,6 +53,17 @@ mk build spec.json -o out/page.html -f wide # Craft Page / standalone in
|
|
|
53
53
|
mk bake spec.json -o out/diagram.svg -f wide --fps 12 # zero-JS animated SVG
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
+
For plain HTML or a framework-independent live embed, use
|
|
57
|
+
`mk vendor public/motion-kit --adapter element`, then load
|
|
58
|
+
`./motion-kit/adapter/motion-diagram.mjs` with `type="module"` and place
|
|
59
|
+
`<motion-diagram src="./spec.json" format="wide">` around a final-frame SVG
|
|
60
|
+
or image fallback. Copy the spec to `public/spec.json` and serve over HTTP.
|
|
61
|
+
Inline JSON (`spec` attribute or child
|
|
62
|
+
`script[type="application/json"]`), `locale`, `theme` and JSON `style-spec`
|
|
63
|
+
are supported; the normal `style` attribute stays CSS. The element exposes
|
|
64
|
+
`controller` after `motion-ready`, preserves the fallback during loading or
|
|
65
|
+
errors, and cleans up on disconnect. Full usage: `adapters/element/README.md`.
|
|
66
|
+
|
|
56
67
|
## Delivery package
|
|
57
68
|
|
|
58
69
|
```
|