@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.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  title: motion-kit technique — normative specification
3
3
  status: draft
4
- last_updated: 2026-11-15
4
+ last_updated: 2026-11-16
5
5
  ---
6
6
 
7
7
  # motion-kit technique — normative specification
@@ -35,18 +35,27 @@ A scene is a plain object (`runtime/scene.mjs:1-18`).
35
35
  | `duration` | number, s | MUST | Time of the final state. |
36
36
  | `title` | string | MUST | Accessible name (`<title>`) [throws if empty]. |
37
37
  | `description` | string | MUST | Accessible description (`<desc>`) [throws if empty]. |
38
- | `steps` | `{at, label, detail?}[]` | MUST | ≥ 1 step; `at` strictly increasing; `at ≤ duration` (+1e-9); every `label` non-empty [throws] (`runtime/scene.mjs:46-53`). The last step is the finished diagram. |
39
- | `frame(t)` | `(number) → string` | MUST | Inner SVG markup at `t` (§2). |
38
+ | `steps` | `{at, label, detail?, id?}[]` | MUST | ≥ 1 step; `at` strictly increasing; `at ≤ duration` (+1e-9); every `label` non-empty; an `id`, if present, is a non-empty string unique within the scene [throws] (`validateScene`). The last step is the finished diagram. Page scripts address steps by `id` (§10.2); scene types copy a spec node's, hub's or spoke's `id`. |
39
+ | `frame(t, ctx)` | `(number, {idPrefix}) → string` | MUST | Inner SVG markup at `t` (§2). `ctx.idPrefix` is unique to the rendered instance; every id the frame defines (clip paths, gradients, masks, markers, filters) MUST start with it, as `${idPrefix}-name` [gate] G14. A frame that defines no ids MAY ignore `ctx`. |
40
40
  | `stepLabelsInFrame` | boolean | MAY | `false` declares narrative steps whose labels are not drawn; exempts the scene from gate rule G10 (`lib/check.mjs:74`; used by `examples/custom-pulse.scene.mjs:137`, `brand/logo.scene.mjs:108`). |
41
41
  | `type`, `format`, `locale` | string | MAY | Set by scene types; recorded in the export manifest (`lib/export.mjs:75-77`). |
42
42
 
43
43
  - A scene MUST be produced by either a registered scene type —
44
44
  `createScene(spec, {format, locale})` (`runtime/types/index.mjs:19-23`) — or a
45
- custom module whose default export is `(opts) → scene`
46
- (`lib/load.mjs:29-32`). Both paths run `validateScene`.
47
- - A custom module MUST import only from `runtime/` with single-line relative
48
- `import { … } from "./x.mjs";` statements and use only the export forms the
49
- inliner supports, or `build` throws (`lib/bundle.mjs:8-11,33,59`).
45
+ custom module whose default export is `(opts) → scene`, called by
46
+ `sceneFromModule` (`runtime/kit.mjs`) with
47
+ `opts = { ...options, format, locale, kit }`. `options` are the caller's
48
+ serializable scene options, passed unchanged; option names `format`,
49
+ `locale` and `kit` throw. `kit` is the flat exports of the `motion`, `svg`, `style`, `scene` and `wrap` runtime modules (`KIT`); it has no `createScene`, scene types or player. Both paths
50
+ run `validateScene`. The CLI (`--options`), the vendored gate and the Astro
51
+ adapter call `sceneFromModule`, so one module with the same options, format
52
+ and locale gives the same scene everywhere. A `build` page calls the factory
53
+ with the same object, its `kit` being the bundled runtime, after the CLI has
54
+ built the scene once through `sceneFromModule`.
55
+ - A custom module MUST take the runtime from `kit`, or import only from
56
+ `runtime/` with single-line relative `import { … } from "./x.mjs";`
57
+ statements and use only the export forms the inliner supports, or `build`
58
+ throws (`lib/bundle.mjs:8-11,33,59`).
50
59
  - `detail` SHOULD hold sentences; labels stay short (§7). `detail` feeds the
51
60
  player caption and screen-reader list (§10.2).
52
61
 
@@ -299,28 +308,38 @@ Every target goes through this one function. It MUST emit `<svg>` with
299
308
  | `theme` | `light`/`dark` for resolution or inline vars. |
300
309
  | `live` | Omits inline vars; the container supplies them. |
301
310
  | `background` | Paints a full-size `bg` rect behind the diagram. |
302
- | `idPrefix` | MUST be unique per page when several diagrams share it. |
311
+ | `idPrefix` | Prefix for every id in the output: `<title>`/`<desc>`, and the scene's own through `frame(t, { idPrefix })`. Made a safe id token (`safeId`: letters, digits, `_`, `-`). MUST be unique per page when several diagrams share it. |
303
312
 
304
313
  ### 10.2 Live player (`runtime/player.mjs`)
305
314
 
306
315
  | Requirement | Source |
307
316
  |---|---|
308
317
  | MUST touch the DOM only when mounted; scenes stay pure, the player owns the clock (`requestAnimationFrame`, wall time). | `runtime/player.mjs` (`mountPlayer`, `tick`), `AGENTS.md` |
