@liqweed/motion-kit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@
7
7
  "name": "motion-kit",
8
8
  "source": "./",
9
9
  "description": "animated-diagram, motion-render and project-logo skills and the motion-kit runtime/CLI",
10
- "version": "0.3.0"
10
+ "version": "0.4.0"
11
11
  }
12
12
  ]
13
13
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "motion-kit",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Deterministic animated diagrams: scenes as pure functions of time for live pages, Slidev, slide frames, baked SVG and video; plus project logos/icons.",
5
5
  "author": { "name": "Ophir Radnitz" },
6
6
  "repository": "https://github.com/liqweed/motion-kit",
package/README.md CHANGED
@@ -92,10 +92,47 @@ The skills look for this clone at `~/workspace/motion-kit` first (it has
92
92
  node cli/motion-kit.mjs vendor <repo>/components/motion-kit --adapter slidev # or astro / page / element
93
93
  ```
94
94
 
95
- Copies `runtime/`, the adapter, `lib/check.mjs` and `LICENSE`; writes a gate
96
- script and `MOTION_KIT_VERSION`. Don't edit vendored files; change motion-kit
97
- and re-vendor. Vendoring keeps consumer CI
98
- self-contained (no install step, no network).
95
+ Copies `runtime/`, the adapter, the gate (`lib/check.mjs`, `lib/gate.mjs`,
96
+ `lib/load.mjs`) and `LICENSE`; writes `check.mjs` and `MOTION_KIT_VERSION`.
97
+ Don't edit vendored files; change motion-kit and re-vendor. Vendoring keeps
98
+ consumer CI self-contained (no install step, no network): the vendored gate
99
+ runs the same checks as `motion-kit check`.
100
+
101
+ ```bash
102
+ node src/motion-kit/check.mjs src/diagrams/*.json src/diagrams/*.scene.mjs \
103
+ --locale en --locale nl --style src/brand/motion-style.json --options src/diagrams/labels.mjs
104
+ ```
105
+
106
+ ### Astro
107
+
108
+ ```bash
109
+ node cli/motion-kit.mjs vendor <site>/src/motion-kit --adapter astro
110
+ ```
111
+
112
+ ```astro
113
+ ---
114
+ import AnimatedDiagram from "../motion-kit/adapter/AnimatedDiagram.astro";
115
+ import spec from "../diagrams/order-flow.json";
116
+ import brandStyle from "../brand/motion-style.json"; // token data, as `--style` reads it
117
+ import { dictionary } from "../i18n"; // your site's own text, keyed by locale
118
+ const lang = Astro.currentLocale ?? "en";
119
+ const t = dictionary[lang];
120
+ ---
121
+ <AnimatedDiagram spec={spec} format="wide" locale="nl" class="hidden lg:block" />
122
+ <AnimatedDiagram spec={spec} format="tall" locale="nl" class="lg:hidden" />
123
+
124
+ <!-- A custom scene module, its text from the page's dictionary -->
125
+ <AnimatedDiagram module="/src/diagrams/flow.scene.mjs" options={{ labels: t.flow }}
126
+ format="wide" locale={lang} theme="light" style={brandStyle} id="flow" />
127
+ ```
128
+
129
+ The server render is the player's first state: the final frame, the step list
130
+ and the style's colours, with the controls in place, so the diagram is complete
131
+ without JavaScript and mounting causes no layout shift. `theme` fixes light or
132
+ dark; `style` is token data. Page scripts reach a player through its root
133
+ element's `controller` (set on mount; `motion-ready` announces it), and can
134
+ address steps by id (`controller.playToStep("payment")`). All props are listed in the adapter's
135
+ header comment.
99
136
 
100
137
  ### Plain HTML and framework-independent custom element
101
138
 
@@ -123,9 +160,17 @@ for inline specs, styles, lifecycle and error handling.
123
160
 
124
161
  Deterministic bytes · settled step frames · rounded numbers · token-only colours ·
125
162
  escaped labels · labels fit their budget in every locale · holds the final frame ·
126
- ≤ ~8–10 s · no clock or randomness in scenes. See
163
+ ≤ ~8–10 s · no clock or randomness in scenes · ids from the instance prefix. See
127
164
  `skills/animated-diagram/references/technique.md`.
128
165
 
166
+ ## Contributing, changes and stability
167
+
168
+ - [CONTRIBUTING.md](CONTRIBUTING.md): setup, the gate and hooks, commits,
169
+ change notes, adding a scene type.
170
+ - [CHANGELOG.md](CHANGELOG.md): what each release changed.
171
+ - [docs/stability.md](docs/stability.md): the public API, what semver promises
172
+ for it, and how vendoring consumers learn about a new version.
173
+
129
174
  ## Licence and credits
130
175
 
131
176
  MIT, see [LICENSE](LICENSE). Keep the copied `LICENSE` file and the SPDX
@@ -4,52 +4,178 @@
4
4
  /**
5
5
  * motion-kit · Astro adapter (reference).
6
6
  *
7
- * Server-renders the FINAL frame (no-JS visitors, crawlers and reduced-motion
8
- * users get the complete diagram), then the client script mounts the live
9
- * player, which replays once when the diagram scrolls into view.
7
+ * Server-renders the player's first state: the FINAL frame, the step list and
8
+ * the style's colours, with the controls in place but inert. No-JS visitors,
9
+ * crawlers and reduced-motion users get the complete diagram, and mounting the
10
+ * live player moves nothing on the page. The player replays once when the
11
+ * diagram scrolls into view.
12
+ *
13
+ * A spec for a registered scene type:
10
14
  *
11
15
  * import AnimatedDiagram from "../motion-kit/adapter/AnimatedDiagram.astro";
12
16
  * import spec from "../diagrams/order-flow.json";
13
17
  * <AnimatedDiagram spec={spec} format="wide" locale="nl" class="hidden lg:block" />
14
18
  * <AnimatedDiagram spec={spec} format="tall" locale="nl" class="lg:hidden" />
15
19
  *
20
+ * A custom scene module, with options for its factory (text from the page's
21
+ * dictionary, a view). Modules live under src/ and end in .scene.mjs or
22
+ * .scene.js; name one by its path from the project root:
23
+ *
24
+ * <AnimatedDiagram module="/src/diagrams/flow.scene.mjs" options={{ labels: t.flow }}
25
+ * format="wide" locale={lang} theme="light" style={brand} id="flow" />
26
+ *
27
+ * Props:
28
+ * spec JSON spec for a registered scene type, or
29
+ * module path of a custom scene module, "/src/…/name.scene.mjs"
30
+ * options serializable options for the module's factory, passed unchanged
31
+ * (module only); the factory gets { ...options, format, locale, kit }
32
+ * format "16:9" | "4:3" | "1:1" | "9:16" | "wide" | "tall" (default "16:9")
33
+ * locale default "en"
34
+ * theme "light" | "dark"; default: follow prefers-color-scheme
35
+ * style token data (the shape `motion-kit --style` reads); default neutral
36
+ * id HTML id of the root element, capture-hook key and id prefix:
37
+ * letters, digits, "_" and "-", starting with a letter, used once
38
+ * per page; default: generated, unique on the page
39
+ * scrubber show a timeline scrubber (default false)
40
+ * labels UI strings: flat { play, pause, … } or keyed by locale
41
+ * class CSS classes for the root element
42
+ *
43
+ * Page scripts reach the live player through the root element: its
44
+ * `controller` property, set on mount, and the `motion-ready` event (bubbling,
45
+ * `detail.controller`), dispatched once the page's own scripts (and their
46
+ * DOMContentLoaded and astro:page-load handlers) have run; `motion-error`
47
+ * reports a failed mount. Use whichever comes first:
48
+ *
49
+ * const el = document.getElementById("flow");
50
+ * const go = (c) => c.playToStep("paid");
51
+ * el.controller ? go(el.controller) : el.addEventListener("motion-ready", (e) => go(e.detail.controller), { once: true });
52
+ *
16
53
  * Mount a wide and a tall instance and switch with CSS: display:none also
17
- * removes the hidden one from the accessibility tree and its autoplay observer.
18
- * Pass only serializable props (a spec, not a scene object).
54
+ * removes the hidden one from the accessibility tree and stops its clock.
55
+ * Every prop must be serializable (a spec or a module path, not a scene).
19
56
  */
20
- import { renderSvg } from "../runtime/scene.mjs";
57
+ import { sceneFromModule } from "../runtime/kit.mjs";
58
+ import { PLAYER_CSS, playerMarkup, themeCss } from "../runtime/player.mjs";
59
+ import { claimId, claimStylesheet, newPageState } from "../runtime/page.mjs";
21
60
  import { createScene } from "../runtime/types/index.mjs";
22
61
 
23
62
  interface Props {
24
- spec: Record<string, unknown>;
63
+ spec?: Record<string, unknown>;
64
+ module?: string;
65
+ options?: Record<string, unknown>;
25
66
  format?: string;
26
67
  locale?: string;
68
+ theme?: "light" | "dark";
69
+ /** Token data, `{ name?, font?, light?: {…}, dark?: {…} }`, or "neutral". */
70
+ style?: Record<string, unknown> | "neutral";
71
+ id?: string;
27
72
  class?: string;
28
73
  scrubber?: boolean;
29
- labels?: Record<string, string>;
74
+ /** Flat `{ play, pause, … }`, or a dictionary keyed by locale (`{ en: {…}, nl: {…} }`). */
75
+ labels?: Record<string, string | Record<string, string>>;
76
+ }
77
+ const { spec, module: modulePath, options, format = "16:9", locale = "en", theme, style, id: idProp, class: className, scrubber = false, labels } = Astro.props;
78
+ const fail = (message: string): never => {
79
+ throw new Error(`AnimatedDiagram: ${message}`);
80
+ };
81
+ if ((spec == null) === (modulePath == null)) fail('pass exactly one of spec (a JSON spec) or module (a path such as "/src/diagrams/flow.scene.mjs")');
82
+ if (spec && options) fail("options apply to custom scene modules; a spec takes none");
83
+ if (theme != null && theme !== "light" && theme !== "dark") fail(`theme must be "light" or "dark", got "${theme}"`);
84
+ if (typeof style === "string" && style !== "neutral") fail("style is token data (an object); use class for CSS");
85
+
86
+ const modules = import.meta.glob("/src/**/*.scene.{mjs,js}");
87
+ let scene;
88
+ if (spec) scene = createScene(spec, { format, locale });
89
+ else {
90
+ const load = modules[modulePath as string];
91
+ if (!load) fail(`no scene module at "${modulePath}". Modules live under src/ and end in .scene.mjs or .scene.js; found: ${Object.keys(modules).join(", ") || "none"}`);
92
+ const mod = (await load()) as { default: unknown };
93
+ scene = sceneFromModule(mod.default, { format, locale, options });
30
94
  }
31
- const { spec, format = "16:9", locale = "en", class: className, scrubber = false, labels } = Astro.props;
32
- const scene = createScene(spec, { format, locale });
33
- const fallback = renderSvg(scene, scene.duration, { live: true, idPrefix: `${scene.id}-ssr` });
95
+
96
+ // Per page: the ids in use and whether the player stylesheet is out yet.
97
+ const page = ((Astro.locals as Record<string, any>).__motionKit ??= newPageState());
98
+ const id = (() => {
99
+ try {
100
+ return claimId(page, idProp, scene.id);
101
+ } catch (error) {
102
+ return fail((error as Error).message);
103
+ }
104
+ })();
105
+ const css = claimStylesheet(page) ? `<style data-mk-player-css>${PLAYER_CSS}</style>` : "";
106
+ const tokens = `<style>${themeCss(`#${id}`, style, theme)}</style>`;
107
+ const markup = playerMarkup(scene, { id, style, theme, labels, locale, scrubber });
108
+ const config = JSON.stringify({ spec, module: modulePath, options, format, locale, theme, style, scrubber, labels });
34
109
  ---
35
110
 
36
- <div
37
- class:list={["mk-astro", className]}
38
- data-mk-spec={JSON.stringify(spec)}
39
- data-mk-opts={JSON.stringify({ format, locale, scrubber, labels })}
40
- set:html={fallback}
41
- />
111
+ <Fragment set:html={css + tokens} />
112
+ <div id={id} class:list={["mk-astro", "mk-player", className]} data-mk-astro={config} set:html={markup} />
42
113
 
43
114
  <script>
115
+ import { sceneFromModule } from "../runtime/kit.mjs";
44
116
  import { mountPlayer } from "../runtime/player.mjs";
45
117
  import { createScene } from "../runtime/types/index.mjs";
46
118
 
47
- for (const el of document.querySelectorAll<HTMLElement>("[data-mk-spec]")) {
48
- if (el.dataset.mkMounted) continue;
49
- el.dataset.mkMounted = "1";
50
- const spec = JSON.parse(el.dataset.mkSpec ?? "{}");
51
- const opts = JSON.parse(el.dataset.mkOpts ?? "{}");
52
- const scene = createScene(spec, { format: opts.format, locale: opts.locale });
53
- mountPlayer(el, scene, { scrubber: opts.scrubber, labels: opts.labels, id: `${scene.id}-${Math.random().toString(36).slice(2, 7)}` });
119
+ type Controller = ReturnType<typeof mountPlayer>;
120
+ type Root = HTMLElement & { controller?: Controller | null };
121
+ // The same modules the server render can name; each loads on demand.
122
+ const modules = import.meta.glob("/src/**/*.scene.{mjs,js}");
123
+ const mounted = new Set<Root>();
124
+
125
+ // Page scripts that come after this one must be able to listen: tell them
126
+ // once the document is parsed, in a task after the current one, so their
127
+ // DOMContentLoaded and astro:page-load handlers have run too.
128
+ const parsed = new Promise<void>((resolve) => {
129
+ const nav = performance.getEntriesByType?.("navigation")[0] as PerformanceNavigationTiming | undefined;
130
+ if (document.readyState === "complete" || (nav?.domContentLoadedEventStart ?? 0) > 0) return resolve();
131
+ document.addEventListener("DOMContentLoaded", () => resolve(), { once: true });
132
+ addEventListener("load", () => resolve(), { once: true });
133
+ });
134
+ function announce(el: Root, type: "motion-ready" | "motion-error", detail: object) {
135
+ void parsed.then(() =>
136
+ setTimeout(() => {
137
+ if (el.isConnected && mounted.has(el)) el.dispatchEvent(new CustomEvent(type, { bubbles: true, detail }));
138
+ }, 0),
139
+ );
140
+ }
141
+
142
+ async function mount(el: Root) {
143
+ mounted.add(el);
144
+ try {
145
+ const cfg = JSON.parse(el.dataset.mkAstro ?? "{}");
146
+ let scene;
147
+ if (cfg.spec) scene = createScene(cfg.spec, { format: cfg.format, locale: cfg.locale });
148
+ else {
149
+ const load = modules[cfg.module];
150
+ if (!load) throw new Error(`motion-kit: no scene module at "${cfg.module}"`);
151
+ const mod = (await load()) as { default: unknown };
152
+ // A page swap during the import released this element.
153
+ if (!mounted.has(el) || !el.isConnected) return;
154
+ scene = sceneFromModule(mod.default, { format: cfg.format, locale: cfg.locale, options: cfg.options });
155
+ }
156
+ const controller = mountPlayer(el, scene, { id: el.id, style: cfg.style, theme: cfg.theme, scrubber: cfg.scrubber, labels: cfg.labels, locale: cfg.locale });
157
+ el.controller = controller;
158
+ announce(el, "motion-ready", { controller });
159
+ } catch (error) {
160
+ // The server-rendered diagram stays as it is.
161
+ announce(el, "motion-error", { error });
162
+ console.error(error);
163
+ }
164
+ }
165
+ function mountAll() {
166
+ for (const el of document.querySelectorAll<Root>("[data-mk-astro]")) if (!mounted.has(el)) void mount(el);
54
167
  }
168
+ function teardown() {
169
+ for (const el of mounted) {
170
+ el.controller?.destroy();
171
+ el.controller = null;
172
+ }
173
+ mounted.clear();
174
+ }
175
+
176
+ mountAll();
177
+ // Astro view transitions swap the DOM without reloading the page: release
178
+ // the old players, then mount the new page's diagrams.
179
+ document.addEventListener("astro:before-swap", teardown);
180
+ document.addEventListener("astro:page-load", mountAll);
55
181
  </script>
@@ -29,7 +29,7 @@ then `src`. Escape JSON for its HTML context (in a script, escape `<` as
29
29
 
30
30
  Observed attributes are `spec`, `src`, `format` (default `16:9`), `locale`
31
31
  (default `en`), `theme` (`light`/`dark`, absent follows the OS), and
32
- `style-spec` (JSON visual-style tokens, default neutral). The standard `style`
32
+ `style-spec` (JSON visual-style tokens, default neutral), and `labels` (JSON UI strings: flat, or keyed by locale). The standard `style`
33
33
  attribute remains CSS, for example `style="max-width: 960px"`. Attribute
34
34
  changes rebuild the player. Inline script text changes require a remount
35
35
  (remove and reinsert the element).
@@ -15,7 +15,7 @@ let nextId = 0;
15
15
 
16
16
  export class MotionDiagram extends HTMLElement {
17
17
  static get observedAttributes() {
18
- return ["spec", "src", "format", "locale", "theme", "style-spec"];
18
+ return ["spec", "src", "format", "locale", "theme", "style-spec", "labels"];
19
19
  }
20
20
 
21
21
  constructor() {
@@ -100,12 +100,13 @@ export class MotionDiagram extends HTMLElement {
100
100
  if (!this.isConnected || revision !== this._revision) return;
101
101
  const theme = this.getAttribute("theme");
102
102
  if (theme && theme !== "light" && theme !== "dark") throw new Error('motion-diagram: theme must be "light" or "dark"');
103
- const scene = createScene(spec, { format: this.getAttribute("format") ?? "16:9", locale: this.getAttribute("locale") ?? "en" });
103
+ const locale = this.getAttribute("locale") ?? "en";
104
+ const scene = createScene(spec, { format: this.getAttribute("format") ?? "16:9", locale });
104
105
  const style = JSON.parse(this.getAttribute("style-spec") ?? "null");
105
106
  player = this.ownerDocument.createElement("div");
106
107
  // Mount inside a child so player CSS cannot overwrite the host's CSS.
107
108
  this.appendChild(player);
108
- this.controller = mountPlayer(player, scene, { id: this._id, style, theme: theme || undefined });
109
+ this.controller = mountPlayer(player, scene, { id: this._id, style, theme: theme || undefined, locale, labels: JSON.parse(this.getAttribute("labels") ?? "null") ?? undefined });
109
110
  this._player = player;
110
111
  this._fallback.hidden = true;
111
112
  this.dispatchEvent(new CustomEvent("motion-ready", { detail: { controller: this.controller } }));
@@ -14,8 +14,9 @@ motion-kit build diagram.json --out diagram.html [--format wide] [--locale nl] [
14
14
  `motion-kit bake` (zero-JS animated SVG) or step PNGs via `image-preview`.
15
15
  - **Static hosting / file://:** works as is.
16
16
 
17
- The final frame is pre-rendered into the markup, so the diagram is complete
18
- before JS runs. The player replays once on scroll-into-view, shows pause/play,
17
+ The player's first state (final frame, step list, colours) is pre-rendered
18
+ into the markup, so the diagram is complete before JS runs and nothing moves
19
+ when the player mounts. The player replays once on scroll-into-view, shows pause/play,
19
20
  step buttons, a scrubber and captions, and respects `prefers-reduced-motion`
20
21
  and `prefers-color-scheme`.
21
22
 
@@ -102,6 +102,12 @@ watch(stepIndex, (next, prev) => {
102
102
  }
103
103
  });
104
104
 
105
+ // A replaced scene keeps the same step index but may time that step differently.
106
+ watch(scene, (next) => {
107
+ cancelAnimationFrame(raf);
108
+ t.value = next.steps[Math.min(stepIndex.value, next.steps.length - 1)].at;
109
+ });
110
+
105
111
  onMounted(() => {
106
112
  if (info) clicks.register(id, info);
107
113
  if (animated.value && props.intro && stepIndex.value === 0) animate(0, scene.value.steps[0].at);
@@ -111,6 +117,12 @@ onUnmounted(() => {
111
117
  clicks?.unregister(id);
112
118
  });
113
119
 
120
+ const announcement = computed(() => {
121
+ const steps = scene.value.steps;
122
+ const i = Math.min(stepIndex.value, steps.length - 1);
123
+ const s = steps[i];
124
+ return `${i + 1}. ${s.detail ? `${s.label}: ${s.detail}` : s.label}`;
125
+ });
114
126
  const dark = computed(() => (props.theme ? props.theme === "dark" : isDark.value));
115
127
  const markup = computed(() => renderSvg(scene.value, t.value, { style: style.value, live: true, idPrefix: id }));
116
128
  const vars = computed(() => `${cssVars(style.value, dark.value ? "dark" : "light")};--mk-max-h:${props.maxHeight}`);
@@ -119,14 +131,26 @@ const vars = computed(() => `${cssVars(style.value, dark.value ? "dark" : "light
119
131
  <template>
120
132
  <figure class="mk-slidev" :style="vars" :data-mk-step="stepIndex + 1">
121
133
  <div class="mk-slidev-stage" v-html="markup" />
134
+ <!-- Clicks advance steps; say which one, like the live player does. -->
135
+ <div class="mk-slidev-live" role="status" aria-live="polite" aria-atomic="true">{{ announcement }}</div>
122
136
  </figure>
123
137
  </template>
124
138
 
125
139
  <style scoped>
126
140
  .mk-slidev {
141
+ position: relative;
127
142
  margin: 0;
128
143
  width: 100%;
129
144
  }
145
+ .mk-slidev-live {
146
+ position: absolute;
147
+ width: 1px;
148
+ height: 1px;
149
+ margin: -1px;
150
+ overflow: hidden;
151
+ clip: rect(0, 0, 0, 0);
152
+ white-space: nowrap;
153
+ }
130
154
  .mk-slidev-stage :deep(svg) {
131
155
  display: block;
132
156
  width: 100%;
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * motion-kit CLI.
4
4
  *
5
- * motion-kit check <scene...> [--format F] [--locale L] gate (all formats/locales by default)
5
+ * motion-kit check <scene...> [--format F]… [--locale L]… [--style S] gate (all formats/locales by default)
6
6
  * motion-kit build <scene> --out x.html [--format F] [--locale L] [--style S] [--no-scrubber] [--no-heading]
7
7
  * motion-kit export <scene> --out dir [--format F] [--locale L] [--style S] [--theme light|dark] [--png] [--scale 2] [--qc] [--background]
8
8
  * motion-kit bake <scene> --out x.svg [--fps 15] [--theme ...] [--style S]
@@ -12,6 +12,9 @@
12
12
  * motion-kit formats | types
13
13
  *
14
14
  * <scene> is a spec (.json, any registered type) or a custom module (.mjs).
15
+ * --options O passes scene options to a custom module's factory, unchanged:
16
+ * inline JSON ('{"view":"short"}'), a .json file, or an .mjs module whose
17
+ * default export is the options or ({ format, locale }) => options.
15
18
  */
16
19
  import { cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
20
  import { dirname, join, resolve } from "node:path";
@@ -19,13 +22,13 @@ import { fileURLToPath } from "node:url";
19
22
  import { parseArgs } from "node:util";
20
23
  import { bake, bakeStats } from "../runtime/bake.mjs";
21
24
  import { FORMATS } from "../runtime/scene.mjs";
22
- import { checkContrast } from "../runtime/style.mjs";
23
25
  import { SCENE_TYPES } from "../runtime/types/index.mjs";
24
26
  import { checkScene } from "../lib/check.mjs";
27
+ import { checkFiles } from "../lib/gate.mjs";
25
28
  import { buildHtml } from "../lib/build.mjs";
26
29
  import { writeIconSet } from "../lib/icon.mjs";
27
30
  import { exportSteps } from "../lib/export.mjs";
28
- import { loadScene, loadStyle } from "../lib/load.mjs";
31
+ import { isModule, loadOptions, loadScene, loadStyle } from "../lib/load.mjs";
29
32
  import { rasterizer } from "../lib/raster.mjs";
30
33
  import { probe, renderVideo, videoContactSheet } from "../lib/video.mjs";
31
34
 
@@ -36,9 +39,10 @@ const { values: a, positionals } = parseArgs({
36
39
  allowPositionals: true,
37
40
  options: {
38
41
  out: { type: "string", short: "o" },
39
- format: { type: "string", short: "f" },
40
- locale: { type: "string", short: "l" },
42
+ format: { type: "string", short: "f", multiple: true },
43
+ locale: { type: "string", short: "l", multiple: true },
41
44
  style: { type: "string", short: "s" },
45
+ options: { type: "string" },
42
46
  theme: { type: "string", default: "light" },
43
47
  png: { type: "boolean", default: false },
44
48
  scale: { type: "string", default: "2" },
@@ -73,7 +77,15 @@ async function main() {
73
77
  return;
74
78
  }
75
79
  const style = loadStyle(a.style);
76
- const opts = { format: a.format ?? "16:9", locale: a.locale ?? "en" };
80
+ // Commands other than check build one format and locale: the last one given.
81
+ const format = a.format?.at(-1);
82
+ const where = { format: format ?? "16:9", locale: a.locale?.at(-1) ?? "en" };
83
+ const optionsFor = await loadOptions(a.options);
84
+ /** Scene options for one scene file at `at`; specs take none. @param {string} file @param {{format: string, locale: string}} at */
85
+ const sceneOpts = async (file, at = where) => {
86
+ if (optionsFor && !isModule(file)) fail(`${cmd}: --options apply to custom scene modules, not to the spec ${file}`);
87
+ return { ...at, options: optionsFor ? await optionsFor(at) : undefined };
88
+ };
77
89
 
78
90
  switch (cmd) {
79
91
  case "formats":
@@ -84,38 +96,17 @@ async function main() {
84
96
  return;
85
97
  case "check": {
86
98
  if (!args.length) fail("check: give at least one scene file");
87
- const styleProblems = checkContrast(style);
88
- for (const p of styleProblems) console.error(`✗ style: ${p}`);
89
- let bad = styleProblems.length;
90
- for (const file of args) {
91
- const formats = a.format ? [a.format] : Object.keys(FORMATS);
92
- const raw = file.endsWith(".json") ? JSON.parse(readFileSync(file, "utf8")) : null;
93
- const locales = a.locale ? [a.locale] : raw ? detectLocales(raw) : ["en"];
94
- for (const format of formats) {
95
- for (const locale of locales) {
96
- try {
97
- const { scene } = await loadScene(file, { format, locale });
98
- const r = checkScene(scene);
99
- if (r.ok) console.log(`✓ ${file} · ${format} · ${locale} · ${scene.duration.toFixed(2)} s · ${scene.steps.length} steps`);
100
- else {
101
- bad++;
102
- console.error(`✗ ${file} · ${format} · ${locale}\n - ${r.problems.join("\n - ")}`);
103
- }
104
- } catch (e) {
105
- bad++;
106
- console.error(`✗ ${file} · ${format} · ${locale}: ${e instanceof Error ? e.message : e}`);
107
- }
108
- }
109
- }
110
- }
99
+ const bad = await checkFiles(args, { formats: a.format, locales: a.locale, style, options: optionsFor });
111
100
  if (bad) process.exit(1);
112
101
  return;
113
102
  }
114
103
  case "build": {
115
- const loaded = await loadScene(need(args[0], "<scene>"), opts);
104
+ const file = need(args[0], "<scene>");
105
+ const sopts = await sceneOpts(file);
106
+ const loaded = await loadScene(file, sopts);
116
107
  const r = checkScene(loaded.scene);
117
108
  if (!r.ok) fail(`scene fails the gate:\n - ${r.problems.join("\n - ")}`);
118
- const html = buildHtml(loaded, { style, ...opts, scrubber: !a["no-scrubber"], heading: !a["no-heading"] });
109
+ const html = buildHtml(loaded, { style, ...where, options: sopts.options, scrubber: !a["no-scrubber"], heading: !a["no-heading"] });
119
110
  if (/<\/script/i.test(html.slice(html.indexOf("<script>") + 8, html.lastIndexOf("</script>")))) fail("bundled code contains </script>");
120
111
  const out = need(a.out, "--out");
121
112
  mkdirSync(dirname(resolve(out)), { recursive: true });
@@ -125,16 +116,29 @@ async function main() {
125
116
  }
126
117
  case "export": {
127
118
  const file = need(args[0], "<scene>");
128
- const { scene } = await loadScene(file, opts);
119
+ const sopts = await sceneOpts(file);
120
+ const { scene } = await loadScene(file, sopts);
129
121
  const r = checkScene(scene);
130
122
  if (!r.ok) fail(`scene fails the gate:\n - ${r.problems.join("\n - ")}`);
131
123
  if (a.png && !(await rasterizer())) fail("--png needs @resvg/resvg-js or Chrome");
132
- const m = await exportSteps(scene, { out: need(a.out, "--out"), style, theme: a.theme, png: a.png, scale: Number(a.scale), qc: a.qc, background: a.background, sourceFile: resolve(file), version: VERSION });
124
+ // The contact sheet's phone row shows the tall layout, as a phone does.
125
+ /** @type {{ scene?: any, error?: string }} */
126
+ const phone = {};
127
+ if (where.format === "tall") phone.scene = scene;
128
+ else {
129
+ try {
130
+ phone.scene = (await loadScene(file, await sceneOpts(file, { ...where, format: "tall" }))).scene;
131
+ } catch (e) {
132
+ phone.error = e instanceof Error ? e.message : String(e);
133
+ }
134
+ }
135
+ const m = await exportSteps(scene, { out: need(a.out, "--out"), style, theme: a.theme, png: a.png, scale: Number(a.scale), qc: a.qc, background: a.background, sourceFile: resolve(file), version: VERSION, phone, ...sopts });
133
136
  console.log(`wrote ${m.files.length} frames + index.html + manifest.json to ${a.out}`);
134
137
  return;
135
138
  }
136
139
  case "bake": {
137
- const { scene } = await loadScene(need(args[0], "<scene>"), opts);
140
+ const file = need(args[0], "<scene>");
141
+ const { scene } = await loadScene(file, await sceneOpts(file));
138
142
  const svg = bake(scene, { fps: Number(a.fps ?? 15), style, theme: a.theme, background: a.background });
139
143
  const out = need(a.out, "--out");
140
144
  writeFileSync(out, svg);
@@ -143,7 +147,8 @@ async function main() {
143
147
  return;
144
148
  }
145
149
  case "video": {
146
- const { scene } = await loadScene(need(args[0], "<scene>"), opts);
150
+ const file = need(args[0], "<scene>");
151
+ const { scene } = await loadScene(file, await sceneOpts(file));
147
152
  const out = need(a.out, "--out");
148
153
  const r = await renderVideo(scene, {
149
154
  out,
@@ -161,7 +166,8 @@ async function main() {
161
166
  return;
162
167
  }
163
168
  case "icon": {
164
- const { scene } = await loadScene(need(args[0], "<scene>"), { ...opts, format: a.format ?? "1:1" });
169
+ const file = need(args[0], "<scene>");
170
+ const { scene } = await loadScene(file, await sceneOpts(file, { ...where, format: format ?? "1:1" }));
165
171
  const r = checkScene(scene);
166
172
  if (!r.ok) fail(`scene fails the gate:\n - ${r.problems.join("\n - ")}`);
167
173
  const png = !a["no-png"];
@@ -180,7 +186,7 @@ async function main() {
180
186
  const adapter = join(ROOT, "adapters", a.adapter);
181
187
  cpSync(adapter, join(dir, "adapter"), { recursive: true });
182
188
  mkdirSync(join(dir, "lib"), { recursive: true });
183
- cpSync(join(ROOT, "lib", "check.mjs"), join(dir, "lib", "check.mjs"));
189
+ for (const f of ["check.mjs", "gate.mjs", "load.mjs"]) cpSync(join(ROOT, "lib", f), join(dir, "lib", f));
184
190
  writeFileSync(join(dir, "check.mjs"), VENDOR_CHECK);
185
191
  writeFileSync(join(dir, "MOTION_KIT_VERSION"), `motion-kit ${VERSION}\nadapter ${a.adapter}\nvendored from liqweed/motion-kit; do not edit here, re-vendor instead.\n`);
186
192
  console.log(`vendored runtime + ${a.adapter} adapter (motion-kit ${VERSION}) into ${dir}`);
@@ -192,48 +198,40 @@ async function main() {
192
198
  }
193
199
 
194
200
  const VENDOR_CHECK = `#!/usr/bin/env node
195
- // motion-kit gate for vendored copies: node check.mjs <spec.json...> [--format F]
196
- // Checks every listed spec in every format (or --format) and every locale it contains.
197
- import { readFileSync } from "node:fs";
198
- import { checkScene } from "./lib/check.mjs";
199
- import { FORMATS } from "./runtime/scene.mjs";
200
- import { createScene } from "./runtime/types/index.mjs";
201
+ // motion-kit gate for vendored copies: the same checks as \`motion-kit check\` (lib/gate.mjs).
202
+ //
203
+ // node check.mjs <scene.json|scene.mjs …> [--format F]… [--locale L]… [--style style.json] [--options O]
204
+ //
205
+ // Every format unless --format; for a spec every locale its strings carry, for
206
+ // a custom module "en", unless --locale. The style (neutral by default) must
207
+ // pass the contrast check. --options passes scene options to custom modules:
208
+ // a .json file, inline JSON, or an .mjs module exporting ({ format, locale }) => options.
209
+ // Exits 1 if anything fails; a file that cannot be loaded fails on its own.
210
+ import { parseArgs } from "node:util";
211
+ import { checkFiles } from "./lib/gate.mjs";
212
+ import { loadOptions, loadStyle } from "./lib/load.mjs";
201
213
 
202
- const args = process.argv.slice(2);
203
- const fi = args.indexOf("--format");
204
- const formats = fi >= 0 ? [args.splice(fi, 2)[1]] : Object.keys(FORMATS);
205
- let bad = 0;
206
- for (const file of args) {
207
- const spec = JSON.parse(readFileSync(file, "utf8"));
208
- const locales = new Set();
209
- JSON.stringify(spec, (k, v) => {
210
- if (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length && Object.keys(v).every((x) => /^[a-z]{2}$/.test(x))) Object.keys(v).forEach((l) => locales.add(l));
211
- return v;
212
- });
213
- for (const format of formats) {
214
- for (const locale of locales.size ? locales : ["en"]) {
215
- try {
216
- const r = checkScene(createScene(spec, { format, locale }));
217
- if (r.ok) console.log(\`✓ \${file} · \${format} · \${locale}\`);
218
- else { bad++; console.error(\`✗ \${file} · \${format} · \${locale}\\n - \${r.problems.join("\\n - ")}\`); }
219
- } catch (e) { bad++; console.error(\`✗ \${file} · \${format} · \${locale}: \${e.message}\`); }
220
- }
221
- }
214
+ const { values, positionals } = parseArgs({
215
+ allowPositionals: true,
216
+ options: {
217
+ format: { type: "string", multiple: true },
218
+ locale: { type: "string", multiple: true },
219
+ style: { type: "string" },
220
+ options: { type: "string" },
221
+ help: { type: "boolean", short: "h" },
222
+ },
223
+ });
224
+ if (values.help || !positionals.length) {
225
+ console.log("usage: node check.mjs <scene.json|scene.mjs …> [--format F]… [--locale L]… [--style style.json] [--options O]");
226
+ process.exit(values.help ? 0 : 1);
222
227
  }
223
- process.exit(bad ? 1 : 0);
224
- `;
225
-
226
- function detectLocales(spec) {
227
- const found = new Set();
228
- const walk = (v) => {
229
- if (v && typeof v === "object" && !Array.isArray(v)) {
230
- const keys = Object.keys(v);
231
- if (keys.length && keys.every((k) => /^[a-z]{2}(-[A-Z]{2})?$/.test(k) && typeof v[k] === "string")) keys.forEach((k) => found.add(k));
232
- else Object.values(v).forEach(walk);
233
- } else if (Array.isArray(v)) v.forEach(walk);
234
- };
235
- walk(spec);
236
- return found.size ? [...found] : ["en"];
228
+ try {
229
+ const bad = await checkFiles(positionals, { formats: values.format, locales: values.locale, style: loadStyle(values.style), options: await loadOptions(values.options) });
230
+ process.exit(bad ? 1 : 0);
231
+ } catch (e) {
232
+ console.error(\`✗ \${e instanceof Error ? e.message : e}\`);
233
+ process.exit(1);
237
234
  }
235
+ `;
238
236
 
239
237
  main().catch((e) => fail(e.stack ?? e.message));