@liqweed/motion-kit 0.4.0 → 0.5.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 (38) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +13 -5
  4. package/adapters/element/README.md +5 -0
  5. package/adapters/page/README.md +5 -0
  6. package/cli/motion-kit.mjs +9 -3
  7. package/docs/spec/technique.md +93 -30
  8. package/examples/custom-pulse.scene.mjs +3 -0
  9. package/examples/incident.json +18 -0
  10. package/examples/web-stack.json +17 -0
  11. package/lib/build.mjs +1 -1
  12. package/lib/check.mjs +207 -16
  13. package/lib/export.mjs +104 -7
  14. package/lib/gate.mjs +5 -3
  15. package/package.json +6 -3
  16. package/runtime/kit.mjs +2 -2
  17. package/runtime/links.mjs +314 -0
  18. package/runtime/parts.mjs +15 -0
  19. package/runtime/patch.mjs +297 -0
  20. package/runtime/player.mjs +5 -1
  21. package/runtime/scene.mjs +3 -1
  22. package/runtime/style.mjs +62 -16
  23. package/runtime/types/hub-spoke.mjs +2 -2
  24. package/runtime/types/index.mjs +4 -0
  25. package/runtime/types/sequence.mjs +2 -2
  26. package/runtime/types/stack.mjs +227 -0
  27. package/runtime/types/timeline.mjs +405 -0
  28. package/skills/animated-diagram/SKILL.md +27 -6
  29. package/skills/animated-diagram/references/custom-scenes.md +6 -1
  30. package/skills/animated-diagram/references/interactivity.md +111 -6
  31. package/skills/animated-diagram/references/qc.md +3 -0
  32. package/skills/animated-diagram/references/scene-types.md +45 -2
  33. package/skills/animated-diagram/references/styles.md +45 -5
  34. package/skills/animated-diagram/references/technique.md +9 -4
  35. package/skills/motion-render/SKILL.md +24 -6
  36. package/skills/motion-render/references/formats.md +8 -8
  37. package/skills/project-logo/SKILL.md +15 -4
  38. package/styles/neutral.json +2 -2