309
- | Initial state MUST be the final frame; a server/no-JS fallback SHOULD put the final frame in the container. | `runtime/player.mjs` (initial-state block), `lib/build.mjs:25`, `adapters/astro/AnimatedDiagram.astro:31` |
310
- | Autoplay `visible` (default): plays once from 0 when ≥ 40 % in view, then holds; `none` disables. MUST NOT loop. | `runtime/player.mjs` (`autoplay`, `autoplayPending`) |
311
- | Play/pause MUST always be present when motion can play (WCAG 2.2.2); label shows Play/Pause/Replay. | `runtime/player.mjs` (`playBtn`, `draw`) |
318
+ | Initial state MUST be the final frame. A server/no-JS fallback SHOULD be `playerMarkup(scene, { id, … })` inside a `.mk-player` container, with `PLAYER_CSS` in a `style[data-mk-player-css]` and the tokens from `themeCss(selector, style, theme)`: the markup the player builds, with the controls `inert`. The step list and the colours then exist without JavaScript, and mounting moves nothing. A plain final-frame SVG MAY be used instead. | `runtime/player.mjs` (`view`, `playerMarkup`, `themeCss`), `lib/build.mjs`, `adapters/astro/AnimatedDiagram.astro`, `test/player.test.mjs` |
319
+ | Autoplay `visible` (default): plays once from 0 when ≥ 40 % of the diagram, or ≥ 40 % of the viewport's height, is in view (decided from the intersection, not `isIntersecting` alone), then holds; `none` disables. MUST NOT loop. | `runtime/player.mjs` (`shown`, `THRESHOLDS`) |
320
+ | While a playing diagram does not intersect the viewport (scrolled away, `display: none`), its clock MUST stop and no frame be drawn; when it intersects again, playback resumes from the same time. Visibility is observed until `destroy()`. | `runtime/player.mjs` (`onVisibility`, `run`) |
321
+ | Play/pause MUST always be present when motion can play (WCAG 2.2.2); label shows Play/Pause/Replay. | `runtime/player.mjs` (`playLabel`, `draw`) |
322
+ | Every control (buttons, scrubber) MUST be at least 44 × 44 px. The caption and the play button MUST keep the size of their longest content, so playback does not shift the layout. | `PLAYER_CSS` (`.mk-btn`, `.mk-scrub`, `.mk-caption`, `.mk-play`) |
312
323
  | One `<button>` per step, labelled `N. label`; activating it jumps by default. `animateSteps: true` opts buttons and keyboard navigation into `playToStep`. `aria-current="step"` marks the active step. | `runtime/player.mjs` |
313
324
  | Optional range scrubber (`aria-label`, default "Timeline"); input pauses and seeks. | `runtime/player.mjs` (`options.scrubber`) |
314
325
  | Caption shows the active step's `detail` and is `aria-hidden`; a visually hidden ordered list of all steps (`label: detail`) MUST be present for screen readers. | `runtime/player.mjs` (`caption`, `sr`) |
315
- | Keyboard on the focusable stage: ←/→ step, Home/End first/last, Space play/pause. | `runtime/player.mjs` (`stage.tabIndex`, `keydown` handler) |
316
- | Visible focus style for every control. | `runtime/player.mjs` (`.mk-btn:focus-visible` rule) |
326
+ | Keyboard on the focusable stage, a `role="group"` named by the scene title and described by a visually hidden hint (`labels.keys`): ←/→ step, Home/End first/last, Space play/pause. Every element with `tabindex="0"` has a role. | `runtime/player.mjs` (`view`, `keydown` handler) |
327
+ | Visible focus style for the stage and every control. | `PLAYER_CSS` (`:focus-visible` rule) |
317
328
  | `prefers-reduced-motion: reduce`: final frame, no autoplay, no play button, Space ignored. | `runtime/player.mjs` (`reduced`) |
318
- | Theme: `options.theme`, else follows `prefers-color-scheme` live. | `runtime/player.mjs` (`applyTheme`, `themeQuery`) |
319
- | `playToStep(i)` MUST play forward from the current time, clamp to the target step's exact `at` and hold. Backward, same-time and reduced-motion calls MUST jump. Indices are zero-based; invalid indices throw `RangeError`. Retargeting replaces the target; `play()` continues to duration; `seek(t)` cancels playback. | `runtime/player.mjs`, `test/player.test.mjs` |
329
+ | Theme: `options.theme`, else follows `prefers-color-scheme` live. Tokens MUST be set one custom property at a time, keeping the container's other inline CSS. | `runtime/player.mjs` (`applyTheme`, `themeQuery`) |
330
+ | The player stylesheet MUST be in the document whenever a player mounts: it is added to `<head>` unless a `style[data-mk-player-css]` is present, so a page swap that removed it cannot leave players unstyled. `injectCss: false` opts out. | `runtime/player.mjs` (`ensureStyle`), `test/player.test.mjs` |
331
+ | Ids: each player renders with its own prefix, `options.id`, else `scene.id` plus a per-page counter, so two players of one scene share no ids. | `runtime/player.mjs` (`prefix`) |
332
+ | `playToStep(ref)` MUST play forward from the current time, clamp to the target step's exact `at` and hold. Backward, same-time and reduced-motion calls MUST jump. `seekStep(ref)` jumps. `ref` is a zero-based index or a step `id`; an invalid index or unknown id throws `RangeError` (`stepIndex`). Retargeting replaces the target; `play()` continues to duration; `seek(t)` cancels playback. | `runtime/player.mjs`, `runtime/scene.mjs`, `test/player.test.mjs` |
320
333
  | `destroy()` MUST cancel the animation frame, disconnect visibility observation, remove theme listening and remove this controller's capture entry. | `runtime/player.mjs`, `test/player.test.mjs` |
321
334
  | **Capture hook**: the controller `{seek, play, pause, seekStep, playToStep, destroy, time, scene}` MUST be exposed at `globalThis.__motionKit[options.id ?? scene.id]`. | `runtime/player.mjs` |
322
335
 
