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.
@@ -1,15 +1,18 @@
1
1
  // The player's state-to-interface decisions, kept portable so the same
2
2
  // decisions are unit-tested without a browser. The actual show transport is
3
3
  // injected as commands; the browser surface is injected as a view. This module
4
- // owns no clock, no tick, no audio graph and no renderer call — it maps the
5
- // actual show state to labels, focus, keyboard intent and the display-change
4
+ // owns no clock, no tick state, no audio graph and no renderer call — it maps
5
+ // the actual show state to labels, focus, keyboard intent and the display-change
6
6
  // policy, and never steps or forces the show.
7
7
  //
8
- // Ownership: UI state vocabulary, keyboard intent, focus handoff, notes/errors.
8
+ // Ownership: UI state vocabulary, keyboard intent (including the beat/bar seek
9
+ // arithmetic), focus handoff, notes/errors.
9
10
 
10
11
  const ACTIVE_STATES = new Set(['playing', 'paused', 'press-to-resume']);
12
+ const PLAYABLE_STATES = new Set(['ready', 'playing', 'paused', 'press-to-resume', 'ended', 'stopped']);
11
13
  const SPACE_STATES = new Set(['ready', 'playing', 'paused', 'press-to-resume']);
12
14
  const RESTARTABLE_STATES = new Set(['ended', 'stopped']);
15
+ const ARROW_KEYS = new Set(['ArrowRight', 'ArrowLeft', 'PageUp', 'PageDown']);
13
16
 
14
17
  /** A host length in the design's one-decimal form when it is a whole second. */
