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.
@@ -8,6 +8,7 @@
8
8
  // Ownership: UI state vocabulary, keyboard intent, focus handoff, notes/errors.
9
9
 
10
10
  const ACTIVE_STATES = new Set(['playing', 'paused', 'press-to-resume']);
11
+ const PLAYABLE_STATES = new Set(['ready', 'playing', 'paused', 'press-to-resume', 'ended', 'stopped']);
11
12
  const SPACE_STATES = new Set(['ready', 'playing', 'paused', 'press-to-resume']);
12
13
  const RESTARTABLE_STATES = new Set(['ended', 'stopped']);
13
14
 
@@ -17,6 +18,257 @@ export function formatSeconds(seconds) {
17
18
  return Number.isInteger(seconds) ? seconds.toFixed(1) : String(seconds);
18
19
  }
19
20
 
21
+ // Pacer's tick grid and the transport's own grid are different clocks:
22
+ // PPC is one bar of pacer ticks (a quarter is PPC / beatsPerBar), while the
23
+ // show's seek grid is 100 ticks per second. The tempo map is authored in the
24
+ // former; the readout and the ruler receive the latter.
25
+ const PACER_TICKS_PER_BAR = 720720;
26
+ const SHOW_TICKS_PER_SECOND = 100;
27
+ const DEFAULT_BPM = 82;
28
+ const DEFAULT_BEATS_PER_BAR = 4;
29
+ const POSITION_EPSILON = 1e-9;
30
+
31
+ function finiteNumber(value, fallback) {
32
+ let number = value;
33
+ if (typeof value === 'bigint') number = Number(value);
34
+ else if (typeof value === 'string' && value.trim() !== '') number = Number(value);
35
+ return typeof number === 'number' && Number.isFinite(number) ? number : fallback;
36
+ }
37
+
38
+ function formatBpm(bpm) {
39
+ return Number.isInteger(bpm) ? String(bpm) : bpm.toFixed(1);
40
+ }
41
+
42
+ /**
43
+ * The tempo map integrated into seconds. Each segment starts at a pacer tick
44
+ * and carries its BPM; the score's end (transport.dur) bounds the musical grid
45
+ * so the hold tail can be named without pretending it is another bar.
46
+ */
47
+ function tempoModel(meta) {
48
+ const transport = meta?.transport ?? {};
49
+ const openingBpm = finiteNumber(transport.bpm, DEFAULT_BPM);
50
+ const bpm = openingBpm > 0 ? openingBpm : DEFAULT_BPM;
51
+ const beatsPerBar = Math.max(1, Math.floor(finiteNumber(transport.beatsPerBar, DEFAULT_BEATS_PER_BAR)));
52
+ const dur = finiteNumber(transport.dur, Infinity);
53
+ const scoreEndTick = dur > 0 ? dur : Infinity;
54
+ const ticksPerBeat = PACER_TICKS_PER_BAR / beatsPerBar;
55
+
56
+ const points = (Array.isArray(meta?.tempoMap) ? meta.tempoMap : [])
57
+ .map((point) => ({
58
+ tick: finiteNumber(point?.tick, NaN),
59
+ bpm: finiteNumber(point?.bpm, NaN),
60
+ }))
61
+ .filter((point) => Number.isFinite(point.tick) && point.tick >= 0
62
+ && point.tick <= scoreEndTick && Number.isFinite(point.bpm) && point.bpm > 0)
63
+ .sort((a, b) => a.tick - b.tick);
64
+
65
+ if (points.length === 0 || points[0].tick > 0) points.unshift({ tick: 0, bpm });
66
+ else points[0] = { tick: 0, bpm: points[0].bpm };
67
+
68
+ const segments = [];
69
+ let startSeconds = 0;
70
+ for (let index = 0; index < points.length; index += 1) {
71
+ const point = points[index];
72
+ const nextTick = index + 1 < points.length ? points[index + 1].tick : scoreEndTick;
73
+ const endTick = Number.isFinite(scoreEndTick) ? Math.min(nextTick, scoreEndTick) : nextTick;
74
+ const span = Math.max(0, endTick - point.tick);
75
+ const spanSeconds = (span / ticksPerBeat) * (60 / point.bpm);
76
+ segments.push({
77
+ startTick: point.tick,
78
+ startSeconds,
79
+ endSeconds: startSeconds + spanSeconds,
80
+ bpm: point.bpm,
81
+ });
82
+ startSeconds += spanSeconds;
83
+ }
84
+
85
+ return {
86
+ beatsPerBar,
87
+ ticksPerBeat,
88
+ segments,
89
+ scoreEndSeconds: segments.at(-1)?.endSeconds ?? Infinity,
90
+ endBpm: segments.at(-1)?.bpm ?? bpm,
91
+ };
92
+ }
93
+
94
+ /**
95
+ * The musical readout for a transport tick (100 per second): `bar 5 · beat 3 ·
96
+ * 82 BPM`, `hold · 82 BPM` past the score's end, `bar 1 · beat 1 · 82 BPM` at 0.
97
+ * Tempo changes are integrated from `meta.tempoMap`, whose tick fields are
98
+ * pacer ticks, never read from the opening BPM alone.
99
+ */
100
+ export function formatPosition(tick, meta) {
101
+ const model = tempoModel(meta);
102
+ const seconds = Math.max(0, finiteNumber(tick, 0) / SHOW_TICKS_PER_SECOND);
103
+
104
+ if (seconds >= model.scoreEndSeconds - POSITION_EPSILON) {
105
+ return `hold · ${formatBpm(model.endBpm)} BPM`;
106
+ }
107
+
108
+ let segment = model.segments[0];
109
+ for (const candidate of model.segments) {
110
+ if (seconds >= candidate.startSeconds - POSITION_EPSILON) segment = candidate;
111
+ else break;
112
+ }
113
+
114
+ const beats = segment.startTick / model.ticksPerBeat
115
+ + (seconds - segment.startSeconds) * (segment.bpm / 60);
116
+ const barIndex = Math.floor(beats / model.beatsPerBar + POSITION_EPSILON);
117
+ const beat = Math.min(
118
+ model.beatsPerBar,
119
+ Math.floor(beats - barIndex * model.beatsPerBar + POSITION_EPSILON) + 1,
120
+ );
121
+ return `bar ${barIndex + 1} · beat ${beat} · ${formatBpm(segment.bpm)} BPM`;
122
+ }
123
+
124
+ /** One pacer tick in seconds, integrating the compiled tempo segments. */
125
+ function pacerTickToSeconds(model, tick) {
126
+ if (!Number.isFinite(tick) || tick <= 0) return 0;
127
+ let segment = model.segments[0];
128
+ for (const candidate of model.segments) {
129
+ if (tick >= candidate.startTick - POSITION_EPSILON) segment = candidate;
130
+ else break;
131
+ }
132
+ if (!segment) return 0;
133
+ const beats = (tick - segment.startTick) / model.ticksPerBeat;
134
+ return segment.startSeconds + (beats * 60) / segment.bpm;
135
+ }
136
+
137
+ /**
138
+ * The document's scenes projected onto the show's own tick grid (100 per
139
+ * second). Scene ticks are pacer ticks, so a tempo change stretches a window
140
+ * exactly as it stretches the musical grid.
141
+ */
142
+ export function sceneWindows(meta) {
143
+ const model = tempoModel(meta);
144
+ return (Array.isArray(meta?.scenes) ? meta.scenes : []).map((scene) => {
145
+ const name = String(scene?.name ?? '');
146
+ const startTick = finiteNumber(scene?.startTick, NaN);
147
+ const durTicks = finiteNumber(scene?.durTicks, NaN);
148
+ if (!Number.isFinite(startTick) || !Number.isFinite(durTicks) || durTicks < 0) {
149
+ return { name, start: 0, end: 0 };
150
+ }
151
+ const start = Math.max(0, Math.round(pacerTickToSeconds(model, startTick) * SHOW_TICKS_PER_SECOND));
152
+ const end = Math.max(start, Math.round(
153
+ pacerTickToSeconds(model, startTick + durTicks) * SHOW_TICKS_PER_SECOND,
154
+ ));
155
+ return { name, start, end };
156
+ });
157
+ }
158
+
159
+ /**
160
+ * The window containing a show tick, or null. Intervals are half-open at the
161
+ * end, so adjacent scenes do not both contain their shared boundary. When
162
+ * scenes overlap, every window whose own interval covers the tick contains it;
163
+ * this answers the last such window in declaration order.
164
+ */
165
+ export function sceneAt(tick, windows) {
166
+ const at = finiteNumber(tick, NaN);
167
+ if (!Number.isFinite(at) || !Array.isArray(windows)) return null;
168
+ let containing = null;
169
+ for (const window of windows) {
170
+ if (!window) continue;
171
+ const start = finiteNumber(window.start, NaN);
172
+ const end = finiteNumber(window.end, NaN);
173
+ if (Number.isFinite(start) && Number.isFinite(end) && at >= start && at < end) containing = window;
174
+ }
175
+ return containing;
176
+ }
177
+
178
+ function laneBounds(raw, lanes, fallback) {
179
+ if (Array.isArray(raw) && raw.length > 0) {
180
+ return Array.from({ length: lanes }, (_, index) => {
181
+ const own = finiteNumber(raw[index], NaN);
182
+ return Number.isFinite(own) ? own : finiteNumber(raw[0], fallback);
183
+ });
184
+ }
185
+ const scalar = finiteNumber(raw, NaN);
186
+ return Array.from({ length: lanes }, () => (Number.isFinite(scalar) ? scalar : fallback));
187
+ }
188
+
189
+ /**
190
+ * One pacer `meta.controls` entry as the widget the chrome builds. A declared
191
+ * slider with no ends is a numeric field, not a faux bounded slider; colour
192
+ * lanes default to the 0–1 range pacer's swatch assumes. `name: null` is a
193
+ * virtual knob and still yields a descriptor.
194
+ */
195
+ export function describeControl(control) {
196
+ const id = String(control?.id ?? '');
197
+ const type = typeof control?.type === 'string' ? control.type : '';
198
+ const rawValue = Array.isArray(control?.value)
199
+ ? control.value
200
+ : control?.value === undefined ? [] : [control.value];
201
+ const declaredLanes = finiteNumber(control?.ncomp, NaN);
202
+ const lanes = Number.isFinite(declaredLanes) && declaredLanes > 0
203
+ ? Math.floor(declaredLanes)
204
+ : rawValue.length > 0
205
+ ? rawValue.length
206
+ : type === 'xy' ? 2 : type === 'color' ? 3 : 1;
207
+ const value = Array.from({ length: lanes }, (_, index) => finiteNumber(rawValue[index], 0));
208
+ const hasMin = Array.isArray(control?.min)
209
+ ? control.min.length > 0
210
+ : control?.min !== undefined && control?.min !== null;
211
+ const hasMax = Array.isArray(control?.max)
212
+ ? control.max.length > 0
213
+ : control?.max !== undefined && control?.max !== null;
214
+ const hasBounds = hasMin || hasMax;
215
+
216
+ let kind;
217
+ if (type === 'xy' && lanes >= 2) kind = 'xy';
218
+ else if (type === 'color' && lanes >= 3) kind = 'color';
219
+ else if (type === 'slider' && hasBounds) kind = 'slider';
220
+ else if (type === 'slider') kind = 'numeric';
221
+ else if (lanes === 2) kind = 'xy';
222
+ else if (lanes >= 3) kind = 'color';
223
+ else kind = hasBounds ? 'slider' : 'numeric';
224
+
225
+ const min = kind === 'numeric' ? null : laneBounds(control?.min, lanes, 0);
226
+ const max = kind === 'numeric' ? null : laneBounds(control?.max, lanes, 1);
227
+ const name = control?.name === undefined ? null : control.name;
228
+ return { id, kind, lanes, min, max, name, value };
229
+ }
230
+
231
+ /**
232
+ * The controls disclosure's label: `controls 6 · 2 held` for several pins,
233
+ * `controls 1 · heat held` for one. Held ids are filtered to declared controls
234
+ * and named in declaration order.
235
+ */
236
+ export function heldSummary(controls, heldIds) {
237
+ const declared = Array.isArray(controls) ? controls : [];
238
+ const held = new Set(heldIds instanceof Set ? heldIds : Array.isArray(heldIds) ? heldIds : []);
239
+ const names = declared.filter((control) => held.has(control?.id)).map((control) => control.id);
240
+ const base = `controls ${declared.length}`;
241
+ if (names.length === 0) return base;
242
+ if (names.length === 1) return `${base} · ${names[0]} held`;
243
+ return `${base} · ${names.length} held`;
244
+ }
245
+
246
+ /** `13.20 s / 36.00 s` — the transport's 10 ms tick shown in hundredths. */
247
+ export function formatElapsed(seconds, hostSeconds) {
248
+ const part = (value) => (Number.isFinite(value) ? value.toFixed(2) : '—');
249
+ return `${part(seconds)} s / ${part(hostSeconds)} s`;
250
+ }
251
+
252
+ // The readout's visual grammar: words and separators are muted, numbers carry
253
+ // the text tone. The mockup's words are bar, beat, BPM, hold, frame, seek,
254
+ // release and the unit s; its separators are ·, / and →.
255
+ const READOUT_SEPARATORS = new Set(['·', '/', '→']);
256
+
257
+ /**
258
+ * Split a readout string into writable pieces while preserving its exact
259
+ * spacing. Numeric tokens are values; the three separators are separators;
260
+ * every other token is a muted word. The same pieces feed the dev chrome and
261
+ * the release readout, so both spellings keep one visual grammar.
262
+ */
263
+ export function readoutPieces(text) {
264
+ return String(text ?? '').split(/(\s+)/).filter(Boolean).map((token) => {
265
+ if (/^\s+$/.test(token)) return token;
266
+ if (READOUT_SEPARATORS.has(token)) return { text: token, className: 'readout-separator' };
267
+ if (/^\d/.test(token)) return { text: token, className: 'readout-value' };
268
+ return { text: token, className: 'readout-label' };
269
+ });
270
+ }
271
+
20
272
  /**
21
273
  * The actual decoded soundtrack length measured against the host end. A long
22
274
  * track is cut at the host end; a short one leaves silence. This is a decode
@@ -78,7 +330,8 @@ function keepsNativeSpace(target) {
78
330
  * @param {object} options.actions actual show commands: start, pause, resume,
79
331
  * stop, restart, fullscreen. Each may return a promise.
80
332
  * @param {object} options.view browser surface: apply(ui), activeElement(),
81
- * focusPrimary(), focusSecondary(), focusError().
333
+ * focusPrimary(), focusSecondary(), focusError(), and optionally
334
+ * fullscreenActive() for the browser's current fullscreen element.
82
335
  * @param {number|null} [options.seconds] the host show length from config.
83
336
  * @param {boolean} [options.fullscreenAvailable]
84
337
  */
