@liqweed/motion-kit 0.9.1 → 0.11.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqweed/motion-kit",
3
- "version": "0.9.1",
3
+ "version": "0.11.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 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 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,243 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · connectors, for custom scenes (`kit`).
5
+ *
6
+ * Parts that tie a diagram's pieces together, as pure functions of time:
7
+ *
8
+ * - a **connector**: a dashed line along a flat polyline or a path through the
9
+ * world (seen through an iso camera), with an optional open-V arrowhead. It
10
+ * draws on from its start, the dash pattern anchored there, and rests as a
11
+ * dashed line (`connectorPath`, `drawConnector`);
12
+ * - a **junction**: a small diamond where connectors turn, split or join, flat
13
+ * on the picture or lying in the floor plane of an iso view, that lights when
14
+ * a pulse reaches it (`drawJunction`);
15
+ * - a **pulse**: a light that travels a connector once, from its start to its
16
+ * end, with a glow and a short fading tail, and is gone (or held at the end)
17
+ * when it arrives (`drawPulse`, `pulseEnd`).
18
+ *
19
+ * Nothing here repeats. A pulse is one run inside a step's beat, as a token is;
20
+ * the scene keeps the steps settled by having every pulse over (`pulseEnd`) at
21
+ * least 50 ms before the step's time. Colours are token names, never literals.
22
+ *
23
+ * Imports stay single-line named imports: lib/bundle.mjs inlines only that form.
24
+ */
25
+ import { clamp01, easeStandard, progress } from "./motion.mjs";
26
+ import { projector } from "./iso.mjs";
27
+ import { tok } from "./style.mjs";
28
+ import { el, fade, num } from "./svg.mjs";
29
+
30
+ /** @import { Camera } from "./iso.mjs" */
31
+ /** @typedef {{ x: number, y: number, z?: number }} Vertex a flat point (z ignored) or a world point */
32
+
33
+ /**
34
+ * @typedef {{
35
+ * length: number,
36
+ * at: (f: number) => { x: number, y: number },
37
+ * cut: (f: number) => { x: number, y: number }[],
38
+ * span: (from: number, to: number) => { x: number, y: number }[],
39
+ * tip: (f: number) => { x: number, y: number, angle: number },
40
+ * }} ConnectorPath
41
+ * `length` is the length of the path in its own units (pixels when flat, world
42
+ * units under a camera). `at(f)` is the picture position at fraction `f` of
43
+ * that length, `cut(f)` the picture points of the path up to `f`, `span(from, to)` those
44
+ * between two fractions (every route vertex between them, so a corner stays a
45
+ * corner), and `tip(f)`
46
+ * the position at `f` with the direction of travel there, in radians.
47
+ */
48
+
49
+ /** @param {number} n */
50
+ const finite = (n) => typeof n === "number" && Number.isFinite(n);
51
+
52
+ /**
53
+ * A connector's route: through flat `points` (picture pixels), or, with a
54
+ * `camera`, through world points `{ x, y, z }` projected by it. Positions go by
55
+ * distance along the path (in the world under a camera), so a pulse on a linear
56
+ * `ease` keeps a constant speed in the world whatever the camera does.
57
+ * @param {Vertex[]} points
58
+ * @param {{ camera?: Camera }} [opts]
59
+ * @returns {ConnectorPath}
60
+ */
61
+ export function connectorPath(points, { camera } = {}) {
62
+ if (!Array.isArray(points) || points.length < 2) throw new Error("connectorPath: needs at least two points");
63
+ for (const p of points) if (!p || !finite(p.x) || !finite(p.y) || (p.z !== undefined && !finite(p.z))) throw new Error("connectorPath: points must be finite { x, y, z? }");
64
+ const world = camera ? points.map((p) => ({ x: p.x, y: p.y, z: p.z ?? 0 })) : points.map((p) => ({ x: p.x, y: p.y, z: 0 }));
65
+ const to = camera ? projector(camera) : (/** @type {Vertex} */ p) => ({ x: p.x, y: p.y });
66
+ const starts = [0];
67
+ for (let i = 1; i < world.length; i++) starts.push(starts[i - 1] + Math.hypot(world[i].x - world[i - 1].x, world[i].y - world[i - 1].y, world[i].z - world[i - 1].z));
68
+ const length = starts[starts.length - 1];
69
+ if (!Number.isFinite(length)) throw new Error("connectorPath: the path needs a finite length");
70
+ if (!(length > 0)) throw new Error("connectorPath: the path has no length");
71
+
72
+ /** The segment holding distance `d`, skipping any of zero length, and where in it. */
73
+ const locate = (/** @type {number} */ f) => {
74
+ const d = clamp01(f) * length;
75
+ let i = 1;
76
+ while (i < world.length - 1 && (d > starts[i] || starts[i] === starts[i - 1])) i++;
77
+ const span = starts[i] - starts[i - 1];
78
+ return { i, k: span === 0 ? 0 : Math.min(1, Math.max(0, (d - starts[i - 1]) / span)) };
79
+ };
80
+ const worldAt = (/** @type {number} */ f) => {
81
+ const { i, k } = locate(f);
82
+ const a = world[i - 1];
83
+ const b = world[i];
84
+ return { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k, z: a.z + (b.z - a.z) * k };
85
+ };
86
+ return {
87
+ length,
88
+ at: (f) => to(worldAt(f)),
89
+ cut(f) {
90
+ const { i } = locate(f);
91
+ return [...world.slice(0, i), worldAt(f)].map((p) => {
92
+ const s = to(p);
93
+ return { x: s.x, y: s.y };
94
+ });
95
+ },
96
+ span(from, to0) {
97
+ const a = clamp01(from);
98
+ const b = clamp01(to0);
99
+ const inner = world.filter((_, j) => starts[j] / length > a && starts[j] / length < b);
100
+ return [worldAt(a), ...inner, worldAt(b)].map((p) => {
101
+ const s = to(p);
102
+ return { x: s.x, y: s.y };
103
+ });
104
+ },
105
+ tip(f) {
106
+ const { i } = locate(f);
107
+ const here = to(worldAt(f));
108
+ // The direction of the segment at `f`; a segment that is a point on the picture
109
+ // (straight up in plan view, say) takes the nearest one before it that is not.
110
+ for (let j = i; j >= 1; j--) {
111
+ const a = to(world[j - 1]);
112
+ const b = to(world[j]);
113
+ if (Math.hypot(b.x - a.x, b.y - a.y) > 1e-6) return { x: here.x, y: here.y, angle: Math.atan2(b.y - a.y, b.x - a.x) };
114
+ }
115
+ return { x: here.x, y: here.y, angle: 0 };
116
+ },
117
+ };
118
+ }
119
+
120
+ /**
121
+ * A connector drawn up to fraction `p` of its path (`p` as the eased progress of
122
+ * a draw-on, 0..1): a dashed polyline in the token `stroke`, whose dash pattern
123
+ * starts at the path's start, so the dashes stand still as the line grows and
124
+ * the finished line is the dashed line it rests as. With `arrow` an open-V
125
+ * arrowhead rides the leading end, fading in over the first tenth of the
126
+ * draw-on. Nothing for `p` ≤ 0.
127
+ * @param {ConnectorPath} path
128
+ * @param {number} p
129
+ * @param {{ stroke?: string, width?: number, dash?: [number, number], arrow?: boolean, arrowSize?: number, opacity?: number, id?: string }} [o]
130
+ * @returns {string}
131
+ */
132
+ export function drawConnector(path, p, { stroke = "line", width = 1.5, dash = [6, 5], arrow = true, arrowSize = 9, opacity = 1, id } = {}) {
133
+ if (p <= 0) return "";
134
+ const color = tok(stroke);
135
+ const pts = path.cut(p);
136
+ const d = pts.map((q, i) => `${i === 0 ? "M" : "L"}${num(q.x)} ${num(q.y)}`).join(" ");
137
+ const line = el("path", { d, fill: "none", stroke: color, "stroke-width": width, "stroke-dasharray": `${num(dash[0])} ${num(dash[1])}`, "stroke-linejoin": "round" });
138
+ let head = "";
139
+ if (arrow) {
140
+ const { x, y, angle } = path.tip(p);
141
+ const spread = (28 * Math.PI) / 180;
142
+ const wing = (/** @type {number} */ s) => `${num(x - arrowSize * Math.cos(angle + s))} ${num(y - arrowSize * Math.sin(angle + s))}`;
143
+ head = fade(clamp01(p / 0.1), {}, el("path", { d: `M${wing(spread)} L${num(x)} ${num(y)} L${wing(-spread)}`, fill: "none", stroke: color, "stroke-width": width, "stroke-linecap": "round", "stroke-linejoin": "round" }));
144
+ }
145
+ return fade(opacity, id ? { "data-connector": id } : {}, line, head);
146
+ }
147
+
148
+ /**
149
+ * A diamond junction, centred where connectors turn, split or join: a small
150
+ * square turned 45°, `size` pixels from its centre to a corner. `plane:
151
+ * "screen"` (default) stands on the picture; `"floor"` lies in the floor plane
152
+ * of an iso view, which is the same diamond flattened by `sin(elevation)`, so
153
+ * it is a full diamond in plan view and a flat one in isometric. `lit` (0..1)
154
+ * cross-fades a second layer (`litFill`, `litStroke`) over the resting one, for
155
+ * the moment a pulse arrives.
156
+ * @param {{ at: Vertex, camera?: Camera, plane?: "screen" | "floor", size?: number, lit?: number, fill?: string, stroke?: string, litFill?: string, litStroke?: string, strokeWidth?: number, opacity?: number, id?: string }} o
157
+ * `at` is a flat point, or a world point when `camera` is given.
158
+ * @returns {string}
159
+ */
160
+ export function drawJunction({ at, camera, plane = "screen", size = 7, lit = 0, fill = "surface", stroke = "line", litFill = "accent", litStroke = "accent", strokeWidth = 1.5, opacity = 1, id }) {
161
+ if (!finite(size) || size <= 0) throw new Error(`drawJunction: size must be a positive number, got ${size}`);
162
+ if (plane !== "screen" && plane !== "floor") throw new Error(`drawJunction: plane must be "screen" or "floor", got "${plane}"`);
163
+ const c = camera ? projector(camera)({ x: at.x, y: at.y, z: at.z ?? 0 }) : at;
164
+ const ry = plane === "floor" && camera ? size * Math.sin((camera.elevation * Math.PI) / 180) : size;
165
+ const d = `M${num(c.x)} ${num(c.y - ry)} L${num(c.x + size)} ${num(c.y)} L${num(c.x)} ${num(c.y + ry)} L${num(c.x - size)} ${num(c.y)} Z`;
166
+ const layer = (/** @type {string} */ f, /** @type {string} */ s) => el("path", { d, fill: tok(f), stroke: tok(s), "stroke-width": strokeWidth, "stroke-linejoin": "round" });
167
+ return fade(opacity, id ? { "data-junction": id } : {}, layer(fill, stroke), fade(lit, {}, layer(litFill, litStroke)));
168
+ }
169
+
170
+ /** Seconds the pulse's tail trails its head by, unless a run sets `lag`. */
171
+ export const PULSE_LAG = 0.12;
172
+
173
+ /**
174
+ * One pulse's journey: it starts at `start` s, its head takes `duration` s along
175
+ * the connector on `ease` (default `easeStandard`), and its tail follows `lag` s
176
+ * later on the same curve (split edges), so the light stretches in flight and
177
+ * gathers at the end. The pulse grows in over the first tenth of its life and,
178
+ * unless it is held, fades over the last sixth; with `hold` the head stays lit
179
+ * at the end of the connector once the tail has gathered.
180
+ * @typedef {{ start: number, duration: number, lag?: number, ease?: (p: number) => number, hold?: boolean }} PulseRun
181
+ */
182
+
183
+ /**
184
+ * The time a pulse is over (or, held, at rest): `start + duration + lag`. A
185
+ * scene's step comes at least 50 ms after this for every pulse of its beat.
186
+ * @param {PulseRun} run
187
+ * @returns {number}
188
+ */
189
+ export function pulseEnd(run) {
190
+ return run.start + run.duration + (run.lag ?? PULSE_LAG);
191
+ }
192
+
193
+ /**
194
+ * Where a pulse's head is on its connector, as a fraction 0..1 of the path, at
195
+ * time `t` (0 before it starts, 1 once it has arrived), for a scene that lights
196
+ * a target as the pulse passes it.
197
+ * @param {number} t
198
+ * @param {PulseRun} run
199
+ * @returns {number}
200
+ */
201
+ export function pulseHead(t, run) {
202
+ return progress(t, run.start, run.duration, run.ease ?? easeStandard);
203
+ }
204
+
205
+ const TAIL_SLICES = 6;
206
+
207
+ /**
208
+ * A pulse at time `t`: a bright head with a soft glow (three halos in the same
209
+ * token, fainter outward) and a tail of short slices that fade toward the
210
+ * trailing end. Empty before the run starts and, unless it is held, after
211
+ * `pulseEnd(run)`.
212
+ * @param {ConnectorPath} path
213
+ * @param {number} t
214
+ * @param {PulseRun} run
215
+ * @param {{ color?: string, radius?: number }} [o] `color` is a token (default `emphasis`), `radius` the head's, in pixels
216
+ * @returns {string}
217
+ */
218
+ export function drawPulse(path, t, run, { color = "emphasis", radius = 4 } = {}) {
219
+ const lag = run.lag ?? PULSE_LAG;
220
+ const ease = run.ease ?? easeStandard;
221
+ const lead = progress(t, run.start, run.duration, ease);
222
+ if (lead <= 0) return "";
223
+ if (t >= pulseEnd(run) && !run.hold) return "";
224
+ const total = run.duration + lag;
225
+ const life = total > 0 ? (t - run.start) / total : 1; // an instantaneous run is already at its end
226
+ const trail = progress(t, run.start + lag, run.duration, ease);
227
+ const env = clamp01(Math.min(life / 0.1, run.hold ? 1 : (1 - life) / (1 / 6)));
228
+ if (env < 0.001) return "";
229
+ const fill = tok(color);
230
+ const out = [];
231
+ if (lead - trail > 1e-6) {
232
+ for (let i = 0; i < TAIL_SLICES; i++) {
233
+ // Each slice follows the route, so it turns at a corner between its ends.
234
+ const pts = path.span(trail + ((lead - trail) * i) / TAIL_SLICES, trail + ((lead - trail) * (i + 1)) / TAIL_SLICES);
235
+ const k = (i + 1) / TAIL_SLICES;
236
+ out.push(el("path", { d: pts.map((q, j) => `${j === 0 ? "M" : "L"}${num(q.x)} ${num(q.y)}`).join(" "), fill: "none", stroke: fill, "stroke-width": radius * 2 * (0.3 + 0.7 * k) * env, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: 0.5 * k * env }));
237
+ }
238
+ }
239
+ const head = path.at(lead);
240
+ for (const [grow, alpha] of [[3.2, 0.1], [2.2, 0.16], [1.5, 0.26]]) out.push(el("circle", { cx: head.x, cy: head.y, r: radius * grow * env, fill, opacity: alpha * env }));
241
+ out.push(el("circle", { cx: head.x, cy: head.y, r: radius * env, fill }));
242
+ return out.join("");
243
+ }
package/runtime/kit.mjs CHANGED
@@ -23,23 +23,25 @@
23
23
  */
