animader-cli 0.5.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,16 +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']);
11
12
  const PLAYABLE_STATES = new Set(['ready', 'playing', 'paused', 'press-to-resume', 'ended', 'stopped']);
12
13
  const SPACE_STATES = new Set(['ready', 'playing', 'paused', 'press-to-resume']);
13
14
  const RESTARTABLE_STATES = new Set(['ended', 'stopped']);
15
+ const ARROW_KEYS = new Set(['ArrowRight', 'ArrowLeft', 'PageUp', 'PageDown']);
14
16
 
15
17
  /** A host length in the design's one-decimal form when it is a whole second. */
16
18
  export function formatSeconds(seconds) {
@@ -18,6 +20,48 @@ export function formatSeconds(seconds) {
18
20
  return Number.isInteger(seconds) ? seconds.toFixed(1) : String(seconds);
19
21
  }
20
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
+
21
65
  // Pacer's tick grid and the transport's own grid are different clocks:
22
66
  // PPC is one bar of pacer ticks (a quarter is PPC / beatsPerBar), while the
23
67
  // show's seek grid is 100 ticks per second. The tempo map is authored in the
@@ -77,6 +121,8 @@ function tempoModel(meta) {
77
121
  startTick: point.tick,
78
122
  startSeconds,
79
123
  endSeconds: startSeconds + spanSeconds,
124
+ startBeat: point.tick / ticksPerBeat,
125
+ beats: span / ticksPerBeat,
80
126
  bpm: point.bpm,
81
127
  });
82
128
  startSeconds += spanSeconds;
@@ -91,17 +137,123 @@ function tempoModel(meta) {
91
137
  };
92
138
  }
93
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
+
177
+ /**
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
+
94
245
  /**
95
246
  * 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.
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.
99
251
  */
