animader-cli 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/player/boot.mjs CHANGED
@@ -8,6 +8,8 @@
8
8
  // One implementation, not two players: the transport, score compile, route
9
9
  // pair and pngine wiring below are the same code on both spellings.
10
10
 
11
+ import { formatElapsed, formatPosition, readoutPieces, readResume, resumeKey, scoreSeconds, showEndSeconds, writeResume } from './controller.mjs';
12
+
11
13
  const canvas = document.getElementById('canvas');
12
14
  const performanceElement = document.getElementById('performance');
13
15
  const stage = document.getElementById('stage');
@@ -25,6 +27,8 @@ let context = null;
25
27
  let port = null;
26
28
  let stageScale = 1;
27
29
  let hostSeconds = null;
30
+ let scoreEndSeconds = null;
31
+ let effectiveSeconds = null;
28
32
  let decodedDuration = null;
29
33
  let reflection = null;
30
34
  let join = null;
@@ -35,9 +39,31 @@ let provenance = null;
35
39
  let manifest = null;
36
40
  let config = null;
37
41
  let activeProfile = null;
42
+ let chrome = null;
43
+ let releaseReadout = null;
38
44
  let renderer = null;
45
+ // The chrome's `score` ghost reads what the last painted frame actually wrote
46
+ // under a pin. Pacer writes controls AFTER tracks so the pin outranks them;
47
+ // the ghost is the last track write before those control entries, not the pin.
48
+ // Keyed by target name, replaced on every frame, never merged.
49
+ const lastWrites = new Map();
39
50
  let rendererError = null;
40
51
  let ShowErrorClass = Error;
52
+ // The two logical output presets. They live here, not in the dev chrome:
53
+ // boot is shared by the release entry and must never import the dev-only
54
+ // surface.
55
+ const DEVICE_DESKTOP = Object.freeze({ presetLabel: 'Desktop · 1280×720', width: 1280, height: 720 });
56
+ const DEVICE_MOBILE = Object.freeze({ presetLabel: 'Mobile · 720×1280', width: 720, height: 1280 });
57
+ const SHOW_TICKS_PER_SECOND = 100;
58
+ // The states whose visible frame is a moment worth restoring. READY is the
59
+ // fresh page (a seek to 0 stays READY anyway); loading and error have no
60
+ // position to keep.
61
+ const RESUME_STATES = new Set(['playing', 'paused', 'press-to-resume', 'ended', 'stopped']);
62
+ let devicePreset = DEVICE_DESKTOP;
63
+ // The preset whose CSS box the stage is currently fitted to. It moves with
64
+ // setDeviceBox (before a flip settles) so an in-flight ResizeObserver callback
65
+ // never reverts the stage to the outgoing orientation.
66
+ let stagePreset = DEVICE_DESKTOP;
41
67
  const hashes = { payload: null, timeline: null, soundtrack: null, score: null, manifest: null };
42
68
 