24
24
  import { DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 } from "./motion.mjs";
25
25
  import { FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId } from "./scene.mjs";
26
- import { CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok } from "./style.mjs";
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, drawSolid, drawSolids, fitCamera, labelAnchor, labelProblems, lerpCamera, orderSolids, path3, prism, project, projector, regularPolygon, slab } from "./iso.mjs";
28
28
  import { attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment } from "./svg.mjs";
29
+ import { PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead } from "./connectors.mjs";
29
30
  import { estimateWidth, wrapLabel } from "./wrap.mjs";
30
31
 
31
32
  /**
32
33
  * The runtime, flat, handed to custom scene modules as `opts.kit`: the exports
33
- * of motion, scene, style, svg, iso and wrap (not the scene types or the player).
34
+ * of motion, scene, style, svg, iso, connectors and wrap (not the scene types or the player).
34
35
  * Named imports, because lib/bundle.mjs inlines only that form; a new export
35
36
  * in one of those modules is added here (test/runtime.test.mjs checks).
36
37
  */
37
38
  export const KIT = Object.freeze({
38
39
  ...{ DEFAULT_MOTION, ENTRANCE_MAX, SPRING_SETTLE_X, clamp01, cubicBezier, easeIn, easeOut, easeStandard, easings, lerp, linear, progress, splitEdge, springSettleTime, springStep, springTo, stagger, window01 },
39
40
  ...{ FORMATS, localize, renderSvg, safeId, stepIndex, stepIndexAt, stepTimes, validateScene, withId },
40
- ...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, cssVars, normalizeStyle, resolveTokens, tok },
41
+ ...{ CONTRAST_EXEMPT, CONTRAST_PAIRS, NEUTRAL, TOKENS, checkContrast, contrast, contrastReport, cssVars, normalizeStyle, resolveTokens, sharedPairs, tok },
41
42
  ...{ attrString, cubic, dist, drawOn, el, esc, fade, num, pointOnLine, polyline, scaleAbout, text, tokenPoints, tokensAlong, translate, trimSegment },
42
43
  ...{ CAMERA_ISOMETRIC, CAMERA_PLAN, ISO_ELEVATION, box, camera, drawSolid, drawSolids, fitCamera, labelAnchor, labelProblems, lerpCamera, orderSolids, path3, prism, project, projector, regularPolygon, slab },
44
+ ...{ PULSE_LAG, connectorPath, drawConnector, drawJunction, drawPulse, pulseEnd, pulseHead },
43
45
  ...{ estimateWidth, wrapLabel },
44
46
  });
