@liqweed/motion-kit 0.4.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 (38) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +13 -5
  4. package/adapters/element/README.md +5 -0
  5. package/adapters/page/README.md +5 -0
  6. package/cli/motion-kit.mjs +9 -3
  7. package/docs/spec/technique.md +93 -30
  8. package/examples/custom-pulse.scene.mjs +3 -0
  9. package/examples/incident.json +18 -0
  10. package/examples/web-stack.json +17 -0
  11. package/lib/build.mjs +1 -1
  12. package/lib/check.mjs +207 -16
  13. package/lib/export.mjs +104 -7
  14. package/lib/gate.mjs +5 -3
  15. package/package.json +6 -3
  16. package/runtime/kit.mjs +2 -2
  17. package/runtime/links.mjs +314 -0
  18. package/runtime/parts.mjs +15 -0
  19. package/runtime/patch.mjs +297 -0
  20. package/runtime/player.mjs +5 -1
  21. package/runtime/scene.mjs +3 -1
  22. package/runtime/style.mjs +62 -16
  23. package/runtime/types/hub-spoke.mjs +2 -2
  24. package/runtime/types/index.mjs +4 -0
  25. package/runtime/types/sequence.mjs +2 -2
  26. package/runtime/types/stack.mjs +227 -0
  27. package/runtime/types/timeline.mjs +405 -0
  28. package/skills/animated-diagram/SKILL.md +27 -6
  29. package/skills/animated-diagram/references/custom-scenes.md +6 -1
  30. package/skills/animated-diagram/references/interactivity.md +111 -6
  31. package/skills/animated-diagram/references/qc.md +3 -0
  32. package/skills/animated-diagram/references/scene-types.md +45 -2
  33. package/skills/animated-diagram/references/styles.md +45 -5
  34. package/skills/animated-diagram/references/technique.md +9 -4
  35. package/skills/motion-render/SKILL.md +24 -6
  36. package/skills/motion-render/references/formats.md +8 -8
  37. package/skills/project-logo/SKILL.md +15 -4
  38. package/styles/neutral.json +2 -2
package/lib/check.mjs CHANGED
@@ -4,11 +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
8
  *
9
9
  * Over files, formats and locales (the CLI and the vendored gate): lib/gate.mjs.
10
10
  */
11
11
  import { renderSvg } from "../runtime/scene.mjs";
12
+ import { checkContrast } from "../runtime/style.mjs";
12
13
 
13
14
  const SAMPLES = 120;
14
15
 
@@ -34,12 +35,175 @@ export function wellFormed(svg) {
34
35
  return null;
35
36
  }
36
37
 
37
- 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 } = {}) {
38
199
  const problems = [];
39
- const render = (t) => renderSvg(scene, t);
40
- 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;
41
202
 
42
- // 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;
43
207
  for (let i = 0; i <= samples; i++) {
44
208
  const t = at(i);
45
209
  const a = render(t);
@@ -49,17 +213,37 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
49
213
  const long = a.match(/-?\d+\.\d{5,}/);
50
214
  if (long) problems.push(`unrounded number ${long[0]} at t=${t.toFixed(3)} (use num())`);
51
215
  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?\(/);
54
- if (lit) problems.push(`colour literal "${lit[0]}" at t=${t.toFixed(3)} (use tok())`);
216
+ const lit = findColourLiteral(frame);
217
+ if (lit) problems.push(`colour literal ${lit} at t=${t.toFixed(3)} (use tok())`);
55
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
+ }
56
232
  if (problems.length > 12) break;
57
233
  }
58
234
 
59
- // 2. Settled steps: nothing moves at a step's time.
60
- for (const s of scene.steps) {
61
- const before = render(Math.max(0, s.at - 0.001));
62
- 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
+ }
63
247
  }
64
248
 
65
249
  // 3. Builds up and finishes.
@@ -74,26 +258,33 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
74
258
 
75
259
  // 5. Every step label is visible in the final frame (escaped form), unless
76
260
  // the scene declares narrative steps (stepLabelsInFrame: false).
77
- 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;");
78
262
  const plain = lastFrame.replace(/<\/tspan><tspan[^>]*>/g, " ").replace(/<[^>]+>/g, "\u0000");