43
69
  function fallbackFatal(error) {
@@ -100,32 +126,199 @@ function syncFullscreenLabel() {
100
126
  if (secondary) fullscreenButton.textContent = secondaryLabel(secondary.label);
101
127
  }
102
128
 
129
+ // The dev chrome is driven by the actual show state and tick; it owns no
130
+ // clock of its own. While playing, the show's own wake wraps each pump so the
131
+ // readout follows the frame the transport just stepped.
132
+ function renderChrome() {
133
+ if (chrome && show) chrome.render(show.state, show.tick);
134
+ }
135
+
136
+ function pageLocation() {
137
+ return window.location ?? globalThis.location ?? null;
138
+ }
139
+
140
+ /** The session store, or null when the browser exposes or denies nothing. */
141
+ function resumeStorage() {
142
+ try {
143
+ return window.sessionStorage ?? globalThis.sessionStorage ?? null;
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Write the visible moment on the way out (pagehide, and the hidden edge as
151
+ * the belt for engines that skip it). Only the dev profile keeps a moment; a
152
+ * published player has no reload to survive.
153
+ */
154
+ function rememberMoment(profile) {
155
+ if (profile.name !== 'dev' || !show || !RESUME_STATES.has(show.state)) return;
156
+ const location = pageLocation();
157
+ writeResume(resumeStorage(), resumeKey(location?.pathname ?? ''), show.tick);
158
+ }
159
+
160
+ /** The URL's `?t=<seconds>` moment in ticks, or null when malformed. */
161
+ function urlMoment(search) {
162
+ const raw = new URLSearchParams(search ?? '').get('t');
163
+ if (raw === null) return null;
164
+ const text = raw.trim();
165
+ if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) return null;
166
+ const seconds = Number(text);
167
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
168
+ return Math.round(seconds * SHOW_TICKS_PER_SECOND);
169
+ }
170
+
171
+ /**
172
+ * Bring the dev page back to the moment it left: the URL's shareable moment
173
+ * wins over the stored tick, and the show's own seek clamps at the effective
174
+ * end. A position short of the end is the paused still frame; the end itself
175
+ * is the show's terminal `ended` landing. Either way the show never starts or
176
+ * resumes here. The release profile never reads the store.
177
+ */
178
+ async function restoreMoment(profile) {
179
+ if (profile.name !== 'dev' || !show || show.state === 'error') return null;
180
+ const location = pageLocation();
181
+ const fromUrl = urlMoment(location?.search ?? '');
182
+ const tick = fromUrl ?? readResume(resumeStorage(), resumeKey(location?.pathname ?? ''));
183
+ if (tick === null) return null;
184
+ const end = Number.isFinite(show.totalTicks) ? show.totalTicks : Infinity;
185
+ const target = Math.min(end, Math.max(0, Math.round(tick)));
186
+ await show.seek(target);
187
+ return target;
188
+ }
189
+
190
+ // The release player shows the musical position and the elapsed time and
191
+ // nothing else from the dev chrome. This mount fills the one shared #readout
192
+ // row the static markup already carries; it never creates a second element.
193
+ // It owns no clock: it repaints from show.tick on the state announcement and,
194
+ // only while playing, once per animation frame. Pause, stop, end and error
195
+ // all cancel that frame.
196
+ const releaseReadouts = new WeakMap();
197
+
198
+ function writeReadoutPieces(element, pieces) {
199
+ const nodes = pieces.map((piece) => {
200
+ if (typeof piece === 'string') return document.createTextNode(piece);
201
+ const span = document.createElement('span');
202
+ span.className = piece.className;
203
+ span.textContent = piece.text;
204
+ return span;
205
+ });
206
+ element.replaceChildren(...nodes);
207
+ }
208
+
209
+ /**
210
+ * Mount the release readout on the shared row. The same formatters the dev
211
+ * chrome uses make the two spellings identical; a second call answers the
212
+ * first, so a retry cannot duplicate the row or its playing frame.
213
+ */
214
+ export function mountReleaseReadout({
215
+ readout,
216
+ position,
217
+ elapsed,
218
+ show,
219
+ meta = {},
220
+ seconds,
221
+ formatPosition: positionFormatter = formatPosition,
222
+ formatElapsed: elapsedFormatter = formatElapsed,
223
+ requestFrame = (callback) => requestAnimationFrame(callback),
224
+ cancelFrame = (id) => cancelAnimationFrame(id),
225
+ }) {
226
+ if (!readout || !position || !elapsed || !show) {
227
+ throw new TypeError('mountReleaseReadout needs the shared row, its two spans and the show');
228
+ }
229
+ const mounted = releaseReadouts.get(readout);
230
+ if (mounted) return mounted;
231
+
232
+ readout.hidden = false;
233
+ let frame = null;
234
+ let lastPosition = null;
235
+ let lastElapsed = null;
236
+
237
+ function draw() {
238
+ const tick = Number.isFinite(show.tick) ? show.tick : 0;
239
+ const nextPosition = positionFormatter(tick, meta);
240
+ if (nextPosition !== lastPosition) {
241
+ writeReadoutPieces(position, readoutPieces(nextPosition));
242
+ lastPosition = nextPosition;
243
+ }
244
+ const nextElapsed = elapsedFormatter(tick / SHOW_TICKS_PER_SECOND, seconds);
245
+ if (nextElapsed !== lastElapsed) {
246
+ writeReadoutPieces(elapsed, readoutPieces(nextElapsed));
247
+ lastElapsed = nextElapsed;
248
+ }
249
+ }
250
+
251
+ function onFrame() {
252
+ frame = null;
253
+ if (show.state !== 'playing') return;
254
+ draw();
255
+ frame = requestFrame(onFrame);
256
+ }
257
+
258
+ function render(state = show.state) {
259
+ draw();
260
+ if (state === 'playing') {
261
+ if (frame === null) frame = requestFrame(onFrame);
262
+ } else if (frame !== null) {
263
+ cancelFrame(frame);
264
+ frame = null;
265
+ }
266
+ return state;
267
+ }
268
+
269
+ const handle = {
270
+ render,
271
+ get running() { return frame !== null; },
272
+ destroy() {
273
+ if (frame !== null) {
274
+ cancelFrame(frame);
275
+ frame = null;
276
+ }
277
+ releaseReadouts.delete(readout);
278
+ readout.hidden = true;
279
+ },
280
+ };
281
+ releaseReadouts.set(readout, handle);
282
+ render(show.state);
283
+ return handle;
284
+ }
285
+
103
286
  const view = {
104
287
  apply(ui) {
105
288
  statusLine.textContent = ui.status;
106
289
  if (ui.primary) {
107
290
  primaryButton.hidden = false;
108
291
  primaryButton.textContent = ui.primary.label;
292
+ primaryButton.disabled = ui.primary.disabled === true;
109
293
  } else {
110
294
  primaryButton.hidden = true;
295
+ primaryButton.disabled = false;
111
296
  }
112
297
  if (ui.secondary) {
113
298
  fullscreenButton.hidden = false;
114
299
  fullscreenButton.textContent = secondaryLabel(ui.secondary.label);
300
+ fullscreenButton.disabled = ui.secondary.disabled === true;
115
301
  } else {
116
302
  fullscreenButton.hidden = true;
303
+ fullscreenButton.disabled = false;
117
304
  }
118
305
  errorBanner.hidden = !ui.errorVisible;
119
306
  errorMessage.textContent = ui.errorText;
120
307
  diagnostics.hidden = false;
121
308
  renderDiagnostics(ui.diagnostics);
122
309
  diagnostics.open = ui.diagnosticsOpen;
310
+ chrome?.setBusy?.(Boolean(ui.rangeDisabled));
311
+ chrome?.setTransition?.(ui.transition ?? null);
312
+ renderChrome();
123
313
  },
124
314
  activeElement() {
125
315
  if (document.activeElement === primaryButton) return 'primary';
126
316
  if (document.activeElement === fullscreenButton) return 'fullscreen';
127
317
  return 'none';
128
318
  },
319
+ fullscreenActive() {
320
+ return Boolean(document.fullscreenElement);
321
+ },
129
322
  focusPrimary() {
130
323
  if (!primaryButton.hidden) primaryButton.focus();
131
324
  },
@@ -137,15 +330,147 @@ const view = {
137
330
  },
138
331
  };
139
332
 
140
- function updateStageScale() {
333
+ function updateStageScale(preset = stagePreset) {
334
+ stagePreset = preset;
335
+ stage.classList?.toggle?.('stage--portrait', preset.height > preset.width);
141
336
  const width = stage.clientWidth;
142
337
  const height = stage.clientHeight;
143
338
  if (width < 1 || height < 1) return;
144
- const scale = Math.min(width / 1280, height / 720);
339
+ const scale = Math.min(width / preset.width, height / preset.height);
145
340
  stageScale = scale;
146
341
  canvas.style.transform = `scale(${scale})`;
147
- canvas.style.left = `${(width - 1280 * scale) / 2}px`;
148
- canvas.style.top = `${(height - 720 * scale) / 2}px`;
342
+ canvas.style.left = `${(width - preset.width * scale) / 2}px`;
343
+ canvas.style.top = `${(height - preset.height * scale) / 2}px`;
344
+ }
345
+
346
+ // The CSS-box resize barrier: poll the observer's logical size, but never
347
+ // wait longer than this before restoring the old preset and failing.
348
+ const RESIZE_POLL_MS = 16;
349
+ const RESIZE_TIMEOUT_MS = 2000;
350
+
351
+ function resizeTimeoutError(preset) {
352
+ return new ShowErrorClass(
353
+ 'resize-timeout',
354
+ `the canvas did not reach ${preset.width}×${preset.height} within ${RESIZE_TIMEOUT_MS} ms`,
355
+ { stage: 'resize', document: 'player/boot.mjs' },
356
+ );
357
+ }
358
+
359
+ /**
360
+ * The preset is a CSS-box change only. After transferControlToOffscreen(),
361
+ * canvas.width/height throw on assignment and read stale forever; pngine's
362
+ * device-pixel ResizeObserver carries the CSS box to the worker and reports
363
+ * the new logical size through the viewer's width/height. A single frame is
364
+ * not that report, so poll until the observer's values match, and time out
365
+ * rather than hang the transport when it never does.
366
+ */
367
+ function waitForRendererSize(preset) {
368
+ return new Promise((resolve, reject) => {
369
+ let poll = null;
370
+ let deadline = null;
371
+ let settled = false;
372
+ const finish = (settle, value) => {
373
+ if (settled) return;
374
+ settled = true;
375
+ if (poll !== null) clearTimeout(poll);
376
+ if (deadline !== null) clearTimeout(deadline);
377
+ settle(value);
378
+ };
379
+ const check = () => {
380
+ if (settled) return;
381
+ if (renderer && renderer.width === preset.width && renderer.height === preset.height) {
382
+ finish(resolve);
383
+ return;
384
+ }
385
+ poll = setTimeout(check, RESIZE_POLL_MS);
386
+ };
387
+ deadline = setTimeout(() => finish(reject, resizeTimeoutError(preset)), RESIZE_TIMEOUT_MS);
388
+ check();
389
+ });
390
+ }
391
+
392
+ function setDeviceBox(preset) {
393
+ canvas.style.width = `${preset.width}px`;
394
+ canvas.style.height = `${preset.height}px`;
395
+ updateStageScale(preset);
396
+ }
397
+
398
+ /** Apply the preset to the CSS box and resolve once the observer reports it. */
399
+ function applyDeviceSize(preset) {
400
+ setDeviceBox(preset);
401
+ return waitForRendererSize(preset);
402
+ }
403
+
404
+ function holdSeconds(tick) {
405
+ return (tick / SHOW_TICKS_PER_SECOND).toFixed(2);
406
+ }
407
+
408
+ function sameDevice(left, right) {
409
+ return Boolean(left && right)
410
+ && left.presetLabel === right.presetLabel
411
+ && left.width === right.width
412
+ && left.height === right.height;
413
+ }
414
+
415
+ /**
416
+ * Flip the logical output without losing the moment: measure the tick, show
417
+ * the hold, change the CSS box and wait for pngine's observer to report it,
418
+ * reset through the show's settled restart, seek back, and resume only if the
419
+ * show was actually playing. The label moves last, after the replacement frame
420
+ * exists; a rejection restores the previous box and scale, leaves the label on
421
+ * the old preset and lets the show's own error surface own the failure.
422
+ */
423
+ async function flipDevice(nextPreset) {
424
+ if (!show || !controller) return undefined;
425
+ const next = nextPreset ?? (sameDevice(devicePreset, DEVICE_DESKTOP) ? DEVICE_MOBILE : DEVICE_DESKTOP);
426
+ if (sameDevice(next, devicePreset)) return show.state;
427
+
428
+ const previous = devicePreset;
429
+ const tick = show.tick;
430
+ const wasPlaying = show.state === 'playing';
431
+ controller.setTransition(`switching to ${next.presetLabel} — holding ${holdSeconds(tick)} s`);
432
+ try {
433
+ await applyDeviceSize(next);
434
+ await show.restart();
435
+ await show.seek(tick);
436
+ if (wasPlaying) await show.resume();
437
+ } catch (error) {
438
+ setDeviceBox(previous);
439
+ controller.clearTransition();
440
+ throw error;
441
+ }
442
+ controller.clearTransition();
443
+ devicePreset = next;
444
+ chrome?.setDevice?.(next);
445
+ chrome?.reapplyHolds?.();
446
+ renderChrome();
447
+ return show.state;
448
+ }
449
+
450
+ /**
451
+ * A backing-store change (DPR) is the same replay with the preset unchanged:
452
+ * the same CSS-only applyDeviceSize barrier, no preset change, no label move,
453
+ * and the same failure path.
454
+ */
455
+ async function restoreDisplay() {
456
+ if (!show || !controller) return undefined;
457
+ const tick = show.tick;
458
+ const wasPlaying = show.state === 'playing';
459
+ controller.setTransition(`restoring the display — holding ${holdSeconds(tick)} s`);
460
+ try {
461
+ await applyDeviceSize(devicePreset);
462
+ await show.restart();
463
+ await show.seek(tick);
464
+ if (wasPlaying) await show.resume();
465
+ } catch (error) {
466
+ setDeviceBox(devicePreset);
467
+ controller.clearTransition();
468
+ throw error;
469
+ }
470
+ controller.clearTransition();
471
+ chrome?.reapplyHolds?.();
472
+ renderChrome();
473
+ return show.state;
149
474
  }
150
475
 
151
476
  // The fullscreen action is a toggle: the control's label names what the
@@ -184,7 +509,51 @@ const actions = {
184
509
  if (show.state === 'ready') await show.start();
185
510
  return show.state;
186
511
  },
512
+ seek: async (tick) => (show ? show.seek(tick) : undefined),
513
+ // Pacer's setControl/clearControl take the authored control id or its slot,
514
+ // never the resolved target name. The score ghost, by contrast, reads the
515
+ // target name the frame's writes are keyed by.
516
+ holdControl: async (id, value) => {
517
+ if (!show) return false;
518
+ const control = (metaSafe?.controls ?? []).find((entry) => entry.id === id);
519
+ return show.holdControl(control?.id ?? id, value);
520
+ },
521
+ releaseControl: async (id) => {
522
+ if (!show) return false;
523
+ const control = (metaSafe?.controls ?? []).find((entry) => entry.id === id);
524
+ return show.releaseControl(control?.id ?? id);
525
+ },
526
+ scoreValue: (id) => {
527
+ const controls = metaSafe?.controls ?? [];
528
+ const control = controls.find((entry) => entry.id === id);
529
+ if (!control) return null;
530
+ const target = control.name ?? control.id;
531
+ const writes = lastWrites.get(target);
532
+ if (!writes || writes.length === 0) return null;
533
+ // Every document control with a resolved target writes once, after the
534
+ // tracks. Step back over those writes to the score the pin is covering.
535
+ const pinCount = controls.filter((entry) => entry.name !== null
536
+ && entry.name !== undefined && entry.name === target).length;
537
+ const index = writes.length - pinCount - 1;
538
+ return index >= 0 ? writes[index] : writes[writes.length - 1];
539
+ },
187
540
  fullscreen: toggleFullscreen,
541
+ toggleDevice: async (nextPreset) => {
542
+ try {
543
+ return await flipDevice(nextPreset);
544
+ } catch (error) {
545
+ if (show?.state !== 'error') reportRuntimeFailure(error);
546
+ return show?.state ?? 'error';
547
+ }
548
+ },
549
+ restoreDisplay: async () => {
550
+ try {
551
+ return await restoreDisplay();
552
+ } catch (error) {
553
+ if (show?.state !== 'error') reportRuntimeFailure(error);
554
+ return show?.state ?? 'error';
555
+ }
556
+ },
188
557
  };
189
558
 
190
559
  function rendererFailure(error) {
@@ -248,18 +617,22 @@ function reportRuntimeFailure(error) {
248
617
 
249
618
  function qaGeometry() {
250
619
  const rect = canvas.getBoundingClientRect();
620
+ const dpr = window.devicePixelRatio ?? 1;
621
+ const viewerWidth = renderer?.width ?? 0;
622
+ const viewerHeight = renderer?.height ?? 0;
251
623
  return {
252
- dpr: window.devicePixelRatio,
624
+ dpr,
253
625
  stage: { width: stage.clientWidth, height: stage.clientHeight },
254
626
  canvas: {
255
- backingWidth: canvas.width,
256
- backingHeight: canvas.height,
627
+ // canvas.width/height are stale after transferControlToOffscreen(); report the live viewer instead.
628
+ backingWidth: viewerWidth * dpr,
629
+ backingHeight: viewerHeight * dpr,
257
630
  cssWidth: rect.width,
258
631
  cssHeight: rect.height,
259
632
  inlineWidth: canvas.style.width,
260
633
  inlineHeight: canvas.style.height,
261
634
  },
262
- viewer: { width: renderer?.width ?? 0, height: renderer?.height ?? 0 },
635
+ viewer: { width: viewerWidth, height: viewerHeight },
263
636
  scale: stageScale,
264
637
  };
265
638
  }
@@ -274,6 +647,8 @@ window.animaderDemo = Object.freeze({
274
647
  get origin() { return show?.origin ?? null; },
275
648
  get mode() { return activeProfile?.name ?? null; },
276
649
  get hostSeconds() { return hostSeconds; },
650
+ get scoreSeconds() { return scoreEndSeconds; },
651
+ get effectiveSeconds() { return effectiveSeconds; },
277
652
  get decodedDuration() { return decodedDuration; },
278
653
  get audioContext() { return context; },
279
654
  get audioContextState() { return context?.state ?? null; },
@@ -312,8 +687,9 @@ function armDprWatcher() {
312
687
  if (typeof window.matchMedia !== 'function') return;
313
688
  const query = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
314
689
  const onChange = () => {
315
- controller?.handleResize();
690
+ const restoring = actions.restoreDisplay();
316
691
  armDprWatcher();
692
+ return restoring;
317
693
  };
318
694
  if (typeof query.addEventListener === 'function') query.addEventListener('change', onChange, { once: true });
319
695
  else query.addListener?.(onChange);
@@ -638,6 +1014,13 @@ async function load(controllerModule, profile) {
638
1014
  : new TextEncoder().encode(scoreText).byteLength;
639
1015
  join = loaded.join;
640
1016
  metaSafe = jsonSafe(loaded.meta);
1017
+ // The score's own bars, integrated from its tempo map, bound the show: the
1018
+ // effective end is the shorter of the host policy and that score end, on the
1019
+ // show's 100-tick grid. One value feeds the show, the chrome's range and
1020
+ // readout, the release readout and the status, so no surface can disagree.
1021
+ scoreEndSeconds = scoreSeconds(metaSafe);
1022
+ effectiveSeconds = showEndSeconds(hostSeconds, metaSafe);
1023
+ controller.setSeconds(effectiveSeconds);
641
1024
  hashes.score = await safeHash(loaded.score);
642
1025
 
643
1026
  controller.setLoading('player');
@@ -651,11 +1034,19 @@ async function load(controllerModule, profile) {
651
1034
  toUniforms,
652
1035
  setUniform: (name, value, options) => setUniform(renderer, name, value, options),
653
1036
  draw: (options) => draw(renderer, options),
1037
+ onFrame: (frame) => {
1038
+ lastWrites.clear();
1039
+ for (const write of frame?.writes ?? []) {
1040
+ const values = lastWrites.get(write.name);
1041
+ if (values) values.push(write.value);
1042
+ else lastWrites.set(write.name, [write.value]);
1043
+ }
1044
+ },
654
1045
  });
655
1046
 
656
1047
  controller.setLoading('audio decode');
657
1048
  show = createShow({
658
- seconds: hostSeconds,
1049
+ seconds: effectiveSeconds,
659
1050
  prepare: async () => ({
660
1051
  driver: loaded.driver,
661
1052
  player,
@@ -684,16 +1075,22 @@ async function load(controllerModule, profile) {
684
1075
  );
685
1076
  }
686
1077
  decodedDuration = decoded.duration;
687
- const note = audioDurationNote(decoded.duration, hostSeconds);
1078
+ const note = audioDurationNote(decoded.duration, effectiveSeconds);
688
1079
  if (note) controller.addNote(note);
689
1080
  return decoded;
690
1081
  },
691
1082
  audio: port,
692
1083
  scheduleWake: (fn) => {
693
- const id = requestAnimationFrame(fn);
1084
+ const id = requestAnimationFrame(() => {
1085
+ fn();
1086
+ renderChrome();
1087
+ });
694
1088
  return () => cancelAnimationFrame(id);
695
1089
  },
696
- onState: (state) => controller.handleState(state, show?.error ?? null),
1090
+ onState: (state) => {
1091
+ controller.handleState(state, show?.error ?? null);
1092
+ releaseReadout?.render(state);
1093
+ },
697
1094
  });
698
1095
 
699
1096
  try {
@@ -701,6 +1098,49 @@ async function load(controllerModule, profile) {
701
1098
  } catch (error) {
702
1099
  if (show.state !== 'error') controller.fail(error);
703
1100
  }
1101
+
1102
+ // The dev profile supplies the chrome through this seam; boot never imports
1103
+ // the module itself, so the release graph stays unchanged. A chrome failure
1104
+ // is a note, never a reason to take the show down.
1105
+ if (show.state !== 'error') {
1106
+ try {
1107
+ chrome = await profile.loadChrome?.({
1108
+ host: document.getElementById('controls'),
1109
+ readout: document.getElementById('readout'),
1110
+ seconds: effectiveSeconds,
1111
+ meta: metaSafe,
1112
+ decodedSeconds: decodedDuration,
1113
+ device: devicePreset,
1114
+ actions,
1115
+ }) ?? null;
1116
+ renderChrome();
1117
+ } catch (error) {
1118
+ controller.addNote(`dev chrome unavailable — ${error?.message ?? error}`);
1119
+ }
1120
+ }
1121
+
1122
+ // The dev page comes back at the moment it left (a rebuild reload
1123
+ // included), paused and never playing. The chrome is already mounted, so
1124
+ // the restored tick is painted by the same render path. The release profile
1125
+ // has nothing to restore.
1126
+ if (show.state !== 'error') await restoreMoment(profile);
1127
+
1128
+ // The release player carries the readout row and nothing else from the
1129
+ // chrome. It mounts on the same static element the dev chrome owns, and the
1130
+ // release entry is untouched: boot already knows the profile.
1131
+ if (profile.name === 'release' && show.state !== 'error') {
1132
+ document.getElementById('controls')?.classList?.add('panel-release');
1133
+ releaseReadout = mountReleaseReadout({
1134
+ readout: document.getElementById('readout'),
1135
+ position: document.getElementById('readout-position'),
1136
+ elapsed: document.getElementById('readout-elapsed'),
1137
+ show,
1138
+ meta: metaSafe,
1139
+ seconds: effectiveSeconds,
1140
+ formatPosition,
1141
+ formatElapsed,
1142
+ });
1143
+ }
704
1144
  }
705
1145
 
706
1146
  /**
@@ -736,6 +1176,12 @@ export async function boot(profile) {
736
1176
  view,
737
1177
  seconds: null,
738
1178
  fullscreenAvailable: Boolean(document.fullscreenEnabled),
1179
+ // The score metadata is only known after the compile; the getter keeps the
1180
+ // controller current without rebuilding it. Position and the host end are
1181
+ // the show's own clock values, read at the key press.
1182
+ meta: () => metaSafe,
1183
+ position: () => (show ? show.tick : 0),
1184
+ totalTicks: () => (show ? show.totalTicks : undefined),
739
1185
  });
740
1186
 
741
1187
  // A rejecting action must be observable: route it through the page's
@@ -755,8 +1201,10 @@ export async function boot(profile) {
755
1201
  controller.handleKey(event);
756
1202
  });
757
1203
  document.addEventListener('visibilitychange', () => {
1204
+ if (document.hidden) rememberMoment(profile);
758
1205
  void controller.setVisibility(document.hidden);
759
1206
  });
1207
+ window.addEventListener('pagehide', () => rememberMoment(profile));
760
1208
  document.addEventListener('fullscreenchange', () => {
761
1209
  updateStageScale();
762
1210
  syncFullscreenLabel();
@@ -764,10 +1212,14 @@ export async function boot(profile) {
764
1212
  });
765
1213
  window.addEventListener('resize', () => {
766
1214
  updateStageScale();
767
- controller.handleResize();
1215
+ controller.handleLayoutChange();
1216
+ chrome?.resize?.();
768
1217
  });
769
1218
  if (typeof ResizeObserver !== 'undefined') {
770
- const observer = new ResizeObserver(updateStageScale);
1219
+ // ResizeObserver hands the callback an entries array; pass no argument so
1220
+ // updateStageScale keeps its device-preset default instead of treating the
1221
+ // entries as a preset. The stage box itself is the only input it needs.
1222
+ const observer = new ResizeObserver(() => updateStageScale());
771
1223
  observer.observe(stage);
772
1224
  }
773
1225
  updateStageScale();