@liqweed/motion-kit 0.4.0 → 0.6.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.
Files changed (45) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +26 -6
  4. package/adapters/element/README.md +5 -0
  5. package/adapters/page/README.md +10 -0
  6. package/cli/motion-kit.mjs +14 -4
  7. package/docs/spec/technique.md +129 -51
  8. package/examples/checkout.json +104 -0
  9. package/examples/connection.json +80 -0
  10. package/examples/custom-pulse.scene.mjs +5 -0
  11. package/examples/incident.json +18 -0
  12. package/examples/player-states.json +97 -0
  13. package/examples/web-stack.json +17 -0
  14. package/lib/build.mjs +1 -1
  15. package/lib/check.mjs +215 -21
  16. package/lib/export.mjs +116 -7
  17. package/lib/gate.mjs +9 -7
  18. package/lib/load.mjs +15 -0
  19. package/package.json +6 -3
  20. package/runtime/kit.mjs +2 -2
  21. package/runtime/links.mjs +318 -0
  22. package/runtime/parts.mjs +15 -0
  23. package/runtime/patch.mjs +297 -0
  24. package/runtime/player.mjs +45 -2
  25. package/runtime/scene.mjs +24 -9
  26. package/runtime/style.mjs +65 -16
  27. package/runtime/types/hub-spoke.mjs +10 -8
  28. package/runtime/types/index.mjs +7 -0
  29. package/runtime/types/sequence.mjs +10 -8
  30. package/runtime/types/stack.mjs +230 -0
  31. package/runtime/types/timeline.mjs +407 -0
  32. package/runtime/types/walk.mjs +162 -0
  33. package/skills/animated-diagram/SKILL.md +28 -7
  34. package/skills/animated-diagram/references/custom-scenes.md +20 -1
  35. package/skills/animated-diagram/references/interactivity.md +129 -6
  36. package/skills/animated-diagram/references/motion-vocabulary.md +1 -1
  37. package/skills/animated-diagram/references/qc.md +3 -0
  38. package/skills/animated-diagram/references/scene-types.md +100 -4
  39. package/skills/animated-diagram/references/styles.md +55 -6
  40. package/skills/animated-diagram/references/technique.md +15 -6
  41. package/skills/motion-render/SKILL.md +31 -6
  42. package/skills/motion-render/references/formats.md +8 -8
  43. package/skills/motion-render/references/video.md +1 -1
  44. package/skills/project-logo/SKILL.md +15 -4
  45. package/styles/neutral.json +2 -2