@@ -94,6 +347,7 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
94
347
  let canFullscreen = Boolean(fullscreenAvailable);
95
348
  let error = null;
96
349
  let notes = [];
350
+ let transition = null;
97
351
  let displayChanged = false;
98
352
  let visibilityHidden = false;
99
353
  let hiddenPause = false;
@@ -123,10 +377,19 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
123
377
  else if (state === 'paused' || state === 'press-to-resume') primary = { label: 'Resume', action: 'resume' };
124
378
  else if (state === 'ended' || state === 'stopped') primary = { label: 'Restart', action: 'restart' };
125
379
 
126
- const secondary = state === 'ready' && canFullscreen
380
+ let secondary = PLAYABLE_STATES.has(state) && canFullscreen
127
381
  ? { label: 'Fullscreen', action: 'fullscreen' }
128
382
  : null;
129
383
 
384
+ // A device flip or a backing-store restore is its own visible state: the
385
+ // show's state keeps running underneath, the transport reports the hold,
386
+ // and every command that could race the rebuild is disabled. An actual
387
+ // failure wins over the overlay and keeps its own status.
388
+ if (transition !== null) {
389
+ if (primary) primary = { ...primary, disabled: true };
390
+ if (secondary) secondary = { ...secondary, disabled: true };
391
+ }
392
+
130
393
  let status;