@@ -0,0 +1,314 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · page links: drive a player from the page around it (browser;
5
+ * the step mapping is pure and also runs in Node).
6
+ *
7
+ * scrollSteps(controller, sections, options) → dispose
8
+ * Each text section names a step; as the reader scrolls, the section
9
+ * crossing a line across the viewport selects its step. One settled step
10
+ * per section, down and up; never scrubs continuously.
11
+ * linkSteps(controller, rootOrElements, options) → dispose
12
+ * Elements with `data-mk-step` select their step on hover (mouse, pen),
13
+ * keyboard focus and click.
14
+ *
15
+ * `controller` is what mountPlayer returns (or `.controller` of
16
+ * `<motion-diagram>` / the Astro adapter's root element). A step is named by
17
+ * its id or its zero-based index; an unknown id throws RangeError when the
18
+ * helper binds, not when the reader gets there.
19
+ *
20
+ * Nothing touches the DOM at import time, and neither helper moves focus or
21
+ * layout: the active section or term gets `aria-current="step"`, which the
22
+ * page styles without changing sizes.
23
+ */
24
+ import { stepIndex } from "./scene.mjs";
25
+
26
+ /** The attribute that names an element's step. */
27
+ const STEP_ATTR = "data-mk-step";
28
+
29
+ /** @import { Scene } from "./scene.mjs" */
30
+ /**
31
+ * The part of the player controller the helpers use.
32
+ * @typedef {{ scene: Scene, time: number, seek: (t: number) => void, seekStep: (ref: number | string) => void, playToStep: (ref: number | string) => void }} StepController
33
+ */
34
+ /**
35
+ * @typedef {object} ScrollStepsOptions
36
+ * @property {number} [line] where the line sits, as a share of the root's height from its top (0–1, default 0.5)
37
+ * @property {Element | Document | null} [root] the scroll container; default the viewport
38
+ * @property {boolean} [animate] play forward to the next section's step (default true); other moves jump
39
+ * @property {boolean} [mark] set `aria-current="step"` on the active section (default true)
40
+ * @property {(index: number, section: Element | null) => void} [onChange] called when the active section changes; -1 and null before the first
41
+ */
42
+ /**
43
+ * @typedef {object} LinkStepsOptions
44
+ * @property {boolean} [animate] play forward to a later step instead of jumping (default false)
45
+ * @property {boolean} [restore] when hover and focus leave every term, return to the frame shown before (default false: the step stays); a click keeps its step
46
+ * @property {boolean} [mark] set `aria-current="step"` on the terms of the selected step (default true)
47
+ * @property {(step: number, element: Element | null) => void} [onChange] called when a term selects a step, and with -1 and null on restore
48
+ */
49
+
50
+ /* ------------------------------------------------------- pure step mapping */
51
+
52
+ /**
53
+ * The step index a reference names: a step id, else a whole-number index
54
+ * (a number, or digits as `data-mk-step` gives them). An id wins over an index
55
+ * when a step's id is digits. Throws RangeError for an unknown id or an index
56
+ * out of range.
57
+ * @param {Scene} scene
58
+ * @param {number | string} ref
59
+ * @returns {number}
60
+ */
61
+ export function stepRef(scene, ref) {
62
+ if (typeof ref === "string") {
63
+ const trimmed = ref.trim();
64
+ if (scene.steps.some((s) => s.id === trimmed)) return stepIndex(scene, trimmed);
65
+ if (/^\d+$/.test(trimmed)) return stepIndex(scene, Number(trimmed));
66
+ return stepIndex(scene, trimmed);
67
+ }
68
+ return stepIndex(scene, ref);
69
+ }
70
+
71
+ /**
72
+ * The step of each section, in order: its own reference (`data-mk-step`) when
73
+ * it has one, else its position (the third section shows step 2). Throws
74
+ * RangeError when a reference is unknown or a section has no step to take.
75
+ * @param {Scene} scene
76
+ * @param {(number | string | null | undefined)[]} refs one per section; null or undefined to go by order
77
+ * @returns {number[]}
78
+ */
79
+ export function sectionSteps(scene, refs) {
80
+ return refs.map((ref, i) => {
81
+ if (ref != null && ref !== "") return stepRef(scene, ref);
82
+ if (i >= scene.steps.length) throw new RangeError(`Section ${i + 1} has no ${STEP_ATTR} and the scene has only ${scene.steps.length} steps`);
83
+ return i;
84
+ });
85
+ }
86
+
87
+ /**
88
+ * The active section: the last one, in order, whose top has reached the line
89
+ * (top ≤ line). A section stays active through the gap after it until the next
90
+ * one reaches the line, and the last one stays active below it. -1 while no
91
+ * section has reached the line.
92
+ * @param {number[]} tops each section's top, in the same coordinates as `line`
93
+ * @param {number} line
94
+ * @returns {number}
95
+ */
96
+ export function activeSection(tops, line) {
97
+ let active = -1;
98
+ tops.forEach((top, i) => {
99
+ if (top <= line) active = i;
100
+ });
101
+ return active;
102
+ }
103
+
104
+ /**
105
+ * How to move between sections: "play" to the next section's step when it is
106
+ * one section further and a later step (animation allowed, no reduced motion),
107
+ * "seek" for every other change (back, skipping, the first section), and null
108
+ * when there is nothing to do (no section, or the same step).
109
+ * @param {{ from: number, to: number, fromStep: number, toStep: number, animate?: boolean, reduced?: boolean }} move
110
+ * @returns {"play" | "seek" | null}
111
+ */
112
+ export function scrollMove({ from, to, fromStep, toStep, animate = true, reduced = false }) {
113
+ if (to < 0 || (from >= 0 && toStep === fromStep)) return null;
114
+ return animate && !reduced && from >= 0 && to === from + 1 && toStep > fromStep ? "play" : "seek";
115
+ }
116
+
117
+ /* ---------------------------------------------------------------- the DOM */
118
+
119
+ const reducedMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
120
+
121
+ /** @param {Element} el @param {boolean} on */
122
+ function markCurrent(el, on) {
123
+ if (on) el.setAttribute("aria-current", "step");
124
+ else if (el.getAttribute("aria-current") === "step") el.removeAttribute("aria-current");
125
+ }
126
+
127
+ /** @param {unknown} controller @returns {StepController} */
128
+ function needController(controller) {
129
+ const c = /** @type {any} */ (controller);
130
+ if (!c || typeof c.seekStep !== "function" || !c.scene) throw new TypeError("expected a player controller (mountPlayer, or .controller of <motion-diagram> / the Astro adapter)");
131
+ return c;
132
+ }
133
+
134
+ /**
135
+ * Bind a player to a list of text sections: as each section's top crosses a
136
+ * line across the viewport (or `root`), the diagram goes to that section's
137
+ * settled step. A section names its step with `data-mk-step` (step id or
138
+ * index), else by order. Moving one section forward plays to the next step;
139
+ * moving back, skipping sections and reduced motion jump. Without
140
+ * IntersectionObserver it does nothing.
141
+ *
142
+ * Give the page room below the last section (e.g. `padding-bottom: 50vh`), so
143
+ * the last section's top can reach the line. Mount the player with
144
+ * `autoplay: "none"`; the first section's step replaces any pending autoplay.
145
+ * @param {StepController} controller
146
+ * @param {Iterable<Element> | ArrayLike<Element>} sections in reading order
147
+ * @param {ScrollStepsOptions} [options]
148
+ * @returns {() => void} dispose: stops observing and clears the marks
149
+ */
150
+ export function scrollSteps(controller, sections, options = {}) {
151
+ const c = needController(controller);
152
+ const els = Array.from(sections);
153
+ const steps = sectionSteps(c.scene, els.map((el) => el.getAttribute(STEP_ATTR)));
154
+ const line = Math.min(Math.max(options.line ?? 0.5, 0), 1);
155
+ const { root = null, animate = true, mark = true, onChange } = options;
156
+ let current = -1;
157
+ let disposed = false;
158
+
159
+ /** The line's position in viewport coordinates. */
160
+ const lineY = () => {
161
+ if (root && "getBoundingClientRect" in root) {
162
+ const r = root.getBoundingClientRect();
163
+ return r.top + line * r.height;
164
+ }
165
+ return line * (globalThis.innerHeight ?? 0);
166
+ };
167
+ const update = () => {
168
+ if (disposed) return;
169
+ const next = activeSection(els.map((el) => el.getBoundingClientRect().top), lineY());
170
+ if (next === current) return;
171
+ const move = scrollMove({ from: current, to: next, fromStep: steps[current] ?? -1, toStep: steps[next] ?? -1, animate, reduced: reducedMotion() });
172
+ if (move === "play") c.playToStep(steps[next]);
173
+ else if (move === "seek") c.seekStep(steps[next]);
174
+ if (mark) els.forEach((el, i) => markCurrent(el, i === next));
175
+ current = next;
176
+ onChange?.(next, els[next] ?? null);
177
+ };
178
+
179
+ if (typeof IntersectionObserver !== "function") return () => {};
180
+ // The root, cut off at the line: a section enters or leaves it exactly
181
+ // when its top crosses the line, which is when the active one can change.
182
+ const below = `${(1 - line) * 100}%`;
183
+ const observer = new IntersectionObserver(update, { root, rootMargin: `0px 0px -${below} 0px`, threshold: 0 });
184
+ for (const el of els) observer.observe(el);
185
+ // A jump that moves every section across the line without changing which
186
+ // are inside the observed area sends no notification, so scrolling asks
187
+ // again, at most once per frame.
188
+ const scroller = root && "addEventListener" in root ? root : globalThis;
189
+ const raf = globalThis.requestAnimationFrame?.bind(globalThis);
190
+ let queued = false;
191
+ const onScroll = () => {
192
+ if (queued || disposed) return;
193
+ if (!raf) return update();
194
+ queued = true;
195
+ raf(() => {
196
+ queued = false;
197
+ update();
198
+ });
199
+ };
200
+ scroller.addEventListener?.("scroll", onScroll, { passive: true });
201
+ return () => {
202
+ if (disposed) return;
203
+ disposed = true;
204
+ observer.disconnect();
205
+ scroller.removeEventListener?.("scroll", onScroll);
206
+ if (mark) for (const el of els) markCurrent(el, false);
207
+ };
208
+ }
209
+
210
+ /**
211
+ * Bind a player to terms in the page: every element with `data-mk-step` (step
212
+ * id or index) under `root`, or the elements given, selects its step on
213
+ * pointer hover (mouse and pen; touch selects on click instead), on keyboard
214
+ * focus (also focus inside it) and on click. Make terms focusable, e.g.
215
+ * `<button type="button" data-mk-step="payment">`, so keyboard users get the
216
+ * same step as pointer users. A selection jumps; `animate: true` plays forward
217
+ * to a later step unless the reader prefers reduced motion.
218
+ *
219
+ * By default the selected step stays when the pointer or focus leaves.
220
+ * `restore: true` makes hover and focus a preview: once neither is on a term,
221
+ * the diagram returns to the frame it showed before; a click keeps its step.
222
+ * Terms are collected when binding; bind again for terms added later.
223
+ * @param {StepController} controller
224
+ * @param {ParentNode | Iterable<Element> | ArrayLike<Element>} target a root to search, or the terms
225
+ * @param {LinkStepsOptions} [options]
226
+ * @returns {() => void} dispose: removes the listeners and clears the marks
227
+ */
228
+ export function linkSteps(controller, target, options = {}) {
229
+ const c = needController(controller);
230
+ const { animate = false, restore = false, mark = true, onChange } = options;
231
+ const t = /** @type {any} */ (target);
232
+ /** @type {Element[]} */
233
+ const els = typeof t?.querySelectorAll === "function" ? Array.from(t.querySelectorAll(`[${STEP_ATTR}]`)) : Array.from(t);
234
+ const steps = els.map((el) => {
235
+ const ref = el.getAttribute(STEP_ATTR);
236
+ if (ref == null || ref === "") throw new RangeError(`linkSteps: an element has no ${STEP_ATTR}`);
237
+ return stepRef(c.scene, ref);
238
+ });
239
+ /** @type {Element | null} */
240
+ let hovered = null;
241
+ /** @type {Element | null} */
242
+ let focused = null;
243
+ /** The time before a preview began, to restore; null when nothing is previewed. @type {number | null} */
244
+ let before = null;
245
+ let selected = -1;
246
+
247
+ /** @param {number} step @param {Element | null} el */
248
+ const show = (step, el) => {
249
+ selected = step;
250
+ if (mark) els.forEach((e, i) => markCurrent(e, steps[i] === step));
251
+ onChange?.(step, el);
252
+ };
253
+ /** @param {number} i */
254
+ const select = (i) => {
255
+ const step = steps[i];
256
+ if (animate && !reducedMotion()) c.playToStep(step);
257
+ else c.seekStep(step);
258
+ show(step, els[i]);
259
+ };
260
+ /** @param {number} i */
261
+ const preview = (i) => {
262
+ if (restore && before === null) before = c.time;
263
+ select(i);
264
+ };
265
+ const leave = () => {
266
+ if (!restore || hovered || focused || before === null) return;
267
+ c.seek(before);
268
+ before = null;
269
+ if (selected !== -1) show(-1, null);
270
+ };
271
+
272
+ /** @type {[Element, string, (e: any) => void][]} */
273
+ const bound = [];
274
+ els.forEach((el, i) => {
275
+ /** @type {Record<string, (e: any) => void>} */
276
+ const on = {
277
+ pointerenter: (e) => {
278
+ if (e?.pointerType === "touch") return;
279
+ hovered = el;
280
+ preview(i);
281
+ },
282
+ pointerleave: (e) => {
283
+ if (e?.pointerType === "touch" || hovered !== el) return;
284
+ hovered = null;
285
+ leave();
286
+ },
287
+ focusin: () => {
288
+ focused = el;
289
+ preview(i);
290
+ },
291
+ focusout: () => {
292
+ if (focused !== el) return;
293
+ focused = null;
294
+ leave();
295
+ },
296
+ click: () => {
297
+ // A click commits: nothing to restore afterwards.
298
+ before = null;
299
+ select(i);
300
+ },
301
+ };
302
+ for (const [name, fn] of Object.entries(on)) {
303
+ el.addEventListener(name, fn);
304
+ bound.push([el, name, fn]);
305
+ }
306
+ });
307
+ let disposed = false;
308
+ return () => {
309
+ if (disposed) return;
310
+ disposed = true;
311
+ for (const [el, name, fn] of bound) el.removeEventListener(name, fn);
312
+ if (mark) for (const el of els) markCurrent(el, false);
313
+ };
314
+ }
package/runtime/parts.mjs CHANGED
@@ -12,6 +12,21 @@ import { attrString, el, esc, fade, num, text, translate } from "./svg.mjs";
12
12
  import { tok } from "./style.mjs";
13
13
 
14
14
  export const FONT_MIN = 14; // smallest label size at 1× (viewBox units)
15
+ export const FONT_MAX = 200; // largest `fontSize` a scene may ask for
16
+
17
+ /**
18
+ * The largest label size a scene type tries: its `fontSize`, else `dflt`. The
19
+ * fit searches count down from it, so it must be a finite number in range.
20
+ * @param {{ fontSize?: number }} spec
21
+ * @param {number} dflt
22
+ * @param {string} name for the error
23
+ * @returns {number}
24
+ */
25
+ export function maxFontSize(spec, dflt, name) {
26
+ const fs = spec.fontSize ?? dflt;
27
+ if (!Number.isFinite(fs) || fs < FONT_MIN || fs > FONT_MAX) throw new Error(`${name}: fontSize must be a number from ${FONT_MIN} to ${FONT_MAX}, got ${fs}`);
28
+ return fs;
29
+ }
15
30
 
16
31
  /**
17
32
  * Optional icon: SVG path data drawn on a 24×24 grid with round strokes
@@ -0,0 +1,297 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · update rendered SVG in place (browser; the parser runs anywhere).
5
+ *
6
+ * patchMarkup(parent, markup) → true when updated in place, false when it fell back to innerHTML
7
+ *
8
+ * The live player draws each frame by handing the frame's markup to
9
+ * patchMarkup instead of assigning innerHTML. Nodes that persist between
10
+ * frames are kept; only changed attributes and text are written; nodes are
11
+ * added or removed only where the markup's structure changes. The browser
12
+ * then restyles and lays out what changed, and hover and other node state
13
+ * survive.
14
+ *
15
+ * Children are matched by position: a child whose tag differs from the one
16
+ * drawn before is replaced with its subtree, and a child whose markup is
17
+ * byte-identical to the one drawn before is not visited at all.
18
+ *
19
+ * The parser takes the markup scenes emit (one or more `<svg>` elements;
20
+ * double-quoted attributes; text with the entities `esc()` writes and numeric
21
+ * ones) and builds the nodes the HTML parser would build from the same string:
22
+ * names lowercased then SVG-cased, `xlink:`/`xml:`/`xmlns` attributes in their
23
+ * namespaces. Anything else (comments, CDATA, single-quoted or bare
24
+ * attributes, named entities beyond the XML five, elements inside `<title>`,
25
+ * `<desc>` or `<foreignObject>`, HTML elements that leave SVG) is left to the
26
+ * HTML parser: patchMarkup then assigns innerHTML for that call.
27
+ *
28
+ * The patch owns the parent's content: change it only through patchMarkup. If
29
+ * the parent's children were replaced by other code, the next call rebuilds.
30
+ */
31
+
32
+ const SVG_NS = "http://www.w3.org/2000/svg";
33
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
34
+ const XML_NS = "http://www.w3.org/XML/1998/namespace";
35
+ const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
36
+
37
+ /** @param {string} names @returns {Map<string, string>} lowercased → SVG-cased */
38
+ const caseMap = (names) => new Map(names.split(" ").map((n) => [n.toLowerCase(), n]));
39
+
40
+ // The HTML parser's "adjust SVG tag names" and "adjust SVG attributes" tables.
41
+ const SVG_TAGS = caseMap(
42
+ "altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer " +
43
+ "feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR " +
44
+ "feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence " +
45
+ "foreignObject glyphRef linearGradient radialGradient textPath",
46
+ );
47
+ const SVG_ATTRS = caseMap(
48
+ "attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits diffuseConstant edgeMode filterUnits glyphRef " +
49
+ "gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle " +
50
+ "markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform " +
51
+ "patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur " +
52
+ "requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles " +
53
+ "surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan",
54
+ );
55
+ /** The HTML parser's "adjust foreign attributes": name → [namespace, local name]. @type {Map<string, [string, string]>} */
56
+ const FOREIGN_ATTRS = new Map([
57
+ ...["actuate", "arcrole", "href", "role", "show", "title", "type"].map((n) => /** @type {[string, [string, string]]} */ ([`xlink:${n}`, [XLINK_NS, n]])),
58
+ ["xml:lang", [XML_NS, "lang"]],
59
+ ["xml:space", [XML_NS, "space"]],
60
+ ["xmlns", [XMLNS_NS, "xmlns"]],
61
+ ["xmlns:xlink", [XMLNS_NS, "xlink"]],
62
+ ]);
63
+ // Start tags that take the HTML parser out of SVG, and the SVG elements whose
64
+ // child elements it parses as HTML.
65
+ const LEAVES_SVG = new Set(
66
+ "b big blockquote body br center code dd div dl dt em embed font h1 h2 h3 h4 h5 h6 head hr i img li listing math menu meta nobr ol p pre ruby s small span strike strong sub sup table tt u ul var".split(" "),
67
+ );
68
+ const HTML_INSIDE = new Set(["title", "desc", "foreignObject"]);
69
+
70
+ // Whitespace is the HTML parser's: tab, line feed, form feed, space.
71
+ const TAG = /<(\/?)([A-Za-z][^\t\n\f />]*)((?:[\t\n\f ]+[^\t\n\f "'<>/=]+="[^"]*")*)[\t\n\f ]*(\/?)>/y;
72
+ const ATTR = /([^\t\n\f "'<>/=]+)="([^"]*)"/g;
73
+ const ENTITY = /&(?:#(\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|(amp|lt|gt|quot|apos));|&/g;
74
+ const NAMED = /** @type {Record<string, string>} */ ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" });
75
+
76
+ /**
77
+ * One parsed node. Elements have a tag, attributes as a flat
78
+ * `[name, value, …]` list and children; text nodes have the tag `#text` and
79
+ * their decoded `text`. `src` is the node's own markup; `dom` the live node
80
+ * once drawn.
81
+ * @typedef {{ tag: string, attrs: string[], kids: MarkupNode[], src: string, text: string, dom: Node | null }} MarkupNode
82
+ */
83
+
84
+ // Shared empty lists: a node's attributes when it has none, and a text node's
85
+ // children (never patched).
86
+ /** @type {string[]} */
87
+ const NO_ATTRS = [];
88
+ /** @type {MarkupNode[]} */
89
+ const NO_KIDS = [];
90
+
91
+ /** Decode entities as the HTML parser does; null for an `&` it might read differently. @param {string} s */
92
+ function decode(s) {
93
+ if (!s.includes("&")) return s;
94
+ let ok = true;
95
+ const out = s.replace(ENTITY, (m, dec, hex, name) => {
96
+ if (name) return NAMED[name];
97
+ const cp = dec ? Number(dec) : hex ? parseInt(hex, 16) : -1;
98
+ // Code points the HTML parser remaps or rejects are left to it.
99
+ if (cp < 0x20 ? cp !== 9 && cp !== 10 : (cp >= 0x7f && cp <= 0x9f) || (cp >= 0xd800 && cp <= 0xdfff) || cp > 0x10ffff) ok = false;
100
+ return ok ? String.fromCodePoint(cp) : m;
101
+ });
102
+ return ok ? out : null;
103
+ }
104
+
105
+ /** @param {string} s */
106
+ function parseAttrs(s) {
107
+ /** @type {string[]} */
108
+ const attrs = [];
109
+ for (const m of s.matchAll(ATTR)) {
110
+ const lower = m[1].toLowerCase();
111
+ const name = SVG_ATTRS.get(lower) ?? lower;
112
+ const value = decode(m[2]);
113
+ if (value === null) return null;
114
+ // The HTML parser keeps the first of a repeated attribute.
115
+ if (find(attrs, name) < 0) attrs.push(name, value);
116
+ }
117
+ return attrs;
118
+ }
119
+
120
+ /**
121
+ * Parse markup into nodes, or return null when it is outside the subset this
122
+ * module reproduces exactly (see the module comment). Exported for tests.
123
+ * @param {string} markup
124
+ * @returns {MarkupNode[] | null}
125
+ */
126
+ export function parseMarkup(markup) {
127
+ if (/[\r\0]/.test(markup)) return null;
128
+ /** @type {MarkupNode[]} */
129
+ const root = [];
130
+ /** @type {MarkupNode[]} */
131
+ const open = [];
132
+ /** @type {number[]} */
133
+ const starts = [];
134
+ let kids = root;
135
+ let pos = 0;
136
+ while (pos < markup.length) {
137
+ if (markup.charCodeAt(pos) !== 60 /* < */) {
138
+ let end = markup.indexOf("<", pos);
139
+ if (end < 0) end = markup.length;
140
+ const src = markup.slice(pos, end);
141
+ const text = decode(src);
142
+ if (text === null) return null;
143
+ kids.push({ tag: "#text", attrs: NO_ATTRS, kids: NO_KIDS, src, text, dom: null });
144
+ pos = end;
145
+ continue;
146
+ }
147
+ TAG.lastIndex = pos;
148
+ const m = TAG.exec(markup);
149
+ if (!m) return null;
150
+ const lower = m[2].toLowerCase();
151
+ const tag = SVG_TAGS.get(lower) ?? lower;
152
+ if (m[1]) {
153
+ if (m[3] || m[4]) return null;
154
+ const el = open.pop();
155
+ if (!el || el.tag !== tag) return null;
156
+ el.src = markup.slice(/** @type {number} */ (starts.pop()), TAG.lastIndex);
157
+ kids = open.length ? open[open.length - 1].kids : root;
158
+ } else {
159
+ const parent = open[open.length - 1];
160
+ if (parent ? HTML_INSIDE.has(parent.tag) || LEAVES_SVG.has(tag) : tag !== "svg") return null;
161
+ const attrs = m[3] ? parseAttrs(m[3]) : NO_ATTRS;
162
+ if (!attrs) return null;
163
+ /** @type {MarkupNode} */
164
+ const el = { tag, attrs, kids: [], src: m[0], text: "", dom: null };
165
+ kids.push(el);
166
+ if (!m[4]) {
167
+ open.push(el);
168
+ starts.push(pos);
169
+ kids = el.kids;
170
+ }
171
+ }
172
+ pos = TAG.lastIndex;
173
+ }
174
+ return open.length ? null : root;
175
+ }
176
+
177
+ /** @param {Element} el @param {string} name @param {string} value */
178
+ function setAttr(el, name, value) {
179
+ const f = FOREIGN_ATTRS.get(name);
180
+ if (f) el.setAttributeNS(f[0], name, value);
181
+ else el.setAttribute(name, value);
182
+ }
183
+
184
+ /** @param {Element} el @param {string} name */
185
+ function removeAttr(el, name) {
186
+ const f = FOREIGN_ATTRS.get(name);
187
+ if (f) el.removeAttributeNS(f[0], f[1]);
188
+ else el.removeAttribute(name);
189
+ }
190
+
191
+ /** Write the attributes that changed. @param {Element} el @param {string[]} from @param {string[]} to */
192
+ function patchAttrs(el, from, to) {
193
+ let same = from.length === to.length;
194
+ for (let i = 0; same && i < to.length; i += 2) same = from[i] === to[i];
195
+ if (same) {
196
+ // Same names in the same order: the usual case for an animated element.
197
+ for (let i = 1; i < to.length; i += 2) if (from[i] !== to[i]) setAttr(el, to[i - 1], to[i]);
198
+ return;
199
+ }
200
+ for (let i = 0; i < from.length; i += 2) if (find(to, from[i]) < 0) removeAttr(el, from[i]);
201
+ for (let i = 0; i < to.length; i += 2) {
202
+ const j = find(from, to[i]);
203
+ if (j < 0 || from[j + 1] !== to[i + 1]) setAttr(el, to[i], to[i + 1]);
204
+ }
205
+ }
206
+
207
+ /** Index of an attribute's name in a flat `[name, value, …]` list, or -1. @param {string[]} attrs @param {string} name */
208
+ function find(attrs, name) {
209
+ for (let i = 0; i < attrs.length; i += 2) if (attrs[i] === name) return i;
210
+ return -1;
211
+ }
212
+
213
+ /** Build a node's subtree, detached. @param {Document} doc @param {MarkupNode} node @returns {Node} */
214
+ function create(doc, node) {
215
+ if (node.tag === "#text") return (node.dom = doc.createTextNode(node.text));
216
+ const el = doc.createElementNS(SVG_NS, node.tag);
217
+ for (let i = 0; i < node.attrs.length; i += 2) setAttr(el, node.attrs[i], node.attrs[i + 1]);
218
+ for (const kid of node.kids) el.appendChild(create(doc, kid));
219
+ return (node.dom = el);
220
+ }
221
+
222
+ /**
223
+ * Make `parent`'s children, drawn from `from`, match `to`. Children of `to`
224
+ * whose markup did not change are replaced by their `from` node, which keeps
225
+ * its live node and its children.
226
+ * @param {Document} doc @param {Node} parent @param {MarkupNode[]} from @param {MarkupNode[]} to
227
+ */
228
+ function patchKids(doc, parent, from, to) {
229
+ for (let i = 0; i < to.length; i++) {
230
+ const next = to[i];
231
+ const prev = from[i];
232
+ if (!prev) {
233
+ parent.appendChild(create(doc, next));
234
+ } else if (prev.src === next.src) {
235
+ to[i] = prev;
236
+ } else if (prev.tag !== next.tag) {
237
+ parent.replaceChild(create(doc, next), /** @type {Node} */ (prev.dom));
238
+ } else if (next.tag === "#text") {
239
+ next.dom = prev.dom;
240
+ if (prev.text !== next.text) /** @type {Text} */ (next.dom).data = next.text;
241
+ } else {
242
+ const el = /** @type {Element} */ (prev.dom);
243
+ next.dom = el;
244
+ patchAttrs(el, prev.attrs, next.attrs);
245
+ patchKids(doc, el, prev.kids, next.kids);
246
+ }
247
+ }
248
+ for (let i = from.length - 1; i >= to.length; i--) parent.removeChild(/** @type {Node} */ (from[i].dom));
249
+ }
250
+
251
+ /** What each parent shows: its nodes and the markup they came from. @type {WeakMap<Node, { kids: MarkupNode[], markup: string }>} */
252
+ const drawn = new WeakMap();
253
+
254
+ /** Whether the parent still holds exactly the nodes drawn last time. @param {Node} parent @param {MarkupNode[]} kids */
255
+ function intact(parent, kids) {
256
+ const nodes = parent.childNodes;
257
+ if (nodes.length !== kids.length) return false;
258
+ for (let i = 0; i < kids.length; i++) if (nodes[i] !== kids[i].dom) return false;
259
+ return true;
260
+ }
261
+
262
+ /**
263
+ * Show `markup` in `parent`, updating the nodes already there instead of
264
+ * replacing them. The result is the DOM `parent.innerHTML = markup` would
265
+ * build. Falls back to that assignment when the markup is outside the subset
266
+ * described in the module comment.
267
+ * @param {Element} parent an HTML element whose content only patchMarkup changes
268
+ * @param {string} markup one frame's SVG markup (renderSvg output)
269
+ * @returns {boolean} true when the DOM was updated in place, false when innerHTML was assigned
270
+ */
271
+ export function patchMarkup(parent, markup) {
272
+ const last = drawn.get(parent);
273
+ const kept = last !== undefined && intact(parent, last.kids);
274
+ if (kept && last.markup === markup) return true;
275
+ const kids = parseMarkup(markup);
276
+ if (kids) {
277
+ const doc = /** @type {Document} */ (parent.ownerDocument);
278
+ try {
279
+ if (kept) patchKids(doc, parent, last.kids, kids);
280
+ else {
281
+ parent.textContent = "";
282
+ for (const kid of kids) parent.appendChild(create(doc, kid));
283
+ }
284
+ drawn.set(parent, { kids, markup });
285
+ return true;
286
+ } catch (e) {
287
+ // A name the DOM refuses (createElementNS, setAttribute) but the HTML
288
+ // parser accepts: let it decide. Anything else is a bug; surface it.
289
+ // A DOMException, possibly from another realm (an iframe's document).
290
+ const name = typeof e === "object" && e !== null && "name" in e ? e.name : "";
291
+ if (name !== "InvalidCharacterError" && name !== "NamespaceError") throw e;
292
+ }
293
+ }
294
+ drawn.delete(parent);
295
+ parent.innerHTML = markup;
296
+ return false;
297
+ }
@@ -24,9 +24,12 @@
24
24
  * - Keyboard on the stage (a named group, described by a hint): ←/→ previous/next
25
25
  * step, Space play/pause, Home/End.
26
26
  * - Capture hook: controller.seek(t), and window.__motionKit[id] for renderers.
27
+ * - Each frame updates the stage's SVG in place (runtime/patch.mjs): nodes that
28
+ * persist between frames are kept, only changed attributes and text are written.
27
29
  *
28
30
  * The player owns the clock (requestAnimationFrame); scenes stay pure.
29
31
  */
32
+ import { patchMarkup } from "./patch.mjs";
30
33
  import { renderSvg, safeId, stepIndex, stepIndexAt } from "./scene.mjs";
31
34
  import { cssVars, normalizeStyle, TOKENS } from "./style.mjs";
32
35
  import { esc } from "./svg.mjs";
@@ -284,7 +287,8 @@ export function mountPlayer(container, scene, options = {}) {
284
287
  let visibilityObserver;
285
288
 
286
289
  function draw() {
287
- stage.innerHTML = renderSvg(scene, t, { style, idPrefix: prefix, live: true });
290
+ // In place: nodes that persist keep their identity, only what changed is written.
291
+ patchMarkup(stage, renderSvg(scene, t, { style, idPrefix: prefix, live: true }));
288
292
  const idx = stepIndexAt(scene, t);
289
293
  ui.steps.forEach((b, i) => (i === idx ? b.setAttribute("aria-current", "step") : b.removeAttribute("aria-current")));
290
294
  ui.captions?.forEach((c, i) => (i === idx ? c.setAttribute("class", "mk-on") : c.removeAttribute("class")));
package/runtime/scene.mjs CHANGED
@@ -36,7 +36,9 @@ import { normalizeStyle, cssVars, resolveTokens } from "./style.mjs";
36
36
  */
37
37
  /**
38
38
  * An animated diagram as a pure function of time (see the module comment).
39
- * @typedef {{ id: string, width: number, height: number, duration: number, title: string, description: string, steps: Step[], frame: (t: number, ctx: FrameContext) => string, stepLabelsInFrame?: boolean, type?: string, format?: string, locale?: string }} Scene
39
+ * `contrastPairs`: token pairs the scene draws beyond CONTRAST_PAIRS
40
+ * (runtime/style.mjs), which the gate checks the style against.
41
+ * @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 }[], type?: string, format?: string, locale?: string }} Scene
40
42
  */
41
43
 
42
44
  /** Formats: name → viewBox. Layouts are computed per format, never cropped. */