@zodal/media 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +73 -2
- package/dist/chunk-3JIQJ7J6.js +148 -0
- package/dist/chunk-3JIQJ7J6.js.map +1 -0
- package/dist/chunk-7I3V4HKP.js +132 -0
- package/dist/chunk-7I3V4HKP.js.map +1 -0
- package/dist/chunk-AMK7QKN7.js +50 -0
- package/dist/chunk-AMK7QKN7.js.map +1 -0
- package/dist/chunk-NBKMSPYQ.js +46 -0
- package/dist/chunk-NBKMSPYQ.js.map +1 -0
- package/dist/chunk-P3EWPYFQ.js +42 -0
- package/dist/chunk-P3EWPYFQ.js.map +1 -0
- package/dist/chunk-YBCEHG5I.js +68 -0
- package/dist/chunk-YBCEHG5I.js.map +1 -0
- package/dist/commands.cjs +198 -0
- package/dist/commands.cjs.map +1 -0
- package/dist/commands.d.cts +17 -0
- package/dist/commands.d.ts +17 -0
- package/dist/commands.js +171 -0
- package/dist/commands.js.map +1 -0
- package/dist/cues.cjs +78 -0
- package/dist/cues.cjs.map +1 -0
- package/dist/cues.d.cts +39 -0
- package/dist/cues.d.ts +39 -0
- package/dist/cues.js +15 -0
- package/dist/cues.js.map +1 -0
- package/dist/follow.cjs +162 -0
- package/dist/follow.cjs.map +1 -0
- package/dist/follow.d.cts +83 -0
- package/dist/follow.d.ts +83 -0
- package/dist/follow.js +19 -0
- package/dist/follow.js.map +1 -0
- package/dist/index.cjs +510 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/playback.cjs +72 -0
- package/dist/playback.cjs.map +1 -0
- package/dist/playback.d.cts +47 -0
- package/dist/playback.d.ts +47 -0
- package/dist/playback.js +11 -0
- package/dist/playback.js.map +1 -0
- package/dist/sleep.cjs +176 -0
- package/dist/sleep.cjs.map +1 -0
- package/dist/sleep.d.cts +99 -0
- package/dist/sleep.d.ts +99 -0
- package/dist/sleep.js +15 -0
- package/dist/sleep.js.map +1 -0
- package/dist/timed-text.cjs +155 -0
- package/dist/timed-text.cjs.map +1 -0
- package/dist/timed-text.d.cts +44 -0
- package/dist/timed-text.d.ts +44 -0
- package/dist/timed-text.js +9 -0
- package/dist/timed-text.js.map +1 -0
- package/dist/transport.cjs +167 -0
- package/dist/transport.cjs.map +1 -0
- package/dist/transport.d.cts +74 -0
- package/dist/transport.d.ts +74 -0
- package/dist/transport.js +110 -0
- package/dist/transport.js.map +1 -0
- package/dist/vtt.cjs +66 -0
- package/dist/vtt.cjs.map +1 -0
- package/dist/vtt.d.cts +22 -0
- package/dist/vtt.d.ts +22 -0
- package/dist/vtt.js +7 -0
- package/dist/vtt.js.map +1 -0
- package/package.json +155 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Thor Whalen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zodal/media
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Headless audio and media UI affordances for the zodal ecosystem: timed text (a transcript, song lyrics, subtitles) that follows the voice and plays from a tapped line, a seek-and-play that works on every engine, and a transport with a queue whose actions are commands.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add @zodal/media
|
|
7
|
+
# ./transport also needs zustand; ./commands also needs acture and zod
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## A transcript or lyrics panel in a few lines
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { createTimedText, createFollow, attachFollow } from '@zodal/media';
|
|
14
|
+
|
|
15
|
+
const audio = document.querySelector('audio')!;
|
|
16
|
+
const panel = document.querySelector('.lyrics') as HTMLElement; // the list's own scroll box
|
|
17
|
+
const lines = [...panel.querySelectorAll('p')] as HTMLElement[];
|
|
18
|
+
|
|
19
|
+
const follow = createFollow({ resumeAfterMs: 4000 }); // lyrics: come back by itself
|
|
20
|
+
const view = attachFollow(panel, follow, { anchor: 0.35 }); // scrolls the panel only
|
|
21
|
+
const text = createTimedText(cues, audio, { follow }); // cues: [{start, end, text, words?}]
|
|
22
|
+
|
|
23
|
+
text.subscribe((now, before) => {
|
|
24
|
+
lines[before.cue]?.classList.remove('on');
|
|
25
|
+
lines[now.cue]?.classList.add('on');
|
|
26
|
+
view.bring(lines[now.cue]);
|
|
27
|
+
});
|
|
28
|
+
lines.forEach((line, i) => line.addEventListener('click', () => text.tapCue(i)));
|
|
29
|
+
audio.addEventListener('timeupdate', text.tick);
|
|
30
|
+
audio.addEventListener('seeked', text.tick);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
A transcript plays from a tapped line (the default). A lyrics panel whose player lives elsewhere passes `playOnTap: false` and only moves there. `createFollow()` without `resumeAfterMs` never comes back by itself: show a "Back to now" button that calls `follow.resume()`.
|
|
34
|
+
|
|
35
|
+
## What is in it
|
|
36
|
+
|
|
37
|
+
| Subpath | What |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `./cues` | `cueAt` (with a 10 ms tolerance, and `gaps: true` for subtitles), `wordAt`, `cuesDuration`, `formatTime`. Pure. |
|
|
40
|
+
| `./vtt` | `parseWebVtt(text)`: a WebVTT (or SRT) file of captions or chapters as cues, with ids and voice-tag speakers. Pure. |
|
|
41
|
+
| `./playback` | `seekThenPlay(el, t)` and `seekLanded(el)`: play from a chosen point, safely on Safari too (below). |
|
|
42
|
+
| `./follow` | `createFollow` (headless: following, finger-down hold, optional auto-resume) and `attachFollow` (one scroll container, never `scrollIntoView`). |
|
|
43
|
+
| `./timed-text` | `createTimedText(cues, port, options)`: the current cue and word, `tapCue`, `cancelHeldPlay`. |
|
|
44
|
+
| `./sleep` | `createSleepTimer(port)`: pause after listening minutes, at a media time or at the end, with a fade; `formatCountdown`, `SLEEP_MINUTES`. |
|
|
45
|
+
| `./transport` | `createMediaPlayer(port)`: a zustand store with play, pause, seek, skip, rate, volume and a queue, over any `MediaPort`. |
|
|
46
|
+
| `./commands` | `mediaCommands(player)`: the transport's actions as [acture](https://www.npmjs.com/package/acture) commands, continuous ones marked. |
|
|
47
|
+
|
|
48
|
+
The root export is the pure part (cues, vtt, playback, follow, timed text), with no dependency at all; the transport and its commands come from their subpaths.
|
|
49
|
+
|
|
50
|
+
## A sleep timer
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { createSleepTimer, formatCountdown } from '@zodal/media';
|
|
54
|
+
|
|
55
|
+
const sleep = createSleepTimer(audio); // listens to `timeupdate` itself
|
|
56
|
+
sleep.set({ kind: 'after', minutes: 15 }); // 15 minutes of listening (a pause stops the count)
|
|
57
|
+
sleep.set({ kind: 'at', seconds: 1260, label: 'end of chapter' });
|
|
58
|
+
sleep.set({ kind: 'end' }); // the end of the item
|
|
59
|
+
sleep.subscribe((s) => chip.textContent = s.remainingMs == null ? 'Sleep' : formatCountdown(s.remainingMs));
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
It fades the volume over the last 10 s (`fadeMs`) and restores it after the pause, a cancel or an `extend(minutes)`. A seek past an `at` point ends the timer (`ended: 'passed'`) rather than pausing at once. `sleepCommands(timer)` in `./commands` gives `sleep.after`, `sleep.at`, `sleep.end`, `sleep.extend` and `sleep.cancel`.
|
|
63
|
+
|
|
64
|
+
## The trap it closes: tapping a line after the end
|
|
65
|
+
|
|
66
|
+
In WebKit (Safari, and every browser on an iPhone or iPad), `el.currentTime = t; el.play()` on a media element that has *ended* starts from the end, which ends again at once, or from 0, because the seek has not landed when `play()` runs. Chromium and Firefox apply the seek first. It showed as "after the overview finished, tapping the transcript played it from the start" (2026-11-13). `seekThenPlay` reads whether the element had ended before seeking and, if its seek is still landing, plays on `seeked`; a pause meanwhile cancels it (an `AbortSignal`). `createTimedText` and `createMediaPlayer` use it. Measured in Playwright WebKit: 12 of 12 taps restarted at 0 before, 16 of 16 played from the line after.
|
|
67
|
+
|
|
68
|
+
## Where it comes from
|
|
69
|
+
|
|
70
|
+
It pools the fleet's copies of the same ideas: `@zodal/speech` (i2mint/zodal-speech: the transcript player of spoken overviews, whose `./media` seed became `./transport`), arioso's lyrics navigator (container scroll at 35 %, auto-resume, finger hold), and srtplay (gaps between subtitles). The name and scope were decided in media_hub's research (`@zodal/media`, with `@zodal/speech` kept as a preset; i2mint/zodal-speech#4). The timed-text wire model belongs to lacing (`AlignedTrackV1`); this package reads cues structurally.
|
|
71
|
+
|
|
72
|
+
Next: `./media-session` (lock-screen controls with `setPositionState`), `./react` (`useMediaClock`, `<TimedText>`), `./waveform`, `./range` (loop, A–B), and `@zodal/speech` re-based on this package.
|
|
73
|
+
|
|
74
|
+
Part of [zodal](https://github.com/i2mint/zodal). MIT.
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// src/sleep.ts
|
|
2
|
+
var DEFAULT_SLEEP_FADE_MS = 1e4;
|
|
3
|
+
var DEFAULT_SLEEP_TICK_MS = 1e3;
|
|
4
|
+
var SLEEP_MINUTES = [5, 10, 15, 20, 30, 45, 60, 90];
|
|
5
|
+
var JUMP_S = 3;
|
|
6
|
+
var END_EPSILON_S = 0.25;
|
|
7
|
+
var OFF = { target: null, remainingMs: null, fading: false, ended: null };
|
|
8
|
+
function createSleepTimer(port, options = {}) {
|
|
9
|
+
const {
|
|
10
|
+
fadeMs = DEFAULT_SLEEP_FADE_MS,
|
|
11
|
+
tickMs = DEFAULT_SLEEP_TICK_MS,
|
|
12
|
+
gain,
|
|
13
|
+
pause = () => port.pause(),
|
|
14
|
+
now = () => Date.now(),
|
|
15
|
+
setTimer = (fn, ms) => setTimeout(fn, ms),
|
|
16
|
+
clearTimer = (h) => clearTimeout(h)
|
|
17
|
+
} = options;
|
|
18
|
+
let state = OFF;
|
|
19
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
20
|
+
const emit = (next) => {
|
|
21
|
+
const previous = state;
|
|
22
|
+
state = next;
|
|
23
|
+
listeners.forEach((l) => l(state, previous));
|
|
24
|
+
};
|
|
25
|
+
let leftMs = 0;
|
|
26
|
+
let lastAt = 0;
|
|
27
|
+
let lastTime = 0;
|
|
28
|
+
let volume = null;
|
|
29
|
+
let fadingNow = false;
|
|
30
|
+
let handle = null;
|
|
31
|
+
const setLevel = (level) => {
|
|
32
|
+
if (gain) {
|
|
33
|
+
gain(level);
|
|
34
|
+
fadingNow = level < 1;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (level >= 1) {
|
|
38
|
+
if (volume !== null) port.volume = volume;
|
|
39
|
+
volume = null;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (volume === null) volume = port.volume;
|
|
43
|
+
port.volume = volume * level;
|
|
44
|
+
};
|
|
45
|
+
const restoreVolume = () => {
|
|
46
|
+
if (gain) {
|
|
47
|
+
if (fadingNow) gain(1);
|
|
48
|
+
fadingNow = false;
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
setLevel(1);
|
|
52
|
+
};
|
|
53
|
+
const schedule = () => {
|
|
54
|
+
if (handle !== null) clearTimer(handle);
|
|
55
|
+
handle = state.target ? setTimer(tick, state.fading ? Math.min(100, tickMs) : tickMs) : null;
|
|
56
|
+
};
|
|
57
|
+
const stop = (reason) => {
|
|
58
|
+
restoreVolume();
|
|
59
|
+
if (handle !== null) clearTimer(handle);
|
|
60
|
+
handle = null;
|
|
61
|
+
emit({ ...OFF, ended: reason });
|
|
62
|
+
};
|
|
63
|
+
const mediaLeftMs = (seconds) => Math.max(0, seconds - port.currentTime) / (port.playbackRate || 1) * 1e3;
|
|
64
|
+
function tick() {
|
|
65
|
+
const target = state.target;
|
|
66
|
+
if (!target) return;
|
|
67
|
+
const t = now();
|
|
68
|
+
const time = port.currentTime;
|
|
69
|
+
const playing = !port.paused;
|
|
70
|
+
let remaining;
|
|
71
|
+
if (target.kind === "after") {
|
|
72
|
+
if (playing) leftMs -= Math.max(0, t - lastAt);
|
|
73
|
+
remaining = leftMs;
|
|
74
|
+
} else {
|
|
75
|
+
const at = target.kind === "at" ? target.seconds : port.duration;
|
|
76
|
+
if (!Number.isFinite(at) || at <= 0) {
|
|
77
|
+
remaining = Infinity;
|
|
78
|
+
} else {
|
|
79
|
+
const jumped = Math.abs(time - lastTime) > JUMP_S * Math.max(1, port.playbackRate) + (t - lastAt) / 1e3;
|
|
80
|
+
if (jumped && lastTime < at - END_EPSILON_S && time > at) {
|
|
81
|
+
lastAt = t;
|
|
82
|
+
lastTime = time;
|
|
83
|
+
return stop("passed");
|
|
84
|
+
}
|
|
85
|
+
remaining = port.ended || time >= at - END_EPSILON_S ? 0 : mediaLeftMs(at);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
lastAt = t;
|
|
89
|
+
lastTime = time;
|
|
90
|
+
if (remaining <= 0) {
|
|
91
|
+
if (playing) pause();
|
|
92
|
+
return stop("slept");
|
|
93
|
+
}
|
|
94
|
+
const fading = playing && fadeMs > 0 && remaining <= fadeMs;
|
|
95
|
+
if (fading) setLevel(remaining / fadeMs);
|
|
96
|
+
else restoreVolume();
|
|
97
|
+
emit({ target, remainingMs: Number.isFinite(remaining) ? Math.round(remaining) : null, fading, ended: null });
|
|
98
|
+
schedule();
|
|
99
|
+
}
|
|
100
|
+
const onTimeupdate = () => tick();
|
|
101
|
+
port.addEventListener?.("timeupdate", onTimeupdate);
|
|
102
|
+
const timer = {
|
|
103
|
+
get: () => state,
|
|
104
|
+
subscribe(listener) {
|
|
105
|
+
listeners.add(listener);
|
|
106
|
+
return () => listeners.delete(listener);
|
|
107
|
+
},
|
|
108
|
+
set(target) {
|
|
109
|
+
restoreVolume();
|
|
110
|
+
if (target.kind === "after") leftMs = Math.max(0, target.minutes) * 6e4;
|
|
111
|
+
lastAt = now();
|
|
112
|
+
lastTime = port.currentTime;
|
|
113
|
+
state = { ...OFF, target };
|
|
114
|
+
tick();
|
|
115
|
+
},
|
|
116
|
+
extend(minutes) {
|
|
117
|
+
const target = state.target;
|
|
118
|
+
if (!target) return timer.set({ kind: "after", minutes });
|
|
119
|
+
const base = target.kind === "after" ? leftMs : state.remainingMs ?? 0;
|
|
120
|
+
timer.set({ kind: "after", minutes: (base + minutes * 6e4) / 6e4 });
|
|
121
|
+
},
|
|
122
|
+
cancel() {
|
|
123
|
+
if (state.target) stop("cancelled");
|
|
124
|
+
},
|
|
125
|
+
tick,
|
|
126
|
+
dispose() {
|
|
127
|
+
port.removeEventListener?.("timeupdate", onTimeupdate);
|
|
128
|
+
if (state.target) restoreVolume();
|
|
129
|
+
if (handle !== null) clearTimer(handle);
|
|
130
|
+
handle = null;
|
|
131
|
+
listeners.clear();
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
return timer;
|
|
135
|
+
}
|
|
136
|
+
function formatCountdown(ms) {
|
|
137
|
+
const s = Math.max(0, Math.ceil(ms / 1e3));
|
|
138
|
+
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export {
|
|
142
|
+
DEFAULT_SLEEP_FADE_MS,
|
|
143
|
+
DEFAULT_SLEEP_TICK_MS,
|
|
144
|
+
SLEEP_MINUTES,
|
|
145
|
+
createSleepTimer,
|
|
146
|
+
formatCountdown
|
|
147
|
+
};
|
|
148
|
+
//# sourceMappingURL=chunk-3JIQJ7J6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sleep.ts"],"sourcesContent":["/**\n * A sleep timer: pause the media after some listening time, or at a point in it (the end of a\n * chapter, the end of the item), fading the volume out first so the stop does not wake anyone.\n * Headless: no DOM beyond an optional `timeupdate` listener on the port, no zustand, no React.\n *\n * ```ts\n * const sleep = createSleepTimer(audio);\n * sleep.set({ kind: 'after', minutes: 15 }); // 15 minutes of listening\n * sleep.set({ kind: 'at', seconds: 1260 }); // at 21:00 in the item (a chapter's end)\n * sleep.set({ kind: 'end' }); // at the end of the item\n * sleep.extend(5); sleep.cancel();\n * sleep.subscribe((s) => render(s.remainingMs, s.fading));\n * ```\n *\n * Choices, each a default the host can change:\n * - **Listening time, not clock time.** `after` counts down only while the media plays: a person\n * who paused is not asleep, and a timer that ran out during a pause would surprise them.\n * - **A fade** of `fadeMs` (10 s) before the pause; the volume is restored after the pause, after a\n * cancel and after an extend, so the next play is at the volume the person chose. iOS ignores\n * `volume` on a media element: there the fade has no audible effect and the pause still happens; a\n * host that routes the element through Web Audio passes `gain` to fade a `GainNode` instead.\n * - **A jump past an `at` point cancels the timer** (reason `passed`) instead of pausing at once\n * after a seek; a host that wants \"the end of the chapter I am in now\" sets it again.\n * - **Ticks from two clocks**: its own timer (smooth countdown) and the port's `timeupdate` when the\n * port has one, because a phone throttles timers on a hidden page while the audio keeps playing.\n */\n\n/** What the timer needs from a media element (an `HTMLMediaElement` is one). */\nexport interface SleepPort {\n readonly currentTime: number;\n readonly duration: number;\n readonly paused: boolean;\n readonly ended?: boolean;\n readonly playbackRate: number;\n volume: number;\n pause(): void;\n addEventListener?(type: 'timeupdate', listener: () => void): void;\n removeEventListener?(type: 'timeupdate', listener: () => void): void;\n}\n\nexport type SleepTarget =\n /** After this many minutes of listening. */\n | { kind: 'after'; minutes: number }\n /** When playback reaches this media time (seconds); `label` names it for the UI (\"end of chapter\"). */\n | { kind: 'at'; seconds: number; label?: string }\n /** When playback reaches the end of the item. */\n | { kind: 'end' };\n\nexport type SleepEndReason = 'slept' | 'cancelled' | 'passed';\n\nexport interface SleepState {\n /** The target while the timer runs, `null` when it is off. */\n target: SleepTarget | null;\n /** Listening time left, in ms (an `at`/`end` target: estimated from media time and speed); `null` when off. */\n remainingMs: number | null;\n /** The volume is being lowered: the pause is less than `fadeMs` away. */\n fading: boolean;\n /** Why the last timer ended, until a new one is set. */\n ended: SleepEndReason | null;\n}\n\nexport interface SleepTimerOptions {\n /** How long the fade before the pause lasts, in ms. Default 10 000; 0 for none. */\n fadeMs?: number;\n /** Countdown refresh while playing, in ms. Default 1000 (and every 100 ms while fading). */\n tickMs?: number;\n /** Set the fade level, 1 (full) to 0. Default: scale `port.volume`; pass a Web Audio gain setter on iOS. */\n gain?: (level: number) => void;\n /** Pause the media. Default `port.pause()`; a host passes its transport's pause or a command. */\n pause?: () => void;\n /** Clock and timers, for tests. */\n now?: () => number;\n setTimer?: (fn: () => void, ms: number) => unknown;\n clearTimer?: (handle: unknown) => void;\n}\n\nexport interface SleepTimer {\n get(): SleepState;\n subscribe(listener: (state: SleepState, previous: SleepState) => void): () => void;\n set(target: SleepTarget): void;\n /** Add minutes: to an `after` timer's time left, or turn an `at`/`end` target into `after`. */\n extend(minutes: number): void;\n cancel(): void;\n /** Re-read the port; called by its own timer and on `timeupdate`. */\n tick(): void;\n dispose(): void;\n}\n\nexport const DEFAULT_SLEEP_FADE_MS = 10_000;\nexport const DEFAULT_SLEEP_TICK_MS = 1000;\n/** Minutes offered by a sleep-timer picker; a host may offer others. */\nexport const SLEEP_MINUTES = [5, 10, 15, 20, 30, 45, 60, 90] as const;\n/** A playhead step bigger than this (in media seconds per tick, at speed 1) is a jump, not playback. */\nconst JUMP_S = 3;\nconst END_EPSILON_S = 0.25;\n\nconst OFF: SleepState = { target: null, remainingMs: null, fading: false, ended: null };\n\nexport function createSleepTimer(port: SleepPort, options: SleepTimerOptions = {}): SleepTimer {\n const {\n fadeMs = DEFAULT_SLEEP_FADE_MS,\n tickMs = DEFAULT_SLEEP_TICK_MS,\n gain,\n pause = () => port.pause(),\n now = () => Date.now(),\n setTimer = (fn, ms) => setTimeout(fn, ms),\n clearTimer = (h) => clearTimeout(h as ReturnType<typeof setTimeout>),\n } = options;\n\n let state: SleepState = OFF;\n const listeners = new Set<(s: SleepState, p: SleepState) => void>();\n const emit = (next: SleepState) => {\n const previous = state;\n state = next;\n listeners.forEach((l) => l(state, previous));\n };\n\n let leftMs = 0; // `after`: listening time left\n let lastAt = 0; // wall clock of the last tick\n let lastTime = 0; // media time of the last tick\n let volume: number | null = null; // the person's volume, held while fading\n let fadingNow = false;\n let handle: unknown = null;\n\n // The level of the fade, 1 to 0: a host's gain, or the element's volume scaled from where it was.\n const setLevel = (level: number) => {\n if (gain) { gain(level); fadingNow = level < 1; return; }\n if (level >= 1) {\n if (volume !== null) port.volume = volume;\n volume = null;\n return;\n }\n if (volume === null) volume = port.volume;\n port.volume = volume * level;\n };\n const restoreVolume = () => {\n if (gain) { if (fadingNow) gain(1); fadingNow = false; return; }\n setLevel(1);\n };\n const schedule = () => {\n if (handle !== null) clearTimer(handle);\n handle = state.target ? setTimer(tick, state.fading ? Math.min(100, tickMs) : tickMs) : null;\n };\n const stop = (reason: SleepEndReason) => {\n restoreVolume();\n if (handle !== null) clearTimer(handle);\n handle = null;\n emit({ ...OFF, ended: reason });\n };\n\n const mediaLeftMs = (seconds: number) =>\n (Math.max(0, seconds - port.currentTime) / (port.playbackRate || 1)) * 1000;\n\n function tick() {\n const target = state.target;\n if (!target) return;\n const t = now();\n const time = port.currentTime;\n const playing = !port.paused;\n let remaining: number;\n\n if (target.kind === 'after') {\n if (playing) leftMs -= Math.max(0, t - lastAt);\n remaining = leftMs;\n } else {\n const at = target.kind === 'at' ? target.seconds : port.duration;\n if (!Number.isFinite(at) || at <= 0) {\n remaining = Infinity; // `end` before the duration is known\n } else {\n const jumped = Math.abs(time - lastTime) > JUMP_S * Math.max(1, port.playbackRate) + (t - lastAt) / 1000;\n if (jumped && lastTime < at - END_EPSILON_S && time > at) {\n lastAt = t; lastTime = time;\n return stop('passed');\n }\n remaining = port.ended || time >= at - END_EPSILON_S ? 0 : mediaLeftMs(at);\n }\n }\n lastAt = t;\n lastTime = time;\n\n if (remaining <= 0) {\n if (playing) pause();\n return stop('slept');\n }\n const fading = playing && fadeMs > 0 && remaining <= fadeMs;\n if (fading) setLevel(remaining / fadeMs);\n else restoreVolume();\n emit({ target, remainingMs: Number.isFinite(remaining) ? Math.round(remaining) : null, fading, ended: null });\n schedule();\n }\n\n const onTimeupdate = () => tick();\n port.addEventListener?.('timeupdate', onTimeupdate);\n\n const timer: SleepTimer = {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n set(target) {\n restoreVolume();\n if (target.kind === 'after') leftMs = Math.max(0, target.minutes) * 60_000;\n lastAt = now();\n lastTime = port.currentTime;\n state = { ...OFF, target };\n tick();\n },\n extend(minutes) {\n const target = state.target;\n if (!target) return timer.set({ kind: 'after', minutes });\n const base = target.kind === 'after' ? leftMs : (state.remainingMs ?? 0);\n timer.set({ kind: 'after', minutes: (base + minutes * 60_000) / 60_000 });\n },\n cancel() {\n if (state.target) stop('cancelled');\n },\n tick,\n dispose() {\n port.removeEventListener?.('timeupdate', onTimeupdate);\n if (state.target) restoreVolume();\n if (handle !== null) clearTimer(handle);\n handle = null;\n listeners.clear();\n },\n };\n return timer;\n}\n\n/** \"14:05\" for a countdown in ms (minutes may exceed 59: \"90:00\"). */\nexport function formatCountdown(ms: number): string {\n const s = Math.max(0, Math.ceil(ms / 1000));\n return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;\n}\n"],"mappings":";AAwFO,IAAM,wBAAwB;AAC9B,IAAM,wBAAwB;AAE9B,IAAM,gBAAgB,CAAC,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE;AAE3D,IAAM,SAAS;AACf,IAAM,gBAAgB;AAEtB,IAAM,MAAkB,EAAE,QAAQ,MAAM,aAAa,MAAM,QAAQ,OAAO,OAAO,KAAK;AAE/E,SAAS,iBAAiB,MAAiB,UAA6B,CAAC,GAAe;AAC7F,QAAM;AAAA,IACJ,SAAS;AAAA,IACT,SAAS;AAAA,IACT;AAAA,IACA,QAAQ,MAAM,KAAK,MAAM;AAAA,IACzB,MAAM,MAAM,KAAK,IAAI;AAAA,IACrB,WAAW,CAAC,IAAI,OAAO,WAAW,IAAI,EAAE;AAAA,IACxC,aAAa,CAAC,MAAM,aAAa,CAAkC;AAAA,EACrE,IAAI;AAEJ,MAAI,QAAoB;AACxB,QAAM,YAAY,oBAAI,IAA4C;AAClE,QAAM,OAAO,CAAC,SAAqB;AACjC,UAAM,WAAW;AACjB,YAAQ;AACR,cAAU,QAAQ,CAAC,MAAM,EAAE,OAAO,QAAQ,CAAC;AAAA,EAC7C;AAEA,MAAI,SAAS;AACb,MAAI,SAAS;AACb,MAAI,WAAW;AACf,MAAI,SAAwB;AAC5B,MAAI,YAAY;AAChB,MAAI,SAAkB;AAGtB,QAAM,WAAW,CAAC,UAAkB;AAClC,QAAI,MAAM;AAAE,WAAK,KAAK;AAAG,kBAAY,QAAQ;AAAG;AAAA,IAAQ;AACxD,QAAI,SAAS,GAAG;AACd,UAAI,WAAW,KAAM,MAAK,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,WAAK,sBAAsB,cAAc,YAAY;AACrD,UAAI,MAAM,OAAQ,eAAc;AAChC,UAAI,WAAW,KAAM,YAAW,MAAM;AACtC,eAAS;AACT,gBAAU,MAAM;AAAA,IAClB;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,gBAAgB,IAAoB;AAClD,QAAM,IAAI,KAAK,IAAI,GAAG,KAAK,KAAK,KAAK,GAAI,CAAC;AAC1C,SAAO,GAAG,KAAK,MAAM,IAAI,EAAE,CAAC,IAAI,OAAO,IAAI,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AACjE;","names":[]}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// src/follow.ts
|
|
2
|
+
var DEFAULT_FOLLOW_OPTIONS = { following: true, resumeAfterMs: null };
|
|
3
|
+
function createFollow(options = {}) {
|
|
4
|
+
const {
|
|
5
|
+
following = DEFAULT_FOLLOW_OPTIONS.following,
|
|
6
|
+
resumeAfterMs = DEFAULT_FOLLOW_OPTIONS.resumeAfterMs,
|
|
7
|
+
setTimer = (fn, ms) => setTimeout(fn, ms),
|
|
8
|
+
clearTimer = (h) => clearTimeout(h)
|
|
9
|
+
} = options;
|
|
10
|
+
let state = { following };
|
|
11
|
+
let fingerIsDown = false;
|
|
12
|
+
let timer = null;
|
|
13
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
14
|
+
const set = (next) => {
|
|
15
|
+
if (state.following === next) return;
|
|
16
|
+
state = { following: next };
|
|
17
|
+
listeners.forEach((l) => l(state));
|
|
18
|
+
};
|
|
19
|
+
const cancel = () => {
|
|
20
|
+
if (timer !== null) clearTimer(timer);
|
|
21
|
+
timer = null;
|
|
22
|
+
};
|
|
23
|
+
const plan = () => {
|
|
24
|
+
cancel();
|
|
25
|
+
if (resumeAfterMs === null || fingerIsDown) return;
|
|
26
|
+
timer = setTimer(() => {
|
|
27
|
+
timer = null;
|
|
28
|
+
set(true);
|
|
29
|
+
}, resumeAfterMs);
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
get: () => state,
|
|
33
|
+
subscribe(listener) {
|
|
34
|
+
listeners.add(listener);
|
|
35
|
+
return () => listeners.delete(listener);
|
|
36
|
+
},
|
|
37
|
+
handMoved() {
|
|
38
|
+
set(false);
|
|
39
|
+
plan();
|
|
40
|
+
},
|
|
41
|
+
fingerDown() {
|
|
42
|
+
fingerIsDown = true;
|
|
43
|
+
cancel();
|
|
44
|
+
},
|
|
45
|
+
fingerUp() {
|
|
46
|
+
fingerIsDown = false;
|
|
47
|
+
if (!state.following) plan();
|
|
48
|
+
},
|
|
49
|
+
resume() {
|
|
50
|
+
cancel();
|
|
51
|
+
set(true);
|
|
52
|
+
},
|
|
53
|
+
dispose: cancel
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function isPageScroller(el) {
|
|
57
|
+
const doc = el.ownerDocument;
|
|
58
|
+
return el === doc.scrollingElement || el === doc.documentElement;
|
|
59
|
+
}
|
|
60
|
+
var SCROLL_KEYS = ["PageUp", "PageDown", "Home", "End"];
|
|
61
|
+
function scrollLineIntoContainer(container, line, { anchor = 0.5, smooth = true } = {}) {
|
|
62
|
+
const win = container.ownerDocument.defaultView;
|
|
63
|
+
const box = container.getBoundingClientRect();
|
|
64
|
+
const at = line.getBoundingClientRect();
|
|
65
|
+
const isPage = isPageScroller(container);
|
|
66
|
+
const style = win?.getComputedStyle?.(line);
|
|
67
|
+
const marginTop = parseFloat(style?.scrollMarginTop ?? "") || 0;
|
|
68
|
+
const marginBottom = parseFloat(style?.scrollMarginBottom ?? "") || 0;
|
|
69
|
+
const viewTop = (isPage ? 0 : box.top + container.clientTop) + marginTop;
|
|
70
|
+
const fullHeight = isPage ? win?.innerHeight ?? box.height : container.clientHeight;
|
|
71
|
+
const viewHeight = Math.max(0, fullHeight - marginTop - marginBottom);
|
|
72
|
+
const top = container.scrollTop + (at.top - viewTop) - (viewHeight * anchor - at.height / 2);
|
|
73
|
+
const calm = win?.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
|
|
74
|
+
const behavior = smooth && !calm ? "smooth" : "auto";
|
|
75
|
+
if (typeof container.scrollTo === "function") container.scrollTo({ top: Math.max(0, top), behavior });
|
|
76
|
+
else container.scrollTop = Math.max(0, top);
|
|
77
|
+
}
|
|
78
|
+
function scrollerOf(el) {
|
|
79
|
+
const doc = el.ownerDocument;
|
|
80
|
+
const page = doc.scrollingElement ?? doc.documentElement;
|
|
81
|
+
for (let node = el.parentElement; node && node !== doc.body && node !== doc.documentElement; node = node.parentElement) {
|
|
82
|
+
const overflow = doc.defaultView?.getComputedStyle(node).overflowY ?? "";
|
|
83
|
+
if ((overflow === "auto" || overflow === "scroll" || overflow === "overlay") && node.scrollHeight > node.clientHeight) return node;
|
|
84
|
+
}
|
|
85
|
+
return page;
|
|
86
|
+
}
|
|
87
|
+
var DEFAULT_OWN_SCROLL_MS = 900;
|
|
88
|
+
function attachFollow(container, follow, options = {}) {
|
|
89
|
+
const { anchor = 0.5, ownScrollMs = DEFAULT_OWN_SCROLL_MS, scrollKeys = SCROLL_KEYS, now = () => Date.now() } = options;
|
|
90
|
+
const doc = container.ownerDocument;
|
|
91
|
+
const target = isPageScroller(container) ? doc.defaultView ?? container : container;
|
|
92
|
+
let ownUntil = 0;
|
|
93
|
+
const offs = [];
|
|
94
|
+
const on = (type, fn) => {
|
|
95
|
+
target.addEventListener(type, fn, { passive: true });
|
|
96
|
+
offs.push(() => target.removeEventListener(type, fn));
|
|
97
|
+
};
|
|
98
|
+
const byHand = () => {
|
|
99
|
+
if (now() > ownUntil) follow.handMoved();
|
|
100
|
+
};
|
|
101
|
+
on("wheel", byHand);
|
|
102
|
+
on("touchmove", byHand);
|
|
103
|
+
on("touchstart", () => follow.fingerDown());
|
|
104
|
+
on("touchend", () => follow.fingerUp());
|
|
105
|
+
on("touchcancel", () => follow.fingerUp());
|
|
106
|
+
on("keydown", (e) => {
|
|
107
|
+
const t = e.target;
|
|
108
|
+
const editable = !!t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));
|
|
109
|
+
if (!e.defaultPrevented && !editable && scrollKeys.includes(e.key)) follow.handMoved();
|
|
110
|
+
});
|
|
111
|
+
return {
|
|
112
|
+
bring(line, force = false) {
|
|
113
|
+
if (!line || !force && !follow.get().following) return;
|
|
114
|
+
ownUntil = now() + ownScrollMs;
|
|
115
|
+
scrollLineIntoContainer(container, line, { anchor });
|
|
116
|
+
},
|
|
117
|
+
detach() {
|
|
118
|
+
offs.forEach((off) => off());
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export {
|
|
124
|
+
DEFAULT_FOLLOW_OPTIONS,
|
|
125
|
+
createFollow,
|
|
126
|
+
SCROLL_KEYS,
|
|
127
|
+
scrollLineIntoContainer,
|
|
128
|
+
scrollerOf,
|
|
129
|
+
DEFAULT_OWN_SCROLL_MS,
|
|
130
|
+
attachFollow
|
|
131
|
+
};
|
|
132
|
+
//# sourceMappingURL=chunk-7I3V4HKP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/follow.ts"],"sourcesContent":["/**\n * Following the voice: a list of timed lines that keeps the current one in view until a person\n * scrolls it, and how it comes back.\n *\n * Two parts. `createFollow` is the headless state (following or not, and when to resume by\n * itself), driven by plain calls and an injectable clock, so it is tested without a DOM.\n * `attachFollow` wires it to one scroll container: it scrolls *that container* with `scrollTo`\n * (never `scrollIntoView`, which also scrolls every ancestor: a sheet, a page around a frame), and\n * hears hand scrolling *on that container only*, not on the window.\n *\n * Both behaviours come from the fleet's two copies: `@zodal/speech` (own-scroll grace, a manual\n * \"Back to now\") and arioso's lyrics view (container scroll at 35 %, a finger down holds, resume\n * by itself 4 s after the hand is still). The differences are options, not forks.\n */\n\nexport interface FollowState {\n following: boolean;\n}\n\nexport interface FollowOptions {\n /** Start following. */\n following?: boolean;\n /** Resume by itself this long after the hand is still; `null` never (a \"Back to now\" only). */\n resumeAfterMs?: number | null;\n /** The timer, for tests. */\n setTimer?: (fn: () => void, ms: number) => unknown;\n clearTimer?: (handle: unknown) => void;\n}\n\nexport interface Follow {\n get(): FollowState;\n subscribe(listener: (state: FollowState) => void): () => void;\n /** A person moved the list: stop following (and, with `resumeAfterMs`, plan the return). */\n handMoved(): void;\n /** A finger is on the list: never resume while it is down. */\n fingerDown(): void;\n fingerUp(): void;\n /** \"Back to now\", or a tap on a line: follow again at once. */\n resume(): void;\n /** Stops a planned resume; call when the view goes away. */\n dispose(): void;\n}\n\nexport const DEFAULT_FOLLOW_OPTIONS = { following: true, resumeAfterMs: null } as const;\n\n/** Creates the headless follow state. */\nexport function createFollow(options: FollowOptions = {}): Follow {\n const {\n following = DEFAULT_FOLLOW_OPTIONS.following,\n resumeAfterMs = DEFAULT_FOLLOW_OPTIONS.resumeAfterMs,\n setTimer = (fn, ms) => setTimeout(fn, ms),\n clearTimer = (h) => clearTimeout(h as ReturnType<typeof setTimeout>),\n } = options;\n let state: FollowState = { following };\n let fingerIsDown = false;\n let timer: unknown = null;\n const listeners = new Set<(state: FollowState) => void>();\n\n const set = (next: boolean) => {\n if (state.following === next) return;\n state = { following: next };\n listeners.forEach((l) => l(state));\n };\n const cancel = () => {\n if (timer !== null) clearTimer(timer);\n timer = null;\n };\n const plan = () => {\n cancel();\n if (resumeAfterMs === null || fingerIsDown) return;\n timer = setTimer(() => {\n timer = null;\n set(true);\n }, resumeAfterMs);\n };\n\n return {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n handMoved() {\n set(false);\n plan();\n },\n fingerDown() {\n fingerIsDown = true;\n cancel();\n },\n fingerUp() {\n fingerIsDown = false;\n if (!state.following) plan();\n },\n resume() {\n cancel();\n set(true);\n },\n dispose: cancel,\n };\n}\n\n/** True when `el` is the page's own scroller (its scroll events reach the window, its view is the window). */\nfunction isPageScroller(el: HTMLElement): boolean {\n const doc = el.ownerDocument;\n return el === doc.scrollingElement || el === doc.documentElement;\n}\n\n/**\n * Keys that mean a person is scrolling the list. Space and the arrows are left out: a player binds\n * them to play and seek, and a key pressed in a text field is never counted.\n */\nexport const SCROLL_KEYS = ['PageUp', 'PageDown', 'Home', 'End'] as const;\n\n/**\n * Scrolls `container` so `line` sits at `anchor` (0 top, 0.5 middle) of its visible height.\n * Only the container moves. `smooth` falls back to instant under reduced motion.\n */\nexport function scrollLineIntoContainer(\n container: HTMLElement,\n line: HTMLElement,\n { anchor = 0.5, smooth = true }: { anchor?: number; smooth?: boolean } = {},\n): void {\n const win = container.ownerDocument.defaultView;\n const box = container.getBoundingClientRect();\n const at = line.getBoundingClientRect();\n // The page's own scroller reports its box as the whole document; its view is the window.\n const isPage = isPageScroller(container);\n // The line's scroll margins (a sticky bar's height) shrink the view it is placed in, as they\n // do for scrollIntoView.\n const style = win?.getComputedStyle?.(line);\n const marginTop = parseFloat(style?.scrollMarginTop ?? '') || 0;\n const marginBottom = parseFloat(style?.scrollMarginBottom ?? '') || 0;\n const viewTop = (isPage ? 0 : box.top + container.clientTop) + marginTop;\n const fullHeight = isPage ? win?.innerHeight ?? box.height : container.clientHeight;\n const viewHeight = Math.max(0, fullHeight - marginTop - marginBottom);\n const top = container.scrollTop + (at.top - viewTop) - (viewHeight * anchor - at.height / 2);\n const calm = win?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n const behavior: ScrollBehavior = smooth && !calm ? 'smooth' : 'auto';\n if (typeof container.scrollTo === 'function') container.scrollTo({ top: Math.max(0, top), behavior });\n else container.scrollTop = Math.max(0, top);\n}\n\n/** The nearest ancestor of `el` that scrolls vertically, or the page's scroller. */\nexport function scrollerOf(el: HTMLElement): HTMLElement {\n const doc = el.ownerDocument;\n const page = (doc.scrollingElement ?? doc.documentElement) as HTMLElement;\n for (let node = el.parentElement; node && node !== doc.body && node !== doc.documentElement; node = node.parentElement) {\n const overflow = doc.defaultView?.getComputedStyle(node).overflowY ?? '';\n if ((overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay') && node.scrollHeight > node.clientHeight) return node;\n }\n return page;\n}\n\nexport interface AttachFollowOptions {\n /** Where the current line sits in the container: arioso 0.35, a transcript 0.5. */\n anchor?: number;\n /** How long the list's own smooth scroll is not mistaken for a person's. */\n ownScrollMs?: number;\n /** Keys that mean a person is scrolling; leave out keys the host uses (arrows that seek). */\n scrollKeys?: readonly string[];\n now?: () => number;\n}\n\nexport const DEFAULT_OWN_SCROLL_MS = 900;\n\nexport interface AttachedFollow {\n /** Bring `line` into view, if following. `force` brings it even when not (after a resume). */\n bring(line: HTMLElement | null | undefined, force?: boolean): void;\n detach(): void;\n}\n\n/**\n * Wires `follow` to one scroll `container`: hand scrolling there stops following; `bring` moves\n * only the container. For a page that scrolls as a whole, pass `document.scrollingElement`; the\n * hand listeners then go on the window, since a page's scroll events reach it there.\n */\nexport function attachFollow(container: HTMLElement, follow: Follow, options: AttachFollowOptions = {}): AttachedFollow {\n const { anchor = 0.5, ownScrollMs = DEFAULT_OWN_SCROLL_MS, scrollKeys = SCROLL_KEYS, now = () => Date.now() } = options;\n const doc = container.ownerDocument;\n const target: EventTarget = isPageScroller(container) ? doc.defaultView ?? container : container;\n let ownUntil = 0;\n const offs: Array<() => void> = [];\n const on = (type: string, fn: (e: Event) => void) => {\n target.addEventListener(type, fn, { passive: true });\n offs.push(() => target.removeEventListener(type, fn));\n };\n const byHand = () => {\n if (now() > ownUntil) follow.handMoved();\n };\n on('wheel', byHand);\n on('touchmove', byHand);\n on('touchstart', () => follow.fingerDown());\n on('touchend', () => follow.fingerUp());\n on('touchcancel', () => follow.fingerUp());\n on('keydown', (e) => {\n const t = e.target as HTMLElement | null;\n const editable = !!t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));\n if (!e.defaultPrevented && !editable && scrollKeys.includes((e as KeyboardEvent).key)) follow.handMoved();\n });\n return {\n bring(line, force = false) {\n if (!line || (!force && !follow.get().following)) return;\n ownUntil = now() + ownScrollMs;\n scrollLineIntoContainer(container, line, { anchor });\n },\n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A,SAAS;AACP,WAAK,QAAQ,CAAC,QAAQ,IAAI,CAAC;AAAA,IAC7B;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// src/cues.ts
|
|
2
|
+
var CUE_EPSILON_S = 0.01;
|
|
3
|
+
var SECONDS_PER_MINUTE = 60;
|
|
4
|
+
var MINUTES_PER_HOUR = 60;
|
|
5
|
+
function lastStarted(count, startOf, time) {
|
|
6
|
+
let lo = 0;
|
|
7
|
+
let hi = count - 1;
|
|
8
|
+
let at = -1;
|
|
9
|
+
while (lo <= hi) {
|
|
10
|
+
const mid = lo + hi >> 1;
|
|
11
|
+
if (startOf(mid) <= time) {
|
|
12
|
+
at = mid;
|
|
13
|
+
lo = mid + 1;
|
|
14
|
+
} else {
|
|
15
|
+
hi = mid - 1;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return at;
|
|
19
|
+
}
|
|
20
|
+
function cueAt(cues, time, options = {}) {
|
|
21
|
+
const { epsilonS = CUE_EPSILON_S, gaps = false } = options;
|
|
22
|
+
const at = lastStarted(cues.length, (i) => cues[i].start, time + epsilonS);
|
|
23
|
+
if (gaps && at >= 0 && time >= cues[at].end) return -1;
|
|
24
|
+
return at;
|
|
25
|
+
}
|
|
26
|
+
function wordAt(cue, time) {
|
|
27
|
+
const words = cue?.words;
|
|
28
|
+
if (!words?.length) return -1;
|
|
29
|
+
return Math.max(0, lastStarted(words.length, (i) => words[i][0], time));
|
|
30
|
+
}
|
|
31
|
+
function cuesDuration(cues) {
|
|
32
|
+
return cues.length ? cues[cues.length - 1].end : 0;
|
|
33
|
+
}
|
|
34
|
+
function formatTime(seconds) {
|
|
35
|
+
const whole = Math.max(0, Math.floor(seconds || 0));
|
|
36
|
+
const hours = Math.floor(whole / (SECONDS_PER_MINUTE * MINUTES_PER_HOUR));
|
|
37
|
+
const minutes = Math.floor(whole / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;
|
|
38
|
+
const secs = whole % SECONDS_PER_MINUTE;
|
|
39
|
+
const mm = hours && minutes < 10 ? `0${minutes}` : `${minutes}`;
|
|
40
|
+
return `${hours ? `${hours}:` : ""}${mm}:${secs < 10 ? "0" : ""}${secs}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export {
|
|
44
|
+
CUE_EPSILON_S,
|
|
45
|
+
cueAt,
|
|
46
|
+
wordAt,
|
|
47
|
+
cuesDuration,
|
|
48
|
+
formatTime
|
|
49
|
+
};
|
|
50
|
+
//# sourceMappingURL=chunk-AMK7QKN7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cues.ts"],"sourcesContent":["/**\n * Timed text, looked up by time: which cue and which word are being heard. Pure, no DOM.\n *\n * A cue is a span of text with a start and an end, in seconds, and optionally the times of its\n * words. A spoken overview's sentences (`@zodal/speech`), a song's lyric lines (arioso) and a\n * film's subtitles (srtplay) are all lists of cues. The shape is structural, so this module needs\n * no schema at runtime; the wire model is lacing's (`AlignedTrackV1`, media_hub ADR-0010).\n */\n\n/** The fields of a cue this module reads. `words` are `[start, end, text]`, in seconds. */\nexport interface CueLike {\n start: number;\n end: number;\n text?: string;\n words?: ReadonlyArray<readonly [number, number, string]>;\n}\n\n/**\n * Tolerance so a seek to a cue's own start lands in that cue and not the one before it, after\n * float rounding (`currentTime` is rarely exactly what was set).\n */\nexport const CUE_EPSILON_S = 0.01;\n\nconst SECONDS_PER_MINUTE = 60;\nconst MINUTES_PER_HOUR = 60;\n\n/** The last index `i` of a sorted list with `startOf(i) <= time`, or -1. */\nfunction lastStarted(count: number, startOf: (i: number) => number, time: number): number {\n let lo = 0;\n let hi = count - 1;\n let at = -1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n if (startOf(mid) <= time) {\n at = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return at;\n}\n\nexport interface CueAtOptions {\n /** See `CUE_EPSILON_S`. */\n epsilonS?: number;\n /**\n * `false` (the default): the last cue that has started stays current through the gap after it,\n * as a transcript or lyrics view wants. `true`: -1 between cues, as subtitles want.\n */\n gaps?: boolean;\n}\n\n/** The index of the cue being heard at `time`: the last one that has started, or -1. */\nexport function cueAt(cues: readonly CueLike[], time: number, options: CueAtOptions = {}): number {\n const { epsilonS = CUE_EPSILON_S, gaps = false } = options;\n const at = lastStarted(cues.length, (i) => cues[i].start, time + epsilonS);\n if (gaps && at >= 0 && time >= cues[at].end) return -1;\n return at;\n}\n\n/** The index of the word being heard within `cue`, or -1 when it has no word times. */\nexport function wordAt(cue: CueLike | undefined, time: number): number {\n const words = cue?.words;\n if (!words?.length) return -1;\n return Math.max(0, lastStarted(words.length, (i) => words[i][0], time));\n}\n\n/** The cues' total length: the last cue's end, which stands in until the media reports its own. */\nexport function cuesDuration(cues: readonly CueLike[]): number {\n return cues.length ? cues[cues.length - 1].end : 0;\n}\n\n/** `m:ss`, or `h:mm:ss` past the hour. */\nexport function formatTime(seconds: number): string {\n const whole = Math.max(0, Math.floor(seconds || 0));\n const hours = Math.floor(whole / (SECONDS_PER_MINUTE * MINUTES_PER_HOUR));\n const minutes = Math.floor(whole / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR;\n const secs = whole % SECONDS_PER_MINUTE;\n const mm = hours && minutes < 10 ? `0${minutes}` : `${minutes}`;\n return `${hours ? `${hours}:` : ''}${mm}:${secs < 10 ? '0' : ''}${secs}`;\n}\n"],"mappings":";AAqBO,IAAM,gBAAgB;AAE7B,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AAGzB,SAAS,YAAY,OAAe,SAAgC,MAAsB;AACxF,MAAI,KAAK;AACT,MAAI,KAAK,QAAQ;AACjB,MAAI,KAAK;AACT,SAAO,MAAM,IAAI;AACf,UAAM,MAAO,KAAK,MAAO;AACzB,QAAI,QAAQ,GAAG,KAAK,MAAM;AACxB,WAAK;AACL,WAAK,MAAM;AAAA,IACb,OAAO;AACL,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AACA,SAAO;AACT;AAaO,SAAS,MAAM,MAA0B,MAAc,UAAwB,CAAC,GAAW;AAChG,QAAM,EAAE,WAAW,eAAe,OAAO,MAAM,IAAI;AACnD,QAAM,KAAK,YAAY,KAAK,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO,QAAQ;AACzE,MAAI,QAAQ,MAAM,KAAK,QAAQ,KAAK,EAAE,EAAE,IAAK,QAAO;AACpD,SAAO;AACT;AAGO,SAAS,OAAO,KAA0B,MAAsB;AACrE,QAAM,QAAQ,KAAK;AACnB,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,SAAO,KAAK,IAAI,GAAG,YAAY,MAAM,QAAQ,CAAC,MAAM,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC;AACxE;AAGO,SAAS,aAAa,MAAkC;AAC7D,SAAO,KAAK,SAAS,KAAK,KAAK,SAAS,CAAC,EAAE,MAAM;AACnD;AAGO,SAAS,WAAW,SAAyB;AAClD,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,WAAW,CAAC,CAAC;AAClD,QAAM,QAAQ,KAAK,MAAM,SAAS,qBAAqB,iBAAiB;AACxE,QAAM,UAAU,KAAK,MAAM,QAAQ,kBAAkB,IAAI;AACzD,QAAM,OAAO,QAAQ;AACrB,QAAM,KAAK,SAAS,UAAU,KAAK,IAAI,OAAO,KAAK,GAAG,OAAO;AAC7D,SAAO,GAAG,QAAQ,GAAG,KAAK,MAAM,EAAE,GAAG,EAAE,IAAI,OAAO,KAAK,MAAM,EAAE,GAAG,IAAI;AACxE;","names":[]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// src/playback.ts
|
|
2
|
+
var SEEK_LAND_TIMEOUT_MS = 1500;
|
|
3
|
+
function abortError() {
|
|
4
|
+
const e = new Error("The play was cancelled while its seek was landing.");
|
|
5
|
+
e.name = "AbortError";
|
|
6
|
+
return e;
|
|
7
|
+
}
|
|
8
|
+
function seekLanded(port, { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal } = {}) {
|
|
9
|
+
if (signal?.aborted) return Promise.reject(abortError());
|
|
10
|
+
if (!port.seeking || !port.addEventListener) return Promise.resolve();
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
let timer;
|
|
13
|
+
const settle = () => {
|
|
14
|
+
clearTimeout(timer);
|
|
15
|
+
port.removeEventListener?.("seeked", landed);
|
|
16
|
+
signal?.removeEventListener("abort", aborted);
|
|
17
|
+
};
|
|
18
|
+
const landed = () => {
|
|
19
|
+
settle();
|
|
20
|
+
resolve();
|
|
21
|
+
};
|
|
22
|
+
const aborted = () => {
|
|
23
|
+
settle();
|
|
24
|
+
reject(abortError());
|
|
25
|
+
};
|
|
26
|
+
timer = setTimeout(() => {
|
|
27
|
+
if (!port.seeking) landed();
|
|
28
|
+
}, timeoutMs);
|
|
29
|
+
port.addEventListener("seeked", landed);
|
|
30
|
+
signal?.addEventListener("abort", aborted);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function seekThenPlay(port, time, options = {}) {
|
|
34
|
+
const play = options.play ?? (() => port.play());
|
|
35
|
+
const wasEnded = !!port.ended;
|
|
36
|
+
port.currentTime = time;
|
|
37
|
+
if (!wasEnded || !port.seeking) return Promise.resolve(play());
|
|
38
|
+
return seekLanded(port, options).then(() => play());
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export {
|
|
42
|
+
SEEK_LAND_TIMEOUT_MS,
|
|
43
|
+
seekLanded,
|
|
44
|
+
seekThenPlay
|
|
45
|
+
};
|
|
46
|
+
//# sourceMappingURL=chunk-NBKMSPYQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/playback.ts"],"sourcesContent":["/**\n * Playing from a chosen point, safely on every engine, with no DOM beyond the port itself.\n *\n * The trap: in WebKit (Safari, and every browser on an iPhone or iPad) `el.currentTime = t;\n * el.play()` on an element that has *ended* starts from the end, which ends again at once, or\n * from 0, because the seek has not landed when `play()` runs. Chromium and Firefox apply the\n * seek first. It shows as \"after the audio finished, tapping a transcript line plays from the\n * start\" (annals, 2026-11-13). Measured in Playwright WebKit: 12 of 12 taps restarted at 0;\n * calling `play()` first and seeking again still failed 10 of 12; waiting for `seeked` and then\n * playing was right 16 of 16.\n *\n * So `seekThenPlay` reads whether the element had ended *before* seeking (after the seek WebKit\n * already reports `ended === false`), and if it had and the seek is still landing, it plays on\n * `seeked`. The element has played before, so playing outside the tap is allowed.\n */\n\n/** The part of a media element `seekThenPlay` uses. The optional members are an HTMLMediaElement's. */\nexport interface SeekablePort {\n currentTime: number;\n play(): Promise<void> | void;\n /** True once playback reached the end. A port without it is never waited on. */\n readonly ended?: boolean;\n /** True while a seek is landing. */\n readonly seeking?: boolean;\n addEventListener?(type: 'seeked', listener: () => void): void;\n removeEventListener?(type: 'seeked', listener: () => void): void;\n}\n\n/** Play anyway after this long, if no seek is under way by then (a seek still landing is still awaited). */\nexport const SEEK_LAND_TIMEOUT_MS = 1500;\n\nexport interface SeekThenPlayOptions {\n /** What starting playback means; defaults to `port.play()`. A player passes its own, to catch a refusal. */\n play?: () => Promise<void> | void;\n timeoutMs?: number;\n /** Cancels a play held for its seek (a pause meanwhile): the promise rejects with an AbortError. */\n signal?: AbortSignal;\n}\n\nfunction abortError(): Error {\n const e = new Error('The play was cancelled while its seek was landing.');\n e.name = 'AbortError';\n return e;\n}\n\n/** Resolves once `port`'s seek has landed (`seeked`), or at once when no seek is landing. */\nexport function seekLanded(\n port: SeekablePort,\n { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal }: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<void> {\n if (signal?.aborted) return Promise.reject(abortError());\n if (!port.seeking || !port.addEventListener) return Promise.resolve();\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const settle = () => {\n clearTimeout(timer);\n port.removeEventListener?.('seeked', landed);\n signal?.removeEventListener('abort', aborted);\n };\n const landed = () => { settle(); resolve(); };\n const aborted = () => { settle(); reject(abortError()); };\n // Playing while the seek is still under way is the bug itself, so the timer only ends a wait\n // whose seek is over without a `seeked` (a source that went away).\n timer = setTimeout(() => { if (!port.seeking) landed(); }, timeoutMs);\n port.addEventListener!('seeked', landed);\n signal?.addEventListener('abort', aborted);\n });\n}\n\n/**\n * Seeks `port` to `time` and plays from there, also when it has ended (see the module note).\n * Plays synchronously, inside the tap, whenever it can; returns what playing returned.\n */\nexport function seekThenPlay(port: SeekablePort, time: number, options: SeekThenPlayOptions = {}): Promise<void> {\n const play = options.play ?? (() => port.play());\n const wasEnded = !!port.ended;\n port.currentTime = time;\n if (!wasEnded || !port.seeking) return Promise.resolve(play());\n return seekLanded(port, options).then(() => play());\n}\n"],"mappings":";AA6BO,IAAM,uBAAuB;AAUpC,SAAS,aAAoB;AAC3B,QAAM,IAAI,IAAI,MAAM,oDAAoD;AACxE,IAAE,OAAO;AACT,SAAO;AACT;AAGO,SAAS,WACd,MACA,EAAE,YAAY,sBAAsB,OAAO,IAAkD,CAAC,GAC/E;AACf,MAAI,QAAQ,QAAS,QAAO,QAAQ,OAAO,WAAW,CAAC;AACvD,MAAI,CAAC,KAAK,WAAW,CAAC,KAAK,iBAAkB,QAAO,QAAQ,QAAQ;AACpE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACJ,UAAM,SAAS,MAAM;AACnB,mBAAa,KAAK;AAClB,WAAK,sBAAsB,UAAU,MAAM;AAC3C,cAAQ,oBAAoB,SAAS,OAAO;AAAA,IAC9C;AACA,UAAM,SAAS,MAAM;AAAE,aAAO;AAAG,cAAQ;AAAA,IAAG;AAC5C,UAAM,UAAU,MAAM;AAAE,aAAO;AAAG,aAAO,WAAW,CAAC;AAAA,IAAG;AAGxD,YAAQ,WAAW,MAAM;AAAE,UAAI,CAAC,KAAK,QAAS,QAAO;AAAA,IAAG,GAAG,SAAS;AACpE,SAAK,iBAAkB,UAAU,MAAM;AACvC,YAAQ,iBAAiB,SAAS,OAAO;AAAA,EAC3C,CAAC;AACH;AAMO,SAAS,aAAa,MAAoB,MAAc,UAA+B,CAAC,GAAkB;AAC/G,QAAM,OAAO,QAAQ,SAAS,MAAM,KAAK,KAAK;AAC9C,QAAM,WAAW,CAAC,CAAC,KAAK;AACxB,OAAK,cAAc;AACnB,MAAI,CAAC,YAAY,CAAC,KAAK,QAAS,QAAO,QAAQ,QAAQ,KAAK,CAAC;AAC7D,SAAO,WAAW,MAAM,OAAO,EAAE,KAAK,MAAM,KAAK,CAAC;AACpD;","names":[]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/vtt.ts
|
|
2
|
+
var SECONDS_PER_MINUTE = 60;
|
|
3
|
+
var SECONDS_PER_HOUR = 3600;
|
|
4
|
+
var MS_PER_SECOND = 1e3;
|
|
5
|
+
var TIME = String.raw`(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})`;
|
|
6
|
+
var TIMING = new RegExp(String.raw`^\s*${TIME}\s+-->\s+${TIME}`);
|
|
7
|
+
var SKIPPED_BLOCKS = /^(WEBVTT|NOTE|STYLE|REGION)(\s|$)/;
|
|
8
|
+
var VOICE = /<v(?:\.[^\s>]*)?\s+([^>]+)>/;
|
|
9
|
+
var ENTITIES = { amp: "&", lt: "<", gt: ">", nbsp: "\xA0", lrm: "\u200E", rlm: "\u200F", quot: '"', apos: "'" };
|
|
10
|
+
function seconds(h, m, s, frac) {
|
|
11
|
+
return Number(h ?? 0) * SECONDS_PER_HOUR + Number(m) * SECONDS_PER_MINUTE + Number(s) + Number(frac.padEnd(3, "0")) / MS_PER_SECOND;
|
|
12
|
+
}
|
|
13
|
+
function plain(payload) {
|
|
14
|
+
return payload.replace(/<[^>]*>/g, "").replace(/&(\w+);/g, (all, name) => ENTITIES[name] ?? all).replace(/\s+/g, " ").trim();
|
|
15
|
+
}
|
|
16
|
+
function parseWebVtt(text) {
|
|
17
|
+
const blocks = text.replace(/^/, "").replace(/\r\n?/g, "\n").split(/\n{2,}/);
|
|
18
|
+
const cues = [];
|
|
19
|
+
for (const block of blocks) {
|
|
20
|
+
const lines = block.split("\n").filter((line, i) => i > 0 || line.trim() !== "");
|
|
21
|
+
if (!lines.length || SKIPPED_BLOCKS.test(lines[0])) continue;
|
|
22
|
+
const at = lines.findIndex((line) => TIMING.test(line));
|
|
23
|
+
if (at < 0 || at > 1) continue;
|
|
24
|
+
const m = TIMING.exec(lines[at]);
|
|
25
|
+
const payload = lines.slice(at + 1).join("\n");
|
|
26
|
+
const cue = {
|
|
27
|
+
start: seconds(m[1], m[2], m[3], m[4]),
|
|
28
|
+
end: seconds(m[5], m[6], m[7], m[8]),
|
|
29
|
+
text: plain(payload)
|
|
30
|
+
};
|
|
31
|
+
if (at === 1 && lines[0].trim()) cue.id = lines[0].trim();
|
|
32
|
+
const voice = VOICE.exec(payload);
|
|
33
|
+
if (voice) cue.speaker = voice[1].trim();
|
|
34
|
+
cues.push(cue);
|
|
35
|
+
}
|
|
36
|
+
return cues.sort((a, b) => a.start - b.start);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export {
|
|
40
|
+
parseWebVtt
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=chunk-P3EWPYFQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vtt.ts"],"sourcesContent":["/**\n * WebVTT (and SRT) text to cues. Pure, no DOM.\n *\n * Captions, a transcript or chapters often arrive as a `.vtt` file beside the audio: every\n * captioning tool writes it, and `<track kind=\"chapters\">` uses the same format with one title\n * per cue. `parseWebVtt` reads the cue blocks and skips the header, `NOTE`, `STYLE` and `REGION`\n * blocks. It tolerates SRT too (numbered blocks, a comma before the milliseconds). Markup in a\n * cue's text is removed; a voice tag (`<v Ana>`) becomes the cue's `speaker`.\n */\nimport type { CueLike } from './cues.js';\n\n/** A cue read from WebVTT: always with its text, and with its id and speaker when present. */\nexport interface VttCue extends CueLike {\n text: string;\n id?: string;\n speaker?: string;\n}\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3600;\nconst MS_PER_SECOND = 1000;\nconst TIME = String.raw`(?:(\\d+):)?(\\d{1,2}):(\\d{2})[.,](\\d{1,3})`;\nconst TIMING = new RegExp(String.raw`^\\s*${TIME}\\s+-->\\s+${TIME}`);\nconst SKIPPED_BLOCKS = /^(WEBVTT|NOTE|STYLE|REGION)(\\s|$)/;\nconst VOICE = /<v(?:\\.[^\\s>]*)?\\s+([^>]+)>/;\nconst ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', nbsp: ' ', lrm: '', rlm: '', quot: '\"', apos: \"'\" };\n\nfunction seconds(h: string | undefined, m: string, s: string, frac: string): number {\n return Number(h ?? 0) * SECONDS_PER_HOUR + Number(m) * SECONDS_PER_MINUTE + Number(s) + Number(frac.padEnd(3, '0')) / MS_PER_SECOND;\n}\n\nfunction plain(payload: string): string {\n return payload\n .replace(/<[^>]*>/g, '')\n .replace(/&(\\w+);/g, (all, name: string) => ENTITIES[name] ?? all)\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/** The cues of a WebVTT (or SRT) text, in time order. Blocks without a timing line are skipped. */\nexport function parseWebVtt(text: string): VttCue[] {\n const blocks = text.replace(/^/, '').replace(/\\r\\n?/g, '\\n').split(/\\n{2,}/);\n const cues: VttCue[] = [];\n for (const block of blocks) {\n const lines = block.split('\\n').filter((line, i) => i > 0 || line.trim() !== '');\n if (!lines.length || SKIPPED_BLOCKS.test(lines[0])) continue;\n const at = lines.findIndex((line) => TIMING.test(line));\n if (at < 0 || at > 1) continue;\n const m = TIMING.exec(lines[at]) as RegExpExecArray;\n const payload = lines.slice(at + 1).join('\\n');\n const cue: VttCue = {\n start: seconds(m[1], m[2], m[3], m[4]),\n end: seconds(m[5], m[6], m[7], m[8]),\n text: plain(payload),\n };\n if (at === 1 && lines[0].trim()) cue.id = lines[0].trim();\n const voice = VOICE.exec(payload);\n if (voice) cue.speaker = voice[1].trim();\n cues.push(cue);\n }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