131
394
  if (state === 'loading') status = `loading — ${loadingStep || 'preparing'}`;
132
395
  else if (state === 'ready') {
@@ -145,9 +408,11 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
145
408
 
146
409
  return {
147
410
  state,
148
- status,
411
+ status: transition !== null && state !== 'error' ? transition : status,
412
+ transition: state === 'error' ? null : transition,
149
413
  primary,
150
414
  secondary,
415
+ rangeDisabled: transition !== null,
151
416
  ...errorView(),
152
417
  };
153
418
  }
@@ -194,6 +459,24 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
194
459
  render();
195
460
  }
196
461
 
462
+ /**
463
+ * The visible overlay for a renderer rebuild. It never changes `state`: the
464
+ * show keeps its own state underneath while the status speaks for the flip
465
+ * and the transport's commands are disabled. Blank text is not a status.
466
+ */
467
+ function setTransition(text) {
468
+ const next = String(text ?? '');
469
+ if (next.trim() === '') return;
470
+ transition = next;
471
+ render();
472
+ }
473
+
474
+ function clearTransition() {
475
+ if (transition === null) return;
476
+ transition = null;
477
+ render();
478
+ }
479
+
197
480
  function addNote(note) {
198
481
  const text = String(note ?? '').trim();
199
482
  if (text === '' || notes.includes(text)) return;
@@ -218,6 +501,7 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
218
501
  }
