@liqweed/motion-kit 0.12.0 → 0.13.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.12.0"
10
+ "version": "0.13.0"
11
11
  }
12
12
  ]
13
13
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "motion-kit",
3
- "version": "0.12.0",
3
+ "version": "0.13.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
@@ -56,7 +56,7 @@ dependency) or Chrome; video: `ffmpeg`.
56
56
  ```
57
57
  runtime/ dependency-free ES modules (browser + Node)
58
58
  motion.mjs easing (exact cubic-bezier), progress, critically damped spring, retarget, split edges
59
- svg.mjs escaping, rounding, el/text/fade, polyline + Bézier arc-length, drawOn, several tokens
59
+ svg.mjs escaping, rounding, el/text/fade, polyline + Bézier arc-length, drawOn, several tokens, blur reveal, highlighter sweep
60
60
  iso.mjs isometric kit for custom scenes: camera, solids (rounded too), depth order, grid backdrop, content on faces, label anchors and pills
61
61
  connectors.mjs dashed connectors, diamond junctions and single-pass light pulses for custom scenes
62
62
  wrap.mjs label wrapping with hard budgets
@@ -74,8 +74,9 @@ skills/ animated-diagram, motion-render, project-logo (Claude Code / Cra
74
74
  examples/ order-flow (sequence), smart-home (hub-spoke), incident (timeline),
75
75
  web-stack (stack), custom-pulse (custom module),
76
76
  isometric-swivel (custom module: isometric kit, several tokens),
77
- isometric-platform (custom module: rounded slabs, grid backdrop, mark on a top face, pill tags)
78
- connectors (custom module: connectors, diamond junctions, pulses)
77
+ isometric-platform (custom module: rounded slabs, grid backdrop, mark on a top face, pill tags),
78
+ connectors (custom module: connectors, diamond junctions, pulses),
79
+ text-reveal (custom module: blur-and-fade reveal, highlighter sweep)
79
80
  bench/ heavy scene for npm run bench:player (live-player frame cost)
80
81
  brand/ logo scene (built with motion-kit); renders go to assets/ + .idea/ (npm run media)
81
82
  assets/ generated project icon: icon.svg, icon.png, icon-animated.svg
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  title: motion-kit technique — normative specification
3
3
  status: draft
4
- last_updated: 2026-11-19
4
+ last_updated: 2026-11-21
5
5
  ---
6
6
 
7
7
  # motion-kit technique — normative specification
@@ -39,7 +39,7 @@ A scene is a plain object (`runtime/scene.mjs:1-18`).
39
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
  | `contrastPairs` | `{fg, bg, min, use?}[]` | MAY | The token pairs the scene draws (§6). The gate holds the style to exactly these in both themes, and only warns about the shared pairs (`CONTRAST_PAIRS`) the list leaves out; a scene that declares none is held to every shared pair [gate] G12 (`lib/check.mjs`, `contrastReport`; used by `examples/custom-pulse.scene.mjs`; every registered scene type sets it). Tokens MUST be known and `min` in [1, 21]. |
42
- | `labelBoxes(t)` | `(number) → LabelBox[]` | MAY | The box of every label `frame(t)` draws, in the scene's own coordinates (`{id, x, y, width, height, stem?, opacity?}`; `labelAnchor` and `labelPill` return one, §4.9). Must be a function [throws]. The gate fails a scene whose labels overlap, whose stems cross a label or that leave the picture [gate] G15 (`lib/check.mjs`, rule 9; each box MUST be `{id, x, y, width, height}` with finite numbers [gate]; used by `examples/isometric-swivel.scene.mjs`). |
42
+ | `labelBoxes(t)` | `(number) → LabelBox[]` | MAY | The box of every label `frame(t)` draws, in the scene's own coordinates (`{id, x, y, width, height, stem?, opacity?}`; `labelAnchor(...)` and `labelPill(...)` return `{markup, box}`; return its `.box`, not the whole result, §4.9). Must be a function [throws]. The gate fails a scene whose labels overlap, whose stems cross a label or that leave the picture [gate] G15 (`lib/check.mjs`, rule 9; each box MUST be `{id, x, y, width, height}` with `id` a string and the rest finite numbers, `width` and `height` not negative, `opacity`, when given, finite, and `stem`, when given, `{x1, y1, x2, y2}` with four finite numbers [gate]; used by `examples/isometric-swivel.scene.mjs`). |
43
43
  | `type`, `format`, `locale` | string | MAY | Set by scene types; recorded in the export manifest (`lib/export.mjs:75-77`). |
44
44
 
45
45
  - A scene MUST be produced by either a registered scene type —
@@ -68,9 +68,9 @@ A scene is a plain object (`runtime/scene.mjs:1-18`).
68
68
  |---|---|---|---|
69
69
  | T1 | `frame(t)` MUST depend only on `t` and the scene's constants: no `Date`, `Math.random`, `performance.now`, no state carried between calls, no module-level mutable state. | [gate] G1 re-renders each `t`; G11 renders under stubbed clocks and scans the source (`lib/check.mjs`) | Random access: a player can jump, an exporter can write exactly one frame, video samples `t = f/fps` (`runtime/scene.mjs:14-17`). |
70
70
  | T2 | Same `t` (and same style/options) MUST give byte-identical output. | [gate] G1 | Tests, diffs, caching and committed media all depend on it. |
71
- | T3 | Callers MUST clamp `t` to `[0, duration]`; `renderSvg` does (`runtime/scene.mjs:70`). `frame` MAY assume a clamped `t`. | — | Defines "before start" and "hold". |
72
- | T4 | Every number interpolated into markup MUST be rounded: `num(n, 2)` by default, 3 digits for `opacity`, 4 for scale factors (`runtime/svg.mjs:17-22,29,64`). `num` MUST throw on non-finite input and never emit `-0`. | [gate] G3; non-finite → G5 | 17-digit floats made "settled" frames differ by 1 ms (`skills/animated-diagram/references/technique.md:128-129`). |
73
- | T5 | Visibility MUST be decided on rounded values: an element whose opacity rounds to 0 is omitted; an opacity that rounds to 1 is not written (`runtime/svg.mjs:28,39,68-72`). | by construction (`el`, `fade`) | Identical-looking frames must be identical bytes (opacity 0.9999 vs omitted). |
71
+ | T3 | Callers MUST clamp `t` to `[0, duration]`; `renderSvg` does (`renderSvg` in `runtime/scene.mjs`). `frame` MAY assume a clamped `t`, except that it MUST hold: the gate also calls it with a raw `t` past `duration` and requires the final frame. | — | Defines "before start" and "hold". |
72
+ | T4 | Every number interpolated into markup MUST be rounded: `num(n, 2)` by default, 3 digits for `opacity`, 4 for scale factors (`num`, `el`, `fade` in `runtime/svg.mjs`). `num` MUST throw on non-finite input and never emit `-0`. | [gate] G3; non-finite → G5 | 17-digit floats made "settled" frames differ by 1 ms (`skills/animated-diagram/references/technique.md`, "Lessons learned"). |
73
+ | T5 | Visibility MUST be decided on rounded values: an element whose opacity rounds to 0 is omitted; an opacity that rounds to 1 is not written (`el`, `fade` in `runtime/svg.mjs`). | by construction (`el`, `fade`) | Identical-looking frames must be identical bytes (opacity 0.9999 vs omitted). |
74
74
  | T6 | Scenes MUST NOT use CSS transitions/animations or timers; the renderer owns the clock (`runtime/player.mjs:15`). | — | Exported frames would not match what plays. |
75
75
  | T7 | Variation, if any, MUST derive from constants and `t` (seeded), never from runtime randomness. | [gate] G1, G11 | Same as T2. |
76
76
 
@@ -194,13 +194,13 @@ move ends at `start + lag + duration`, which is what step timing MUST budget.
194
194
  ### 4.7 Geometry: arc length and draw-on (`runtime/svg.mjs`)
195
195
 
196
196
  - `polyline(points)` → `{length, d, at(f)}`; `at` returns the point at fraction
197
- `f` of total arc length (`runtime/svg.mjs:92-113`).
197
+ `f` of total arc length (`polyline` in `runtime/svg.mjs`).
198
198
  - `cubic(p0…p3, samples = 64)` → `{length, d, at(f)}` with a 64-sample
199
199
  arc-length lookup table and binary search, so a marker moves at constant
200
- speed without a DOM in Node and browsers (`runtime/svg.mjs:119-152`).
200
+ speed (approximately, within a lookup interval) without a DOM in Node and browsers (`cubic` in `runtime/svg.mjs`).
201
201
  - `drawOn(length, p)`: `null` for `p ≤ 0`, `{}` for `p ≥ 1`, else
202
202
  `stroke-dasharray: L L; stroke-dashoffset: L·(1 − p)`
203
- (`runtime/svg.mjs:159-163`). Callers MUST skip the element when it returns
203
+ (`drawOn` in `runtime/svg.mjs`). Callers MUST skip the element when it returns
204
204
  `null`: a zero-length dash with round caps paints a dot.
205
205
  - Two-state elements (pending → active) MUST cross-fade two layers with
206
206
  opacities `1 − p` and `p` instead of interpolating colours, which would need
@@ -247,7 +247,7 @@ functions; a colour is a token name, resolved with `tok()` (G4 applies).
247
247
  opacity, id})` extrudes a convex footprint (any winding; stored
248
248
  counter-clockwise) from base height `z` by `h` ≥ 0; `box` (centred on x, y)
