@liqweed/motion-kit 0.3.0 → 0.5.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.
Files changed (46) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +63 -10
  4. package/adapters/astro/AnimatedDiagram.astro +150 -24
  5. package/adapters/element/README.md +6 -1
  6. package/adapters/element/motion-diagram.mjs +4 -3
  7. package/adapters/page/README.md +8 -2
  8. package/adapters/slidev/AnimatedDiagram.vue +24 -0
  9. package/cli/motion-kit.mjs +85 -81
  10. package/docs/spec/technique.md +166 -63
  11. package/examples/custom-pulse.scene.mjs +3 -0
  12. package/examples/incident.json +18 -0
  13. package/examples/web-stack.json +17 -0
  14. package/lib/build.mjs +26 -12
  15. package/lib/bundle.mjs +9 -2
  16. package/lib/check.mjs +219 -15
  17. package/lib/export.mjs +135 -16
  18. package/lib/gate.mjs +90 -0
  19. package/lib/load.mjs +49 -19
  20. package/package.json +6 -3
  21. package/runtime/bake.mjs +18 -4
  22. package/runtime/kit.mjs +59 -0
  23. package/runtime/links.mjs +314 -0
  24. package/runtime/page.mjs +52 -0
  25. package/runtime/parts.mjs +15 -0
  26. package/runtime/patch.mjs +297 -0
  27. package/runtime/player.mjs +334 -130
  28. package/runtime/scene.mjs +82 -5
  29. package/runtime/style.mjs +64 -16
  30. package/runtime/types/hub-spoke.mjs +7 -7
  31. package/runtime/types/index.mjs +4 -0
  32. package/runtime/types/sequence.mjs +5 -5
  33. package/runtime/types/stack.mjs +227 -0
  34. package/runtime/types/timeline.mjs +405 -0
  35. package/skills/animated-diagram/SKILL.md +30 -7
  36. package/skills/animated-diagram/references/custom-scenes.md +64 -9
  37. package/skills/animated-diagram/references/interactivity.md +150 -15
  38. package/skills/animated-diagram/references/qc.md +5 -2
  39. package/skills/animated-diagram/references/scene-types.md +45 -2
  40. package/skills/animated-diagram/references/styles.md +45 -5
  41. package/skills/animated-diagram/references/targets.md +7 -5
  42. package/skills/animated-diagram/references/technique.md +14 -4
  43. package/skills/motion-render/SKILL.md +31 -8
  44. package/skills/motion-render/references/formats.md +8 -8
  45. package/skills/project-logo/SKILL.md +15 -4
  46. package/styles/neutral.json +2 -2
package/lib/check.mjs CHANGED
@@ -4,9 +4,12 @@
4
4
  * motion-kit · scene gate. Every scene, every format/locale it ships in, must
5
5
  * pass these before anything is exported or mounted.
6
6
  *