219
502
 
220
503
  function pressPrimary() {
504
+ if (transition !== null) return Promise.resolve(state);
221
505
  if (state === 'ready') return Promise.resolve(actions.start());
222
506
  if (state === 'playing') return Promise.resolve(actions.stop());
223
507
  if (state === 'paused' || state === 'press-to-resume') return Promise.resolve(actions.resume());
@@ -229,7 +513,7 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
229
513
  }
230
514
 
231
515
  async function pressFullscreen() {
232
- if (state !== 'ready' || !canFullscreen) return false;
516
+ if (transition !== null || !canFullscreen) return false;
233
517
  let accepted = false;
234
518
  try {
235
519
  accepted = (await actions.fullscreen()) === true;
@@ -268,17 +552,33 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
268
552
  }
269
553
  }
270
554
 
555
+ /**
556
+ * The browser's fullscreen state belongs to the browser surface. The view is
557
+ * the injected surface when it reports one; otherwise the event's own
558
+ * document (and, in a page, `globalThis.document`) carries the element.
559
+ */
560
+ function fullscreenActive(event) {
561
+ if (typeof view.fullscreenActive === 'function') return Boolean(view.fullscreenActive());
562
+ const ownerDocument = event?.target?.ownerDocument ?? globalThis.document;
563
+ return Boolean(ownerDocument?.fullscreenElement);
564
+ }
565
+
271
566
  function handleKey(event) {
272
567
  if (!event || event.defaultPrevented) return false;
568
+ // A rebuild owns the transport: no key may start, stop, pause or restart
569
+ // the show between the restart and the seek back.
570
+ if (transition !== null) return false;
273
571
  if (isTextEntry(event.target)) return false;
274
572
  if (event.ctrlKey || event.metaKey || event.altKey) return false;
275
573
 
276
574
  const key = event.key;
277
575
  if (key === ' ' || key === 'Spacebar') {
278
- // A focused secondary button or native disclosure keeps its Space
279
- // activation. The primary's Space is the transport contract, so it is
280
- // handled once here.
281
- if (controlKind(event.target) === 'fullscreen' || keepsNativeSpace(event.target)) return false;
576
+ // A focused secondary or device button, or a native disclosure, keeps
577
+ // its Space activation. The primary's Space is the transport contract,
578
+ // so it is handled once here.
579
+ const kind = controlKind(event.target);
580
+ if (kind === 'fullscreen' || kind === 'device' || kind === 'scene'
581
+ || keepsNativeSpace(event.target)) return false;
282
582
  if (!SPACE_STATES.has(state)) return false;
283
583
  event.preventDefault?.();
284
584
  dispatch(spaceAction);
@@ -286,6 +586,9 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
286
586
  }
287
587
 
288
588
  if (key === 'Escape' && ACTIVE_STATES.has(state)) {
589
+ // Escape in fullscreen is the browser's own exit gesture; the show keeps
590
+ // playing. Only a windowed Escape is the page's Stop.
591
+ if (fullscreenActive(event)) return false;
289
592
  event.preventDefault?.();
290
593
  dispatch(() => actions.stop());
291
594
  return true;
@@ -301,13 +604,32 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
301
604
  return false;
302
605
  }
303
606
 
304
- function handleResize() {
607
+ /**
608
+ * A letterbox/layout change (window resize, fullscreen entry, rotation)
609
+ * rescales the page only. It never stops the show and never claims the
610
+ * display changed; it answers whether the show was active so the caller can
611
+ * decide whether it needs a redraw.
612
+ */
613
+ function handleLayoutChange() {
614
+ return ACTIVE_STATES.has(state);
615
+ }
616
+
617
+ /**
618
+ * An unintended output change keeps the old stop-and-announce policy; the
619
+ * page's own device flip and DPR restore use the position-preserving replay
620
+ * instead and never route through this path.
621
+ */
622
+ function handleOutputChange() {
305
623
  if (displayChanged || !ACTIVE_STATES.has(state)) return false;
306
624
  displayChanged = true;
307
625
  dispatch(() => actions.stop());
308
626
  return true;
309
627
  }
310
628
 
629
+ // Existing callers and tests keep the old name; it is the output-change
630
+ // policy, not the layout one.
631
+ const handleResize = handleOutputChange;
632
+
311
633
  async function setVisibility(hidden) {
312
634
  visibilityHidden = Boolean(hidden);
313
635
  if (visibilityHidden) {
@@ -353,10 +675,14 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
353
675
  setLoading,
354
676
  setSeconds,
355
677
  setFullscreenAvailable,
678
+ setTransition,
679
+ clearTransition,
356
680
  addNote,
357
681
  fail,
358
682
  handleState,
359
683
  handleKey,
684
+ handleLayoutChange,
685
+ handleOutputChange,
360
686
  handleResize,
361
687
  handleFullscreenExit,
362
688
  pressPrimary,
package/player/index.html CHANGED
@@ -19,6 +19,10 @@
19
19
  <div id="controls" class="panel" role="group" aria-label="Playback controls">
20
20
  <button id="primary" type="button" data-player-control="primary" hidden>Start</button>
21
21
  <button id="fullscreen" type="button" class="secondary" data-player-control="fullscreen" hidden>Fullscreen</button>
22
+ <div id="readout" class="readout" hidden>
23
+ <span id="readout-position"></span>
24
+ <span id="readout-elapsed"></span>
25
+ </div>
22
26
  </div>
23
27
  <div id="error" class="banner" role="alert" tabindex="-1" hidden>
24
28
  <span class="marker">error:</span> <span id="error-message"></span>
package/player/page.mjs CHANGED
@@ -99,6 +99,12 @@ const devProfile = {
99
99
  configUrl: `${prefix}/config.json`,
100
100
  manifestUrl: null,
101
101
  configManifestPath: null,
102
+ // The dev-only chrome lives behind this profile seam: boot never imports it,
103
+ // and the release entry does not carry this file at all.
104
+ loadChrome: async (options) => {
105
+ const { mountTransport } = await importModule('./transport.mjs');
106
+ return mountTransport(options);
107
+ },
102
108
  assets: [
103
109
  { key: 'payload', url: `${prefix}/project/out/show.png`, kind: 'bytes' },
104
110
  { key: 'timeline', url: `${prefix}/project/timeline.piece.sjon`, kind: 'text' },