323
- UI strings MAY be localized via `options.labels`.
336
+ UI strings MAY be localized via `options.labels`: a flat `{ play, pause, replay, steps, scrubber, keys }` object (`steps` names the controls group, `keys` is the stage's keyboard hint), or a dictionary keyed by locale (`{ en: {…}, nl: {…} }`) resolved with `options.locale`, then its language subtag, then `en`, then the first entry. Missing keys keep the English defaults (`resolveLabels`, `runtime/player.mjs`).
337
+
338
+ Keyboard step changes (←/→/Home/End) MUST be announced through a visually hidden `role="status"` polite live region (`N. label: detail`); autoplay, pointer and scrubber use stay silent.
339
+
340
+ `mountPlayer` MUST release any player already mounted on the same container (`destroy()`), so remounting never leaks clocks, observers or capture entries. The build output passes `locale` through, so label dictionaries resolve there too; the Slidev adapter announces each click's step through the same kind of live region.
341
+
342
+ The Astro adapter mounts each diagram once, tears the players down on `astro:before-swap` and mounts the new page's diagrams on `astro:page-load`. Its root element exposes the controller as `.controller` from mount, and dispatches `motion-ready` (bubbling, `detail.controller`) or `motion-error` (`detail.error`) once the page's own scripts and their `DOMContentLoaded` and `astro:page-load` handlers have run, so a script placed after the diagram can still listen. Its `id` prop sets the element id, the capture-hook key and the id prefix; it MUST be a safe id token, used once per page, or the build fails.
324
343
 
325
344
  ### 10.2.1 Custom element (`adapters/element/motion-diagram.mjs`)
326
345
 
@@ -343,8 +362,10 @@ UI strings MAY be localized via `options.labels`.
343
362
  - MUST be one document with the runtime inlined by `lib/bundle.mjs`, no
344
363
  external scripts, stylesheets or fetches (`test/cli.test.mjs:31-37`), so it
345
364
  works under `connect-src 'none'` and from `file://`.
346
- - MUST pre-render the final frame (`lib/build.mjs:25`) and set `<html lang>`
347
- to the scene locale (`:31-33`).
365
+ - MUST pre-render the player's first state (`playerMarkup`, `PLAYER_CSS`,
366
+ `themeCss`) and set `<html lang>` to the scene locale (`lib/build.mjs`).
367
+ - A custom module is built with the caller's `--options` and `kit`: every
368
+ runtime module is a bundle entry, so the `MotionKit` global is the kit.
348
369
  - The CLI MUST refuse a scene that fails the gate (`cli/motion-kit.mjs:112-113`)
349
370
  and bundled code containing `</script>` (`:115`).
350
371
  - The inlined runtime MUST render the same bytes as Node
@@ -361,6 +382,8 @@ UI strings MAY be localized via `options.labels`.
361
382
  animation delayed `0.3 s + start`; the last slice holds (`mk-hold`, fill
362
383
  forwards) (`:35-47`). Plays once; MUST hold the final frame.
363
384
  - Under `prefers-reduced-motion: reduce` only the final slice is visible (`:39`).
385
+ - Slices share one document: a slice whose markup defines ids is rendered with
386
+ its own prefix (`<idPrefix>-<n>`, base `mk-bake` or `options.idPrefix`).
364
387
  - One theme per file; for theme-following embeds publish a light and dark file
365
388
  (`README.md:21-29`, `scripts/render-media.sh`).
366
389
  - Size grows with fps × duration; README use SHOULD lower fps to 10–12.
@@ -377,11 +400,15 @@ UI strings MAY be localized via `options.labels`.
377
400
  makes the canvas opaque (transparent by default).
378
401
  - `--qc`: frames at `max(0, at − 0.2)` and `at + 0.2` (not after the last step)
379
402
  under `qc/` (`lib/export.mjs:58-65`).
380
- - `index.html` contact sheet: steps, QC row, a 360 px phone row and the human
381
- review checklist (`lib/export.mjs:93-108`).
403
+ - `index.html` contact sheet: steps, QC row, a phone row and the human review
404
+ checklist (`lib/export.mjs`, `contactSheet`). The phone row MUST show the
405
+ scene built for the `tall` format, in the same locale, options, style and
406
+ theme, at 360 px (`qc/phone.svg`, manifest `kind: "phone"`); when the tall
407
+ layout cannot be built, it shows the exported frame and says why.
382
408
  - `manifest.json` MUST contain no timestamps: tool, version, scene, type,
383
- format, locale, size, duration, style, theme, a 16-hex input hash
384
- (source file + style), source commit, render settings, file list
409
+ format, locale, scene options, size, duration, style, theme, a 16-hex input
410
+ hash (source file + style + scene options), source commit, render settings,
411
+ file list
385
412
  (`lib/export.mjs:66-88`). Two exports of the same inputs MUST be equal
386
413
  (`test/cli.test.mjs:20-30`).
387
414
 
@@ -405,21 +432,34 @@ UI strings MAY be localized via `options.labels`.
405
432
  itself (`:67-72`); forward by one click animates from the previous step's
406
433
  `at` to the next, any other move seeks (`:93-100`); print/export, overview
407
434
  and reduced motion show the settled step frame (`:65`).
408
- - **Astro** (`adapters/astro/AnimatedDiagram.astro`): server-renders the final
409
- frame and mounts the player; props MUST be serializable (a spec, not a scene).
435
+ - **Astro** (`adapters/astro/AnimatedDiagram.astro`): server-renders the
436
+ player's first state (§10.2) and mounts the player. It takes a `spec`, or a
437
+ custom module by path (`module`, a `/src/…/*.scene.mjs|js` file found with
438
+ `import.meta.glob`, loaded on demand in the browser) with its `options`;
439
+ `theme` (`light`/`dark`, else the system), `style` (token data), `id`,
440
+ `scrubber`, `labels`, `class`. Props MUST be serializable (a spec or a module
441
+ path, not a scene). The player stylesheet is emitted once per page; each
442
+ instance carries its tokens and a page-unique id (`mk-<scene.id>-<n>` unless
443
+ `id` is given). It fails the build for a missing module, options with a spec,
444
+ or an invalid theme.
410
445
  - **Vendor** (`cli/motion-kit.mjs`, `vendor` command): copies `runtime/`, one