45
47
 
package/runtime/scene.mjs CHANGED
@@ -40,12 +40,14 @@ import { normalizeStyle, cssVars, resolveTokens } from "./style.mjs";
40
40
  */
41
41
  /**
42
42
  * An animated diagram as a pure function of time (see the module comment).
43
- * `contrastPairs`: token pairs the scene draws beyond CONTRAST_PAIRS
44
- * (runtime/style.mjs), which the gate checks the style against.
43
+ * `contrastPairs`: the token pairs the scene draws (runtime/style.mjs
44
+ * `sharedPairs` picks from CONTRAST_PAIRS; others are written out). The gate
45
+ * holds the style to exactly these and reports the shared pairs left out as
46
+ * warnings; a scene that declares none is held to all of CONTRAST_PAIRS.
45
47
  * `labelBoxes`: the box of every label `frame(t)` draws, in the picture's
46
48
  * coordinates (`labelAnchor` returns one); the gate fails a scene whose labels
47
49
  * overlap, whose stems cross a label, or that leave the picture (runtime/iso.mjs).
48
- * @typedef {{ id: string, width: number, height: number, duration: number, title: string, description: string, steps: Step[], frame: (t: number, ctx: FrameContext) => string, stepLabelsInFrame?: boolean, contrastPairs?: { fg: string, bg: string, min: number, use?: string }[], labelBoxes?: (t: number) => LabelBox[], type?: string, format?: string, locale?: string }} Scene
50
+ * @typedef {{ id: string, width: number, height: number, duration: number, title: string, description: string, steps: Step[], frame: (t: number, ctx: FrameContext) => string, stepLabelsInFrame?: boolean, contrastPairs?: readonly { fg: string, bg: string, min: number, use?: string }[], labelBoxes?: (t: number) => LabelBox[], type?: string, format?: string, locale?: string }} Scene
49
51
  */
