animader-cli 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1460 @@
1
+ // The dev-only transport chrome. It is loaded by the dev profile alone and
2
+ // builds everything it owns at runtime inside #controls: the device button,
3
+ // the shared readout row, the Canvas 2D ruler with its transparent native
4
+ // range, the scene chips and lane, and one widget per declared piece control.
5
+ // Nothing here is imported by boot.mjs, controller.mjs or release.mjs, and
6
+ // nothing here is in the static markup.
7
+ //
8
+ // The ruler is a window on the piece, not a progress bar: the playhead is the
9
+ // exact centre and the musical grid moves under it at 26 CSS px per second.
10
+ // Pointer scrubbing is relative for the same reason — the native range's
11
+ // absolute x-to-time mapping cannot describe a fixed centre.
12
+
13
+ import {
14
+ describeControl,
15
+ formatElapsed,
16
+ formatPosition,
17
+ heldSummary,
18
+ readoutPieces,
19
+ sceneWindows,
20
+ } from './controller.mjs';
21
+
22
+ const SCALE = 26;
23
+ const MUSICAL_HEIGHT = 48;
24
+ const SCENE_TOP = 52;
25
+ const SCENE_SUBLANE = 20;
26
+ const SCENE_BASE_HEIGHT = 80;
27
+ const DPR_MAX = 3;
28
+ const PRESET_DESKTOP = Object.freeze({ presetLabel: 'Desktop · 1280×720', width: 1280, height: 720 });
29
+ const PRESET_MOBILE = Object.freeze({ presetLabel: 'Mobile · 720×1280', width: 720, height: 1280 });
30
+ export const DEVICE_PRESETS = Object.freeze([PRESET_DESKTOP, PRESET_MOBILE]);
31
+ const PPC = 720720;
32
+ const EPS = 1e-7;
33
+ // The transport's own seek quantum. The decoded soundtrack's tail is judged
34
+ // against it too, so decode rounding never becomes visible product truth.
35
+ const QUANTUM_SECONDS = 0.01;
36
+ const QUARTER_MIN_WIDTH = 480;
37
+ const PHONE_MAX_WIDTH = 719;
38
+ const FONT = '11px system-ui, sans-serif';
39
+ let mountSequence = 0;
40
+
41
+ const COLOR = {
42
+ quarter: '#675f58',
43
+ bar: '#8f857a',
44
+ track: '#3a2a33',
45
+ label: '#8f857a',
46
+ text: '#d8cfc4',
47
+ scoreEnd: '#2c2026',
48
+ accent: '#f0b27a',
49
+ muted: '#8f857a',
50
+ };
51
+
52
+ function presetFor(device) {
53
+ if (!device || typeof device !== 'object') return DEVICE_PRESETS[0];
54
+ return DEVICE_PRESETS.find((preset) => preset.presetLabel === device.presetLabel
55
+ && preset.width === device.width
56
+ && preset.height === device.height) ?? DEVICE_PRESETS[0];
57
+ }
58
+
59
+ function otherDevice(device) {
60
+ return DEVICE_PRESETS.find((preset) => preset !== device) ?? DEVICE_PRESETS[0];
61
+ }
62
+
63
+ function numberFrom(value, fallback) {
64
+ let number = value;
65
+ if (typeof value === 'bigint') number = Number(value);
66
+ else if (typeof value === 'string' && value.trim() !== '') number = Number(value);
67
+ return typeof number === 'number' && Number.isFinite(number) ? number : fallback;
68
+ }
69
+
70
+ function clamp(value, min, max) {
71
+ return Math.max(min, Math.min(max, value));
72
+ }
73
+
74
+ /**
75
+ * The decoded soundtrack's own end is a product-visible boundary only when
76
+ * the distance to the host end survives the transport's 10 ms quantum. A
77
+ * decode rounding difference (35.999977 s against a 36 s host) is not a
78
+ * zero-length silence region, so it returns null.
79
+ */
80
+ export function audioEndBoundary(hostSeconds, decodedSeconds) {
81
+ const host = numberFrom(hostSeconds, NaN);
82
+ const decoded = numberFrom(decodedSeconds, NaN);
83
+ if (!Number.isFinite(host) || !Number.isFinite(decoded) || decoded <= 0) return null;
84
+ const interval = host - decoded;
85
+ return Math.round(interval / QUANTUM_SECONDS) >= 1 ? decoded : null;
86
+ }
87
+
88
+ function formatLane(value) {
89
+ const number = numberFrom(value, NaN);
90
+ return Number.isFinite(number) ? number.toFixed(2) : '—';
91
+ }
92
+
93
+ function formatLanes(values) {
94
+ return (Array.isArray(values) ? values : [values]).map(formatLane).join(', ');
95
+ }
96
+
97
+ function firstLane(value) {
98
+ return Array.isArray(value) ? value[0] : value;
99
+ }
100
+
101
+ function stepFor(min, max) {
102
+ const span = Math.abs(max - min);
103
+ if (!(span > 0)) return QUANTUM_SECONDS;
104
+ const step = span / 1000;
105
+ return step >= QUANTUM_SECONDS ? step : Number(step.toFixed(6));
106
+ }
107
+
108
+ function sceneBar(window, meta, index) {
109
+ const scene = Array.isArray(meta?.scenes) ? meta.scenes[index] : null;
110
+ const startTick = numberFrom(scene?.startTick, NaN);
111
+ if (Number.isFinite(startTick) && startTick >= 0) {
112
+ return String(Math.floor(startTick / PPC) + 1);
113
+ }
114
+ const position = formatPosition(Math.round(window.start), meta);
115
+ const parsed = /^bar (\d+) ·/.exec(position);
116
+ return parsed ? parsed[1] : null;
117
+ }
118
+
119
+ /**
120
+ * Assign overlapping scene windows to stacked sublanes: the first lane whose
121
+ * previous interval has ended by this window's start. Returns the assignment
122
+ * plus the lane count that sets the ruler's drawn height.
123
+ */
124
+ function layoutSceneLanes(windows) {
125
+ const ends = [];
126
+ const lanes = windows.map((window) => {
127
+ let lane = 0;
128
+ while (lane < ends.length && ends[lane] > window.start) lane += 1;
129
+ ends[lane] = Math.max(ends[lane] ?? window.end, window.end);
130
+ return { window, lane };
131
+ });
132
+ return { lanes, depth: Math.max(1, ends.length) };
133
+ }
134
+
135
+ function sceneRulerHeight(windows, open) {
136
+ if (!open || windows.length === 0) return MUSICAL_HEIGHT;
137
+ return SCENE_BASE_HEIGHT + (layoutSceneLanes(windows).depth - 1) * SCENE_SUBLANE;
138
+ }
139
+
140
+ /**
141
+ * The tempo map integrated into seconds and beats. The map's tick fields are
142
+ * pacer ticks (PPC = one bar); the show's own tick grid is 100 per second.
143
+ */
144
+ function buildModel(meta) {
145
+ const transport = meta?.transport ?? {};
146
+ const openingBpm = numberFrom(transport.bpm, 82);
147
+ const bpm = openingBpm > 0 ? openingBpm : 82;
148
+ const beatsPerBar = Math.max(1, Math.floor(numberFrom(transport.beatsPerBar, 4)));
149
+ const dur = numberFrom(transport.dur, Infinity);
150
+ const scoreEndTick = dur > 0 ? dur : Infinity;
151
+ const ticksPerBeat = PPC / beatsPerBar;
152
+
153
+ const points = (Array.isArray(meta?.tempoMap) ? meta.tempoMap : [])
154
+ .map((point) => ({
155
+ tick: numberFrom(point?.tick, NaN),
156
+ bpm: numberFrom(point?.bpm, NaN),
157
+ }))
158
+ .filter((point) => Number.isFinite(point.tick) && point.tick >= 0
159
+ && point.tick <= scoreEndTick && Number.isFinite(point.bpm) && point.bpm > 0)
160
+ .sort((a, b) => a.tick - b.tick);
161
+
162
+ if (points.length === 0 || points[0].tick > 0) points.unshift({ tick: 0, bpm });
163
+ else points[0] = { tick: 0, bpm: points[0].bpm };
164
+
165
+ const segments = [];
166
+ let startSeconds = 0;
167
+ for (let index = 0; index < points.length; index += 1) {
168
+ const point = points[index];
169
+ const nextTick = index + 1 < points.length ? points[index + 1].tick : scoreEndTick;
170
+ const endTick = Number.isFinite(scoreEndTick) ? Math.min(nextTick, scoreEndTick) : nextTick;
171
+ const span = Math.max(0, endTick - point.tick);
172
+ const startBeat = point.tick / ticksPerBeat;
173
+ const beats = span / ticksPerBeat;
174
+ const spanSeconds = (beats * 60) / point.bpm;
175
+ segments.push({
176
+ startTick: point.tick,
177
+ startSeconds,
178
+ endSeconds: startSeconds + spanSeconds,
179
+ startBeat,
180
+ beats,
181
+ bpm: point.bpm,
182
+ });
183
+ startSeconds += spanSeconds;
184
+ }
185
+
186
+ return {
187
+ beatsPerBar,
188
+ ticksPerBeat,
189
+ segments,
190
+ scoreEndSeconds: segments.at(-1)?.endSeconds ?? Infinity,
191
+ };
192
+ }
193
+
194
+ function timeAtBeat(model, beat) {
195
+ for (let index = 0; index < model.segments.length; index += 1) {
196
+ const segment = model.segments[index];
197
+ const endBeat = segment.startBeat + segment.beats;
198
+ if (beat < endBeat - EPS || index === model.segments.length - 1) {
199
+ return segment.startSeconds + ((beat - segment.startBeat) * 60) / segment.bpm;
200
+ }
201
+ }
202
+ return 0;
203
+ }
204
+
205
+ function verticalLine(ctx, x, y, height, color) {
206
+ ctx.fillStyle = color;
207
+ ctx.fillRect(Math.round(x), y, 1, height);
208
+ }
209
+
210
+ function hollowCap(ctx, x, y, size, color) {
211
+ const left = Math.round(x) - Math.floor(size / 2);
212
+ ctx.fillStyle = color;
213
+ ctx.fillRect(left, y, size, 1);
214
+ ctx.fillRect(left, y + size - 1, size, 1);
215
+ ctx.fillRect(left, y, 1, size);
216
+ ctx.fillRect(left + size - 1, y, 1, size);
217
+ }
218
+
219
+ function edgeBracket(ctx, width, side, y, color) {
220
+ const left = side === 'left' ? 0 : width - 4;
221
+ ctx.fillStyle = color;
222
+ ctx.fillRect(left, y, 4, 1);
223
+ ctx.fillRect(left, y + 6, 4, 1);
224
+ ctx.fillRect(side === 'left' ? left + 3 : left, y, 1, 7);
225
+ }
226
+
227
+ function ariaAt(seconds, hostSeconds, meta) {
228
+ const position = formatPosition(Math.round(seconds * 100), meta);
229
+ const hold = /^hold · (.+) BPM$/.exec(position);
230
+ if (hold) {
231
+ return `hold, ${seconds.toFixed(2)} seconds of ${hostSeconds.toFixed(2)}, ${hold[1]} BPM`;
232
+ }
233
+ const parsed = /^bar (\d+) · beat (\d+) · (.+) BPM$/.exec(position);
234
+ if (!parsed) return position;
235
+ return `bar ${parsed[1]}, beat ${parsed[2]}, ${seconds.toFixed(2)} seconds of ${hostSeconds.toFixed(2)}, ${parsed[3]} BPM`;
236
+ }
237
+
238
+ function ariaDuringDrag(seconds, frameSeconds, meta) {
239
+ const position = formatPosition(Math.round(seconds * 100), meta);
240
+ const hold = /^hold · /.test(position);
241
+ const lead = hold
242
+ ? `Proposed hold, ${seconds.toFixed(2)} seconds`
243
+ : position.replace(
244
+ /^bar (\d+) · beat (\d+) · .+ BPM$/,
245
+ (_, bar, beat) => `Proposed bar ${bar}, beat ${beat}, ${seconds.toFixed(2)} seconds`,
246
+ );
247
+ return `${lead}; frame remains ${frameSeconds.toFixed(2)} seconds; release to seek`;
248
+ }
249
+
250
+ /**
251
+ * Build the dev chrome inside `host` and answer the render/destroy surface the
252
+ * shared page drives. `actions` carries the show commands; `pause`/`resume`
253
+ * are optional because a caller that only exposes `seek` still gets the
254
+ * pointer mapping, just without pausing during a drag.
255
+ */
256
+ export function mountTransport({
257
+ host, readout, seconds, meta = {}, decodedSeconds = null, actions = {}, device: initialDevice = null,
258
+ }) {
259
+ if (!host || typeof host.appendChild !== 'function') {
260
+ throw new TypeError('mountTransport needs a host element');
261
+ }
262
+ host.classList?.add?.('panel--transport');
263
+ const document = host.ownerDocument ?? globalThis.document;
264
+ const hostSeconds = numberFrom(seconds, 0) > 0 ? numberFrom(seconds, 0) : 0;
265
+ const model = buildModel(meta);
266
+ const scoreEndSeconds = Number.isFinite(model.scoreEndSeconds) ? model.scoreEndSeconds : hostSeconds;
267
+ const audioSeconds = numberFrom(decodedSeconds, NaN);
268
+ const audioEnd = audioEndBoundary(hostSeconds, audioSeconds);
269
+ const windows = sceneWindows(meta);
270
+ const controls = (Array.isArray(meta?.controls) ? meta.controls : []).map(describeControl);
271
+ const mountId = `transport-${mountSequence += 1}`;
272
+ const primary = document?.getElementById?.('primary') ?? null;
273
+ const fullscreen = document?.getElementById?.('fullscreen') ?? null;
274
+
275
+ const device = document.createElement('button');
276
+ device.type = 'button';
277
+ device.id = 'device';
278
+ device.className = 'secondary device';
279
+ device.dataset.playerControl = 'device';
280
+ let currentDevice = presetFor(initialDevice);
281
+
282
+ function syncDeviceLabel() {
283
+ const next = otherDevice(currentDevice);
284
+ device.textContent = currentDevice.presetLabel;
285
+ device.setAttribute('aria-label', `${currentDevice.presetLabel}. Switch to ${next.presetLabel}`);
286
+ }
287
+
288
+ syncDeviceLabel();
289
+
290
+ const timeline = document.createElement('div');
291
+ timeline.className = 'timeline';
292
+ const track = document.createElement('div');
293
+ track.className = 'ruler-track';
294
+ const canvas = document.createElement('canvas');
295
+ canvas.className = 'ruler';
296
+ canvas.setAttribute('aria-hidden', 'true');
297
+ const range = document.createElement('input');
298
+ range.type = 'range';
299
+ range.className = 'ruler-range';
300
+ range.min = '0';
301
+ range.max = String(hostSeconds);
302
+ range.step = String(QUANTUM_SECONDS);
303
+ range.value = '0';
304
+ range.setAttribute('aria-label', 'Show position');
305
+
306
+ const readoutElement = readout ?? document.createElement('div');
307
+ if (!readoutElement.id) readoutElement.id = 'readout';
308
+ if (readoutElement.classList) readoutElement.classList.add('readout');
309
+ else readoutElement.className = `${readoutElement.className ?? ''} readout`.trim();
310
+ readoutElement.hidden = false;
311
+
312
+ const span = (id) => {
313
+ let element = document.getElementById?.(id) ?? null;
314
+ if (!element) {
315
+ element = document.createElement('span');
316
+ element.id = id;
317
+ readoutElement.appendChild(element);
318
+ }
319
+ return element;
320
+ };
321
+ const positionElement = span('readout-position');
322
+ const elapsedElement = span('readout-elapsed');
323
+
324
+ // Words and separators are muted; numbers carry the text tone. The release
325
+ // mount writes the same pieces from the same shared splitter.
326
+ const writeReadout = (element, text) => {
327
+ const nodes = readoutPieces(text).map((piece) => {
328
+ if (typeof piece === 'string') return document.createTextNode(piece);
329
+ const token = document.createElement('span');
330
+ token.className = piece.className;
331
+ token.textContent = piece.text;
332
+ return token;
333
+ });
334
+ element.replaceChildren(...nodes);
335
+ };
336
+
337
+ // The rebuild's second line: the same held seconds the status names, under
338
+ // the readout. Hidden at rest and whenever no transition is set.
339
+ const holdingNote = document.createElement('p');
340
+ holdingNote.className = 'holding-note';
341
+ holdingNote.hidden = true;
342
+
343
+ const browserLocation = globalThis.location ?? null;
344
+ const browserHistory = globalThis.history ?? null;
345
+ const compact = globalThis.matchMedia?.('(max-width: 719px)')?.matches
346
+ ?? (numberFrom(globalThis.innerWidth, 1280) < PHONE_MAX_WIDTH + 1);
347
+ const query = new URLSearchParams(browserLocation?.search ?? '');
348
+ const explicitScenes = query.get('scenes') === '0' || query.get('scenes') === '1';
349
+ const explicitControls = query.get('controls') === '0' || query.get('controls') === '1';
350
+ let scenesOpen = explicitScenes ? query.get('scenes') === '1' : !compact;
351
+ let controlsOpen = explicitControls
352
+ ? query.get('controls') === '1'
353
+ : !compact || controls.length === 1;
354
+ let scenesDetails = null;
355
+ let controlsDetails = null;
356
+ let controlsLabel = null;
357
+ let sceneChips = [];
358
+ let scenesRow = null;
359
+ let scenesWrap = null;
360
+ const controlWidgets = [];
361
+ const held = new Map();
362
+ const pointerHeld = new Set();
363
+ let lastCurrentKey = null;
364
+ let suppressToggle = false;
365
+ let scenesLabel = null;
366
+ let scenesAction = null;
367
+ let controlsAction = null;
368
+ let forcedQuery = globalThis.matchMedia?.('(forced-colors: active)') ?? null;
369
+ let probeElements = null;
370
+ let probeHost = null;
371
+
372
+ const rangeNotes = document.createElement('p');
373
+ rangeNotes.id = `${mountId}-notes`;
374
+ rangeNotes.className = 'visually-hidden';
375
+ rangeNotes.textContent = describeRulerNotes();
376
+ range.setAttribute('aria-describedby', rangeNotes.id);
377
+
378
+ scenesDetails = buildScenesSurface();
379
+ controlsDetails = buildControlsSurface();
380
+
381
+ track.append(canvas, range);
382
+ timeline.append(readoutElement, holdingNote, track, rangeNotes);
383
+ if (primary && fullscreen && fullscreen.parentNode === host) host.insertBefore(device, fullscreen);
384
+ else if (primary && primary.parentNode === host) host.insertBefore(device, primary.nextSibling);
385
+ else host.append(device);
386
+ host.append(timeline);
387
+ if (scenesDetails) host.append(scenesDetails);
388
+ if (controlsDetails) host.append(controlsDetails);
389
+
390
+ let lastState = 'loading';
391
+ let lastTick = 0;
392
+ let busy = false;
393
+ let drag = null;
394
+ let prepared = null;
395
+ let destroyed = false;
396
+
397
+ function describeRulerNotes() {
398
+ const parts = ['Bar numbers mark bar starts'];
399
+ const changes = model.segments.filter((segment) => segment.startTick > 0);
400
+ if (changes.length === 0) {
401
+ const bpm = model.segments[0]?.bpm ?? 82;
402
+ parts.push(`${Number.isInteger(bpm) ? bpm : bpm.toFixed(1)} BPM throughout`);
403
+ } else {
404
+ for (const segment of changes) {
405
+ const bar = Math.floor(segment.startTick / PPC) + 1;
406
+ const bpm = Number.isInteger(segment.bpm) ? segment.bpm : segment.bpm.toFixed(1);
407
+ parts.push(`tempo change to ${bpm} BPM at bar ${bar}`);
408
+ }
409
+ }
410
+ if (scoreEndSeconds < hostSeconds - EPS) {
411
+ parts.push(`hold from ${scoreEndSeconds.toFixed(2)} to ${hostSeconds.toFixed(2)} seconds`);
412
+ }
413
+ if (Number.isFinite(audioSeconds) && audioSeconds < hostSeconds - EPS) {
414
+ if (audioEnd !== null) {
415
+ parts.push(`silence from ${audioEnd.toFixed(2)} to ${hostSeconds.toFixed(2)} seconds`);
416
+ }
417
+ }
418
+ if (windows.length > 0) {
419
+ const names = windows.map((window, index) => {
420
+ const bar = sceneBar(window, meta, index);
421
+ return bar === null ? window.name : `${window.name} from bar ${bar}`;
422
+ });
423
+ parts.push(`Scene lane: ${names.join('; ')}`);
424
+ }
425
+ return `${parts.join('; ')}.`;
426
+ }
427
+
428
+ function syncDisclosures() {
429
+ if (scenesDetails) {
430
+ if (scenesLabel) scenesLabel.textContent = `scenes ${windows.length}`;
431
+ if (scenesAction) scenesAction.textContent = scenesDetails.open ? 'hide' : 'show';
432
+ }
433
+ if (controlsDetails) {
434
+ const label = controlsDetails.open ? `controls ${controls.length}` : heldSummary(controls, [...held.keys()]);
435
+ if (controlsLabel) controlsLabel.textContent = label;
436
+ if (controlsAction) controlsAction.textContent = controlsDetails.open ? 'hide' : 'show';
437
+ }
438
+ }
439
+
440
+ function persistDisclosures() {
441
+ if (typeof browserHistory?.replaceState !== 'function') return;
442
+ const params = new URLSearchParams(browserLocation?.search ?? '');
443
+ if (windows.length > 0) params.set('scenes', scenesDetails?.open ? '1' : '0');
444
+ if (controls.length > 0) params.set('controls', controlsDetails?.open ? '1' : '0');
445
+ const search = params.toString();
446
+ const pathname = browserLocation?.pathname ?? '';
447
+ const hash = browserLocation?.hash ?? '';
448
+ browserHistory.replaceState({}, '', `${pathname}${search === '' ? '' : `?${search}`}${hash}`);
449
+ }
450
+
451
+ function updateCue() {
452
+ if (!scenesWrap || !scenesRow) return;
453
+ const more = scenesRow.scrollWidth > scenesRow.clientWidth + 1
454
+ && scenesRow.scrollLeft + scenesRow.clientWidth < scenesRow.scrollWidth - 1;
455
+ scenesWrap.classList.toggle('is-scrollable-right', more);
456
+ }
457
+
458
+ // Reveal the current chip by scrolling the chip row alone. scrollIntoView
459
+ // would also scroll every scrollable ancestor, including the page: on first
460
+ // load the row sits below the fold, so asking the browser to show the chip
461
+ // moved scrollY off zero and clipped the stage. The row is the only thing
462
+ // that may move.
463
+ function revealCurrentChip(chip) {
464
+ if (!scenesRow || !chip) return;
465
+ const rowLeft = numberFrom(scenesRow.scrollLeft, 0);
466
+ const rowWidth = numberFrom(scenesRow.clientWidth, 0);
467
+ const left = numberFrom(chip.offsetLeft, 0);
468
+ const width = numberFrom(chip.offsetWidth, 0);
469
+ if (!(rowWidth > 0) || !(width > 0)) return;
470
+ if (left < rowLeft) {
471
+ scenesRow.scrollLeft = Math.max(0, left - 16);
472
+ } else if (left + width > rowLeft + rowWidth) {
473
+ scenesRow.scrollLeft = left + width - rowWidth + 16;
474
+ }
475
+ }
476
+
477
+ function buildScenesSurface() {
478
+ if (windows.length === 0) return null;
479
+ const details = document.createElement('details');
480
+ details.className = 'disclosure disclosure--scenes';
481
+ details.open = scenesOpen;
482
+ const summary = document.createElement('summary');
483
+ summary.className = 'disclosure__summary';
484
+ scenesLabel = document.createElement('span');
485
+ scenesLabel.className = 'disclosure__label';
486
+ scenesLabel.textContent = `scenes ${windows.length}`;
487
+ scenesAction = document.createElement('span');
488
+ scenesAction.className = 'disclosure__action';
489
+ summary.append(scenesLabel, scenesAction);
490
+ const wrap = document.createElement('div');
491
+ wrap.className = 'scenes-wrap';
492
+ scenesWrap = wrap;
493
+ const row = document.createElement('div');
494
+ row.className = 'scenes';
495
+ row.setAttribute('role', 'group');
496
+ row.setAttribute('aria-label', 'Scenes');
497
+ scenesRow = row;
498
+ sceneChips = windows.map((window, index) => {
499
+ const chip = document.createElement('button');
500
+ chip.type = 'button';
501
+ chip.className = 'scene-chip';
502
+ chip.dataset.playerControl = 'scene';
503
+ const bar = sceneBar(window, meta, index);
504
+ const name = document.createElement('span');
505
+ name.className = 'scene-chip__name';
506
+ name.textContent = window.name;
507
+ const barSpan = document.createElement('span');
508
+ barSpan.className = 'scene-chip__bar';
509
+ barSpan.textContent = bar === null ? '' : ` · bar ${bar}`;
510
+ const current = document.createElement('span');
511
+ current.className = 'scene-chip__current';
512
+ current.textContent = '\u00a0current';
513
+ chip.append(name, barSpan, current);
514
+ chip.setAttribute(
515
+ 'aria-label',
516
+ compact
517
+ ? `${window.name}${bar === null ? '' : ` · bar ${bar}`} · ${(window.start / 100).toFixed(2)} s`
518
+ : `${window.name}${bar === null ? '' : ` · bar ${bar}`}`,
519
+ );
520
+ chip.dataset.start = String(window.start);
521
+ chip.addEventListener('click', () => {
522
+ if (lastState === 'loading' || lastState === 'error') return;
523
+ if (lastTick === window.start) return;
524
+ performSeek(window.start);
525
+ });
526
+ return chip;
527
+ });
528
+ row.append(...sceneChips);
529
+ const cue = document.createElement('span');
530
+ cue.className = 'scenes__cue';
531
+ cue.setAttribute('aria-hidden', 'true');
532
+ wrap.append(row, cue);
533
+ details.append(summary, wrap);
534
+ details.addEventListener('toggle', () => {
535
+ if (suppressToggle) return;
536
+ scenesOpen = details.open;
537
+ syncDisclosures();
538
+ persistDisclosures();
539
+ applyRulerHeight();
540
+ if (details.open) {
541
+ lastCurrentKey = null;
542
+ updateCurrentScenes();
543
+ }
544
+ updateCue();
545
+ draw();
546
+ });
547
+ row.addEventListener('scroll', updateCue);
548
+ return details;
549
+ }
550
+
551
+ function buildControlsSurface() {
552
+ if (controls.length === 0) return null;
553
+ const details = document.createElement('details');
554
+ details.className = 'disclosure disclosure--controls';
555
+ details.open = controlsOpen;
556
+ const summary = document.createElement('summary');
557
+ summary.className = 'disclosure__summary';
558
+ controlsLabel = document.createElement('span');
559
+ controlsLabel.className = 'disclosure__label';
560
+ controlsAction = document.createElement('span');
561
+ controlsAction.className = 'disclosure__action';
562
+ summary.append(controlsLabel, controlsAction);
563
+ const content = document.createElement('div');
564
+ content.className = 'controls';
565
+ const grid = document.createElement('div');
566
+ grid.className = 'controls__grid';
567
+ grid.setAttribute('role', 'group');
568
+ grid.setAttribute('aria-label', 'Piece controls');
569
+ controls.forEach((descriptor, index) => {
570
+ grid.append(buildControlWidget(descriptor, index));
571
+ });
572
+ content.append(grid);
573
+ details.append(summary, content);
574
+ details.addEventListener('toggle', () => {
575
+ if (suppressToggle) return;
576
+ controlsOpen = details.open;
577
+ syncDisclosures();
578
+ persistDisclosures();
579
+ });
580
+ return details;
581
+ }
582
+
583
+ function buildControlWidget(descriptor, index) {
584
+ const widget = {
585
+ descriptor,
586
+ inputs: [],
587
+ axisValues: [],
588
+ valueElement: null,
589
+ heldElement: null,
590
+ scoreElement: null,
591
+ swatch: null,
592
+ followScore: false,
593
+ heldId: `${mountId}-${index}-held`,
594
+ scoreId: `${mountId}-${index}-score`,
595
+ element: document.createElement('div'),
596
+ };
597
+ const control = widget.element;
598
+ control.className = `control control--${descriptor.kind}`;
599
+ control.dataset.control = descriptor.id;
600
+
601
+ const head = document.createElement('div');
602
+ head.className = 'control__head';
603
+ const label = document.createElement('span');
604
+ label.className = 'control__label';
605
+ label.textContent = descriptor.id;
606
+ head.append(label);
607
+ if (descriptor.name === null) {
608
+ const hint = document.createElement('span');
609
+ hint.className = 'control__hint';
610
+ hint.textContent = 'expr only';
611
+ head.append(hint);
612
+ }
613
+ if (descriptor.kind !== 'numeric') {
614
+ widget.valueElement = document.createElement('span');
615
+ widget.valueElement.className = 'control__value';
616
+ widget.valueElement.textContent = formatLanes(descriptor.value);
617
+ head.append(widget.valueElement);
618
+ }
619
+ widget.heldElement = document.createElement('span');
620
+ widget.heldElement.className = 'control__held';
621
+ widget.heldElement.id = widget.heldId;
622
+ widget.heldElement.textContent = 'held';
623
+ widget.heldElement.hidden = true;
624
+ widget.scoreElement = document.createElement('span');
625
+ widget.scoreElement.className = 'control__score';
626
+ widget.scoreElement.id = widget.scoreId;
627
+ widget.scoreElement.hidden = true;
628
+ head.append(widget.heldElement, widget.scoreElement);
629
+ control.append(head);
630
+
631
+ const addRange = (lane, min, max, value, suffix = '') => {
632
+ const input = document.createElement('input');
633
+ input.type = 'range';
634
+ input.className = 'control__range';
635
+ input.min = String(min);
636
+ input.max = String(max);
637
+ input.step = String(stepFor(min, max));
638
+ input.value = String(value);
639
+ input.dataset.lane = String(lane);
640
+ input.setAttribute('aria-label', suffix === '' ? descriptor.id : `${descriptor.id} ${suffix}`);
641
+ input.setAttribute('aria-valuetext', formatLane(value));
642
+ listenToInput(widget, input, lane);
643
+ widget.inputs[lane] = { input, lane };
644
+ return input;
645
+ };
646
+
647
+ if (descriptor.kind === 'numeric') {
648
+ const box = document.createElement('label');
649
+ box.className = 'control__number-box';
650
+ const input = document.createElement('input');
651
+ input.type = 'number';
652
+ input.className = 'control__number';
653
+ input.step = 'any';
654
+ input.value = String(descriptor.value[0] ?? 0);
655
+ input.dataset.lane = '0';
656
+ input.setAttribute('aria-label', descriptor.id);
657
+ input.setAttribute('aria-valuetext', formatLane(input.value));
658
+ listenToInput(widget, input, 0);
659
+ widget.inputs[0] = { input, lane: 0 };
660
+ box.append(input);
661
+ control.append(box);
662
+ } else if (descriptor.kind === 'slider') {
663
+ control.append(addRange(0, descriptor.min[0], descriptor.max[0], descriptor.value[0]));
664
+ } else if (descriptor.kind === 'xy') {
665
+ for (let lane = 0; lane < 2; lane += 1) {
666
+ const axis = document.createElement('div');
667
+ axis.className = 'control__axis';
668
+ const axisLabel = document.createElement('span');
669
+ axisLabel.className = 'control__axis-label';
670
+ axisLabel.textContent = lane === 0 ? 'x' : 'y';
671
+ const value = document.createElement('span');
672
+ value.className = 'control__axis-value';
673
+ value.textContent = formatLane(descriptor.value[lane]);
674
+ widget.axisValues.push({ lane, element: value });
675
+ const input = addRange(
676
+ lane,
677
+ descriptor.min[lane],
678
+ descriptor.max[lane],
679
+ descriptor.value[lane],
680
+ lane === 0 ? 'x' : 'y',
681
+ );
682
+ axis.append(axisLabel, input, value);
683
+ control.append(axis);
684
+ }
685
+ } else if (descriptor.kind === 'color') {
686
+ widget.swatch = document.createElement('span');
687
+ widget.swatch.className = 'control__swatch';
688
+ widget.swatch.setAttribute('aria-hidden', 'true');
689
+ head.append(widget.swatch);
690
+ const labels = ['r', 'g', 'b', 'a'];
691
+ for (let lane = 0; lane < descriptor.lanes; lane += 1) {
692
+ const axis = document.createElement('div');
693
+ axis.className = 'control__axis';
694
+ const axisLabel = document.createElement('span');
695
+ axisLabel.className = 'control__axis-label';
696
+ axisLabel.textContent = labels[lane] ?? String(lane + 1);
697
+ const value = document.createElement('span');
698
+ value.className = 'control__axis-value';
699
+ value.textContent = formatLane(descriptor.value[lane]);
700
+ widget.axisValues.push({ lane, element: value });
701
+ const input = addRange(
702
+ lane,
703
+ descriptor.min[lane],
704
+ descriptor.max[lane],
705
+ descriptor.value[lane],
706
+ labels[lane] ?? String(lane + 1),
707
+ );
708
+ axis.append(axisLabel, input, value);
709
+ control.append(axis);
710
+ }
711
+ }
712
+
713
+ controlWidgets.push(widget);
714
+ return control;
715
+ }
716
+
717
+ function widgetValue(widget) {
718
+ return widget.inputs.map(({ input }) => numberFrom(input.value, 0));
719
+ }
720
+
721
+ function holdWidget(widget) {
722
+ if (lastState === 'loading' || lastState === 'error') return;
723
+ const id = widget.descriptor.id;
724
+ widget.followScore = false;
725
+ held.set(id, widgetValue(widget));
726
+ try {
727
+ const pending = actions.holdControl?.(id, [...held.get(id)]);
728
+ pending?.catch?.(() => {});
729
+ } catch {
730
+ // The show's own failure surface is the report.
731
+ }
732
+ refreshControlDisplays();
733
+ }
734
+
735
+ function updateWidget(widget) {
736
+ const id = widget.descriptor.id;
737
+ if (!held.has(id)) holdWidget(widget);
738
+ else {
739
+ held.set(id, widgetValue(widget));
740
+ try {
741
+ const pending = actions.holdControl?.(id, [...held.get(id)]);
742
+ pending?.catch?.(() => {});
743
+ } catch {
744
+ // The show's own failure surface is the report.
745
+ }
746
+ refreshControlDisplays();
747
+ }
748
+ }
749
+
750
+ function releaseWidget(widget) {
751
+ const id = widget.descriptor.id;
752
+ if (!held.has(id)) return;
753
+ held.delete(id);
754
+ widget.followScore = true;
755
+ try {
756
+ const pending = actions.releaseControl?.(id);
757
+ pending?.catch?.(() => {});
758
+ } catch {
759
+ // The show's own failure surface is the report.
760
+ }
761
+ const scoreRaw = actions.scoreValue?.(id);
762
+ if (scoreRaw !== undefined && scoreRaw !== null) {
763
+ const scoreLanes = Array.isArray(scoreRaw) ? scoreRaw : [scoreRaw];
764
+ widget.inputs.forEach(({ input, lane }) => {
765
+ input.value = String(numberFrom(scoreLanes[lane], numberFrom(scoreLanes[0], input.value)));
766
+ });
767
+ }
768
+ refreshControlDisplays();
769
+ }
770
+
771
+ function listenToInput(widget, input, lane) {
772
+ const id = widget.descriptor.id;
773
+ input.addEventListener('pointerdown', () => {
774
+ pointerHeld.add(id);
775
+ holdWidget(widget);
776
+ });
777
+ input.addEventListener('input', () => updateWidget(widget));
778
+ // A range's `change` can land after the document's pointerup or after the
779
+ // input's blur. It must never re-pin a control the release already
780
+ // returned to the score: only an existing hold is updated here.
781
+ input.addEventListener('change', () => {
782
+ if (held.has(id)) updateWidget(widget);
783
+ });
784
+ input.addEventListener('focus', () => holdWidget(widget));
785
+ input.addEventListener('blur', (event) => {
786
+ if (widget.element.contains(event.relatedTarget)) return;
787
+ releaseWidget(widget);
788
+ });
789
+ input.addEventListener('keydown', (event) => {
790
+ if (event.key === 'Escape') {
791
+ event.preventDefault?.();
792
+ releaseWidget(widget);
793
+ }
794
+ });
795
+ input.dataset.lane = String(lane);
796
+ }
797
+
798
+ function refreshControlDisplays() {
799
+ for (const widget of controlWidgets) {
800
+ const id = widget.descriptor.id;
801
+ const isHeld = held.has(id);
802
+ const scoreRaw = actions.scoreValue?.(id);
803
+ const score = firstLane(scoreRaw);
804
+ const hasScore = Number.isFinite(numberFrom(score, NaN));
805
+
806
+ if (isHeld) {
807
+ const pinned = held.get(id) ?? [];
808
+ widget.inputs.forEach(({ input, lane }) => {
809
+ input.value = String(pinned[lane] ?? 0);
810
+ });
811
+ } else if (widget.followScore && hasScore) {
812
+ const scoreLanes = Array.isArray(scoreRaw) ? scoreRaw : [scoreRaw];
813
+ widget.inputs.forEach(({ input, lane }) => {
814
+ input.value = String(numberFrom(scoreLanes[lane], numberFrom(scoreLanes[0], input.value)));
815
+ });
816
+ }
817
+
818
+ const current = widgetValue(widget);
819
+ if (widget.valueElement) {
820
+ widget.valueElement.textContent = formatLanes(isHeld ? held.get(id) : current);
821
+ }
822
+ widget.heldElement.hidden = !isHeld;
823
+ widget.scoreElement.hidden = !isHeld || !hasScore;
824
+ widget.scoreElement.textContent = isHeld && hasScore ? `score ${formatLane(score)}` : '';
825
+ widget.inputs.forEach(({ input, lane }) => {
826
+ if (isHeld) {
827
+ input.setAttribute(
828
+ 'aria-valuetext',
829
+ `${formatLane(held.get(id)?.[lane])}, held${hasScore ? `; score ${formatLane(score)}` : ''}`,
830
+ );
831
+ input.setAttribute('aria-describedby', hasScore
832
+ ? `${widget.heldId} ${widget.scoreId}`
833
+ : widget.heldId);
834
+ } else {
835
+ input.setAttribute('aria-valuetext', formatLane(current[lane]));
836
+ input.removeAttribute('aria-describedby');
837
+ }
838
+ });
839
+ if (widget.swatch) {
840
+ const rgb = current.slice(0, 3).map((value) => Math.round(clamp(numberFrom(value, 0), 0, 1) * 255));
841
+ widget.swatch.style.background = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
842
+ }
843
+ for (const axis of widget.axisValues) {
844
+ axis.element.textContent = formatLane(current[axis.lane]);
845
+ }
846
+ }
847
+ if (controlsDetails) {
848
+ controlsLabel.textContent = controlsDetails.open
849
+ ? `controls ${controls.length}`
850
+ : heldSummary(controls, [...held.keys()]);
851
+ controlsAction.textContent = controlsDetails.open ? 'hide' : 'show';
852
+ }
853
+ }
854
+
855
+ function reapplyHolds() {
856
+ for (const [id, value] of held) {
857
+ try {
858
+ const pending = actions.holdControl?.(id, [...value]);
859
+ pending?.catch?.(() => {});
860
+ } catch {
861
+ // The show's own failure surface is the report.
862
+ }
863
+ }
864
+ refreshControlDisplays();
865
+ }
866
+
867
+ function performSeek(tick) {
868
+ let pending;
869
+ try {
870
+ pending = Promise.resolve(actions.seek?.(tick));
871
+ } catch {
872
+ pending = Promise.resolve();
873
+ }
874
+ return pending.catch(() => {}).finally(() => {
875
+ if (destroyed) return;
876
+ reapplyHolds();
877
+ updateText();
878
+ draw();
879
+ });
880
+ }
881
+
882
+ function releasePointerHolds() {
883
+ if (pointerHeld.size === 0) return;
884
+ for (const id of [...pointerHeld]) {
885
+ pointerHeld.delete(id);
886
+ const widget = controlWidgets.find((candidate) => candidate.descriptor.id === id);
887
+ if (widget) releaseWidget(widget);
888
+ }
889
+ }
890
+
891
+ function rulerHeight() {
892
+ return sceneRulerHeight(windows, scenesOpen);
893
+ }
894
+
895
+ function applyRulerHeight() {
896
+ const height = rulerHeight();
897
+ track.style.height = `${height}px`;
898
+ canvas.style.height = `${height}px`;
899
+ range.style.height = `${height}px`;
900
+ }
901
+
902
+ function updateCurrentScenes() {
903
+ let currentKey = '';
904
+ sceneChips.forEach((chip, index) => {
905
+ const window = windows[index];
906
+ const current = lastTick >= window.start && lastTick < window.end;
907
+ chip.classList.toggle('current', current);
908
+ if (current) chip.setAttribute('aria-current', 'true');
909
+ else chip.removeAttribute('aria-current');
910
+ currentKey += current ? '1' : '0';
911
+ });
912
+ if (currentKey === lastCurrentKey) return;
913
+ lastCurrentKey = currentKey;
914
+ const first = sceneChips.find((chip) => chip.classList.contains('current'));
915
+ revealCurrentChip(first);
916
+ updateCue();
917
+ }
918
+
919
+ function prepare() {
920
+ const width = track.clientWidth || canvas.getBoundingClientRect?.().width || 0;
921
+ if (width < 1) return null;
922
+ const height = rulerHeight();
923
+ applyRulerHeight();
924
+ const dpr = Math.min(globalThis.devicePixelRatio || 1, DPR_MAX);
925
+ const backingWidth = Math.max(1, Math.round(width * dpr));
926
+ const backingHeight = Math.max(1, Math.round(height * dpr));
927
+ if (canvas.width !== backingWidth) canvas.width = backingWidth;
928
+ if (canvas.height !== backingHeight) canvas.height = backingHeight;
929
+ const ctx = canvas.getContext?.('2d');
930
+ if (!ctx) return null;
931
+ prepared = { ctx, width, height, dpr };
932
+ return prepared;
933
+ }
934
+
935
+ function paletteFor() {
936
+ if (!forcedQuery?.matches) return COLOR;
937
+ if (!probeElements) {
938
+ probeElements = {};
939
+ probeHost = document.createElement('div');
940
+ probeHost.hidden = true;
941
+ probeHost.className = 'color-probes';
942
+ for (const name of ['Canvas', 'CanvasText', 'GrayText', 'Highlight']) {
943
+ const probe = document.createElement('span');
944
+ probe.style.color = name;
945
+ probeHost.append(probe);
946
+ probeElements[name] = probe;
947
+ }
948
+ (document.body ?? host).append(probeHost);
949
+ }
950
+ const read = (name, fallback) => {
951
+ const value = globalThis.getComputedStyle?.(probeElements[name])?.color;
952
+ return value || fallback;
953
+ };
954
+ const canvasColor = read('Canvas', COLOR.label);
955
+ const textColor = read('CanvasText', COLOR.text);
956
+ const gray = read('GrayText', COLOR.label);
957
+ return {
958
+ quarter: gray,
959
+ bar: gray,
960
+ track: gray,
961
+ label: gray,
962
+ text: textColor,
963
+ scoreEnd: gray,
964
+ accent: read('Highlight', COLOR.accent),
965
+ muted: gray,
966
+ canvas: canvasColor,
967
+ forced: true,
968
+ };
969
+ }
970
+
971
+ function drawSceneLane(ctx, palette, width, xOf) {
972
+ if (!scenesOpen) return;
973
+ const { lanes } = layoutSceneLanes(windows);
974
+ for (const { window, lane } of lanes) {
975
+ const startX = xOf(window.start / 100);
976
+ const endX = xOf(window.end / 100);
977
+ const visibleStart = Math.max(0, startX);
978
+ const visibleEnd = Math.min(width, endX);
979
+ const markTop = SCENE_TOP + 4 + lane * SCENE_SUBLANE;
980
+ const baselineY = SCENE_TOP + 20 + lane * SCENE_SUBLANE;
981
+ const labelY = SCENE_TOP + 16 + lane * SCENE_SUBLANE;
982
+
983
+ if (visibleEnd > visibleStart) {
984
+ ctx.fillStyle = palette.track;
985
+ ctx.fillRect(Math.round(visibleStart), baselineY, Math.max(1, Math.round(visibleEnd - visibleStart)), 1);
986
+ }
987
+ if (startX >= 0 && startX < width) verticalLine(ctx, startX, markTop, 16, palette.muted);
988
+ if (endX >= 0 && endX < width) verticalLine(ctx, endX, markTop, 16, palette.muted);
989
+
990
+ ctx.font = FONT;
991
+ ctx.fillStyle = palette.muted;
992
+ ctx.textAlign = 'left';
993
+ ctx.textBaseline = 'alphabetic';
994
+ const labelWidth = ctx.measureText(window.name).width;
995
+ const labelX = startX >= 0 ? startX + 4 : Math.max(4, visibleStart + 4);
996
+ if (labelX + labelWidth + 4 <= visibleEnd && labelX + labelWidth <= width) {
997
+ ctx.fillText(window.name, labelX, labelY);
998
+ }
999
+ }
1000
+ }
1001
+
1002
+ function draw() {
1003
+ const surface = prepare();
1004
+ if (!surface) return;
1005
+ const { ctx, width, height, dpr } = surface;
1006
+ const palette = paletteFor();
1007
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
1008
+ if (palette.forced) {
1009
+ ctx.fillStyle = palette.canvas;
1010
+ ctx.fillRect(0, 0, width, height);
1011
+ } else {
1012
+ ctx.clearRect(0, 0, width, height);
1013
+ }
1014
+
1015
+ const centre = width / 2;
1016
+ const at = drag ? drag.proposed : lastTick / 100;
1017
+ const committed = drag ? drag.startValue : null;
1018
+ const xOf = (value) => centre + (value - at) * SCALE;
1019
+
1020
+ // Quarter ticks (8 px on the 32–40 baseline) and bar lines (26 px from
1021
+ // 14 to 40), both stopping at the score's own end. A phone loses the
1022
+ // quarter ticks first and keeps every bar line, with every second number.
1023
+ if (width >= QUARTER_MIN_WIDTH) {
1024
+ for (let beat = 0; beat < 10000; beat += 1) {
1025
+ const time = timeAtBeat(model, beat);
1026
+ if (!(time < scoreEndSeconds - EPS)) break;
1027
+ const x = xOf(time);
1028
+ if (x >= 0 && x < width) verticalLine(ctx, x, 32, 8, palette.quarter);
1029
+ }
1030
+ }
1031
+
1032
+ const bars = [];
1033
+ for (let barIndex = 0; barIndex < 10000; barIndex += 1) {
1034
+ const time = timeAtBeat(model, barIndex * model.beatsPerBar);
1035
+ if (!(time < scoreEndSeconds - EPS)) break;
1036
+ const x = xOf(time);
1037
+ if (x >= 0 && x < width) {
1038
+ verticalLine(ctx, x, 14, 26, palette.bar);
1039
+ bars.push({ number: barIndex + 1, x });
1040
+ }
1041
+ }
1042
+
1043
+ // Bar numbers in the top lane, 3 px from their line; a number that would
1044
+ // cross the fixed playhead's ±12 px column is skipped rather than clipped.
1045
+ ctx.font = FONT;
1046
+ ctx.fillStyle = palette.label;
1047
+ ctx.textBaseline = 'alphabetic';
1048
+ for (const bar of bars) {
1049
+ if (width < QUARTER_MIN_WIDTH && bar.number % 2 === 0) continue;
1050
+ const label = String(bar.number);
1051
+ const labelWidth = ctx.measureText(label).width;
1052
+ const right = Math.round(bar.x) + 3;
1053
+ const left = Math.round(bar.x) - 3;
1054
+ const useRight = right + labelWidth <= width;
1055
+ const textX = useRight ? right : left;
1056
+ const spanLeft = useRight ? textX : textX - labelWidth;
1057
+ const spanRight = useRight ? textX + labelWidth : textX;
1058
+ if (spanLeft < 0 || spanRight > width) continue;
1059
+ if (spanLeft < centre + 12 && spanRight > centre - 12) continue;
1060
+ ctx.textAlign = useRight ? 'left' : 'right';
1061
+ ctx.fillText(label, textX, 10);
1062
+ }
1063
+
1064
+ // The track is the piece's own extent, never the host tail.
1065
+ const trackStart = Math.max(0, Math.round(xOf(0)));
1066
+ const trackEnd = Math.min(width, Math.round(xOf(scoreEndSeconds)));
1067
+ if (trackEnd > trackStart) {
1068
+ ctx.fillStyle = palette.track;
1069
+ ctx.fillRect(trackStart, 39, trackEnd - trackStart, 1);
1070
+ }
1071
+
1072
+ // The score end and the hold gap to the host end.
1073
+ const scoreEndX = xOf(scoreEndSeconds);
1074
+ if (scoreEndX >= 0 && scoreEndX < width) verticalLine(ctx, scoreEndX, 14, 26, palette.scoreEnd);
1075
+ const hostEndX = xOf(hostSeconds);
1076
+ if (scoreEndSeconds < hostSeconds - EPS && scoreEndX >= 0 && hostEndX > scoreEndX) {
1077
+ const mid = (scoreEndX + Math.min(width, hostEndX)) / 2;
1078
+ ctx.font = FONT;
1079
+ ctx.fillStyle = palette.label;
1080
+ ctx.textAlign = 'center';
1081
+ ctx.textBaseline = 'alphabetic';
1082
+ const labelWidth = ctx.measureText('hold').width;
1083
+ if (mid - labelWidth / 2 >= 0 && mid + labelWidth / 2 <= width) ctx.fillText('hold', mid, 36);
1084
+ }
1085
+
1086
+ // A decoded soundtrack shorter than the host ends in silence; the
1087
+ // boundary is the decode's own measurement and the playhead continues.
1088
+ // A tail that rounds away at the seek quantum is not drawn at all.
1089
+ if (audioEnd !== null) {
1090
+ const audioX = xOf(audioEnd);
1091
+ if (audioX >= 0 && audioX < width) verticalLine(ctx, audioX, 14, 26, palette.scoreEnd);
1092
+ ctx.font = FONT;
1093
+ ctx.fillStyle = palette.muted;
1094
+ ctx.textAlign = 'left';
1095
+ ctx.textBaseline = 'alphabetic';
1096
+ const label = 'silence →';
1097
+ const labelWidth = ctx.measureText(label).width;
1098
+ const labelX = clamp(audioX + 4, 4, width);
1099
+ if (labelX + labelWidth <= width) ctx.fillText(label, labelX, 36);
1100
+ }
1101
+
1102
+ if (scenesOpen && windows.length > 0) drawSceneLane(ctx, palette, width, xOf);
1103
+
1104
+ // The committed moment stays visible while the grid moves under it.
1105
+ if (committed !== null) {
1106
+ const committedX = xOf(committed);
1107
+ if (committedX < 0) edgeBracket(ctx, width, 'left', 11, palette.muted);
1108
+ else if (committedX > width) edgeBracket(ctx, width, 'right', 11, palette.muted);
1109
+ else {
1110
+ verticalLine(ctx, committedX, 14, 26, palette.muted);
1111
+ hollowCap(ctx, committedX, 11, 7, palette.muted);
1112
+ }
1113
+ }
1114
+
1115
+ // The playhead never moves: 2 px at the exact centre plus the 11 × 3 cap.
1116
+ ctx.fillStyle = palette.accent;
1117
+ ctx.fillRect(centre - 1, 0, 2, height);
1118
+ ctx.fillRect(centre - 5.5, 0, 11, 3);
1119
+
1120
+ // Tempo changes keep their diamond in the top lane and carry their own
1121
+ // label; the bar lines behind them were already spaced by the new tempo.
1122
+ for (let index = 1; index < model.segments.length; index += 1) {
1123
+ const point = model.segments[index];
1124
+ if (!(point.startTick > 0)) continue;
1125
+ const pointX = xOf(point.startSeconds);
1126
+ if (pointX < -4 || pointX > width + 4) continue;
1127
+ ctx.fillStyle = palette.accent;
1128
+ ctx.beginPath();
1129
+ ctx.moveTo(pointX, 12);
1130
+ ctx.lineTo(pointX + 3.5, 15.5);
1131
+ ctx.lineTo(pointX, 19);
1132
+ ctx.lineTo(pointX - 3.5, 15.5);
1133
+ ctx.closePath();
1134
+ ctx.fill();
1135
+ const bpm = Number.isInteger(point.bpm) ? point.bpm : point.bpm.toFixed(1);
1136
+ const label = `${bpm} BPM`;
1137
+ ctx.font = FONT;
1138
+ ctx.fillStyle = palette.text;
1139
+ ctx.textAlign = 'left';
1140
+ ctx.textBaseline = 'middle';
1141
+ const labelX = pointX + 14;
1142
+ if (labelX >= 0 && labelX + ctx.measureText(label).width <= width) ctx.fillText(label, labelX, 15.5);
1143
+ }
1144
+ }
1145
+
1146
+ function updateText() {
1147
+ const loading = lastState === 'loading' || lastState === 'error';
1148
+ const at = drag ? drag.proposed : lastTick / 100;
1149
+ const frame = drag ? drag.startValue : lastTick / 100;
1150
+
1151
+ if (loading) {
1152
+ writeReadout(positionElement, '—');
1153
+ writeReadout(elapsedElement, '—');
1154
+ range.setAttribute('aria-valuetext', 'Show position unavailable');
1155
+ return;
1156
+ }
1157
+
1158
+ writeReadout(positionElement, formatPosition(Math.round(at * 100), meta));
1159
+ if (drag) {
1160
+ writeReadout(elapsedElement, `frame ${frame.toFixed(2)} s → seek ${at.toFixed(2)} s · release`);
1161
+ range.setAttribute('aria-valuetext', ariaDuringDrag(at, frame, meta));
1162
+ } else {
1163
+ writeReadout(elapsedElement, formatElapsed(at, hostSeconds));
1164
+ range.setAttribute('aria-valuetext', ariaAt(at, hostSeconds, meta));
1165
+ }
1166
+ }
1167
+
1168
+ function applyBusy() {
1169
+ const blocked = busy || lastState === 'loading' || lastState === 'error';
1170
+ range.disabled = blocked;
1171
+ device.disabled = blocked;
1172
+ for (const chip of sceneChips) chip.disabled = blocked;
1173
+ for (const widget of controlWidgets) {
1174
+ for (const { input } of widget.inputs) input.disabled = blocked;
1175
+ }
1176
+ track.classList?.toggle('is-busy', busy);
1177
+ }
1178
+
1179
+ function setBusy(value) {
1180
+ busy = Boolean(value);
1181
+ applyBusy();
1182
+ }
1183
+
1184
+ function setTransition(text) {
1185
+ const match = /holding ([\d.]+) s/.exec(String(text ?? ''));
1186
+ if (!match) {
1187
+ holdingNote.hidden = true;
1188
+ holdingNote.textContent = '';
1189
+ return;
1190
+ }
1191
+ holdingNote.textContent = `holding ${match[1]} s while the renderer rebuilds`;
1192
+ holdingNote.hidden = false;
1193
+ }
1194
+
1195
+ function render(state, tick) {
1196
+ const nextState = typeof state === 'string' ? state : lastState;
1197
+ // restart() clears every held control by design; the chrome must not keep
1198
+ // painting a pin the score no longer has. A seek keeps the pin and
1199
+ // performSeek() re-applies it. A device flip's restart announces READY
1200
+ // while the transport is busy: the chrome's own pin is the one the flip
1201
+ // will re-apply after the seek, so only an idle READY clears it.
1202
+ if (nextState === 'error'
1203
+ || (!busy && nextState === 'ready' && lastState !== 'ready' && lastState !== 'loading')) {
1204
+ held.clear();
1205
+ pointerHeld.clear();
1206
+ if (nextState === 'ready') {
1207
+ for (const widget of controlWidgets) {
1208
+ widget.followScore = false;
1209
+ widget.inputs.forEach(({ input, lane }) => {
1210
+ input.value = String(widget.descriptor.value[lane] ?? 0);
1211
+ });
1212
+ }
1213
+ }
1214
+ }
1215
+ lastState = nextState;
1216
+ lastTick = Math.max(0, numberFrom(tick, lastTick));
1217
+ if (!drag) range.value = (lastTick / 100).toFixed(2);
1218
+ applyBusy();
1219
+ updateCurrentScenes();
1220
+ refreshControlDisplays();
1221
+ updateText();
1222
+ draw();
1223
+ }
1224
+
1225
+ function releaseCapture(id) {
1226
+ try {
1227
+ if (track.hasPointerCapture?.(id)) track.releasePointerCapture(id);
1228
+ } catch {
1229
+ // The pointer may already be gone.
1230
+ }
1231
+ }
1232
+
1233
+ function resumeAfterDrag(finished) {
1234
+ if (!finished.wasPlaying) return;
1235
+ try {
1236
+ const result = actions.resume?.();
1237
+ if (result && typeof result.catch === 'function') result.catch(() => {});
1238
+ } catch {
1239
+ // The show's own error state is the report.
1240
+ }
1241
+ }
1242
+
1243
+ function cancelDrag() {
1244
+ if (!drag) return;
1245
+ const finished = drag;
1246
+ drag = null;
1247
+ releaseCapture(finished.id);
1248
+ range.value = finished.startValue.toFixed(2);
1249
+ updateText();
1250
+ draw();
1251
+ resumeAfterDrag(finished);
1252
+ }
1253
+
1254
+ function onPointerDown(event) {
1255
+ if (drag || range.disabled) return;
1256
+ if (event.isPrimary === false || (event.button !== undefined && event.button !== 0)) return;
1257
+ event.preventDefault?.();
1258
+ const startValue = clamp(numberFrom(range.value, lastTick / 100), 0, hostSeconds);
1259
+ drag = {
1260
+ id: event.pointerId,
1261
+ startX: event.clientX,
1262
+ startValue,
1263
+ proposed: startValue,
1264
+ moved: false,
1265
+ wasPlaying: lastState === 'playing',
1266
+ };
1267
+ try {
1268
+ track.setPointerCapture?.(event.pointerId);
1269
+ } catch {
1270
+ // Capture is an enhancement; the handlers still work inside the ruler.
1271
+ }
1272
+ range.focus?.({ preventScroll: true });
1273
+ if (drag.wasPlaying) {
1274
+ try {
1275
+ const result = actions.pause?.();
1276
+ if (result && typeof result.catch === 'function') result.catch(() => {});
1277
+ } catch {
1278
+ // A denied pause is not the chrome's to report.
1279
+ }
1280
+ }
1281
+ updateText();
1282
+ draw();
1283
+ }
1284
+
1285
+ function onPointerMove(event) {
1286
+ if (!drag || event.pointerId !== drag.id) return;
1287
+ event.preventDefault?.();
1288
+ if (event.clientX !== drag.startX) drag.moved = true;
1289
+ const proposed = clamp(drag.startValue - (event.clientX - drag.startX) / SCALE, 0, hostSeconds);
1290
+ drag.proposed = Math.round(proposed * 100) / 100;
1291
+ range.value = drag.proposed.toFixed(2);
1292
+ updateText();
1293
+ draw();
1294
+ }
1295
+
1296
+ function onPointerUp(event) {
1297
+ if (!drag || event.pointerId !== drag.id) return;
1298
+ const finished = drag;
1299
+ drag = null;
1300
+ releaseCapture(finished.id);
1301
+
1302
+ if (!finished.moved) {
1303
+ range.value = finished.startValue.toFixed(2);
1304
+ updateText();
1305
+ draw();
1306
+ resumeAfterDrag(finished);
1307
+ return;
1308
+ }
1309
+
1310
+ const tick = Math.round(finished.proposed * 100);
1311
+ range.value = (tick / 100).toFixed(2);
1312
+ performSeek(tick).then(() => resumeAfterDrag(finished));
1313
+ }
1314
+
1315
+ function onPointerCancel(event) {
1316
+ if (!drag || event.pointerId !== drag.id) return;
1317
+ cancelDrag();
1318
+ }
1319
+
1320
+ function onLostPointerCapture() {
1321
+ if (drag) cancelDrag();
1322
+ }
1323
+
1324
+ function tickAfterBeats(tick, beats) {
1325
+ const seconds = tick / 100;
1326
+ let segment = model.segments[0];
1327
+ for (const candidate of model.segments) {
1328
+ if (seconds >= candidate.startSeconds - EPS) segment = candidate;
1329
+ else break;
1330
+ }
1331
+ if (!segment) return tick;
1332
+ const beat = segment.startBeat + ((seconds - segment.startSeconds) * segment.bpm) / 60;
1333
+ const target = timeAtBeat(model, beat + beats);
1334
+ return clamp(Math.round(target * 100), 0, Math.round(hostSeconds * 100));
1335
+ }
1336
+
1337
+ function onKeyDown(event) {
1338
+ if (event.key === 'Escape') {
1339
+ if (drag) {
1340
+ event.preventDefault?.();
1341
+ cancelDrag();
1342
+ }
1343
+ return;
1344
+ }
1345
+ if (drag) return;
1346
+ if (event.shiftKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
1347
+ event.preventDefault?.();
1348
+ const tick = tickAfterBeats(Math.round(lastTick), event.key === 'ArrowRight' ? 1 : -1);
1349
+ range.value = (tick / 100).toFixed(2);
1350
+ performSeek(tick);
1351
+ } else if (event.key === 'PageUp' || event.key === 'PageDown') {
1352
+ event.preventDefault?.();
1353
+ const direction = event.key === 'PageUp' ? 1 : -1;
1354
+ const tick = tickAfterBeats(Math.round(lastTick), direction * model.beatsPerBar);
1355
+ range.value = (tick / 100).toFixed(2);
1356
+ performSeek(tick);
1357
+ }
1358
+ }
1359
+
1360
+ function onRangeChange() {
1361
+ if (drag) return;
1362
+ const value = clamp(numberFrom(range.value, lastTick / 100), 0, hostSeconds);
1363
+ const tick = Math.round(value * 100);
1364
+ range.value = (tick / 100).toFixed(2);
1365
+ performSeek(tick);
1366
+ }
1367
+
1368
+ function onResize() {
1369
+ applyRulerHeight();
1370
+ updateCue();
1371
+ draw();
1372
+ }
1373
+
1374
+ function onToggle() {
1375
+ draw();
1376
+ }
1377
+
1378
+ function onDeviceClick() {
1379
+ try {
1380
+ const result = actions.toggleDevice?.(otherDevice(currentDevice));
1381
+ if (result && typeof result.catch === 'function') result.catch(() => {});
1382
+ } catch {
1383
+ // The show's own failure surface is the report.
1384
+ }
1385
+ }
1386
+
1387
+ function setDevice(preset) {
1388
+ const matched = presetFor(preset);
1389
+ if (matched.presetLabel !== String(preset?.presetLabel)) return;
1390
+ currentDevice = matched;
1391
+ syncDeviceLabel();
1392
+ }
1393
+
1394
+ syncDisclosures();
1395
+ refreshControlDisplays();
1396
+ applyBusy();
1397
+
1398
+ function onForcedChange() {
1399
+ draw();
1400
+ }
1401
+
1402
+ device.addEventListener('click', onDeviceClick);
1403
+ track.addEventListener('pointerdown', onPointerDown);
1404
+ track.addEventListener('pointermove', onPointerMove);
1405
+ track.addEventListener('pointerup', onPointerUp);
1406
+ track.addEventListener('pointercancel', onPointerCancel);
1407
+ track.addEventListener('lostpointercapture', onLostPointerCapture);
1408
+ range.addEventListener('keydown', onKeyDown);
1409
+ range.addEventListener('change', onRangeChange);
1410
+ host.addEventListener('toggle', onToggle, true);
1411
+ document.addEventListener?.('pointerup', releasePointerHolds);
1412
+ document.addEventListener?.('pointercancel', releasePointerHolds);
1413
+ forcedQuery?.addEventListener?.('change', onForcedChange);
1414
+
1415
+ let observer = null;
1416
+ if (typeof ResizeObserver === 'function') {
1417
+ observer = new ResizeObserver(onResize);
1418
+ observer.observe(track);
1419
+ }
1420
+ if (typeof globalThis.addEventListener === 'function') globalThis.addEventListener('resize', onResize);
1421
+
1422
+ return {
1423
+ render,
1424
+ resize: onResize,
1425
+ setDevice,
1426
+ setBusy,
1427
+ setTransition,
1428
+ reapplyHolds,
1429
+ destroy() {
1430
+ destroyed = true;
1431
+ observer?.disconnect();
1432
+ if (typeof globalThis.removeEventListener === 'function') globalThis.removeEventListener('resize', onResize);
1433
+ device.removeEventListener('click', onDeviceClick);
1434
+ track.removeEventListener('pointerdown', onPointerDown);
1435
+ track.removeEventListener('pointermove', onPointerMove);
1436
+ track.removeEventListener('pointerup', onPointerUp);
1437
+ track.removeEventListener('pointercancel', onPointerCancel);
1438
+ track.removeEventListener('lostpointercapture', onLostPointerCapture);
1439
+ range.removeEventListener('keydown', onKeyDown);
1440
+ range.removeEventListener('change', onRangeChange);
1441
+ host.removeEventListener('toggle', onToggle, true);
1442
+ document.removeEventListener?.('pointerup', releasePointerHolds);
1443
+ document.removeEventListener?.('pointercancel', releasePointerHolds);
1444
+ forcedQuery?.removeEventListener?.('change', onForcedChange);
1445
+ if (readoutElement.parentNode === timeline) host.insertBefore(readoutElement, timeline);
1446
+ readoutElement.hidden = true;
1447
+ device.remove();
1448
+ timeline.remove();
1449
+ host.classList?.remove?.('panel--transport');
1450
+ scenesDetails?.remove();
1451
+ controlsDetails?.remove();
1452
+ rangeNotes.remove();
1453
+ probeHost?.remove();
1454
+ probeElements = null;
1455
+ probeHost = null;
1456
+ drag = null;
1457
+ prepared = null;
1458
+ },
1459
+ };
1460
+ }