@liqweed/motion-kit 0.12.0 → 0.14.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/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.14.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 examples/bars.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",
@@ -0,0 +1,226 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · bars with values, for custom scenes (`kit`).
5
+ *
6
+ * Parts for a row of a benchmark-style chart, as pure functions of time:
7
+ *
8
+ * - a **hatch**: a pattern of diagonal lines at 45° in a token colour, whose id
9
+ * is built from the frame's `idPrefix` (`hatchPattern`);
10
+ * - a **track**: a rounded, empty bar filled with that hatching (`drawTrack`);
11
+ * - a **bar**: a rounded bar that grows over the track from its start
12
+ * (`drawBar`), on the style's movement curve (`barProgress`);
13
+ * - a **value**: a number that rolls from a start value to its end value with
14
+ * the bar's progress, formatted by the caller (`drawValue`, `rollingValue`).
15
+ *
16
+ * Nothing here repeats. A bar grows once inside its step's beat and rests; its
17
+ * value shows exactly its end value from the moment the bar has settled, so a
18
+ * step frame is the settled frame (`barEnd` says when). Colours are token
19
+ * names, never literals.
20
+ *
21
+ * Imports stay single-line named imports: lib/bundle.mjs inlines only that form.
22
+ */
23
+ import { clamp01, easings, lerp, progress } from "./motion.mjs";
24
+ import { safeId } from "./scene.mjs";
25
+ import { tok } from "./style.mjs";
26
+ import { el, fade, num, text } from "./svg.mjs";
27
+
28
+ /** @import { Style } from "./style.mjs" */
29
+
30
+ /** @param {number} n */
31
+ const finite = (n) => typeof n === "number" && Number.isFinite(n);
32
+ /** What may stand in an id: the characters `safeId` leaves. */
33
+ const ID_PART = /^[A-Za-z0-9_]+$/;
34
+ /** Names `renderSvg` already uses for ids (`${id}-title`, `${id}-desc`). */
35
+ const RESERVED_NAMES = new Set(["title", "desc"]);
36
+ /** @param {unknown} value */
37
+ const renderedFinite = (value) => typeof value === "number" && finite(value) && finite(Number(num(value)));
38
+ /**
39
+ * The paint `drawTrack` emits for a hatch: `fill`, read once as a data property of a frozen
40
+ * object (so a getter or a later write cannot change it) and shaped `url(#id)`. It is the only
41
+ * hatch value `drawTrack` emits; `markup` is the `<defs>` the scene puts in its own frame, so
42
+ * it is not checked here (a hatch must come from `hatchPattern`, from any vendored copy).
43
+ * @param {unknown} hatch
44
+ * @returns {string | null}
45
+ */
46
+ const hatchFill = (hatch) => {
47
+ if (!hatch || typeof hatch !== "object" || !Object.isFrozen(hatch)) return null;
48
+ const field = Object.getOwnPropertyDescriptor(hatch, "fill");
49
+ if (!field || !("value" in field)) return null;
50
+ return typeof field.value === "string" && /^url\(#[A-Za-z][A-Za-z0-9_-]*\)$/.test(field.value) ? field.value : null;
51
+ };
52
+
53
+ /**
54
+ * @typedef {{ readonly id: string, readonly fill: string, readonly markup: string }} Hatch
55
+ * `markup` is the `<defs>` holding the pattern: put it in the frame once,
56
+ * before any track that uses it, every frame. `fill` is the paint to refer to
57
+ * it, `url(#id)`.
58
+ */
59
+
60
+ /**
61
+ * Diagonal hatching: lines at 45°, rising to the right, `spacing` pixels apart
62
+ * (measured across the lines) and `width` pixels wide, in the token `stroke`.
63
+ * The pattern is anchored to the picture, not to a track, so tracks that use it
64
+ * show one continuous hatch. Its id is `<prefix>-hatch-<name>`; `idPrefix` is normalized with `safeId`, so prefixes must
65
+ * be unique after that normalization: the frame's prefix keeps two instances on a page separate, and a scene that draws
66
+ * several hatchings gives each its own `name`.
67
+ * @param {{ idPrefix: string, name?: string, stroke?: string, spacing?: number, width?: number }} o
68
+ * @returns {Hatch}
69
+ */
70
+ export function hatchPattern({ idPrefix, name = "hatch", stroke = "line", spacing = 7, width = 1.5 }) {
71
+ if (typeof idPrefix !== "string" || idPrefix === "") throw new Error(`hatchPattern: idPrefix must be the frame's idPrefix, a non-empty string, got ${JSON.stringify(idPrefix)}`);
72
+ if (typeof name !== "string" || !ID_PART.test(name)) throw new Error(`hatchPattern: name must use letters, digits and "_" (no "-", which ends the prefix in the id), got ${JSON.stringify(name)}`);
73
+ if (RESERVED_NAMES.has(name)) throw new Error(`hatchPattern: name "${name}" is reserved for the picture's own ids`);
74
+ if (!finite(spacing) || spacing <= 0) throw new Error(`hatchPattern: spacing must be a finite positive number, got ${spacing}`);
75
+ if (!finite(width) || width <= 0 || width >= spacing) throw new Error(`hatchPattern: width must be finite, more than 0 and less than the spacing, got ${width} of ${spacing}`);
76
+ const drawnSpacing = Number(num(spacing));
77
+ const drawnWidth = Number(num(width));
78
+ if (!finite(drawnSpacing) || drawnSpacing <= 0) throw new Error(`hatchPattern: spacing must remain finite and positive after SVG rounding, got ${spacing}`);
79
+ if (!finite(drawnWidth) || drawnWidth <= 0 || drawnWidth >= drawnSpacing) throw new Error(`hatchPattern: width must remain finite, more than 0 and less than the spacing after SVG rounding, got ${width} of ${spacing}`);
80
+ const id = `${safeId(idPrefix)}-hatch-${name}`; // normalized here so a direct call with a raw prefix (as in the tests) matches what renderSvg passes
81
+ // One vertical line in the middle of a square tile, turned 45° by the pattern.
82
+ const line = el("path", { d: `M${num(spacing / 2)} 0 V${num(spacing)}`, fill: "none", stroke: tok(stroke), "stroke-width": width });
83
+ const pattern = el("pattern", { id, width: spacing, height: spacing, patternUnits: "userSpaceOnUse", patternTransform: "rotate(45)" }, line);
84
+ const hatch = Object.freeze({ id, fill: `url(#${id})`, markup: el("defs", {}, pattern) });
85
+ return hatch;
86
+ }
87
+
88
+ /** @param {string} who @param {{ x: number, y: number, width: number, height: number }} r */
89
+ function checkRect(who, { x, y, width, height }, allowEmpty = false) {
90
+ if (![x, y, width, height].every(renderedFinite)) throw new Error(`${who}: x, y, width and height must remain finite after SVG rounding`);
91
+ if (allowEmpty && width === 0 && height > 0) return;
92
+ if (width <= 0 || height <= 0) throw new Error(`${who}: width and height must be positive, got ${width} × ${height}`);
93
+ if ((!allowEmpty && Number(num(width)) <= 0) || Number(num(height)) <= 0) throw new Error(`${who}: width and height must remain positive after SVG rounding, got ${width} × ${height}`);
94
+ }
95
+
96
+ /** The corner radius for a rect `w` × `h`: `radius`, never more than half of either side. */
97
+ const corner = (/** @type {number | undefined} */ radius, /** @type {number} */ w, /** @type {number} */ h) => {
98
+ const r = radius ?? h / 2;
99
+ if (!finite(r) || r < 0) throw new Error(`radius must be a finite number of 0 or more, got ${radius}`);
100
+ return Math.min(r, w / 2, h / 2);
101
+ };
102
+
103
+ /**
104
+ * An empty track: a rounded bar of `width` × `height` at (`x`, `y`), filled with
105
+ * the token `fill` (default `surface`; `null` for none) and, over it, with the
106
+ * `hatch` when one is given. A track needs one of the two. `radius` defaults to
107
+ * half the height, a pill.
108
+ * @param {{ x: number, y: number, width: number, height: number, hatch?: Hatch, fill?: string | null, radius?: number, opacity?: number, id?: string }} o
109
+ * @returns {string}
110
+ */
111
+ export function drawTrack({ x, y, width, height, hatch, fill = "surface", radius, opacity = 1, id }) {
112
+ checkRect("drawTrack", { x, y, width, height });
113
+ const hatchPaint = hatch === undefined ? null : hatchFill(hatch);
114
+ if (hatch !== undefined && !hatchPaint) throw new Error("drawTrack: hatch must be a frozen hatchPattern result with a url(#id) fill");
115
+ if (!hatchPaint && fill === null) throw new Error("drawTrack: a track needs a fill or a hatch");
116
+ const rx = corner(radius, width, height);
117
+ const rect = (/** @type {string} */ paint) => el("rect", { x, y, width, height, rx, fill: paint });
118
+ return fade(opacity, id ? { "data-track": id } : {}, fill === null ? "" : rect(tok(fill)), hatchPaint ? rect(hatchPaint) : "");
119
+ }
120
+
121
+ /**
122
+ * A bar `width` long when it is done (its end value's share of the track, 0 for a zero value), drawn
123
+ * up to fraction `p` of it from its start at (`x`, `y`): `p` is the eased progress of its
124
+ * growth (`barProgress`), and the bar is rounded at both ends all the way, so
125
+ * it grows as a pill. Nothing for `p` ≤ 0; `p` ≥ 1 is the full bar it rests as.
126
+ * `trackWidth` clips a short bar to its track's silhouette; with it, `idPrefix`
127
+ * is the frame instance prefix and `id` is a safe, instance-local key.
128
+ * @param {{ x: number, y: number, width: number, height: number, p: number, fill?: string, radius?: number, trackRadius?: number, opacity?: number, id?: string, idPrefix?: string, trackWidth?: number }} o
129
+ * @returns {string}
130
+ */
131
+ export function drawBar({ x, y, width, height, p, fill = "accent", radius, trackRadius, opacity = 1, id, idPrefix, trackWidth }) {
132
+ checkRect("drawBar", { x, y, width, height }, true); // a zero value is a zero-width bar: nothing to draw
133
+ if (!finite(p)) throw new Error(`drawBar: p must be a finite number, got ${p}`);
134
+ if (trackWidth !== undefined && (!renderedFinite(trackWidth) || trackWidth <= 0 || trackWidth < width)) throw new Error(`drawBar: trackWidth must remain finite and at least the bar width, got ${trackWidth}`);
135
+ if (trackWidth !== undefined && (typeof idPrefix !== "string" || idPrefix === "" || typeof id !== "string" || !ID_PART.test(id) || RESERVED_NAMES.has(id))) throw new Error("drawBar: trackWidth needs the frame idPrefix and a non-reserved id using letters, digits and _");
136
+ const share = clamp01(p);
137
+ if (share <= 0) return "";
138
+ const w = width * share;
139
+ if (w <= 0) return "";
140
+ if (Number(num(w)) <= 0) return "";
141
+ if (!renderedFinite(w)) throw new Error(`drawBar: rendered width must remain finite, got ${w}`);
142
+ const bar = el("rect", { x, y, width: w, height, rx: corner(radius, w, height), fill: tok(fill) });
143
+ if (trackWidth === undefined) return fade(opacity, id ? { "data-bar": id } : {}, bar);
144
+ const clipId = `${safeId(idPrefix)}-clip-${id}`;
145
+ const clip = el("defs", {}, el("clipPath", { id: clipId }, el("rect", { x, y, width: trackWidth, height, rx: corner(trackRadius, trackWidth, height) })));
146
+ return fade(opacity, { "data-bar": id }, clip, el("g", { "clip-path": `url(#${clipId})` }, bar));
147
+ }
148
+
149
+ /**
150
+ * One bar's growth: it starts at `start` s and takes `duration` s.
151
+ * @typedef {{ start: number, duration: number }} BarRun
152
+ */
153
+
154
+ /**
155
+ * The eased progress of a bar's growth at time `t`, 0 before it starts and
156
+ * exactly 1 once it has ended, on the style's movement curve (`style.motion`,
157
+ * or the default curve for no style), so a bar moves as the rest of the diagram
158
+ * does on the page's own curve. `style` is the one `frame(t, { idPrefix, style })`
159
+ * is given.
160
+ * @param {number} t
161
+ * @param {BarRun} run
162
+ * @param {Pick<Style, "motion"> | null} [style]
163
+ * @returns {number}
164
+ */
165
+ export function barProgress(t, run, style) {
166
+ checkRun(run);
167
+ if (!finite(t)) throw new Error(`barProgress: t must be finite, got ${t}`);
168
+ if (t >= barEnd(run)) return 1;
169
+ return progress(t, run.start, run.duration, easings(style?.motion).easeStandard);
170
+ }
171
+
172
+ /**
173
+ * The time a bar has settled and its value shows its end value: `start +
174
+ * duration`. A scene's step comes at least 50 ms after this for every bar of
175
+ * its beat.
176
+ * @param {BarRun} run
177
+ * @returns {number}
178
+ */
179
+ export function barEnd(run) {
180
+ checkRun(run);
181
+ const end = run.start + run.duration;
182
+ if (!finite(end) || end <= run.start) throw new Error(`bar run: end must be finite and after start, got ${run.start} + ${run.duration}`);
183
+ return end;
184
+ }
185
+
186
+ /** @param {BarRun} run */
187
+ function checkRun(run) {
188
+ if (!run || !finite(run.start) || !finite(run.duration) || run.duration <= 0) throw new Error(`bar run: start must be finite and duration must be finite and above 0, got ${JSON.stringify(run)}`);
189
+ }
190
+
191
+ /**
192
+ * The value a number shows at progress `p` of its bar: `from` at 0, `to` at
193
+ * the end, and in between a straight line (the bar's easing already shapes
194
+ * it), so the number and the bar arrive together. At `p` ≥ 1 it is `to` itself,
195
+ * exactly, never a rounded sum.
196
+ * @param {number} from
197
+ * @param {number} to
198
+ * @param {number} p
199
+ * @returns {number}
200
+ */
201
+ export function rollingValue(from, to, p) {
202
+ if (!finite(from) || !finite(to) || !finite(p)) throw new Error(`rollingValue: from, to and p must be finite numbers, got ${from}, ${to}, ${p}`);
203
+ if (p >= 1) return to;
204
+ if (p <= 0) return from;
205
+ const v = lerp(from, to, p);
206
+ return finite(v) ? v : from * (1 - p) + to * p; // to - from overflowed: weigh each end instead
207
+ }
208
+
209
+ /**
210
+ * The number that rolls beside a bar: `format(rollingValue(from, to, p))` as
211
+ * text at (`x`, `y`), vertically centred on `y`. `format` is the caller's
212
+ * (units, decimals, locale: `(v) => new Intl.NumberFormat(locale, …).format(v)`)
213
+ * and must return a string; the default rounds to a whole number. Set `family`
214
+ * to a monospace face so the digits do not jitter as they change, and `anchor`
215
+ * to `"end"` at a fixed x so the number grows leftward, or `"start"` beside the
216
+ * bar's end.
217
+ * @param {{ x: number, y: number, to: number, from?: number, p: number, format?: (value: number) => string, fontSize?: number, anchor?: "start" | "middle" | "end", fill?: string, weight?: number, family?: string, opacity?: number, id?: string }} o
218
+ * @returns {string}
219
+ */
220
+ export function drawValue({ x, y, to, from = 0, p, format = (v) => num(v, 0), fontSize = 16, anchor = "start", fill = "ink", weight = 600, family, opacity = 1, id }) {
221
+ if (![x, y, fontSize, weight].every(renderedFinite) || fontSize <= 0 || Number(num(fontSize)) <= 0) throw new Error("drawValue: x, y, fontSize and weight must remain finite and the size positive after SVG rounding");
222
+ if (typeof format !== "function") throw new Error("drawValue: format must be a function (number) => string");
223
+ const shown = format(rollingValue(from, to, p));
224
+ if (typeof shown !== "string") throw new Error(`drawValue: format must return a string, got ${typeof shown}`);
225
+ return fade(opacity, id ? { "data-value": id } : {}, text({ x, y, "text-anchor": anchor, "dominant-baseline": "central", "font-size": fontSize, "font-weight": weight, "font-family": family, fill: tok(fill) }, shown));
226
+ }
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,13 +25,14 @@ 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
+ import { barEnd, barProgress, drawBar, drawTrack, drawValue, hatchPattern, rollingValue } from "./bars.mjs";
29
30
  import { PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead } from "./connectors.mjs";
30
31
  import { estimateWidth, wrapLabel } from "./wrap.mjs";
31
32
 
32
33
  /**
33
34
  * The runtime, flat, handed to custom scene modules as `opts.kit`: the exports
34
- * of motion, scene, style, svg, iso, connectors and wrap (not the scene types or the player).
35
+ * of motion, scene, style, svg, iso, connectors, bars and wrap (not the scene types or the player).
35
36
  * Named imports, because lib/bundle.mjs inlines only that form; a new export
36
37
  * in one of those modules is added here (test/runtime.test.mjs checks).
37
38
  */
@@ -39,9 +40,10 @@ export const KIT = Object.freeze({
39
40
  ...{ DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
40
41
  ...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
41
42
  ...{ 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 },
43
+ ...{ attrString, blurReveal, cubic, dist, drawOn, el, esc, fade, highlightSweep, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
43
44
  ...{ 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
45
  ...{ PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead },
46
+ ...{ barEnd, barProgress, drawBar, drawTrack, drawValue, hatchPattern, rollingValue },
45
47
  ...{ estimateWidth, wrapLabel },
46
48
  });
47
49
 
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,10 @@ 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, text that sharpens into place
63
+ with a highlighter sweep (`blurReveal`, `highlightSweep`), and hatched bar tracks
64
+ with bars that grow and values that roll.
63
65
  4. **Gate.** `motion-kit check spec.json` must pass in every format/locale
64
66
  shipped: deterministic, settled steps, rounded numbers, token-only colours,
65
67
  escaped labels, labels fit, holds the final frame.
@@ -114,7 +116,7 @@ headers when redistributing the vendored runtime and adapters.
114
116
  | `references/targets.md` | Where it will be shown and what each target allows |
115
117
  | `references/styles.md` | Neutral default, style files, brand presets, contrast |
116
118
  | `references/qc.md` | Review stages, checklist, review-report template |
117
- | `references/custom-scenes.md` | Writing a one-off scene module, including isometric views, several tokens at once, and connectors with pulses |
119
+ | `references/custom-scenes.md` | Writing a one-off scene module, including isometric views, several tokens at once, connectors with pulses, and bars with rolling values |
118
120
  | `references/ecosystem.md` | When GSAP, HyperFrames, Remotion, Motion Canvas, Manim, Mermaid or ELK are the better tool |
119
121
 
120
122
  For rendering, slide packaging and video, see the **motion-render** skill.