50
52
 
51
53
  /** Formats: name → viewBox. Layouts are computed per format, never cropped. */
package/runtime/style.mjs CHANGED
@@ -163,10 +163,12 @@ export function contrast(a, b) {
163
163
  */
164
164
 
165
165
  /**
166
- * Every token pair the scene types and shared parts draw where the pair
167
- * carries meaning in a step frame (runtime/types/*, runtime/parts.mjs). A
168
- * scene that draws other pairs declares them in `scene.contrastPairs`; the
169
- * gate checks those too (lib/check.mjs).
166
+ * The shared list: every token pair the scene types and shared parts draw
167
+ * where the pair carries meaning in a step frame (runtime/types/*,
168
+ * runtime/parts.mjs), with the contrast WCAG asks of it. It is the menu the
169
+ * scene types pick from (`sharedPairs`), not what every scene must meet: a
170
+ * scene is held to the pairs it draws (`contrastReport`). A scene that
171
+ * declares nothing is held to all of them.
170
172
  * @type {readonly ContrastPair[]}
171
173
  */
172
174
  export const CONTRAST_PAIRS = Object.freeze([
@@ -177,14 +179,14 @@ export const CONTRAST_PAIRS = Object.freeze([
177
179
  { fg: "onAccent", bg: "accent", min: 4.5, use: "labels, glyphs and icons inside reached nodes (boxNode, circleNode)" },
178
180
  { fg: "line", bg: "bg", min: 3, use: "connectors and the outlines of pending nodes" },
179
181
  { fg: "accent", bg: "bg", min: 3, use: "reached nodes and drawn connectors" },
180
- { fg: "emphasis", bg: "bg", min: 3, use: "the emphasis ring (sequence) and dot (hub-spoke) on the canvas" },
182
+ { fg: "emphasis", bg: "bg", min: 3, use: "the emphasis ring (sequence, flowchart) and dot (hub-spoke, stack, walk) on the canvas, and the timeline's now pill" },
181
183
  {
182
184
  fg: "emphasis",
183
185
  bg: "accent",
184
186
  min: 3,
185
- use: "the emphasis ring around the reached node it marks (sequence): 3.5 units apart, so adjacent at phone size. It tells the current node from the reached ones without relying on hue",
187
+ use: "the emphasis ring around the reached node it marks (sequence, flowchart): 3.5 units apart, so adjacent at phone size. It tells the current node from the reached ones without relying on hue. The dot of hub-spoke, stack and walk rides over accent connectors",
186
188
  },
187
- ]);
189
+ ].map((p) => Object.freeze(p)));
188
190
 
189
191
  /**
190
192
  * Pairs that are drawn (by the scene types, only in motion; or by the
@@ -200,26 +202,89 @@ export const CONTRAST_EXEMPT = Object.freeze([
200
202
  ]);
201
203
 
202
204
  /**
203
- * WCAG contrast checks a style must pass, in both themes.
204
- * @param {any} style style data or "neutral"; normalizeStyle fills the rest
205
- * @param {readonly ContrastPair[]} [pairs] default CONTRAST_PAIRS; a scene's
206
- * own pairs (`scene.contrastPairs`) are checked with the same function
207
- * @returns {string[]} problems (empty = ok)
205
+ * Why a list of pairs cannot be checked (empty = it can).
206
+ * @param {string} name the style's name, for the message
207
+ * @param {unknown} pairs
208
+ * @returns {string[]}
208
209
  */
209
- export function checkContrast(style, pairs = CONTRAST_PAIRS) {
210
- const s = normalizeStyle(style);
211
- if (!Array.isArray(pairs)) return [`${s.name}: contrast pairs must be an array of { fg, bg, min }`];
210
+ function malformedPairs(name, pairs) {
211
+ if (!Array.isArray(pairs)) return [`${name}: contrast pairs must be an array of { fg, bg, min }`];
212
212
  const problems = [];
213
213
  for (const [i, p] of pairs.entries()) {
214
214
  const bad = !p || typeof p !== "object" ? "is not an object" : !TOKENS.includes(p.fg) ? `has unknown fg token "${p.fg}"` : !TOKENS.includes(p.bg) ? `has unknown bg token "${p.bg}"` : !(typeof p.min === "number" && p.min >= 1 && p.min <= 21) ? "needs a min contrast between 1 and 21" : "";
215
- if (bad) problems.push(`${s.name}: contrast pair ${i} ${bad}`);
215
+ if (bad) problems.push(`${name}: contrast pair ${i} ${bad}`);
216
216
  }
217
- if (problems.length) return problems;
218
- for (const theme of ["light", "dark"]) {
217
+ return problems;
218
+ }
219
+
220
+ /**
221
+ * Each pair a style does not reach, in both themes.
222
+ * @param {ReturnType<typeof normalizeStyle>} s
223
+ * @param {readonly ContrastPair[]} pairs well-formed
224
+ */
225
+ function misses(s, pairs) {
226
+ const out = [];
227
+ for (const theme of /** @type {const} */ (["light", "dark"])) {
219
228
  for (const { fg, bg, min } of pairs) {
220
- const r = contrast(s[theme][fg], s[theme][bg]);
221
- if (r < min) problems.push(`${s.name} ${theme}: ${fg} on ${bg} is ${r.toFixed(2)}:1, needs ${min}:1`);
229
+ const ratio = contrast(s[theme][fg], s[theme][bg]);
230
+ if (ratio < min) out.push({ theme, fg, bg, min, ratio });
222
231
  }
223
232
  }
224
- return problems;
233
+ return out;
234
+ }
235
+
236
+ /**
237
+ * WCAG contrast checks a style must pass, in both themes.
238
+ * @param {any} style style data or "neutral"; normalizeStyle fills the rest
239
+ * @param {readonly ContrastPair[]} [pairs] default CONTRAST_PAIRS; a scene's
240
+ * own pairs (`scene.contrastPairs`) are checked with the same function
241
+ * @returns {string[]} problems (empty = ok)
242
+ */
243
+ export function checkContrast(style, pairs = CONTRAST_PAIRS) {
244
+ const s = normalizeStyle(style);
245
+ const bad = malformedPairs(s.name, pairs);
246
+ if (bad.length) return bad;
247
+ return misses(s, pairs).map((m) => `${s.name} ${m.theme}: ${m.fg} on ${m.bg} is ${m.ratio.toFixed(2)}:1, needs ${m.min}:1`);
248
+ }
249
+
250
+ /**
251
+ * The shared pairs a scene type draws, picked from CONTRAST_PAIRS by their
252
+ * `fg/bg` names, in the order of that list. A scene type records them with
253
+ * the type (`contrastPairs` on its scenes) and a custom scene may do the same.
254
+ * @param {...string} names `"fg/bg"`, e.g. `"ink/bg"`; throws on one that CONTRAST_PAIRS does not hold
255
+ * @returns {readonly ContrastPair[]}
256
+ */
257
+ export function sharedPairs(...names) {
258
+ for (const n of names) if (!CONTRAST_PAIRS.some((p) => `${p.fg}/${p.bg}` === n)) throw new Error(`sharedPairs: "${n}" is not a shared pair (known: ${CONTRAST_PAIRS.map((p) => `${p.fg}/${p.bg}`).join(", ")})`);
259
+ return Object.freeze(CONTRAST_PAIRS.filter((p) => names.includes(`${p.fg}/${p.bg}`)));
260
+ }
261
+
262
+ /**
263
+ * What one scene owes the style, WCAG 1.4.3 and 1.4.11 applied to the pairs it
264
+ * draws. A scene that declares no pairs draws, for this purpose, all of
265
+ * CONTRAST_PAIRS: every miss is a problem. A scene that declares them
266
+ * (`scene.contrastPairs`) is held to those; the shared pairs it does not
267
+ * declare are only reported, as warnings, because WCAG judges what is drawn,
268
+ * not the palette.
269
+ * @param {any} style style data or "neutral"
270
+ * @param {readonly ContrastPair[]} [drawn] `scene.contrastPairs`
271
+ * @returns {{ problems: string[], warnings: string[] }}
272
+ */
273
+ export function contrastReport(style, drawn) {
274
+ const s = normalizeStyle(style);
275
+ // An empty list says nothing about what is drawn, which is no reason to drop every check.
276
+ if (drawn === undefined || (Array.isArray(drawn) && drawn.length === 0)) return { problems: checkContrast(s), warnings: [] };
277
+ if (!Array.isArray(drawn) || malformedPairs(s.name, drawn).length) return { problems: checkContrast(s, drawn), warnings: [] };
278
+ // A declaration may add pairs and name shared ones, never weaken a shared threshold.
279
+ // Contrast is symmetric, so a pair written the other way round is the same adjacency.
280
+ /** @param {ContrastPair} p @param {ContrastPair} d */
281
+ const same = (p, d) => (p.fg === d.fg && p.bg === d.bg) || (p.fg === d.bg && p.bg === d.fg);
282
+ drawn = drawn.map((d) => {
283
+ const shared = CONTRAST_PAIRS.find((p) => same(p, d));
284
+ return shared && d.min < shared.min ? { ...d, min: shared.min } : d;
285
+ });
286
+ const problems = checkContrast(s, drawn);
287
+ const undrawn = CONTRAST_PAIRS.filter((p) => !drawn.some((d) => same(p, d)));
288
+ const warnings = misses(s, undrawn).map((m) => `${s.name} ${m.theme}: ${m.fg} on ${m.bg} is ${m.ratio.toFixed(2)}:1, ${m.min}:1 recommended (this scene does not draw it)`);
289
+ return { problems, warnings };
225
290
  }
@@ -29,10 +29,17 @@
29
29
  import { progress, easings } from "../motion.mjs";
30
30
  import { FONT_MIN, maxFontSize, rectEdge } from "../parts.mjs";
31
31
  import { FORMATS, localize, withId } from "../scene.mjs";
32
- import { NEUTRAL, tok } from "../style.mjs";
32
+ import { NEUTRAL, sharedPairs, tok } from "../style.mjs";
33
33
  import { drawOn, el, fade, num, polyline, text, translate } from "../svg.mjs";
34
34
  import { estimateWidth, wrapLabel } from "../wrap.mjs";
35
35
 
36
+ /**
37
+ * The shared contrast pairs this type draws: node labels, edge labels on the canvas, the emphasis ring on the canvas and around the reached node; no muted on surface.
38
+ * The gate holds its scenes to these and reports the other shared pairs as
39
+ * warnings (`contrastReport`, runtime/style.mjs).
40
+ */
41
+ export const contrastPairs = sharedPairs("ink/bg", "muted/bg", "ink/surface", "onAccent/accent", "line/bg", "accent/bg", "emphasis/bg", "emphasis/accent");
42
+
36
43
  export const FLOWCHART_SHAPES = ["box", "round", "pill", "decision"];
37
44
  export const FLOWCHART_DIRECTIONS = ["down", "up", "right", "left"];
38
45
 
@@ -398,6 +405,7 @@ export function flowchart(spec, { format = "16:9", locale = "en" } = {}) {
398
405
  title: localize(spec.title, locale),
399
406
  description: localize(spec.description, locale),
400
407
  steps: order.map((v, k) => withId({ at: stepAt(k), label: labels[v], detail: localize(nodes[v].detail, locale) }, nodes[v].id)),
408
+ contrastPairs,
401
409
  frame,
402
410
  };
403
411
  }
@@ -20,10 +20,17 @@
20
20
  import { progress, window01, easings } from "../motion.mjs";
21
21
  import { boxNode, FONT_MIN, maxFontSize, rectEdge } from "../parts.mjs";
22
22
  import { FORMATS, localize, withId } from "../scene.mjs";
23
- import { NEUTRAL, tok } from "../style.mjs";
23
+ import { NEUTRAL, sharedPairs, tok } from "../style.mjs";
24
24
  import { drawOn, el, pointOnLine } from "../svg.mjs";
25
25
  import { wrapLabel } from "../wrap.mjs";
26
26
 
27
+ /**
28
+ * The shared contrast pairs this type draws: boxNode labels, connectors, the emphasis dot riding over them; no text on the canvas.
29
+ * The gate holds its scenes to these and reports the other shared pairs as
30
+ * warnings (`contrastReport`, runtime/style.mjs).
31
+ */
32
+ export const contrastPairs = sharedPairs("ink/surface", "onAccent/accent", "line/bg", "accent/bg", "emphasis/bg", "emphasis/accent");
33
+
27
34
  const ENTER = 0.4;
28
35
  const ENTER_GAP = 0.08;
29
36
  const FILL = 0.25;
@@ -213,6 +220,7 @@ export function hubSpoke(spec, { format = "16:9", locale = "en" } = {}) {
213
220
  withId({ at: HUB_ON + FILL, label: hubLabel, detail: localize(spec.hub.detail, locale) }, spec.hub.id),
214
221
  ...spokes.map((s, i) => withId({ at: stepAt(i), label: s.label, detail: s.detail }, spokesSpec[i].id)),
215
222
  ],
223
+ contrastPairs,
216
224
  frame,
217
225
  };
218
226
  }