100
252
  export function formatPosition(tick, meta) {
101
253
  const model = tempoModel(meta);
102
254
  const seconds = Math.max(0, finiteNumber(tick, 0) / SHOW_TICKS_PER_SECOND);
103
255
 
104
- if (seconds >= model.scoreEndSeconds - POSITION_EPSILON) {
256
+ if (seconds > model.scoreEndSeconds + POSITION_EPSILON) {
105
257
  return `hold · ${formatBpm(model.endBpm)} BPM`;
106
258
  }
107
259
 
@@ -270,12 +422,13 @@ export function readoutPieces(text) {
270
422
  }
271
423
 
272
424
  /**
273
- * The actual decoded soundtrack length measured against the host end. A long
274
- * track is cut at the host end; a short one leaves silence. This is a decode
275
- * measurement, never a claim that music was heard.
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.
276
429
  *
277
430
  * @param {number} decodedSeconds
278
- * @param {number} hostSeconds
431
+ * @param {number} showSeconds
279
432
  * @returns {string|null}
280
433
  */
281
434
  export function audioDurationNote(decodedSeconds, hostSeconds) {
@@ -287,9 +440,9 @@ export function audioDurationNote(decodedSeconds, hostSeconds) {
287
440
  if (Math.abs(difference) <= 1e-3) return null;
288
441
  const host = formatSeconds(hostSeconds);
289
442
  if (difference > 0) {
290
- 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`;
291
444
  }
292
- 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`;
293
446
  }
294
447
 
295
448
  function normalizeError(error) {
@@ -307,11 +460,29 @@ function normalizeError(error) {
307
460
  return { code: 'error', message: String(error), stage: '', document: '', diagnostics: [] };
308
461
  }
309
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
+
310
469
  function isTextEntry(target) {
311
470
  if (!target) return false;
312
471
  if (target.isContentEditable === true) return true;
313
472
  const tag = typeof target.tagName === 'string' ? target.tagName.toLowerCase() : '';
314
- 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');
315
486
  }
316
487
 
317
488
  function controlKind(target) {
@@ -328,14 +499,28 @@ function keepsNativeSpace(target) {
328
499
  /**
329
500
  * @param {object} options
330
501
  * @param {object} options.actions actual show commands: start, pause, resume,
331
- * stop, restart, fullscreen. Each may return a promise.
502
+ * stop, restart, fullscreen, seek. Each may return a promise.
332
503
  * @param {object} options.view browser surface: apply(ui), activeElement(),
333
504
  * focusPrimary(), focusSecondary(), focusError(), and optionally
334
505
  * fullscreenActive() for the browser's current fullscreen element.
335
506
  * @param {number|null} [options.seconds] the host show length from config.
336
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.
337
514
  */
338
- 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
+ }) {
339
524
  if (!actions || typeof actions !== 'object') throw new TypeError('createPlayerController needs actual show action commands');
340
525
  if (!view || typeof view.apply !== 'function' || typeof view.activeElement !== 'function') {
341
526
  throw new TypeError('createPlayerController needs a view with apply() and activeElement()');
@@ -352,6 +537,10 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
352
537
  let visibilityHidden = false;
353
538
  let hiddenPause = false;
354
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;
355
544
 
356
545
  function errorView() {
357
546
  if (!error) {
@@ -530,6 +719,41 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
530
719
  else if (ui?.errorVisible) view.focusError();
531
720
  }
532
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
+
533
757
  function spaceAction() {
534
758
  if (state === 'ready') return actions.start();
535
759
  if (state === 'playing') return actions.pause();
@@ -579,12 +803,33 @@ export function createPlayerController({ actions, view, seconds = null, fullscre
579
803
  const kind = controlKind(event.target);
580
804
  if (kind === 'fullscreen' || kind === 'device' || kind === 'scene'
581
805
  || keepsNativeSpace(event.target)) return false;
582
- if (!SPACE_STATES.has(state)) 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
+ }
583
816
  event.preventDefault?.();
584
817
  dispatch(spaceAction);
585
818
  return true;
586
819
  }
587
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
+
588
833
  if (key === 'Escape' && ACTIVE_STATES.has(state)) {
589
834
  // Escape in fullscreen is the browser's own exit gesture; the show keeps
590
835
  // playing. Only a windowed Escape is the page's Stop.
@@ -4,14 +4,18 @@
4
4
  //
5
5
  // The protocol is deliberately small and honest: on a successful build the
6
6
  // server broadcasts `reload` with the URL of the new generation, and the
7
- // page does a full location.replace onto it — playback stops, the page
8
- // boots into READY and requires Start again. No state is preserved and no
9
- // hot reload is claimed or attempted. On a failed build the server
10
- // broadcasts `stale` with the build error: the page keeps the last
11
- // successful view and shows a clear indication; recovery is the next
12
- // successful edit's reload. A (re)connecting client is greeted with the
13
- // CURRENT generation, so a channel that reconnects after a reload lands on
14
- // whatever is served now.
7
+ // page does a full location.replace onto it. Playback stops; the dev page
8
+ // writes the visible tick to sessionStorage on the way out (boot.mjs owns
9
+ // that store) and the fresh page comes back paused at that moment — a
10
+ // `?t=<seconds>` moment on the reload URL wins — so a rebuild keeps the
11
+ // frame being inspected instead of returning to zero. No hot reload is
12
+ // claimed or attempted; the published release entry never carries this
13
+ // channel and never reads or writes the store. On a failed build the server
14
+ // broadcasts `stale`
15
+ // with the build error: the page keeps the last successful view and shows a
16
+ // clear indication; recovery is the next successful edit's reload. A
17
+ // (re)connecting client is greeted with the CURRENT generation, so a
18
+ // channel that reconnects after a reload lands on whatever is served now.
15
19
  //
16
20
  // The client uses the browser's own EventSource reconnection; no timers,
17
21
  // no workers, no second clock.
@@ -76,8 +80,9 @@ export function connectDevChannel({ generation, onStale = () => {}, eventSourceC
76
80
  return;
77
81
  }
78
82
  if (detail && typeof detail.url === 'string' && detail.url.startsWith('/')) {
79
- // Stop playback and reload onto the new generation: a fresh boot, a
80
- // fresh READY, Start pressed again by the person editing.
83
+ // Stop playback and reload onto the new generation: a fresh boot that
84
+ // restores the moment the page wrote on the way out (or the reload
85
+ // URL's `?t=`), paused and never playing.
81
86
  window.location.replace(detail.url);
82
87
  }
83
88
  });
@@ -73,15 +73,15 @@ function clamp(value, min, max) {
73
73
 
74
74
  /**
75
75
  * The decoded soundtrack's own end is a product-visible boundary only when
76
- * the distance to the host end survives the transport's 10 ms quantum. A
77
- * decode rounding difference (35.999977 s against a 36 s host) is not a
78
- * zero-length silence region, so it returns null.
76
+ * the distance to the show's effective end survives the transport's 10 ms
77
+ * quantum. A decode rounding difference (35.999977 s against a 35.12 s show
78
+ * end) is not a zero-length silence region, so it returns null.
79
79
  */
80
- export function audioEndBoundary(hostSeconds, decodedSeconds) {
81
- const host = numberFrom(hostSeconds, NaN);
80
+ export function audioEndBoundary(showSeconds, decodedSeconds) {
81
+ const show = numberFrom(showSeconds, NaN);
82
82
  const decoded = numberFrom(decodedSeconds, NaN);
83
- if (!Number.isFinite(host) || !Number.isFinite(decoded) || decoded <= 0) return null;
84
- const interval = host - decoded;
83
+ if (!Number.isFinite(show) || !Number.isFinite(decoded) || decoded <= 0) return null;
84
+ const interval = show - decoded;
85
85
  return Math.round(interval / QUANTUM_SECONDS) >= 1 ? decoded : null;
86
86
  }
87
87
 
@@ -224,15 +224,15 @@ function edgeBracket(ctx, width, side, y, color) {
224
224
  ctx.fillRect(side === 'left' ? left + 3 : left, y, 1, 7);
225
225
  }
226
226
 
227
- function ariaAt(seconds, hostSeconds, meta) {
227
+ function ariaAt(seconds, showSeconds, meta) {
228
228
  const position = formatPosition(Math.round(seconds * 100), meta);
229
229
  const hold = /^hold · (.+) BPM$/.exec(position);
230
230
  if (hold) {
231
- return `hold, ${seconds.toFixed(2)} seconds of ${hostSeconds.toFixed(2)}, ${hold[1]} BPM`;
231
+ return `hold, ${seconds.toFixed(2)} seconds of ${showSeconds.toFixed(2)}, ${hold[1]} BPM`;
232
232
  }
233
233
  const parsed = /^bar (\d+) · beat (\d+) · (.+) BPM$/.exec(position);
234
234
  if (!parsed) return position;
235
- return `bar ${parsed[1]}, beat ${parsed[2]}, ${seconds.toFixed(2)} seconds of ${hostSeconds.toFixed(2)}, ${parsed[3]} BPM`;
235
+ return `bar ${parsed[1]}, beat ${parsed[2]}, ${seconds.toFixed(2)} seconds of ${showSeconds.toFixed(2)}, ${parsed[3]} BPM`;
236
236
  }
237
237
 
238
238
  function ariaDuringDrag(seconds, frameSeconds, meta) {
@@ -261,11 +261,18 @@ export function mountTransport({
261
261
  }
262
262
  host.classList?.add?.('panel--transport');
263
263
  const document = host.ownerDocument ?? globalThis.document;
264
- const hostSeconds = numberFrom(seconds, 0) > 0 ? numberFrom(seconds, 0) : 0;
264
+ // `seconds` is the page's one effective length: the shorter of the host
265
+ // policy and the score's own tempo-integrated end, already on the show's
266
+ // 100-tick grid. The ruler, range, readout and seeks all share it.
267
+ const showSeconds = numberFrom(seconds, 0) > 0 ? numberFrom(seconds, 0) : 0;
265
268
  const model = buildModel(meta);
266
- const scoreEndSeconds = Number.isFinite(model.scoreEndSeconds) ? model.scoreEndSeconds : hostSeconds;
269
+ const scoreEndSeconds = Number.isFinite(model.scoreEndSeconds) ? model.scoreEndSeconds : showSeconds;
270
+ // The score's own end is the ruler's end unless the host is genuinely
271
+ // shorter. One seek quantum is the smallest interval the transport can
272
+ // reach, so a score within that quantum of the end has no hold to show.
273
+ const scorePastEnd = scoreEndSeconds > showSeconds + QUANTUM_SECONDS;
267
274
  const audioSeconds = numberFrom(decodedSeconds, NaN);
268
- const audioEnd = audioEndBoundary(hostSeconds, audioSeconds);
275
+ const audioEnd = audioEndBoundary(showSeconds, audioSeconds);
269
276
  const windows = sceneWindows(meta);
270
277
  const controls = (Array.isArray(meta?.controls) ? meta.controls : []).map(describeControl);
271
278
  const mountId = `transport-${mountSequence += 1}`;
@@ -298,7 +305,7 @@ export function mountTransport({
298
305
  range.type = 'range';
299
306
  range.className = 'ruler-range';
300
307
  range.min = '0';
301
- range.max = String(hostSeconds);
308
+ range.max = String(showSeconds);
302
309
  range.step = String(QUANTUM_SECONDS);
303
310
  range.value = '0';
304
311
  range.setAttribute('aria-label', 'Show position');
@@ -407,12 +414,14 @@ export function mountTransport({
407
414
  parts.push(`tempo change to ${bpm} BPM at bar ${bar}`);
408
415
  }
409
416
  }
410
- if (scoreEndSeconds < hostSeconds - EPS) {
411
- parts.push(`hold from ${scoreEndSeconds.toFixed(2)} to ${hostSeconds.toFixed(2)} seconds`);
417
+ if (scorePastEnd) {
418
+ parts.push(`hold from ${showSeconds.toFixed(2)} to ${scoreEndSeconds.toFixed(2)} seconds`);
419
+ } else if (Number.isFinite(model.scoreEndSeconds)) {
420
+ parts.push(`score ends at ${scoreEndSeconds.toFixed(2)} seconds`);
412
421
  }
413
- if (Number.isFinite(audioSeconds) && audioSeconds < hostSeconds - EPS) {
422
+ if (Number.isFinite(audioSeconds) && audioSeconds < showSeconds - EPS) {
414
423
  if (audioEnd !== null) {
415
- parts.push(`silence from ${audioEnd.toFixed(2)} to ${hostSeconds.toFixed(2)} seconds`);
424
+ parts.push(`silence from ${audioEnd.toFixed(2)} to ${showSeconds.toFixed(2)} seconds`);
416
425
  }
417
426
  }
418
427
  if (windows.length > 0) {
@@ -1061,29 +1070,33 @@ export function mountTransport({
1061
1070
  ctx.fillText(label, textX, 10);
1062
1071
  }
1063
1072
 
1064
- // The track is the piece's own extent, never the host tail.
1073
+ // The track is the show's own extent, never a host tail.
1065
1074
  const trackStart = Math.max(0, Math.round(xOf(0)));
1066
- const trackEnd = Math.min(width, Math.round(xOf(scoreEndSeconds)));
1075
+ const trackEnd = Math.min(width, Math.round(xOf(showSeconds)));
1067
1076
  if (trackEnd > trackStart) {
1068
1077
  ctx.fillStyle = palette.track;
1069
1078
  ctx.fillRect(trackStart, 39, trackEnd - trackStart, 1);
1070
1079
  }
1071
1080
 
1072
- // The score end and the hold gap to the host end.
1073
- const scoreEndX = xOf(scoreEndSeconds);
1074
- if (scoreEndX >= 0 && scoreEndX < width) verticalLine(ctx, scoreEndX, 14, 26, palette.scoreEnd);
1075
- const hostEndX = xOf(hostSeconds);
1076
- if (scoreEndSeconds < hostSeconds - EPS && scoreEndX >= 0 && hostEndX > scoreEndX) {
1077
- const mid = (scoreEndX + Math.min(width, hostEndX)) / 2;
1078
- ctx.font = FONT;
1079
- ctx.fillStyle = palette.label;
1080
- ctx.textAlign = 'center';
1081
- ctx.textBaseline = 'alphabetic';
1082
- const labelWidth = ctx.measureText('hold').width;
1083
- if (mid - labelWidth / 2 >= 0 && mid + labelWidth / 2 <= width) ctx.fillText('hold', mid, 36);
1081
+ // A score running past the ruler's end keeps its own marker and the hold
1082
+ // label in the unreachable remainder. A score that ends at the ruler's
1083
+ // end has no hold to name, so neither is drawn.
1084
+ if (scorePastEnd) {
1085
+ const scoreEndX = xOf(scoreEndSeconds);
1086
+ if (scoreEndX >= 0 && scoreEndX < width) verticalLine(ctx, scoreEndX, 14, 26, palette.scoreEnd);
1087
+ const endX = xOf(showSeconds);
1088
+ if (endX >= 0 && scoreEndX > endX) {
1089
+ const mid = (endX + Math.min(width, scoreEndX)) / 2;
1090
+ ctx.font = FONT;
1091
+ ctx.fillStyle = palette.label;
1092
+ ctx.textAlign = 'center';
1093
+ ctx.textBaseline = 'alphabetic';
1094
+ const labelWidth = ctx.measureText('hold').width;
1095
+ if (mid - labelWidth / 2 >= 0 && mid + labelWidth / 2 <= width) ctx.fillText('hold', mid, 36);
1096
+ }
1084
1097
  }
1085
1098
 
1086
- // A decoded soundtrack shorter than the host ends in silence; the
1099
+ // A decoded soundtrack shorter than the show's end leaves silence; the
1087
1100
  // boundary is the decode's own measurement and the playhead continues.
1088
1101
  // A tail that rounds away at the seek quantum is not drawn at all.
1089
1102
  if (audioEnd !== null) {
@@ -1160,8 +1173,8 @@ export function mountTransport({
1160
1173
  writeReadout(elapsedElement, `frame ${frame.toFixed(2)} s → seek ${at.toFixed(2)} s · release`);
1161
1174
  range.setAttribute('aria-valuetext', ariaDuringDrag(at, frame, meta));
1162
1175
  } else {
1163
- writeReadout(elapsedElement, formatElapsed(at, hostSeconds));
1164
- range.setAttribute('aria-valuetext', ariaAt(at, hostSeconds, meta));
1176
+ writeReadout(elapsedElement, formatElapsed(at, showSeconds));
1177
+ range.setAttribute('aria-valuetext', ariaAt(at, showSeconds, meta));
1165
1178
  }
1166
1179
  }
1167
1180
 
@@ -1255,7 +1268,7 @@ export function mountTransport({
1255
1268
  if (drag || range.disabled) return;
1256
1269
  if (event.isPrimary === false || (event.button !== undefined && event.button !== 0)) return;
1257
1270
  event.preventDefault?.();
1258
- const startValue = clamp(numberFrom(range.value, lastTick / 100), 0, hostSeconds);
1271
+ const startValue = clamp(numberFrom(range.value, lastTick / 100), 0, showSeconds);
1259
1272
  drag = {
1260
1273
  id: event.pointerId,
1261
1274
  startX: event.clientX,
@@ -1286,7 +1299,7 @@ export function mountTransport({
1286
1299
  if (!drag || event.pointerId !== drag.id) return;
1287
1300
  event.preventDefault?.();
1288
1301
  if (event.clientX !== drag.startX) drag.moved = true;
1289
- const proposed = clamp(drag.startValue - (event.clientX - drag.startX) / SCALE, 0, hostSeconds);
1302
+ const proposed = clamp(drag.startValue - (event.clientX - drag.startX) / SCALE, 0, showSeconds);
1290
1303
  drag.proposed = Math.round(proposed * 100) / 100;
1291
1304
  range.value = drag.proposed.toFixed(2);
1292
1305
  updateText();
@@ -1321,45 +1334,17 @@ export function mountTransport({
1321
1334
  if (drag) cancelDrag();
1322
1335
  }
1323
1336
 
1324
- function tickAfterBeats(tick, beats) {
1325
- const seconds = tick / 100;
1326
- let segment = model.segments[0];
1327
- for (const candidate of model.segments) {
1328
- if (seconds >= candidate.startSeconds - EPS) segment = candidate;
1329
- else break;
1330
- }
1331
- if (!segment) return tick;
1332
- const beat = segment.startBeat + ((seconds - segment.startSeconds) * segment.bpm) / 60;
1333
- const target = timeAtBeat(model, beat + beats);
1334
- return clamp(Math.round(target * 100), 0, Math.round(hostSeconds * 100));
1335
- }
1336
-
1337
1337
  function onKeyDown(event) {
1338
- if (event.key === 'Escape') {
1339
- if (drag) {
1340
- event.preventDefault?.();
1341
- cancelDrag();
1342
- }
1343
- return;
1344
- }
1345
- if (drag) return;
1346
- if (event.shiftKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
1347
- event.preventDefault?.();
1348
- const tick = tickAfterBeats(Math.round(lastTick), event.key === 'ArrowRight' ? 1 : -1);
1349
- range.value = (tick / 100).toFixed(2);
1350
- performSeek(tick);
1351
- } else if (event.key === 'PageUp' || event.key === 'PageDown') {
1352
- event.preventDefault?.();
1353
- const direction = event.key === 'PageUp' ? 1 : -1;
1354
- const tick = tickAfterBeats(Math.round(lastTick), direction * model.beatsPerBar);
1355
- range.value = (tick / 100).toFixed(2);
1356
- performSeek(tick);
1357
- }
1338
+ // Arrow/Page stepping belongs to the controller, which owns the show's
1339
+ // position and tempo. The range keeps only its drag cancellation here.
1340
+ if (event.key !== 'Escape' || !drag) return;
1341
+ event.preventDefault?.();
1342
+ cancelDrag();
1358
1343
  }
1359
1344
 
1360
1345
  function onRangeChange() {
1361
1346
  if (drag) return;
1362
- const value = clamp(numberFrom(range.value, lastTick / 100), 0, hostSeconds);
1347
+ const value = clamp(numberFrom(range.value, lastTick / 100), 0, showSeconds);
1363
1348
  const tick = Math.round(value * 100);
1364
1349
  range.value = (tick / 100).toFixed(2);
1365
1350
  performSeek(tick);