7
- * checkScene(scene) → { ok, problems: string[] }
7
+ * checkScene(scene, { style }) → { 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";
12
+ import { checkContrast } from "../runtime/style.mjs";
10
13
 
11
14
  const SAMPLES = 120;
12
15
 
@@ -32,12 +35,175 @@ export function wellFormed(svg) {
32
35
  return null;
33
36
  }
34
37
 
35
- export function checkScene(scene, { samples = SAMPLES } = {}) {
38
+ /* ------------------------------------------------------------ colour literals */
39
+
40
+ /** Presentation attributes whose value is a colour. */
41
+ const COLOUR_ATTRS = new Set(["fill", "stroke", "stop-color", "color", "flood-color", "lighting-color"]);
42
+ /** CSS properties (in style="…" or a <style> element) whose value is a colour. */
43
+ const isColourProperty = (/** @type {string} */ name) => COLOUR_ATTRS.has(name) || name === "background" || /-colou?r$/.test(name);
44
+ /**
45
+ * Values that name no colour, so they look the same under every style and
46
+ * theme: no paint, the inherited or current colour, `transparent` (no hue,
47
+ * invisible in light and dark alike), marker context paint, CSS-wide keywords.
48
+ */
49
+ const NOT_A_COLOUR = /^(none|currentcolor|transparent|inherit|initial|unset|revert|revert-layer|context-fill|context-stroke)$/i;
50
+ /** Literal colour syntax anywhere in markup or CSS: hex and colour functions. */
51
+ const COLOUR_SYNTAX = /#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color|color-mix|light-dark)\(/i;
52
+ /** References to ids, which are not colours: url(#x). */
53
+ const ID_REF = /url\(\s*['"]?#[^)]*\)/g;
54
+
55
+ /**
56
+ * The literal colour in one colour value (`fill`, `stroke`, a style
57
+ * property), or null when it uses only tokens (`var(--mk-x)`), id references
58
+ * and the keywords in NOT_A_COLOUR. Named colours (`red`), hex, colour
59
+ * functions and other custom properties are literals.
60
+ * @param {string} value
61
+ * @returns {string | null}
62
+ */
63
+ export function colourLiteral(value) {
64
+ const rest = value.replace(/!important/gi, "").replace(ID_REF, " ").replace(/var\(--mk-[a-zA-Z]+\)/g, " ").trim();
65
+ if (!rest || rest.split(/\s+/).every((word) => NOT_A_COLOUR.test(word))) return null;
66
+ return rest;
67
+ }
68
+
69
+ /**
70
+ * @param {string} css declarations, or a whole stylesheet
71
+ * @returns {string | null}
72
+ */
73
+ function cssColourLiteral(css) {
74
+ for (const [, prop, value] of css.matchAll(/([\w-]+)\s*:\s*([^;{}]+)/g)) {
75
+ if (!isColourProperty(prop.toLowerCase())) continue;
76
+ const lit = colourLiteral(value);
77
+ if (lit) return `${prop}: ${lit}`;
78
+ }
79
+ // Colour syntax in a declaration, never in a selector: `#face-node` is an id.
80
+ const declarations = css.includes("{") ? [...css.matchAll(/\{([^{}]*)\}/g)].map((m) => m[1]).join(";") : css;
81
+ return declarations.replace(ID_REF, "").match(COLOUR_SYNTAX)?.[0] ?? null;
82
+ }
83
+
84
+ /** @param {string} v */
85
+ const unescapeAttr = (v) => v.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
86
+
87
+ /**
88
+ * The first colour literal in a frame's markup, or null. Looks inside tags
89
+ * and <style> elements, not at text content: a label may say "#1".
90
+ * @param {string} markup
91
+ * @returns {string | null}
92
+ */
93
+ export function findColourLiteral(markup) {
94
+ for (const [, tag] of markup.matchAll(/<([a-zA-Z][^>]*)>/g)) {
95
+ for (const [, name, raw] of tag.matchAll(/([\w:-]+)="([^"]*)"/g)) {
96
+ if (name === "href" || name === "xlink:href") continue; // href="#id"
97
+ const value = unescapeAttr(raw);
98
+ let lit;
99
+ if (name === "style") lit = cssColourLiteral(value);
100
+ else if (COLOUR_ATTRS.has(name)) lit = colourLiteral(value);
101
+ else lit = value.replace(ID_REF, "").match(COLOUR_SYNTAX)?.[0] ?? null;
102
+ if (lit) return `${name}="${lit}"`;
103
+ }
104
+ }
105
+ for (const [, css] of markup.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)) {
106
+ const lit = cssColourLiteral(css);
107
+ if (lit) return `<style> ${lit}`;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /* ------------------------------------------------------- clock and randomness */
113
+
114
+ /**
115
+ * Two fixed clocks far apart (1970 and 2100; random 0 and almost 1). A frame
116
+ * that reads Date, performance.now, Temporal.Now or Math.random, itself or in
117
+ * a helper it calls, renders differently under at least one of them than
118
+ * under the real ones.
119
+ */
120
+ const STUB_CLOCKS = [
121
+ { now: 0, perf: 0, random: 0 },
122
+ { now: 4102444800000, perf: 1e9, random: 0.999999 },
123
+ ];
124
+
125
+ /**
126
+ * Run `fn` with Date, performance.now, Temporal.Now and Math.random replaced
127
+ * by a fixed clock; the originals are restored before it returns or throws.
128
+ * @template T
129
+ * @param {{ now: number, perf: number, random: number }} clock
130
+ * @param {() => T} fn
131
+ * @returns {T}
132
+ */
133
+ function underStubbedClock({ now, perf, random }, fn) {
134
+ const g = /** @type {any} */ (globalThis);
135
+ const RealDate = g.Date;
136
+ const realRandom = Math.random;
137
+ const performance = g.performance;
138
+ const ownNow = performance && Object.getOwnPropertyDescriptor(performance, "now");
139
+ const temporal = g.Temporal;
140
+ const realTemporalNow = temporal?.Now;
141
+ /** @param {...any} args */
142
+ function FakeDate(...args) {
143
+ if (!new.target) return new RealDate(now).toString();
144
+ return args.length ? new RealDate(...args) : new RealDate(now);
145
+ }
146
+ FakeDate.now = () => now;
147
+ FakeDate.parse = RealDate.parse;
148
+ FakeDate.UTC = RealDate.UTC;
149
+ FakeDate.prototype = RealDate.prototype;
150
+ try {
151
+ g.Date = FakeDate;
152
+ Math.random = () => random;
153
+ if (performance) Object.defineProperty(performance, "now", { value: () => perf, configurable: true, writable: true });
154
+ if (realTemporalNow) {
155
+ const instant = () => temporal.Instant.fromEpochMilliseconds(now);
156
+ const zoned = (tz = "UTC") => instant().toZonedDateTimeISO(tz);
157
+ temporal.Now = {
158
+ instant,
159
+ timeZoneId: () => "UTC",
160
+ zonedDateTimeISO: zoned,
161
+ plainDateTimeISO: (/** @type {string | undefined} */ tz) => zoned(tz).toPlainDateTime(),
162
+ plainDateISO: (/** @type {string | undefined} */ tz) => zoned(tz).toPlainDate(),
163
+ plainTimeISO: (/** @type {string | undefined} */ tz) => zoned(tz).toPlainTime(),
164
+ };
165
+ }
166
+ return fn();
167
+ } finally {
168
+ g.Date = RealDate;
169
+ Math.random = realRandom;
170
+ if (performance) {
171
+ if (ownNow) Object.defineProperty(performance, "now", ownNow);
172
+ else delete performance.now;
173
+ }
174
+ if (realTemporalNow) temporal.Now = realTemporalNow;
175
+ }
176
+ }
177
+
178
+ /* --------------------------------------------------------------------- gate */
179
+
180
+ /**
181
+ * Offsets (s) after a step's `at` at which the frame must still be the step
182
+ * frame. The canon leaves at least 50 ms between a step and the next beat
183
+ * (motion-vocabulary.md, "Pause between beats"), so motion passing through
184
+ * `at` shows inside this window, while the next beat, which may start at
185
+ * exactly `at` + 50 ms, never does.
186
+ */
187
+ export const SETTLE_AFTER = Object.freeze([0.001, 0.015, 0.03, 0.045]);
188
+
189
+ /**
190
+ * Run the scene gate on one built scene.
191
+ * @param {import("../runtime/scene.mjs").Scene} scene
192
+ * @param {{ samples?: number, style?: any }} [options]
193
+ * style: what the scene's own `contrastPairs` are checked against (neutral
194
+ * if absent). The pairs every scene draws (CONTRAST_PAIRS) are a property of
195
+ * the style alone, checked once per style by lib/gate.mjs.
196
+ * @returns {{ ok: boolean, problems: string[] }}
197
+ */
198
+ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
36
199
  const problems = [];
37
- const render = (t) => renderSvg(scene, t);
38
- const at = (i) => (scene.duration * i) / samples;
200
+ const render = (/** @type {number} */ t) => renderSvg(scene, t);
201
+ const at = (/** @type {number} */ i) => (scene.duration * i) / samples;
39
202
 
40
- // 1. Deterministic + well-formed + rounded + token-only, across the timeline.
203
+ // 1. Deterministic + well-formed + rounded + token-only, across the timeline,
204
+ // and the same bytes under two stubbed clocks: no clock or randomness,
205
+ // also not in the helpers the frame calls.
206
+ let clockRead = false;
41
207
  for (let i = 0; i <= samples; i++) {
42
208
  const t = at(i);
43
209
  const a = render(t);
@@ -46,17 +212,38 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
46
212
  if (wf) problems.push(`malformed at t=${t.toFixed(3)}: ${wf}`);
47
213
  const long = a.match(/-?\d+\.\d{5,}/);
48
214
  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
- const lit = frame.match(/#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(/);
51
- if (lit) problems.push(`colour literal "${lit[0]}" at t=${t.toFixed(3)} (use tok())`);
215
+ const frame = scene.frame(Math.min(t, scene.duration), { idPrefix: scene.id });
216
+ const lit = findColourLiteral(frame);
217
+ if (lit) problems.push(`colour literal ${lit} at t=${t.toFixed(3)} (use tok())`);
52
218
  if (/NaN|undefined|Infinity/.test(frame)) problems.push(`NaN/undefined/Infinity in frame at t=${t.toFixed(3)}`);
219
+ for (const clock of clockRead ? [] : STUB_CLOCKS) {
220
+ let stubbed;
221
+ try {
222
+ stubbed = underStubbedClock(clock, () => render(t));
223
+ } catch (e) {
224
+ stubbed = e;
225
+ }
226
+ if (stubbed !== a) {
227
+ clockRead = true;
228
+ problems.push(`frame() reads the clock or randomness: at t=${t.toFixed(3)} it renders differently under a stubbed Date, performance.now or Math.random`);
229
+ break;
230
+ }
231
+ }
53
232
  if (problems.length > 12) break;
54
233
  }
55
234
 
56
- // 2. Settled steps: nothing moves at a step's time.
57
- for (const s of scene.steps) {
58
- const before = render(Math.max(0, s.at - 0.001));
59
- if (before !== render(s.at)) problems.push(`step "${s.label}" at ${s.at.toFixed(3)}s is not settled (something is still moving)`);
235
+ // 2. Settled steps: nothing moves at a step's time. The step's own motion
236
+ // is at rest 1 ms before `at`, and nothing changes in the SETTLE_AFTER
237
+ // window after it (up to the next step), so no motion passes through `at`.
238
+ for (const [i, s] of scene.steps.entries()) {
239
+ const still = render(s.at);
240
+ const next = scene.steps[i + 1]?.at ?? Infinity;
241
+ const offsets = [-0.001, ...SETTLE_AFTER.filter((d) => s.at + d < next)];
242
+ const moved = offsets.find((d) => render(Math.max(0, s.at + d)) !== still);
243
+ if (moved !== undefined) {
244
+ const when = moved < 0 ? "1 ms before" : `${Math.round(moved * 1000)} ms after`;
245
+ problems.push(`step "${s.label}" at ${s.at.toFixed(3)}s is not settled: the frame ${when} differs (something is still moving)`);
246
+ }
60
247
  }
61
248
 
62
249
  // 3. Builds up and finishes.
@@ -71,16 +258,33 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
71
258
 
72
259
  // 5. Every step label is visible in the final frame (escaped form), unless
73
260
  // the scene declares narrative steps (stepLabelsInFrame: false).
74
- const escd = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
261
+ const escd = (/** @type {string} */ s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
75
262
  const plain = lastFrame.replace(/<\/tspan><tspan[^>]*>/g, " ").replace(/<[^>]+>/g, "\u0000");
76
263
  for (const s of scene.stepLabelsInFrame === false ? [] : scene.steps) {
77
264
  const words = escd(s.label).split(/\s+/);
78
265
  if (!words.every((w) => plain.includes(w.replace(/\/$/, "")))) problems.push(`step label "${s.label}" not found in the final frame`);
79
266
  }
80
267
 
81
- // 6. No forbidden sources of time/randomness in the frame function.
268
+ // 6. No clock or randomness named in the frame function's own source: a
269
+ // hint for code paths the samples miss (rule 1 catches what they reach).
82
270
  const src = scene.frame.toString();
83
- if (/Date\.now|new Date|Math\.random|performance\.now/.test(src)) problems.push("frame() reads the clock or randomness");
271
+ if (!clockRead && /Date\.now|new Date|Math\.random|performance\.now|Temporal\.Now/.test(src)) problems.push("frame() reads the clock or randomness");
272
+
273
+ // 7. Every id comes from the instance prefix, so two instances on a page
274
+ // never share one: render with two prefixes and look for common ids.
275
+ const fixed = new Set();
276
+ for (let i = 0; i <= samples; i += 10) {
277
+ const ids = (/** @type {string} */ prefix) => new Set([...renderSvg(scene, at(i), { idPrefix: prefix }).matchAll(/\sid="([^"]*)"/g)].map((m) => m[1]));
278
+ const second = ids("mk-gate-b");
279
+ for (const id of ids("mk-gate-a")) if (second.has(id)) fixed.add(id);
280
+ }
281
+ for (const id of fixed) problems.push(`fixed id "${id}": build ids from frame(t, { idPrefix }), e.g. \`\${idPrefix}-${id}\``);
282
+
283
+ // 8. The token pairs this scene draws beyond the shared ones
284
+ // (scene.contrastPairs) meet their contrast in the style, both themes.
285
+ if (scene.contrastPairs !== undefined) {
286
+ for (const p of checkContrast(style, scene.contrastPairs)) problems.push(`contrast: ${p}`);
287
+ }
84
288
 
85
289
  return { ok: problems.length === 0, problems };
86
290
  }
package/lib/export.mjs CHANGED
@@ -5,13 +5,21 @@
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
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.
10
18
  */
11
19
  import { createHash } from "node:crypto";
12
20
  import { execFileSync } from "node:child_process";
13
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
- import { join } from "node:path";
21
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
22
+ import { basename, dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
15
23
  import { renderSvg } from "../runtime/scene.mjs";
16
24
  import { svgToPng } from "./raster.mjs";
17
25
 
@@ -25,24 +33,91 @@ export function slug(s) {
25
33
  .slice(0, 40);
26
34
  }
27
35
 
28
- function gitCommit(cwd) {
36
+ /**
37
+ * @param {string[]} args
38
+ * @param {string} cwd
39
+ * @returns {string | null} git's output; null outside a repository or without git
40
+ */
41
+ function git(args, cwd) {
42
+ // The repository is the one holding `cwd`, not one named by the caller's
43
+ // environment: inside a git hook GIT_DIR and friends point at the hook's
44
+ // repository, which would answer for a source file outside it.
45
+ const env = { ...process.env };
46
+ for (const k of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY"]) delete env[k];
29
47
  try {
30
- return execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
48
+ return execFileSync("git", args, { cwd, env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
31
49
  } catch {
32
50
  return null;
33
51
  }
34
52
  }
35
53
 
54
+ /**
55
+ * Where a source file stands in git: the short HEAD commit of the repository
56
+ * holding it, and whether the file differs from that commit (modified,
57
+ * staged, untracked or ignored: `git status --porcelain -- <file>` is not empty).
58
+ * Both null outside a git repository. Only the source file counts: modules a
59
+ * custom scene imports, the style file and the options file are not looked
60
+ * at (the input hash covers the style and the options).
61
+ * @param {string} file absolute path
62
+ * @returns {{ commit: string | null, dirty: boolean | null }}
63
+ */
64
+ export function sourceState(file) {
65
+ const cwd = dirname(file);
66
+ const commit = git(["rev-parse", "--short", "HEAD"], cwd)?.trim() || null;
67
+ if (!commit) return { commit: null, dirty: null };
68
+ const status = git(["status", "--porcelain", "--untracked-files=all", "--ignored", "--", basename(file)], cwd);
69
+ return { commit, dirty: status == null ? null : status.trim() !== "" };
70
+ }
71
+
72
+ /**
73
+ * The files the manifest.json already in `out` lists, relative to `out`:
74
+ * what the previous export there wrote. Empty when there is none, or it is
75
+ * not motion-kit's or cannot be read. Entries that would leave `out` are
76
+ * ignored.
77
+ * @param {string} out
78
+ * @returns {string[]}
79
+ */
80
+ function previousFiles(out) {
81
+ let manifest;
82
+ try {
83
+ manifest = JSON.parse(readFileSync(join(out, "manifest.json"), "utf8"));
84
+ } catch {
85
+ return [];
86
+ }
87
+ if (manifest?.tool !== "motion-kit" || !Array.isArray(manifest.files)) return [];
88
+ /** @type {unknown[]} */
89
+ const listed = manifest.files.flatMap((/** @type {any} */ f) => [f?.svg, f?.png]);
90
+ return listed.filter((p) => typeof p === "string" && p !== "" && !isAbsolute(p) && !normalize(p).split(sep).includes("..")).map(String);
91
+ }
92
+
93
+ /**
94
+ * @param {string} dir
95
+ * @returns {string[]} every file under `dir`, relative to it, "/"-separated
96
+ */
97
+ function listFiles(dir) {
98
+ return readdirSync(dir, { recursive: true, withFileTypes: true })
99
+ .filter((d) => d.isFile())
100
+ .map((d) => relative(dir, join(d.parentPath, d.name)).split(sep).join("/"))
101
+ .sort();
102
+ }
103
+
36
104
  /**
37
105
  * @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
106
+ * @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
107
+ * phone: the same scene built for the `tall` format (what a phone shows), or
108
+ * why it could not be built; the contact sheet's phone row shows it.
109
+ * format, locale, options: what the scene was built with, for the manifest
110
+ * (a custom module's scene options change its frames, so they are hashed).
111
+ * warn: told about files in `out` that no export wrote (default console.warn).
39
112
  */
40
- export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version }) {
113
+ 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) }) {
41
114
  mkdirSync(out, { recursive: true });
115
+ const previous = previousFiles(out);
42
116
  const opts = { standalone: true, style, theme, background };
43
117
  const files = [];
44
- const write = async (name, t, kind, label) => {
45
- const svg = renderSvg(scene, t, opts);
118
+ let phoneError = phone?.error;
119
+ const write = async (name, t, kind, label, from = scene) => {
120
+ const svg = renderSvg(from, t, opts);
46
121
  writeFileSync(join(out, `${name}.svg`), svg);
47
122
  const entry = { kind, t: Math.round(t * 1000) / 1000, label, svg: `${name}.svg` };
48
123
  if (png) {
@@ -63,48 +138,92 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
63
138
  if (i < scene.steps.length - 1) await write(`qc/${n}-after`, s.at + 0.2, "after", s.label);
64
139
  }
65
140
  }
141
+ if (phone?.scene) {
142
+ mkdirSync(join(out, "qc"), { recursive: true });
143
+ const last = phone.scene.steps[phone.scene.steps.length - 1];
144
+ // loadScene never calls frame(), so a custom scene can still fail here.
145
+ try {
146
+ await write("qc/phone", phone.scene.duration, "phone", last.label, phone.scene);
147
+ } catch (e) {
148
+ phoneError = e instanceof Error ? e.message : String(e);
149
+ }
150
+ }
66
151
  const inputHash = createHash("sha256")
67
152
  .update(sourceFile ? readFileSync(sourceFile) : scene.frame.toString())
68
153
  .update(JSON.stringify(style ?? "neutral"))
154
+ .update(JSON.stringify(options ?? null))
69
155
  .digest("hex")
70
156
  .slice(0, 16);
157
+ const source = sourceFile ? sourceState(sourceFile) : { commit: null, dirty: null };
71
158
  const manifest = {
72
159
  tool: "motion-kit",
73
160
  version,
74
161
  scene: scene.id,
75
162
  type: scene.type ?? "custom",
76
- format: scene.format ?? null,
77
- locale: scene.locale ?? null,
163
+ format: scene.format ?? format ?? null,
164
+ locale: scene.locale ?? locale ?? null,
165
+ options: options ?? null,
78
166
  width: scene.width,
79
167
  height: scene.height,
80
168
  duration: Math.round(scene.duration * 1000) / 1000,
81
169
  style: style?.name ?? "neutral",
82
170
  theme,
83
171
  inputHash,
84
- sourceCommit: sourceFile ? gitCommit(join(sourceFile, "..")) : null,
172
+ sourceCommit: source.commit,
173
+ sourceDirty: source.dirty,
85
174
  render: { png, scale: png ? scale : null, background, qc },
86
175
  files,
87
176
  };
177
+
178
+ // Replace the previous export: remove what it wrote that this one did not.
179
+ // The new manifest is published only afterwards, so a removal that fails
180
+ // leaves the old one listing the stale files for the retry.
181
+ const written = new Set(["manifest.json", "index.html", ...files.flatMap((f) => (f.png ? [f.svg, f.png] : [f.svg]))]);
182
+ const root = realpathSync(out);
183
+ for (const p of previous) {
184
+ if (written.has(p)) continue;
185
+ const target = join(out, p);
186
+ // A directory symlinked out of `out` must not lead the removal elsewhere.
187
+ let parent;
188
+ try {
189
+ parent = realpathSync(dirname(target));
190
+ } catch {
191
+ continue; // its folder is gone, so is the file
192
+ }
193
+ if (parent !== root && !parent.startsWith(root + sep)) {
194
+ warn(`motion-kit export: did not remove ${p}: it resolves outside ${out}`);
195
+ continue;
196
+ }
197
+ rmSync(target, { force: true });
198
+ }
88
199
  writeFileSync(join(out, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
89
- writeFileSync(join(out, "index.html"), contactSheet(scene, files, theme, style));
200
+ writeFileSync(join(out, "index.html"), contactSheet(scene, files, theme, style, phoneError));
201
+ const qcDir = join(out, "qc");
202
+ if (existsSync(qcDir) && readdirSync(qcDir).length === 0) rmdirSync(qcDir);
203
+ const unknown = listFiles(out).filter((p) => !written.has(p));
204
+ if (unknown.length) warn(`motion-kit export: left ${unknown.length} file(s) in ${out} that no export wrote: ${unknown.join(", ")}`);
90
205
  return manifest;
91
206
  }
92
207
 
93
- function contactSheet(scene, files, theme, style) {
208
+ function contactSheet(scene, files, theme, style, phoneError) {
94
209
  const bg = style?.[theme]?.bg ?? (theme === "dark" ? "#0f1115" : "#ffffff");
95
210
  const card = (f) =>
96
211
  `<figure><img src="${f.svg}" alt=""><figcaption>${f.kind} · ${f.t}s · ${escapeHtml(f.label)}</figcaption></figure>`;
97
212
  const steps = files.filter((f) => f.kind === "step");
98
- const qcs = files.filter((f) => f.kind !== "step");
213
+ const qcs = files.filter((f) => f.kind === "before" || f.kind === "after");
214
+ const tall = files.find((f) => f.kind === "phone");
215
+ const phoneRow = tall
216
+ ? `<div class="grid phone">${card(tall)}</div>`
217
+ : `<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
218
  return `<!doctype html><meta charset="utf-8"><title>${escapeHtml(scene.title)} · contact sheet</title>
100
219
  <style>body{font:14px system-ui;margin:24px;background:#e5e7eb}h2{margin:24px 0 8px}
101
220
  .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:12px}
102
221
  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>
222
+ figcaption{font-size:12px;color:#6b7280;margin-top:4px}.phone figure{width:fit-content}.phone img{width:360px}</style>
104
223
  <h1>${escapeHtml(scene.title)}</h1><p>${escapeHtml(scene.id)} · ${scene.width}×${scene.height} · ${scene.duration.toFixed(2)} s · ${theme}</p>
105
224
  <h2>Steps (what a slide shows)</h2><div class="grid">${steps.map(card).join("")}</div>
106
225
  ${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><div class="grid phone">${steps.slice(-1).map(card).join("")}</div>
226
+ <h2>Phone size (tall layout, 360 px wide)</h2>${phoneRow}
108
227
  <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
228
  }
110
229
 
package/lib/gate.mjs ADDED
@@ -0,0 +1,90 @@
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 for the pairs every scene draws
10
+ * (G12, CONTRAST_PAIRS), once.
11
+ * - Every file × format (all of FORMATS unless given) × locale passes
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 `en` for a module.
15
+ * - A file that cannot be read, parsed or built is a failure for that file
16
+ * only; the remaining files are still checked.
17
+ */
18
+ import { readFileSync } from "node:fs";
19
+ import { FORMATS } from "../runtime/scene.mjs";
20
+ import { checkContrast } from "../runtime/style.mjs";
21
+ import { checkScene } from "./check.mjs";
22
+ import { isModule, loadScene } from "./load.mjs";
23
+
24
+ /** @param {unknown} e */
25
+ const message = (e) => (e instanceof Error ? e.message : String(e));
26
+
27
+ /**
28
+ * Locales a spec's strings carry: every key of an object whose keys are all
29
+ * locale tags (`en`, `nl`, `pt-BR`) with string values. `["en"]` if none.
30
+ * @param {unknown} spec
31
+ * @returns {string[]}
32
+ */
33
+ export function detectLocales(spec) {
34
+ const found = new Set();
35
+ /** @param {unknown} v */
36
+ const walk = (v) => {
37
+ if (Array.isArray(v)) v.forEach(walk);
38
+ else if (v && typeof v === "object") {
39
+ const entries = Object.entries(v);
40
+ if (entries.length && entries.every(([k, x]) => /^[a-z]{2}(-[A-Z]{2})?$/.test(k) && typeof x === "string")) entries.forEach(([k]) => found.add(k));
41
+ else entries.forEach(([, x]) => walk(x));
42
+ }
43
+ };
44
+ walk(spec);
45
+ return found.size ? [...found] : ["en"];
46
+ }
47
+
48
+ /**
49
+ * @param {string[]} files specs (.json) and custom modules (.mjs)
50
+ * @param {{ formats?: string[], locales?: string[], style?: any, options?: import("./load.mjs").OptionsSource, log?: (line: string) => void, error?: (line: string) => void }} [o]
51
+ * @returns {Promise<number>} failures (0 = the gate passes)
52
+ */
53
+ export async function checkFiles(files, { formats, locales, style, options, log = console.log, error = console.error } = {}) {
54
+ let bad = 0;
55
+ for (const p of checkContrast(style)) {
56
+ bad++;
57
+ error(`✗ style: ${p}`);
58
+ }
59
+ for (const file of files) {
60
+ const module = isModule(file);
61
+ let fileLocales = locales?.length ? locales : ["en"];
62
+ if (!locales?.length && !module) {
63
+ try {
64
+ fileLocales = detectLocales(JSON.parse(readFileSync(file, "utf8")));
65
+ } catch (e) {
66
+ bad++;
67
+ error(`✗ ${file}: ${message(e)}`);
68
+ continue;
69
+ }
70
+ }
71
+ for (const format of formats?.length ? formats : Object.keys(FORMATS)) {
72
+ for (const locale of fileLocales) {
73
+ try {
74
+ const sceneOptions = module && options ? await options({ format, locale }) : undefined;
75
+ const { scene } = await loadScene(file, { format, locale, options: sceneOptions });
76
+ const r = checkScene(scene, { style });
77
+ if (r.ok) log(`✓ ${file} · ${format} · ${locale} · ${scene.duration.toFixed(2)} s · ${scene.steps.length} steps`);
78
+ else {
79
+ bad++;
80
+ error(`✗ ${file} · ${format} · ${locale}\n - ${r.problems.join("\n - ")}`);
81
+ }
82
+ } catch (e) {
83
+ bad++;
84
+ error(`✗ ${file} · ${format} · ${locale}: ${message(e)}`);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ return bad;
90
+ }