249
249
  and `slab` (default `h` 0.25) are rectangular prisms; `regularPolygon` makes
250
- a footprint. A non-convex, degenerate or too-small footprint, an unknown
250
+ a footprint. A non-convex, degenerate or too-small footprint, one with a repeated vertex (adjacent or not, so a footprint that winds round twice), an unknown
251
251
  token or a negative height throws. `fill` is the token of the top face,
252
252
  `sides` of the side faces (default `fill`); `shade` (default `ink`, `null`
253
253
  for none) is layered over each side at an opacity from 0.10 to 0.26 by how
@@ -305,8 +305,9 @@ functions; a colour is a token name, resolved with `tok()` (G4 applies).
305
305
  - **Labels.** `labelAnchor(cam, {id, at, lines, fontSize, lift, side,
306
306
  opacity})` draws a dot on the projected point, a vertical stem `lift` pixels
307
307
  up and a label box above it (or beside its top), and returns the markup and
308
- the `LabelBox`. `labelProblems(boxes, {width, height, gap = 4})` lists the
309
- collisions G15 reports. Labels follow §7 (wrapped, localized, ≥ 14 px).
308
+ the `LabelBox`, rounded to two decimals as the SVG attributes are, so the gate
309
+ and the picture agree on those coordinates (`labelPill` rounds its box the same way). `labelProblems(boxes, {width, height, gap = 4, limit})`
310
+ lists the collisions G15 reports, and stops at `limit` (a whole number from 0 or Infinity, else `RangeError`; default all; 0 returns none; only distinct sentences count). Labels follow §7 (wrapped, localized, ≥ 14 px).
310
311
  `labelPill({id, x, y, lines, fontSize, fill, stroke, ink, opacity})` is a
311
312
  stemless tag: a rounded box of text centred on the screen point (`x`, `y`),
312
313
  its colours tokens (`surface`, `line`, `ink` by default). It returns the
@@ -358,11 +359,67 @@ functions; a colour is a token name (G4 applies).
358
359
  its target has filled, and nothing repeats while a step rests, so the
359
360
  settled-frame rule (G6) holds. Several pulses may run in one beat.
360
361
 
