@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/lib/check.mjs
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* pass these before anything is exported or mounted.
|
|
6
6
|
*
|
|
7
7
|
* checkScene(scene) → { ok, problems: string[] }
|
|
8
|
+
*
|
|
9
|
+
* Over files, formats and locales (the CLI and the vendored gate): lib/gate.mjs.
|
|
8
10
|
*/
|
|
9
11
|
import { renderSvg } from "../runtime/scene.mjs";
|
|
10
12
|
|
|
@@ -46,8 +48,9 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
|
|
|
46
48
|
if (wf) problems.push(`malformed at t=${t.toFixed(3)}: ${wf}`);
|
|
47
49
|
const long = a.match(/-?\d+\.\d{5,}/);
|
|
48
50
|
if (long) problems.push(`unrounded number ${long[0]} at t=${t.toFixed(3)} (use num())`);
|
|
49
|
-
const frame = scene.frame(Math.min(t, scene.duration));
|
|
50
|
-
|
|
51
|
+
const frame = scene.frame(Math.min(t, scene.duration), { idPrefix: scene.id });
|
|
52
|
+
// References to ids (url(#x), href="#x") are not colours.
|
|
53
|
+
const lit = frame.replace(/url\(\s*#[^)]*\)|href="#[^"]*"/g, "").match(/#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(/);
|
|
51
54
|
if (lit) problems.push(`colour literal "${lit[0]}" at t=${t.toFixed(3)} (use tok())`);
|
|
52
55
|
if (/NaN|undefined|Infinity/.test(frame)) problems.push(`NaN/undefined/Infinity in frame at t=${t.toFixed(3)}`);
|
|
53
56
|
if (problems.length > 12) break;
|
|
@@ -82,5 +85,15 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
|
|
|
82
85
|
const src = scene.frame.toString();
|
|
83
86
|
if (/Date\.now|new Date|Math\.random|performance\.now/.test(src)) problems.push("frame() reads the clock or randomness");
|
|
84
87
|
|
|
88
|
+
// 7. Every id comes from the instance prefix, so two instances on a page
|
|
89
|
+
// never share one: render with two prefixes and look for common ids.
|
|
90
|
+
const fixed = new Set();
|
|
91
|
+
for (let i = 0; i <= samples; i += 10) {
|
|
92
|
+
const ids = (prefix) => new Set([...renderSvg(scene, at(i), { idPrefix: prefix }).matchAll(/\sid="([^"]*)"/g)].map((m) => m[1]));
|
|
93
|
+
const second = ids("mk-gate-b");
|
|
94
|
+
for (const id of ids("mk-gate-a")) if (second.has(id)) fixed.add(id);
|
|
95
|
+
}
|
|
96
|
+
for (const id of fixed) problems.push(`fixed id "${id}": build ids from frame(t, { idPrefix }), e.g. \`\${idPrefix}-${id}\``);
|
|
97
|
+
|
|
85
98
|
return { ok: problems.length === 0, problems };
|
|
86
99
|
}
|
package/lib/export.mjs
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* NN-<step>.svg standalone, tokens resolved (PowerPoint/Keynote take SVG)
|
|
6
6
|
* NN-<step>.png with --png (Google Slides, Marp/Slidev, travelling decks)
|
|
7
7
|
* qc/… with --qc: frames 0.2 s before and after every step
|
|
8
|
+
* qc/phone.svg the tall layout's final frame, for the phone row
|
|
8
9
|
* index.html contact sheet (steps, QC row, phone-size row)
|
|
9
10
|
* manifest.json reproducible: no timestamps; input hash + settings
|
|
10
11
|
*/
|
|
@@ -35,14 +36,19 @@ function gitCommit(cwd) {
|
|
|
35
36
|
|
|
36
37
|
/**
|
|
37
38
|
* @param {any} scene
|
|
38
|
-
* @param {{out: string, style?: import("../runtime/style.mjs").Style, theme?: string, png?: boolean, scale?: number, qc?: boolean, background?: boolean, sourceFile?: string, version?: string}} options
|
|
39
|
+
* @param {{out: string, style?: import("../runtime/style.mjs").Style, theme?: string, png?: boolean, scale?: number, qc?: boolean, background?: boolean, sourceFile?: string, version?: string, phone?: { scene?: any, error?: string }, format?: string, locale?: string, options?: Record<string, unknown>}} options
|
|
40
|
+
* phone: the same scene built for the `tall` format (what a phone shows), or
|
|
41
|
+
* why it could not be built; the contact sheet's phone row shows it.
|
|
42
|
+
* format, locale, options: what the scene was built with, for the manifest
|
|
43
|
+
* (a custom module's scene options change its frames, so they are hashed).
|
|
39
44
|
*/
|
|
40
|
-
export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version }) {
|
|
45
|
+
export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version, phone, format, locale, options }) {
|
|
41
46
|
mkdirSync(out, { recursive: true });
|
|
42
47
|
const opts = { standalone: true, style, theme, background };
|
|
43
48
|
const files = [];
|
|
44
|
-
|
|
45
|
-
|
|
49
|
+
let phoneError = phone?.error;
|
|
50
|
+
const write = async (name, t, kind, label, from = scene) => {
|
|
51
|
+
const svg = renderSvg(from, t, opts);
|
|
46
52
|
writeFileSync(join(out, `${name}.svg`), svg);
|
|
47
53
|
const entry = { kind, t: Math.round(t * 1000) / 1000, label, svg: `${name}.svg` };
|
|
48
54
|
if (png) {
|
|
@@ -63,9 +69,20 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
|
|
|
63
69
|
if (i < scene.steps.length - 1) await write(`qc/${n}-after`, s.at + 0.2, "after", s.label);
|
|
64
70
|
}
|
|
65
71
|
}
|
|
72
|
+
if (phone?.scene) {
|
|
73
|
+
mkdirSync(join(out, "qc"), { recursive: true });
|
|
74
|
+
const last = phone.scene.steps[phone.scene.steps.length - 1];
|
|
75
|
+
// loadScene never calls frame(), so a custom scene can still fail here.
|
|
76
|
+
try {
|
|
77
|
+
await write("qc/phone", phone.scene.duration, "phone", last.label, phone.scene);
|
|
78
|
+
} catch (e) {
|
|
79
|
+
phoneError = e instanceof Error ? e.message : String(e);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
66
82
|
const inputHash = createHash("sha256")
|
|
67
83
|
.update(sourceFile ? readFileSync(sourceFile) : scene.frame.toString())
|
|
68
84
|
.update(JSON.stringify(style ?? "neutral"))
|
|
85
|
+
.update(JSON.stringify(options ?? null))
|
|
69
86
|
.digest("hex")
|
|
70
87
|
.slice(0, 16);
|
|
71
88
|
const manifest = {
|
|
@@ -73,8 +90,9 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
|
|
|
73
90
|
version,
|
|
74
91
|
scene: scene.id,
|
|
75
92
|
type: scene.type ?? "custom",
|
|
76
|
-
format: scene.format ?? null,
|
|
77
|
-
locale: scene.locale ?? null,
|
|
93
|
+
format: scene.format ?? format ?? null,
|
|
94
|
+
locale: scene.locale ?? locale ?? null,
|
|
95
|
+
options: options ?? null,
|
|
78
96
|
width: scene.width,
|
|
79
97
|
height: scene.height,
|
|
80
98
|
duration: Math.round(scene.duration * 1000) / 1000,
|
|
@@ -86,25 +104,29 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
|
|
|
86
104
|
files,
|
|
87
105
|
};
|
|
88
106
|
writeFileSync(join(out, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
89
|
-
writeFileSync(join(out, "index.html"), contactSheet(scene, files, theme, style));
|
|
107
|
+
writeFileSync(join(out, "index.html"), contactSheet(scene, files, theme, style, phoneError));
|
|
90
108
|
return manifest;
|
|
91
109
|
}
|
|
92
110
|
|
|
93
|
-
function contactSheet(scene, files, theme, style) {
|
|
111
|
+
function contactSheet(scene, files, theme, style, phoneError) {
|
|
94
112
|
const bg = style?.[theme]?.bg ?? (theme === "dark" ? "#0f1115" : "#ffffff");
|
|
95
113
|
const card = (f) =>
|
|
96
114
|
`<figure><img src="${f.svg}" alt=""><figcaption>${f.kind} · ${f.t}s · ${escapeHtml(f.label)}</figcaption></figure>`;
|
|
97
115
|
const steps = files.filter((f) => f.kind === "step");
|
|
98
|
-
const qcs = files.filter((f) => f.kind
|
|
116
|
+
const qcs = files.filter((f) => f.kind === "before" || f.kind === "after");
|
|
117
|
+
const tall = files.find((f) => f.kind === "phone");
|
|
118
|
+
const phoneRow = tall
|
|
119
|
+
? `<div class="grid phone">${card(tall)}</div>`
|
|
120
|
+
: `<p>The tall layout could not be built${phoneError ? ` (${escapeHtml(phoneError)})` : ""}; this is the ${escapeHtml(scene.format ?? "exported")} frame at 360 px.</p><div class="grid phone">${steps.slice(-1).map(card).join("")}</div>`;
|
|
99
121
|
return `<!doctype html><meta charset="utf-8"><title>${escapeHtml(scene.title)} · contact sheet</title>
|
|
100
122
|
<style>body{font:14px system-ui;margin:24px;background:#e5e7eb}h2{margin:24px 0 8px}
|
|
101
123
|
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:12px}
|
|
102
124
|
figure{margin:0;background:${bg};padding:8px;border-radius:8px}img{width:100%;display:block}
|
|
103
|
-
figcaption{font-size:12px;color:#6b7280;margin-top:4px}.phone figure{width:360px}</style>
|
|
125
|
+
figcaption{font-size:12px;color:#6b7280;margin-top:4px}.phone figure{width:fit-content}.phone img{width:360px}</style>
|
|
104
126
|
<h1>${escapeHtml(scene.title)}</h1><p>${escapeHtml(scene.id)} · ${scene.width}×${scene.height} · ${scene.duration.toFixed(2)} s · ${theme}</p>
|
|
105
127
|
<h2>Steps (what a slide shows)</h2><div class="grid">${steps.map(card).join("")}</div>
|
|
106
128
|
${qcs.length ? `<h2>QC: 0.2 s before / after each step</h2><div class="grid">${qcs.map(card).join("")}</div>` : ""}
|
|
107
|
-
<h2>Phone size (360 px wide)</h2
|
|
129
|
+
<h2>Phone size (tall layout, 360 px wide)</h2>${phoneRow}
|
|
108
130
|
<h2>Review</h2><ol><li>Does the step sequence tell the story without narration?</li><li>Any overlapping text, half-drawn lines or stray dots?</li><li>Readable at phone size?</li><li>Only approved copy and claims? No invented numbers?</li><li>Human approval: ____________ (name, date)</li></ol>`;
|
|
109
131
|
}
|
|
110
132
|
|
package/lib/gate.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Ophir Radnitz
|
|
3
|
+
/**
|
|
4
|
+
* motion-kit · the gate over files: what `motion-kit check` and the vendored
|
|
5
|
+
* `check.mjs` both run, so the two cannot drift apart.
|
|
6
|
+
*
|
|
7
|
+
* checkFiles(files, { formats, locales, style, options }) → number of failures
|
|
8
|
+
*
|
|
9
|
+
* - The style must pass the contrast check (G12).
|
|
10
|
+
* - Every file × format (all of FORMATS unless given) × locale passes
|
|
11
|
+
* checkScene. Locales: the given ones; else, for a spec, every locale its
|
|
12
|
+
* strings carry, and `en` for a module.
|
|
13
|
+
* - A file that cannot be read, parsed or built is a failure for that file
|
|
14
|
+
* only; the remaining files are still checked.
|
|
15
|
+
*/
|
|
16
|
+
import { readFileSync } from "node:fs";
|
|
17
|
+
import { FORMATS } from "../runtime/scene.mjs";
|
|
18
|
+
import { checkContrast } from "../runtime/style.mjs";
|
|
19
|
+
import { checkScene } from "./check.mjs";
|
|
20
|
+
import { isModule, loadScene } from "./load.mjs";
|
|
21
|
+
|
|
22
|
+
/** @param {unknown} e */
|
|
23
|
+
const message = (e) => (e instanceof Error ? e.message : String(e));
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Locales a spec's strings carry: every key of an object whose keys are all
|
|
27
|
+
* locale tags (`en`, `nl`, `pt-BR`) with string values. `["en"]` if none.
|
|
28
|
+
* @param {unknown} spec
|
|
29
|
+
* @returns {string[]}
|
|
30
|
+
*/
|
|
31
|
+
export function detectLocales(spec) {
|
|
32
|
+
const found = new Set();
|
|
33
|
+
/** @param {unknown} v */
|
|
34
|
+
const walk = (v) => {
|
|
35
|
+
if (Array.isArray(v)) v.forEach(walk);
|
|
36
|
+
else if (v && typeof v === "object") {
|
|
37
|
+
const entries = Object.entries(v);
|
|
38
|
+
if (entries.length && entries.every(([k, x]) => /^[a-z]{2}(-[A-Z]{2})?$/.test(k) && typeof x === "string")) entries.forEach(([k]) => found.add(k));
|
|
39
|
+
else entries.forEach(([, x]) => walk(x));
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
walk(spec);
|
|
43
|
+
return found.size ? [...found] : ["en"];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string[]} files specs (.json) and custom modules (.mjs)
|
|
48
|
+
* @param {{ formats?: string[], locales?: string[], style?: any, options?: import("./load.mjs").OptionsSource, log?: (line: string) => void, error?: (line: string) => void }} [o]
|
|
49
|
+
* @returns {Promise<number>} failures (0 = the gate passes)
|
|
50
|
+
*/
|
|
51
|
+
export async function checkFiles(files, { formats, locales, style, options, log = console.log, error = console.error } = {}) {
|
|
52
|
+
let bad = 0;
|
|
53
|
+
for (const p of checkContrast(style)) {
|
|
54
|
+
bad++;
|
|
55
|
+
error(`✗ style: ${p}`);
|
|
56
|
+
}
|
|
57
|
+
for (const file of files) {
|
|
58
|
+
const module = isModule(file);
|
|
59
|
+
let fileLocales = locales?.length ? locales : ["en"];
|
|
60
|
+
if (!locales?.length && !module) {
|
|
61
|
+
try {
|
|
62
|
+
fileLocales = detectLocales(JSON.parse(readFileSync(file, "utf8")));
|
|
63
|
+
} catch (e) {
|
|
64
|
+
bad++;
|
|
65
|
+
error(`✗ ${file}: ${message(e)}`);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
for (const format of formats?.length ? formats : Object.keys(FORMATS)) {
|
|
70
|
+
for (const locale of fileLocales) {
|
|
71
|
+
try {
|
|
72
|
+
const sceneOptions = module && options ? await options({ format, locale }) : undefined;
|
|
73
|
+
const { scene } = await loadScene(file, { format, locale, options: sceneOptions });
|
|
74
|
+
const r = checkScene(scene);
|
|
75
|
+
if (r.ok) log(`✓ ${file} · ${format} · ${locale} · ${scene.duration.toFixed(2)} s · ${scene.steps.length} steps`);
|
|
76
|
+
else {
|
|
77
|
+
bad++;
|
|
78
|
+
error(`✗ ${file} · ${format} · ${locale}\n - ${r.problems.join("\n - ")}`);
|
|
79
|
+
}
|
|
80
|
+
} catch (e) {
|
|
81
|
+
bad++;
|
|
82
|
+
error(`✗ ${file} · ${format} · ${locale}: ${message(e)}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return bad;
|
|
88
|
+
}
|
package/lib/load.mjs
CHANGED
|
@@ -1,53 +1,83 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Ophir Radnitz
|
|
1
3
|
/**
|
|
2
4
|
* motion-kit · load a scene from a spec (.json) or a custom module (.mjs).
|
|
3
5
|
*
|
|
4
6
|
* Custom modules: `export default (opts) => scene` with
|
|
5
|
-
* opts = { format, locale, kit }. `
|
|
6
|
-
*
|
|
7
|
-
*
|
|
7
|
+
* opts = { ...options, format, locale, kit } (runtime/kit.mjs). `options` are
|
|
8
|
+
* the caller's scene options (`--options`), passed unchanged; `kit` is the
|
|
9
|
+
* whole runtime in one flat namespace, so a scene that lives in another
|
|
10
|
+
* repository (a project logo) needs no imports at all:
|
|
8
11
|
*
|
|
9
|
-
* export default ({ kit }) => { const { tok, el, num } = kit; … }
|
|
12
|
+
* export default ({ kit, labels }) => { const { tok, el, num } = kit; … }
|
|
10
13
|
*
|
|
11
14
|
* Scenes inside this repo (or a vendored copy) may import the runtime with
|
|
12
|
-
* relative paths instead
|
|
15
|
+
* relative paths instead.
|
|
13
16
|
*/
|
|
14
17
|
import { readFileSync } from "node:fs";
|
|
15
18
|
import { resolve } from "node:path";
|
|
16
19
|
import { pathToFileURL } from "node:url";
|
|
17
|
-
import {
|
|
20
|
+
import { KIT, sceneFromModule } from "../runtime/kit.mjs";
|
|
18
21
|
import { normalizeStyle } from "../runtime/style.mjs";
|
|
19
22
|
import { createScene } from "../runtime/types/index.mjs";
|
|
20
|
-
import * as motion from "../runtime/motion.mjs";
|
|
21
|
-
import * as scene from "../runtime/scene.mjs";
|
|
22
|
-
import * as style from "../runtime/style.mjs";
|
|
23
|
-
import * as svg from "../runtime/svg.mjs";
|
|
24
|
-
import * as wrap from "../runtime/wrap.mjs";
|
|
25
23
|
|
|
26
|
-
|
|
27
|
-
export const KIT = Object.freeze({ ...motion, ...svg, ...style, ...scene, ...wrap });
|
|
24
|
+
export { KIT };
|
|
28
25
|
|
|
29
26
|
/**
|
|
30
27
|
* @typedef {{scene: any, spec?: any, kind: "spec" | "module", file: string}} LoadedScene
|
|
31
28
|
*/
|
|
29
|
+
/**
|
|
30
|
+
* Scene options for one format and locale (see loadOptions).
|
|
31
|
+
* @typedef {(ctx: { format: string, locale: string }) => Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined>} OptionsSource
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/** True for a file the CLI treats as a custom scene module rather than a spec. */
|
|
35
|
+
export function isModule(file) {
|
|
36
|
+
return !file.endsWith(".json");
|
|
37
|
+
}
|
|
32
38
|
|
|
33
39
|
/**
|
|
34
40
|
* @param {string} file path to a .json spec or an .mjs module
|
|
35
|
-
* @param {{format?: string, locale?: string}} [opts]
|
|
41
|
+
* @param {{format?: string, locale?: string, options?: Record<string, unknown>}} [opts]
|
|
42
|
+
* `options` reach a module's factory unchanged; a spec takes none.
|
|
36
43
|
* @returns {Promise<LoadedScene>}
|
|
37
44
|
*/
|
|
38
45
|
export async function loadScene(file, opts = {}) {
|
|
39
46
|
const abs = resolve(file);
|
|
40
|
-
|
|
47
|
+
const { options, ...where } = opts;
|
|
48
|
+
if (!isModule(abs)) {
|
|
49
|
+
if (options != null) throw new Error(`${file}: scene options apply to custom scene modules, not to specs`);
|
|
41
50
|
const spec = JSON.parse(readFileSync(abs, "utf8"));
|
|
42
|
-
return { scene: createScene(spec,
|
|
51
|
+
return { scene: createScene(spec, where), spec, kind: "spec", file: abs };
|
|
43
52
|
}
|
|
44
53
|
const mod = await import(pathToFileURL(abs).href);
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
return { scene: validateScene(make({ ...opts, kit: KIT })), kind: "module", file: abs };
|
|
54
|
+
if (typeof mod.default !== "function") throw new Error(`${file}: default export must be (opts) => scene`);
|
|
55
|
+
return { scene: sceneFromModule(mod.default, { ...where, options }), kind: "module", file: abs };
|
|
48
56
|
}
|
|
49
57
|
|
|
50
58
|
export function loadStyle(arg) {
|
|
51
59
|
if (!arg || arg === "neutral") return normalizeStyle("neutral");
|
|
52
60
|
return normalizeStyle(JSON.parse(readFileSync(resolve(arg), "utf8")));
|
|
53
61
|
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Scene options from `--options`: inline JSON (`{"view":"short"}`), a .json
|
|
65
|
+
* file, or a module whose default export is the options or
|
|
66
|
+
* `({ format, locale }) => options` (to pick a locale's dictionary).
|
|
67
|
+
* @param {string | undefined} arg
|
|
68
|
+
* @returns {Promise<OptionsSource | undefined>}
|
|
69
|
+
*/
|
|
70
|
+
export async function loadOptions(arg) {
|
|
71
|
+
if (arg == null) return undefined;
|
|
72
|
+
/** @param {unknown} v */
|
|
73
|
+
const fixed = (v) => {
|
|
74
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error(`--options ${arg}: scene options must be a JSON object`);
|
|
75
|
+
return () => /** @type {Record<string, unknown>} */ (v);
|
|
76
|
+
};
|
|
77
|
+
if (arg.trim().startsWith("{")) return fixed(JSON.parse(arg));
|
|
78
|
+
const abs = resolve(arg);
|
|
79
|
+
if (abs.endsWith(".json")) return fixed(JSON.parse(readFileSync(abs, "utf8")));
|
|
80
|
+
const mod = await import(pathToFileURL(abs).href);
|
|
81
|
+
if (typeof mod.default === "function") return (ctx) => mod.default(ctx);
|
|
82
|
+
return fixed(mod.default);
|
|
83
|
+
}
|
package/package.json
CHANGED
package/runtime/bake.mjs
CHANGED
|
@@ -16,22 +16,36 @@
|
|
|
16
16
|
import { renderSvg } from "./scene.mjs";
|
|
17
17
|
import { num } from "./svg.mjs";
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* @param {import("./scene.mjs").Scene} scene
|
|
21
|
+
* @param {{ fps?: number, delay?: number, idPrefix?: string, style?: any, theme?: string, background?: boolean }} [options]
|
|
22
|
+
* idPrefix: prefix for the file's ids (default "mk-bake"); give each baked
|
|
23
|
+
* SVG inlined into one page its own.
|
|
24
|
+
* @returns {string}
|
|
25
|
+
*/
|
|
19
26
|
export function bake(scene, options = {}) {
|
|
20
27
|
const fps = options.fps ?? 15;
|
|
21
28
|
const delay = options.delay ?? 0.3;
|
|
29
|
+
const base = options.idPrefix ?? "mk-bake";
|
|
22
30
|
const total = Math.ceil(scene.duration * fps);
|
|
31
|
+
/** @param {number} t @param {string} idPrefix */
|
|
32
|
+
const render = (t, idPrefix) => renderSvg(scene, t, { ...options, standalone: true, idPrefix });
|
|
23
33
|
const frames = [];
|
|
24
34
|
for (let f = 0; f <= total; f++) {
|
|
25
35
|
const t = Math.min(f / fps, scene.duration);
|
|
26
|
-
const inner = innerOf(
|
|
36
|
+
const inner = innerOf(render(t, base));
|
|
27
37
|
const last = frames[frames.length - 1];
|
|
28
38
|
if (last && last.body === inner) last.end = t;
|
|
29
39
|
else frames.push({ start: t, end: t, body: inner });
|
|
30
40
|
}
|
|
31
|
-
// Each slice lasts until the next one starts.
|
|
32
|
-
|
|
41
|
+
// Each slice lasts until the next one starts. Slices sit in one document,
|
|
42
|
+
// so a scene that defines ids gets a prefix per slice.
|
|
43
|
+
for (let i = 0; i < frames.length; i++) {
|
|
44
|
+
if (i < frames.length - 1) frames[i].end = frames[i + 1].start;
|
|
45
|
+
if (/\sid="/.test(frames[i].body)) frames[i].body = innerOf(render(frames[i].start, `${base}-${i + 1}`));
|
|
46
|
+
}
|
|
33
47
|
|
|
34
|
-
const full =
|
|
48
|
+
const full = render(scene.duration, base);
|
|
35
49
|
const open = full.slice(0, full.indexOf(">") + 1);
|
|
36
50
|
const head = full.slice(open.length, full.indexOf("</desc>") + "</desc>".length);
|
|
37
51
|
const css = [
|
package/runtime/kit.mjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Ophir Radnitz
|
|
3
|
+
/**
|
|
4
|
+
* motion-kit · custom scene modules.
|
|
5
|
+
*
|
|
6
|
+
* A custom scene module's default export is a factory, `(opts) => scene`, for
|
|
7
|
+
* diagrams no scene type draws. It is called with
|
|
8
|
+
*
|
|
9
|
+
* opts = { ...options, format, locale, kit }
|
|
10
|
+
*
|
|
11
|
+
* - `options`: the caller's serializable scene options, unchanged (text from a
|
|
12
|
+
* site's dictionary, a view to draw). Keys `format`, `locale` and `kit` are
|
|
13
|
+
* reserved.
|
|
14
|
+
* - `format`, `locale`: what to build (see FORMATS).
|
|
15
|
+
* - `kit`: the whole runtime in one flat namespace, so a scene kept in another
|
|
16
|
+
* repository needs no imports: `const { tok, el, num } = kit`.
|
|
17
|
+
*
|
|
18
|
+
* The CLI and the vendored gate (lib/load.mjs) and the Astro adapter, on the
|
|
19
|
+
* server and in the browser, go through sceneFromModule, so one module, given
|
|
20
|
+
* the same options, format and locale, draws the same scene everywhere. A page
|
|
21
|
+
* from `motion-kit build` calls the factory the same way, with the bundled
|
|
22
|
+
* runtime as `kit`, after the CLI built it here once.
|
|
23
|
+
*/
|
|
24
|
+
import { ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 } from "./motion.mjs";
|
|
25
|
+
import { FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId } from "./scene.mjs";
|
|
26
|
+
import { NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok } from "./style.mjs";
|
|
27
|
+
import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment } from "./svg.mjs";
|
|
28
|
+
import { estimateWidth, wrapLabel } from "./wrap.mjs";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The runtime, flat, handed to custom scene modules as `opts.kit`: the exports
|
|
32
|
+
* of motion, scene, style, svg and wrap (not the scene types or the player).
|
|
33
|
+
* Named imports, because lib/bundle.mjs inlines only that form; a new export
|
|
34
|
+
* in one of those modules is added here (test/runtime.test.mjs checks).
|
|
35
|
+
*/
|
|
36
|
+
export const KIT = Object.freeze({
|
|
37
|
+
...{ ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
|
|
38
|
+
...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
|
|
39
|
+
...{ NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
|
|
40
|
+
...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment },
|
|
41
|
+
...{ estimateWidth, wrapLabel },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const RESERVED = ["format", "locale", "kit"];
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Build and validate a scene from a module's default export.
|
|
48
|
+
* @param {unknown} make the module's default export
|
|
49
|
+
* @param {{ format?: string, locale?: string, options?: Record<string, unknown> | null }} [opts]
|
|
50
|
+
* @returns {import("./scene.mjs").Scene}
|
|
51
|
+
*/
|
|
52
|
+
export function sceneFromModule(make, { format = "16:9", locale = "en", options } = {}) {
|
|
53
|
+
if (typeof make !== "function") throw new TypeError("a scene module's default export must be (opts) => scene");
|
|
54
|
+
if (options != null && (typeof options !== "object" || Array.isArray(options))) throw new TypeError("scene options must be a plain object");
|
|
55
|
+
for (const key of RESERVED) {
|
|
56
|
+
if (options && Object.hasOwn(options, key)) throw new Error(`scene options must not set "${key}": it is passed separately`);
|
|
57
|
+
}
|
|
58
|
+
return validateScene(make({ ...options, format, locale, kit: KIT }));
|
|
59
|
+
}
|
package/runtime/page.mjs
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Ophir Radnitz
|
|
3
|
+
/**
|
|
4
|
+
* motion-kit · per-page bookkeeping for server-rendering adapters.
|
|
5
|
+
*
|
|
6
|
+
* DOM-free decisions an adapter shares: which id an instance gets, and whether
|
|
7
|
+
* the player stylesheet is out yet. The adapter owns where the page state lives
|
|
8
|
+
* (Astro: `Astro.locals`) and what it does with the answer.
|
|
9
|
+
*/
|
|
10
|
+
import { safeId } from "./scene.mjs";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {{ count: number, ids: Set<string>, css: boolean }} PageState
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** @returns {PageState} */
|
|
17
|
+
export function newPageState() {
|
|
18
|
+
return { count: 0, ids: new Set(), css: false };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Take an id for one instance on the page: the requested one, validated, or a
|
|
23
|
+
* generated one from the scene id and the page's counter. Throws on a malformed
|
|
24
|
+
* or already used id.
|
|
25
|
+
* @param {PageState} page
|
|
26
|
+
* @param {string | undefined | null} requested
|
|
27
|
+
* @param {string} sceneId
|
|
28
|
+
* @returns {string}
|
|
29
|
+
*/
|
|
30
|
+
export function claimId(page, requested, sceneId) {
|
|
31
|
+
if (requested != null && safeId(requested) !== requested) throw new Error(`id "${requested}" must be letters, digits, "_" and "-", starting with a letter`);
|
|
32
|
+
let id = requested;
|
|
33
|
+
if (id == null) {
|
|
34
|
+
// Skip ids an explicit request already took.
|
|
35
|
+
do id = safeId(`mk-${sceneId}-${++page.count}`);
|
|
36
|
+
while (page.ids.has(id));
|
|
37
|
+
}
|
|
38
|
+
if (page.ids.has(id)) throw new Error(`id "${id}" is already used on this page; give each instance (the wide and the tall one too) its own`);
|
|
39
|
+
page.ids.add(id);
|
|
40
|
+
return id;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* True once per page: the first caller emits the player stylesheet.
|
|
45
|
+
* @param {PageState} page
|
|
46
|
+
* @returns {boolean}
|
|
47
|
+
*/
|
|
48
|
+
export function claimStylesheet(page) {
|
|
49
|
+
if (page.css) return false;
|
|
50
|
+
page.css = true;
|
|
51
|
+
return true;
|
|
52
|
+
}
|