animader-cli 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 } 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');
@@ -35,9 +37,27 @@ let provenance = null;
35
37
  let manifest = null;
36
38
  let config = null;
37
39
  let activeProfile = null;
40
+ let chrome = null;
41
+ let releaseReadout = null;
38
42
  let renderer = null;
43
+ // The chrome's `score` ghost reads what the last painted frame actually wrote
44
+ // under a pin. Pacer writes controls AFTER tracks so the pin outranks them;
45
+ // the ghost is the last track write before those control entries, not the pin.
46
+ // Keyed by target name, replaced on every frame, never merged.
47
+ const lastWrites = new Map();
39
48
  let rendererError = null;
40
49
  let ShowErrorClass = Error;
50
+ // The two logical output presets. They live here, not in the dev chrome:
51
+ // boot is shared by the release entry and must never import the dev-only
52
+ // surface.
53
+ const DEVICE_DESKTOP = Object.freeze({ presetLabel: 'Desktop · 1280×720', width: 1280, height: 720 });
54
+ const DEVICE_MOBILE = Object.freeze({ presetLabel: 'Mobile · 720×1280', width: 720, height: 1280 });
55
+ const SHOW_TICKS_PER_SECOND = 100;
56
+ let devicePreset = DEVICE_DESKTOP;
57
+ // The preset whose CSS box the stage is currently fitted to. It moves with
58
+ // setDeviceBox (before a flip settles) so an in-flight ResizeObserver callback
59
+ // never reverts the stage to the outgoing orientation.
60
+ let stagePreset = DEVICE_DESKTOP;
41
61
  const hashes = { payload: null, timeline: null, soundtrack: null, score: null, manifest: null };
42
62
 
