@real-music-packages/web-core 0.37.0 → 0.39.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.
@@ -0,0 +1,367 @@
1
+ import {
2
+ computeReflowScrollDelta,
3
+ createFollowController
4
+ } from "./chunk-HZFDLJLA.js";
5
+ import {
6
+ distinctOnsets,
7
+ hitTestMeasureAt,
8
+ measureColumnsFromLayout,
9
+ vstackAudioPlayheadLine
10
+ } from "./chunk-BHRDISMU.js";
11
+ import "./chunk-HXTRNE74.js";
12
+
13
+ // src/notationPlayerVerovio.ts
14
+ var EMPTY_LAYOUT = {
15
+ src: { x: 0, y: 0, w: 0, h: 0 },
16
+ rect: { dx: 0, dy: 0, dw: 0, dh: 0 },
17
+ systems: [],
18
+ measures: []
19
+ };
20
+ function safeRect(el) {
21
+ return typeof el.getBoundingClientRect === "function" ? el.getBoundingClientRect() : null;
22
+ }
23
+ function readViewBox(svgEl) {
24
+ const baseVal = svgEl.viewBox && svgEl.viewBox.baseVal;
25
+ if (baseVal && baseVal.width > 0) return { w: baseVal.width, h: baseVal.height };
26
+ const attr = svgEl.getAttribute("viewBox");
27
+ if (!attr) return null;
28
+ const parts = attr.trim().split(/[\s,]+/).map(Number);
29
+ if (parts.length !== 4 || !(parts[2] > 0)) return null;
30
+ return { w: parts[2], h: parts[3] };
31
+ }
32
+ function pageGeometry(root, pageEl) {
33
+ const outerSvg = pageEl.querySelector("svg");
34
+ if (!outerSvg) return null;
35
+ const innerSvg = outerSvg.querySelector("svg[viewBox]") ?? outerSvg;
36
+ const vb = readViewBox(innerSvg);
37
+ if (!vb) return null;
38
+ const outerRect = safeRect(outerSvg);
39
+ const rootRect = safeRect(root);
40
+ const pageRect = safeRect(pageEl);
41
+ if (!outerRect || !rootRect || !pageRect) return null;
42
+ if (!(outerRect.width > 0)) return null;
43
+ const scale = outerRect.width / vb.w;
44
+ if (!(scale > 0) || !Number.isFinite(scale)) return null;
45
+ return { scale, offsetX: pageRect.left - rootRect.left, offsetY: pageRect.top - rootRect.top };
46
+ }
47
+ function boxFromElement(el, geom) {
48
+ const ge = el;
49
+ if (typeof ge.getBBox !== "function") return null;
50
+ let bbox;
51
+ try {
52
+ bbox = ge.getBBox();
53
+ } catch {
54
+ return null;
55
+ }
56
+ if (!bbox || !(bbox.width > 0) || !(bbox.height > 0)) return null;
57
+ return {
58
+ x: geom.offsetX + bbox.x * geom.scale,
59
+ y: geom.offsetY + bbox.y * geom.scale,
60
+ w: bbox.width * geom.scale,
61
+ h: bbox.height * geom.scale
62
+ };
63
+ }
64
+ function computePageGeometries(root) {
65
+ const map = /* @__PURE__ */ new Map();
66
+ for (const pageEl of Array.from(root.querySelectorAll(".vrv-page"))) {
67
+ const geom = pageGeometry(root, pageEl);
68
+ if (geom) map.set(pageEl, geom);
69
+ }
70
+ return map;
71
+ }
72
+ function collectMeasureElements(pageGeoms) {
73
+ const out = [];
74
+ for (const [pageEl, geom] of pageGeoms) {
75
+ for (const measureEl of Array.from(pageEl.querySelectorAll("g.measure"))) {
76
+ if (measureEl.querySelector("g.staff")) out.push({ el: measureEl, geom });
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+ function verovioNotationLayout(root) {
82
+ try {
83
+ const pageGeoms = computePageGeometries(root);
84
+ if (!pageGeoms.size) return EMPTY_LAYOUT;
85
+ const measureEntries = collectMeasureElements(pageGeoms);
86
+ if (!measureEntries.length) return EMPTY_LAYOUT;
87
+ const measures = [];
88
+ measureEntries.forEach(({ el: measureEl, geom }, index) => {
89
+ const staffEls = Array.from(measureEl.querySelectorAll("g.staff"));
90
+ const staffBoxes = staffEls.map((el) => ({ el, box: boxFromElement(el, geom) })).filter((s) => !!s.box).sort((a, b) => a.box.y - b.box.y);
91
+ staffBoxes.forEach(({ el: staffEl, box }, staff) => {
92
+ const noteEls = Array.from(measureEl.querySelectorAll("g.note")).filter(
93
+ (n) => n.closest("g.staff") === staffEl
94
+ );
95
+ const noteXs = noteEls.map((n) => boxFromElement(n, geom)?.x).filter((x) => x != null);
96
+ const noteStartX = noteXs.length ? Math.min(...noteXs) : box.x;
97
+ measures.push({ index, staff, box, noteStartX });
98
+ });
99
+ });
100
+ if (!measures.length) return EMPTY_LAYOUT;
101
+ const systems = [];
102
+ for (const [pageEl, geom] of pageGeoms) {
103
+ for (const sysEl of Array.from(pageEl.querySelectorAll("g.system"))) {
104
+ const box = boxFromElement(sysEl, geom);
105
+ if (box) systems.push(box);
106
+ }
107
+ }
108
+ const rootRect = safeRect(root);
109
+ const fallbackW = Math.max(0, ...measures.map((m) => m.box.x + m.box.w));
110
+ const fallbackH = Math.max(0, ...measures.map((m) => m.box.y + m.box.h));
111
+ const dw = rootRect && rootRect.width > 0 ? rootRect.width : fallbackW;
112
+ const dh = rootRect && rootRect.height > 0 ? rootRect.height : fallbackH;
113
+ return { src: { x: 0, y: 0, w: dw, h: dh }, rect: { dx: 0, dy: 0, dw, dh }, systems, measures };
114
+ } catch {
115
+ return EMPTY_LAYOUT;
116
+ }
117
+ }
118
+ function verovioOnsetColumns(root, layout, onsets) {
119
+ try {
120
+ const distinctMs = distinctOnsets(onsets.map((o) => ({ onsetMs: o.tMs })));
121
+ if (!distinctMs.length) return void 0;
122
+ const cols = measureColumnsFromLayout(layout.measures);
123
+ if (!cols.length) return void 0;
124
+ const pageGeoms = computePageGeometries(root);
125
+ const measureEntries = collectMeasureElements(pageGeoms);
126
+ if (!measureEntries.length) return void 0;
127
+ const measureIndexOf = /* @__PURE__ */ new Map();
128
+ measureEntries.forEach((m, i) => measureIndexOf.set(m.el, i));
129
+ const idsByOnset = /* @__PURE__ */ new Map();
130
+ for (const o of onsets) {
131
+ const arr = idsByOnset.get(o.tMs) ?? [];
132
+ for (const id of o.noteIds) if (!arr.includes(id)) arr.push(id);
133
+ idsByOnset.set(o.tMs, arr);
134
+ }
135
+ const doc = root.ownerDocument;
136
+ return distinctMs.map((tMs, k) => {
137
+ const ids = idsByOnset.get(tMs) ?? [];
138
+ const positions = [];
139
+ for (const id of ids) {
140
+ const noteEl = doc ? doc.getElementById(id) : null;
141
+ const measureEl = noteEl ? noteEl.closest("g.measure") : null;
142
+ const index = measureEl ? measureIndexOf.get(measureEl) : void 0;
143
+ if (index == null) continue;
144
+ const m = cols[index];
145
+ const geom = measureEntries[index]?.geom;
146
+ const box = noteEl && geom ? boxFromElement(noteEl, geom) : null;
147
+ if (!box || !m) continue;
148
+ const sx = Math.min(m.noteStartX, m.x + m.w);
149
+ const denom = m.x + m.w - sx;
150
+ const frac = denom > 0 ? Math.min(1, Math.max(0, (box.x - sx) / denom)) : 0;
151
+ positions.push(index + frac);
152
+ }
153
+ if (positions.length) return positions.reduce((a, b) => a + b, 0) / positions.length;
154
+ return distinctMs.length === 1 ? 0 : k / (distinctMs.length - 1) * cols.length;
155
+ });
156
+ } catch {
157
+ return void 0;
158
+ }
159
+ }
160
+ var VEROVIO_BASE_SCALE = 40;
161
+ var VEROVIO_MIN_SCALE = 20;
162
+ var VEROVIO_MAX_SCALE = 120;
163
+ function verovioZoomOptions(hostWidthPx, zoom) {
164
+ const z = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
165
+ const scale = Math.max(VEROVIO_MIN_SCALE, Math.min(VEROVIO_MAX_SCALE, VEROVIO_BASE_SCALE * z));
166
+ const w = Number.isFinite(hostWidthPx) && hostWidthPx > 0 ? hostWidthPx : MAX_ENGRAVE_WIDTH_VRV;
167
+ const pageWidth = w * 100 / scale;
168
+ return { scale, pageWidth };
169
+ }
170
+ var toolkitPromise = null;
171
+ function getVerovioToolkit() {
172
+ if (!toolkitPromise) {
173
+ toolkitPromise = (async () => {
174
+ const [{ default: createVerovioModule }, { VerovioToolkit }] = await Promise.all([
175
+ import("verovio/wasm"),
176
+ import("verovio/esm")
177
+ ]);
178
+ const VerovioModule = await createVerovioModule();
179
+ return new VerovioToolkit(VerovioModule);
180
+ })();
181
+ }
182
+ return toolkitPromise;
183
+ }
184
+ var DEFAULT_PLAYHEAD_COLOR = "#2f6f4f";
185
+ var MAX_ENGRAVE_WIDTH_VRV = 1200;
186
+ var MIN_ENGRAVE_WIDTH_VRV = 280;
187
+ function createVerovioNotationPlayer(opts) {
188
+ const { host, musicXml, onsets: rawOnsets } = opts;
189
+ const playheadColor = opts.playheadColor ?? DEFAULT_PLAYHEAD_COLOR;
190
+ const onsets = distinctOnsets(rawOnsets.map((o) => ({ onsetMs: o.tMs })));
191
+ const root = document.createElement("div");
192
+ root.style.position = "relative";
193
+ root.style.width = "100%";
194
+ root.style.touchAction = "pan-y pinch-zoom";
195
+ host.appendChild(root);
196
+ const svgHost = document.createElement("div");
197
+ root.appendChild(svgHost);
198
+ const playheadEl = document.createElement("div");
199
+ playheadEl.style.position = "absolute";
200
+ playheadEl.style.left = "0px";
201
+ playheadEl.style.top = "0px";
202
+ playheadEl.style.width = "2px";
203
+ playheadEl.style.height = "0px";
204
+ playheadEl.style.background = playheadColor;
205
+ playheadEl.style.opacity = "0";
206
+ playheadEl.style.pointerEvents = "none";
207
+ root.appendChild(playheadEl);
208
+ let currentLayout = null;
209
+ let currentNoteCols;
210
+ let currentZoom = opts.zoom ?? 1;
211
+ let lastEngravedWidthPx = 0;
212
+ let loaded = false;
213
+ let destroyed = false;
214
+ let lastTMs = 0;
215
+ let rebuildToken = 0;
216
+ function desiredEngraveWidthPx() {
217
+ const w = host.clientWidth || 0;
218
+ return Math.max(MIN_ENGRAVE_WIDTH_VRV, Math.min(w || MAX_ENGRAVE_WIDTH_VRV, MAX_ENGRAVE_WIDTH_VRV));
219
+ }
220
+ const follow = createFollowController();
221
+ function renderPlayhead(tMs) {
222
+ lastTMs = tMs;
223
+ if (!currentLayout) return;
224
+ const nBars = currentLayout.measures.length ? Math.max(...currentLayout.measures.map((m) => m.index)) + 1 : 0;
225
+ const line = vstackAudioPlayheadLine(currentLayout, onsets, tMs, nBars, currentNoteCols);
226
+ if (!line) {
227
+ playheadEl.style.opacity = "0";
228
+ return;
229
+ }
230
+ playheadEl.style.opacity = String(line.alpha);
231
+ playheadEl.style.left = `${line.x}px`;
232
+ playheadEl.style.top = `${line.y0}px`;
233
+ playheadEl.style.height = `${Math.max(0, line.y1 - line.y0)}px`;
234
+ follow.follow(
235
+ () => typeof playheadEl.getBoundingClientRect === "function" ? playheadEl.getBoundingClientRect() : null
236
+ );
237
+ }
238
+ function setTime(tMs) {
239
+ if (destroyed) return;
240
+ follow.onSetTime(tMs);
241
+ renderPlayhead(tMs);
242
+ }
243
+ function rebuildLayoutFromDom() {
244
+ currentLayout = verovioNotationLayout(svgHost);
245
+ currentNoteCols = verovioOnsetColumns(svgHost, currentLayout, rawOnsets);
246
+ }
247
+ function renderAllPages(toolkit) {
248
+ svgHost.replaceChildren();
249
+ const pageCount = Math.max(0, toolkit.getPageCount());
250
+ for (let p = 1; p <= pageCount; p++) {
251
+ const pageDiv = document.createElement("div");
252
+ pageDiv.className = "vrv-page";
253
+ pageDiv.innerHTML = toolkit.renderToSVG(p);
254
+ svgHost.appendChild(pageDiv);
255
+ }
256
+ }
257
+ async function initialEngrave() {
258
+ if (opts.rendered) {
259
+ currentLayout = opts.rendered;
260
+ lastEngravedWidthPx = desiredEngraveWidthPx();
261
+ renderPlayhead(lastTMs);
262
+ return;
263
+ }
264
+ const toolkit = await getVerovioToolkit();
265
+ if (destroyed) return;
266
+ const widthPx = desiredEngraveWidthPx();
267
+ const { scale, pageWidth } = verovioZoomOptions(widthPx, currentZoom);
268
+ toolkit.setOptions({ scale, pageWidth, breaks: "auto", adjustPageHeight: true });
269
+ loaded = !!toolkit.loadData(musicXml);
270
+ if (destroyed) return;
271
+ lastEngravedWidthPx = widthPx;
272
+ if (loaded) renderAllPages(toolkit);
273
+ rebuildLayoutFromDom();
274
+ renderPlayhead(lastTMs);
275
+ }
276
+ const ready = initialEngrave();
277
+ async function reflow(newZoom) {
278
+ if (destroyed) return;
279
+ const widthPx = desiredEngraveWidthPx();
280
+ if (widthPx === lastEngravedWidthPx && newZoom === currentZoom) return;
281
+ if (opts.rendered || !loaded) {
282
+ currentZoom = newZoom;
283
+ return;
284
+ }
285
+ const toolkit = await getVerovioToolkit();
286
+ if (destroyed) return;
287
+ const myToken = ++rebuildToken;
288
+ const oldLayout = currentLayout;
289
+ const hasWin = typeof window !== "undefined";
290
+ let anchorY = null;
291
+ const anchorX = widthPx / 2;
292
+ if (hasWin && typeof root.getBoundingClientRect === "function") {
293
+ const r = root.getBoundingClientRect();
294
+ anchorY = window.innerHeight / 2 - r.top;
295
+ }
296
+ const { scale, pageWidth } = verovioZoomOptions(widthPx, newZoom);
297
+ toolkit.setOptions({ scale, pageWidth, breaks: "auto", adjustPageHeight: true });
298
+ const ok = toolkit.loadData(musicXml);
299
+ if (destroyed || myToken !== rebuildToken) return;
300
+ if (!ok) {
301
+ loaded = false;
302
+ return;
303
+ }
304
+ lastEngravedWidthPx = widthPx;
305
+ currentZoom = newZoom;
306
+ renderAllPages(toolkit);
307
+ rebuildLayoutFromDom();
308
+ if (oldLayout && currentLayout && anchorY != null && hasWin) {
309
+ const delta = computeReflowScrollDelta(oldLayout, currentLayout, anchorX, anchorY);
310
+ if (Number.isFinite(delta) && Math.abs(delta) > 0.5) {
311
+ window.scrollTo({ top: Math.max(0, window.scrollY + delta), left: window.scrollX, behavior: "auto" });
312
+ }
313
+ }
314
+ if (!destroyed) renderPlayhead(lastTMs);
315
+ }
316
+ const clickListeners = [];
317
+ function onRootClick(e) {
318
+ if (!currentLayout) return;
319
+ const rect = root.getBoundingClientRect();
320
+ const mx = e.clientX - rect.left;
321
+ const my = e.clientY - rect.top;
322
+ const idx = hitTestMeasureAt(currentLayout, mx, my);
323
+ if (idx != null) for (const cb of clickListeners) cb(idx);
324
+ }
325
+ root.addEventListener("click", onRootClick);
326
+ return {
327
+ ready,
328
+ setTime,
329
+ async setZoom(z) {
330
+ await ready;
331
+ await reflow(z);
332
+ },
333
+ async resize() {
334
+ await ready;
335
+ await reflow(currentZoom);
336
+ },
337
+ onMeasureClick(cb) {
338
+ clickListeners.push(cb);
339
+ return () => {
340
+ const i = clickListeners.indexOf(cb);
341
+ if (i >= 0) clickListeners.splice(i, 1);
342
+ };
343
+ },
344
+ destroy() {
345
+ if (destroyed) return;
346
+ destroyed = true;
347
+ rebuildToken++;
348
+ root.removeEventListener("click", onRootClick);
349
+ follow.destroy();
350
+ clickListeners.length = 0;
351
+ currentLayout = null;
352
+ currentNoteCols = void 0;
353
+ if (root.parentNode === host) host.removeChild(root);
354
+ }
355
+ };
356
+ }
357
+ export {
358
+ MAX_ENGRAVE_WIDTH_VRV,
359
+ VEROVIO_BASE_SCALE,
360
+ VEROVIO_MAX_SCALE,
361
+ VEROVIO_MIN_SCALE,
362
+ createVerovioNotationPlayer,
363
+ verovioNotationLayout,
364
+ verovioOnsetColumns,
365
+ verovioZoomOptions
366
+ };
367
+ //# sourceMappingURL=notationPlayerVerovio.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/notationPlayerVerovio.ts"],"sourcesContent":["// createVerovioNotationPlayer — the Verovio (vector) sibling of\n// createSvgNotationPlayer (notationPlayerSvg.ts). Same job (a live,\n// caller-driven notation + gliding-playhead widget) and the same swap-friendly\n// API shape, different rendering engine: Verovio's own MusicXML→SVG engraver\n// instead of OSMD. See\n// docs/superpowers/specs/2026-08-11-verovio-player-design.md (stave-web-sightread)\n// §2 for the full design rationale.\n//\n// THE BINDING REFRAME (design doc, top): \"Timing is ours; Verovio renders.\"\n// This module NEVER calls `renderToTimemap` or `getElementsAtTime` — Verovio's\n// timemap is proven wrong on tuplets (the root-cause finding that motivated\n// this whole migration). All timing (`onsets`) is supplied by the caller,\n// derived from `parseReduction`'s spans/offsets; this module's only job is\n// SVG + id→geometry, exactly like notationPlayerSvg.ts's job is OSMD SVG +\n// id→geometry. (Grep gate — see the build report.)\n//\n// REUSED, VERBATIM, NO NEW MATH (same hard rule as notationPlayerSvg.ts):\n// - `vstackAudioPlayheadLine` (scene/notationGeometry.ts) — the exact same\n// onset-anchored, carriage-return playhead interpolation both SVG-family\n// players use. It only ever reads a `NotationLayout`; it does not care\n// that THIS module's layout came from Verovio's rendered SVG DOM instead\n// of OSMD's `GraphicalMusicSheet` object model.\n// - `hitTestMeasureAt`, `measureColumnsFromLayout`, `distinctOnsets`\n// (scene/notationGeometry.ts) — reused as-is, identical to\n// notationPlayerSvg.ts's usage.\n// - `computeReflowScrollDelta` + the auto-follow discriminator\n// (`createFollowController`) — EXTRACTED (0.39.0) out of\n// notationPlayerSvg.ts into `./notationCommon`, so both SVG-family\n// players share one implementation. See that module's doc.\n//\n// WHAT'S NEW (not a re-derivation of any of the above):\n// - `verovioNotationLayout` — a Verovio-backend geometry extractor, this\n// module's counterpart to notationPlayerSvg.ts's `svgNotationLayout`.\n// Verovio exposes NO object model to JS (unlike OSMD's `GraphicSheet`) —\n// only rendered SVG + MEI/timemap (timemap being off-limits per the\n// binding reframe above) — so this reads the ACTUAL rendered SVG DOM:\n// `<g class=\"measure\">` / `<g class=\"staff\">` / `<g class=\"system\">` /\n// `<g class=\"note\">` are Verovio's own stable, documented SVG output\n// classes (confirmed against a real 6.2.0 render — see the migration\n// spike's `id-test*.mjs`). Measure `index` is assigned by DOCUMENT ORDER\n// (musical order) across however many pages were rendered — no reliance\n// on Verovio's own (internal, non-deterministic) generated ids.\n// - Stamped-id note lookups (`verovioOnsetColumns`): Task 1 (stave repo)\n// stamps a deterministic `xml:id` per note before handing MusicXML to\n// Verovio; Verovio PRESERVES caller-supplied ids as the rendered SVG\n// element's own `id` attribute (confirmed: `<note id=\"n-0-0-0\">` in the\n// source round-trips to `<g id=\"n-0-0-0\" class=\"note\">` in the output —\n// an EXACT lookup, no heuristics, unlike the ordinal-spread fallback\n// `vstackAudioPlayheadLine` uses when no `noteCols` are supplied at all).\n// - `verovioZoomOptions` — the semantic zoom→Verovio-options mapping. The\n// migration spike's `zoom-test*.mjs` proved `pageWidth` (Verovio's\n// line-breaking width, in ITS OWN units) drives measures-per-system\n// while `scale` (glyph size) alone does NOT (avgMeasuresPerSystem stayed\n// 3.61 across scale 40/80/150 at a fixed pageWidth; it moved from 2.24 to\n// 3.61 to 5.91 as pageWidth alone rose 1000→1600→2400). Verovio's\n// rendered SVG width in CSS px is EXACTLY `pageWidth * scale / 100`\n// (confirmed empirically) — so solving that identity for `pageWidth`\n// given a TARGET output width (the host's width, held fixed across zoom\n// levels) and a zoom-driven `scale` makes both halves of the semantic\n// (\"bigger zoom ⇒ bigger glyphs AND fewer measures/system, width still\n// fits host\") fall out of ONE formula, not two independently-tuned ones.\n// - The unit-conversion for any element's `getBBox()` (Verovio's rendered\n// SVG user-unit space) → CSS px: each rendered page is\n// `<svg width=\"Wpx\" height=\"Hpx\">` (no viewBox) wrapping a nested\n// `<svg class=\"definition-scale\" viewBox=\"0 0 VBW VBH\">` (Verovio's own\n// structure) — so `cssPx = userUnit * (W / VBW)`, the SAME \"read the\n// scale factor from the live render, never hardcode it\" principle\n// `svgNotationLayout`'s `unitInPixels` derivation uses, just sourced from\n// the DOM (Verovio exposes no JS-side unit constant) instead of an\n// imported library constant.\n//\n// PAGES: \"all rendered, stacked in flow\" (design doc §2) — every Verovio\n// page (`getPageCount()`) is rendered to its own `<svg>` and appended, in\n// order, inside its own `.vrv-page` wrapper `<div>`, inside `svgHost`. Normal\n// block layout stacks them vertically; `verovioNotationLayout` reads each\n// page's OWN offset (`getBoundingClientRect()` relative to the shared root)\n// so geometry from every page lands in ONE continuous coordinate space, the\n// same space the playhead overlay is positioned in. No \"current page\" /\n// pagination concept anywhere in this module — the whole score is always in\n// the DOM; the PAGE scrolls it (identical framing to notationPlayerSvg.ts).\n//\n// SHARED TOOLKIT INSTANCE: Verovio's own package doc: \"only one instance can\n// be created for now\" (`VerovioToolkit.instances`, a static array the C++\n// bridge expects to hold at most one live toolkit). This module therefore\n// keeps ONE module-level toolkit init promise for the whole session — every\n// player created on the page shares it. This is NOT a \"one live player at a\n// time\" assumption — the real consumer (PlayerPage) keeps a harmony player\n// AND a written player alive SIMULTANEOUSLY (lazy-built, destroyed only on\n// piece switch), so two players' `loadData` calls genuinely interleave over\n// the toolkit's lifetime. Safety comes from RECLAIM: every toolkit-consuming\n// path (initial engrave; `reflow`, shared by `setZoom`/`resize`) re-parses\n// ITS OWN `musicXml` via `loadData` synchronously, immediately before\n// rendering — never assumes the toolkit still holds what it loaded last\n// time. Because the reclaim call and the render calls that follow it have no\n// `await` between them, JS's single-threaded run-to-completion semantics\n// guarantee no other player's reflow can interleave mid-sequence — see\n// `reflow`'s own comment + `tests/notationPlayerVerovio.test.ts`'s\n// two-player interleaved-reflow test (the regression this guards against).\n//\n// IMPORT PATH: subpath-only —\n// `@real-music-packages/web-core/notationPlayerVerovio` — not re-exported\n// from the root barrel (same reasoning as notationPlayer.ts/\n// notationPlayerSvg.ts: the root barrel is theory-only/zero-dependency).\n// `verovio` itself is a dynamic `import('verovio/wasm')` /\n// `import('verovio/esm')` INSIDE this module only, marked `external` in\n// tsup.config.ts, so the ~2.3MB gzip WASM only loads on pages that actually\n// construct a player — see the build report's dist-grep evidence.\n\nimport {\n vstackAudioPlayheadLine,\n distinctOnsets,\n hitTestMeasureAt,\n measureColumnsFromLayout,\n type NotationLayout,\n} from './scene/notationGeometry';\nimport type { Box, StaffMeasureBox } from './promo';\nimport { computeReflowScrollDelta, createFollowController } from './notationCommon';\n\n// ─── Public types ───────────────────────────────────────────────────────────\n\n/** One distinct note-onset instant: the audio-clock time it sounds at, and\n * the stamped `xml:id`s (Task 1, stave repo) of every note that sounds at\n * that instant (>1 for a chord). Multiple entries sharing the same `tMs`\n * are merged (their `noteIds` unioned) — the caller does not need to\n * pre-group chords into one entry. */\nexport interface VerovioOnset {\n tMs: number;\n noteIds: string[];\n}\n\nexport interface CreateVerovioNotationPlayerOpts {\n /** Element the player's content is mounted into. Takes NATURAL content\n * height (the whole score, page-flow layout, ALL Verovio pages stacked)\n * — the host must not clip a fixed height; the PAGE scrolls the score. */\n host: HTMLElement;\n /** Display MusicXML to engrave (Task 1's transform-pipeline output — ids\n * already stamped). Ignored when `rendered` (the test seam) is set. */\n musicXml: string;\n /** Note onsets the playhead locks to, WITH the stamped ids of the notes\n * sounding at each onset — see `VerovioOnset`. Distinct/sorted\n * automatically (duplicates by `tMs` are merged, not required to be\n * pre-sorted). */\n onsets: VerovioOnset[];\n /** Playhead line color. Default `'#2f6f4f'`. */\n playheadColor?: string;\n /** Initial semantic zoom — see `verovioZoomOptions`'s doc for the mapping.\n * Default 1 (a normal readable size that fits the host's width). */\n zoom?: number;\n /**\n * Advanced / test seam: a pre-built `NotationLayout`, bypassing the real\n * Verovio engrave (`musicXml` is still required by the type but is\n * ignored when this is set). Mirrors `CreateSvgNotationPlayerOpts.rendered`\n * in notationPlayerSvg.ts for the identical reason: real Verovio rendering\n * needs a real SVG DOM (`getBBox`/`getBoundingClientRect`) that jsdom can't\n * provide — see notationPlayerSvg.ts's module doc for why headless can't do\n * a real one. When set, `noteIds`-based note lookups have no live DOM to\n * resolve against, so the playhead falls back to `vstackAudioPlayheadLine`'s\n * own ordinal spread (same graceful-degradation path as \"no `noteCols`\n * supplied\" on the SVG player) — fine for a lifecycle test, not for\n * notehead-accurate positioning. `setZoom`/`resize` update the tracked zoom\n * /width but perform no real re-engrave (there is nothing to re-engrave).\n */\n rendered?: NotationLayout;\n}\n\nexport interface VerovioNotationPlayer {\n /** Resolves once the engraving is in the DOM and ready to draw. `setTime`/\n * click hit-testing are safe to call before this resolves (no-op until\n * ready, same contract as the SVG player). */\n readonly ready: Promise<void>;\n /** Drive the playhead for absolute playback time `tMs`. Caller owns the\n * audio clock + rAF loop. */\n setTime(tMs: number): void;\n /** Re-engrave at a new semantic zoom (systems reflow — see\n * `verovioZoomOptions`). The scroll position is restored afterward so the\n * content that was centered in the viewport before the reflow is still\n * centered after it. */\n setZoom(z: number): Promise<void>;\n /** Re-measure the host and reflow to match its current width, with the\n * same scroll-position preservation as `setZoom`. Call on host resize /\n * orientation change. */\n resize(): Promise<void>;\n /** Register a measure-click handler (measure index, matching the DOM-order\n * index `verovioNotationLayout` assigns). Returns an unsubscribe fn. */\n onMeasureClick(cb: (measureIndex: number) => void): () => void;\n /** Tear down: removes the mounted DOM (engraving + playhead overlay) from\n * `host`, and drops every listener this instance added (click, window\n * scroll) and pending async work (a token guard drops any in-flight\n * reflow's effects). Idempotent. Does NOT destroy the shared module-level\n * Verovio toolkit instance (see the module doc's \"SHARED TOOLKIT\n * INSTANCE\" note) — it is reused by the next player, if any. */\n destroy(): void;\n}\n\n// ─── Verovio-backend geometry extraction (DOM-based) ───────────────────────\n\nconst EMPTY_LAYOUT: NotationLayout = {\n src: { x: 0, y: 0, w: 0, h: 0 },\n rect: { dx: 0, dy: 0, dw: 0, dh: 0 },\n systems: [],\n measures: [],\n};\n\n/** Per-page unit-conversion + placement: `cssPx = userUnit * scale`, plus\n * this page's own `(offsetX, offsetY)` within the shared root's coordinate\n * space (see the module doc's \"unit-conversion\" + \"PAGES\" sections). */\ninterface PageGeom {\n scale: number;\n offsetX: number;\n offsetY: number;\n}\n\nfunction safeRect(el: Element): DOMRect | null {\n return typeof el.getBoundingClientRect === 'function' ? el.getBoundingClientRect() : null;\n}\n\nfunction readViewBox(svgEl: SVGSVGElement): { w: number; h: number } | null {\n const baseVal = svgEl.viewBox && svgEl.viewBox.baseVal;\n if (baseVal && baseVal.width > 0) return { w: baseVal.width, h: baseVal.height };\n const attr = svgEl.getAttribute('viewBox');\n if (!attr) return null;\n const parts = attr.trim().split(/[\\s,]+/).map(Number);\n if (parts.length !== 4 || !(parts[2] > 0)) return null;\n return { w: parts[2], h: parts[3] };\n}\n\n/** One page's unit-conversion factor + placement offset, derived ENTIRELY\n * from the live DOM (Verovio's rendered SVG is self-describing — outer\n * `<svg width>` + inner `<svg viewBox>` — no external constant needed; see\n * the module doc). Returns null (never throws) if the page's markup is\n * missing the expected structure. */\nfunction pageGeometry(root: Element, pageEl: Element): PageGeom | null {\n const outerSvg = pageEl.querySelector('svg');\n if (!outerSvg) return null;\n const innerSvg = (outerSvg.querySelector('svg[viewBox]') ?? outerSvg) as unknown as SVGSVGElement;\n const vb = readViewBox(innerSvg);\n if (!vb) return null;\n const outerRect = safeRect(outerSvg);\n const rootRect = safeRect(root);\n const pageRect = safeRect(pageEl);\n if (!outerRect || !rootRect || !pageRect) return null;\n if (!(outerRect.width > 0)) return null;\n const scale = outerRect.width / vb.w;\n if (!(scale > 0) || !Number.isFinite(scale)) return null;\n return { scale, offsetX: pageRect.left - rootRect.left, offsetY: pageRect.top - rootRect.top };\n}\n\n/** `el.getBBox()` (Verovio's rendered user-unit space) converted to this\n * page's CSS px space (`scale` + `offsetX`/`offsetY`). Null for anything\n * that isn't a real `SVGGraphicsElement` or has a degenerate (zero-area)\n * box — same defensive style as `svgNotationLayout`'s box filtering. */\nfunction boxFromElement(el: Element, geom: PageGeom): Box | null {\n const ge = el as unknown as SVGGraphicsElement;\n if (typeof ge.getBBox !== 'function') return null;\n let bbox: DOMRect;\n try {\n bbox = ge.getBBox();\n } catch {\n return null;\n }\n if (!bbox || !(bbox.width > 0) || !(bbox.height > 0)) return null;\n return {\n x: geom.offsetX + bbox.x * geom.scale,\n y: geom.offsetY + bbox.y * geom.scale,\n w: bbox.width * geom.scale,\n h: bbox.height * geom.scale,\n };\n}\n\nfunction computePageGeometries(root: Element): Map<Element, PageGeom> {\n const map = new Map<Element, PageGeom>();\n for (const pageEl of Array.from(root.querySelectorAll('.vrv-page'))) {\n const geom = pageGeometry(root, pageEl);\n if (geom) map.set(pageEl, geom);\n }\n return map;\n}\n\n/**\n * Every `<g class=\"measure\">` across all rendered pages that has at least\n * one `<g class=\"staff\">` child, in DOCUMENT ORDER (= musical order, since\n * pages are stacked in `.vrv-page` DOM order and Verovio renders each page's\n * measures left-to-right/top-to-bottom). This exact list's POSITION is the\n * single source of truth for the `index` every measure/note lookup in this\n * module uses (`verovioNotationLayout` AND `verovioOnsetColumns` both call\n * this, so they can never drift out of sync with each other — no separate\n * re-derivation of \"which position is this measure\" anywhere else).\n */\nfunction collectMeasureElements(pageGeoms: Map<Element, PageGeom>): { el: Element; geom: PageGeom }[] {\n const out: { el: Element; geom: PageGeom }[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const measureEl of Array.from(pageEl.querySelectorAll('g.measure'))) {\n if (measureEl.querySelector('g.staff')) out.push({ el: measureEl, geom });\n }\n }\n return out;\n}\n\n/**\n * Pure(ish) — DOM-in, `NotationLayout`-out — Verovio-backend geometry\n * extractor. `root` is the container holding every rendered `.vrv-page`\n * wrapper `<div>` (this player's `svgHost`; a test fixture must reproduce\n * that same wrapper structure — see the extractor tests). Builds the SAME\n * `NotationLayout` shape `svgNotationLayout` (notationPlayerSvg.ts) does,\n * from Verovio's rendered SVG DOM instead of OSMD's object model — see the\n * module doc for the full derivation (measure/staff/system/note lookup via\n * Verovio's own stable SVG classes, unit conversion via the live\n * width/viewBox on each page). Never throws; returns `EMPTY_LAYOUT` on any\n * missing/malformed structure.\n */\nexport function verovioNotationLayout(root: Element): NotationLayout {\n try {\n const pageGeoms = computePageGeometries(root);\n if (!pageGeoms.size) return EMPTY_LAYOUT;\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return EMPTY_LAYOUT;\n\n const measures: StaffMeasureBox[] = [];\n measureEntries.forEach(({ el: measureEl, geom }, index) => {\n const staffEls = Array.from(measureEl.querySelectorAll('g.staff'));\n const staffBoxes = staffEls\n .map((el) => ({ el, box: boxFromElement(el, geom) }))\n .filter((s): s is { el: Element; box: Box } => !!s.box)\n .sort((a, b) => a.box.y - b.box.y);\n staffBoxes.forEach(({ el: staffEl, box }, staff) => {\n const noteEls = Array.from(measureEl.querySelectorAll('g.note')).filter(\n (n) => n.closest('g.staff') === staffEl,\n );\n const noteXs = noteEls.map((n) => boxFromElement(n, geom)?.x).filter((x): x is number => x != null);\n const noteStartX = noteXs.length ? Math.min(...noteXs) : box.x;\n measures.push({ index, staff, box, noteStartX });\n });\n });\n if (!measures.length) return EMPTY_LAYOUT;\n\n const systems: Box[] = [];\n for (const [pageEl, geom] of pageGeoms) {\n for (const sysEl of Array.from(pageEl.querySelectorAll('g.system'))) {\n const box = boxFromElement(sysEl, geom);\n if (box) systems.push(box);\n }\n }\n\n const rootRect = safeRect(root);\n const fallbackW = Math.max(0, ...measures.map((m) => m.box.x + m.box.w));\n const fallbackH = Math.max(0, ...measures.map((m) => m.box.y + m.box.h));\n const dw = rootRect && rootRect.width > 0 ? rootRect.width : fallbackW;\n const dh = rootRect && rootRect.height > 0 ? rootRect.height : fallbackH;\n\n return { src: { x: 0, y: 0, w: dw, h: dh }, rect: { dx: 0, dy: 0, dw, dh }, systems, measures };\n } catch {\n return EMPTY_LAYOUT;\n }\n}\n\n/**\n * Resolve each DISTINCT onset (see `distinctOnsets`) to a `noteCols` entry —\n * the SAME \"real engraved column\" format `vstackAudioPlayheadLine` already\n * accepts from the SVG/canvas players (`measureIndex + fractionWithinMeasure`\n * — see that function's doc for how it's consumed). For each onset, every\n * stamped `noteId` sounding at that instant (a chord may have several) is\n * looked up by id in the live DOM (`document.getElementById` — Task 1 stamps\n * ids that Verovio preserves verbatim as SVG element ids), mapped to its\n * measure via `collectMeasureElements`'s canonical indexing (so it lines up\n * EXACTLY with `verovioNotationLayout`'s own `index` numbering), and its\n * fractional x-position within that measure's column computed with the exact\n * same formula `vstackAudioPlayheadLine`'s own `colX` uses internally (not\n * re-derived independently — this is the note's ANCHOR position, not new\n * interpolation math). A chord's several ids are averaged. Any onset with NO\n * resolvable id (missing from the DOM, e.g. a `rendered`-seam layout with no\n * live SVG) falls back to the ordinal spread `vstackAudioPlayheadLine` itself\n * uses when `noteCols` is entirely absent — so one bad id degrades ONLY that\n * onset, not the whole piece. Returns `undefined` (not a partially-bad array)\n * only when there is no usable layout/DOM at all to resolve against.\n */\nexport function verovioOnsetColumns(\n root: Element,\n layout: NotationLayout,\n onsets: VerovioOnset[],\n): number[] | undefined {\n try {\n const distinctMs = distinctOnsets(onsets.map((o) => ({ onsetMs: o.tMs })));\n if (!distinctMs.length) return undefined;\n const cols = measureColumnsFromLayout(layout.measures);\n if (!cols.length) return undefined;\n\n const pageGeoms = computePageGeometries(root);\n const measureEntries = collectMeasureElements(pageGeoms);\n if (!measureEntries.length) return undefined;\n const measureIndexOf = new Map<Element, number>();\n measureEntries.forEach((m, i) => measureIndexOf.set(m.el, i));\n\n const idsByOnset = new Map<number, string[]>();\n for (const o of onsets) {\n const arr = idsByOnset.get(o.tMs) ?? [];\n for (const id of o.noteIds) if (!arr.includes(id)) arr.push(id);\n idsByOnset.set(o.tMs, arr);\n }\n\n const doc = root.ownerDocument;\n\n return distinctMs.map((tMs, k) => {\n const ids = idsByOnset.get(tMs) ?? [];\n const positions: number[] = [];\n for (const id of ids) {\n const noteEl = doc ? doc.getElementById(id) : null;\n const measureEl = noteEl ? noteEl.closest('g.measure') : null;\n const index = measureEl ? measureIndexOf.get(measureEl) : undefined;\n if (index == null) continue;\n const m = cols[index];\n const geom = measureEntries[index]?.geom;\n const box = noteEl && geom ? boxFromElement(noteEl, geom) : null;\n if (!box || !m) continue;\n const sx = Math.min(m.noteStartX, m.x + m.w);\n const denom = m.x + m.w - sx;\n const frac = denom > 0 ? Math.min(1, Math.max(0, (box.x - sx) / denom)) : 0;\n positions.push(index + frac);\n }\n if (positions.length) return positions.reduce((a, b) => a + b, 0) / positions.length;\n // Same ordinal-spread fallback vstackAudioPlayheadLine uses internally\n // when no noteCols are supplied at all — degrades this ONE onset only.\n return distinctMs.length === 1 ? 0 : (k / (distinctMs.length - 1)) * cols.length;\n });\n } catch {\n return undefined;\n }\n}\n\n// ─── Semantic zoom mapping ──────────────────────────────────────────────────\n\n/** Verovio glyph-size percent at semantic zoom 1 (matches the migration\n * spike's own default — a normal, readable size at typical host widths). */\nexport const VEROVIO_BASE_SCALE = 40;\n/** Clamp band for the derived `scale`, so an extreme `zoom` never collapses\n * glyphs to unreadable or blows them up past sane bounds. */\nexport const VEROVIO_MIN_SCALE = 20;\nexport const VEROVIO_MAX_SCALE = 120;\n\nexport interface VerovioRenderOptions {\n scale: number;\n pageWidth: number;\n}\n\n/**\n * Semantic zoom → Verovio options. The migration spike's `zoom-test*.mjs`\n * proved `pageWidth` (Verovio's line-breaking width, in ITS OWN units)\n * drives measures-per-system while `scale` (glyph size) alone does NOT\n * (avgMeasuresPerSystem was IDENTICAL — 3.61 — across scale 40/80/150 at a\n * fixed pageWidth 1600; it moved 2.24→3.61→5.91 as pageWidth alone rose\n * 1000→1600→2400 at a fixed scale). Verovio's own rendered SVG width in CSS\n * px is EXACTLY `pageWidth * scale / 100` (confirmed empirically against\n * real 6.2.0 renders) — an identity, not an approximation.\n *\n * This function picks `scale` proportional to `zoom` (bigger zoom ⇒ bigger\n * glyphs) and then SOLVES that identity for the `pageWidth` that makes the\n * rendered width land EXACTLY on `hostWidthPx` regardless of zoom\n * (`pageWidth = hostWidthPx * 100 / scale`). Composing it this way — instead\n * of tuning `scale` and `pageWidth` independently — makes BOTH halves of the\n * spec's semantic fall out of the ONE formula: as `zoom` rises, `scale`\n * rises (glyphs bigger) AND the required `pageWidth` (in Verovio units)\n * SHRINKS proportionally (since it's inversely proportional to `scale` at a\n * fixed target width) — and per the spike's own finding, a smaller\n * `pageWidth` fits FEWER measures per system. So \"bigger zoom ⇒ fewer\n * measures/system, glyphs larger, width still fits host\" (design doc §2) is\n * a direct consequence of this one identity, pinned by\n * `tests/notationPlayerVerovio.test.ts`'s real-Verovio monotonicity test.\n *\n * No floor on `pageWidth` beyond what the identity itself produces: `scale`\n * is already clamped to `[VEROVIO_MIN_SCALE, VEROVIO_MAX_SCALE]` (both > 0)\n * and `hostWidthPx` is floored to a sane fallback when invalid, so\n * `pageWidth = w * 100 / scale` is ALWAYS finite and positive — an\n * additional floor would only ever fire by breaking the width-fits-host\n * identity (clamping the OUTPUT width away from the host's actual width),\n * which is worse than a small `pageWidth`.\n */\nexport function verovioZoomOptions(hostWidthPx: number, zoom: number): VerovioRenderOptions {\n const z = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;\n const scale = Math.max(VEROVIO_MIN_SCALE, Math.min(VEROVIO_MAX_SCALE, VEROVIO_BASE_SCALE * z));\n const w = Number.isFinite(hostWidthPx) && hostWidthPx > 0 ? hostWidthPx : MAX_ENGRAVE_WIDTH_VRV;\n const pageWidth = (w * 100) / scale;\n return { scale, pageWidth };\n}\n\n// ─── Shared module-level toolkit (see the module doc's \"SHARED TOOLKIT\n// INSTANCE\" section) ─────────────────────────────────────────────────\n\n/** The subset of `VerovioToolkit`'s instance API this module calls — see\n * `src/types/verovio.d.ts` for the ambient module declaration backing the\n * dynamic imports below (the `verovio` npm package ships no types of its\n * own). Deliberately duck-typed/local rather than importing the real class\n * type statically, so nothing about this module's own type-checking\n * depends on a STATIC import of `verovio/esm` (only the dynamic one inside\n * `getVerovioToolkit` touches the package at all, which is what tsup's\n * `external` + the build-audit grep gate verify). */\ninterface VerovioToolkitInstance {\n loadData(data: string): boolean;\n getPageCount(): number;\n renderToSVG(page: number): string;\n setOptions(options: Record<string, unknown>): void;\n redoLayout(options?: Record<string, unknown>): void;\n}\n\nlet toolkitPromise: Promise<VerovioToolkitInstance> | null = null;\n\nfunction getVerovioToolkit(): Promise<VerovioToolkitInstance> {\n if (!toolkitPromise) {\n toolkitPromise = (async () => {\n // Literal dynamic imports — consumers' bundlers must statically see\n // these specifiers to code-split Verovio out of every OTHER dist\n // entry (tsup marks `verovio` external — see tsup.config.ts + the\n // build report's dist-grep evidence). A caller that only ever uses\n // the `rendered` test seam never pulls Verovio in at all.\n const [{ default: createVerovioModule }, { VerovioToolkit }] = await Promise.all([\n import('verovio/wasm'),\n import('verovio/esm'),\n ]);\n const VerovioModule = await createVerovioModule();\n return new VerovioToolkit(VerovioModule) as unknown as VerovioToolkitInstance;\n })();\n }\n return toolkitPromise;\n}\n\n// ─── createVerovioNotationPlayer ────────────────────────────────────────────\n\nconst DEFAULT_PLAYHEAD_COLOR = '#2f6f4f';\n/** Engrave-width ceiling, CSS px — same policy as notationPlayerSvg.ts's\n * `MAX_ENGRAVE_WIDTH_SVG` (design doc §\"Render\": \"cap ~1200px\"), restated\n * independently since the two players' constants are independently\n * tunable. */\nexport const MAX_ENGRAVE_WIDTH_VRV = 1200;\n/** Floor so a not-yet-laid-out / zero-width host never engraves at 0px. */\nconst MIN_ENGRAVE_WIDTH_VRV = 280;\n\n/** Build a live, interactive Verovio (vector) notation player. See the\n * module doc + `docs/superpowers/specs/2026-08-11-verovio-player-design.md`\n * (in stave-web-sightread) §2 for the full design. */\nexport function createVerovioNotationPlayer(opts: CreateVerovioNotationPlayerOpts): VerovioNotationPlayer {\n const { host, musicXml, onsets: rawOnsets } = opts;\n const playheadColor = opts.playheadColor ?? DEFAULT_PLAYHEAD_COLOR;\n const onsets = distinctOnsets(rawOnsets.map((o) => ({ onsetMs: o.tMs })));\n\n const root = document.createElement('div');\n root.style.position = 'relative';\n root.style.width = '100%';\n // Same \"optical zoom is free\" reasoning as notationPlayerSvg.ts — let\n // native pinch-zoom + vertical page-scroll gestures through unimpeded.\n root.style.touchAction = 'pan-y pinch-zoom';\n host.appendChild(root);\n\n const svgHost = document.createElement('div');\n root.appendChild(svgHost);\n\n const playheadEl = document.createElement('div');\n playheadEl.style.position = 'absolute';\n playheadEl.style.left = '0px';\n playheadEl.style.top = '0px';\n playheadEl.style.width = '2px';\n playheadEl.style.height = '0px';\n playheadEl.style.background = playheadColor;\n playheadEl.style.opacity = '0';\n playheadEl.style.pointerEvents = 'none';\n root.appendChild(playheadEl);\n\n let currentLayout: NotationLayout | null = null;\n let currentNoteCols: number[] | undefined;\n let currentZoom = opts.zoom ?? 1;\n let lastEngravedWidthPx = 0;\n let loaded = false; // toolkit.loadData succeeded (rendered-seam path never sets this)\n let destroyed = false;\n let lastTMs = 0;\n // Stale-reflow guard — same \"each async re-engrave captures its own\n // token\" rule as notationPlayerSvg.ts's `rebuildToken`.\n let rebuildToken = 0;\n\n function desiredEngraveWidthPx(): number {\n const w = host.clientWidth || 0;\n return Math.max(MIN_ENGRAVE_WIDTH_VRV, Math.min(w || MAX_ENGRAVE_WIDTH_VRV, MAX_ENGRAVE_WIDTH_VRV));\n }\n\n // ─── Playhead + auto-follow (createFollowController — notationCommon.ts) ─\n\n const follow = createFollowController();\n\n function renderPlayhead(tMs: number): void {\n lastTMs = tMs;\n if (!currentLayout) return;\n const nBars = currentLayout.measures.length\n ? Math.max(...currentLayout.measures.map((m) => m.index)) + 1\n : 0;\n const line = vstackAudioPlayheadLine(currentLayout, onsets, tMs, nBars, currentNoteCols);\n if (!line) {\n playheadEl.style.opacity = '0';\n return;\n }\n playheadEl.style.opacity = String(line.alpha);\n playheadEl.style.left = `${line.x}px`;\n playheadEl.style.top = `${line.y0}px`;\n playheadEl.style.height = `${Math.max(0, line.y1 - line.y0)}px`;\n follow.follow(() =>\n typeof playheadEl.getBoundingClientRect === 'function' ? playheadEl.getBoundingClientRect() : null,\n );\n }\n\n function setTime(tMs: number): void {\n if (destroyed) return;\n follow.onSetTime(tMs);\n renderPlayhead(tMs);\n }\n\n // ─── Engrave / reflow ──────────────────────────────────────────────────\n\n function rebuildLayoutFromDom(): void {\n currentLayout = verovioNotationLayout(svgHost);\n currentNoteCols = verovioOnsetColumns(svgHost, currentLayout, rawOnsets);\n }\n\n function renderAllPages(toolkit: VerovioToolkitInstance): void {\n svgHost.replaceChildren();\n const pageCount = Math.max(0, toolkit.getPageCount());\n for (let p = 1; p <= pageCount; p++) {\n const pageDiv = document.createElement('div');\n pageDiv.className = 'vrv-page';\n pageDiv.innerHTML = toolkit.renderToSVG(p);\n svgHost.appendChild(pageDiv);\n }\n }\n\n async function initialEngrave(): Promise<void> {\n if (opts.rendered) {\n currentLayout = opts.rendered;\n lastEngravedWidthPx = desiredEngraveWidthPx();\n renderPlayhead(lastTMs);\n return;\n }\n\n const toolkit = await getVerovioToolkit();\n if (destroyed) return;\n\n const widthPx = desiredEngraveWidthPx();\n const { scale, pageWidth } = verovioZoomOptions(widthPx, currentZoom);\n toolkit.setOptions({ scale, pageWidth, breaks: 'auto', adjustPageHeight: true });\n loaded = !!toolkit.loadData(musicXml);\n if (destroyed) return;\n\n lastEngravedWidthPx = widthPx;\n if (loaded) renderAllPages(toolkit);\n rebuildLayoutFromDom();\n renderPlayhead(lastTMs);\n }\n\n const ready = initialEngrave();\n\n /** Re-engrave at `newZoom` and the host's CURRENT width, preserving the\n * scroll position of whatever content is centered in the viewport right\n * now. Shared by both `setZoom` and `resize` — same shape as\n * notationPlayerSvg.ts's `reflow`. No-op when neither the width nor the\n * zoom actually changed, or when using the `rendered` test seam / the\n * initial load never succeeded (nothing to re-engrave). */\n async function reflow(newZoom: number): Promise<void> {\n if (destroyed) return;\n const widthPx = desiredEngraveWidthPx();\n if (widthPx === lastEngravedWidthPx && newZoom === currentZoom) return;\n if (opts.rendered || !loaded) {\n currentZoom = newZoom;\n return;\n }\n\n const toolkit = await getVerovioToolkit();\n if (destroyed) return;\n\n const myToken = ++rebuildToken;\n const oldLayout = currentLayout;\n const hasWin = typeof window !== 'undefined';\n let anchorY: number | null = null;\n const anchorX = widthPx / 2;\n if (hasWin && typeof root.getBoundingClientRect === 'function') {\n const r = root.getBoundingClientRect();\n anchorY = window.innerHeight / 2 - r.top;\n }\n\n const { scale, pageWidth } = verovioZoomOptions(widthPx, newZoom);\n toolkit.setOptions({ scale, pageWidth, breaks: 'auto', adjustPageHeight: true });\n // RECLAIM (see the module doc's \"SHARED TOOLKIT INSTANCE\" note): the\n // module-level toolkit is shared across every live player on the page —\n // and the real consumer (PlayerPage) keeps a harmony player AND a\n // written player alive SIMULTANEOUSLY (lazy-built, destroyed only on\n // piece switch), so `loadData` calls from the two players genuinely\n // interleave (e.g. harmony active -> resize while written hidden -> back\n // to written -> writtenPlayer.setZoom()). A plain `redoLayout()` here\n // would silently re-lay-out and render WHATEVER document the toolkit\n // currently holds — which may belong to the OTHER player if it rendered\n // more recently. So every reflow re-parses THIS player's own `musicXml`\n // synchronously, immediately before rendering (loadData does a full\n // parse + layout with the just-set options, making a separate\n // `redoLayout()` call redundant). Because this call and `renderAllPages`\n // below are both synchronous with NO `await` between them, and the only\n // preceding `await` (`getVerovioToolkit()`) already resolved, JS's\n // single-threaded run-to-completion semantics guarantee no other\n // player's reflow/initialEngrave can interleave between the reclaim and\n // the render — the shared singleton is therefore safe under alternating\n // use. See `tests/notationPlayerVerovio.test.ts`'s two-player\n // interleaved-reflow test for the regression this guards against.\n const ok = toolkit.loadData(musicXml);\n if (destroyed || myToken !== rebuildToken) return;\n if (!ok) {\n loaded = false;\n return;\n }\n\n lastEngravedWidthPx = widthPx;\n currentZoom = newZoom;\n renderAllPages(toolkit);\n rebuildLayoutFromDom();\n\n if (oldLayout && currentLayout && anchorY != null && hasWin) {\n const delta = computeReflowScrollDelta(oldLayout, currentLayout, anchorX, anchorY);\n if (Number.isFinite(delta) && Math.abs(delta) > 0.5) {\n window.scrollTo({ top: Math.max(0, window.scrollY + delta), left: window.scrollX, behavior: 'auto' });\n }\n }\n if (!destroyed) renderPlayhead(lastTMs);\n }\n\n // ─── Click-to-seek ─────────────────────────────────────────────────────\n\n const clickListeners: Array<(measureIndex: number) => void> = [];\n function onRootClick(e: MouseEvent): void {\n if (!currentLayout) return;\n const rect = root.getBoundingClientRect();\n const mx = e.clientX - rect.left;\n const my = e.clientY - rect.top;\n const idx = hitTestMeasureAt(currentLayout, mx, my);\n if (idx != null) for (const cb of clickListeners) cb(idx);\n }\n root.addEventListener('click', onRootClick);\n\n return {\n ready,\n setTime,\n async setZoom(z: number): Promise<void> {\n await ready;\n await reflow(z);\n },\n async resize(): Promise<void> {\n await ready;\n await reflow(currentZoom);\n },\n onMeasureClick(cb: (measureIndex: number) => void): () => void {\n clickListeners.push(cb);\n return () => {\n const i = clickListeners.indexOf(cb);\n if (i >= 0) clickListeners.splice(i, 1);\n };\n },\n destroy(): void {\n if (destroyed) return;\n destroyed = true;\n rebuildToken++;\n root.removeEventListener('click', onRootClick);\n follow.destroy();\n clickListeners.length = 0;\n currentLayout = null;\n currentNoteCols = undefined;\n if (root.parentNode === host) host.removeChild(root);\n },\n };\n}\n"],"mappings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;AACZ;AACA,WAAK,oBAAoB,SAAS,WAAW;AAC7C,aAAO,QAAQ;AACf,qBAAe,SAAS;AACxB,sBAAgB;AAChB,wBAAkB;AAClB,UAAI,KAAK,eAAe,KAAM,MAAK,YAAY,IAAI;AAAA,IACrD;AAAA,EACF;AACF;","names":[]}
@@ -2,8 +2,8 @@ import { A as AudioClock, S as Score, a as LayerFactory, R as RenderCtx, b as Sc
2
2
  export { L as Layer, d as SpectrumInput, e as SpectrumProps, W as WaveformInput, f as WaveformProps, s as scoreFromMusicXML, g as spectrumFactory, w as waveformFactory } from '../waveform-DdSMAbYQ.js';
3
3
  import { PromoTheme, RecordOpts, Scene, SafeBox } from '../video.js';
4
4
  import { RenderedNotation, Box } from '../promo.js';
5
- import { N as NotationLayout } from '../notationGeometry-CyYXJrUH.js';
6
- export { F as FOLLOW_BARS, a as FOLLOW_PAD, b as NotationLayoutOpts, c as NotationRect, P as PlayheadLine, d as audioPlayheadLine, e as cropAroundBox, f as cubicEaseInOut, g as distinctMeasureIndices, h as distinctOnsets, i as firstMeasureBox, j as followBoxAt, k as followWindowStart, l as lerpBox, m as measureColumnsFromLayout, n as measureCount, o as measureSpanBox, p as measureSystemMap, q as notationLayout, r as playheadLine, s as systemBox, v as vstackAudioPlayheadLine, t as vstackFollowBox } from '../notationGeometry-CyYXJrUH.js';
5
+ import { N as NotationLayout } from '../notationGeometry-54fFq5yU.js';
6
+ export { F as FOLLOW_BARS, a as FOLLOW_PAD, b as NotationLayoutOpts, c as NotationRect, P as PlayheadLine, d as audioPlayheadLine, e as cropAroundBox, f as cubicEaseInOut, g as distinctMeasureIndices, h as distinctOnsets, i as firstMeasureBox, j as followBoxAt, k as followWindowStart, m as lerpBox, n as measureColumnsFromLayout, o as measureCount, p as measureSpanBox, q as measureSystemMap, r as notationLayout, s as playheadLine, t as systemBox, v as vstackAudioPlayheadLine, u as vstackFollowBox } from '../notationGeometry-54fFq5yU.js';
7
7
 
8
8
  /** One scheduled audio event, in seconds RELATIVE to the schedule start. */
9
9
  interface AudioEvent {
@@ -9,6 +9,13 @@ import {
9
9
  noteNameToIndex,
10
10
  pitchClass
11
11
  } from "../chunk-GORQ5YMR.js";
12
+ import {
13
+ getNotationEngraving,
14
+ notationFactory,
15
+ scrollCursorFactory,
16
+ setFollowLayoutProvider,
17
+ setNotationEngraving
18
+ } from "../chunk-QGKDKXX2.js";
12
19
  import {
13
20
  FOLLOW_BARS,
14
21
  FOLLOW_PAD,
@@ -20,22 +27,17 @@ import {
20
27
  firstMeasureBox,
21
28
  followBoxAt,
22
29
  followWindowStart,
23
- getNotationEngraving,
24
30
  lerpBox,
25
31
  measureColumnsFromLayout,
26
32
  measureCount,
27
33
  measureSpanBox,
28
34
  measureSystemMap,
29
- notationFactory,
30
35
  notationLayout,
31
36
  playheadLine,
32
- scrollCursorFactory,
33
- setFollowLayoutProvider,
34
- setNotationEngraving,
35
37
  systemBox,
36
38
  vstackAudioPlayheadLine,
37
39
  vstackFollowBox
38
- } from "../chunk-4565POLG.js";
40
+ } from "../chunk-BHRDISMU.js";
39
41
  import {
40
42
  ctaScene,
41
43
  drawSafeGuides,