362
+
363
+ ### 4.11 Text reveal and highlighter sweep (`runtime/svg.mjs`)
364
+
365
+ - `blurReveal(enter, {id, rise = 6, blur = 4}, ...children)` draws `children`
366
+ with an opacity that rises to one and a rise and a blur that go to zero as
367
+ `enter` (an eased progress, §4.2) goes from 0 to 1: one `<g transform opacity filter>` and,
368
+ while the blur is 0.005 or more, a `<defs>` holding one `<filter>` with one
369
+ `<feGaussianBlur>`. It returns `""` for `enter ≤ 0` and wherever the opacity rounds to zero.
370
+ - **Settled means bare.** Once `enter` reaches 1, as `fade` rounds it (0.9995
371
+ and above), `blurReveal` MUST return the children unchanged: no group, no
372
+ filter, no `<defs>`, so a settled frame is byte-identical to the same markup
373
+ drawn without the reveal, and every step frame, the final frame, a baked
374
+ last slice and a reduced-motion frame carry no filter. Between 0 and 1 the
375
+ `transform` and the `filter` are left off once they round to nothing
376
+ (a rise or a blur under 0.005 units), so a frame never carries
377
+ a `stdDeviation="0"`, which renderers read differently.
378
+ - **Ids.** `id` names the filter and MUST be built from `frame`'s `idPrefix`
379
+ (`${idPrefix}-reveal-1`), one per revealed element, so the sampled G14 check for ids shared across instances holds and a baked
380
+ SVG, which renders each slice with its own prefix, never repeats one
381
+ [throws unless `id` is a CSS-safe token]. `rise` is 0 to 24 and `blur` 0 to 12
382
+ [throws].
383
+ - **Renderers.** The filter is `feGaussianBlur` in sRGB over a region of
384
+ `x −25 %`, `y −100 %`, `width 150 %`, `height 300 %` of the element's box,
385
+ which holds the blur only while, on each side, the padding (25 % of the width sideways, 100 % of the height above and below) less any overhang of stroke or markers past the box leaves at least 3 × `blur` of clearance. For an element too narrow or shallow for that (a zero-height rule included), a `blur` above the default, or a stroke or markers that eat the padding (a thick stroke on a small shape, at any size), `box: {x, y, width, height}` (the
386
+ element's own painted box: all four fields finite, `width` and `height` positive, `x` and `y` free [throws], covering the painted stroke) makes the region that box
387
+ plus 3 × `blur` on every side (`filterUnits="userSpaceOnUse"`). The tests compare the SVG markup, baked slices and the patched DOM, and a resvg fixture of one mid-reveal frame; other renderers are not compared. The live player (its
388
+ in-place patch updates `stdDeviation` and the group's attributes, and drops
389
+ the group when the reveal ends), `renderSvg` and `bake` use the same helper and filter parameters; their SVG bytes differ (`bake` renames filter ids per slice and wraps frames in groups; `renderSvg` resolves token references only in standalone mode), so do not compare or reuse them interchangeably. PNG export and video rasterize with resvg or Chrome, and raster appearance can vary with renderer, fonts and scale (`test/reveal.test.mjs`,
390
+ `test/player.test.mjs`). A consumer that ignores SVG filters (some slide
391
+ applications) shows the fade and the rise without the blur, and only in a
392
+ frame taken mid-reveal: step frames carry no filter.
393
+ - **Timing.** The reveal is one entrance, 300 to 600 ms (§4.2), on the style's
394
+ entrance curve (`easings(style.motion).easeOut`), finished 50 ms or more
395
+ before the step it belongs to. That is the scene's obligation: G6 only checks that frames around a step are stable, so a scene that holds `enter` at, say, 0.5 through a step or the end keeps a filter in those frames and passes. The no-filter guarantee holds only for a reveal completed in time. It happens once per element and holds.
396
+ The blur is a paint cost no other motion helper has; the plain fade
397
+ (`fade`) stays the default for a label whose arrival does not need to be
398
+ watched
399
+ ([`motion-vocabulary.md`](../../skills/animated-diagram/references/motion-vocabulary.md)).
400
+ - `highlightSweep(p, {x, y, width, height, token = "emphasis", opacity = 0.3,
401
+ radius = 4})` draws a rounded `<rect>` filled with a token at `opacity`,
402
+ from `x` to `x + width · p` (`p` eased, 0 to 1); `""` for a swept width under 0.01 (`p ≤ 0` included), which returns before the `token` is read, so an unknown token throws only once the swept width reaches 0.01; an `opacity` that rounds to zero also yields `""`, but only after the `token` has been checked; at 1 the
403
+ rectangle is the same on every frame. It is drawn before the text it marks,
404
+ and `opacity` starts low (0.2 to 0.4): at the default 0.3 the neutral
405
+ style's ink reads on the tinted canvas at 4.5:1 or more in both themes
406
+ (`test/reveal.test.mjs`). The gate checks text against the canvas, not
407
+ against the band, so a custom style must check its ink against the
408
+ composited tint itself. `width` is the scene's to set; `estimateWidth` is a
409
+ rough heuristic (characters × size × 0.56), not a bound, so pass a
410
+ conservative width where the band must cover the whole line [throws on a
411
+ non-finite or non-positive size, an unknown token, or an `opacity` that is
412
+ not a finite number in (0, 1]].
413
+ - Both helpers are pure functions of their arguments. `examples/text-reveal.scene.mjs`
414
+ reveals three labels in reading order, then a quoted line with one band per
415
+ wrapped line swept first line to last.
416
+
417
+
361
418
  ## 5. Markup
362
419
 
363
420
  - Text and attribute values MUST be escaped (`& < > " '`) via `esc`, `text` or
364
- `el`/`attrString` (`runtime/svg.mjs:10-14,24-33,45-57`). Labels MUST NOT be able
365
- to inject markup (`test/runtime.test.mjs:118-124`).
421
+ `el`/`attrString` (`esc`, `text`, `el` in `runtime/svg.mjs`). Labels MUST NOT be able
422
+ to inject markup (the "escapes label text" test in `test/runtime.test.mjs`).
366
423
  - `el(tag, attrs, …children)` treats children as trusted markup; untrusted
367
424
  strings MUST go through `text()`/`esc()`.
368
425
  - Output MUST be well-formed: balanced tags, no stray `<`, no bare `&` [gate] G2.
@@ -689,14 +746,15 @@ that removes every listener, observer and mark they added.
689
746
  ## 11. The gate
690
747
 
691
748
  `checkScene(scene)` (`lib/check.mjs`) samples 121 evenly spaced times
692
- (`SAMPLES = 120`) and stops collecting after 13 problems.
749
+ (`SAMPLES = 120`). The per-sample rules test for 13 problems between samples, so one sample can add a few more; the fixed-id check and the label gate (rule 9) hold to what is left of 13, but the settled-step check appends one problem per moving step whatever the count, so the total can exceed 13.
693
750
  `motion-kit check` and the vendored `check.mjs` both run `checkFiles`
694
751
  (`lib/gate.mjs`): every file × format (all six unless `--format`, repeatable)
695
752
  × locale (`--locale`, repeatable; else every locale a spec's strings carry, and
696
753
  `en` for a module, §7), with `--options` for modules, plus the style contrast check of the pairs each scene draws and a once-per-run warning
697
754
  for the shared pairs the style misses. A file that cannot be read, parsed or built fails on its own and the
698
- remaining files are still checked; the exit code is 1 on any failure. `npm run gate` = unit tests +
699
- `check` over `examples/` and `brand/` (`package.json:15-18`).
755
+ remaining files are still checked; the exit code is 1 on any failure. `npm run gate` = `gate:core`
756
+ (typecheck, version sync, unit tests, `check` over `examples/` and `brand/`,
757
+ media freshness) plus the site build (`package.json` scripts `gate:core`, `gate`).
700
758
 
701
759
  | ID | Rule | Code | Rationale |
702
760
  |---|---|---|---|
@@ -707,7 +765,7 @@ remaining files are still checked; the exit code is 1 on any failure. `npm run g
707
765
  | G5 | No `NaN`, `undefined`, `Infinity` in `frame()` output. | `:50` | Silent geometry bugs. |
708
766
  | G6 | For every step, `render(at)` equals `render(at − 1 ms)` and `render(at + δ)` for δ = 1, 15, 30, 45 ms (before the next step). | `lib/check.mjs` (rule 2, `SETTLE_AFTER`) | Settled step frames (§8); the 45 ms look-ahead sees slow motion that rounding hides over 1 ms. |
709
767
  | G7 | First frame ≠ last frame. | `:61-63` | Something must animate. |
710
- | G8 | `render(duration + 5) === render(duration)`. | `:65` | Holds the final frame. |
768
+ | G8 | `frame(duration + 5) === frame(duration)`, called raw, unclamped. | `checkScene` in `lib/check.mjs` | Holds the final frame. |
711
769
  | G9 | `duration ≤ 12` s. | `:68` | Hard limit; authoring target ≤ 8 s. |
712
770
  | 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. |
713
771
  | G11 | Every sampled frame MUST render the same bytes under two stubbed clocks as under the real one: `Date`, `performance.now`, `Temporal.Now` and `Math.random` fixed at 1970 and 0, then at 2100 and ≈ 1, the globals restored afterwards. `frame.toString()` MUST NOT contain `Date.now`, `new Date`, `Math.random`, `performance.now`, `Temporal.Now`. | `lib/check.mjs` (rules 1 and 6) | T1. The stubbed render catches reads in the helpers a frame calls; the source scan, code paths the samples miss. A reference taken before the check runs (`const D = Date` at import) escapes the stub. |
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Example custom scene: text that sharpens into place, and a highlighter.
3
+ *
4
+ * Shows the text helpers of `kit` (runtime/svg.mjs): `blurReveal`, which
5
+ * fades a line in while it rises a few units and a blur goes to zero, and
6
+ * `highlightSweep`, a token-coloured band that grows behind a line. Three
7
+ * labels reveal in reading order, then a quoted line reveals and is marked,
8
+ * one band per wrapped line, swept from the first line to the last. Each
9
+ * reveal is one beat on the style's entrance curve and ends before its step,
10
+ * so a step frame carries no filter at all. Nothing loops. Pure: frame(t)
11
+ * depends only on t and constants.
12
+ */
13
+ import { easings, progress } from "../runtime/motion.mjs";
14
+ import { FORMATS, localize } from "../runtime/scene.mjs";
15
+ import { tok } from "../runtime/style.mjs";
16
+ import { blurReveal, el, highlightSweep, text } from "../runtime/svg.mjs";
17
+ import { estimateWidth, wrapLabel } from "../runtime/wrap.mjs";
18
+
19
+ export const locales = ["en", "nl"];
20
+
21
+ const COPY = {
22
+ title: { en: "Release notes, line by line", nl: "Releasenotes, regel voor regel" },
23
+ description: {
24
+ en: "Three labels sharpen into place one after another, then a quoted line appears and a highlighter sweeps behind it.",
25
+ nl: "Drie labels worden één voor één scherp, daarna verschijnt een geciteerde regel en veegt een markeerstift erachter.",
26
+ },
27
+ heading: { en: "What's new", nl: "Wat is nieuw" },
28
+ labels: [
29
+ { en: "Faster startup", nl: "Snellere start" },
30
+ { en: "Smaller bundles", nl: "Kleinere bundels" },
31
+ { en: "Clearer errors", nl: "Duidelijkere fouten" },
32
+ ],
33
+ quote: {
34
+ en: "Each change lands once, then it holds.",
35
+ nl: "Elke wijziging landt één keer en blijft dan staan.",
36
+ },
37
+ steps: [
38
+ { label: { en: "Labels revealed", nl: "Labels onthuld" }, detail: { en: "Three labels sharpen into place, one after another.", nl: "Drie labels worden één voor één scherp." } },
39
+ { label: { en: "Quote highlighted", nl: "Citaat gemarkeerd" }, detail: { en: "A band sweeps behind the quoted line.", nl: "Een band veegt achter de geciteerde regel." } },
40
+ ],
41
+ };
42
+
43
+ const ENTER = 0.4; // one reveal (the entrance budget is 0.3–0.6 s)
44
+ const GAP = 0.12; // siblings, in reading order (80–150 ms)
45
+ const PAUSE = 0.05; // between a beat and its step
46
+ const QUOTE_AT = 1.3;
47
+ const SWEEP_AT = QUOTE_AT + 0.2;
48
+ const SWEEP = 0.6;
49
+
50
+ export default function make({ format = "16:9", locale = "en" } = {}) {
51
+ const f = FORMATS[format];
52
+ if (!f) throw new Error(`unknown format "${format}"`);
53
+ const W = f.width;
54
+ // Sizes follow the width, never below a readable 14.
55
+ const u = W >= 900 ? 1 : W >= 700 ? 0.85 : W >= 500 ? 0.7 : 0.55;
56
+ const fsHead = Math.max(14, Math.round(18 * u));
57
+ const fsLabel = Math.max(16, Math.round(36 * u));
58
+ const fsQuote = Math.max(14, Math.round(26 * u));
59
+ const x0 = Math.round(W * 0.1);
60
+ const pad = Math.round(fsQuote * 0.4); // the band's padding either side of the text
61
+ const chars = (/** @type {number} */ fs, /** @type {number} */ room) => Math.floor(room / (fs * 0.56));
62
+ const heading = localize(COPY.heading, locale);
63
+ const labels = COPY.labels.map((l) => wrapLabel(localize(l, locale), chars(fsLabel, W - 2 * x0), 1));
64
+ const quote = wrapLabel(localize(COPY.quote, locale), chars(fsQuote, W - 2 * x0 - 2 * pad), 3);
65
+
66
+ // Vertical layout, top to bottom, centred in the picture.
67
+ const rowLabel = Math.round(fsLabel * 1.5);
68
+ const rowQuote = Math.round(fsQuote * 1.6);
69
+ const headRow = Math.round(fsHead * 2.2);
70
+ const block = headRow + labels.length * rowLabel + Math.round(fsQuote * 1.4) + quote.length * rowQuote;
71
+ const H = f.height || block + 2 * Math.round(W * 0.1);
72
+ const top = Math.round((H - block) / 2);
73
+ const yHead = top + fsHead / 2;
74
+ const yLabel = (/** @type {number} */ i) => top + headRow + i * rowLabel + rowLabel / 2;
75
+ const quoteTop = top + headRow + labels.length * rowLabel + Math.round(fsQuote * 1.4);
76
+ const yQuote = (/** @type {number} */ i) => quoteTop + i * rowQuote + rowQuote / 2;
77
+
78
+ // Reveal times: the heading, then the labels in reading order.
79
+ const labelAt = (/** @type {number} */ i) => (i + 1) * GAP;
80
+ const labelsDone = labelAt(labels.length - 1) + ENTER;
81
+ const sweepDone = SWEEP_AT + SWEEP;
82
+ const steps = [
83
+ { at: labelsDone + PAUSE, ...COPY.steps[0] },
84
+ { at: Math.max(sweepDone, QUOTE_AT + ENTER) + PAUSE, ...COPY.steps[1] },
85
+ ];
86
+ const duration = steps[1].at + 0.4;
87
+
88
+ // One sweep over all the lines of the quote: line i fills while the sweep
89
+ // is inside its share of the total width.
90
+ // estimateWidth is a rough heuristic; 0.9 of it hugs a typical sans-serif for these fixed lines (checked by eye in the rendered frames; the gate does not measure glyph widths).
91
+ const widths = quote.map((line) => estimateWidth(line, fsQuote) * 0.9 + 2 * pad);
92
+ const total = widths.reduce((a, b) => a + b, 0);
93
+ const before = widths.map((_, i) => widths.slice(0, i).reduce((a, b) => a + b, 0));
94
+
95
+ /** @param {number} t @param {{ idPrefix: string, style?: any }} ctx */
96
+ function frame(t, { idPrefix, style }) {
97
+ const { easeOut } = easings(style?.motion);
98
+ const id = (/** @type {string} */ name) => `${idPrefix}-reveal-${name}`;
99
+ const out = [];
100
+ out.push(
101
+ blurReveal(
102
+ progress(t, 0, ENTER, easeOut),
103
+ { id: id("heading") },
104
+ text({ x: x0, y: yHead, "dominant-baseline": "central", "font-size": fsHead, "font-weight": 500, fill: tok("muted") }, heading),
105
+ ),
106
+ );
107
+ labels.forEach((lines, i) => {
108
+ out.push(
109
+ blurReveal(
110
+ progress(t, labelAt(i), ENTER, easeOut),
111
+ { id: id(`label-${i}`) },
112
+ text({ x: x0, y: yLabel(i), "dominant-baseline": "central", "font-size": fsLabel, "font-weight": 600, fill: tok("ink") }, lines),
113
+ ),
114
+ );
115
+ });
116
+ // The bands first, so the quote sits on top of them.
117
+ const swept = progress(t, SWEEP_AT, SWEEP, easeOut) * total;
118
+ quote.forEach((_, i) => {
119
+ out.push(
120
+ highlightSweep((swept - before[i]) / widths[i], {
121
+ x: x0 - pad,
122
+ y: yQuote(i) - rowQuote / 2 + 3,
123
+ width: widths[i],
124
+ height: rowQuote - 6,
125
+ radius: 6,
126
+ }),
127
+ );
128
+ });
129
+ out.push(
130
+ blurReveal(
131
+ progress(t, QUOTE_AT, ENTER, easeOut),
132
+ { id: id("quote") },
133
+ quote.map((line, i) => text({ x: x0, y: yQuote(i), "dominant-baseline": "central", "font-size": fsQuote, "font-weight": 500, fill: tok("ink") }, line)),
134
+ ),
135
+ );
136
+ return out.join("");
137
+ }
138
+
139
+ return {
140
+ id: `text-reveal-${format.replace(":", "x")}`,
141
+ width: W,
142
+ height: H,
143
+ duration,
144
+ title: localize(COPY.title, locale),
145
+ description: localize(COPY.description, locale),
146
+ // The steps are beats, not labels in the drawing: their text lives in the
147
+ // player's step buttons and captions.
148
+ stepLabelsInFrame: false,
149
+ steps: steps.map((s) => ({ at: s.at, label: localize(s.label, locale), detail: localize(s.detail, locale) })),
150
+ frame,
151
+ };
152
+ }
package/lib/check.mjs CHANGED
@@ -9,7 +9,7 @@
9
9
  * Over files, formats and locales (the CLI and the vendored gate): lib/gate.mjs.
10
10
  */
11
11
  import { labelProblems } from "../runtime/iso.mjs";
12
- import { renderSvg, validateScene } from "../runtime/scene.mjs";
12
+ import { renderSvg, safeId, validateScene } from "../runtime/scene.mjs";
13
13
  import { contrastReport, normalizeStyle } from "../runtime/style.mjs";
14
14
 
15
15
  const SAMPLES = 120;
@@ -187,6 +187,9 @@ function underStubbedClock({ now, perf, random }, fn) {
187
187
  */
188
188
  export const SETTLE_AFTER = Object.freeze([0.001, 0.015, 0.03, 0.045]);
189
189
 
190
+ /** The most problems a scene reports before the gate stops looking. */
191
+ const MAX_PROBLEMS = 13;
192
+
190
193
  /**
191
194
  * Run the scene gate on one built scene.
192
195
  * @param {import("../runtime/scene.mjs").Scene} scene
@@ -220,7 +223,7 @@ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
220
223
  if (wf) problems.push(`malformed at t=${t.toFixed(3)}: ${wf}`);
221
224
  const long = a.match(/-?\d+\.\d{5,}/);
222
225
  if (long) problems.push(`unrounded number ${long[0]} at t=${t.toFixed(3)} (use num())`);
223
- const frame = scene.frame(Math.min(t, scene.duration), { idPrefix: scene.id, style });
226
+ const frame = scene.frame(Math.min(t, scene.duration), { idPrefix: safeId(scene.id), style });
224
227
  const lit = findColourLiteral(frame);
225
228
  if (lit) problems.push(`colour literal ${lit} at t=${t.toFixed(3)} (use tok())`);
226
229
  if (/NaN|undefined|Infinity/.test(frame)) problems.push(`NaN/undefined/Infinity in frame at t=${t.toFixed(3)}`);
@@ -237,7 +240,7 @@ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
237
240
  break;
238
241
  }
239
242
  }
240
- if (problems.length > 12) break;
243
+ if (problems.length >= MAX_PROBLEMS) break;
241
244
  }
242
245
 
243
246
  // 2. Settled steps: nothing moves at a step's time. The step's own motion
@@ -259,7 +262,7 @@ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
259
262
  const lastFrame = render(scene.duration);
260
263
  if (first === lastFrame) problems.push("first and last frame are identical: nothing animates");
261
264
  if (scene.steps[scene.steps.length - 1].at > scene.duration) problems.push("last step is after duration");
262
- if (scene.frame(scene.duration + 5, { idPrefix: scene.id, style }) !== scene.frame(scene.duration, { idPrefix: scene.id, style })) problems.push("frames after the end differ from the final frame (must hold)");
265
+ if (scene.frame(scene.duration + 5, { idPrefix: safeId(scene.id), style }) !== scene.frame(scene.duration, { idPrefix: safeId(scene.id), style })) problems.push("frames after the end differ from the final frame (must hold)");
263
266
 
264
267
  // 4. Hard limit: 12 s. Authoring target: 8 s; these are distinct.
265
268
  if (scene.duration > 12) problems.push(`duration ${scene.duration.toFixed(1)}s exceeds the 12 s limit (aim for ≤ 8 s)`);
@@ -286,7 +289,10 @@ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
286
289
  const second = ids("mk-gate-b");
287
290
  for (const id of ids("mk-gate-a")) if (second.has(id)) fixed.add(id);
288
291
  }
289
- for (const id of fixed) problems.push(`fixed id "${id}": build ids from frame(t, { idPrefix }), e.g. \`\${idPrefix}-${id}\``);
292
+ for (const id of fixed) {
293
+ if (problems.length >= MAX_PROBLEMS) break;
294
+ problems.push(`fixed id "${id}": build ids from frame(t, { idPrefix }), e.g. \`\${idPrefix}-${id}\``);
295
+ }
290
296
 
