@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,241 @@
1
+ import {
2
+ PROGRAMMATIC_SCROLL_EPSILON_PX,
3
+ computeReflowScrollDelta,
4
+ createFollowController,
5
+ hasReachedProgrammaticTarget,
6
+ isWithinProgrammaticScroll
7
+ } from "./chunk-HZFDLJLA.js";
8
+ import {
9
+ distinctOnsets,
10
+ hitTestMeasureAt,
11
+ vstackAudioPlayheadLine
12
+ } from "./chunk-BHRDISMU.js";
13
+ import "./chunk-HXTRNE74.js";
14
+
15
+ // src/notationPlayerSvg.ts
16
+ var EMPTY_LAYOUT = {
17
+ src: { x: 0, y: 0, w: 0, h: 0 },
18
+ rect: { dx: 0, dy: 0, dw: 0, dh: 0 },
19
+ systems: [],
20
+ measures: []
21
+ };
22
+ function svgNotationLayout(osmd, opts) {
23
+ try {
24
+ const zoom = typeof osmd?.Zoom === "number" && osmd.Zoom > 0 ? osmd.Zoom : typeof osmd?.zoom === "number" && osmd.zoom > 0 ? osmd.zoom : 1;
25
+ const f = opts.unitInPixels * zoom;
26
+ const graphic = osmd?.GraphicSheet;
27
+ const page = graphic?.MusicPages?.[0];
28
+ const pageSize = page?.PositionAndShape?.Size;
29
+ const musicSystems = page?.MusicSystems ?? [];
30
+ if (!(pageSize?.width > 0) || !(pageSize?.height > 0) || !musicSystems.length) return EMPTY_LAYOUT;
31
+ const toBox = (pas) => {
32
+ const p = pas?.AbsolutePosition;
33
+ const sz = pas?.Size;
34
+ if (!p || !sz) return null;
35
+ return { x: p.x * f, y: p.y * f, w: sz.width * f, h: sz.height * f };
36
+ };
37
+ const systems = musicSystems.map((s) => toBox(s?.PositionAndShape)).filter((b) => !!b && b.w > 1 && b.h > 1).sort((a, b) => a.y - b.y);
38
+ if (!systems.length) return EMPTY_LAYOUT;
39
+ const measureList = graphic?.MeasureList ?? [];
40
+ const measures = [];
41
+ measureList.forEach((staves, index) => {
42
+ (staves ?? []).forEach((m, staff) => {
43
+ const box = toBox(m?.PositionAndShape);
44
+ if (box && box.w > 1 && box.h > 1) {
45
+ const seX = (m?.staffEntries ?? [])[0]?.PositionAndShape?.AbsolutePosition?.x;
46
+ const noteStartX = typeof seX === "number" ? seX * f : box.x;
47
+ measures.push({ index, staff, box, noteStartX });
48
+ }
49
+ });
50
+ });
51
+ const dw = pageSize.width * f;
52
+ const dh = pageSize.height * f;
53
+ return {
54
+ src: { x: 0, y: 0, w: dw, h: dh },
55
+ rect: { dx: 0, dy: 0, dw, dh },
56
+ systems,
57
+ measures
58
+ };
59
+ } catch {
60
+ return EMPTY_LAYOUT;
61
+ }
62
+ }
63
+ var DEFAULT_PLAYHEAD_COLOR = "#2f6f4f";
64
+ var MAX_ENGRAVE_WIDTH_SVG = 1200;
65
+ var MIN_ENGRAVE_WIDTH_SVG = 280;
66
+ function createSvgNotationPlayer(opts) {
67
+ const { host, musicXml, onsetsMs, noteCols } = opts;
68
+ const playheadColor = opts.playheadColor ?? DEFAULT_PLAYHEAD_COLOR;
69
+ const onsets = distinctOnsets(onsetsMs.map((onsetMs) => ({ onsetMs })));
70
+ const root = document.createElement("div");
71
+ root.style.position = "relative";
72
+ root.style.width = "100%";
73
+ root.style.touchAction = "pan-y pinch-zoom";
74
+ host.appendChild(root);
75
+ const svgHost = document.createElement("div");
76
+ root.appendChild(svgHost);
77
+ const playheadEl = document.createElement("div");
78
+ playheadEl.style.position = "absolute";
79
+ playheadEl.style.left = "0px";
80
+ playheadEl.style.top = "0px";
81
+ playheadEl.style.width = "2px";
82
+ playheadEl.style.height = "0px";
83
+ playheadEl.style.background = playheadColor;
84
+ playheadEl.style.opacity = "0";
85
+ playheadEl.style.pointerEvents = "none";
86
+ root.appendChild(playheadEl);
87
+ let osmd = null;
88
+ let currentLayout = null;
89
+ let currentZoom = opts.zoom ?? 1;
90
+ let unitInPixelsConst = 10;
91
+ let lastEngravedWidthPx = 0;
92
+ let destroyed = false;
93
+ let lastTMs = 0;
94
+ let rebuildToken = 0;
95
+ function desiredEngraveWidthPx() {
96
+ const w = host.clientWidth || 0;
97
+ return Math.max(MIN_ENGRAVE_WIDTH_SVG, Math.min(w || MAX_ENGRAVE_WIDTH_SVG, MAX_ENGRAVE_WIDTH_SVG));
98
+ }
99
+ function renderPlayhead(tMs) {
100
+ lastTMs = tMs;
101
+ if (!currentLayout) return;
102
+ const nBars = currentLayout.measures.length ? Math.max(...currentLayout.measures.map((m) => m.index)) + 1 : 0;
103
+ const line = vstackAudioPlayheadLine(currentLayout, onsets, tMs, nBars, noteCols);
104
+ if (!line) {
105
+ playheadEl.style.opacity = "0";
106
+ return;
107
+ }
108
+ playheadEl.style.opacity = String(line.alpha);
109
+ playheadEl.style.left = `${line.x}px`;
110
+ playheadEl.style.top = `${line.y0}px`;
111
+ playheadEl.style.height = `${Math.max(0, line.y1 - line.y0)}px`;
112
+ follow.follow(
113
+ () => typeof playheadEl.getBoundingClientRect === "function" ? playheadEl.getBoundingClientRect() : null
114
+ );
115
+ }
116
+ const follow = createFollowController();
117
+ function setTime(tMs) {
118
+ if (destroyed) return;
119
+ follow.onSetTime(tMs);
120
+ renderPlayhead(tMs);
121
+ }
122
+ async function initialEngrave() {
123
+ if (opts.rendered) {
124
+ currentLayout = opts.rendered;
125
+ lastEngravedWidthPx = desiredEngraveWidthPx();
126
+ renderPlayhead(lastTMs);
127
+ return;
128
+ }
129
+ const { OpenSheetMusicDisplay, unitInPixels } = await import("opensheetmusicdisplay");
130
+ unitInPixelsConst = unitInPixels;
131
+ if (destroyed) return;
132
+ const widthPx = desiredEngraveWidthPx();
133
+ svgHost.style.width = `${widthPx}px`;
134
+ const inst = new OpenSheetMusicDisplay(svgHost, {
135
+ backend: "svg",
136
+ autoResize: false,
137
+ drawTitle: false,
138
+ drawSubtitle: false,
139
+ drawComposer: false,
140
+ drawLyricist: false,
141
+ drawPartNames: false
142
+ });
143
+ await inst.load(musicXml);
144
+ if (destroyed) return;
145
+ inst.Zoom = currentZoom;
146
+ inst.render();
147
+ if (destroyed) return;
148
+ osmd = inst;
149
+ lastEngravedWidthPx = widthPx;
150
+ currentLayout = svgNotationLayout(inst, { unitInPixels: unitInPixelsConst });
151
+ renderPlayhead(lastTMs);
152
+ }
153
+ const ready = initialEngrave();
154
+ async function reflow(newZoom) {
155
+ if (destroyed) return;
156
+ const widthPx = desiredEngraveWidthPx();
157
+ if (widthPx === lastEngravedWidthPx && newZoom === currentZoom) return;
158
+ if (opts.rendered || !osmd) {
159
+ currentZoom = newZoom;
160
+ return;
161
+ }
162
+ const myToken = ++rebuildToken;
163
+ const oldLayout = currentLayout;
164
+ const hasWin = typeof window !== "undefined";
165
+ let anchorY = null;
166
+ const anchorX = widthPx / 2;
167
+ if (hasWin && typeof root.getBoundingClientRect === "function") {
168
+ const r = root.getBoundingClientRect();
169
+ anchorY = window.innerHeight / 2 - r.top;
170
+ }
171
+ svgHost.style.width = `${widthPx}px`;
172
+ osmd.Zoom = newZoom;
173
+ osmd.updateGraphic();
174
+ osmd.render();
175
+ if (destroyed || myToken !== rebuildToken) return;
176
+ lastEngravedWidthPx = widthPx;
177
+ currentZoom = newZoom;
178
+ currentLayout = svgNotationLayout(osmd, { unitInPixels: unitInPixelsConst });
179
+ if (oldLayout && anchorY != null && hasWin) {
180
+ const delta = computeReflowScrollDelta(oldLayout, currentLayout, anchorX, anchorY);
181
+ if (Number.isFinite(delta) && Math.abs(delta) > 0.5) {
182
+ window.scrollTo({ top: Math.max(0, window.scrollY + delta), left: window.scrollX, behavior: "auto" });
183
+ }
184
+ }
185
+ if (!destroyed) renderPlayhead(lastTMs);
186
+ }
187
+ const clickListeners = [];
188
+ function onRootClick(e) {
189
+ if (!currentLayout) return;
190
+ const rect = root.getBoundingClientRect();
191
+ const mx = e.clientX - rect.left;
192
+ const my = e.clientY - rect.top;
193
+ const idx = hitTestMeasureAt(currentLayout, mx, my);
194
+ if (idx != null) for (const cb of clickListeners) cb(idx);
195
+ }
196
+ root.addEventListener("click", onRootClick);
197
+ return {
198
+ ready,
199
+ setTime,
200
+ async setZoom(z) {
201
+ await ready;
202
+ await reflow(z);
203
+ },
204
+ async resize() {
205
+ await ready;
206
+ await reflow(currentZoom);
207
+ },
208
+ onMeasureClick(cb) {
209
+ clickListeners.push(cb);
210
+ return () => {
211
+ const i = clickListeners.indexOf(cb);
212
+ if (i >= 0) clickListeners.splice(i, 1);
213
+ };
214
+ },
215
+ destroy() {
216
+ if (destroyed) return;
217
+ destroyed = true;
218
+ rebuildToken++;
219
+ root.removeEventListener("click", onRootClick);
220
+ follow.destroy();
221
+ clickListeners.length = 0;
222
+ try {
223
+ osmd?.clear?.();
224
+ } catch {
225
+ }
226
+ osmd = null;
227
+ currentLayout = null;
228
+ if (root.parentNode === host) host.removeChild(root);
229
+ }
230
+ };
231
+ }
232
+ export {
233
+ MAX_ENGRAVE_WIDTH_SVG,
234
+ PROGRAMMATIC_SCROLL_EPSILON_PX,
235
+ computeReflowScrollDelta,
236
+ createSvgNotationPlayer,
237
+ hasReachedProgrammaticTarget,
238
+ isWithinProgrammaticScroll,
239
+ svgNotationLayout
240
+ };
241
+ //# sourceMappingURL=notationPlayerSvg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/notationPlayerSvg.ts"],"sourcesContent":["// createSvgNotationPlayer — the SVG (vector) sibling of `createNotationPlayer`\n// (src/notationPlayer.ts). Same job (a live, caller-driven notation +\n// gliding-playhead widget), different medium: OSMD's native SVG backend\n// instead of a rasterized canvas. See\n// docs — stave-web-sightread's\n// docs/superpowers/specs/2026-08-11-svg-notation-player-design.md — for the\n// full design rationale (why: vectors don't blur on pinch/browser zoom, no\n// canvas-area cap, no raster tiling needed for full-score scroll).\n//\n// THE CANVAS MODULE IS NOT MODIFIED OR IMPORTED FOR ITS OSMD/RASTER PATH —\n// this is a parallel component. What IS reused, verbatim, no new math:\n// - `vstackAudioPlayheadLine` (scene/notationGeometry.ts) — the exact same\n// onset-anchored, carriage-return playhead interpolation the canvas path\n// uses. It operates purely on a `NotationLayout` (measure column boxes +\n// a vertical clamp band) — it does not care whether those boxes came from\n// a canvas raster or live SVG DOM geometry, so THIS module's job is only\n// to produce a `NotationLayout` in SVG/CSS px space (see\n// `svgNotationLayout` below) and everything downstream is identical.\n// - `hitTestMeasureAt` (scene/notationGeometry.ts, moved there in 0.38.0\n// specifically so this module never has a build-time edge into\n// notationPlayer.ts's canvas/raster implementation) — the exact same pure\n// point-in-measure-box hit-test, reused for click-to-seek.\n// - `distinctOnsets`, `measureColumnsFromLayout` — small pure helpers,\n// reused as-is.\n//\n// WHAT'S NEW (not a re-derivation of any of the above):\n// - `svgNotationLayout` — an SVG-backend geometry extractor, the SVG\n// counterpart to promo.ts's canvas-only `extractGeometry`. See its own\n// doc comment for the unit-conversion derivation.\n// - `computeReflowScrollDelta` — zoom/resize position-preservation math\n// (not playhead interpolation; a one-shot \"where did this same content\n// move to\" lookup using the existing hit-test + column helpers).\n// - `isWithinProgrammaticScroll` / `hasReachedProgrammaticTarget` — the\n// improved auto-follow discriminator (design doc §4): unlike the canvas\n// scroll-mode player's fixed 600ms \"programmatic scroll\" grace window,\n// this compares the ACTUAL scroll position against the EXACT target this\n// component itself requested, so classification is correct regardless of\n// how long a smooth-scroll animation takes (no grace-window race).\n//\n// IMPORT PATH: subpath-only — `@real-music-packages/web-core/notationPlayerSvg`\n// — not re-exported from the root barrel (same reasoning as notationPlayer.ts:\n// the root barrel is theory-only/zero-dependency).\n\nimport {\n vstackAudioPlayheadLine,\n distinctOnsets,\n hitTestMeasureAt,\n type NotationLayout,\n} from './scene/notationGeometry';\nimport type { Box, StaffMeasureBox } from './promo';\nimport {\n computeReflowScrollDelta,\n createFollowController,\n isWithinProgrammaticScroll,\n hasReachedProgrammaticTarget,\n PROGRAMMATIC_SCROLL_EPSILON_PX,\n} from './notationCommon';\n\n// Re-exported for backward compatibility — this module's own tests (and any\n// external importer) still pull these from `notationPlayerSvg`; the\n// implementations now live in `notationCommon.ts` (shared with\n// notationPlayerVerovio.ts, 0.39.0). See that module's doc for why.\nexport { computeReflowScrollDelta, isWithinProgrammaticScroll, hasReachedProgrammaticTarget, PROGRAMMATIC_SCROLL_EPSILON_PX };\n\nexport interface CreateSvgNotationPlayerOpts {\n /** Element the player's content is mounted into. Takes NATURAL content\n * height (the whole score, page-flow layout) — the host must not clip a\n * fixed height; the PAGE scrolls the score, there is no internal camera. */\n host: HTMLElement;\n /** MusicXML to engrave. Ignored when `rendered` (the test seam) is set. */\n musicXml: string;\n /** Distinct note onsets (ms) the playhead locks to — same contract as\n * `CreateNotationPlayerOpts.onsetsMs` in notationPlayer.ts. */\n onsetsMs: number[];\n /** Per-onset engraved column positions, 1:1 with the DEDUPED/sorted\n * `onsetsMs` — same semantics as the canvas player's `noteCols`. */\n noteCols?: number[];\n /** Playhead line color. Default `'#2f6f4f'`. */\n playheadColor?: string;\n /** Initial OSMD zoom (a pure post-layout visual scale — see\n * `svgNotationLayout`'s doc). Default 1 (OSMD's own default — the\n * engraving fits the host's own width at normal note size). */\n zoom?: number;\n /**\n * Advanced / test seam: a pre-built `NotationLayout`, bypassing the real\n * OSMD SVG engrave (`musicXml` is still required by the type but is\n * ignored when this is set). Mirrors `CreateNotationPlayerOpts.rendered` in\n * notationPlayer.ts for the identical reason: real OSMD *rendering* needs\n * actual browser canvas glyph metrics (for its line-breaking pass) even\n * when the SVG backend is selected — headless/jsdom can't fully provide\n * that — so this is how this module stays unit-testable in Node. Not\n * needed in a real browser host. When set, `setZoom`/`resize` update the\n * tracked zoom/width but perform no real re-engrave (there is nothing to\n * re-engrave).\n */\n rendered?: NotationLayout;\n}\n\nexport interface SvgNotationPlayer {\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 canvas 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 OSMD zoom (systems reflow). The scroll position is\n * restored afterward so the content that was centered in the viewport\n * before the reflow is still 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\n * `ScoreNote.measure`/the engraved index). 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. */\n destroy(): void;\n}\n\n// ─── svgNotationLayout — the SVG-backend geometry extractor ───────────────\n//\n// UNIT CONVERSION — derived, not guessed (verified against the vendored\n// opensheetmusicdisplay + vexflow source, not just its .d.ts comments, which\n// are stale here — see below):\n//\n// 1. `GraphicalMusicSheet` (`osmd.GraphicSheet`) positions\n// (`PositionAndShape.AbsolutePosition`/`.Size`) are in backend-agnostic\n// \"OSMD units\" — the SAME object model promo.ts's canvas-only\n// `extractGeometry` reads (`osmd.GraphicSheet.MusicPages[0].MusicSystems`,\n// `.MeasureList`). Whichever backend (canvas/svg) was requested, this\n// layer is identical.\n// 2. OSMD's Vexflow draw layer (`VexFlowMusicSheetDrawer`) converts an OSMD\n// unit value to a \"raw\" Vexflow/SVG px value via an EXPORTED constant,\n// `unitInPixels` (currently 10 — NOT `EngravingRules.unit`, which is a\n// different, unrelated field that is NOT the px-per-unit factor despite\n// what its .d.ts comment implies; confirmed by reading the actual\n// compiled source, not trusting the stale doc comment). This raw value\n// is written directly into each SVG element's own coordinate attributes\n// — it does NOT yet include `zoom`.\n// 3. `osmd.Zoom` (current zoom) is applied SEPARATELY, at the SVG-backend\n// level, via a `viewBox` trick (`vexflow/src/svgcontext.js`'s\n// `scale(x,y)`): the `<svg>` element's `width`/`height` ATTRIBUTES are\n// set to the FINAL (zoomed) CSS px size, while its `viewBox` spans\n// `width/zoom .. height/zoom` — i.e. the RAW (unzoomed, step-2) content\n// coordinates. The browser therefore maps that raw coordinate space onto\n// the final CSS px box by exactly `zoom`.\n// Net result: `cssPx = unitValue * unitInPixels * zoom`. Both factors are\n// read from the live library/instance (never a hardcoded literal `10` or an\n// assumed zoom) — see `SvgNotationLayoutOpts.unitInPixels`'s doc — so a\n// future OSMD version changing either is picked up automatically, which is\n// exactly the \"10 units/staff-space assumptions have version drift\" risk\n// the design doc calls out.\n//\n// This mirrors, in spirit, promo.ts's canvas `extractGeometry` self-\n// calibration (`canvas.width / (contentRight+contentLeft)`, chosen there\n// specifically because a naive formula broke on overflowed layouts) — the SVG\n// backend doesn't have that raster-overflow failure mode (there is no\n// backing-store to overflow; the viewBox IS the content, always), so the\n// derived formula above is exact, not an approximation.\n\nexport interface SvgNotationLayoutOpts {\n /** CSS px per OSMD unit at zoom 1 — OSMD's own exported `unitInPixels`\n * constant (see the derivation above). REQUIRED, no default: the point is\n * to FORCE the real call site to source this from the live\n * `opensheetmusicdisplay` import\n * (`const { unitInPixels } = await import('opensheetmusicdisplay')`)\n * rather than this module assuming a value that could drift across OSMD\n * versions. Tests pin it explicitly. */\n unitInPixels: number;\n}\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/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Pure SVG-backend geometry extractor — builds the SAME `NotationLayout`\n * shape the canvas path's `notationLayout()` does (measure column boxes +\n * system rows + a `rect` vertical band), but read directly from OSMD's\n * `GraphicalMusicSheet` in SVG/CSS px space (see the unit-conversion doc\n * above) instead of a rasterized bitmap. Rebuild on every render (zoom /\n * resize / new score) — cheap, pure array/object mapping, no DOM reads.\n *\n * `osmd` is duck-typed `any` — same contract as promo.ts's\n * `extractGeometry(osmd: any, ...)` — so tests can pass a plain fixture\n * object shaped like the minimal slice of a real `OpenSheetMusicDisplay`\n * instance this function reads (`{ Zoom, GraphicSheet: { MusicPages,\n * MeasureList } }`) without needing a real browser OSMD render (see\n * `CreateSvgNotationPlayerOpts.rendered`'s doc for why headless can't do a\n * real one).\n *\n * `rect` spans the FULL engraved page (top-aligned, `dy = 0`) — there is no\n * follow-camera crop in this component (the whole score is always in the\n * DOM; the PAGE scrolls it) — matching the canvas scroll-mode's `flowLayout`\n * in spirit. `vstackAudioPlayheadLine` only reads `rect.dy`/`rect.dh` to\n * clamp the playhead into the drawn band, so this is a correct, minimal\n * `rect` for that consumer.\n */\nexport function svgNotationLayout(osmd: any, opts: SvgNotationLayoutOpts): NotationLayout {\n try {\n const zoom =\n typeof osmd?.Zoom === 'number' && osmd.Zoom > 0\n ? osmd.Zoom\n : typeof osmd?.zoom === 'number' && osmd.zoom > 0\n ? osmd.zoom\n : 1;\n const f = opts.unitInPixels * zoom;\n\n const graphic: any = osmd?.GraphicSheet;\n const page: any = graphic?.MusicPages?.[0];\n const pageSize = page?.PositionAndShape?.Size;\n const musicSystems: any[] = page?.MusicSystems ?? [];\n if (!(pageSize?.width > 0) || !(pageSize?.height > 0) || !musicSystems.length) return EMPTY_LAYOUT;\n\n const toBox = (pas: any): Box | null => {\n const p = pas?.AbsolutePosition;\n const sz = pas?.Size;\n if (!p || !sz) return null;\n return { x: p.x * f, y: p.y * f, w: sz.width * f, h: sz.height * f };\n };\n\n const systems: Box[] = musicSystems\n .map((s) => toBox(s?.PositionAndShape))\n .filter((b): b is Box => !!b && b.w > 1 && b.h > 1)\n .sort((a, b) => a.y - b.y);\n if (!systems.length) return EMPTY_LAYOUT;\n\n const measureList: any[][] = graphic?.MeasureList ?? [];\n const measures: StaffMeasureBox[] = [];\n measureList.forEach((staves, index) => {\n (staves ?? []).forEach((m: any, staff: number) => {\n const box = toBox(m?.PositionAndShape);\n if (box && box.w > 1 && box.h > 1) {\n const seX = (m?.staffEntries ?? [])[0]?.PositionAndShape?.AbsolutePosition?.x;\n const noteStartX = typeof seX === 'number' ? seX * f : box.x;\n measures.push({ index, staff, box, noteStartX });\n }\n });\n });\n\n const dw = pageSize.width * f;\n const dh = pageSize.height * f;\n return {\n src: { x: 0, y: 0, w: dw, h: dh },\n rect: { dx: 0, dy: 0, dw, dh },\n systems,\n measures,\n };\n } catch {\n return EMPTY_LAYOUT;\n }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n// ─── createSvgNotationPlayer ────────────────────────────────────────────────\n//\n// Zoom/resize position preservation (`computeReflowScrollDelta`) and the\n// auto-follow discriminator (`isWithinProgrammaticScroll` /\n// `hasReachedProgrammaticTarget` + the stateful `createFollowController`)\n// moved to `./notationCommon` (0.39.0) — shared with notationPlayerVerovio.ts.\n// Re-exported above for backward compatibility.\n\nconst DEFAULT_PLAYHEAD_COLOR = '#2f6f4f';\n/** Engrave-width ceiling, CSS px (design doc §\"Render\": \"cap ~1200px, the\n * 0.36.2 rule\" — the same reasoning as notationPlayer.ts's\n * `MAX_ENGRAVE_WIDTH`, restated here rather than imported since the two\n * players' constants are independently tunable, and this one is spec'd to a\n * slightly different value). */\nexport const MAX_ENGRAVE_WIDTH_SVG = 1200;\n/** Floor so a not-yet-laid-out / zero-width host never engraves at 0px. */\nconst MIN_ENGRAVE_WIDTH_SVG = 280;\n\n/** Build a live, interactive SVG (vector) notation player. See the module doc\n * + `docs/superpowers/specs/2026-08-11-svg-notation-player-design.md` (in\n * stave-web-sightread) for the full design. */\nexport function createSvgNotationPlayer(opts: CreateSvgNotationPlayerOpts): SvgNotationPlayer {\n const { host, musicXml, onsetsMs, noteCols } = opts;\n const playheadColor = opts.playheadColor ?? DEFAULT_PLAYHEAD_COLOR;\n const onsets = distinctOnsets(onsetsMs.map((onsetMs) => ({ onsetMs })));\n\n const root = document.createElement('div');\n root.style.position = 'relative';\n root.style.width = '100%';\n // Let the browser's native pinch-zoom AND vertical page-scroll gestures\n // through — the \"optical zoom is free\" half of the design (§5): vectors\n // stay crisp at any pinch/browser-zoom level, and this component adds\n // nothing to make that work beyond not blocking the gesture.\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let osmd: any = null;\n let currentLayout: NotationLayout | null = null;\n let currentZoom = opts.zoom ?? 1;\n let unitInPixelsConst = 10; // overwritten by the real import before first use (rendered-seam path never reads it)\n let lastEngravedWidthPx = 0;\n let destroyed = false;\n let lastTMs = 0;\n // Stale-table guard (design doc §\"Known risks\" — \"Overlay drift on\n // reflow\"): each async re-engrave captures its own token; if a NEWER\n // reflow starts before an older one's `await` resolves, the older one's\n // completion is a no-op instead of clobbering the newer geometry.\n let rebuildToken = 0;\n\n function desiredEngraveWidthPx(): number {\n const w = host.clientWidth || 0;\n return Math.max(MIN_ENGRAVE_WIDTH_SVG, Math.min(w || MAX_ENGRAVE_WIDTH_SVG, MAX_ENGRAVE_WIDTH_SVG));\n }\n\n // ─── Playhead ──────────────────────────────────────────────────────────\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, noteCols);\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 // ─── Auto-follow (target-position discriminator — see notationCommon.ts) ─\n\n const follow = createFollowController();\n\n // ─── setTime ───────────────────────────────────────────────────────────\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 async function initialEngrave(): Promise<void> {\n if (opts.rendered) {\n currentLayout = opts.rendered;\n lastEngravedWidthPx = desiredEngraveWidthPx();\n renderPlayhead(lastTMs);\n return;\n }\n // Literal dynamic import — consumers' bundlers must statically see the\n // specifier (same reasoning as promo.ts/notationPlayer.ts); a caller\n // that only ever uses the `rendered` test seam never pulls OSMD in.\n const { OpenSheetMusicDisplay, unitInPixels } = await import('opensheetmusicdisplay');\n unitInPixelsConst = unitInPixels;\n if (destroyed) return;\n\n const widthPx = desiredEngraveWidthPx();\n svgHost.style.width = `${widthPx}px`;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const inst: any = new OpenSheetMusicDisplay(svgHost, {\n backend: 'svg',\n autoResize: false,\n drawTitle: false,\n drawSubtitle: false,\n drawComposer: false,\n drawLyricist: false,\n drawPartNames: false,\n });\n await inst.load(musicXml);\n if (destroyed) return;\n inst.Zoom = currentZoom;\n inst.render();\n if (destroyed) return;\n\n osmd = inst;\n lastEngravedWidthPx = widthPx;\n currentLayout = svgNotationLayout(inst, { unitInPixels: unitInPixelsConst });\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` (resize just passes the\n * unchanged `currentZoom`). No-op when neither the width nor the zoom\n * actually changed, or when using the `rendered` test seam (nothing to\n * 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 || !osmd) {\n currentZoom = newZoom;\n return;\n }\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 svgHost.style.width = `${widthPx}px`;\n osmd.Zoom = newZoom;\n // Re-run layout (not just a redraw): a width change must re-flow which\n // measures land on which system, and — since we can't be certain a pure\n // zoom change never affects line-breaking on every OSMD version — this is\n // called unconditionally rather than gated to the width-only case.\n osmd.updateGraphic();\n osmd.render();\n if (destroyed || myToken !== rebuildToken) return;\n\n lastEngravedWidthPx = widthPx;\n currentZoom = newZoom;\n currentLayout = svgNotationLayout(osmd, { unitInPixels: unitInPixelsConst });\n\n if (oldLayout && 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n try { (osmd as any)?.clear?.(); } catch { /* best-effort */ }\n osmd = null;\n currentLayout = null;\n if (root.parentNode === host) host.removeChild(root);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgLA,IAAM,eAA+B;AAAA,EACnC,KAAK,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE;AAAA,EAC9B,MAAM,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE;AAAA,EACnC,SAAS,CAAC;AAAA,EACV,UAAU,CAAC;AACb;AA0BO,SAAS,kBAAkB,MAAW,MAA6C;AACxF,MAAI;AACF,UAAM,OACJ,OAAO,MAAM,SAAS,YAAY,KAAK,OAAO,IAC1C,KAAK,OACL,OAAO,MAAM,SAAS,YAAY,KAAK,OAAO,IAC5C,KAAK,OACL;AACR,UAAM,IAAI,KAAK,eAAe;AAE9B,UAAM,UAAe,MAAM;AAC3B,UAAM,OAAY,SAAS,aAAa,CAAC;AACzC,UAAM,WAAW,MAAM,kBAAkB;AACzC,UAAM,eAAsB,MAAM,gBAAgB,CAAC;AACnD,QAAI,EAAE,UAAU,QAAQ,MAAM,EAAE,UAAU,SAAS,MAAM,CAAC,aAAa,OAAQ,QAAO;AAEtF,UAAM,QAAQ,CAAC,QAAyB;AACtC,YAAM,IAAI,KAAK;AACf,YAAM,KAAK,KAAK;AAChB,UAAI,CAAC,KAAK,CAAC,GAAI,QAAO;AACtB,aAAO,EAAE,GAAG,EAAE,IAAI,GAAG,GAAG,EAAE,IAAI,GAAG,GAAG,GAAG,QAAQ,GAAG,GAAG,GAAG,SAAS,EAAE;AAAA,IACrE;AAEA,UAAM,UAAiB,aACpB,IAAI,CAAC,MAAM,MAAM,GAAG,gBAAgB,CAAC,EACrC,OAAO,CAAC,MAAgB,CAAC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AM,IAAI,eAAe,QAAQ,EAAE;AACnC,YAAI,KAAK,EAAG,gBAAe,OAAO,GAAG,CAAC;AAAA,MACxC;AAAA,IACF;AAAA,IACA,UAAgB;AACd,UAAI,UAAW;AACf,kBAAY;AACZ;AACA,WAAK,oBAAoB,SAAS,WAAW;AAC7C,aAAO,QAAQ;AACf,qBAAe,SAAS;AAExB,UAAI;AAAE,QAAC,MAAc,QAAQ;AAAA,MAAG,QAAQ;AAAA,MAAoB;AAC5D,aAAO;AACP,sBAAgB;AAChB,UAAI,KAAK,eAAe,KAAM,MAAK,YAAY,IAAI;AAAA,IACrD;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,163 @@
1
+ import { N as NotationLayout } from './notationGeometry-54fFq5yU.js';
2
+ import './promo.js';
3
+
4
+ /** One distinct note-onset instant: the audio-clock time it sounds at, and
5
+ * the stamped `xml:id`s (Task 1, stave repo) of every note that sounds at
6
+ * that instant (>1 for a chord). Multiple entries sharing the same `tMs`
7
+ * are merged (their `noteIds` unioned) — the caller does not need to
8
+ * pre-group chords into one entry. */
9
+ interface VerovioOnset {
10
+ tMs: number;
11
+ noteIds: string[];
12
+ }
13
+ interface CreateVerovioNotationPlayerOpts {
14
+ /** Element the player's content is mounted into. Takes NATURAL content
15
+ * height (the whole score, page-flow layout, ALL Verovio pages stacked)
16
+ * — the host must not clip a fixed height; the PAGE scrolls the score. */
17
+ host: HTMLElement;
18
+ /** Display MusicXML to engrave (Task 1's transform-pipeline output — ids
19
+ * already stamped). Ignored when `rendered` (the test seam) is set. */
20
+ musicXml: string;
21
+ /** Note onsets the playhead locks to, WITH the stamped ids of the notes
22
+ * sounding at each onset — see `VerovioOnset`. Distinct/sorted
23
+ * automatically (duplicates by `tMs` are merged, not required to be
24
+ * pre-sorted). */
25
+ onsets: VerovioOnset[];
26
+ /** Playhead line color. Default `'#2f6f4f'`. */
27
+ playheadColor?: string;
28
+ /** Initial semantic zoom — see `verovioZoomOptions`'s doc for the mapping.
29
+ * Default 1 (a normal readable size that fits the host's width). */
30
+ zoom?: number;
31
+ /**
32
+ * Advanced / test seam: a pre-built `NotationLayout`, bypassing the real
33
+ * Verovio engrave (`musicXml` is still required by the type but is
34
+ * ignored when this is set). Mirrors `CreateSvgNotationPlayerOpts.rendered`
35
+ * in notationPlayerSvg.ts for the identical reason: real Verovio rendering
36
+ * needs a real SVG DOM (`getBBox`/`getBoundingClientRect`) that jsdom can't
37
+ * provide — see notationPlayerSvg.ts's module doc for why headless can't do
38
+ * a real one. When set, `noteIds`-based note lookups have no live DOM to
39
+ * resolve against, so the playhead falls back to `vstackAudioPlayheadLine`'s
40
+ * own ordinal spread (same graceful-degradation path as "no `noteCols`
41
+ * supplied" on the SVG player) — fine for a lifecycle test, not for
42
+ * notehead-accurate positioning. `setZoom`/`resize` update the tracked zoom
43
+ * /width but perform no real re-engrave (there is nothing to re-engrave).
44
+ */
45
+ rendered?: NotationLayout;
46
+ }
47
+ interface VerovioNotationPlayer {
48
+ /** Resolves once the engraving is in the DOM and ready to draw. `setTime`/
49
+ * click hit-testing are safe to call before this resolves (no-op until
50
+ * ready, same contract as the SVG player). */
51
+ readonly ready: Promise<void>;
52
+ /** Drive the playhead for absolute playback time `tMs`. Caller owns the
53
+ * audio clock + rAF loop. */
54
+ setTime(tMs: number): void;
55
+ /** Re-engrave at a new semantic zoom (systems reflow — see
56
+ * `verovioZoomOptions`). The scroll position is restored afterward so the
57
+ * content that was centered in the viewport before the reflow is still
58
+ * centered after it. */
59
+ setZoom(z: number): Promise<void>;
60
+ /** Re-measure the host and reflow to match its current width, with the
61
+ * same scroll-position preservation as `setZoom`. Call on host resize /
62
+ * orientation change. */
63
+ resize(): Promise<void>;
64
+ /** Register a measure-click handler (measure index, matching the DOM-order
65
+ * index `verovioNotationLayout` assigns). Returns an unsubscribe fn. */
66
+ onMeasureClick(cb: (measureIndex: number) => void): () => void;
67
+ /** Tear down: removes the mounted DOM (engraving + playhead overlay) from
68
+ * `host`, and drops every listener this instance added (click, window
69
+ * scroll) and pending async work (a token guard drops any in-flight
70
+ * reflow's effects). Idempotent. Does NOT destroy the shared module-level
71
+ * Verovio toolkit instance (see the module doc's "SHARED TOOLKIT
72
+ * INSTANCE" note) — it is reused by the next player, if any. */
73
+ destroy(): void;
74
+ }
75
+ /**
76
+ * Pure(ish) — DOM-in, `NotationLayout`-out — Verovio-backend geometry
77
+ * extractor. `root` is the container holding every rendered `.vrv-page`
78
+ * wrapper `<div>` (this player's `svgHost`; a test fixture must reproduce
79
+ * that same wrapper structure — see the extractor tests). Builds the SAME
80
+ * `NotationLayout` shape `svgNotationLayout` (notationPlayerSvg.ts) does,
81
+ * from Verovio's rendered SVG DOM instead of OSMD's object model — see the
82
+ * module doc for the full derivation (measure/staff/system/note lookup via
83
+ * Verovio's own stable SVG classes, unit conversion via the live
84
+ * width/viewBox on each page). Never throws; returns `EMPTY_LAYOUT` on any
85
+ * missing/malformed structure.
86
+ */
87
+ declare function verovioNotationLayout(root: Element): NotationLayout;
88
+ /**
89
+ * Resolve each DISTINCT onset (see `distinctOnsets`) to a `noteCols` entry —
90
+ * the SAME "real engraved column" format `vstackAudioPlayheadLine` already
91
+ * accepts from the SVG/canvas players (`measureIndex + fractionWithinMeasure`
92
+ * — see that function's doc for how it's consumed). For each onset, every
93
+ * stamped `noteId` sounding at that instant (a chord may have several) is
94
+ * looked up by id in the live DOM (`document.getElementById` — Task 1 stamps
95
+ * ids that Verovio preserves verbatim as SVG element ids), mapped to its
96
+ * measure via `collectMeasureElements`'s canonical indexing (so it lines up
97
+ * EXACTLY with `verovioNotationLayout`'s own `index` numbering), and its
98
+ * fractional x-position within that measure's column computed with the exact
99
+ * same formula `vstackAudioPlayheadLine`'s own `colX` uses internally (not
100
+ * re-derived independently — this is the note's ANCHOR position, not new
101
+ * interpolation math). A chord's several ids are averaged. Any onset with NO
102
+ * resolvable id (missing from the DOM, e.g. a `rendered`-seam layout with no
103
+ * live SVG) falls back to the ordinal spread `vstackAudioPlayheadLine` itself
104
+ * uses when `noteCols` is entirely absent — so one bad id degrades ONLY that
105
+ * onset, not the whole piece. Returns `undefined` (not a partially-bad array)
106
+ * only when there is no usable layout/DOM at all to resolve against.
107
+ */
108
+ declare function verovioOnsetColumns(root: Element, layout: NotationLayout, onsets: VerovioOnset[]): number[] | undefined;
109
+ /** Verovio glyph-size percent at semantic zoom 1 (matches the migration
110
+ * spike's own default — a normal, readable size at typical host widths). */
111
+ declare const VEROVIO_BASE_SCALE = 40;
112
+ /** Clamp band for the derived `scale`, so an extreme `zoom` never collapses
113
+ * glyphs to unreadable or blows them up past sane bounds. */
114
+ declare const VEROVIO_MIN_SCALE = 20;
115
+ declare const VEROVIO_MAX_SCALE = 120;
116
+ interface VerovioRenderOptions {
117
+ scale: number;
118
+ pageWidth: number;
119
+ }
120
+ /**
121
+ * Semantic zoom → Verovio options. The migration spike's `zoom-test*.mjs`
122
+ * proved `pageWidth` (Verovio's line-breaking width, in ITS OWN units)
123
+ * drives measures-per-system while `scale` (glyph size) alone does NOT
124
+ * (avgMeasuresPerSystem was IDENTICAL — 3.61 — across scale 40/80/150 at a
125
+ * fixed pageWidth 1600; it moved 2.24→3.61→5.91 as pageWidth alone rose
126
+ * 1000→1600→2400 at a fixed scale). Verovio's own rendered SVG width in CSS
127
+ * px is EXACTLY `pageWidth * scale / 100` (confirmed empirically against
128
+ * real 6.2.0 renders) — an identity, not an approximation.
129
+ *
130
+ * This function picks `scale` proportional to `zoom` (bigger zoom ⇒ bigger
131
+ * glyphs) and then SOLVES that identity for the `pageWidth` that makes the
132
+ * rendered width land EXACTLY on `hostWidthPx` regardless of zoom
133
+ * (`pageWidth = hostWidthPx * 100 / scale`). Composing it this way — instead
134
+ * of tuning `scale` and `pageWidth` independently — makes BOTH halves of the
135
+ * spec's semantic fall out of the ONE formula: as `zoom` rises, `scale`
136
+ * rises (glyphs bigger) AND the required `pageWidth` (in Verovio units)
137
+ * SHRINKS proportionally (since it's inversely proportional to `scale` at a
138
+ * fixed target width) — and per the spike's own finding, a smaller
139
+ * `pageWidth` fits FEWER measures per system. So "bigger zoom ⇒ fewer
140
+ * measures/system, glyphs larger, width still fits host" (design doc §2) is
141
+ * a direct consequence of this one identity, pinned by
142
+ * `tests/notationPlayerVerovio.test.ts`'s real-Verovio monotonicity test.
143
+ *
144
+ * No floor on `pageWidth` beyond what the identity itself produces: `scale`
145
+ * is already clamped to `[VEROVIO_MIN_SCALE, VEROVIO_MAX_SCALE]` (both > 0)
146
+ * and `hostWidthPx` is floored to a sane fallback when invalid, so
147
+ * `pageWidth = w * 100 / scale` is ALWAYS finite and positive — an
148
+ * additional floor would only ever fire by breaking the width-fits-host
149
+ * identity (clamping the OUTPUT width away from the host's actual width),
150
+ * which is worse than a small `pageWidth`.
151
+ */
152
+ declare function verovioZoomOptions(hostWidthPx: number, zoom: number): VerovioRenderOptions;
153
+ /** Engrave-width ceiling, CSS px — same policy as notationPlayerSvg.ts's
154
+ * `MAX_ENGRAVE_WIDTH_SVG` (design doc §"Render": "cap ~1200px"), restated
155
+ * independently since the two players' constants are independently
156
+ * tunable. */
157
+ declare const MAX_ENGRAVE_WIDTH_VRV = 1200;
158
+ /** Build a live, interactive Verovio (vector) notation player. See the
159
+ * module doc + `docs/superpowers/specs/2026-08-11-verovio-player-design.md`
160
+ * (in stave-web-sightread) §2 for the full design. */
161
+ declare function createVerovioNotationPlayer(opts: CreateVerovioNotationPlayerOpts): VerovioNotationPlayer;
162
+
163
+ export { type CreateVerovioNotationPlayerOpts, MAX_ENGRAVE_WIDTH_VRV, VEROVIO_BASE_SCALE, VEROVIO_MAX_SCALE, VEROVIO_MIN_SCALE, type VerovioNotationPlayer, type VerovioOnset, type VerovioRenderOptions, createVerovioNotationPlayer, verovioNotationLayout, verovioOnsetColumns, verovioZoomOptions };