@@ -0,0 +1,104 @@
1
+ {
2
+ "type": "request-journey",
3
+ "id": "checkout",
4
+ "title": {
5
+ "en": "A checkout request",
6
+ "nl": "Een betaalverzoek"
7
+ },
8
+ "description": {
9
+ "en": "The browser calls the shop, which asks for payment and queues a receipt.",
10
+ "nl": "De browser roept de winkel aan, die betaling vraagt en een ontvangstbewijs klaarzet."
11
+ },
12
+ "components": [
13
+ {
14
+ "id": "browser",
15
+ "label": {
16
+ "en": "Browser",
17
+ "nl": "Browser"
18
+ },
19
+ "region": {
20
+ "en": "Customer",
21
+ "nl": "Klant"
22
+ }
23
+ },
24
+ {
25
+ "id": "shop",
26
+ "label": {
27
+ "en": "Shop API",
28
+ "nl": "Winkel-API"
29
+ },
30
+ "region": {
31
+ "en": "Shop",
32
+ "nl": "Winkel"
33
+ }
34
+ },
35
+ {
36
+ "id": "payment",
37
+ "label": {
38
+ "en": "Payment API",
39
+ "nl": "Betaal-API"
40
+ },
41
+ "region": {
42
+ "en": "Provider",
43
+ "nl": "Aanbieder"
44
+ }
45
+ },
46
+ {
47
+ "id": "queue",
48
+ "label": {
49
+ "en": "Receipt queue",
50
+ "nl": "Bonnenwachtrij"
51
+ },
52
+ "region": {
53
+ "en": "Shop",
54
+ "nl": "Winkel"
55
+ }
56
+ }
57
+ ],
58
+ "hops": [
59
+ {
60
+ "id": "submit",
61
+ "from": "browser",
62
+ "to": "shop",
63
+ "label": {
64
+ "en": "Submit order",
65
+ "nl": "Bestelling sturen"
66
+ }
67
+ },
68
+ {
69
+ "id": "pay",
70
+ "from": "shop",
71
+ "to": "payment",
72
+ "label": {
73
+ "en": "Request payment",
74
+ "nl": "Betaling vragen"
75
+ }
76
+ },
77
+ {
78
+ "id": "paid",
79
+ "from": "payment",
80
+ "to": "shop",
81
+ "label": {
82
+ "en": "Payment accepted",
83
+ "nl": "Betaling aanvaard"
84
+ }
85
+ },
86
+ {
87
+ "id": "enqueue",
88
+ "from": "shop",
89
+ "to": "queue",
90
+ "label": {
91
+ "en": "Queue receipt",
92
+ "nl": "Bon klaarzetten"
93
+ },
94
+ "async": true
95
+ }
96
+ ],
97
+ "initial": "browser",
98
+ "path": [
99
+ "submit",
100
+ "pay",
101
+ "paid",
102
+ "enqueue"
103
+ ]
104
+ }
@@ -0,0 +1,80 @@
1
+ {
2
+ "type": "state-machine",
3
+ "id": "connection",
4
+ "title": {
5
+ "en": "A connection recovers",
6
+ "nl": "Een verbinding herstelt"
7
+ },
8
+ "description": {
9
+ "en": "Connect, retry after failure, then disconnect.",
10
+ "nl": "Verbinden, opnieuw proberen na uitval en verbreken."
11
+ },
12
+ "states": [
13
+ {
14
+ "id": "offline",
15
+ "label": {
16
+ "en": "Offline",
17
+ "nl": "Offline"
18
+ }
19
+ },
20
+ {
21
+ "id": "connecting",
22
+ "label": {
23
+ "en": "Connecting",
24
+ "nl": "Verbinden"
25
+ }
26
+ },
27
+ {
28
+ "id": "online",
29
+ "label": {
30
+ "en": "Online",
31
+ "nl": "Online"
32
+ }
33
+ }
34
+ ],
35
+ "transitions": [
36
+ {
37
+ "id": "connect",
38
+ "from": "offline",
39
+ "to": "connecting",
40
+ "label": {
41
+ "en": "Connect",
42
+ "nl": "Verbinden"
43
+ }
44
+ },
45
+ {
46
+ "id": "retry",
47
+ "from": "connecting",
48
+ "to": "connecting",
49
+ "label": {
50
+ "en": "Retry",
51
+ "nl": "Opnieuw proberen"
52
+ }
53
+ },
54
+ {
55
+ "id": "ready",
56
+ "from": "connecting",
57
+ "to": "online",
58
+ "label": {
59
+ "en": "Connected",
60
+ "nl": "Verbonden"
61
+ }
62
+ },
63
+ {
64
+ "id": "close",
65
+ "from": "online",
66
+ "to": "offline",
67
+ "label": {
68
+ "en": "Disconnect",
69
+ "nl": "Verbreken"
70
+ }
71
+ }
72
+ ],
73
+ "initial": "offline",
74
+ "path": [
75
+ "connect",
76
+ "retry",
77
+ "ready",
78
+ "close"
79
+ ]
80
+ }
@@ -12,6 +12,8 @@ import { tok } from "../runtime/style.mjs";
12
12
  import { cubic, drawOn, el, fade, num, text } from "../runtime/svg.mjs";
13
13
  import { wrapLabel } from "../runtime/wrap.mjs";
14
14
 