291
297
  // 8. (Contrast, G12: checked first, above, by contrastReport.)
292
298
 
@@ -297,6 +303,7 @@ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
297
303
  const seen = new Set();
298
304
  const times = [...Array.from({ length: samples + 1 }, (_, i) => at(i)), ...scene.steps.map((s) => s.at)].sort((a, b) => a - b);
299
305
  for (const t of times) {
306
+ if (problems.length >= MAX_PROBLEMS) break; // the cap: nothing more is asked of labelBoxes()
300
307
  let boxes;
301
308
  try {
302
309
  boxes = scene.labelBoxes(Math.min(t, scene.duration));
@@ -308,17 +315,16 @@ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
308
315
  problems.push("labelBoxes() must return an array of label boxes");
309
316
  break;
310
317
  }
311
- const bad = boxes.findIndex((b) => !b || typeof b !== "object" || typeof b.id !== "string" || !["x", "y", "width", "height"].every((k) => Number.isFinite(b[k])) || (b.opacity !== undefined && !Number.isFinite(b.opacity)) || (b.stem !== undefined && (!b.stem || typeof b.stem !== "object" || !["x1", "y1", "x2", "y2"].every((k) => Number.isFinite(b.stem[k])))));
318
+ const bad = boxes.findIndex((b) => !b || typeof b !== "object" || typeof b.id !== "string" || !["x", "y", "width", "height"].every((k) => Number.isFinite(b[k])) || b.width < 0 || b.height < 0 || (b.opacity !== undefined && !Number.isFinite(b.opacity)) || (b.stem !== undefined && (!b.stem || typeof b.stem !== "object" || !["x1", "y1", "x2", "y2"].every((k) => Number.isFinite(b.stem[k])))));
312
319
  if (bad >= 0) {
313
- problems.push(`labelBoxes() entry ${bad} must be { id, x, y, width, height } with finite numbers (and a stem, when given, { x1, y1, x2, y2 }), at t=${t.toFixed(3)}`);
320
+ problems.push(`labelBoxes() entry ${bad} must be { id, x, y, width, height } with finite numbers (width and height not negative; and a stem, when given, { x1, y1, x2, y2 }), at t=${t.toFixed(3)}`);
314
321
  break;
315
322
  }
316
- for (const p of labelProblems(boxes, { width: scene.width, height: scene.height })) {
317
- if (seen.has(p)) continue;
323
+ // The limit is what is left of the 13-problem cap (the loop entry guarantees some); problems already seen are skipped, not counted.
324
+ for (const p of labelProblems(boxes, { width: scene.width, height: scene.height, limit: MAX_PROBLEMS - problems.length, ignore: seen })) {
318
325
  seen.add(p);
319
326
  problems.push(`${p} at t=${t.toFixed(3)}`);
320
327
  }
321
- if (problems.length > 12) break;
322
328
  }
323
329
  }