411
- adapter, `lib/check.mjs` and the full MIT `LICENSE`; writes a spec-only gate
412
- script and `MOTION_KIT_VERSION`. Consumers MUST retain `LICENSE` and the
446
+ adapter, `lib/check.mjs`, `lib/gate.mjs`, `lib/load.mjs` and the full MIT
447
+ `LICENSE`; writes `check.mjs`, which runs the same gate as `motion-kit
448
+ check` (§11) with `--format`, `--locale`, `--style` and `--options`, and
449
+ `MOTION_KIT_VERSION`. Consumers MUST retain `LICENSE` and the
413
450
  SPDX headers when redistributing vendored files. Vendored files MUST NOT
414
451
  be edited in the consumer.
415
452
 
416
453
  ## 11. The gate
417
454
 
418
- `checkScene(scene)` (`lib/check.mjs:33-84`) samples 121 evenly spaced times
419
- (`SAMPLES = 120`, `:9`) and stops collecting after 13 problems (`:51`).
420
- `motion-kit check` runs it for every file × format (all six unless `--format`)
421
- × locale (§7) and adds the style contrast check; it exits 1 on any failure or
422
- construction error (`cli/motion-kit.mjs:81-108`). `npm run gate` = unit tests +
455
+ `checkScene(scene)` (`lib/check.mjs`) samples 121 evenly spaced times
456
+ (`SAMPLES = 120`) and stops collecting after 13 problems.
457
+ `motion-kit check` and the vendored `check.mjs` both run `checkFiles`
458
+ (`lib/gate.mjs`): every file × format (all six unless `--format`, repeatable)
459
+ × locale (`--locale`, repeatable; else every locale a spec's strings carry, and
460
+ `en` for a module, §7), with `--options` for modules, plus the style contrast
461
+ check. A file that cannot be read, parsed or built fails on its own and the
462
+ remaining files are still checked; the exit code is 1 on any failure. `npm run gate` = unit tests +
423
463
  `check` over `examples/` and `brand/` (`package.json:15-18`).
424
464
 
425
465
  | ID | Rule | Code | Rationale |
@@ -427,7 +467,7 @@ construction error (`cli/motion-kit.mjs:81-108`). `npm run gate` = unit tests +
427
467
  | G1 | Rendering the same `t` twice MUST yield identical bytes. | `lib/check.mjs:41-42` | Determinism (T1/T2). Catches clocks/randomness and call-to-call state; cannot catch state that is consistent between two calls. |
428
468
  | G2 | Each sampled frame MUST be well-formed (balanced tags, no stray `<`, entities only `amp lt gt quot #39 #n`). | `:12-31,43-44` | Escaping failures and broken markup break every target. |
429
469
  | G3 | No number with ≥ 5 decimals in the full SVG. | `:45-46` | Rounding (T4). |
430
- | G4 | No `#hex`, `rgb(a)(`, `hsl(a)(` in `frame()` output. | `:47-49` | Token-only colours: themes and brand styles must work everywhere. |
470
+ | G4 | No `#hex`, `rgb(a)(`, `hsl(a)(` in `frame()` output; id references (`url(#…)`, `href="#…"`) are not colours. | `:47-49` | Token-only colours: themes and brand styles must work everywhere. |
431
471
  | G5 | No `NaN`, `undefined`, `Infinity` in `frame()` output. | `:50` | Silent geometry bugs. |
432
472
  | G6 | `render(at − 0.001) === render(at)` for every step. | `:55-58` | Settled step frames (§8). |
433
473
  | G7 | First frame ≠ last frame. | `:61-63` | Something must animate. |
@@ -435,8 +475,9 @@ construction error (`cli/motion-kit.mjs:81-108`). `npm run gate` = unit tests +
435
475
  | G9 | `duration ≤ 12` s. | `:68` | Explainer budget (see §12 D1). |
436
476
  | G10 | Every word of every step label (escaped, trailing `/` stripped) appears in the final frame's text, unless `stepLabelsInFrame === false`. | `:72-77` | Step buttons and slides refer to things the viewer can see. Word-level, so it does not prove the label is contiguous. |
437
477
  | G11 | `frame.toString()` MUST NOT contain `Date.now`, `new Date`, `Math.random`, `performance.now`. | `:80-81` | T1. Textual heuristic: helpers defined outside `frame` are not scanned. |
438
- | G12 | Style passes WCAG contrast in both themes. | `cli/motion-kit.mjs:83-85`, `runtime/style.mjs:114-134` | Legibility in light and dark. |
439
- | G13 | Scene construction succeeds for the format × locale (validation, fit, collisions, wrapping). | `cli/motion-kit.mjs:92-103` | Reject, don't invent: a broken picture never renders. |
478
+ | G12 | Style passes WCAG contrast in both themes. | `lib/gate.mjs`, `runtime/style.mjs` (`checkContrast`) | Legibility in light and dark. |
479
+ | G13 | Scene construction succeeds for the format × locale (validation, fit, collisions, wrapping). | `lib/gate.mjs` | Reject, don't invent: a broken picture never renders. |
480
+ | G14 | Rendered with two different `idPrefix` values, sampled frames share no `id`. | `lib/check.mjs` (rule 7) | Two instances on one page (wide and tall, or one diagram twice) must not share ids: `url(#x)` resolves to the first element with that id, and WCAG 2.1 SC 4.1.1 forbids duplicates. |
440
481
 
441
482
  The gate checks structure, not looks. Visual review (before/after frames,
442
483
  phone size, real-time playback, dark mode) is required by
@@ -458,8 +499,7 @@ Recorded, not resolved. Each needs an owner decision.
458
499
  | D7 | Style `radius` / `stroke` | Normalized (`runtime/style.mjs:63-64`) but never read; parts default to radius 10, stroke 2 (`runtime/parts.mjs:52,75`). | Documented as style fields (`styles.md:28-29`). |
459
500
  | D8 | Dark fallback | A style with no `dark` applies its **light** overrides to dark (`runtime/style.mjs:66`). | "Missing tokens fall back to neutral" (`styles.md:35`). |
460
501
  | D9 | Video frame reuse | PNGs are reused only when `t` repeats (lead and hold) (`lib/video.mjs:46`). | "Identical consecutive frames are rasterized once" (`skills/motion-render/references/video.md:9`). |