15
+ export const locales = ["en", "nl"];
16
+
15
17
  const COPY = {
16
18
  title: { en: "A request, there and back", nl: "Een verzoek, heen en terug" },
17
19
  description: {
@@ -135,6 +137,9 @@ export default function make({ format = "16:9", locale = "en" } = {}) {
135
137
  // Steps here are events, not nodes: their labels live in the player's
136
138
  // step buttons and captions, not in the drawing.
137
139
  stepLabelsInFrame: false,
140
+ // Beyond the pairs every scene draws: the progress bar's accent fill on
141
+ // its surface track. The gate checks the style against it too.
142
+ contrastPairs: [{ fg: "accent", bg: "surface", min: 3, use: "the progress bar's fill on its track" }],
138
143
  steps: steps.map((s) => ({ at: s.at, label: localize(s.label, locale), detail: localize(s.detail, locale) })),
139
144
  frame,
140
145
  };
@@ -0,0 +1,18 @@
1
+ {
2
+ "type": "timeline",
3
+ "id": "incident",
4
+ "title": { "en": "An incident, start to review", "nl": "Een storing, van begin tot evaluatie" },
5
+ "description": {
6
+ "en": "An outage from the first alert to the all-clear, with the review still to come.",
7
+ "nl": "Een storing van het eerste alarm tot het sein veilig, met de evaluatie nog te gaan."
8
+ },
9
+ "events": [
10
+ { "when": "09:02", "label": { "en": "Alert fires", "nl": "Alarm gaat af" }, "detail": { "en": "Error rates cross the threshold and on-call is paged.", "nl": "Het foutpercentage gaat over de drempel en de dienstdoende wordt opgeroepen." } },
11
+ { "when": "09:06", "label": { "en": "On-call responds", "nl": "Dienstdoende reageert" }, "detail": { "en": "The engineer on call acknowledges and opens an incident channel.", "nl": "De dienstdoende engineer bevestigt en opent een storingskanaal." } },
12
+ { "when": "09:24", "label": { "en": "Cause found", "nl": "Oorzaak gevonden" }, "detail": { "en": "A configuration change from the morning release is the cause.", "nl": "Een configuratiewijziging uit de ochtendrelease is de oorzaak." } },
13
+ { "when": "09:41", "label": { "en": "Fix deployed", "nl": "Herstel uitgerold" }, "detail": { "en": "The change is rolled back and error rates fall.", "nl": "De wijziging wordt teruggedraaid en het foutpercentage daalt." } },
14
+ { "when": "10:15", "label": { "en": "All clear", "nl": "Sein veilig" }, "detail": { "en": "Metrics are back to normal and the incident is closed.", "nl": "De metrieken zijn weer normaal en de storing is gesloten." } },
15
+ { "when": { "en": "Thursday", "nl": "Donderdag" }, "label": { "en": "Review", "nl": "Evaluatie" }, "planned": true, "detail": { "en": "The team writes down what happened and what changes, without blame.", "nl": "Het team legt vast wat er gebeurde en wat er verandert, zonder schuldvraag." } }
16
+ ],
17
+ "now": { "label": { "en": "Now", "nl": "Nu" }, "detail": { "en": "The service is healthy; the review is still to come.", "nl": "De dienst is gezond; de evaluatie moet nog komen." } }
18
+ }
@@ -0,0 +1,97 @@
1
+ {
2
+ "type": "state-machine",
3
+ "id": "player-states",
4
+ "title": {
5
+ "en": "The player, as states",
6
+ "nl": "De speler als toestanden"
7
+ },
8
+ "description": {
9
+ "en": "Play, pause, resume and finish. Replay returns to playing.",
10
+ "nl": "Afspelen, pauzeren, hervatten en afronden. Opnieuw keert terug naar afspelen."
11
+ },
12
+ "states": [
13
+ {
14
+ "id": "ready",
15
+ "label": {
16
+ "en": "Ready",
17
+ "nl": "Gereed"
18
+ }
19
+ },
20
+ {
21
+ "id": "playing",
22
+ "label": {
23
+ "en": "Playing",
24
+ "nl": "Speelt"
25
+ }
26
+ },
27
+ {
28
+ "id": "paused",
29
+ "label": {
30
+ "en": "Paused",
31
+ "nl": "Gepauzeerd"
32
+ }
33
+ },
34
+ {
35
+ "id": "finished",
36
+ "label": {
37
+ "en": "Finished",
38
+ "nl": "Afgerond"
39
+ }
40
+ }
41
+ ],
42
+ "transitions": [
43
+ {
44
+ "id": "play",
45
+ "from": "ready",
46
+ "to": "playing",
47
+ "label": {
48
+ "en": "Play",
49
+ "nl": "Afspelen"
50
+ }
51
+ },
52
+ {
53
+ "id": "pause",
54
+ "from": "playing",
55
+ "to": "paused",
56
+ "label": {
57
+ "en": "Pause",
58
+ "nl": "Pauzeren"
59
+ }
60
+ },
61
+ {
62
+ "id": "resume",
63
+ "from": "paused",
64
+ "to": "playing",
65
+ "label": {
66
+ "en": "Resume",
67
+ "nl": "Hervatten"
68
+ }
69
+ },
70
+ {
71
+ "id": "finish",
72
+ "from": "playing",
73
+ "to": "finished",
74
+ "label": {
75
+ "en": "Finish",
76
+ "nl": "Afronden"
77
+ }
78
+ },
79
+ {
80
+ "id": "replay",
81
+ "from": "finished",
82
+ "to": "playing",
83
+ "label": {
84
+ "en": "Replay",
85
+ "nl": "Opnieuw"
86
+ }
87
+ }
88
+ ],
89
+ "initial": "ready",
90
+ "path": [
91
+ "play",
92
+ "pause",
93
+ "resume",
94
+ "finish",
95
+ "replay"
96
+ ]
97
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "type": "stack",
3
+ "id": "web-stack",
4
+ "title": { "en": "A request through the layers", "nl": "Een verzoek door de lagen" },
5
+ "description": {
6
+ "en": "A request from the browser passes the CDN, the API gateway and the service before it reaches the database.",
7
+ "nl": "Een verzoek uit de browser passeert het CDN, de API-gateway en de dienst voordat het de database bereikt."
8
+ },
9
+ "layers": [
10
+ { "label": { "en": "Browser", "nl": "Browser" }, "detail": { "en": "The user's click becomes an HTTPS request.", "nl": "De klik van de gebruiker wordt een HTTPS-verzoek." } },
11
+ { "label": { "en": "CDN", "nl": "CDN" }, "detail": { "en": "The edge answers cached pages and passes everything else on.", "nl": "De rand beantwoordt gecachete pagina's en geeft de rest door." } },
12
+ { "label": { "en": "API gateway", "nl": "API-gateway" }, "detail": { "en": "Checks who is asking and how often.", "nl": "Controleert wie er vraagt en hoe vaak." } },
13
+ { "label": { "en": "Order service", "nl": "Bestelservice" }, "detail": { "en": "The business logic decides what the request means.", "nl": "De bedrijfslogica bepaalt wat het verzoek betekent." } },
14
+ { "label": { "en": "Database", "nl": "Database" }, "detail": { "en": "The data is read or written, and the answer travels back.", "nl": "De gegevens worden gelezen of geschreven, en het antwoord gaat terug." } }
15
+ ],
16
+ "direction": "down"
17
+ }
package/lib/build.mjs CHANGED
@@ -27,7 +27,7 @@ const scriptJson = (/** @type {unknown} */ value) => JSON.stringify(value).repla
27
27
  */
28
28
  export function buildHtml(loaded, o) {
29
29
  // Every runtime module is an entry, so the MotionKit global is the whole kit.
30
- const entries = ["motion", "svg", "style", "wrap", "scene", "types/index", "player"].map((m) => `${RUNTIME}${m}.mjs`);
30
+ const entries = ["motion", "svg", "style", "wrap", "scene", "types/index", "player", "links"].map((m) => `${RUNTIME}${m}.mjs`);
31
31
  const runtimeCount = entries.length;
32
32
  if (loaded.kind === "module") entries.push(loaded.file);
33
33
  // MotionKitRuntime is the runtime alone: a custom module's exports, spread
package/lib/check.mjs CHANGED
@@ -4,11 +4,12 @@
4
4
  * motion-kit · scene gate. Every scene, every format/locale it ships in, must
5
5
  * pass these before anything is exported or mounted.
6
6
  *
7
- * checkScene(scene) → { ok, problems: string[] }
7
+ * checkScene(scene, { style }) → { ok, problems: string[] }
8
8
  *
9
9
  * Over files, formats and locales (the CLI and the vendored gate): lib/gate.mjs.
10
10
  */
11
- import { renderSvg } from "../runtime/scene.mjs";
11
+ import { renderSvg, validateScene } from "../runtime/scene.mjs";
12
+ import { checkContrast, normalizeStyle } from "../runtime/style.mjs";
12
13
 
13
14
  const SAMPLES = 120;
14
15
 
@@ -34,12 +35,178 @@ export function wellFormed(svg) {
34
35
  return null;
35
36
  }
36
37
 
37
- export function checkScene(scene, { samples = SAMPLES } = {}) {
38
+ /* ------------------------------------------------------------ colour literals */
39
+
40
+ /** Presentation attributes whose value is a colour. */
41
+ const COLOUR_ATTRS = new Set(["fill", "stroke", "stop-color", "color", "flood-color", "lighting-color"]);
42
+ /** CSS properties (in style="…" or a <style> element) whose value is a colour. */
43
+ const isColourProperty = (/** @type {string} */ name) => COLOUR_ATTRS.has(name) || name === "background" || /-colou?r$/.test(name);
44
+ /**
45
+ * Values that name no colour, so they look the same under every style and
46
+ * theme: no paint, the inherited or current colour, `transparent` (no hue,
47
+ * invisible in light and dark alike), marker context paint, CSS-wide keywords.
48
+ */
49
+ const NOT_A_COLOUR = /^(none|currentcolor|transparent|inherit|initial|unset|revert|revert-layer|context-fill|context-stroke)$/i;
50
+ /** Literal colour syntax anywhere in markup or CSS: hex and colour functions. */
51
+ const COLOUR_SYNTAX = /#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color|color-mix|light-dark)\(/i;
52
+ /** References to ids, which are not colours: url(#x). */
53
+ const ID_REF = /url\(\s*['"]?#[^)]*\)/g;
54
+
55
+ /**
56
+ * The literal colour in one colour value (`fill`, `stroke`, a style
57
+ * property), or null when it uses only tokens (`var(--mk-x)`), id references
58
+ * and the keywords in NOT_A_COLOUR. Named colours (`red`), hex, colour
59
+ * functions and other custom properties are literals.
60
+ * @param {string} value
61
+ * @returns {string | null}
62
+ */
63
+ export function colourLiteral(value) {
64
+ const rest = value.replace(/!important/gi, "").replace(ID_REF, " ").replace(/var\(--mk-[a-zA-Z]+\)/g, " ").trim();
65
+ if (!rest || rest.split(/\s+/).every((word) => NOT_A_COLOUR.test(word))) return null;
66
+ return rest;
67
+ }
68
+
69
+ /**
70
+ * @param {string} css declarations, or a whole stylesheet
71
+ * @returns {string | null}
72
+ */
73
+ function cssColourLiteral(css) {
74
+ for (const [, prop, value] of css.matchAll(/([\w-]+)\s*:\s*([^;{}]+)/g)) {
75
+ if (!isColourProperty(prop.toLowerCase())) continue;
76
+ const lit = colourLiteral(value);
77
+ if (lit) return `${prop}: ${lit}`;
78
+ }
79
+ // Colour syntax in a declaration, never in a selector: `#face-node` is an id.
80
+ const declarations = css.includes("{") ? [...css.matchAll(/\{([^{}]*)\}/g)].map((m) => m[1]).join(";") : css;
81
+ return declarations.replace(ID_REF, "").match(COLOUR_SYNTAX)?.[0] ?? null;
82
+ }
83
+
84
+ /** @param {string} v */
85
+ const unescapeAttr = (v) => v.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
86
+
87
+ /**
88
+ * The first colour literal in a frame's markup, or null. Looks inside tags
89
+ * and <style> elements, not at text content: a label may say "#1".
90
+ * @param {string} markup
91
+ * @returns {string | null}
92
+ */
93
+ export function findColourLiteral(markup) {
94
+ for (const [, tag] of markup.matchAll(/<([a-zA-Z][^>]*)>/g)) {
95
+ for (const [, name, raw] of tag.matchAll(/([\w:-]+)="([^"]*)"/g)) {
96
+ if (name === "href" || name === "xlink:href") continue; // href="#id"
97
+ const value = unescapeAttr(raw);
98
+ let lit;
99
+ if (name === "style") lit = cssColourLiteral(value);
100
+ else if (COLOUR_ATTRS.has(name)) lit = colourLiteral(value);
101
+ else lit = value.replace(ID_REF, "").match(COLOUR_SYNTAX)?.[0] ?? null;
102
+ if (lit) return `${name}="${lit}"`;
103
+ }
104
+ }
105
+ for (const [, css] of markup.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g)) {
106
+ const lit = cssColourLiteral(css);
107
+ if (lit) return `<style> ${lit}`;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /* ------------------------------------------------------- clock and randomness */
113
+
114
+ /**
115
+ * Two fixed clocks far apart (1970 and 2100; random 0 and almost 1). A frame
116
+ * that reads Date, performance.now, Temporal.Now or Math.random, itself or in
117
+ * a helper it calls, renders differently under at least one of them than
118
+ * under the real ones.
119
+ */
120
+ const STUB_CLOCKS = [
121
+ { now: 0, perf: 0, random: 0 },
122
+ { now: 4102444800000, perf: 1e9, random: 0.999999 },
123
+ ];
124
+
125
+ /**
126
+ * Run `fn` with Date, performance.now, Temporal.Now and Math.random replaced
127
+ * by a fixed clock; the originals are restored before it returns or throws.
128
+ * @template T
129
+ * @param {{ now: number, perf: number, random: number }} clock
130
+ * @param {() => T} fn
131
+ * @returns {T}
132
+ */
133
+ function underStubbedClock({ now, perf, random }, fn) {
134
+ const g = /** @type {any} */ (globalThis);
135
+ const RealDate = g.Date;
136
+ const realRandom = Math.random;
137
+ const performance = g.performance;
138
+ const ownNow = performance && Object.getOwnPropertyDescriptor(performance, "now");
139
+ const temporal = g.Temporal;
140
+ const realTemporalNow = temporal?.Now;
141
+ /** @param {...any} args */
142
+ function FakeDate(...args) {
143
+ if (!new.target) return new RealDate(now).toString();
144
+ return args.length ? new RealDate(...args) : new RealDate(now);
145
+ }
146
+ FakeDate.now = () => now;
147
+ FakeDate.parse = RealDate.parse;
148
+ FakeDate.UTC = RealDate.UTC;
149
+ FakeDate.prototype = RealDate.prototype;
150
+ try {
151
+ g.Date = FakeDate;
152
+ Math.random = () => random;
153
+ if (performance) Object.defineProperty(performance, "now", { value: () => perf, configurable: true, writable: true });
154
+ if (realTemporalNow) {
155
+ const instant = () => temporal.Instant.fromEpochMilliseconds(now);
156
+ const zoned = (tz = "UTC") => instant().toZonedDateTimeISO(tz);
157
+ temporal.Now = {
158
+ instant,
159
+ timeZoneId: () => "UTC",
160
+ zonedDateTimeISO: zoned,
161
+ plainDateTimeISO: (/** @type {string | undefined} */ tz) => zoned(tz).toPlainDateTime(),
162
+ plainDateISO: (/** @type {string | undefined} */ tz) => zoned(tz).toPlainDate(),
163
+ plainTimeISO: (/** @type {string | undefined} */ tz) => zoned(tz).toPlainTime(),
164
+ };
165
+ }
166
+ return fn();
167
+ } finally {
168
+ g.Date = RealDate;
169
+ Math.random = realRandom;
170
+ if (performance) {
171
+ if (ownNow) Object.defineProperty(performance, "now", ownNow);
172
+ else delete performance.now;
173
+ }
174
+ if (realTemporalNow) temporal.Now = realTemporalNow;
175
+ }
176
+ }
177
+
178
+ /* --------------------------------------------------------------------- gate */
179
+
180
+ /**
181
+ * Offsets (s) after a step's `at` at which the frame must still be the step
182
+ * frame. The canon leaves at least 50 ms between a step and the next beat
183
+ * (motion-vocabulary.md, "Pause between beats"), so motion passing through
184
+ * `at` shows inside this window, while the next beat, which may start at
185
+ * exactly `at` + 50 ms, never does.
186
+ */
187
+ export const SETTLE_AFTER = Object.freeze([0.001, 0.015, 0.03, 0.045]);
188
+
189
+ /**
190
+ * Run the scene gate on one built scene.
191
+ * @param {import("../runtime/scene.mjs").Scene} scene
192
+ * @param {{ samples?: number, style?: any }} [options]
193
+ * style: what the scene's own `contrastPairs` are checked against (neutral
194
+ * if absent). The pairs every scene draws (CONTRAST_PAIRS) are a property of
195
+ * the style alone, checked once per style by lib/gate.mjs.
196
+ * @returns {{ ok: boolean, problems: string[] }}
197
+ */
198
+ export function checkScene(scene, { samples = SAMPLES, style } = {}) {
38
199
  const problems = [];
39
- const render = (t) => renderSvg(scene, t);
40
- const at = (i) => (scene.duration * i) / samples;
200
+ style = normalizeStyle(style);
201
+ try { validateScene(scene); } catch (e) { return { ok: false, problems: [e instanceof Error ? e.message : String(e)] }; }
202
+ for (const p of checkContrast(style)) problems.push(`contrast: ${p}`);
203
+ const render = (/** @type {number} */ t) => renderSvg(scene, t, { style });
204
+ const at = (/** @type {number} */ i) => (scene.duration * i) / samples;
41
205
 
42
- // 1. Deterministic + well-formed + rounded + token-only, across the timeline.
206
+ // 1. Deterministic + well-formed + rounded + token-only, across the timeline,
207
+ // and the same bytes under two stubbed clocks: no clock or randomness,
208
+ // also not in the helpers the frame calls.
209
+ let clockRead = false;
43
210
  for (let i = 0; i <= samples; i++) {
44
211
  const t = at(i);
45
212
  const a = render(t);
@@ -48,18 +215,38 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
48
215
  if (wf) problems.push(`malformed at t=${t.toFixed(3)}: ${wf}`);
49
216
  const long = a.match(/-?\d+\.\d{5,}/);
50
217
  if (long) problems.push(`unrounded number ${long[0]} at t=${t.toFixed(3)} (use num())`);
51
- const frame = scene.frame(Math.min(t, scene.duration), { idPrefix: scene.id });
52
- // References to ids (url(#x), href="#x") are not colours.
53
- const lit = frame.replace(/url\(\s*#[^)]*\)|href="#[^"]*"/g, "").match(/#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(/);
54
- if (lit) problems.push(`colour literal "${lit[0]}" at t=${t.toFixed(3)} (use tok())`);
218
+ const frame = scene.frame(Math.min(t, scene.duration), { idPrefix: scene.id, style });
219
+ const lit = findColourLiteral(frame);
220
+ if (lit) problems.push(`colour literal ${lit} at t=${t.toFixed(3)} (use tok())`);
55
221
  if (/NaN|undefined|Infinity/.test(frame)) problems.push(`NaN/undefined/Infinity in frame at t=${t.toFixed(3)}`);
222
+ for (const clock of clockRead ? [] : STUB_CLOCKS) {
223
+ let stubbed;
224
+ try {
225
+ stubbed = underStubbedClock(clock, () => render(t));
226
+ } catch (e) {
227
+ stubbed = e;
228
+ }
229
+ if (stubbed !== a) {
230
+ clockRead = true;
231
+ problems.push(`frame() reads the clock or randomness: at t=${t.toFixed(3)} it renders differently under a stubbed Date, performance.now or Math.random`);
232
+ break;
233
+ }
234
+ }
56
235
  if (problems.length > 12) break;
57
236
  }
58
237
 
59
- // 2. Settled steps: nothing moves at a step's time.
60
- for (const s of scene.steps) {
61
- const before = render(Math.max(0, s.at - 0.001));
62
- if (before !== render(s.at)) problems.push(`step "${s.label}" at ${s.at.toFixed(3)}s is not settled (something is still moving)`);
238
+ // 2. Settled steps: nothing moves at a step's time. The step's own motion
239
+ // is at rest 1 ms before `at`, and nothing changes in the SETTLE_AFTER
240
+ // window after it (up to the next step), so no motion passes through `at`.
241
+ for (const [i, s] of scene.steps.entries()) {
242
+ const still = render(s.at);
243
+ const next = scene.steps[i + 1]?.at ?? Infinity;
244
+ const offsets = [-0.001, ...SETTLE_AFTER.filter((d) => s.at + d < next)];
245
+ const moved = offsets.find((d) => render(Math.max(0, s.at + d)) !== still);
246
+ if (moved !== undefined) {
247
+ const when = moved < 0 ? "1 ms before" : `${Math.round(moved * 1000)} ms after`;
248
+ problems.push(`step "${s.label}" at ${s.at.toFixed(3)}s is not settled: the frame ${when} differs (something is still moving)`);
249
+ }
63
250
  }
64
251
 
65
252
  // 3. Builds up and finishes.
@@ -67,33 +254,40 @@ export function checkScene(scene, { samples = SAMPLES } = {}) {
67
254
  const lastFrame = render(scene.duration);
68
255
  if (first === lastFrame) problems.push("first and last frame are identical: nothing animates");
69
256
  if (scene.steps[scene.steps.length - 1].at > scene.duration) problems.push("last step is after duration");
70
- if (render(scene.duration + 5) !== lastFrame) problems.push("frames after the end differ from the final frame (must hold)");
257
+ 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)");
71
258
 
72
- // 4. Budget: whole scene under ~10 s (design guidance: ≤ 8 s for explainers).
73
- if (scene.duration > 12) problems.push(`duration ${scene.duration.toFixed(1)}s is long for an explainer (≤ 8–10 s)`);
259
+ // 4. Hard limit: 12 s. Authoring target: 8 s; these are distinct.
260
+ if (scene.duration > 12) problems.push(`duration ${scene.duration.toFixed(1)}s exceeds the 12 s limit (aim for ≤ 8 s)`);
74
261
 
75
262
  // 5. Every step label is visible in the final frame (escaped form), unless
76
263
  // the scene declares narrative steps (stepLabelsInFrame: false).
77
- const escd = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
264
+ const escd = (/** @type {string} */ s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
78
265
  const plain = lastFrame.replace(/<\/tspan><tspan[^>]*>/g, " ").replace(/<[^>]+>/g, "\u0000");
79
266
  for (const s of scene.stepLabelsInFrame === false ? [] : scene.steps) {
80
267
  const words = escd(s.label).split(/\s+/);
81
268
  if (!words.every((w) => plain.includes(w.replace(/\/$/, "")))) problems.push(`step label "${s.label}" not found in the final frame`);
82
269
  }
83
270
 
84
- // 6. No forbidden sources of time/randomness in the frame function.
271
+ // 6. No clock or randomness named in the frame function's own source: a
272
+ // hint for code paths the samples miss (rule 1 catches what they reach).
85
273
  const src = scene.frame.toString();
86
- if (/Date\.now|new Date|Math\.random|performance\.now/.test(src)) problems.push("frame() reads the clock or randomness");
274
+ if (!clockRead && /Date\.now|new Date|Math\.random|performance\.now|Temporal\.Now/.test(src)) problems.push("frame() reads the clock or randomness");
87
275
 
88
276
  // 7. Every id comes from the instance prefix, so two instances on a page
89
277
  // never share one: render with two prefixes and look for common ids.
90
278
  const fixed = new Set();
91
279
  for (let i = 0; i <= samples; i += 10) {
92
- const ids = (prefix) => new Set([...renderSvg(scene, at(i), { idPrefix: prefix }).matchAll(/\sid="([^"]*)"/g)].map((m) => m[1]));
280
+ const ids = (/** @type {string} */ prefix) => new Set([...renderSvg(scene, at(i), { idPrefix: prefix, style }).matchAll(/\sid="([^"]*)"/g)].map((m) => m[1]));
93
281
  const second = ids("mk-gate-b");
94
282
  for (const id of ids("mk-gate-a")) if (second.has(id)) fixed.add(id);
95
283
  }
96
284
  for (const id of fixed) problems.push(`fixed id "${id}": build ids from frame(t, { idPrefix }), e.g. \`\${idPrefix}-${id}\``);
97
285
 
286
+ // 8. The token pairs this scene draws beyond the shared ones
287
+ // (scene.contrastPairs) meet their contrast in the style, both themes.
288
+ if (scene.contrastPairs !== undefined) {
289
+ for (const p of checkContrast(style, scene.contrastPairs)) problems.push(`contrast: ${p}`);
290
+ }
291
+
98
292
  return { ok: problems.length === 0, problems };
99
293
  }