15
18
  export function formatSeconds(seconds) {
@@ -17,13 +20,415 @@ export function formatSeconds(seconds) {
17
20
  return Number.isInteger(seconds) ? seconds.toFixed(1) : String(seconds);
18
21
  }
19
22
 
23
+ // The dev page's reload store: one key per page path, so two projects served
24
+ // from the same origin cannot restore each other's moment. The store itself
25
+ // is injected (sessionStorage in the page), which keeps these helpers pure.
26
+ const RESUME_KEY_PREFIX = 'animader:resume:';
27
+
28
+ /** The session-store key for one page path. */
29
+ export function resumeKey(path) {
30
+ return `${RESUME_KEY_PREFIX}${String(path ?? '')}`;
31
+ }
32
+
33
+ /**
34
+ * The tick a previous page wrote, or null when the key is missing or holds a
35
+ * value the show cannot use (non-numeric, non-finite, negative). The store
36
+ * may be absent or throw (a browser can deny storage), which is no moment.
37
+ */
38
+ export function readResume(store, key) {
39
+ if (!store || typeof store.getItem !== 'function') return null;
40
+ let raw;
41
+ try {
42
+ raw = store.getItem(key);
43
+ } catch {
44
+ return null;
45
+ }
46
+ if (typeof raw !== 'string' || raw.trim() === '') return null;
47
+ const tick = Number(raw);
48
+ if (!Number.isFinite(tick) || tick < 0) return null;
49
+ return Math.round(tick);
50
+ }
51
+
52
+ /** Store the show's integer tick; answers whether the store accepted it. */
53
+ export function writeResume(store, key, tick) {
54
+ if (!store || typeof store.setItem !== 'function') return false;
55
+ const value = Number(tick);
56
+ if (!Number.isFinite(value) || value < 0) return false;
57
+ try {
58
+ store.setItem(key, String(Math.round(value)));
59
+ return true;
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ // Pacer's tick grid and the transport's own grid are different clocks:
66
+ // PPC is one bar of pacer ticks (a quarter is PPC / beatsPerBar), while the
67
+ // show's seek grid is 100 ticks per second. The tempo map is authored in the
68
+ // former; the readout and the ruler receive the latter.
69
+ const PACER_TICKS_PER_BAR = 720720;
70
+ const SHOW_TICKS_PER_SECOND = 100;
71
+ const DEFAULT_BPM = 82;
72
+ const DEFAULT_BEATS_PER_BAR = 4;
73
+ const POSITION_EPSILON = 1e-9;
74
+
75
+ function finiteNumber(value, fallback) {
76
+ let number = value;
77
+ if (typeof value === 'bigint') number = Number(value);
78
+ else if (typeof value === 'string' && value.trim() !== '') number = Number(value);
79
+ return typeof number === 'number' && Number.isFinite(number) ? number : fallback;
80
+ }
81
+
82
+ function formatBpm(bpm) {
83
+ return Number.isInteger(bpm) ? String(bpm) : bpm.toFixed(1);
84
+ }
85
+
86
+ /**
87
+ * The tempo map integrated into seconds. Each segment starts at a pacer tick
88
+ * and carries its BPM; the score's end (transport.dur) bounds the musical grid
89
+ * so the hold tail can be named without pretending it is another bar.
90
+ */
91
+ function tempoModel(meta) {
92
+ const transport = meta?.transport ?? {};
93
+ const openingBpm = finiteNumber(transport.bpm, DEFAULT_BPM);
94
+ const bpm = openingBpm > 0 ? openingBpm : DEFAULT_BPM;
95
+ const beatsPerBar = Math.max(1, Math.floor(finiteNumber(transport.beatsPerBar, DEFAULT_BEATS_PER_BAR)));
96
+ const dur = finiteNumber(transport.dur, Infinity);
97
+ const scoreEndTick = dur > 0 ? dur : Infinity;
98
+ const ticksPerBeat = PACER_TICKS_PER_BAR / beatsPerBar;
99
+
100
+ const points = (Array.isArray(meta?.tempoMap) ? meta.tempoMap : [])
101
+ .map((point) => ({
102
+ tick: finiteNumber(point?.tick, NaN),
103
+ bpm: finiteNumber(point?.bpm, NaN),
104
+ }))
105
+ .filter((point) => Number.isFinite(point.tick) && point.tick >= 0
106
+ && point.tick <= scoreEndTick && Number.isFinite(point.bpm) && point.bpm > 0)
107
+ .sort((a, b) => a.tick - b.tick);
108
+
109
+ if (points.length === 0 || points[0].tick > 0) points.unshift({ tick: 0, bpm });
110
+ else points[0] = { tick: 0, bpm: points[0].bpm };
111
+
112
+ const segments = [];
113
+ let startSeconds = 0;
114
+ for (let index = 0; index < points.length; index += 1) {
115
+ const point = points[index];
116
+ const nextTick = index + 1 < points.length ? points[index + 1].tick : scoreEndTick;
117
+ const endTick = Number.isFinite(scoreEndTick) ? Math.min(nextTick, scoreEndTick) : nextTick;
118
+ const span = Math.max(0, endTick - point.tick);
119
+ const spanSeconds = (span / ticksPerBeat) * (60 / point.bpm);
120
+ segments.push({
121
+ startTick: point.tick,
122
+ startSeconds,
123
+ endSeconds: startSeconds + spanSeconds,
124
+ startBeat: point.tick / ticksPerBeat,
125
+ beats: span / ticksPerBeat,
126
+ bpm: point.bpm,
127
+ });
128
+ startSeconds += spanSeconds;
129
+ }
130
+
131
+ return {
132
+ beatsPerBar,
133
+ ticksPerBeat,
134
+ segments,
135
+ scoreEndSeconds: segments.at(-1)?.endSeconds ?? Infinity,
136
+ endBpm: segments.at(-1)?.bpm ?? bpm,
137
+ };
138
+ }
139
+
140
+ /**
141
+ * The score's own length in seconds, integrated over the packed tempo map.
142
+ * `transport.dur` is pacer ticks; one bar is `PPC` ticks and `beatsPerBar`
143
+ * beats, so a segment of `n` ticks at `bpm` lasts
144
+ * `(n / PPC) * beatsPerBar * (60 / bpm)` seconds. A single tempo is exact;
145
+ * a tempo map is integrated segment by segment.
146
+ */
147
+ export function scoreSeconds(meta) {
148
+ return tempoModel(meta).scoreEndSeconds;
149
+ }
150
+
151
+ /**
152
+ * The effective end: a show never outlives either its host policy or its own
153
+ * score. An absent or non-positive side simply leaves the other in charge.
154
+ */
155
+ export function effectiveEndSeconds(hostSeconds, scoreEndSeconds) {
156
+ const host = finiteNumber(hostSeconds, NaN);
157
+ const score = finiteNumber(scoreEndSeconds, NaN);
158
+ if (!(host > 0)) return Number.isFinite(score) && score > 0 ? score : 0;
159
+ if (!(score > 0) || !Number.isFinite(score)) return host;
160
+ return Math.min(host, score);
161
+ }
162
+
163
+ /**
164
+ * The effective end as the page's one length value, on the show's own
165
+ * 100-tick grid. The grid cannot name a fraction of a tick, so the end rounds
166
+ * down: Meridian's 35.121951… s is 3512 ticks (35.12 s) and the last beat —
167
+ * not the hold tail — is the final reachable moment. The tiny guard only
168
+ * absorbs a binary representation landing a few ulps below a whole tick.
169
+ */
170
+ export function showEndSeconds(hostSeconds, meta) {
171
+ const end = effectiveEndSeconds(hostSeconds, scoreSeconds(meta));
172
+ return Number.isFinite(end)
173
+ ? Math.floor(end * SHOW_TICKS_PER_SECOND + 1e-6) / SHOW_TICKS_PER_SECOND
174
+ : end;
175
+ }
176
+
20
177
  /**
21
- * The actual decoded soundtrack length measured against the host end. A long
22
- * track is cut at the host end; a short one leaves silence. This is a decode
23
- * measurement, never a claim that music was heard.
178
+ * The seconds at a musical beat, integrating the compiled tempo segments.
179
+ * The last segment owns every beat past the score end, so a step beyond the
180
+ * musical grid still resolves to a monotonic time before the show clamps it.
181
+ */
182
+ function timeAtBeat(model, beat) {
183
+ for (let index = 0; index < model.segments.length; index += 1) {
184
+ const segment = model.segments[index];
185
+ const endBeat = segment.startBeat + segment.beats;
186
+ if (beat < endBeat - POSITION_EPSILON || index === model.segments.length - 1) {
187
+ return segment.startSeconds + ((beat - segment.startBeat) * 60) / segment.bpm;
188
+ }
189
+ }
190
+ return 0;
191
+ }
192
+
193
+ /**
194
+ * Move `tick` by `beats` on the show's 100-per-second grid, reading the tempo
195
+ * from the score rather than a constant and clamping to `[0, totalTicks]`.
196
+ * This is the transport's retired range-step arithmetic, now owned here.
197
+ *
198
+ * The step lands on a musical boundary, not on the rounded duration: forward
199
+ * means the first tick at or after the next boundary (`ceil`), backward means
200
+ * the last tick at or before the boundary being left (`floor`). At 82 BPM one
201
+ * beat from 0 is tick 74 (0.74 s, beat 2), and one beat back from 74 is tick 73
202
+ * (0.73 s, the last tick of beat 1). A whole-bar step (`beats` a multiple of
203
+ * `beatsPerBar`) snaps to bar lines the same way. The guard preserves exact
204
+ * grid positions: at 96 BPM a 2.5 s bar from 0 is still exactly 250 ticks.
205
+ */
206
+ export function tickAfterBeats(tick, beats, meta, totalTicks = Infinity) {
207
+ const model = tempoModel(meta);
208
+ const current = finiteNumber(tick, 0);
209
+ const stride = finiteNumber(beats, 0);
210
+ const limit = finiteNumber(totalTicks, Infinity);
211
+ const upper = Number.isFinite(limit) ? Math.max(0, Math.floor(limit)) : Infinity;
212
+
213
+ if (stride === 0) return Math.max(0, Math.min(upper, current));
214
+
215
+ const seconds = Math.max(0, current / SHOW_TICKS_PER_SECOND);
216
+
217
+ let segment = model.segments[0];
218
+ for (const candidate of model.segments) {
219
+ if (seconds >= candidate.startSeconds - POSITION_EPSILON) segment = candidate;
220
+ else break;
221
+ }
222
+ if (!segment) return Math.max(0, Math.min(upper, current));
223
+
224
+ const beat = segment.startBeat + ((seconds - segment.startSeconds) * segment.bpm) / 60;
225
+ // A step of whole bars counts bar boundaries; every other step counts beat
226
+ // boundaries, so both land on the musical line rather than 1 tick short.
227
+ const perBar = model.beatsPerBar;
228
+ const magnitude = Math.abs(stride);
229
+ const barStep = magnitude >= perBar && magnitude % perBar === 0;
230
+ const unit = barStep ? perBar : 1;
231
+ const steps = barStep ? magnitude / perBar : magnitude;
232
+ const position = barStep ? beat / perBar : beat;
233
+
234
+ const boundary = stride > 0
235
+ ? (Math.floor(position + POSITION_EPSILON) + steps) * unit
236
+ : (Math.ceil(position - POSITION_EPSILON) - steps) * unit;
237
+ const target = timeAtBeat(model, Math.max(0, boundary));
238
+ const targetTick = target * SHOW_TICKS_PER_SECOND;
239
+ const landed = stride > 0
240
+ ? Math.ceil(targetTick - POSITION_EPSILON)
241
+ : Math.floor(targetTick + POSITION_EPSILON);
242
+ return Math.max(0, Math.min(upper, landed));
243
+ }
244
+
245
+ /**
246
+ * The musical readout for a transport tick (100 per second): `bar 5 · beat 3 ·
247
+ * 82 BPM`, `hold · 82 BPM` strictly past the score's end, `bar 1 · beat 1 ·
248
+ * 82 BPM` at 0. The score's own end is its last beat; no hold exists when the
249
+ * ruler ends there. Tempo changes are integrated from `meta.tempoMap`, whose
250
+ * tick fields are pacer ticks, never read from the opening BPM alone.
251
+ */
252
+ export function formatPosition(tick, meta) {
253
+ const model = tempoModel(meta);
254
+ const seconds = Math.max(0, finiteNumber(tick, 0) / SHOW_TICKS_PER_SECOND);
255
+
256
+ if (seconds > model.scoreEndSeconds + POSITION_EPSILON) {
257
+ return `hold · ${formatBpm(model.endBpm)} BPM`;
258
+ }
259
+
260
+ let segment = model.segments[0];
261
+ for (const candidate of model.segments) {
262
+ if (seconds >= candidate.startSeconds - POSITION_EPSILON) segment = candidate;
263
+ else break;
264
+ }
265
+
266
+ const beats = segment.startTick / model.ticksPerBeat
267
+ + (seconds - segment.startSeconds) * (segment.bpm / 60);
268
+ const barIndex = Math.floor(beats / model.beatsPerBar + POSITION_EPSILON);
269
+ const beat = Math.min(
270
+ model.beatsPerBar,
271
+ Math.floor(beats - barIndex * model.beatsPerBar + POSITION_EPSILON) + 1,
272
+ );
273
+ return `bar ${barIndex + 1} · beat ${beat} · ${formatBpm(segment.bpm)} BPM`;
274
+ }
275
+
276
+ /** One pacer tick in seconds, integrating the compiled tempo segments. */
277
+ function pacerTickToSeconds(model, tick) {
278
+ if (!Number.isFinite(tick) || tick <= 0) return 0;
279
+ let segment = model.segments[0];
280
+ for (const candidate of model.segments) {
281
+ if (tick >= candidate.startTick - POSITION_EPSILON) segment = candidate;
282
+ else break;
283
+ }
284
+ if (!segment) return 0;
285
+ const beats = (tick - segment.startTick) / model.ticksPerBeat;
286
+ return segment.startSeconds + (beats * 60) / segment.bpm;
287
+ }
288
+
289
+ /**
290
+ * The document's scenes projected onto the show's own tick grid (100 per
291
+ * second). Scene ticks are pacer ticks, so a tempo change stretches a window
292
+ * exactly as it stretches the musical grid.
293
+ */
294
+ export function sceneWindows(meta) {
295
+ const model = tempoModel(meta);
296
+ return (Array.isArray(meta?.scenes) ? meta.scenes : []).map((scene) => {
297
+ const name = String(scene?.name ?? '');
298
+ const startTick = finiteNumber(scene?.startTick, NaN);
299
+ const durTicks = finiteNumber(scene?.durTicks, NaN);
300
+ if (!Number.isFinite(startTick) || !Number.isFinite(durTicks) || durTicks < 0) {
301
+ return { name, start: 0, end: 0 };
302
+ }
303
+ const start = Math.max(0, Math.round(pacerTickToSeconds(model, startTick) * SHOW_TICKS_PER_SECOND));
304
+ const end = Math.max(start, Math.round(
305
+ pacerTickToSeconds(model, startTick + durTicks) * SHOW_TICKS_PER_SECOND,
306
+ ));
307
+ return { name, start, end };
308
+ });
309
+ }
310
+
311
+ /**
312
+ * The window containing a show tick, or null. Intervals are half-open at the
313
+ * end, so adjacent scenes do not both contain their shared boundary. When
314
+ * scenes overlap, every window whose own interval covers the tick contains it;
315
+ * this answers the last such window in declaration order.
316
+ */
317
+ export function sceneAt(tick, windows) {
318
+ const at = finiteNumber(tick, NaN);
319
+ if (!Number.isFinite(at) || !Array.isArray(windows)) return null;
320
+ let containing = null;
321
+ for (const window of windows) {
322
+ if (!window) continue;
323
+ const start = finiteNumber(window.start, NaN);
324
+ const end = finiteNumber(window.end, NaN);
325
+ if (Number.isFinite(start) && Number.isFinite(end) && at >= start && at < end) containing = window;
326
+ }
327
+ return containing;
328
+ }
329
+
330
+ function laneBounds(raw, lanes, fallback) {
331
+ if (Array.isArray(raw) && raw.length > 0) {
332
+ return Array.from({ length: lanes }, (_, index) => {
333
+ const own = finiteNumber(raw[index], NaN);
334
+ return Number.isFinite(own) ? own : finiteNumber(raw[0], fallback);
335
+ });
336
+ }
337
+ const scalar = finiteNumber(raw, NaN);
338
+ return Array.from({ length: lanes }, () => (Number.isFinite(scalar) ? scalar : fallback));
339
+ }
340
+
341
+ /**
342
+ * One pacer `meta.controls` entry as the widget the chrome builds. A declared
343
+ * slider with no ends is a numeric field, not a faux bounded slider; colour
344
+ * lanes default to the 0–1 range pacer's swatch assumes. `name: null` is a
345
+ * virtual knob and still yields a descriptor.
346
+ */
347
+ export function describeControl(control) {
348
+ const id = String(control?.id ?? '');
349
+ const type = typeof control?.type === 'string' ? control.type : '';
350
+ const rawValue = Array.isArray(control?.value)
351
+ ? control.value
352
+ : control?.value === undefined ? [] : [control.value];
353
+ const declaredLanes = finiteNumber(control?.ncomp, NaN);
354
+ const lanes = Number.isFinite(declaredLanes) && declaredLanes > 0
355
+ ? Math.floor(declaredLanes)
356
+ : rawValue.length > 0
357
+ ? rawValue.length
358
+ : type === 'xy' ? 2 : type === 'color' ? 3 : 1;
359
+ const value = Array.from({ length: lanes }, (_, index) => finiteNumber(rawValue[index], 0));
360
+ const hasMin = Array.isArray(control?.min)
361
+ ? control.min.length > 0
362
+ : control?.min !== undefined && control?.min !== null;
363
+ const hasMax = Array.isArray(control?.max)
364
+ ? control.max.length > 0
365
+ : control?.max !== undefined && control?.max !== null;
366
+ const hasBounds = hasMin || hasMax;
367
+
368
+ let kind;
369
+ if (type === 'xy' && lanes >= 2) kind = 'xy';
370
+ else if (type === 'color' && lanes >= 3) kind = 'color';
371
+ else if (type === 'slider' && hasBounds) kind = 'slider';
372
+ else if (type === 'slider') kind = 'numeric';
373
+ else if (lanes === 2) kind = 'xy';
374
+ else if (lanes >= 3) kind = 'color';
375
+ else kind = hasBounds ? 'slider' : 'numeric';
376
+
377
+ const min = kind === 'numeric' ? null : laneBounds(control?.min, lanes, 0);
378
+ const max = kind === 'numeric' ? null : laneBounds(control?.max, lanes, 1);
379
+ const name = control?.name === undefined ? null : control.name;
380
+ return { id, kind, lanes, min, max, name, value };
381
+ }
382
+
383
+ /**
384
+ * The controls disclosure's label: `controls 6 · 2 held` for several pins,
385
+ * `controls 1 · heat held` for one. Held ids are filtered to declared controls
386
+ * and named in declaration order.
387
+ */
388
+ export function heldSummary(controls, heldIds) {
389
+ const declared = Array.isArray(controls) ? controls : [];
390
+ const held = new Set(heldIds instanceof Set ? heldIds : Array.isArray(heldIds) ? heldIds : []);
391
+ const names = declared.filter((control) => held.has(control?.id)).map((control) => control.id);
392
+ const base = `controls ${declared.length}`;
393
+ if (names.length === 0) return base;
394
+ if (names.length === 1) return `${base} · ${names[0]} held`;
395
+ return `${base} · ${names.length} held`;
396
+ }
397
+
398
+ /** `13.20 s / 36.00 s` — the transport's 10 ms tick shown in hundredths. */
399
+ export function formatElapsed(seconds, hostSeconds) {
400
+ const part = (value) => (Number.isFinite(value) ? value.toFixed(2) : '—');
401
+ return `${part(seconds)} s / ${part(hostSeconds)} s`;
402
+ }
403
+
404
+ // The readout's visual grammar: words and separators are muted, numbers carry
405
+ // the text tone. The mockup's words are bar, beat, BPM, hold, frame, seek,
406
+ // release and the unit s; its separators are ·, / and →.
407
+ const READOUT_SEPARATORS = new Set(['·', '/', '→']);
408
+
409
+ /**
410
+ * Split a readout string into writable pieces while preserving its exact
411
+ * spacing. Numeric tokens are values; the three separators are separators;
412
+ * every other token is a muted word. The same pieces feed the dev chrome and
413
+ * the release readout, so both spellings keep one visual grammar.
414
+ */
415
+ export function readoutPieces(text) {
416
+ return String(text ?? '').split(/(\s+)/).filter(Boolean).map((token) => {
417
+ if (/^\s+$/.test(token)) return token;
418
+ if (READOUT_SEPARATORS.has(token)) return { text: token, className: 'readout-separator' };
419
+ if (/^\d/.test(token)) return { text: token, className: 'readout-value' };
420
+ return { text: token, className: 'readout-label' };
421
+ });
422
+ }
423
+
424
+ /**
425
+ * The actual decoded soundtrack length measured against the show's effective
426
+ * end (the shorter of the host and the score). A long track is cut at that
427
+ * end; a short one leaves silence. This is a decode measurement, never a
428
+ * claim that music was heard.
24
429
  *
25
430
  * @param {number} decodedSeconds
26
- * @param {number} hostSeconds
431
+ * @param {number} showSeconds
27
432
  * @returns {string|null}
28
433
  */
29
434
  export function audioDurationNote(decodedSeconds, hostSeconds) {
@@ -35,9 +440,9 @@ export function audioDurationNote(decodedSeconds, hostSeconds) {
35
440
  if (Math.abs(difference) <= 1e-3) return null;
36
441
  const host = formatSeconds(hostSeconds);
37
442
  if (difference > 0) {
38
- return `decoded soundtrack is ${decodedSeconds.toFixed(3)} s; cut at the ${host} s host end`;
443
+ return `decoded soundtrack is ${decodedSeconds.toFixed(3)} s; cut at the ${host} s show end`;
39
444
  }
40
- return `decoded soundtrack is ${decodedSeconds.toFixed(3)} s; silence follows to the ${host} s host end`;
445
+ return `decoded soundtrack is ${decodedSeconds.toFixed(3)} s; silence follows to the ${host} s show end`;
41
446
  }
42
447
 
43
448
  function normalizeError(error) {
@@ -55,11 +460,29 @@ function normalizeError(error) {
55
460
  return { code: 'error', message: String(error), stage: '', document: '', diagnostics: [] };
56
461
  }
57
462
 
463
+ function hasClass(target, name) {
464
+ if (typeof target?.classList?.contains === 'function') return target.classList.contains(name);
465
+ const className = typeof target?.className === 'string' ? target.className : '';
466
+ return className.split(/\s+/).includes(name);
467
+ }
468
+
58
469
  function isTextEntry(target) {
59
470
  if (!target) return false;
60
471
  if (target.isContentEditable === true) return true;
61
472
  const tag = typeof target.tagName === 'string' ? target.tagName.toLowerCase() : '';
62
- return tag === 'input' || tag === 'textarea' || tag === 'select';
473
+ if (tag === 'textarea' || tag === 'select') return true;
474
+ if (tag !== 'input') return false;
475
+ // Only the transport's own scrubber (`input.ruler-range`, created by the
476
+ // transport module) is a transport control: the controller owns its arrows,
477
+ // Page keys and Space. Every other input keeps its text behaviour; a
478
+ // declared piece-control range (slider/xy/color, `control__range`) must
479
+ // keep its native arrows. A minimal DOM may expose type only as an
480
+ // attribute.
481
+ const type = typeof target.type === 'string' && target.type !== ''
482
+ ? target.type
483
+ : String(target.getAttribute?.('type') ?? 'text');
484
+ if (type.toLowerCase() !== 'range') return true;
485
+ return !hasClass(target, 'ruler-range');
63
486
  }
64
487
 
65
488
  function controlKind(target) {
@@ -76,13 +499,28 @@ function keepsNativeSpace(target) {
76
499
  /**
77
500
  * @param {object} options
78
501
  * @param {object} options.actions actual show commands: start, pause, resume,
79
- * stop, restart, fullscreen. Each may return a promise.
502
+ * stop, restart, fullscreen, seek. Each may return a promise.
80
503
  * @param {object} options.view browser surface: apply(ui), activeElement(),
81
- * focusPrimary(), focusSecondary(), focusError().
504
+ * focusPrimary(), focusSecondary(), focusError(), and optionally
505
+ * fullscreenActive() for the browser's current fullscreen element.
82
506
  * @param {number|null} [options.seconds] the host show length from config.
83
507
  * @param {boolean} [options.fullscreenAvailable]
508
+ * @param {object|Function|null} [options.meta] the score metadata, or a getter
509
+ * for it; tempo stepping reads transport bpm/beatsPerBar and tempoMap.
510
+ * @param {number|Function} [options.position] the current show tick, or a
511
+ * getter for it.
512
+ * @param {number|Function|null} [options.totalTicks] the host end on the show
513
+ * grid, or a getter for it; falls back to seconds × 100.
84
514
  */
85
- export function createPlayerController({ actions, view, seconds = null, fullscreenAvailable = true }) {
515
+ export function createPlayerController({
516
+ actions,
517
+ view,
518
+ seconds = null,
519
+ fullscreenAvailable = true,
520
+ meta = null,
521
+ position = null,
522
+ totalTicks = null,
523
+ }) {
86
524
  if (!actions || typeof actions !== 'object') throw new TypeError('createPlayerController needs actual show action commands');
87
525
  if (!view || typeof view.apply !== 'function' || typeof view.activeElement !== 'function') {
88
526
  throw new TypeError('createPlayerController needs a view with apply() and activeElement()');
@@ -94,10 +532,15 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
94
532
  let canFullscreen = Boolean(fullscreenAvailable);
95
533
  let error = null;
96
534
  let notes = [];
535
+ let transition = null;
97
536
  let displayChanged = false;
98
537
  let visibilityHidden = false;
99
538
  let hiddenPause = false;
100
539
  let ui = null;
540
+ // A host that does not inject a live position still gets cumulative steps:
541
+ // the controller remembers the tick it last committed. A live getter always
542
+ // wins, so the real page reads the show's own clock.
543
+ let fallbackTick = typeof position === 'number' && Number.isFinite(position) ? position : 0;
101
544
 
102
545
  function errorView() {
103
546
  if (!error) {
@@ -123,10 +566,19 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
123
566
  else if (state === 'paused' || state === 'press-to-resume') primary = { label: 'Resume', action: 'resume' };
124
567
  else if (state === 'ended' || state === 'stopped') primary = { label: 'Restart', action: 'restart' };
125
568
 
126
- const secondary = state === 'ready' && canFullscreen
569
+ let secondary = PLAYABLE_STATES.has(state) && canFullscreen
127
570
  ? { label: 'Fullscreen', action: 'fullscreen' }
128
571
  : null;
129
572
 
573
+ // A device flip or a backing-store restore is its own visible state: the
574
+ // show's state keeps running underneath, the transport reports the hold,
575
+ // and every command that could race the rebuild is disabled. An actual
576
+ // failure wins over the overlay and keeps its own status.
577
+ if (transition !== null) {
578
+ if (primary) primary = { ...primary, disabled: true };
579
+ if (secondary) secondary = { ...secondary, disabled: true };
580
+ }
581
+
130
582
  let status;
131
583
  if (state === 'loading') status = `loading — ${loadingStep || 'preparing'}`;
132
584
  else if (state === 'ready') {
@@ -145,9 +597,11 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
145
597
 
146
598
  return {
147
599
  state,
148
- status,
600
+ status: transition !== null && state !== 'error' ? transition : status,
601
+ transition: state === 'error' ? null : transition,
149
602
  primary,
150
603
  secondary,
604
+ rangeDisabled: transition !== null,
151
605
  ...errorView(),
152
606
  };
153
607
  }
@@ -194,6 +648,24 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
194
648
  render();
195
649
  }
196
650
 
651
+ /**
652
+ * The visible overlay for a renderer rebuild. It never changes `state`: the
653
+ * show keeps its own state underneath while the status speaks for the flip
654
+ * and the transport's commands are disabled. Blank text is not a status.
655
+ */
656
+ function setTransition(text) {
657
+ const next = String(text ?? '');
658
+ if (next.trim() === '') return;
659
+ transition = next;
660
+ render();
661
+ }
662
+
663
+ function clearTransition() {
664
+ if (transition === null) return;
665
+ transition = null;
666
+ render();
667
+ }
668
+
197
669
  function addNote(note) {
198
670
  const text = String(note ?? '').trim();
199
671
  if (text === '' || notes.includes(text)) return;
@@ -218,6 +690,7 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
218
690
  }
219
691
 
220
692
  function pressPrimary() {
693
+ if (transition !== null) return Promise.resolve(state);
221
694
  if (state === 'ready') return Promise.resolve(actions.start());
222
695
  if (state === 'playing') return Promise.resolve(actions.stop());
223
696
  if (state === 'paused' || state === 'press-to-resume') return Promise.resolve(actions.resume());
@@ -229,7 +702,7 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
229
702
  }
230
703
 
231
704
  async function pressFullscreen() {
232
- if (state !== 'ready' || !canFullscreen) return false;
705
+ if (transition !== null || !canFullscreen) return false;
233
706
  let accepted = false;
234
707
  try {
235
708
  accepted = (await actions.fullscreen()) === true;
@@ -246,6 +719,41 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
246
719
  else if (ui?.errorVisible) view.focusError();
247
720
  }
248
721
 
722
+ function scoreMeta() {
723
+ return typeof meta === 'function' ? meta() : meta;
724
+ }
725
+
726
+ function currentTick() {
727
+ if (typeof position === 'function') {
728
+ const live = finiteNumber(position(), NaN);
729
+ if (Number.isFinite(live)) return live;
730
+ }
731
+ return fallbackTick;
732
+ }
733
+
734
+ function stepLimit() {
735
+ const value = typeof totalTicks === 'function' ? totalTicks() : totalTicks;
736
+ const limit = finiteNumber(value, NaN);
737
+ if (Number.isFinite(limit) && limit >= 0) return Math.floor(limit);
738
+ // No host-reported end: the controller still refuses to step past the
739
+ // effective end (the shorter of the host policy and the score) on the
740
+ // same 100-tick grid the show uses.
741
+ const host = currentSeconds === null ? Infinity : currentSeconds;
742
+ const effective = effectiveEndSeconds(host, scoreSeconds(scoreMeta()));
743
+ return Number.isFinite(effective)
744
+ ? Math.floor(effective * SHOW_TICKS_PER_SECOND + 1e-6)
745
+ : Infinity;
746
+ }
747
+
748
+ /** One beat for a plain arrow, one bar for Shift+Arrow or PageUp/PageDown. */
749
+ function stepTick(key, shiftKey) {
750
+ const model = tempoModel(scoreMeta());
751
+ const bar = key === 'PageUp' || key === 'PageDown' || shiftKey === true;
752
+ const direction = key === 'ArrowRight' || key === 'PageUp' ? 1 : -1;
753
+ const beats = direction * (bar ? model.beatsPerBar : 1);
754
+ return tickAfterBeats(currentTick(), beats, scoreMeta(), stepLimit());
755
+ }
756
+
249
757
  function spaceAction() {
250
758
  if (state === 'ready') return actions.start();
251
759
  if (state === 'playing') return actions.pause();
@@ -268,24 +776,64 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
268
776
  }
269
777
  }
270
778
 
779
+ /**
780
+ * The browser's fullscreen state belongs to the browser surface. The view is
781
+ * the injected surface when it reports one; otherwise the event's own
782
+ * document (and, in a page, `globalThis.document`) carries the element.
783
+ */
784
+ function fullscreenActive(event) {
785
+ if (typeof view.fullscreenActive === 'function') return Boolean(view.fullscreenActive());
786
+ const ownerDocument = event?.target?.ownerDocument ?? globalThis.document;
787
+ return Boolean(ownerDocument?.fullscreenElement);
788
+ }
789
+
271
790
  function handleKey(event) {
272
791
  if (!event || event.defaultPrevented) return false;
792
+ // A rebuild owns the transport: no key may start, stop, pause or restart
793
+ // the show between the restart and the seek back.
794
+ if (transition !== null) return false;
273
795
  if (isTextEntry(event.target)) return false;
274
796
  if (event.ctrlKey || event.metaKey || event.altKey) return false;
275
797
 
276
798
  const key = event.key;
277
799
  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;
282
- if (!SPACE_STATES.has(state)) return false;
800
+ // A focused secondary or device button, or a native disclosure, keeps
801
+ // its Space activation. The primary's Space is the transport contract,
802
+ // so it is handled once here.
803
+ const kind = controlKind(event.target);
804
+ if (kind === 'fullscreen' || kind === 'device' || kind === 'scene'
805
+ || keepsNativeSpace(event.target)) return false;
806
+ // At ended/stopped the focused primary is Restart, and a native button
807
+ // activates on Space. Swallow that default so only the explicit gesture
808
+ // (the button, or R) can restart; Space never does.
809
+ if (!SPACE_STATES.has(state)) {
810
+ if (RESTARTABLE_STATES.has(state)) {
811
+ event.preventDefault?.();
812
+ return true;
813
+ }
814
+ return false;
815
+ }
283
816
  event.preventDefault?.();
284
817
  dispatch(spaceAction);
285
818
  return true;
286
819
  }
287
820
 
821
+ if (ARROW_KEYS.has(key)) {
822
+ // The controller owns stepping so it works with or without range focus.
823
+ // A text field was excluded above; a disclosure keeps its native keys.
824
+ if (!PLAYABLE_STATES.has(state)) return false;
825
+ if (keepsNativeSpace(event.target)) return false;
826
+ event.preventDefault?.();
827
+ const tick = stepTick(key, event.shiftKey === true);
828
+ fallbackTick = tick;
829
+ dispatch(() => actions.seek?.(tick));
830
+ return true;
831
+ }
832
+
288
833
  if (key === 'Escape' && ACTIVE_STATES.has(state)) {
834
+ // Escape in fullscreen is the browser's own exit gesture; the show keeps
835
+ // playing. Only a windowed Escape is the page's Stop.
836
+ if (fullscreenActive(event)) return false;
289
837
  event.preventDefault?.();
290
838
  dispatch(() => actions.stop());
291
839
  return true;
@@ -301,13 +849,32 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
301
849
  return false;
302
850
  }
303
851
 
304
- function handleResize() {
852
+ /**
853
+ * A letterbox/layout change (window resize, fullscreen entry, rotation)
854
+ * rescales the page only. It never stops the show and never claims the
855
+ * display changed; it answers whether the show was active so the caller can
856
+ * decide whether it needs a redraw.
857
+ */
858
+ function handleLayoutChange() {
859
+ return ACTIVE_STATES.has(state);
860
+ }
861
+
862
+ /**
863
+ * An unintended output change keeps the old stop-and-announce policy; the
864
+ * page's own device flip and DPR restore use the position-preserving replay
865
+ * instead and never route through this path.
866
+ */
867
+ function handleOutputChange() {
305
868
  if (displayChanged || !ACTIVE_STATES.has(state)) return false;
306
869
  displayChanged = true;
307
870
  dispatch(() => actions.stop());
308
871
  return true;
309
872
  }
310
873
 
874
+ // Existing callers and tests keep the old name; it is the output-change
875
+ // policy, not the layout one.
876
+ const handleResize = handleOutputChange;
877
+
311
878
  async function setVisibility(hidden) {
312
879
  visibilityHidden = Boolean(hidden);
313
880
  if (visibilityHidden) {
@@ -353,10 +920,14 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
353
920
  setLoading,
354
921
  setSeconds,
355
922
  setFullscreenAvailable,
923
+ setTransition,
924
+ clearTransition,
356
925
  addNote,
357
926
  fail,
358
927
  handleState,
359
928
  handleKey,
929
+ handleLayoutChange,
930
+ handleOutputChange,
360
931
  handleResize,
361
932
  handleFullscreenExit,
362
933
  pressPrimary,