79
263
  for (const s of scene.stepLabelsInFrame === false ? [] : scene.steps) {
80
264
  const words = escd(s.label).split(/\s+/);
81
265
  if (!words.every((w) => plain.includes(w.replace(/\/$/, "")))) problems.push(`step label "${s.label}" not found in the final frame`);
82
266
  }
83
267
 
84
- // 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).
85
270
  const src = scene.frame.toString();
86
- 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");
87
272
 
88
273
  // 7. Every id comes from the instance prefix, so two instances on a page
89
274
  // never share one: render with two prefixes and look for common ids.
90
275
  const fixed = new Set();
91
276
  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]));
277
+ const ids = (/** @type {string} */ prefix) => new Set([...renderSvg(scene, at(i), { idPrefix: prefix }).matchAll(/\sid="([^"]*)"/g)].map((m) => m[1]));
93
278
  const second = ids("mk-gate-b");
94
279
  for (const id of ids("mk-gate-a")) if (second.has(id)) fixed.add(id);
95
280
  }
96
281
  for (const id of fixed) problems.push(`fixed id "${id}": build ids from frame(t, { idPrefix }), e.g. \`\${idPrefix}-${id}\``);
97
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
+ }
288
+
98
289
  return { ok: problems.length === 0, problems };
99
290
  }
package/lib/export.mjs CHANGED
@@ -8,11 +8,18 @@
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
  */
12
19
  import { createHash } from "node:crypto";
13
20
  import { execFileSync } from "node:child_process";
14
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
- 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";
16
23
  import { renderSvg } from "../runtime/scene.mjs";
17
24
  import { svgToPng } from "./raster.mjs";
18
25
 
@@ -26,24 +33,86 @@ export function slug(s) {
26
33
  .slice(0, 40);
27
34
  }
28
35
 
29
- 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];
30
47
  try {
31
- 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"] });
32
49
  } catch {
33
50
  return null;
34
51
  }
35
52
  }
36
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
+
37
104
  /**
38
105
  * @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>}} 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
40
107
  * phone: the same scene built for the `tall` format (what a phone shows), or
41
108
  * why it could not be built; the contact sheet's phone row shows it.
42
109
  * format, locale, options: what the scene was built with, for the manifest
43
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).
44
112
  */
45
- export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version, phone, format, locale, options }) {
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) }) {
46
114
  mkdirSync(out, { recursive: true });
115
+ const previous = previousFiles(out);
47
116
  const opts = { standalone: true, style, theme, background };
48
117
  const files = [];
49
118
  let phoneError = phone?.error;
@@ -85,6 +154,7 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
85
154
  .update(JSON.stringify(options ?? null))
86
155
  .digest("hex")
87
156
  .slice(0, 16);
157
+ const source = sourceFile ? sourceState(sourceFile) : { commit: null, dirty: null };
88
158
  const manifest = {
89
159
  tool: "motion-kit",
90
160
  version,
@@ -99,12 +169,39 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
99
169
  style: style?.name ?? "neutral",
100
170
  theme,
101
171
  inputHash,
102
- sourceCommit: sourceFile ? gitCommit(join(sourceFile, "..")) : null,
172
+ sourceCommit: source.commit,
173
+ sourceDirty: source.dirty,
103
174
  render: { png, scale: png ? scale : null, background, qc },
104
175
  files,
105
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
+ }
106
199
  writeFileSync(join(out, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
107
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(", ")}`);
108
205
  return manifest;
109
206
  }
110
207
 
package/lib/gate.mjs CHANGED
@@ -6,9 +6,11 @@
6
6
  *
7
7
  * checkFiles(files, { formats, locales, style, options }) → number of failures
8
8
  *
9
- * - The style must pass the contrast check (G12).
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. Locales: the given ones; else, for a spec, every locale its
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
12
14
  * strings carry, and `en` for a module.
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.
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqweed/motion-kit",
3
- "version": "0.4.0",
3
+ "version": "0.5.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",
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
- "gate": "npm run -s typecheck && npm run -s versions && npm test && npm run -s check && npm run -s media:check && npm run -s site"
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
  });