@liqweed/motion-kit 0.11.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.
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.
@@ -117,8 +117,9 @@ relative imports to a vendored runtime.
117
117
  ## Isometric and 3D-looking scenes
118
118
 
119
119
  `kit` carries a small isometric kit (`runtime/iso.mjs`), for a floor, machines
120
- or buildings seen from an angle. Template: `examples/isometric-swivel.scene.mjs`
121
- (plan view that swivels to isometric, then three work items travel a line).
120
+ or buildings seen from an angle. Templates: `examples/isometric-swivel.scene.mjs`
121
+ (plan view that swivels to isometric, then three work items travel a line) and
122
+ `examples/isometric-platform.scene.mjs` (rounded slabs, grid backdrop, a mark on a top face, pill tags).
122
123
  Everything is a pure function: the same camera and solids give the same bytes.
123
124
 
124
125
  World: x east, y north, `z` up, in any unit you like. Colours are token names
@@ -133,11 +134,15 @@ World: x east, y north, `z` up, in any unit you like. Colours are token names
133
134
  | Solids | `box({ x, y, w, d, h, z })` (centred on x, y), `slab({ x, y, w, d })` (a thin box, for a floor), `prism({ points, h, z })` with `regularPolygon(x, y, r, n)` for a footprint. Options: `fill` (top token), `sides` (side token, default `fill`), `shade` (token layered over the sides at 10–26 %, `null` for flat; `ink` darkens in the light theme and lightens in the dark one, pick `bg` where the dark theme should be darker), `stroke`, `opacity`, `id` |
134
135
  | Draw them | `drawSolid(solid, cam)`, or `drawSolids(list, cam)`, which orders them far to near first (`orderSolids` alone returns the order). Only faces that face the camera are drawn: at 90° elevation just the tops |
135
136
  | Animate a solid | Build it again each frame with the animated `h`, `z` or `opacity`. Two-state fills cross-fade two solids (`fade(p, {}, drawSolid(reached, cam))` over the pending one), as with any other element |
137
+ | Rounded solids | `roundedBox({ x, y, w, d, h, z, radius, segments })` and `roundedSlab({ x, y, w, d, radius })` (thin, for a floor or platform): a box with rounded vertical corners, `radius` up to half the shorter side, `segments` (default 8) per corner. Same options as `box`, same depth order. The visible sides draw as **one wall, outlined once**, so a rounded side has no seam per sample; only its shade changes. Use these, never a rounded rect sampled into a `prism`, which draws a face and a stroke per sample |
138
+ | A grid backdrop | `drawGrid(cam, { radius, step, stroke, opacity })`: grid lines in the floor plane (`z` for another height) that fade out radially from (`x`, `y`) in a few rings, diamonds in isometric. Token colour (`line` by default) at low opacity. **Draw it first**, under the solids: it has no depth. It is static; do not animate it (a shimmer or pan is ambient motion), fade it in with `opacity` like anything else |
139
+ | 2D content on a face | Give a solid a `top`: `{ markup, view: { width, height }, inset, opacity }`. `markup` is ordinary SVG (an icon's paths, `text`, rects) in its own `view` units (24 × 24 for an icon grid; stroke widths and font sizes in those units); it is fitted into the top face's bounding box less `inset`, centred, aspect kept, and turns with the camera, through a swivel. It is drawn inside the solid, so it is ordered and faded with it. For any horizontal plane at a height (a layer of a mock UI split along z), `drawOnPlane(cam, { x, y, z, w, d, view }, markup, opacity)`, drawn right after the solid below it; `planeMatrix(cam, plane)` gives the SVG matrix alone. Not drawn when the plane is edge on (elevation 0) |
136
140
  | Labels | `labelAnchor(cam, { id, at: { x, y, z }, lines, lift, side, opacity })` → `{ markup, box }`: a dot on the point, a stem `lift` px up, the label above it (`side: "up"`, or beside the stem's top with `"right"` / `"left"`). Wrap and localize `lines` first (`wrapLabel`) |
141
+ | Pill tags | `labelPill({ id, x, y, lines, fontSize, fill, stroke, ink, opacity })` → `{ markup, box }`: a stemless rounded box of text centred on the screen point `x, y` (`project(cam, point)` plus an offset to pin it to the world). Colours are tokens; pick an `ink` that reads on `fill` (`onAccent` on `accent`). Return its `box` from `labelBoxes` with the anchors' |
137
142
  | Several tokens | `tokensAlong(path, t, runs, draw)`: see below |
138
143
 
139
144
  **The gate checks labels.** Return `labelBoxes: (t) => [box, …]` from the scene
140
- (the `box` of each `labelAnchor` you draw at `t`), and `motion-kit check` fails
145
+ (the `box` of each `labelAnchor` and `labelPill` you draw at `t`), and `motion-kit check` fails
141
146
  the scene when, at any sampled time or step, two label boxes overlap (closer
142
147
  than 4 px), a stem runs through another label, or a box leaves the picture. Fix
143
148
  it in the layout: alternate `lift` between neighbours (more in a narrow format,
@@ -189,6 +194,48 @@ Canon: no loops, no ambient motion, no continuous scrubbing, 12 s hard limit
189
194
  other, and under reduced motion the player shows that frame. A constantly
190
195
  moving hero is a 3D model's job, not motion-kit's.
191
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
+
192
239
  ## Declared locales and narrative steps
193
240
 
194
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.
@@ -69,6 +86,10 @@ Use 50–100 ms lag. Draw the shape from `trail` to `lead`.
69
86
  height is invisible. Draw a flat top first (`h` > 0 only so the faces exist).
70
87
  - **Depth:** `orderSolids` is the order; never draw by hand. Heights and
71
88
  footprints decide it; a floor slab is drawn first.
89
+ - **Backdrop, faces and tags:** the grid backdrop is static: it fades in with
90
+ the floor and then rests (a shimmer or pan is ambient motion). Content on a
91
+ top face fades in after its solid has settled, and turns with the camera
92
+ like any face. Pill tags fade in like labels, once the camera rests.
72
93
  - **Several tokens:** stagger their starts by 0.25–0.4 s on a trip of 1.2–2 s,
73
94
  so 3–4 are in flight at once without touching. Use `linear` for tokens that
74
95
  travel a conveyor at a steady speed, and grow them in and out over the first