43
63
  function fallbackFatal(error) {
@@ -100,32 +120,145 @@ function syncFullscreenLabel() {
100
120
  if (secondary) fullscreenButton.textContent = secondaryLabel(secondary.label);
101
121
  }
102
122
 
123
+ // The dev chrome is driven by the actual show state and tick; it owns no
124
+ // clock of its own. While playing, the show's own wake wraps each pump so the
125
+ // readout follows the frame the transport just stepped.
126
+ function renderChrome() {
127
+ if (chrome && show) chrome.render(show.state, show.tick);
128
+ }
129
+
130
+ // The release player shows the musical position and the elapsed time and
131
+ // nothing else from the dev chrome. This mount fills the one shared #readout
132
+ // row the static markup already carries; it never creates a second element.
133
+ // It owns no clock: it repaints from show.tick on the state announcement and,
134
+ // only while playing, once per animation frame. Pause, stop, end and error
135
+ // all cancel that frame.
136
+ const releaseReadouts = new WeakMap();
137
+
138
+ function writeReadoutPieces(element, pieces) {
139
+ const nodes = pieces.map((piece) => {
140
+ if (typeof piece === 'string') return document.createTextNode(piece);
141
+ const span = document.createElement('span');
142
+ span.className = piece.className;
143
+ span.textContent = piece.text;
144
+ return span;
145
+ });
146
+ element.replaceChildren(...nodes);
147
+ }
148
+
149
+ /**
150
+ * Mount the release readout on the shared row. The same formatters the dev
151
+ * chrome uses make the two spellings identical; a second call answers the
152
+ * first, so a retry cannot duplicate the row or its playing frame.
153
+ */
154
+ export function mountReleaseReadout({
155
+ readout,
156
+ position,
157
+ elapsed,
158
+ show,
159
+ meta = {},
160
+ seconds,
161
+ formatPosition: positionFormatter = formatPosition,
162
+ formatElapsed: elapsedFormatter = formatElapsed,
163
+ requestFrame = (callback) => requestAnimationFrame(callback),
164
+ cancelFrame = (id) => cancelAnimationFrame(id),
165
+ }) {
166
+ if (!readout || !position || !elapsed || !show) {
167
+ throw new TypeError('mountReleaseReadout needs the shared row, its two spans and the show');
168
+ }
169
+ const mounted = releaseReadouts.get(readout);
170
+ if (mounted) return mounted;
171
+
172
+ readout.hidden = false;
173
+ let frame = null;
174
+ let lastPosition = null;
175
+ let lastElapsed = null;
176
+
177
+ function draw() {
178
+ const tick = Number.isFinite(show.tick) ? show.tick : 0;
179
+ const nextPosition = positionFormatter(tick, meta);
180
+ if (nextPosition !== lastPosition) {
181
+ writeReadoutPieces(position, readoutPieces(nextPosition));
182
+ lastPosition = nextPosition;
183
+ }
184
+ const nextElapsed = elapsedFormatter(tick / SHOW_TICKS_PER_SECOND, seconds);
185
+ if (nextElapsed !== lastElapsed) {
186
+ writeReadoutPieces(elapsed, readoutPieces(nextElapsed));
187
+ lastElapsed = nextElapsed;
188
+ }
189
+ }
190
+
191
+ function onFrame() {
192
+ frame = null;
193
+ if (show.state !== 'playing') return;
194
+ draw();
195
+ frame = requestFrame(onFrame);
196
+ }
197
+
198
+ function render(state = show.state) {
199
+ draw();
200
+ if (state === 'playing') {
201
+ if (frame === null) frame = requestFrame(onFrame);
202
+ } else if (frame !== null) {
203
+ cancelFrame(frame);
204
+ frame = null;
205
+ }
206
+ return state;
207
+ }
208
+
209
+ const handle = {
210
+ render,
211
+ get running() { return frame !== null; },
212
+ destroy() {
213
+ if (frame !== null) {
214
+ cancelFrame(frame);
215
+ frame = null;
216
+ }
217
+ releaseReadouts.delete(readout);
218
+ readout.hidden = true;
219
+ },
220
+ };
221
+ releaseReadouts.set(readout, handle);
222
+ render(show.state);
223
+ return handle;
224
+ }
225
+
103
226
  const view = {
104
227
  apply(ui) {
105
228
  statusLine.textContent = ui.status;
106
229
  if (ui.primary) {
107
230
  primaryButton.hidden = false;
108
231
  primaryButton.textContent = ui.primary.label;
232
+ primaryButton.disabled = ui.primary.disabled === true;
109
233
  } else {
110
234
  primaryButton.hidden = true;
235
+ primaryButton.disabled = false;
111
236
  }
112
237
  if (ui.secondary) {
113
238
  fullscreenButton.hidden = false;
114
239
  fullscreenButton.textContent = secondaryLabel(ui.secondary.label);
240
+ fullscreenButton.disabled = ui.secondary.disabled === true;
115
241
  } else {
116
242
  fullscreenButton.hidden = true;
243
+ fullscreenButton.disabled = false;
117
244
  }
118
245
  errorBanner.hidden = !ui.errorVisible;
119
246
  errorMessage.textContent = ui.errorText;
120
247
  diagnostics.hidden = false;
121
248
  renderDiagnostics(ui.diagnostics);
122
249
  diagnostics.open = ui.diagnosticsOpen;
250
+ chrome?.setBusy?.(Boolean(ui.rangeDisabled));
251
+ chrome?.setTransition?.(ui.transition ?? null);
252
+ renderChrome();
123
253
  },
124
254
  activeElement() {
125
255
  if (document.activeElement === primaryButton) return 'primary';
126
256
  if (document.activeElement === fullscreenButton) return 'fullscreen';
127
257
  return 'none';
128
258
  },
259
+ fullscreenActive() {
260
+ return Boolean(document.fullscreenElement);
261
+ },
129
262
  focusPrimary() {
130
263
  if (!primaryButton.hidden) primaryButton.focus();
131
264
  },
@@ -137,15 +270,147 @@ const view = {
137
270
  },
138
271
  };
139
272
 
140
- function updateStageScale() {
273
+ function updateStageScale(preset = stagePreset) {
274
+ stagePreset = preset;
275
+ stage.classList?.toggle?.('stage--portrait', preset.height > preset.width);
141
276
  const width = stage.clientWidth;
142
277
  const height = stage.clientHeight;
143
278
  if (width < 1 || height < 1) return;
144
- const scale = Math.min(width / 1280, height / 720);
279
+ const scale = Math.min(width / preset.width, height / preset.height);
145
280
  stageScale = scale;
146
281
  canvas.style.transform = `scale(${scale})`;
147
- canvas.style.left = `${(width - 1280 * scale) / 2}px`;
148
- canvas.style.top = `${(height - 720 * scale) / 2}px`;
282
+ canvas.style.left = `${(width - preset.width * scale) / 2}px`;
283
+ canvas.style.top = `${(height - preset.height * scale) / 2}px`;
284
+ }
285
+
286
+ // The CSS-box resize barrier: poll the observer's logical size, but never
287
+ // wait longer than this before restoring the old preset and failing.
288
+ const RESIZE_POLL_MS = 16;
289
+ const RESIZE_TIMEOUT_MS = 2000;
290
+
291
+ function resizeTimeoutError(preset) {
292
+ return new ShowErrorClass(
293
+ 'resize-timeout',
294
+ `the canvas did not reach ${preset.width}×${preset.height} within ${RESIZE_TIMEOUT_MS} ms`,
295
+ { stage: 'resize', document: 'player/boot.mjs' },
296
+ );
297
+ }
298
+
299
+ /**
300
+ * The preset is a CSS-box change only. After transferControlToOffscreen(),
301
+ * canvas.width/height throw on assignment and read stale forever; pngine's
302
+ * device-pixel ResizeObserver carries the CSS box to the worker and reports
303
+ * the new logical size through the viewer's width/height. A single frame is
304
+ * not that report, so poll until the observer's values match, and time out
305
+ * rather than hang the transport when it never does.
306
+ */
307
+ function waitForRendererSize(preset) {
308
+ return new Promise((resolve, reject) => {
309
+ let poll = null;
310
+ let deadline = null;
311
+ let settled = false;
312
+ const finish = (settle, value) => {
313
+ if (settled) return;
314
+ settled = true;
315
+ if (poll !== null) clearTimeout(poll);
316
+ if (deadline !== null) clearTimeout(deadline);
317
+ settle(value);
318
+ };
319
+ const check = () => {
320
+ if (settled) return;
321
+ if (renderer && renderer.width === preset.width && renderer.height === preset.height) {
322
+ finish(resolve);
323
+ return;
324
+ }
325
+ poll = setTimeout(check, RESIZE_POLL_MS);
326
+ };
327
+ deadline = setTimeout(() => finish(reject, resizeTimeoutError(preset)), RESIZE_TIMEOUT_MS);
328
+ check();
329
+ });
330
+ }
331
+
332
+ function setDeviceBox(preset) {
333
+ canvas.style.width = `${preset.width}px`;
334
+ canvas.style.height = `${preset.height}px`;
335
+ updateStageScale(preset);
336
+ }
337
+
338
+ /** Apply the preset to the CSS box and resolve once the observer reports it. */
339
+ function applyDeviceSize(preset) {
340
+ setDeviceBox(preset);
341
+ return waitForRendererSize(preset);
342
+ }
343
+
344
+ function holdSeconds(tick) {
345
+ return (tick / SHOW_TICKS_PER_SECOND).toFixed(2);
346
+ }
347
+
348
+ function sameDevice(left, right) {
349
+ return Boolean(left && right)
350
+ && left.presetLabel === right.presetLabel
351
+ && left.width === right.width
352
+ && left.height === right.height;
353
+ }
354
+
355
+ /**
356
+ * Flip the logical output without losing the moment: measure the tick, show
357
+ * the hold, change the CSS box and wait for pngine's observer to report it,
358
+ * reset through the show's settled restart, seek back, and resume only if the
359
+ * show was actually playing. The label moves last, after the replacement frame
360
+ * exists; a rejection restores the previous box and scale, leaves the label on
361
+ * the old preset and lets the show's own error surface own the failure.
362
+ */
363
+ async function flipDevice(nextPreset) {
364
+ if (!show || !controller) return undefined;
365
+ const next = nextPreset ?? (sameDevice(devicePreset, DEVICE_DESKTOP) ? DEVICE_MOBILE : DEVICE_DESKTOP);
366
+ if (sameDevice(next, devicePreset)) return show.state;
367
+
368
+ const previous = devicePreset;
369
+ const tick = show.tick;
370
+ const wasPlaying = show.state === 'playing';
371
+ controller.setTransition(`switching to ${next.presetLabel} — holding ${holdSeconds(tick)} s`);
372
+ try {
373
+ await applyDeviceSize(next);
374
+ await show.restart();
375
+ await show.seek(tick);
376
+ if (wasPlaying) await show.resume();
377
+ } catch (error) {
378
+ setDeviceBox(previous);
379
+ controller.clearTransition();
380
+ throw error;
381
+ }
382
+ controller.clearTransition();
383
+ devicePreset = next;
384
+ chrome?.setDevice?.(next);
385
+ chrome?.reapplyHolds?.();
386
+ renderChrome();
387
+ return show.state;
388
+ }
389
+
390
+ /**
391
+ * A backing-store change (DPR) is the same replay with the preset unchanged:
392
+ * the same CSS-only applyDeviceSize barrier, no preset change, no label move,
393
+ * and the same failure path.
394
+ */
395
+ async function restoreDisplay() {
396
+ if (!show || !controller) return undefined;
397
+ const tick = show.tick;
398
+ const wasPlaying = show.state === 'playing';
399
+ controller.setTransition(`restoring the display — holding ${holdSeconds(tick)} s`);
400
+ try {
401
+ await applyDeviceSize(devicePreset);
402
+ await show.restart();
403
+ await show.seek(tick);
404
+ if (wasPlaying) await show.resume();
405
+ } catch (error) {
406
+ setDeviceBox(devicePreset);
407
+ controller.clearTransition();
408
+ throw error;
409
+ }
410
+ controller.clearTransition();
411
+ chrome?.reapplyHolds?.();
412
+ renderChrome();
413
+ return show.state;
149
414
  }
150
415
 
151
416
  // The fullscreen action is a toggle: the control's label names what the
@@ -184,7 +449,51 @@ const actions = {
184
449
  if (show.state === 'ready') await show.start();
185
450
  return show.state;
186
451
  },
452
+ seek: async (tick) => (show ? show.seek(tick) : undefined),
453
+ // Pacer's setControl/clearControl take the authored control id or its slot,
454
+ // never the resolved target name. The score ghost, by contrast, reads the
455
+ // target name the frame's writes are keyed by.
456
+ holdControl: async (id, value) => {
457
+ if (!show) return false;
458
+ const control = (metaSafe?.controls ?? []).find((entry) => entry.id === id);
459
+ return show.holdControl(control?.id ?? id, value);
460
+ },
461
+ releaseControl: async (id) => {
462
+ if (!show) return false;
463
+ const control = (metaSafe?.controls ?? []).find((entry) => entry.id === id);
464
+ return show.releaseControl(control?.id ?? id);
465
+ },
466
+ scoreValue: (id) => {
467
+ const controls = metaSafe?.controls ?? [];
468
+ const control = controls.find((entry) => entry.id === id);
469
+ if (!control) return null;
470
+ const target = control.name ?? control.id;
471
+ const writes = lastWrites.get(target);
472
+ if (!writes || writes.length === 0) return null;
473
+ // Every document control with a resolved target writes once, after the
474
+ // tracks. Step back over those writes to the score the pin is covering.
475
+ const pinCount = controls.filter((entry) => entry.name !== null
476
+ && entry.name !== undefined && entry.name === target).length;
477
+ const index = writes.length - pinCount - 1;
478
+ return index >= 0 ? writes[index] : writes[writes.length - 1];
479
+ },
187
480
  fullscreen: toggleFullscreen,
481
+ toggleDevice: async (nextPreset) => {
482
+ try {
483
+ return await flipDevice(nextPreset);
484
+ } catch (error) {
485
+ if (show?.state !== 'error') reportRuntimeFailure(error);
486
+ return show?.state ?? 'error';
487
+ }
488
+ },
489
+ restoreDisplay: async () => {
490
+ try {
491
+ return await restoreDisplay();
492
+ } catch (error) {
493
+ if (show?.state !== 'error') reportRuntimeFailure(error);
494
+ return show?.state ?? 'error';
495
+ }
496
+ },
188
497
  };
189
498
 
190
499
  function rendererFailure(error) {
@@ -248,18 +557,22 @@ function reportRuntimeFailure(error) {
248
557
 
249
558
  function qaGeometry() {
250
559
  const rect = canvas.getBoundingClientRect();
560
+ const dpr = window.devicePixelRatio ?? 1;
561
+ const viewerWidth = renderer?.width ?? 0;
562
+ const viewerHeight = renderer?.height ?? 0;
251
563
  return {
252
- dpr: window.devicePixelRatio,
564
+ dpr,
253
565
  stage: { width: stage.clientWidth, height: stage.clientHeight },
254
566
  canvas: {
255
- backingWidth: canvas.width,
256
- backingHeight: canvas.height,
567
+ // canvas.width/height are stale after transferControlToOffscreen(); report the live viewer instead.
568
+ backingWidth: viewerWidth * dpr,
569
+ backingHeight: viewerHeight * dpr,
257
570
  cssWidth: rect.width,
258
571
  cssHeight: rect.height,
259
572
  inlineWidth: canvas.style.width,
260
573
  inlineHeight: canvas.style.height,
261
574
  },
262
- viewer: { width: renderer?.width ?? 0, height: renderer?.height ?? 0 },
575
+ viewer: { width: viewerWidth, height: viewerHeight },
263
576
  scale: stageScale,
264
577
  };
265
578
  }
@@ -312,8 +625,9 @@ function armDprWatcher() {
312
625
  if (typeof window.matchMedia !== 'function') return;
313
626
  const query = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
314
627
  const onChange = () => {
315
- controller?.handleResize();
628
+ const restoring = actions.restoreDisplay();
316
629
  armDprWatcher();
630
+ return restoring;
317
631
  };
318
632
  if (typeof query.addEventListener === 'function') query.addEventListener('change', onChange, { once: true });
319
633
  else query.addListener?.(onChange);
@@ -651,6 +965,14 @@ async function load(controllerModule, profile) {
651
965
  toUniforms,
652
966
  setUniform: (name, value, options) => setUniform(renderer, name, value, options),
653
967
  draw: (options) => draw(renderer, options),
968
+ onFrame: (frame) => {
969
+ lastWrites.clear();
970
+ for (const write of frame?.writes ?? []) {
971
+ const values = lastWrites.get(write.name);
972
+ if (values) values.push(write.value);
973
+ else lastWrites.set(write.name, [write.value]);
974
+ }
975
+ },
654
976
  });
655
977
 
656
978
  controller.setLoading('audio decode');
@@ -690,10 +1012,16 @@ async function load(controllerModule, profile) {
690
1012
  },
691
1013
  audio: port,
692
1014
  scheduleWake: (fn) => {
693
- const id = requestAnimationFrame(fn);
1015
+ const id = requestAnimationFrame(() => {
1016
+ fn();
1017
+ renderChrome();
1018
+ });
694
1019
  return () => cancelAnimationFrame(id);
695
1020
  },
696
- onState: (state) => controller.handleState(state, show?.error ?? null),
1021
+ onState: (state) => {
1022
+ controller.handleState(state, show?.error ?? null);
1023
+ releaseReadout?.render(state);
1024
+ },
697
1025
  });
698
1026
 
699
1027
  try {
@@ -701,6 +1029,43 @@ async function load(controllerModule, profile) {
701
1029
  } catch (error) {
702
1030
  if (show.state !== 'error') controller.fail(error);
703
1031
  }
1032
+
1033
+ // The dev profile supplies the chrome through this seam; boot never imports
1034
+ // the module itself, so the release graph stays unchanged. A chrome failure
1035
+ // is a note, never a reason to take the show down.
1036
+ if (show.state !== 'error') {
1037
+ try {
1038
+ chrome = await profile.loadChrome?.({
1039
+ host: document.getElementById('controls'),
1040
+ readout: document.getElementById('readout'),
1041
+ seconds: hostSeconds,
1042
+ meta: metaSafe,
1043
+ decodedSeconds: decodedDuration,
1044
+ device: devicePreset,
1045
+ actions,
1046
+ }) ?? null;
1047
+ renderChrome();
1048
+ } catch (error) {
1049
+ controller.addNote(`dev chrome unavailable — ${error?.message ?? error}`);
1050
+ }
1051
+ }
1052
+
1053
+ // The release player carries the readout row and nothing else from the
1054
+ // chrome. It mounts on the same static element the dev chrome owns, and the
1055
+ // release entry is untouched: boot already knows the profile.
1056
+ if (profile.name === 'release' && show.state !== 'error') {
1057
+ document.getElementById('controls')?.classList?.add('panel-release');
1058
+ releaseReadout = mountReleaseReadout({
1059
+ readout: document.getElementById('readout'),
1060
+ position: document.getElementById('readout-position'),
1061
+ elapsed: document.getElementById('readout-elapsed'),
1062
+ show,
1063
+ meta: metaSafe,
1064
+ seconds: hostSeconds,
1065
+ formatPosition,
1066
+ formatElapsed,
1067
+ });
1068
+ }
704
1069
  }
705
1070
 
706
1071
  /**
@@ -764,10 +1129,14 @@ export async function boot(profile) {
764
1129
  });
765
1130
  window.addEventListener('resize', () => {
766
1131
  updateStageScale();
767
- controller.handleResize();
1132
+ controller.handleLayoutChange();
1133
+ chrome?.resize?.();
768
1134
  });
769
1135
  if (typeof ResizeObserver !== 'undefined') {
770
- const observer = new ResizeObserver(updateStageScale);
1136
+ // ResizeObserver hands the callback an entries array; pass no argument so
1137
+ // updateStageScale keeps its device-preset default instead of treating the
1138
+ // entries as a preset. The stage box itself is the only input it needs.
1139
+ const observer = new ResizeObserver(() => updateStageScale());
771
1140
  observer.observe(stage);
772
1141
  }
773
1142
  updateStageScale();