@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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "motion-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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,21 +89,88 @@ 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
|
-
Copies `runtime/`, the adapter, `lib/check.mjs
|
|
96
|
-
|
|
97
|
-
and re-vendor. Vendoring keeps
|
|
98
|
-
self-contained (no install step, no network)
|
|
95
|
+
Copies `runtime/`, the adapter, the gate (`lib/check.mjs`, `lib/gate.mjs`,
|
|
96
|
+
`lib/load.mjs`) and `LICENSE`; writes `check.mjs` and `MOTION_KIT_VERSION`.
|
|
97
|
+
Don't edit vendored files; change motion-kit and re-vendor. Vendoring keeps
|
|
98
|
+
consumer CI self-contained (no install step, no network): the vendored gate
|
|
99
|
+
runs the same checks as `motion-kit check`.
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
node src/motion-kit/check.mjs src/diagrams/*.json src/diagrams/*.scene.mjs \
|
|
103
|
+
--locale en --locale nl --style src/brand/motion-style.json --options src/diagrams/labels.mjs
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Astro
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
node cli/motion-kit.mjs vendor <site>/src/motion-kit --adapter astro
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
```astro
|
|
113
|
+
---
|
|
114
|
+
import AnimatedDiagram from "../motion-kit/adapter/AnimatedDiagram.astro";
|
|
115
|
+
import spec from "../diagrams/order-flow.json";
|
|
116
|
+
import brandStyle from "../brand/motion-style.json"; // token data, as `--style` reads it
|
|
117
|
+
import { dictionary } from "../i18n"; // your site's own text, keyed by locale
|
|
118
|
+
const lang = Astro.currentLocale ?? "en";
|
|
119
|
+
const t = dictionary[lang];
|
|
120
|
+
---
|
|
121
|
+
<AnimatedDiagram spec={spec} format="wide" locale="nl" class="hidden lg:block" />
|
|
122
|
+
<AnimatedDiagram spec={spec} format="tall" locale="nl" class="lg:hidden" />
|
|
123
|
+
|
|
124
|
+
<!-- A custom scene module, its text from the page's dictionary -->
|
|
125
|
+
<AnimatedDiagram module="/src/diagrams/flow.scene.mjs" options={{ labels: t.flow }}
|
|
126
|
+
format="wide" locale={lang} theme="light" style={brandStyle} id="flow" />
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
The server render is the player's first state: the final frame, the step list
|
|
130
|
+
and the style's colours, with the controls in place, so the diagram is complete
|
|
131
|
+
without JavaScript and mounting causes no layout shift. `theme` fixes light or
|
|
132
|
+
dark; `style` is token data. Page scripts reach a player through its root
|
|
133
|
+
element's `controller` (set on mount; `motion-ready` announces it), and can
|
|
134
|
+
address steps by id (`controller.playToStep("payment")`). All props are listed in the adapter's
|
|
135
|
+
header comment.
|
|
136
|
+
|
|
137
|
+
### Plain HTML and framework-independent custom element
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
node cli/motion-kit.mjs vendor public/motion-kit --adapter element
|
|
141
|
+
cp diagram.json public/diagram.json
|
|
142
|
+
cp diagram-final.svg public/diagram-final.svg # the final-frame fallback image
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
```html
|
|
146
|
+
<motion-diagram src="./diagram.json" format="wide" locale="en">
|
|
147
|
+
<img src="./diagram-final.svg" alt="The complete diagram and its explanation">
|
|
148
|
+
</motion-diagram>
|
|
149
|
+
<script type="module" src="./motion-kit/adapter/motion-diagram.mjs"></script>
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Serve the files over HTTP; no build step is needed. The supplied final-frame
|
|
153
|
+
fallback stays visible without JavaScript, while loading and on errors. Specs
|
|
154
|
+
can also be inline JSON. `theme` and JSON `style-spec` attributes configure
|
|
155
|
+
the appearance, and `element.controller` exposes the live player after the
|
|
156
|
+
`motion-ready` event. See [the element adapter](adapters/element/README.md)
|
|
157
|
+
for inline specs, styles, lifecycle and error handling.
|
|
99
158
|
|
|
100
159
|
## Rules (the gate enforces them)
|
|
101
160
|
|
|
102
161
|
Deterministic bytes · settled step frames · rounded numbers · token-only colours ·
|
|
103
162
|
escaped labels · labels fit their budget in every locale · holds the final frame ·
|
|
104
|
-
≤ ~8–10 s · no clock or randomness in scenes. See
|
|
163
|
+
≤ ~8–10 s · no clock or randomness in scenes · ids from the instance prefix. See
|
|
105
164
|
`skills/animated-diagram/references/technique.md`.
|
|
106
165
|
|
|
166
|
+
## Contributing, changes and stability
|
|
167
|
+
|
|
168
|
+
- [CONTRIBUTING.md](CONTRIBUTING.md): setup, the gate and hooks, commits,
|
|
169
|
+
change notes, adding a scene type.
|
|
170
|
+
- [CHANGELOG.md](CHANGELOG.md): what each release changed.
|
|
171
|
+
- [docs/stability.md](docs/stability.md): the public API, what semver promises
|
|
172
|
+
for it, and how vendoring consumers learn about a new version.
|
|
173
|
+
|
|
107
174
|
## Licence and credits
|
|
108
175
|
|
|
109
176
|
MIT, see [LICENSE](LICENSE). Keep the copied `LICENSE` file and the SPDX
|
|
@@ -4,52 +4,178 @@
|
|
|
4
4
|
/**
|
|
5
5
|
* motion-kit · Astro adapter (reference).
|
|
6
6
|
*
|
|
7
|
-
* Server-renders the FINAL frame
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* Server-renders the player's first state: the FINAL frame, the step list and
|
|
8
|
+
* the style's colours, with the controls in place but inert. No-JS visitors,
|
|
9
|
+
* crawlers and reduced-motion users get the complete diagram, and mounting the
|
|
10
|
+
* live player moves nothing on the page. The player replays once when the
|
|
11
|
+
* diagram scrolls into view.
|
|
12
|
+
*
|
|
13
|
+
* A spec for a registered scene type:
|
|
10
14
|
*
|
|
11
15
|
* import AnimatedDiagram from "../motion-kit/adapter/AnimatedDiagram.astro";
|
|
12
16
|
* import spec from "../diagrams/order-flow.json";
|
|
13
17
|
* <AnimatedDiagram spec={spec} format="wide" locale="nl" class="hidden lg:block" />
|
|
14
18
|
* <AnimatedDiagram spec={spec} format="tall" locale="nl" class="lg:hidden" />
|
|
15
19
|
*
|
|
20
|
+
* A custom scene module, with options for its factory (text from the page's
|
|
21
|
+
* dictionary, a view). Modules live under src/ and end in .scene.mjs or
|
|
22
|
+
* .scene.js; name one by its path from the project root:
|
|
23
|
+
*
|
|
24
|
+
* <AnimatedDiagram module="/src/diagrams/flow.scene.mjs" options={{ labels: t.flow }}
|
|
25
|
+
* format="wide" locale={lang} theme="light" style={brand} id="flow" />
|
|
26
|
+
*
|
|
27
|
+
* Props:
|
|
28
|
+
* spec JSON spec for a registered scene type, or
|
|
29
|
+
* module path of a custom scene module, "/src/…/name.scene.mjs"
|
|
30
|
+
* options serializable options for the module's factory, passed unchanged
|
|
31
|
+
* (module only); the factory gets { ...options, format, locale, kit }
|
|
32
|
+
* format "16:9" | "4:3" | "1:1" | "9:16" | "wide" | "tall" (default "16:9")
|
|
33
|
+
* locale default "en"
|
|
34
|
+
* theme "light" | "dark"; default: follow prefers-color-scheme
|
|
35
|
+
* style token data (the shape `motion-kit --style` reads); default neutral
|
|
36
|
+
* id HTML id of the root element, capture-hook key and id prefix:
|
|
37
|
+
* letters, digits, "_" and "-", starting with a letter, used once
|
|
38
|
+
* per page; default: generated, unique on the page
|
|
39
|
+
* scrubber show a timeline scrubber (default false)
|
|
40
|
+
* labels UI strings: flat { play, pause, … } or keyed by locale
|
|
41
|
+
* class CSS classes for the root element
|
|
42
|
+
*
|
|
43
|
+
* Page scripts reach the live player through the root element: its
|
|
44
|
+
* `controller` property, set on mount, and the `motion-ready` event (bubbling,
|
|
45
|
+
* `detail.controller`), dispatched once the page's own scripts (and their
|
|
46
|
+
* DOMContentLoaded and astro:page-load handlers) have run; `motion-error`
|
|
47
|
+
* reports a failed mount. Use whichever comes first:
|
|
48
|
+
*
|
|
49
|
+
* const el = document.getElementById("flow");
|
|
50
|
+
* const go = (c) => c.playToStep("paid");
|
|
51
|
+
* el.controller ? go(el.controller) : el.addEventListener("motion-ready", (e) => go(e.detail.controller), { once: true });
|
|
52
|
+
*
|
|
16
53
|
* Mount a wide and a tall instance and switch with CSS: display:none also
|
|
17
|
-
* removes the hidden one from the accessibility tree and its
|
|
18
|
-
*
|
|
54
|
+
* removes the hidden one from the accessibility tree and stops its clock.
|
|
55
|
+
* Every prop must be serializable (a spec or a module path, not a scene).
|
|
19
56
|
*/
|
|
20
|
-
import {
|
|
57
|
+
import { sceneFromModule } from "../runtime/kit.mjs";
|
|
58
|
+
import { PLAYER_CSS, playerMarkup, themeCss } from "../runtime/player.mjs";
|
|
59
|
+
import { claimId, claimStylesheet, newPageState } from "../runtime/page.mjs";
|
|
21
60
|
import { createScene } from "../runtime/types/index.mjs";
|
|
22
61
|
|
|
23
62
|
interface Props {
|
|
24
|
-
spec
|
|
63
|
+
spec?: Record<string, unknown>;
|
|
64
|
+
module?: string;
|
|
65
|
+
options?: Record<string, unknown>;
|
|
25
66
|
format?: string;
|
|
26
67
|
locale?: string;
|
|
68
|
+
theme?: "light" | "dark";
|
|
69
|
+
/** Token data, `{ name?, font?, light?: {…}, dark?: {…} }`, or "neutral". */
|
|
70
|
+
style?: Record<string, unknown> | "neutral";
|
|
71
|
+
id?: string;
|
|
27
72
|
class?: string;
|
|
28
73
|
scrubber?: boolean;
|
|
29
|
-
|
|
74
|
+
/** Flat `{ play, pause, … }`, or a dictionary keyed by locale (`{ en: {…}, nl: {…} }`). */
|
|
75
|
+
labels?: Record<string, string | Record<string, string>>;
|
|
76
|
+
}
|
|
77
|
+
const { spec, module: modulePath, options, format = "16:9", locale = "en", theme, style, id: idProp, class: className, scrubber = false, labels } = Astro.props;
|
|
78
|
+
const fail = (message: string): never => {
|
|
79
|
+
throw new Error(`AnimatedDiagram: ${message}`);
|
|
80
|
+
};
|
|
81
|
+
if ((spec == null) === (modulePath == null)) fail('pass exactly one of spec (a JSON spec) or module (a path such as "/src/diagrams/flow.scene.mjs")');
|
|
82
|
+
if (spec && options) fail("options apply to custom scene modules; a spec takes none");
|
|
83
|
+
if (theme != null && theme !== "light" && theme !== "dark") fail(`theme must be "light" or "dark", got "${theme}"`);
|
|
84
|
+
if (typeof style === "string" && style !== "neutral") fail("style is token data (an object); use class for CSS");
|
|
85
|
+
|
|
86
|
+
const modules = import.meta.glob("/src/**/*.scene.{mjs,js}");
|
|
87
|
+
let scene;
|
|
88
|
+
if (spec) scene = createScene(spec, { format, locale });
|
|
89
|
+
else {
|
|
90
|
+
const load = modules[modulePath as string];
|
|
91
|
+
if (!load) fail(`no scene module at "${modulePath}". Modules live under src/ and end in .scene.mjs or .scene.js; found: ${Object.keys(modules).join(", ") || "none"}`);
|
|
92
|
+
const mod = (await load()) as { default: unknown };
|
|
93
|
+
scene = sceneFromModule(mod.default, { format, locale, options });
|
|
30
94
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
95
|
+
|
|
96
|
+
// Per page: the ids in use and whether the player stylesheet is out yet.
|
|
97
|
+
const page = ((Astro.locals as Record<string, any>).__motionKit ??= newPageState());
|
|
98
|
+
const id = (() => {
|
|
99
|
+
try {
|
|
100
|
+
return claimId(page, idProp, scene.id);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
return fail((error as Error).message);
|
|
103
|
+
}
|
|
104
|
+
})();
|
|
105
|
+
const css = claimStylesheet(page) ? `<style data-mk-player-css>${PLAYER_CSS}</style>` : "";
|
|
106
|
+
const tokens = `<style>${themeCss(`#${id}`, style, theme)}</style>`;
|
|
107
|
+
const markup = playerMarkup(scene, { id, style, theme, labels, locale, scrubber });
|
|
108
|
+
const config = JSON.stringify({ spec, module: modulePath, options, format, locale, theme, style, scrubber, labels });
|
|
34
109
|
---
|
|
35
110
|
|
|
36
|
-
<
|
|
37
|
-
|
|
38
|
-
data-mk-spec={JSON.stringify(spec)}
|
|
39
|
-
data-mk-opts={JSON.stringify({ format, locale, scrubber, labels })}
|
|
40
|
-
set:html={fallback}
|
|
41
|
-
/>
|
|
111
|
+
<Fragment set:html={css + tokens} />
|
|
112
|
+
<div id={id} class:list={["mk-astro", "mk-player", className]} data-mk-astro={config} set:html={markup} />
|
|
42
113
|
|
|
43
114
|
<script>
|
|
115
|
+
import { sceneFromModule } from "../runtime/kit.mjs";
|
|
44
116
|
import { mountPlayer } from "../runtime/player.mjs";
|
|
45
117
|
import { createScene } from "../runtime/types/index.mjs";
|
|
46
118
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
119
|
+
type Controller = ReturnType<typeof mountPlayer>;
|
|
120
|
+
type Root = HTMLElement & { controller?: Controller | null };
|
|
121
|
+
// The same modules the server render can name; each loads on demand.
|
|
122
|
+
const modules = import.meta.glob("/src/**/*.scene.{mjs,js}");
|
|
123
|
+
const mounted = new Set<Root>();
|
|
124
|
+
|
|
125
|
+
// Page scripts that come after this one must be able to listen: tell them
|
|
126
|
+
// once the document is parsed, in a task after the current one, so their
|
|
127
|
+
// DOMContentLoaded and astro:page-load handlers have run too.
|
|
128
|
+
const parsed = new Promise<void>((resolve) => {
|
|
129
|
+
const nav = performance.getEntriesByType?.("navigation")[0] as PerformanceNavigationTiming | undefined;
|
|
130
|
+
if (document.readyState === "complete" || (nav?.domContentLoadedEventStart ?? 0) > 0) return resolve();
|
|
131
|
+
document.addEventListener("DOMContentLoaded", () => resolve(), { once: true });
|
|
132
|
+
addEventListener("load", () => resolve(), { once: true });
|
|
133
|
+
});
|
|
134
|
+
function announce(el: Root, type: "motion-ready" | "motion-error", detail: object) {
|
|
135
|
+
void parsed.then(() =>
|
|
136
|
+
setTimeout(() => {
|
|
137
|
+
if (el.isConnected && mounted.has(el)) el.dispatchEvent(new CustomEvent(type, { bubbles: true, detail }));
|
|
138
|
+
}, 0),
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function mount(el: Root) {
|
|
143
|
+
mounted.add(el);
|
|
144
|
+
try {
|
|
145
|
+
const cfg = JSON.parse(el.dataset.mkAstro ?? "{}");
|
|
146
|
+
let scene;
|
|
147
|
+
if (cfg.spec) scene = createScene(cfg.spec, { format: cfg.format, locale: cfg.locale });
|
|
148
|
+
else {
|
|
149
|
+
const load = modules[cfg.module];
|
|
150
|
+
if (!load) throw new Error(`motion-kit: no scene module at "${cfg.module}"`);
|
|
151
|
+
const mod = (await load()) as { default: unknown };
|
|
152
|
+
// A page swap during the import released this element.
|
|
153
|
+
if (!mounted.has(el) || !el.isConnected) return;
|
|
154
|
+
scene = sceneFromModule(mod.default, { format: cfg.format, locale: cfg.locale, options: cfg.options });
|
|
155
|
+
}
|
|
156
|
+
const controller = mountPlayer(el, scene, { id: el.id, style: cfg.style, theme: cfg.theme, scrubber: cfg.scrubber, labels: cfg.labels, locale: cfg.locale });
|
|
157
|
+
el.controller = controller;
|
|
158
|
+
announce(el, "motion-ready", { controller });
|
|
159
|
+
} catch (error) {
|
|
160
|
+
// The server-rendered diagram stays as it is.
|
|
161
|
+
announce(el, "motion-error", { error });
|
|
162
|
+
console.error(error);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function mountAll() {
|
|
166
|
+
for (const el of document.querySelectorAll<Root>("[data-mk-astro]")) if (!mounted.has(el)) void mount(el);
|
|
54
167
|
}
|
|
168
|
+
function teardown() {
|
|
169
|
+
for (const el of mounted) {
|
|
170
|
+
el.controller?.destroy();
|
|
171
|
+
el.controller = null;
|
|
172
|
+
}
|
|
173
|
+
mounted.clear();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
mountAll();
|
|
177
|
+
// Astro view transitions swap the DOM without reloading the page: release
|
|
178
|
+
// the old players, then mount the new page's diagrams.
|
|
179
|
+
document.addEventListener("astro:before-swap", teardown);
|
|
180
|
+
document.addEventListener("astro:page-load", mountAll);
|
|
55
181
|
</script>
|
|
@@ -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), and `labels` (JSON UI strings: flat, or keyed by locale). 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,124 @@
|
|
|
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", "labels"];
|
|
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 locale = this.getAttribute("locale") ?? "en";
|
|
104
|
+
const scene = createScene(spec, { format: this.getAttribute("format") ?? "16:9", locale });
|
|
105
|
+
const style = JSON.parse(this.getAttribute("style-spec") ?? "null");
|
|
106
|
+
player = this.ownerDocument.createElement("div");
|
|
107
|
+
// Mount inside a child so player CSS cannot overwrite the host's CSS.
|
|
108
|
+
this.appendChild(player);
|
|
109
|
+
this.controller = mountPlayer(player, scene, { id: this._id, style, theme: theme || undefined, locale, labels: JSON.parse(this.getAttribute("labels") ?? "null") ?? undefined });
|
|
110
|
+
this._player = player;
|
|
111
|
+
this._fallback.hidden = true;
|
|
112
|
+
this.dispatchEvent(new CustomEvent("motion-ready", { detail: { controller: this.controller } }));
|
|
113
|
+
} catch (error) {
|
|
114
|
+
player?.remove();
|
|
115
|
+
if (this.isConnected && revision === this._revision) {
|
|
116
|
+
this.dispatchEvent(new CustomEvent("motion-error", { detail: { error } }));
|
|
117
|
+
}
|
|
118
|
+
} finally {
|
|
119
|
+
if (this._request === request) this._request = null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (!customElements.get("motion-diagram")) customElements.define("motion-diagram", MotionDiagram);
|
package/adapters/page/README.md
CHANGED
|
@@ -14,8 +14,9 @@ motion-kit build diagram.json --out diagram.html [--format wide] [--locale nl] [
|
|
|
14
14
|
`motion-kit bake` (zero-JS animated SVG) or step PNGs via `image-preview`.
|
|
15
15
|
- **Static hosting / file://:** works as is.
|
|
16
16
|
|
|
17
|
-
The
|
|
18
|
-
|
|
17
|
+
The player's first state (final frame, step list, colours) is pre-rendered
|
|
18
|
+
into the markup, so the diagram is complete before JS runs and nothing moves
|
|
19
|
+
when the player mounts. The player replays once on scroll-into-view, shows pause/play,
|
|
19
20
|
step buttons, a scrubber and captions, and respects `prefers-reduced-motion`
|
|
20
21
|
and `prefers-color-scheme`.
|
|
21
22
|
|
|
@@ -102,6 +102,12 @@ watch(stepIndex, (next, prev) => {
|
|
|
102
102
|
}
|
|
103
103
|
});
|
|
104
104
|
|
|
105
|
+
// A replaced scene keeps the same step index but may time that step differently.
|
|
106
|
+
watch(scene, (next) => {
|
|
107
|
+
cancelAnimationFrame(raf);
|
|
108
|
+
t.value = next.steps[Math.min(stepIndex.value, next.steps.length - 1)].at;
|
|
109
|
+
});
|
|
110
|
+
|
|
105
111
|
onMounted(() => {
|
|
106
112
|
if (info) clicks.register(id, info);
|
|
107
113
|
if (animated.value && props.intro && stepIndex.value === 0) animate(0, scene.value.steps[0].at);
|
|
@@ -111,6 +117,12 @@ onUnmounted(() => {
|
|
|
111
117
|
clicks?.unregister(id);
|
|
112
118
|
});
|
|
113
119
|
|
|
120
|
+
const announcement = computed(() => {
|
|
121
|
+
const steps = scene.value.steps;
|
|
122
|
+
const i = Math.min(stepIndex.value, steps.length - 1);
|
|
123
|
+
const s = steps[i];
|
|
124
|
+
return `${i + 1}. ${s.detail ? `${s.label}: ${s.detail}` : s.label}`;
|
|
125
|
+
});
|
|
114
126
|
const dark = computed(() => (props.theme ? props.theme === "dark" : isDark.value));
|
|
115
127
|
const markup = computed(() => renderSvg(scene.value, t.value, { style: style.value, live: true, idPrefix: id }));
|
|
116
128
|
const vars = computed(() => `${cssVars(style.value, dark.value ? "dark" : "light")};--mk-max-h:${props.maxHeight}`);
|
|
@@ -119,14 +131,26 @@ const vars = computed(() => `${cssVars(style.value, dark.value ? "dark" : "light
|
|
|
119
131
|
<template>
|
|
120
132
|
<figure class="mk-slidev" :style="vars" :data-mk-step="stepIndex + 1">
|
|
121
133
|
<div class="mk-slidev-stage" v-html="markup" />
|
|
134
|
+
<!-- Clicks advance steps; say which one, like the live player does. -->
|
|
135
|
+
<div class="mk-slidev-live" role="status" aria-live="polite" aria-atomic="true">{{ announcement }}</div>
|
|
122
136
|
</figure>
|
|
123
137
|
</template>
|
|
124
138
|
|
|
125
139
|
<style scoped>
|
|
126
140
|
.mk-slidev {
|
|
141
|
+
position: relative;
|
|
127
142
|
margin: 0;
|
|
128
143
|
width: 100%;
|
|
129
144
|
}
|
|
145
|
+
.mk-slidev-live {
|
|
146
|
+
position: absolute;
|
|
147
|
+
width: 1px;
|
|
148
|
+
height: 1px;
|
|
149
|
+
margin: -1px;
|
|
150
|
+
overflow: hidden;
|
|
151
|
+
clip: rect(0, 0, 0, 0);
|
|
152
|
+
white-space: nowrap;
|
|
153
|
+
}
|
|
130
154
|
.mk-slidev-stage :deep(svg) {
|
|
131
155
|
display: block;
|
|
132
156
|
width: 100%;
|