461
- | D10 | Capture-hook key | Key is `options.id ?? scene.id`, i.e. format-suffixed (`order-flow-16x9`); the Astro adapter appends a random suffix (`adapters/astro/AnimatedDiagram.astro:51`); the Slidev adapter exposes none. | `window.__motionKit[sceneId]` / `[id]` (`adapters/page/README.md:22`, `interactivity.md:14-15`). |
462
- | D11 | Vendored gate | `check.mjs` written by `vendor` handles `.json` only, skips the contrast check, and detects locales with `^[a-z]{2}$` (no region, no string-value test) (`cli/motion-kit.mjs:177-207`). | Implied parity with `motion-kit check` (`README.md:90-92`). |
502
+ | D10 | Capture-hook key | Key is `options.id ?? scene.id`, i.e. format-suffixed (`order-flow-16x9`); the Astro adapter uses its `id` prop or `mk-<scene.id>-<n>`; the Slidev adapter exposes none. | `window.__motionKit[sceneId]` / `[id]` (`adapters/page/README.md:22`, `interactivity.md`). |
463
503
  | D12 | Auto-fit maximum | Sequence 22 px, hub-spoke 20 px (`runtime/types/hub-spoke.mjs:97`). | "Fixed formats ≤ 22 px" without type distinction (`technique.md:90`); `formats.md:12` is correct. |
464
504
  | D13 | Timing budgets | `ENTRANCE_MAX` is exported but unused; stagger and entrance limits are not checked. | Listed as "Hard rules" (`skills/animated-diagram/SKILL.md:50`). |
465
- | D14 | Manifest reproducibility | `inputHash` covers the source file and style only, not the runtime; a runtime change keeps the hash while frames change (only `version` hints at it) (`lib/export.mjs:66-70`). | "A stale export is easy to spot" (`skills/motion-render/SKILL.md:66-68`). |
505
+ | D14 | Manifest reproducibility | `inputHash` covers the source file, style and scene options, not the runtime; a runtime change keeps the hash while frames change (only `version` hints at it) (`lib/export.mjs:66-70`). | "A stale export is easy to spot" (`skills/motion-render/SKILL.md:66-68`). |
package/lib/build.mjs CHANGED
@@ -2,32 +2,44 @@
2
2
  * motion-kit · build a self-contained interactive HTML file.
3
3
  *
4
4
  * One document, runtime inlined, no network requests: safe for Craft Pages
5
- * (connect-src 'none'), file:// and any static host. The final frame is
6
- * pre-rendered into the markup, so it reads correctly before (or without) JS.
5
+ * (connect-src 'none'), file:// and any static host. The player's first state
6
+ * (final frame, step list, colours) is pre-rendered into the markup, so it
7
+ * reads correctly before (or without) JS, and mounting moves nothing.
8
+ *
9
+ * A custom module gets its scene options and `kit` (every runtime export),
10
+ * as it does from the CLI.
7
11
  */
8
12
  import { fileURLToPath } from "node:url";
9
13
  import { bundle } from "./bundle.mjs";
10
14
  import { escapeHtml } from "./export.mjs";
11
- import { renderSvg } from "../runtime/scene.mjs";
15
+ import { PLAYER_CSS, playerMarkup, themeCss } from "../runtime/player.mjs";
12
16
  import { cssVars } from "../runtime/style.mjs";
13
17
 
14
18
  const RUNTIME = fileURLToPath(new URL("../runtime/", import.meta.url));
15
19
 
20
+ /** JSON for an inline script: `<` escaped, so no value can close the script element. */
21
+ const scriptJson = (/** @type {unknown} */ value) => JSON.stringify(value).replace(/</g, "\\u003c");
22
+
16
23
  /**
17
24
  * @param {import("./load.mjs").LoadedScene} loaded
18
- * @param {{style:import("../runtime/style.mjs").Style, format:string, locale:string, scrubber?:boolean, heading?:boolean, theme?:string, labels?:Record<string,string>}} o
25
+ * @param {{style:import("../runtime/style.mjs").Style, format:string, locale:string, scrubber?:boolean, heading?:boolean, theme?:string, labels?:Record<string,string|Record<string,string>>, options?:Record<string,unknown>}} o
26
+ * options: scene options for a custom module's factory
19
27
  */
