@liqweed/motion-kit 0.4.0 → 0.6.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 +26 -6
- package/adapters/element/README.md +5 -0
- package/adapters/page/README.md +10 -0
- package/cli/motion-kit.mjs +14 -4
- package/docs/spec/technique.md +129 -51
- package/examples/checkout.json +104 -0
- package/examples/connection.json +80 -0
- package/examples/custom-pulse.scene.mjs +5 -0
- package/examples/incident.json +18 -0
- package/examples/player-states.json +97 -0
- package/examples/web-stack.json +17 -0
- package/lib/build.mjs +1 -1
- package/lib/check.mjs +215 -21
- package/lib/export.mjs +116 -7
- package/lib/gate.mjs +9 -7
- package/lib/load.mjs +15 -0
- package/package.json +6 -3
- package/runtime/kit.mjs +2 -2
- package/runtime/links.mjs +318 -0
- package/runtime/parts.mjs +15 -0
- package/runtime/patch.mjs +297 -0
- package/runtime/player.mjs +45 -2
- package/runtime/scene.mjs +24 -9
- package/runtime/style.mjs +65 -16
- package/runtime/types/hub-spoke.mjs +10 -8
- package/runtime/types/index.mjs +7 -0
- package/runtime/types/sequence.mjs +10 -8
- package/runtime/types/stack.mjs +230 -0
- package/runtime/types/timeline.mjs +407 -0
- package/runtime/types/walk.mjs +162 -0
- package/skills/animated-diagram/SKILL.md +28 -7
- package/skills/animated-diagram/references/custom-scenes.md +20 -1
- package/skills/animated-diagram/references/interactivity.md +129 -6
- package/skills/animated-diagram/references/motion-vocabulary.md +1 -1
- package/skills/animated-diagram/references/qc.md +3 -0
- package/skills/animated-diagram/references/scene-types.md +100 -4
- package/skills/animated-diagram/references/styles.md +55 -6
- package/skills/animated-diagram/references/technique.md +15 -6
- package/skills/motion-render/SKILL.md +31 -6
- package/skills/motion-render/references/formats.md +8 -8
- package/skills/motion-render/references/video.md +1 -1
- package/skills/project-logo/SKILL.md +15 -4
- package/styles/neutral.json +2 -2
package/lib/export.mjs
CHANGED
|
@@ -8,11 +8,19 @@
|
|
|
8
8
|
* qc/phone.svg the tall layout's final frame, for the phone row
|
|
9
9
|
* index.html contact sheet (steps, QC row, phone-size row)
|
|
10
10
|
* manifest.json reproducible: no timestamps; input hash + settings
|
|
11
|
+
*
|
|
12
|
+
* Re-exporting into the same folder replaces the previous export: the files
|
|
13
|
+
* the previous manifest.json listed and the new one does not are removed, so
|
|
14
|
+
* the folder holds what the new manifest lists. Files no manifest listed
|
|
15
|
+
* (someone else put them there) are left in place and the export warns about
|
|
16
|
+
* them, unless the new export writes a file of the same name: that one is
|
|
17
|
+
* overwritten.
|
|
11
18
|
*/
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
12
20
|
import { createHash } from "node:crypto";
|
|
13
21
|
import { execFileSync } from "node:child_process";
|
|
14
|
-
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
15
|
-
import { join } from "node:path";
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
|
|
23
|
+
import { basename, dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
|
|
16
24
|
import { renderSvg } from "../runtime/scene.mjs";
|
|
17
25
|
import { svgToPng } from "./raster.mjs";
|
|
18
26
|
|
|
@@ -26,24 +34,86 @@ export function slug(s) {
|
|
|
26
34
|
.slice(0, 40);
|
|
27
35
|
}
|
|
28
36
|
|
|
29
|
-
|
|
37
|
+
/**
|
|
38
|
+
* @param {string[]} args
|
|
39
|
+
* @param {string} cwd
|
|
40
|
+
* @returns {string | null} git's output; null outside a repository or without git
|
|
41
|
+
*/
|
|
42
|
+
function git(args, cwd) {
|
|
43
|
+
// The repository is the one holding `cwd`, not one named by the caller's
|
|
44
|
+
// environment: inside a git hook GIT_DIR and friends point at the hook's
|
|
45
|
+
// repository, which would answer for a source file outside it.
|
|
46
|
+
const env = { ...process.env };
|
|
47
|
+
for (const k of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY"]) delete env[k];
|
|
30
48
|
try {
|
|
31
|
-
return execFileSync("git",
|
|
49
|
+
return execFileSync("git", args, { cwd, env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
32
50
|
} catch {
|
|
33
51
|
return null;
|
|
34
52
|
}
|
|
35
53
|
}
|
|
36
54
|
|
|
55
|
+
/**
|
|
56
|
+
* Where a source file stands in git: the short HEAD commit of the repository
|
|
57
|
+
* holding it, and whether the file differs from that commit (modified,
|
|
58
|
+
* staged, untracked or ignored: `git status --porcelain -- <file>` is not empty).
|
|
59
|
+
* Both null outside a git repository. Only the source file counts: modules a
|
|
60
|
+
* custom scene imports, the style file and the options file are not looked
|
|
61
|
+
* at (the input hash covers the style and the options).
|
|
62
|
+
* @param {string} file absolute path
|
|
63
|
+
* @returns {{ commit: string | null, dirty: boolean | null }}
|
|
64
|
+
*/
|
|
65
|
+
export function sourceState(file) {
|
|
66
|
+
const cwd = dirname(file);
|
|
67
|
+
const commit = git(["rev-parse", "--short", "HEAD"], cwd)?.trim() || null;
|
|
68
|
+
if (!commit) return { commit: null, dirty: null };
|
|
69
|
+
const status = git(["status", "--porcelain", "--untracked-files=all", "--ignored", "--", basename(file)], cwd);
|
|
70
|
+
return { commit, dirty: status == null ? null : status.trim() !== "" };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The files the manifest.json already in `out` lists, relative to `out`:
|
|
75
|
+
* what the previous export there wrote. Empty when there is none, or it is
|
|
76
|
+
* not motion-kit's or cannot be read. Entries that would leave `out` are
|
|
77
|
+
* ignored.
|
|
78
|
+
* @param {string} out
|
|
79
|
+
* @returns {string[]}
|
|
80
|
+
*/
|
|
81
|
+
function previousFiles(out) {
|
|
82
|
+
let manifest;
|
|
83
|
+
try {
|
|
84
|
+
manifest = JSON.parse(readFileSync(join(out, "manifest.json"), "utf8"));
|
|
85
|
+
} catch {
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
if (manifest?.tool !== "motion-kit" || !Array.isArray(manifest.files)) return [];
|
|
89
|
+
/** @type {unknown[]} */
|
|
90
|
+
const listed = manifest.files.flatMap((/** @type {any} */ f) => [f?.svg, f?.png]);
|
|
91
|
+
return listed.filter((p) => typeof p === "string" && p !== "" && !isAbsolute(p) && !normalize(p).split(sep).includes("..")).map(String);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* @param {string} dir
|
|
96
|
+
* @returns {string[]} every file under `dir`, relative to it, "/"-separated
|
|
97
|
+
*/
|
|
98
|
+
function listFiles(dir) {
|
|
99
|
+
return readdirSync(dir, { recursive: true, withFileTypes: true })
|
|
100
|
+
.filter((d) => d.isFile())
|
|
101
|
+
.map((d) => relative(dir, join(d.parentPath, d.name)).split(sep).join("/"))
|
|
102
|
+
.sort();
|
|
103
|
+
}
|
|
104
|
+
|
|
37
105
|
/**
|
|
38
106
|
* @param {any} scene
|
|
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
|
|
107
|
+
* @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>, warn?: (line: string) => void}} options
|
|
40
108
|
* phone: the same scene built for the `tall` format (what a phone shows), or
|
|
41
109
|
* why it could not be built; the contact sheet's phone row shows it.
|
|
42
110
|
* format, locale, options: what the scene was built with, for the manifest
|
|
43
111
|
* (a custom module's scene options change its frames, so they are hashed).
|
|
112
|
+
* warn: told about files in `out` that no export wrote (default console.warn).
|
|
44
113
|
*/
|
|
45
|
-
export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version, phone, format, locale, options }) {
|
|
114
|
+
export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version, phone, format, locale, options, warn = (line) => console.warn(line) }) {
|
|
46
115
|
mkdirSync(out, { recursive: true });
|
|
116
|
+
const previous = previousFiles(out);
|
|
47
117
|
const opts = { standalone: true, style, theme, background };
|
|
48
118
|
const files = [];
|
|
49
119
|
let phoneError = phone?.error;
|
|
@@ -79,12 +149,23 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
|
|
|
79
149
|
phoneError = e instanceof Error ? e.message : String(e);
|
|
80
150
|
}
|
|
81
151
|
}
|
|
152
|
+
// Include the actual runtime bytes, not only its package version: local
|
|
153
|
+
// runtime edits must invalidate an export even before a release is made.
|
|
154
|
+
const runtimeDir = fileURLToPath(new URL("../runtime/", import.meta.url));
|
|
155
|
+
const runtimeDigest = createHash("sha256");
|
|
156
|
+
for (const file of listFiles(runtimeDir).filter((f) => f.endsWith(".mjs"))) {
|
|
157
|
+
runtimeDigest.update(file).update("\0").update(readFileSync(join(runtimeDir, file))).update("\0");
|
|
158
|
+
}
|
|
159
|
+
const runtimeHash = runtimeDigest.digest("hex");
|
|
82
160
|
const inputHash = createHash("sha256")
|
|
161
|
+
.update(runtimeHash)
|
|
162
|
+
.update(JSON.stringify({ format: scene.format ?? format, locale: scene.locale ?? locale, theme, png, scale, qc, background }))
|
|
83
163
|
.update(sourceFile ? readFileSync(sourceFile) : scene.frame.toString())
|
|
84
164
|
.update(JSON.stringify(style ?? "neutral"))
|
|
85
165
|
.update(JSON.stringify(options ?? null))
|
|
86
166
|
.digest("hex")
|
|
87
167
|
.slice(0, 16);
|
|
168
|
+
const source = sourceFile ? sourceState(sourceFile) : { commit: null, dirty: null };
|
|
88
169
|
const manifest = {
|
|
89
170
|
tool: "motion-kit",
|
|
90
171
|
version,
|
|
@@ -99,12 +180,40 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
|
|
|
99
180
|
style: style?.name ?? "neutral",
|
|
100
181
|
theme,
|
|
101
182
|
inputHash,
|
|
102
|
-
|
|
183
|
+
runtimeHash,
|
|
184
|
+
sourceCommit: source.commit,
|
|
185
|
+
sourceDirty: source.dirty,
|
|
103
186
|
render: { png, scale: png ? scale : null, background, qc },
|
|
104
187
|
files,
|
|
105
188
|
};
|
|
189
|
+
|
|
190
|
+
// Replace the previous export: remove what it wrote that this one did not.
|
|
191
|
+
// The new manifest is published only afterwards, so a removal that fails
|
|
192
|
+
// leaves the old one listing the stale files for the retry.
|
|
193
|
+
const written = new Set(["manifest.json", "index.html", ...files.flatMap((f) => (f.png ? [f.svg, f.png] : [f.svg]))]);
|
|
194
|
+
const root = realpathSync(out);
|
|
195
|
+
for (const p of previous) {
|
|
196
|
+
if (written.has(p)) continue;
|
|
197
|
+
const target = join(out, p);
|
|
198
|
+
// A directory symlinked out of `out` must not lead the removal elsewhere.
|
|
199
|
+
let parent;
|
|
200
|
+
try {
|
|
201
|
+
parent = realpathSync(dirname(target));
|
|
202
|
+
} catch {
|
|
203
|
+
continue; // its folder is gone, so is the file
|
|
204
|
+
}
|
|
205
|
+
if (parent !== root && !parent.startsWith(root + sep)) {
|
|
206
|
+
warn(`motion-kit export: did not remove ${p}: it resolves outside ${out}`);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
rmSync(target, { force: true });
|
|
210
|
+
}
|
|
106
211
|
writeFileSync(join(out, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
107
212
|
writeFileSync(join(out, "index.html"), contactSheet(scene, files, theme, style, phoneError));
|
|
213
|
+
const qcDir = join(out, "qc");
|
|
214
|
+
if (existsSync(qcDir) && readdirSync(qcDir).length === 0) rmdirSync(qcDir);
|
|
215
|
+
const unknown = listFiles(out).filter((p) => !written.has(p));
|
|
216
|
+
if (unknown.length) warn(`motion-kit export: left ${unknown.length} file(s) in ${out} that no export wrote: ${unknown.join(", ")}`);
|
|
108
217
|
return manifest;
|
|
109
218
|
}
|
|
110
219
|
|
package/lib/gate.mjs
CHANGED
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
*
|
|
7
7
|
* checkFiles(files, { formats, locales, style, options }) → number of failures
|
|
8
8
|
*
|
|
9
|
-
* - The style must pass the contrast check
|
|
9
|
+
* - The style must pass the contrast check for the pairs every scene draws
|
|
10
|
+
* (G12, CONTRAST_PAIRS), once.
|
|
10
11
|
* - Every file × format (all of FORMATS unless given) × locale passes
|
|
11
|
-
* checkScene
|
|
12
|
-
*
|
|
12
|
+
* checkScene, which also checks the style against the pairs that scene
|
|
13
|
+
* declares it draws besides (`scene.contrastPairs`). Locales: the given ones; else, for a spec, every locale its
|
|
14
|
+
* strings carry, and a module’s exported `locales` (default `en`).
|
|
13
15
|
* - A file that cannot be read, parsed or built is a failure for that file
|
|
14
16
|
* only; the remaining files are still checked.
|
|
15
17
|
*/
|
|
@@ -17,7 +19,7 @@ import { readFileSync } from "node:fs";
|
|
|
17
19
|
import { FORMATS } from "../runtime/scene.mjs";
|
|
18
20
|
import { checkContrast } from "../runtime/style.mjs";
|
|
19
21
|
import { checkScene } from "./check.mjs";
|
|
20
|
-
import { isModule, loadScene } from "./load.mjs";
|
|
22
|
+
import { isModule, loadScene, moduleLocales } from "./load.mjs";
|
|
21
23
|
|
|
22
24
|
/** @param {unknown} e */
|
|
23
25
|
const message = (e) => (e instanceof Error ? e.message : String(e));
|
|
@@ -57,9 +59,9 @@ export async function checkFiles(files, { formats, locales, style, options, log
|
|
|
57
59
|
for (const file of files) {
|
|
58
60
|
const module = isModule(file);
|
|
59
61
|
let fileLocales = locales?.length ? locales : ["en"];
|
|
60
|
-
if (!locales?.length
|
|
62
|
+
if (!locales?.length) {
|
|
61
63
|
try {
|
|
62
|
-
fileLocales = detectLocales(JSON.parse(readFileSync(file, "utf8")));
|
|
64
|
+
fileLocales = module ? await moduleLocales(file) : detectLocales(JSON.parse(readFileSync(file, "utf8")));
|
|
63
65
|
} catch (e) {
|
|
64
66
|
bad++;
|
|
65
67
|
error(`✗ ${file}: ${message(e)}`);
|
|
@@ -71,7 +73,7 @@ export async function checkFiles(files, { formats, locales, style, options, log
|
|
|
71
73
|
try {
|
|
72
74
|
const sceneOptions = module && options ? await options({ format, locale }) : undefined;
|
|
73
75
|
const { scene } = await loadScene(file, { format, locale, options: sceneOptions });
|
|
74
|
-
const r = checkScene(scene);
|
|
76
|
+
const r = checkScene(scene, { style });
|
|
75
77
|
if (r.ok) log(`✓ ${file} · ${format} · ${locale} · ${scene.duration.toFixed(2)} s · ${scene.steps.length} steps`);
|
|
76
78
|
else {
|
|
77
79
|
bad++;
|
package/lib/load.mjs
CHANGED
|
@@ -81,3 +81,18 @@ export async function loadOptions(arg) {
|
|
|
81
81
|
if (typeof mod.default === "function") return (ctx) => mod.default(ctx);
|
|
82
82
|
return fixed(mod.default);
|
|
83
83
|
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Locales a custom module promises to ship. Undeclared modules keep the
|
|
87
|
+
* backwards-compatible English default; --locale explicitly overrides this.
|
|
88
|
+
* @param {string} file
|
|
89
|
+
* @returns {Promise<string[]>}
|
|
90
|
+
*/
|
|
91
|
+
export async function moduleLocales(file) {
|
|
92
|
+
const mod = await import(pathToFileURL(resolve(file)).href);
|
|
93
|
+
if (mod.locales === undefined) return ["en"];
|
|
94
|
+
if (!Array.isArray(mod.locales) || !mod.locales.length || mod.locales.some((l) => typeof l !== "string" || !/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(l)) || new Set(mod.locales).size !== mod.locales.length) {
|
|
95
|
+
throw new Error(`${file}: locales must be a non-empty array of unique locale tags`);
|
|
96
|
+
}
|
|
97
|
+
return mod.locales;
|
|
98
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@liqweed/motion-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Deterministic animated diagrams: scenes as pure functions of time, for live pages, slides, baked SVG and video.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"animation",
|
|
@@ -47,14 +47,17 @@
|
|
|
47
47
|
"prepare": "lefthook install || true",
|
|
48
48
|
"test": "node --test test/*.test.mjs",
|
|
49
49
|
"typecheck": "tsc -p .",
|
|
50
|
-
"check": "node cli/motion-kit.mjs check examples/order-flow.json examples/smart-home.json examples/release-pipeline.json examples/agent-loop.json examples/integrations.json examples/custom-pulse.scene.mjs brand/logo.scene.mjs",
|
|
50
|
+
"check": "node cli/motion-kit.mjs check examples/order-flow.json examples/smart-home.json examples/release-pipeline.json examples/agent-loop.json examples/integrations.json examples/incident.json examples/web-stack.json examples/custom-pulse.scene.mjs brand/logo.scene.mjs examples/player-states.json examples/checkout.json examples/connection.json",
|
|
51
51
|
"media": "scripts/render-media.sh",
|
|
52
52
|
"media:check": "scripts/render-media.sh --check",
|
|
53
53
|
"site": "npm run -w website build",
|
|
54
54
|
"site:dev": "npm run -w website dev",
|
|
55
55
|
"site:deploy": "npm run -w website deploy",
|
|
56
56
|
"versions": "node scripts/check-versions.mjs",
|
|
57
|
-
"
|
|
57
|
+
"bench:player": "node scripts/bench-player.mjs",
|
|
58
|
+
"snapshots:update": "node scripts/update-snapshots.mjs",
|
|
59
|
+
"gate:core": "npm run -s typecheck && npm run -s versions && npm test && npm run -s check && npm run -s media:check",
|
|
60
|
+
"gate": "npm run -s gate:core && npm run -s site"
|
|
58
61
|
},
|
|
59
62
|
"optionalDependencies": {
|
|
60
63
|
"@resvg/resvg-js": "^2.6.2"
|
package/runtime/kit.mjs
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
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
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";
|
|
26
|
+
import { CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok } from "./style.mjs";
|
|
27
27
|
import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment } from "./svg.mjs";
|
|
28
28
|
import { estimateWidth, wrapLabel } from "./wrap.mjs";
|
|
29
29
|
|
|
@@ -36,7 +36,7 @@ import { estimateWidth, wrapLabel } from "./wrap.mjs";
|
|
|
36
36
|
export const KIT = Object.freeze({
|
|
37
37
|
...{ ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
|
|
38
38
|
...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
|
|
39
|
-
...{ NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
|
|
39
|
+
...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
|
|
40
40
|
...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, translate, trimSegment },
|
|
41
41
|
...{ estimateWidth, wrapLabel },
|
|
42
42
|
});
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 Ophir Radnitz
|
|
3
|
+
/**
|
|
4
|
+
* motion-kit · page links: drive a player from the page around it (browser;
|
|
5
|
+
* the step mapping is pure and also runs in Node).
|
|
6
|
+
*
|
|
7
|
+
* scrollSteps(controller, sections, options) → dispose
|
|
8
|
+
* Each text section names a step; as the reader scrolls, the section
|
|
9
|
+
* crossing a line across the viewport selects its step. One settled step
|
|
10
|
+
* per section, down and up; never scrubs continuously.
|
|
11
|
+
* linkSteps(controller, rootOrElements, options) → dispose
|
|
12
|
+
* Elements with `data-mk-step` select their step on hover (mouse, pen),
|
|
13
|
+
* keyboard focus and click.
|
|
14
|
+
*
|
|
15
|
+
* `controller` is what mountPlayer returns (or `.controller` of
|
|
16
|
+
* `<motion-diagram>` / the Astro adapter's root element). A step is named by
|
|
17
|
+
* its id or its zero-based index; an unknown id throws RangeError when the
|
|
18
|
+
* helper binds, not when the reader gets there.
|
|
19
|
+
*
|
|
20
|
+
* Nothing touches the DOM at import time, and neither helper moves focus or
|
|
21
|
+
* layout: the active section or term gets `aria-current="step"`, which the
|
|
22
|
+
* page styles without changing sizes.
|
|
23
|
+
*/
|
|
24
|
+
import { stepIndex } from "./scene.mjs";
|
|
25
|
+
|
|
26
|
+
/** The attribute that names an element's step. */
|
|
27
|
+
const STEP_ATTR = "data-mk-step";
|
|
28
|
+
|
|
29
|
+
/** @import { Scene } from "./scene.mjs" */
|
|
30
|
+
/**
|
|
31
|
+
* The part of the player controller the helpers use.
|
|
32
|
+
* @typedef {{ scene: Scene, time: number, onStep?: (listener: (index: number) => void) => (() => void), seek: (t: number) => void, seekStep: (ref: number | string) => void, playToStep: (ref: number | string) => void }} StepController
|
|
33
|
+
*/
|
|
34
|
+
/**
|
|
35
|
+
* @typedef {object} ScrollStepsOptions
|
|
36
|
+
* @property {number} [line] where the line sits, as a share of the root's height from its top (0–1, default 0.5)
|
|
37
|
+
* @property {Element | Document | null} [root] the scroll container; default the viewport
|
|
38
|
+
* @property {boolean} [animate] play forward to the next section's step (default true); other moves jump
|
|
39
|
+
* @property {boolean} [mark] set `aria-current="step"` on the active section (default true)
|
|
40
|
+
* @property {(index: number, section: Element | null) => void} [onChange] called when the active section changes; -1 and null before the first
|
|
41
|
+
*/
|
|
42
|
+
/**
|
|
43
|
+
* @typedef {object} LinkStepsOptions
|
|
44
|
+
* @property {boolean} [animate] play forward to a later step instead of jumping (default false)
|
|
45
|
+
* @property {boolean} [restore] when hover and focus leave every term, return to the frame shown before (default false: the step stays); a click keeps its step
|
|
46
|
+
* @property {boolean} [mark] set `aria-current="step"` on the terms of the selected step (default true)
|
|
47
|
+
* @property {(step: number, element: Element | null) => void} [onChange] called when a term selects a step, and with -1 and null on restore
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/* ------------------------------------------------------- pure step mapping */
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The step index a reference names: a step id, else a whole-number index
|
|
54
|
+
* (a number, or digits as `data-mk-step` gives them). An id wins over an index
|
|
55
|
+
* when a step's id is digits. Throws RangeError for an unknown id or an index
|
|
56
|
+
* out of range.
|
|
57
|
+
* @param {Scene} scene
|
|
58
|
+
* @param {number | string} ref
|
|
59
|
+
* @returns {number}
|
|
60
|
+
*/
|
|
61
|
+
export function stepRef(scene, ref) {
|
|
62
|
+
if (typeof ref === "string") {
|
|
63
|
+
const trimmed = ref.trim();
|
|
64
|
+
if (scene.steps.some((s) => s.id === trimmed)) return stepIndex(scene, trimmed);
|
|
65
|
+
if (/^\d+$/.test(trimmed)) return stepIndex(scene, Number(trimmed));
|
|
66
|
+
return stepIndex(scene, trimmed);
|
|
67
|
+
}
|
|
68
|
+
return stepIndex(scene, ref);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The step of each section, in order: its own reference (`data-mk-step`) when
|
|
73
|
+
* it has one, else its position (the third section shows step 2). Throws
|
|
74
|
+
* RangeError when a reference is unknown or a section has no step to take.
|
|
75
|
+
* @param {Scene} scene
|
|
76
|
+
* @param {(number | string | null | undefined)[]} refs one per section; null or undefined to go by order
|
|
77
|
+
* @returns {number[]}
|
|
78
|
+
*/
|
|
79
|
+
export function sectionSteps(scene, refs) {
|
|
80
|
+
return refs.map((ref, i) => {
|
|
81
|
+
if (ref != null && ref !== "") return stepRef(scene, ref);
|
|
82
|
+
if (i >= scene.steps.length) throw new RangeError(`Section ${i + 1} has no ${STEP_ATTR} and the scene has only ${scene.steps.length} steps`);
|
|
83
|
+
return i;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The active section: the last one, in order, whose top has reached the line
|
|
89
|
+
* (top ≤ line). A section stays active through the gap after it until the next
|
|
90
|
+
* one reaches the line, and the last one stays active below it. -1 while no
|
|
91
|
+
* section has reached the line.
|
|
92
|
+
* @param {number[]} tops each section's top, in the same coordinates as `line`
|
|
93
|
+
* @param {number} line
|
|
94
|
+
* @returns {number}
|
|
95
|
+
*/
|
|
96
|
+
export function activeSection(tops, line) {
|
|
97
|
+
let active = -1;
|
|
98
|
+
tops.forEach((top, i) => {
|
|
99
|
+
if (top <= line) active = i;
|
|
100
|
+
});
|
|
101
|
+
return active;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* How to move between sections: "play" to the next section's step when it is
|
|
106
|
+
* one section further and a later step (animation allowed, no reduced motion),
|
|
107
|
+
* "seek" for every other change (back, skipping, the first section), and null
|
|
108
|
+
* when there is nothing to do (no section, or the same step).
|
|
109
|
+
* @param {{ from: number, to: number, fromStep: number, toStep: number, animate?: boolean, reduced?: boolean }} move
|
|
110
|
+
* @returns {"play" | "seek" | null}
|
|
111
|
+
*/
|
|
112
|
+
export function scrollMove({ from, to, fromStep, toStep, animate = true, reduced = false }) {
|
|
113
|
+
if (to < 0 || (from >= 0 && toStep === fromStep)) return null;
|
|
114
|
+
return animate && !reduced && from >= 0 && to === from + 1 && toStep > fromStep ? "play" : "seek";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/* ---------------------------------------------------------------- the DOM */
|
|
118
|
+
|
|
119
|
+
const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
120
|
+
|
|
121
|
+
/** @param {Element} el @param {boolean} on */
|
|
122
|
+
function markCurrent(el, on) {
|
|
123
|
+
if (on) el.setAttribute("aria-current", "step");
|
|
124
|
+
else if (el.getAttribute("aria-current") === "step") el.removeAttribute("aria-current");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** @param {unknown} controller @returns {StepController} */
|
|
128
|
+
function needController(controller) {
|
|
129
|
+
const c = /** @type {any} */ (controller);
|
|
130
|
+
if (!c || typeof c.seekStep !== "function" || !c.scene) throw new TypeError("expected a player controller (mountPlayer, or .controller of <motion-diagram> / the Astro adapter)");
|
|
131
|
+
return c;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Bind a player to a list of text sections: as each section's top crosses a
|
|
136
|
+
* line across the viewport (or `root`), the diagram goes to that section's
|
|
137
|
+
* settled step. A section names its step with `data-mk-step` (step id or
|
|
138
|
+
* index), else by order. Moving one section forward plays to the next step;
|
|
139
|
+
* moving back, skipping sections and reduced motion jump. Without
|
|
140
|
+
* IntersectionObserver it does nothing.
|
|
141
|
+
*
|
|
142
|
+
* Give the page room below the last section (e.g. `padding-bottom: 50vh`), so
|
|
143
|
+
* the last section's top can reach the line. Mount the player with
|
|
144
|
+
* `autoplay: "none"`; the first section's step replaces any pending autoplay.
|
|
145
|
+
* @param {StepController} controller
|
|
146
|
+
* @param {Iterable<Element> | ArrayLike<Element>} sections in reading order
|
|
147
|
+
* @param {ScrollStepsOptions} [options]
|
|
148
|
+
* @returns {() => void} dispose: stops observing and clears the marks
|
|
149
|
+
*/
|
|
150
|
+
export function scrollSteps(controller, sections, options = {}) {
|
|
151
|
+
const c = needController(controller);
|
|
152
|
+
const els = Array.from(sections);
|
|
153
|
+
const steps = sectionSteps(c.scene, els.map((el) => el.getAttribute(STEP_ATTR)));
|
|
154
|
+
const line = Math.min(Math.max(options.line ?? 0.5, 0), 1);
|
|
155
|
+
const { root = null, animate = true, mark = true, onChange } = options;
|
|
156
|
+
let current = -1;
|
|
157
|
+
let disposed = false;
|
|
158
|
+
|
|
159
|
+
/** The line's position in viewport coordinates. */
|
|
160
|
+
const lineY = () => {
|
|
161
|
+
if (root && "getBoundingClientRect" in root) {
|
|
162
|
+
const r = root.getBoundingClientRect();
|
|
163
|
+
return r.top + line * r.height;
|
|
164
|
+
}
|
|
165
|
+
return line * (globalThis.innerHeight ?? 0);
|
|
166
|
+
};
|
|
167
|
+
const update = () => {
|
|
168
|
+
if (disposed) return;
|
|
169
|
+
const next = activeSection(els.map((el) => el.getBoundingClientRect().top), lineY());
|
|
170
|
+
if (next === current) return;
|
|
171
|
+
const move = scrollMove({ from: current, to: next, fromStep: steps[current] ?? -1, toStep: steps[next] ?? -1, animate, reduced: reducedMotion() });
|
|
172
|
+
if (move === "play") c.playToStep(steps[next]);
|
|
173
|
+
else if (move === "seek") c.seekStep(steps[next]);
|
|
174
|
+
if (mark) els.forEach((el, i) => markCurrent(el, i === next));
|
|
175
|
+
current = next;
|
|
176
|
+
onChange?.(next, els[next] ?? null);
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
if (typeof IntersectionObserver !== "function") return () => {};
|
|
180
|
+
const unsubscribe = mark ? c.onStep?.((index) => els.forEach((el, i) => markCurrent(el, steps[i] === index))) : undefined;
|
|
181
|
+
// The root, cut off at the line: a section enters or leaves it exactly
|
|
182
|
+
// when its top crosses the line, which is when the active one can change.
|
|
183
|
+
const below = `${(1 - line) * 100}%`;
|
|
184
|
+
const observer = new IntersectionObserver(update, { root, rootMargin: `0px 0px -${below} 0px`, threshold: 0 });
|
|
185
|
+
for (const el of els) observer.observe(el);
|
|
186
|
+
// A jump that moves every section across the line without changing which
|
|
187
|
+
// are inside the observed area sends no notification, so scrolling asks
|
|
188
|
+
// again, at most once per frame.
|
|
189
|
+
const scroller = root && "addEventListener" in root ? root : globalThis;
|
|
190
|
+
const raf = globalThis.requestAnimationFrame?.bind(globalThis);
|
|
191
|
+
let queued = false;
|
|
192
|
+
const onScroll = () => {
|
|
193
|
+
if (queued || disposed) return;
|
|
194
|
+
if (!raf) return update();
|
|
195
|
+
queued = true;
|
|
196
|
+
raf(() => {
|
|
197
|
+
queued = false;
|
|
198
|
+
update();
|
|
199
|
+
});
|
|
200
|
+
};
|
|
201
|
+
scroller.addEventListener?.("scroll", onScroll, { passive: true });
|
|
202
|
+
return () => {
|
|
203
|
+
if (disposed) return;
|
|
204
|
+
disposed = true;
|
|
205
|
+
observer.disconnect();
|
|
206
|
+
unsubscribe?.();
|
|
207
|
+
scroller.removeEventListener?.("scroll", onScroll);
|
|
208
|
+
if (mark) for (const el of els) markCurrent(el, false);
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Bind a player to terms in the page: every element with `data-mk-step` (step
|
|
214
|
+
* id or index) under `root`, or the elements given, selects its step on
|
|
215
|
+
* pointer hover (mouse and pen; touch selects on click instead), on keyboard
|
|
216
|
+
* focus (also focus inside it) and on click. Make terms focusable, e.g.
|
|
217
|
+
* `<button type="button" data-mk-step="payment">`, so keyboard users get the
|
|
218
|
+
* same step as pointer users. A selection jumps; `animate: true` plays forward
|
|
219
|
+
* to a later step unless the reader prefers reduced motion.
|
|
220
|
+
*
|
|
221
|
+
* By default the selected step stays when the pointer or focus leaves.
|
|
222
|
+
* `restore: true` makes hover and focus a preview: once neither is on a term,
|
|
223
|
+
* the diagram returns to the frame it showed before; a click keeps its step.
|
|
224
|
+
* Terms are collected when binding; bind again for terms added later.
|
|
225
|
+
* @param {StepController} controller
|
|
226
|
+
* @param {ParentNode | Iterable<Element> | ArrayLike<Element>} target a root to search, or the terms
|
|
227
|
+
* @param {LinkStepsOptions} [options]
|
|
228
|
+
* @returns {() => void} dispose: removes the listeners and clears the marks
|
|
229
|
+
*/
|
|
230
|
+
export function linkSteps(controller, target, options = {}) {
|
|
231
|
+
const c = needController(controller);
|
|
232
|
+
const { animate = false, restore = false, mark = true, onChange } = options;
|
|
233
|
+
const t = /** @type {any} */ (target);
|
|
234
|
+
/** @type {Element[]} */
|
|
235
|
+
const els = typeof t?.querySelectorAll === "function" ? Array.from(t.querySelectorAll(`[${STEP_ATTR}]`)) : Array.from(t);
|
|
236
|
+
const steps = els.map((el) => {
|
|
237
|
+
const ref = el.getAttribute(STEP_ATTR);
|
|
238
|
+
if (ref == null || ref === "") throw new RangeError(`linkSteps: an element has no ${STEP_ATTR}`);
|
|
239
|
+
return stepRef(c.scene, ref);
|
|
240
|
+
});
|
|
241
|
+
/** @type {Element | null} */
|
|
242
|
+
let hovered = null;
|
|
243
|
+
/** @type {Element | null} */
|
|
244
|
+
let focused = null;
|
|
245
|
+
/** The time before a preview began, to restore; null when nothing is previewed. @type {number | null} */
|
|
246
|
+
let before = null;
|
|
247
|
+
let selected = -1;
|
|
248
|
+
|
|
249
|
+
/** @param {number} step @param {Element | null} el */
|
|
250
|
+
const show = (step, el) => {
|
|
251
|
+
selected = step;
|
|
252
|
+
if (mark) els.forEach((e, i) => markCurrent(e, steps[i] === step));
|
|
253
|
+
onChange?.(step, el);
|
|
254
|
+
};
|
|
255
|
+
/** @param {number} i */
|
|
256
|
+
const select = (i) => {
|
|
257
|
+
const step = steps[i];
|
|
258
|
+
if (animate && !reducedMotion()) c.playToStep(step);
|
|
259
|
+
else c.seekStep(step);
|
|
260
|
+
show(step, els[i]);
|
|
261
|
+
};
|
|
262
|
+
/** @param {number} i */
|
|
263
|
+
const preview = (i) => {
|
|
264
|
+
if (restore && before === null) before = c.time;
|
|
265
|
+
select(i);
|
|
266
|
+
};
|
|
267
|
+
const leave = () => {
|
|
268
|
+
if (!restore || hovered || focused || before === null) return;
|
|
269
|
+
c.seek(before);
|
|
270
|
+
before = null;
|
|
271
|
+
if (selected !== -1) show(-1, null);
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
/** @type {[Element, string, (e: any) => void][]} */
|
|
275
|
+
const bound = [];
|
|
276
|
+
els.forEach((el, i) => {
|
|
277
|
+
/** @type {Record<string, (e: any) => void>} */
|
|
278
|
+
const on = {
|
|
279
|
+
pointerenter: (e) => {
|
|
280
|
+
if (e?.pointerType === "touch") return;
|
|
281
|
+
hovered = el;
|
|
282
|
+
preview(i);
|
|
283
|
+
},
|
|
284
|
+
pointerleave: (e) => {
|
|
285
|
+
if (e?.pointerType === "touch" || hovered !== el) return;
|
|
286
|
+
hovered = null;
|
|
287
|
+
leave();
|
|
288
|
+
},
|
|
289
|
+
focusin: () => {
|
|
290
|
+
focused = el;
|
|
291
|
+
preview(i);
|
|
292
|
+
},
|
|
293
|
+
focusout: () => {
|
|
294
|
+
if (focused !== el) return;
|
|
295
|
+
focused = null;
|
|
296
|
+
leave();
|
|
297
|
+
},
|
|
298
|
+
click: () => {
|
|
299
|
+
// A click commits: nothing to restore afterwards.
|
|
300
|
+
before = null;
|
|
301
|
+
select(i);
|
|
302
|
+
},
|
|
303
|
+
};
|
|
304
|
+
for (const [name, fn] of Object.entries(on)) {
|
|
305
|
+
el.addEventListener(name, fn);
|
|
306
|
+
bound.push([el, name, fn]);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
const unsubscribe = mark ? c.onStep?.((index) => els.forEach((el, i) => markCurrent(el, steps[i] === index))) : undefined;
|
|
310
|
+
let disposed = false;
|
|
311
|
+
return () => {
|
|
312
|
+
if (disposed) return;
|
|
313
|
+
disposed = true;
|
|
314
|
+
unsubscribe?.();
|
|
315
|
+
for (const [el, name, fn] of bound) el.removeEventListener(name, fn);
|
|
316
|
+
if (mark) for (const el of els) markCurrent(el, false);
|
|
317
|
+
};
|
|
318
|
+
}
|
package/runtime/parts.mjs
CHANGED
|
@@ -12,6 +12,21 @@ import { attrString, el, esc, fade, num, text, translate } from "./svg.mjs";
|
|
|
12
12
|
import { tok } from "./style.mjs";
|
|
13
13
|
|
|
14
14
|
export const FONT_MIN = 14; // smallest label size at 1× (viewBox units)
|
|
15
|
+
export const FONT_MAX = 200; // largest `fontSize` a scene may ask for
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The largest label size a scene type tries: its `fontSize`, else `dflt`. The
|
|
19
|
+
* fit searches count down from it, so it must be a finite number in range.
|
|
20
|
+
* @param {{ fontSize?: number }} spec
|
|
21
|
+
* @param {number} dflt
|
|
22
|
+
* @param {string} name for the error
|
|
23
|
+
* @returns {number}
|
|
24
|
+
*/
|
|
25
|
+
export function maxFontSize(spec, dflt, name) {
|
|
26
|
+
const fs = spec.fontSize ?? dflt;
|
|
27
|
+
if (!Number.isFinite(fs) || fs < FONT_MIN || fs > FONT_MAX) throw new Error(`${name}: fontSize must be a number from ${FONT_MIN} to ${FONT_MAX}, got ${fs}`);
|
|
28
|
+
return fs;
|
|
29
|
+
}
|
|
15
30
|
|
|
16
31
|
/**
|
|
17
32
|
* Optional icon: SVG path data drawn on a 24×24 grid with round strokes
|