324
330
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqweed/motion-kit",
3
- "version": "0.12.0",
3
+ "version": "0.13.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,7 +47,7 @@
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/incident.json examples/web-stack.json examples/custom-pulse.scene.mjs examples/isometric-swivel.scene.mjs examples/connectors.scene.mjs examples/isometric-platform.scene.mjs brand/logo.scene.mjs examples/player-states.json examples/checkout.json examples/connection.json examples/pull-request.json",
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 examples/isometric-swivel.scene.mjs examples/connectors.scene.mjs examples/isometric-platform.scene.mjs examples/text-reveal.scene.mjs brand/logo.scene.mjs examples/player-states.json examples/checkout.json examples/connection.json examples/pull-request.json",
51
51
  "media": "scripts/render-media.sh",
52
52
  "media:check": "scripts/render-media.sh --check",
53
53
  "site": "npm run -w website build",
package/runtime/iso.mjs CHANGED
@@ -241,10 +241,12 @@ function convexCcw(points) {
241
241
  area += a.x * b.y - b.x * a.y;
242
242
  }
243
243
  if (Math.abs(area) < 1e-9) throw new Error("a solid's footprint has no area");
244
+ // Any two vertices at one place, neighbours or not: a footprint that winds
245
+ // round twice has every turn and half-plane right, and draws each face twice.
244
246
  for (let i = 0; i < points.length; i++) {
245
- const a = points[i];
246
- const b = points[(i + 1) % points.length];
247
- if (Math.hypot(b.x - a.x, b.y - a.y) < 1e-9) throw new Error("a solid's footprint has a repeated point");
247
+ for (let j = i + 1; j < points.length; j++) {
248
+ if (Math.hypot(points[j].x - points[i].x, points[j].y - points[i].y) < 1e-9) throw new Error("a solid's footprint has a repeated point");
249
+ }
248
250
  }