20
28
  export function buildHtml(loaded, o) {
21
- const entries = [`${RUNTIME}types/index.mjs`, `${RUNTIME}scene.mjs`, `${RUNTIME}player.mjs`];
29
+ // Every runtime module is an entry, so the MotionKit global is the whole kit.
30
+ const entries = ["motion", "svg", "style", "wrap", "scene", "types/index", "player"].map((m) => `${RUNTIME}${m}.mjs`);
31
+ const runtimeCount = entries.length;
22
32
  if (loaded.kind === "module") entries.push(loaded.file);
23
- const code = bundle(entries);
33
+ // MotionKitRuntime is the runtime alone: a custom module's exports, spread
34
+ // after it into MotionKit, may reuse a runtime name without breaking `kit`.
35
+ const code = bundle(entries, { runtimeName: "MotionKitRuntime", runtimeCount });
24
36
  const { scene } = loaded;
25
- const fallback = renderSvg(scene, scene.duration, { style: o.style, live: true, idPrefix: "mk-fallback" });
37
+ const options = { style: o.style, scrubber: o.scrubber !== false, theme: o.theme, labels: o.labels, locale: o.locale };
38
+ const fallback = playerMarkup(scene, { ...options, id: "mk-fallback" });
26
39
  const make =
27
40
  loaded.kind === "spec"
28
- ? `MotionKit.createScene(${JSON.stringify(loaded.spec)}, ${JSON.stringify({ format: o.format, locale: o.locale })})`
29
- : `MotionKit.default(${JSON.stringify({ format: o.format, locale: o.locale })})`;
30
- const options = { style: o.style, scrubber: o.scrubber !== false, theme: o.theme, labels: o.labels };
41
+ ? `MotionKit.createScene(${scriptJson(loaded.spec)}, ${scriptJson({ format: o.format, locale: o.locale })})`
42
+ : `MotionKitRuntime.validateScene(MotionKit.default(Object.assign(${scriptJson(o.options ?? {})}, ${scriptJson({ format: o.format, locale: o.locale })}, { kit: MotionKitRuntime })))`;
31
43
  const lang = scene.locale ?? o.locale ?? "en";
32
44
  return `<!doctype html>
33
45
  <html lang="${escapeHtml(lang)}">
@@ -42,18 +54,20 @@ body{margin:0;padding:24px;background:var(--mk-bg);color:var(--mk-ink);font-fami
42
54
  main{max-width:${Math.max(scene.width, 360)}px;margin:0 auto}
43
55
  h1{font-size:20px;line-height:1.3;margin:0 0 4px}
44
56
  .lede{margin:0 0 16px;color:var(--mk-muted);font-size:15px;line-height:1.45}
57
+ ${themeCss("#mk", o.style, o.theme)}
45
58
  </style>
59
+ <style data-mk-player-css>${PLAYER_CSS}</style>
46
60
  </head>
47
61
  <body>
48
62
  <main>
49
63
  ${o.heading === false ? "" : `<h1>${escapeHtml(scene.title)}</h1>\n<p class="lede">${escapeHtml(scene.description)}</p>`}
50
- <div id="mk">${fallback}</div>
64
+ <div id="mk" class="mk-player">${fallback}</div>
51
65
  </main>
52
66
  <script>
53
67
  ${code}
54
68
  (function () {
55
69
  var scene = ${make};
56
- MotionKit.mountPlayer(document.getElementById("mk"), scene, ${JSON.stringify(options)});
70
+ MotionKitRuntime.mountPlayer(document.getElementById("mk"), scene, ${scriptJson(options)});
57
71
  })();
58
72
  </script>
59
73
  </body>
package/lib/bundle.mjs CHANGED
@@ -15,7 +15,11 @@ import { dirname, resolve } from "node:path";
15
15
 
16
16
  const IMPORT_RE = /^import\s*\{([^}]*)\}\s*from\s*["'](\.{1,2}\/[^"']+)["'];?\s*$/;
17
17
 
18
- export function bundle(entries, { globalName = "MotionKit" } = {}) {
18
+ /**
19
+ * @param {string[]} entries
20
+ * @param {{ globalName?: string, runtimeName?: string, runtimeCount?: number }} [o]
21
+ */
22
+ export function bundle(entries, { globalName = "MotionKit", runtimeName = "", runtimeCount = entries.length } = {}) {
19
23
  const order = [];
20
24
  const seen = new Map();
21
25
  function visit(file) {
@@ -64,5 +68,8 @@ export function bundle(entries, { globalName = "MotionKit" } = {}) {
64
68
  }
65
69
  const ids = entries.map((e) => visit(e));
66
70
  const merged = ids.map((id) => `...${id}`).join(", ");
67
- return `(() => {\n"use strict";\n${order.join("\n")}\nglobalThis.${globalName} = Object.freeze({ ${merged} });\n})();\n`;
71
+ // runtimeName: a second global of the first `runtimeCount` entries only, so a
72
+ // later entry's exports cannot shadow theirs.
73
+ const runtime = runtimeName ? `\nglobalThis.${runtimeName} = Object.freeze({ ${ids.slice(0, runtimeCount).map((id) => `...${id}`).join(", ")} });` : "";
74
+ return `(() => {\n"use strict";\n${order.join("\n")}\nglobalThis.${globalName} = Object.freeze({ ${merged} });${runtime}\n})();\n`;
68
75
  }
package/lib/check.mjs CHANGED
@@ -5,6 +5,8 @@
5
5
  * pass these before anything is exported or mounted.
6
6
  *
7
7
  * checkScene(scene) → { ok, problems: string[] }
8
+ *
9
+ * Over files, formats and locales (the CLI and the vendored gate): lib/gate.mjs.
8
10
  */
9
11
  import { renderSvg } from "../runtime/scene.mjs";
10
12
 
@@ -46,8 +48,9 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
46
48
  if (wf) problems.push(`malformed at t=${t.toFixed(3)}: ${wf}`);
47
49
  const long = a.match(/-?\d+\.\d{5,}/);
48
50
  if (long) problems.push(`unrounded number ${long[0]} at t=${t.toFixed(3)} (use num())`);
49
- const frame = scene.frame(Math.min(t, scene.duration));
50
- const lit = frame.match(/#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(/);
51
+ const frame = scene.frame(Math.min(t, scene.duration), { idPrefix: scene.id });
52
+ // References to ids (url(#x), href="#x") are not colours.
53
+ const lit = frame.replace(/url\(\s*#[^)]*\)|href="#[^"]*"/g, "").match(/#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(/);
51
54
  if (lit) problems.push(`colour literal "${lit[0]}" at t=${t.toFixed(3)} (use tok())`);
52
55
  if (/NaN|undefined|Infinity/.test(frame)) problems.push(`NaN/undefined/Infinity in frame at t=${t.toFixed(3)}`);
53
56
  if (problems.length > 12) break;
@@ -82,5 +85,15 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
82
85
  const src = scene.frame.toString();
83
86
  if (/Date\.now|new Date|Math\.random|performance\.now/.test(src)) problems.push("frame() reads the clock or randomness");
84
87
 
88
+ // 7. Every id comes from the instance prefix, so two instances on a page
89
+ // never share one: render with two prefixes and look for common ids.
90
+ const fixed = new Set();
91
+ for (let i = 0; i <= samples; i += 10) {
92
+ const ids = (prefix) => new Set([...renderSvg(scene, at(i), { idPrefix: prefix }).matchAll(/\sid="([^"]*)"/g)].map((m) => m[1]));
93
+ const second = ids("mk-gate-b");
94
+ for (const id of ids("mk-gate-a")) if (second.has(id)) fixed.add(id);
95
+ }
96
+ for (const id of fixed) problems.push(`fixed id "${id}": build ids from frame(t, { idPrefix }), e.g. \`\${idPrefix}-${id}\``);
97
+
85
98
  return { ok: problems.length === 0, problems };