@@ -9,13 +9,14 @@
9
9
  * here. A one-off diagram can skip the registry: write a module whose default
10
10
  * export is (opts) → scene (see examples/custom-*.scene.mjs).
11
11
  */
12
+ /** @import { ContrastPair } from "../style.mjs" */
12
13
  import { validateScene } from "../scene.mjs";
13
- import { flowchart } from "./flowchart.mjs";
14
- import { hubSpoke } from "./hub-spoke.mjs";
15
- import { sequence } from "./sequence.mjs";
16
- import { stack } from "./stack.mjs";
17
- import { walk } from "./walk.mjs";
18
- import { timeline } from "./timeline.mjs";
14
+ import { contrastPairs as flowchartPairs, flowchart } from "./flowchart.mjs";
15
+ import { contrastPairs as hubSpokePairs, hubSpoke } from "./hub-spoke.mjs";
16
+ import { contrastPairs as sequencePairs, sequence } from "./sequence.mjs";
17
+ import { contrastPairs as stackPairs, stack } from "./stack.mjs";
18
+ import { contrastPairs as walkPairs, walk } from "./walk.mjs";
19
+ import { contrastPairs as timelinePairs, timeline } from "./timeline.mjs";
19
20
 
20
21
  export const SCENE_TYPES = {
21
22
  sequence,
@@ -27,6 +28,23 @@ export const SCENE_TYPES = {
27
28
  flowchart,
28
29
  };
29
30
 
31
+ /**
32
+ * The shared contrast pairs (CONTRAST_PAIRS) each scene type draws: the pairs
33
+ * the gate holds a scene of that type to, and the only ones for which a style
34
+ * can fail it. Every scene a type builds carries the same list as
35
+ * `scene.contrastPairs`.
36
+ * @type {Readonly<Record<string, readonly ContrastPair[]>>}
37
+ */
38
+ export const SCENE_TYPE_PAIRS = Object.freeze({
39
+ sequence: sequencePairs,
40
+ "hub-spoke": hubSpokePairs,
41
+ timeline: timelinePairs,
42
+ stack: stackPairs,
43
+ "state-machine": walkPairs,
44
+ "request-journey": walkPairs,
45
+ flowchart: flowchartPairs,
46
+ });
47
+
30
48
  export function createScene(spec, opts = {}) {
31
49
  const make = SCENE_TYPES[spec.type];
32
50
  if (!make) throw new Error(`unknown scene type "${spec.type}" (known: ${Object.keys(SCENE_TYPES).join(", ")})`);
@@ -20,10 +20,17 @@
20
20
  import { progress, easings } from "../motion.mjs";
21
21
  import { circleNode, FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
22
22
  import { FORMATS, localize, withId } from "../scene.mjs";
23
- import { NEUTRAL, tok } from "../style.mjs";
23
+ import { NEUTRAL, sharedPairs, tok } from "../style.mjs";
24
24
  import { drawOn, el, polyline, trimSegment } from "../svg.mjs";
25
25
  import { wrapLabel } from "../wrap.mjs";
26
26
 
27
+ /**
28
+ * The shared contrast pairs this type draws: labels on the canvas (stateLabel), circle glyphs, the emphasis ring on the canvas and around the reached node; no boxNode, so no ink on surface.
29
+ * The gate holds its scenes to these and reports the other shared pairs as
30
+ * warnings (`contrastReport`, runtime/style.mjs).
31
+ */
32
+ export const contrastPairs = sharedPairs("ink/bg", "muted/bg", "muted/surface", "onAccent/accent", "line/bg", "accent/bg", "emphasis/bg", "emphasis/accent");
33
+
27
34
  // Timeline (seconds). Steps are settled because PERIOD ≥ HOP + FILL.
28
35
  const ENTER_GAP = 0.1;
29
36
  const ENTER = 0.4;
@@ -199,6 +206,7 @@ export function sequence(spec, { format = "16:9", locale = "en" } = {}) {
199
206
  title: localize(spec.title, locale),
200
207
  description: localize(spec.description, locale),
201
208
  steps: items.map((it, k) => withId({ at: stepAt(k), label: it.label, detail: it.detail }, nodes[k].id)),
209
+ contrastPairs,
202
210
  frame,
203
211
  };
204
212
  }
@@ -24,10 +24,17 @@
24
24
  import { lerp, progress, easings } from "../motion.mjs";
25
25
  import { FONT_MIN, maxFontSize } from "../parts.mjs";
26
26
  import { FORMATS, localize, withId } from "../scene.mjs";
27
- import { NEUTRAL, tok } from "../style.mjs";
27
+ import { NEUTRAL, sharedPairs, tok } from "../style.mjs";
28
28
  import { drawOn, el, fade, num, text, translate } from "../svg.mjs";
29
29
  import { wrapLabel } from "../wrap.mjs";
30
30
 
31
+ /**
32
+ * The shared contrast pairs this type draws: layer labels, the rail and ticks, the packet dot over the accent rail; no text on the canvas.
33
+ * The gate holds its scenes to these and reports the other shared pairs as
34
+ * warnings (`contrastReport`, runtime/style.mjs).
35
+ */
36
+ export const contrastPairs = sharedPairs("ink/surface", "onAccent/accent", "line/bg", "accent/bg", "emphasis/bg", "emphasis/accent");
37
+
31
38
  /** @import { Scene } from "../scene.mjs" */
32
39
 
33
40
  // Timeline (seconds). Steps are settled because PERIOD ≥ HOP + FILL.
@@ -226,6 +233,7 @@ export function stack(spec, { format = "16:9", locale = "en" } = {}) {
226
233
  title: localize(spec.title, locale),
227
234
  description: localize(spec.description, locale),
228
235
  steps: order.map((li, k) => withId({ at: stepAt(k), label: labels[li], detail: localize(layers[li].detail, locale) }, layers[li].id)),
236
+ contrastPairs,
229
237
  frame,
230
238
  };
231
239
  }
@@ -26,10 +26,17 @@
26
26
  import { lerp, progress, springSettleTime, springStep, easings } from "../motion.mjs";
27
27
  import { FONT_MIN, maxFontSize, stateLabel } from "../parts.mjs";
28
28
  import { FORMATS, localize, withId } from "../scene.mjs";
29
- import { NEUTRAL, tok } from "../style.mjs";
29
+ import { NEUTRAL, sharedPairs, tok } from "../style.mjs";
30
30
  import { drawOn, el, fade, num, text, translate } from "../svg.mjs";
31
31
  import { wrapLabel } from "../wrap.mjs";
32
32
 
33
+ /**
34
+ * The shared contrast pairs this type draws: dates and labels on the canvas, dots and stems, the now pill (canvas fill) at the end of the accent axis; no text on surface or accent.
35
+ * The gate holds its scenes to these and reports the other shared pairs as
36
+ * warnings (`contrastReport`, runtime/style.mjs).
37
+ */
38
+ export const contrastPairs = sharedPairs("ink/bg", "muted/bg", "line/bg", "accent/bg", "emphasis/bg", "emphasis/accent");
39
+
33
40
  /** @import { Scene } from "../scene.mjs" */
34
41
 
35
42
  // Timeline (seconds). Each beat ends (step) before the next one starts.
@@ -405,6 +412,7 @@ export function timeline(spec, { format = "16:9", locale = "en" } = {}) {
405
412
  title: localize(spec.title, locale),
406
413
  description: localize(spec.description, locale),
407
414
  steps,
415
+ contrastPairs,
408
416
  frame,
409
417
  };
410
418
  }