249
251
  const flipped = area < 0;
250
252
  const ccw = flipped ? points.map((p) => ({ x: p.x, y: p.y })).reverse() : points.map((p) => ({ x: p.x, y: p.y }));
@@ -826,6 +828,8 @@ export function labelAnchor(cam, { id, at, lines, fontSize = 14, lift = 40, side
826
828
  const x = side === "up" ? tipX - width / 2 : side === "right" ? tipX : tipX - width;
827
829
  const y = side === "up" ? tipY - height : tipY - height / 2;
828
830
  const stem = { x1: p.x, y1: p.y, x2: tipX, y2: tipY };
831
+ const r = drawn2;
832
+ const labelBox = { id, x: r(x), y: r(y), width: r(width), height: r(height), stem: { x1: r(stem.x1), y1: r(stem.y1), x2: r(stem.x2), y2: r(stem.y2) }, opacity };
829
833
  const markup = fade(
830
834
  opacity,
831
835
  { "data-label": id },
@@ -834,9 +838,12 @@ export function labelAnchor(cam, { id, at, lines, fontSize = 14, lift = 40, side
834
838
  el("rect", { x, y, width, height, rx: 6, fill: tok("surface"), stroke: tok("line"), "stroke-width": 1.5 }),
835
839
  text({ x: x + width / 2, y: y + height / 2, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fontSize, "font-weight": 600, fill: tok("ink") }, lines, LINE_HEIGHT),
836
840
  );
837
- return { markup, box: { id, x, y, width, height, stem, opacity } };
841
+ return { markup, box: labelBox };
838
842
  }
839
843
 
844
+ /** A coordinate as the SVG attributes draw it: rounded to two decimals, which is what the gate checks. */
845
+ const drawn2 = (/** @type {number} */ n) => Number(num(n));
846
+
840
847
  /**
841
848
  * A pill: a stemless tag, a rounded box of text centred on the screen point
842
849
  * (`x`, `y`), for the tags and badges that stand on their own. Its `box` goes
@@ -860,7 +867,7 @@ export function labelPill({ id, x, y, lines, fontSize = 14, fill = "surface", st
860
867
  el("rect", { x: left, y: top, width, height, rx: height / 2, fill: tok(token(fill)), stroke: tok(token(stroke)), "stroke-width": 1.5 }),
861
868
  text({ x, y, "text-anchor": "middle", "dominant-baseline": "central", "font-size": fontSize, "font-weight": 600, fill: tok(token(ink)) }, lines, LINE_HEIGHT),
862
869
  );
863
- return { markup, box: { id, x: left, y: top, width, height, opacity } };
870
+ return { markup, box: { id, x: drawn2(left), y: drawn2(top), width: drawn2(width), height: drawn2(height), opacity } };
864
871
  }
865
872
 
866
873
  /**
@@ -890,22 +897,50 @@ function segmentHits(s, r) {
890
897
  * What is wrong with a set of drawn labels: two boxes closer than `gap`
891
898
  * pixels (overlapping), a stem running through another label, a box outside
892
899
  * the picture. Boxes with `opacity` 0 are not drawn and are skipped. Each
893
- * problem is one sentence; none for a clean set.
900
+ * problem is one sentence, and a repeated sentence is reported once; none for
901
+ * a clean set. It stops at `limit` problems (default: all; 0 returns none; a
902
+ * `limit` that is not a whole number from 0 or Infinity throws `RangeError`), so collection ends once it has
903
+ * that many; the collision scan can end early, after the boxes are filtered and indexed. Sentences in `ignore` are skipped
904
+ * and do not count towards the limit.
894
905
  * @param {LabelBox[]} boxes
895
- * @param {{ width: number, height: number, gap?: number }} view the picture's size
906
+ * @param {{ width: number, height: number, gap?: number, limit?: number, ignore?: Set<string> }} view the picture's size
896
907
  * @returns {string[]}
897
908
  */
898
- export function labelProblems(boxes, { width, height, gap = 4 }) {
909
+ export function labelProblems(boxes, { width, height, gap = 4, limit = Infinity, ignore }) {
910
+ if (!(limit === Infinity || (Number.isInteger(limit) && limit >= 0))) throw new RangeError(`labelProblems: limit must be a whole number from 0, or Infinity, got ${typeof limit === "number" ? limit : `a value of type ${typeof limit}`}`);
911
+ if (limit === 0) return [];
912
+ const eps = 1e-9; // rounded box edges that meet exactly must not fail on float noise
899
913
  // Drawn unless it fades out: `fade` drops an element whose opacity rounds to 0.
900
- const drawn = boxes.filter((b) => b.opacity === undefined || Math.round(b.opacity * 1000) > 0);
914
+ // Exact copies (same id, geometry and stem coordinates) all say the same sentences, and two
915
+ // of them already report an overlap with each other, so a third adds nothing:
916
+ // keep two, which bounds the work on a scene that repeats one box thousands of times.
917
+ /** @type {Map<string, number>} */
918
+ const copies = new Map();
919
+ const drawn = boxes.filter((b) => {
920
+ if (b.opacity !== undefined && Math.round(b.opacity * 1000) <= 0) return false;
921
+ const key = JSON.stringify([b.id, b.x, b.y, b.width, b.height, b.stem && [b.stem.x1, b.stem.y1, b.stem.x2, b.stem.y2]]);
922
+ const n = (copies.get(key) ?? 0) + 1;
923
+ copies.set(key, n);
924
+ return n <= 2;
925
+ });
926
+ /** @type {string[]} */
901
927
  const problems = [];
928
+ /** @type {Set<string>} */
929
+ const found = new Set();
930
+ /** @param {string} message @returns {boolean} whether the limit is reached */
931
+ const add = (message) => {
932
+ if (ignore?.has(message) || found.has(message)) return false;
933
+ found.add(message);
934
+ return problems.push(message) >= limit;
935
+ };
902
936
  for (const [i, a] of drawn.entries()) {
903
- if (a.x < 0 || a.y < 0 || a.x + a.width > width || a.y + a.height > height) problems.push(`label "${a.id}" is outside the picture`);
904
- for (const b of drawn.slice(i + 1)) {
905
- if (a.x < b.x + b.width + gap && b.x < a.x + a.width + gap && a.y < b.y + b.height + gap && b.y < a.y + a.height + gap) problems.push(`labels "${a.id}" and "${b.id}" overlap`);
937
+ if ((a.x < -eps || a.y < -eps || a.x + a.width > width + eps || a.y + a.height > height + eps) && add(`label "${a.id}" is outside the picture`)) return problems;
938
+ for (let j = i + 1; j < drawn.length; j++) {
939
+ const b = drawn[j];
940
+ if (a.x < b.x + b.width + gap - eps && b.x < a.x + a.width + gap - eps && a.y < b.y + b.height + gap - eps && b.y < a.y + a.height + gap - eps && add(`labels "${a.id}" and "${b.id}" overlap`)) return problems;
906
941
  }
907
942
  for (const b of drawn) {
908
- if (b !== a && b.stem && segmentHits(b.stem, a)) problems.push(`the stem of label "${b.id}" crosses label "${a.id}"`);
943
+ if (b !== a && b.stem && segmentHits(b.stem, a) && add(`the stem of label "${b.id}" crosses label "${a.id}"`)) return problems;
909
944
  }
910
945
  }
911
946
  return problems;
package/runtime/kit.mjs CHANGED
@@ -25,7 +25,7 @@ import { DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, ea
25
25
  import { FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId } from "./scene.mjs";
26
26
  import { CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, contrastReport, cssVars, normalizeStyle, resolveTokens, sharedPairs, tok } from "./style.mjs";
27
27
  import { CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawGrid, drawOnPlane, drawSolid, drawSolids, fitCamera, labelAnchor, labelPill, labelProblems, lerpCamera, orderSolids, path3, planeMatrix, prism, project, projector, regularPolygon, roundedBox, roundedSlab, slab } from "./iso.mjs";
28
- import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment } from "./svg.mjs";
28
+ import { attrString, blurReveal, cubic, dist, drawOn, el, esc, fade, highlightSweep, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment } from "./svg.mjs";
29
29
  import { PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead } from "./connectors.mjs";
30
30
  import { estimateWidth, wrapLabel } from "./wrap.mjs";
31
31
 
@@ -39,7 +39,7 @@ export const KIT = Object.freeze({
39
39
  ...{ DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
40
40
  ...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
41
41
  ...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, contrastReport, cssVars, normalizeStyle, resolveTokens, sharedPairs, tok },
42
- ...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
42
+ ...{ attrString, blurReveal, cubic, dist, drawOn, el, esc, fade, highlightSweep, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
43
43
  ...{ CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawGrid, drawOnPlane, drawSolid, drawSolids, fitCamera, labelAnchor, labelPill, labelProblems, lerpCamera, orderSolids, path3, planeMatrix, prism, project, projector, regularPolygon, roundedBox, roundedSlab, slab },
44
44
  ...{ PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead },
45
45
  ...{ estimateWidth, wrapLabel },
package/runtime/svg.mjs CHANGED
@@ -8,7 +8,8 @@
8
8
  * here; numbers are rounded here. Numbers you interpolate into a template
9
9
  * string yourself (transform, points, path d) must go through `num()`.
10
10
  */
11
- import { easeStandard, progress } from "./motion.mjs";
11
+ import { clamp01, easeStandard, progress } from "./motion.mjs";
12
+ import { tok } from "./style.mjs";
12
13
 
13
14
  const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
14
15
 
@@ -74,6 +75,84 @@ export function fade(opacity, attrs, ...children) {
74
75
  return el("g", { ...attrs, opacity: o >= 1 ? undefined : o }, ...children);
75
76
  }
76
77
 
78
+ /**
79
+ * Reveal: opacity, a small rise and a blur that goes to zero, on one group.
80
+ * The element starts soft, transparent and `rise` units low and sharpens into
81
+ * place as `enter` goes from 0 to 1 (`progress(t, start, 0.3–0.6, ease)`, with
82
+ * the style's entrance curve: `easings(style.motion).easeOut`).
83
+ *
84
+ * The blur is an SVG filter, which is the one thing a frame must clean up
85
+ * after: once `enter` reaches 1 (as `fade` rounds it) the children come back
86
+ * bare, with no group, no filter and no `<defs>`, so a settled frame is
87
+ * byte-identical to the same markup drawn without the reveal. Before it
88
+ * starts (`enter` ≤ 0) nothing is drawn.
89
+ *
90
+ * `id` names the filter and must be built from the frame's `idPrefix`
91
+ * (`${idPrefix}-reveal-1`), one id per revealed element: two instances on a
92
+ * page, and every slice of a baked SVG, then never share a filter. The filter
93
+ * works in sRGB, so every renderer blurs the same colours. Its region is the
94
+ * element's box plus 25 % sideways and 100 % above and below, which holds the
95
+ * blur of text at least about 50 units wide; for anything narrower (a short
96
+ * label, an icon) or a larger `blur`, pass `box`, the element's own
97
+ * `{ x, y, width, height }`, and the region becomes that box plus 3 × `blur`
98
+ * on every side, in the element's own units.
99
+ *
100
+ * @param {number} enter eased progress, 0 to 1
101
+ * @param {{ id: string, rise?: number, blur?: number, box?: { x: number, y: number, width: number, height: number } }} options
102
+ * `rise`: units it starts below its place (default 6); `blur`: its starting
103
+ * blur radius, in units (default 4, at most 12); `box`: the element's box, see above
104
+ * @param {...(string | string[])} children markup
105
+ * @returns {string}
106
+ */
107
+ export function blurReveal(enter, { id, rise = 6, blur = 4, box }, ...children) {
108
+ if (typeof id !== "string" || !/^[A-Za-z][\w-]*$/.test(id)) throw new Error(`blurReveal: id must be a CSS-safe id built from idPrefix, got ${JSON.stringify(id)}`);
109
+ if (!Number.isFinite(rise) || rise < 0 || rise > 24) throw new Error(`blurReveal: rise must be a number from 0 to 24, got ${rise}`);
110
+ if (!Number.isFinite(blur) || blur < 0 || blur > 12) throw new Error(`blurReveal: blur must be a number from 0 to 12, got ${blur}`);
111
+ if (box !== undefined && !(box && ["x", "y", "width", "height"].every((k) => Number.isFinite(box[k])) && box.width > 0 && box.height > 0)) throw new Error("blurReveal: box must be { x, y, width, height } with finite numbers and a positive size");
112
+ const o = Math.round(clamp01(enter) * 1000) / 1000; // as fade(): 0.9999 ≡ 1
113
+ if (o <= 0) return "";
114
+ const body = children.flat().filter(Boolean).join("");
115
+ if (o >= 1) return body;
116
+ const dy = (1 - o) * rise;
117
+ const sd = (1 - o) * blur;
118
+ const blurred = sd >= 0.005; // below that it rounds to 0 and would filter nothing
119
+ const m = 3 * blur;
120
+ const region = box
121
+ ? { filterUnits: "userSpaceOnUse", x: box.x - m, y: box.y - m, width: box.width + 2 * m, height: box.height + 2 * m }
122
+ : { x: "-25%", y: "-100%", width: "150%", height: "300%" };
123
+ const filter = blurred ? `<defs>${el("filter", { id, ...region, "color-interpolation-filters": "sRGB" }, el("feGaussianBlur", { stdDeviation: sd }))}</defs>` : "";
124
+ return filter + el("g", { transform: dy >= 0.005 ? translate(0, dy) : undefined, opacity: o, filter: blurred ? `url(#${id})` : undefined }, body);
125
+ }
126
+
127
+ /**
128
+ * Highlighter sweep: a band in a token colour at low opacity that grows from
129
+ * its left edge to `x + width` as `p` goes from 0 to 1. Draw it before the
130
+ * text it marks, so the text sits on top; size it to the line
131
+ * (`estimateWidth(line, fontSize)` plus a little padding each side). Nothing is
132
+ * drawn at `p` ≤ 0, and at 1 the band is the same rectangle every frame.
133
+ *
134
+ * Keep `opacity` low (0.2 to 0.4) as a starting point: the text drawn over it
135
+ * keeps its contrast only while the band stays a light tint of the canvas, and
136
+ * the gate checks the text against the canvas, not against the band. For a
137
+ * custom style, check the ink against the composited tint yourself (the neutral
138
+ * style does at 0.3). `token` is any style token;
139
+ * the default `emphasis` is the style's marker colour.
140
+ *
141
+ * @param {number} p eased progress, 0 to 1
142
+ * @param {{ x: number, y: number, width: number, height: number, token?: string, opacity?: number, radius?: number }} band
143
+ * @returns {string}
144
+ */
145
+ export function highlightSweep(p, { x, y, width, height, token = "emphasis", opacity = 0.3, radius = 4 }) {
146
+ for (const [name, v] of [["x", x], ["y", y], ["width", width], ["height", height], ["radius", radius]]) {
147
+ if (!Number.isFinite(v)) throw new Error(`highlightSweep: ${name} must be a finite number, got ${v}`);
148
+ }
149
+ if (width <= 0 || height <= 0) throw new Error("highlightSweep: width and height must be positive");
150
+ if (!(Number.isFinite(opacity) && opacity > 0 && opacity <= 1)) throw new Error(`highlightSweep: opacity must be above 0 and at most 1, got ${opacity}`);
151
+ const w = width * clamp01(p);
152
+ if (w < 0.01) return "";
153
+ return el("rect", { x, y, width: w, height, rx: Math.max(0, Math.min(radius, w / 2, height / 2)), fill: tok(token), opacity });
154
+ }
155
+
77
156
  /* ---------------------------------------------------------------- geometry */
78
157
 
79
158
  export function dist(a, b) {
@@ -58,8 +58,9 @@ from the system's package manager (`brew install ffmpeg`, `apt install ffmpeg`).
58
58
  flowchart? `motion-kit import flow.mmd --out flow.json` writes the spec
59
59
  (layout computed once). Only write a custom scene module when no type fits
60
60
  (`references/custom-scenes.md`): that file also covers an isometric view
61
- (camera, solids, depth order, label anchors), several tokens moving at once and
62
- dashed connectors with diamond junctions and light pulses.
61
+ (camera, solids, depth order, label anchors), several tokens moving at once, dashed
62
+ connectors with diamond junctions and light pulses, and text that sharpens into place
63
+ with a highlighter sweep (`blurReveal`, `highlightSweep`).
63
64
  4. **Gate.** `motion-kit check spec.json` must pass in every format/locale
64
65
  shipped: deterministic, settled steps, rounded numbers, token-only colours,
65
66
  escaped labels, labels fit, holds the final frame.
@@ -194,6 +194,48 @@ Canon: no loops, no ambient motion, no continuous scrubbing, 12 s hard limit
194
194
  other, and under reduced motion the player shows that frame. A constantly
195
195
  moving hero is a 3D model's job, not motion-kit's.
196
196
 
197
+ ## Text that sharpens into place, and a highlighter
198
+
199
+ `kit` carries text helpers (`runtime/svg.mjs`), for a label or a quote that
200
+ should arrive as a beat and not just appear. Template:
201
+ `examples/text-reveal.scene.mjs` (three labels reveal in reading order, then a
202
+ quoted line reveals and is marked).
203
+
204
+ | Need | Use |
205
+ |---|---|
206
+ | A reveal | `blurReveal(enter, { id, rise, blur }, ...markup)` with `enter = progress(t, start, 0.4, easings(style.motion).easeOut)`. The markup starts soft, transparent and `rise` units low (default 6) and sharpens into place; `blur` is the starting radius (default 4, at most 12). Any markup works, a `<text>`, a group, a card. The default region holds the blur when the element's painted bounds are at least 12 × `blur` units wide (50 units at the default blur) **and** at least 3 × `blur` units tall (it adds only one element height above and below). For a narrower or shallower element, a short label, a thin rule or an icon, a larger `blur`, or any shape whose stroke or markers reach past its geometry by more than that padding (a thick stroke on a small shape, at any size), pass `box: { x, y, width, height }` covering the painted bounds (all four finite; `width` and `height` positive; `x` and `y` may be anything) |
207
+ | Its filter id | `id: idPrefix + "-reveal-" + i`, one per revealed element. The gate reports ids shared across instances at its sampled times (it can miss a short reveal between samples), so keep the prefix, and every slice of a baked SVG has its own prefix |
208
+ | A highlighter | `highlightSweep(p, { x, y, width, height, token, opacity, radius })`: a band in a token (default `emphasis`) at 30 % that grows from `x` to `x + width` as `p` (eased) goes 0 → 1; its `token` is checked once the band is drawn. Draw it **before** the text; size it from `estimateWidth(line, fontSize)` plus padding each side (the estimate is generous; do not shrink it where wide glyphs such as a capital W may appear, since they can run past a shortened band. `examples/text-reveal.scene.mjs` takes 0.9 of it for its fixed lines only, checked by eye in the rendered frames; the gate does not compare glyph widths with the band) |
209
+
210
+ Rules that keep it inside the canon:
211
+
212
+ - **Settled means bare.** When `enter` reaches 1, `blurReveal` returns your
213
+ markup with no group, no filter and no `<defs>`, so every step frame and the
214
+ final frame are byte-identical to the same text drawn without the reveal, provided the scene finishes the reveal (the gate checks only that those frames are stable).
215
+ Finish each reveal 50 ms or more before the step it belongs to, as with any
216
+ beat; the gate's settled-step rule then holds. Do not wrap the call in your
217
+ own filter or opacity.
218
+ - **Once per element, inside a beat.** A reveal runs 300–600 ms and never
219
+ repeats. Stagger siblings 80–150 ms in reading order. A blinking cursor or any
220
+ other loop is ambient motion and stays out; a static cursor is fine.
221
+ - **Reduced motion** shows the final frame, which is the settled text and the
222
+ full band: no filter, no motion.
223
+ - **Renderers.** The live player (in-place patch), `bake`, PNG export (resvg,
224
+ Chrome) and video use the same helper and filter parameters; the raster blur can vary with renderer, fonts and scale, and only one resvg frame is checked. A consumer that ignores SVG filters
225
+ shows the fade and the rise only, and only mid-reveal; step frames carry no
226
+ filter.
227
+ - **Cost.** A blur is the most expensive thing a frame can ask the browser for.
228
+ Reveal the handful of elements the viewer must watch arrive, not every
229
+ element in a dense diagram; for those, `fade()` is enough
230
+ (`motion-vocabulary.md`, "Blur reveal or plain fade").
231
+ - **Contrast.** Start the band's `opacity` at 0.2–0.4, but the gate checks the
232
+ text against the canvas, not against the tinted band. With a custom style,
233
+ composite the band colour at that opacity over the token actually behind it
234
+ (`bg` for text on the canvas, `surface` for text on a node, `accent` for text
235
+ on an active node) and check every text colour actually drawn there (`ink`, `muted` for
236
+ pending labels, or `onAccent` on an accent fill) against the result (4.5:1), or lower the
237
+ opacity until it holds.
238
+
197
239
  ## Declared locales and narrative steps
198
240
 
199
241
  Export `const locales = ["en", "nl"]` alongside the default factory so both
@@ -25,6 +25,23 @@ custom scene's `frame` rather than importing the constants.
25
25
  | Pause between beats | ≥ 50 ms, so step frames settle |
26
26
  | Whole explainer | aim for ≤ 8 s, then hold; gate limit 12 s |
27
27
 
28
+ ## Blur reveal or plain fade (`blurReveal`, `highlightSweep`)
29
+
30
+ | | Plain fade (`fade`, the node parts' 8-unit rise) | Blur reveal (`blurReveal`) |
31
+ |---|---|---|
32
+ | Use it for | Nodes, connectors, anything in a dense diagram; text that is not the point of the beat | Text the viewer should watch land: a heading, the label of the one thing the beat introduces, a quoted line, a card |
33
+ | Looks like | Appears from transparent, rising a few units | The same, and starts soft: sharpens into place over the same 300–600 ms |
34
+ | Cost | Opacity and transform only | An SVG filter per revealing element, every frame of the reveal. Keep to a few elements at a time |
35
+ | Settled | No opacity or transform left; `fade` still wraps the markup in a `<g>` | No trace: the markup comes back bare, byte-identical |
36
+
37
+ Reveal in reading order, siblings 80–150 ms apart, on the style's entrance
38
+ curve. A reveal that does not carry a beat is decoration: use the fade. A
39
+ `highlightSweep` marks one thing in a scene (it uses the `emphasis` token, and
40
+ there is one emphasis element), grows left to right behind its text over about
41
+ 0.6 s on the entrance curve, and starts while the text is still sharpening or
42
+ once it has. Neither helper loops; a blinking cursor is ambient motion, so a
43
+ cursor stays static.
44
+
28
45
  ## Springs, without breaking random access (derived)
29
46
 
30
47
  Frame-by-frame spring simulation depends on earlier frames. Use the closed form.