86
99
  }
package/lib/export.mjs CHANGED
@@ -5,6 +5,7 @@
5
5
  * NN-<step>.svg standalone, tokens resolved (PowerPoint/Keynote take SVG)
6
6
  * NN-<step>.png with --png (Google Slides, Marp/Slidev, travelling decks)
7
7
  * qc/… with --qc: frames 0.2 s before and after every step
8
+ * qc/phone.svg the tall layout's final frame, for the phone row
8
9
  * index.html contact sheet (steps, QC row, phone-size row)
9
10
  * manifest.json reproducible: no timestamps; input hash + settings
10
11
  */
@@ -35,14 +36,19 @@ function gitCommit(cwd) {
35
36
 
36
37
  /**
37
38
  * @param {any} scene
38
- * @param {{out: string, style?: import("../runtime/style.mjs").Style, theme?: string, png?: boolean, scale?: number, qc?: boolean, background?: boolean, sourceFile?: string, version?: string}} options
39
+ * @param {{out: string, style?: import("../runtime/style.mjs").Style, theme?: string, png?: boolean, scale?: number, qc?: boolean, background?: boolean, sourceFile?: string, version?: string, phone?: { scene?: any, error?: string }, format?: string, locale?: string, options?: Record<string, unknown>}} options
40
+ * phone: the same scene built for the `tall` format (what a phone shows), or
41
+ * why it could not be built; the contact sheet's phone row shows it.
42
+ * format, locale, options: what the scene was built with, for the manifest
43
+ * (a custom module's scene options change its frames, so they are hashed).
39
44
  */
40
- export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version }) {
45
+ export async function exportSteps(scene, { out, style, theme = "light", png = false, scale = 2, qc = false, background = false, sourceFile, version, phone, format, locale, options }) {
41
46
  mkdirSync(out, { recursive: true });
42
47
  const opts = { standalone: true, style, theme, background };
43
48
  const files = [];
44
- const write = async (name, t, kind, label) => {
45
- const svg = renderSvg(scene, t, opts);
49
+ let phoneError = phone?.error;
50
+ const write = async (name, t, kind, label, from = scene) => {
51
+ const svg = renderSvg(from, t, opts);
46
52
  writeFileSync(join(out, `${name}.svg`), svg);
47
53
  const entry = { kind, t: Math.round(t * 1000) / 1000, label, svg: `${name}.svg` };
48
54
  if (png) {
@@ -63,9 +69,20 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
63
69
  if (i < scene.steps.length - 1) await write(`qc/${n}-after`, s.at + 0.2, "after", s.label);
64
70
  }
65
71
  }
72
+ if (phone?.scene) {
73
+ mkdirSync(join(out, "qc"), { recursive: true });
74
+ const last = phone.scene.steps[phone.scene.steps.length - 1];
75
+ // loadScene never calls frame(), so a custom scene can still fail here.
76
+ try {
77
+ await write("qc/phone", phone.scene.duration, "phone", last.label, phone.scene);
78
+ } catch (e) {
79
+ phoneError = e instanceof Error ? e.message : String(e);
80
+ }
81
+ }
66
82
  const inputHash = createHash("sha256")
67
83
  .update(sourceFile ? readFileSync(sourceFile) : scene.frame.toString())
68
84
  .update(JSON.stringify(style ?? "neutral"))
85
+ .update(JSON.stringify(options ?? null))
69
86
  .digest("hex")
70
87
  .slice(0, 16);
71
88
  const manifest = {
@@ -73,8 +90,9 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
73
90
  version,
74
91
  scene: scene.id,
75
92
  type: scene.type ?? "custom",
76
- format: scene.format ?? null,
77
- locale: scene.locale ?? null,
93
+ format: scene.format ?? format ?? null,
94
+ locale: scene.locale ?? locale ?? null,
95
+ options: options ?? null,
78
96
  width: scene.width,
79
97
  height: scene.height,
80
98
  duration: Math.round(scene.duration * 1000) / 1000,
@@ -86,25 +104,29 @@ export async function exportSteps(scene, { out, style, theme = "light", png = fa
86
104
  files,
87
105
  };
88
106
  writeFileSync(join(out, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
89
- writeFileSync(join(out, "index.html"), contactSheet(scene, files, theme, style));
107
+ writeFileSync(join(out, "index.html"), contactSheet(scene, files, theme, style, phoneError));
90
108
  return manifest;
91
109
  }
92
110
 
93
- function contactSheet(scene, files, theme, style) {
111
+ function contactSheet(scene, files, theme, style, phoneError) {
94
112
  const bg = style?.[theme]?.bg ?? (theme === "dark" ? "#0f1115" : "#ffffff");
95
113
  const card = (f) =>
96
114
  `<figure><img src="${f.svg}" alt=""><figcaption>${f.kind} · ${f.t}s · ${escapeHtml(f.label)}</figcaption></figure>`;
97
115
  const steps = files.filter((f) => f.kind === "step");
98
- const qcs = files.filter((f) => f.kind !== "step");
116
+ const qcs = files.filter((f) => f.kind === "before" || f.kind === "after");
117
+ const tall = files.find((f) => f.kind === "phone");
118
+ const phoneRow = tall
119
+ ? `<div class="grid phone">${card(tall)}</div>`
120
+ : `<p>The tall layout could not be built${phoneError ? ` (${escapeHtml(phoneError)})` : ""}; this is the ${escapeHtml(scene.format ?? "exported")} frame at 360 px.</p><div class="grid phone">${steps.slice(-1).map(card).join("")}</div>`;
99
121
  return `<!doctype html><meta charset="utf-8"><title>${escapeHtml(scene.title)} · contact sheet</title>
100
122
  <style>body{font:14px system-ui;margin:24px;background:#e5e7eb}h2{margin:24px 0 8px}
101
123
  .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:12px}
102
124
  figure{margin:0;background:${bg};padding:8px;border-radius:8px}img{width:100%;display:block}
103
- figcaption{font-size:12px;color:#6b7280;margin-top:4px}.phone figure{width:360px}</style>
125
+ figcaption{font-size:12px;color:#6b7280;margin-top:4px}.phone figure{width:fit-content}.phone img{width:360px}</style>
104
126
  <h1>${escapeHtml(scene.title)}</h1><p>${escapeHtml(scene.id)} · ${scene.width}×${scene.height} · ${scene.duration.toFixed(2)} s · ${theme}</p>
105
127
  <h2>Steps (what a slide shows)</h2><div class="grid">${steps.map(card).join("")}</div>
106
128
  ${qcs.length ? `<h2>QC: 0.2 s before / after each step</h2><div class="grid">${qcs.map(card).join("")}</div>` : ""}
107
- <h2>Phone size (360 px wide)</h2><div class="grid phone">${steps.slice(-1).map(card).join("")}</div>
129
+ <h2>Phone size (tall layout, 360 px wide)</h2>${phoneRow}
108
130
  <h2>Review</h2><ol><li>Does the step sequence tell the story without narration?</li><li>Any overlapping text, half-drawn lines or stray dots?</li><li>Readable at phone size?</li><li>Only approved copy and claims? No invented numbers?</li><li>Human approval: ____________ (name, date)</li></ol>`;
109
131
  }
110
132
 
package/lib/gate.mjs ADDED
@@ -0,0 +1,88 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · the gate over files: what `motion-kit check` and the vendored
5
+ * `check.mjs` both run, so the two cannot drift apart.
6
+ *
7
+ * checkFiles(files, { formats, locales, style, options }) → number of failures
8
+ *
9
+ * - The style must pass the contrast check (G12).
10
+ * - Every file × format (all of FORMATS unless given) × locale passes
11
+ * checkScene. Locales: the given ones; else, for a spec, every locale its
12
+ * strings carry, and `en` for a module.
13
+ * - A file that cannot be read, parsed or built is a failure for that file
14
+ * only; the remaining files are still checked.
15
+ */
16
+ import { readFileSync } from "node:fs";
17
+ import { FORMATS } from "../runtime/scene.mjs";
18
+ import { checkContrast } from "../runtime/style.mjs";
19
+ import { checkScene } from "./check.mjs";
20
+ import { isModule, loadScene } from "./load.mjs";
21
+
22
+ /** @param {unknown} e */
23
+ const message = (e) => (e instanceof Error ? e.message : String(e));
24
+
25
+ /**
26
+ * Locales a spec's strings carry: every key of an object whose keys are all
27
+ * locale tags (`en`, `nl`, `pt-BR`) with string values. `["en"]` if none.
28
+ * @param {unknown} spec
29
+ * @returns {string[]}
30
+ */
31
+ export function detectLocales(spec) {
32
+ const found = new Set();
33
+ /** @param {unknown} v */
34
+ const walk = (v) => {
35
+ if (Array.isArray(v)) v.forEach(walk);
36
+ else if (v && typeof v === "object") {
37
+ const entries = Object.entries(v);
38
+ if (entries.length && entries.every(([k, x]) => /^[a-z]{2}(-[A-Z]{2})?$/.test(k) && typeof x === "string")) entries.forEach(([k]) => found.add(k));
39
+ else entries.forEach(([, x]) => walk(x));
40
+ }
41
+ };
42
+ walk(spec);
43
+ return found.size ? [...found] : ["en"];
44
+ }
45
+
46
+ /**
47
+ * @param {string[]} files specs (.json) and custom modules (.mjs)
48
+ * @param {{ formats?: string[], locales?: string[], style?: any, options?: import("./load.mjs").OptionsSource, log?: (line: string) => void, error?: (line: string) => void }} [o]
49
+ * @returns {Promise<number>} failures (0 = the gate passes)
50
+ */
51
+ export async function checkFiles(files, { formats, locales, style, options, log = console.log, error = console.error } = {}) {
52
+ let bad = 0;
53
+ for (const p of checkContrast(style)) {
54
+ bad++;
55
+ error(`✗ style: ${p}`);
56
+ }
57
+ for (const file of files) {
58
+ const module = isModule(file);
59
+ let fileLocales = locales?.length ? locales : ["en"];
60
+ if (!locales?.length && !module) {
61
+ try {
62
+ fileLocales = detectLocales(JSON.parse(readFileSync(file, "utf8")));
63
+ } catch (e) {
64
+ bad++;
65
+ error(`✗ ${file}: ${message(e)}`);
66
+ continue;
67
+ }
68
+ }
69
+ for (const format of formats?.length ? formats : Object.keys(FORMATS)) {
70
+ for (const locale of fileLocales) {
71
+ try {
72
+ const sceneOptions = module && options ? await options({ format, locale }) : undefined;
73
+ const { scene } = await loadScene(file, { format, locale, options: sceneOptions });
74
+ const r = checkScene(scene);
75
+ if (r.ok) log(`✓ ${file} · ${format} · ${locale} · ${scene.duration.toFixed(2)} s · ${scene.steps.length} steps`);
76
+ else {
77
+ bad++;
78
+ error(`✗ ${file} · ${format} · ${locale}\n - ${r.problems.join("\n - ")}`);
79
+ }
80
+ } catch (e) {
81
+ bad++;
82
+ error(`✗ ${file} · ${format} · ${locale}: ${message(e)}`);
83
+ }
84
+ }
85
+ }
86
+ }
87
+ return bad;
88
+ }