@zodal/media 0.1.0 → 0.2.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/dist/index.cjs CHANGED
@@ -21,14 +21,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  CUE_EPSILON_S: () => CUE_EPSILON_S,
24
+ DEFAULT_END_MODE: () => DEFAULT_END_MODE,
24
25
  DEFAULT_FOLLOW_OPTIONS: () => DEFAULT_FOLLOW_OPTIONS,
25
26
  DEFAULT_OWN_SCROLL_MS: () => DEFAULT_OWN_SCROLL_MS,
26
27
  DEFAULT_SLEEP_FADE_MS: () => DEFAULT_SLEEP_FADE_MS,
27
28
  DEFAULT_SLEEP_TICK_MS: () => DEFAULT_SLEEP_TICK_MS,
29
+ END_MODES: () => END_MODES,
30
+ END_MODE_INFO: () => END_MODE_INFO,
31
+ PREVIOUS_RESTARTS_AFTER_S: () => PREVIOUS_RESTARTS_AFTER_S,
28
32
  SCROLL_KEYS: () => SCROLL_KEYS,
29
33
  SEEK_LAND_TIMEOUT_MS: () => SEEK_LAND_TIMEOUT_MS,
30
34
  SLEEP_MINUTES: () => SLEEP_MINUTES,
31
35
  attachFollow: () => attachFollow,
36
+ createEndPolicy: () => createEndPolicy,
32
37
  createFollow: () => createFollow,
33
38
  createSleepTimer: () => createSleepTimer,
34
39
  createTimedText: () => createTimedText,
@@ -36,11 +41,14 @@ __export(src_exports, {
36
41
  cuesDuration: () => cuesDuration,
37
42
  formatCountdown: () => formatCountdown,
38
43
  formatTime: () => formatTime,
44
+ isEndMode: () => isEndMode,
45
+ nextEndMode: () => nextEndMode,
39
46
  parseWebVtt: () => parseWebVtt,
40
47
  scrollLineIntoContainer: () => scrollLineIntoContainer,
41
48
  scrollerOf: () => scrollerOf,
42
49
  seekLanded: () => seekLanded,
43
50
  seekThenPlay: () => seekThenPlay,
51
+ skipMode: () => skipMode,
44
52
  wordAt: () => wordAt
45
53
  });
46
54
  module.exports = __toCommonJS(src_exports);
@@ -482,17 +490,186 @@ function formatCountdown(ms) {
482
490
  const s = Math.max(0, Math.ceil(ms / 1e3));
483
491
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
484
492
  }
493
+
494
+ // src/end-mode.ts
495
+ var END_MODES = ["stop", "repeat-one", "next", "repeat-all", "shuffle"];
496
+ var DEFAULT_END_MODE = "next";
497
+ var END_MODE_INFO = {
498
+ stop: {
499
+ mode: "stop",
500
+ label: "Stop after this one",
501
+ short: "Then stop",
502
+ description: "When this item ends, playback stops.",
503
+ icon: { material: "keyboard_tab", lucide: "arrow-right-to-line" }
504
+ },
505
+ "repeat-one": {
506
+ mode: "repeat-one",
507
+ label: "Repeat this one",
508
+ short: "Repeat 1",
509
+ description: "This item plays again from the start each time it ends.",
510
+ icon: { material: "repeat_one", lucide: "repeat-1" }
511
+ },
512
+ next: {
513
+ mode: "next",
514
+ label: "Play the list in order",
515
+ short: "In order",
516
+ description: "The next item of the list plays; playback stops after the last one.",
517
+ icon: { material: "playlist_play", lucide: "list-video" }
518
+ },
519
+ "repeat-all": {
520
+ mode: "repeat-all",
521
+ label: "Repeat the list",
522
+ short: "Repeat all",
523
+ description: "The list plays in order and starts again after its last item.",
524
+ icon: { material: "repeat", lucide: "repeat" }
525
+ },
526
+ shuffle: {
527
+ mode: "shuffle",
528
+ label: "Shuffle the list",
529
+ short: "Shuffle",
530
+ description: "A random item of the list plays next; each plays once before any plays again.",
531
+ icon: { material: "shuffle", lucide: "shuffle" }
532
+ }
533
+ };
534
+ var isEndMode = (value) => END_MODES.includes(value);
535
+ function nextEndMode(mode) {
536
+ return END_MODES[(END_MODES.indexOf(mode) + 1) % END_MODES.length];
537
+ }
538
+ var PREVIOUS_RESTARTS_AFTER_S = 3;
539
+ var skipMode = (mode) => mode === "stop" || mode === "repeat-one" ? "next" : mode;
540
+ var STOP = { kind: "stop" };
541
+ var REPLAY = { kind: "replay" };
542
+ var HISTORY_LIMIT = 500;
543
+ function createEndPolicy({ random = Math.random, restartAfterS = PREVIOUS_RESTARTS_AFTER_S } = {}) {
544
+ let played = /* @__PURE__ */ new Set();
545
+ let history = [];
546
+ let forward = [];
547
+ let picked = null;
548
+ let moved = null;
549
+ let shuffling = false;
550
+ const enter = (mode) => {
551
+ const s = mode === "shuffle";
552
+ if (s !== shuffling) {
553
+ history = [];
554
+ forward = [];
555
+ shuffling = s;
556
+ }
557
+ };
558
+ const remember = (id) => {
559
+ if (history[history.length - 1] !== id) history.push(id);
560
+ if (history.length > HISTORY_LIMIT) history.splice(0, history.length - HISTORY_LIMIT);
561
+ };
562
+ const forwardTop = (ids, current) => {
563
+ while (forward.length) {
564
+ const id = forward[forward.length - 1];
565
+ if (id !== current && ids.includes(id)) return id;
566
+ forward.pop();
567
+ }
568
+ return null;
569
+ };
570
+ const shufflePick = (ids, current) => {
571
+ const again = forwardTop(ids, current);
572
+ if (again) return { kind: "play", id: again, wrapped: false };
573
+ if (picked && picked.after === current && ids.includes(picked.id) && picked.id !== current) {
574
+ return { kind: "play", id: picked.id, wrapped: picked.wrapped };
575
+ }
576
+ const others = ids.filter((id2) => id2 !== current);
577
+ if (!others.length) return ids.includes(current) ? REPLAY : STOP;
578
+ const fresh = others.filter((id2) => !played.has(id2));
579
+ const wrapped = fresh.length === 0;
580
+ const pool = wrapped ? others : fresh;
581
+ const id = pool[Math.min(pool.length - 1, Math.floor(random() * pool.length))];
582
+ picked = { after: current, id, wrapped };
583
+ return { kind: "play", id, wrapped };
584
+ };
585
+ const decide = (mode, ids, current) => {
586
+ enter(mode);
587
+ if (mode === "stop") return STOP;
588
+ if (mode === "repeat-one") return REPLAY;
589
+ if (mode === "shuffle") return shufflePick(ids, current);
590
+ const i = ids.indexOf(current);
591
+ if (mode === "next") return i >= 0 && i + 1 < ids.length ? { kind: "play", id: ids[i + 1], wrapped: false } : STOP;
592
+ if (!ids.length) return STOP;
593
+ if (i < 0) return { kind: "play", id: ids[0], wrapped: false };
594
+ if (ids.length === 1) return REPLAY;
595
+ return i + 1 < ids.length ? { kind: "play", id: ids[i + 1], wrapped: false } : { kind: "play", id: ids[0], wrapped: true };
596
+ };
597
+ const take = (mode, ids, current) => {
598
+ const d = decide(mode, ids, current);
599
+ if (mode === "shuffle") {
600
+ if (d.kind === "play" && forward[forward.length - 1] === d.id) forward.pop();
601
+ else if (d.kind === "play" && d.wrapped) played = /* @__PURE__ */ new Set();
602
+ else played.add(current);
603
+ if (d.kind === "play") remember(current);
604
+ }
605
+ moved = d.kind === "play" ? d.id : null;
606
+ picked = null;
607
+ return d;
608
+ };
609
+ const back = (mode, ids, current, position) => {
610
+ enter(mode);
611
+ moved = null;
612
+ if (position > restartAfterS) return REPLAY;
613
+ if (mode === "shuffle") {
614
+ while (history.length) {
615
+ const id = history.pop();
616
+ if (id !== current && ids.includes(id)) {
617
+ forward.push(current);
618
+ picked = null;
619
+ moved = id;
620
+ return { kind: "play", id, wrapped: false };
621
+ }
622
+ }
623
+ return REPLAY;
624
+ }
625
+ const i = ids.indexOf(current);
626
+ const d = i > 0 ? { kind: "play", id: ids[i - 1], wrapped: false } : mode === "repeat-all" && ids.length > (i === 0 ? 1 : 0) ? { kind: "play", id: ids[ids.length - 1], wrapped: i === 0 } : REPLAY;
627
+ moved = d.kind === "play" ? d.id : null;
628
+ return d;
629
+ };
630
+ return {
631
+ peek: decide,
632
+ take,
633
+ peekSkip: (mode, ids, current) => decide(skipMode(mode), ids, current),
634
+ skip: (mode, ids, current) => take(skipMode(mode), ids, current),
635
+ back,
636
+ opened(from, to) {
637
+ if (to === moved) {
638
+ moved = null;
639
+ return;
640
+ }
641
+ moved = null;
642
+ picked = null;
643
+ forward = [];
644
+ if (!shuffling) return;
645
+ if (from && from !== to) remember(from);
646
+ played.add(to);
647
+ },
648
+ reset() {
649
+ played = /* @__PURE__ */ new Set();
650
+ picked = null;
651
+ history = [];
652
+ forward = [];
653
+ moved = null;
654
+ }
655
+ };
656
+ }
485
657
  // Annotate the CommonJS export names for ESM import in node:
486
658
  0 && (module.exports = {
487
659
  CUE_EPSILON_S,
660
+ DEFAULT_END_MODE,
488
661
  DEFAULT_FOLLOW_OPTIONS,
489
662
  DEFAULT_OWN_SCROLL_MS,
490
663
  DEFAULT_SLEEP_FADE_MS,
491
664
  DEFAULT_SLEEP_TICK_MS,
665
+ END_MODES,
666
+ END_MODE_INFO,
667
+ PREVIOUS_RESTARTS_AFTER_S,
492
668
  SCROLL_KEYS,
493
669
  SEEK_LAND_TIMEOUT_MS,
494
670
  SLEEP_MINUTES,
495
671
  attachFollow,
672
+ createEndPolicy,
496
673
  createFollow,
497
674
  createSleepTimer,
498
675
  createTimedText,
@@ -500,11 +677,14 @@ function formatCountdown(ms) {
500
677
  cuesDuration,
501
678
  formatCountdown,
502
679
  formatTime,
680
+ isEndMode,
681
+ nextEndMode,
503
682
  parseWebVtt,
504
683
  scrollLineIntoContainer,
505
684
  scrollerOf,
506
685
  seekLanded,
507
686
  seekThenPlay,
687
+ skipMode,
508
688
  wordAt
509
689
  });
510
690
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/cues.ts","../src/vtt.ts","../src/playback.ts","../src/follow.ts","../src/timed-text.ts","../src/sleep.ts"],"sourcesContent":["/**\n * `@zodal/media`: the fleet's audio and media UI affordances, headless first.\n *\n * - `./cues`: timed text looked up by time (`cueAt`, `wordAt`, `formatTime`).\n * - `./vtt`: `parseWebVtt`, WebVTT or SRT captions and chapters to cues.\n * - `./playback`: `seekThenPlay`, playing from a chosen point safely on every engine.\n * - `./follow`: keep the current line in view until a person scrolls, scrolling one container.\n * - `./timed-text`: a timed text over a media port: current cue and word, tap a line.\n * - `./sleep`: a sleep timer: pause after listening minutes or at a point, with a fade.\n * - `./transport`: a headless player with a queue over any `MediaPort`.\n * - `./commands`: the transport's and the sleep timer's actions as acture commands (needs `acture` and `zod`).\n *\n * The root re-exports the pure parts (cues, vtt, playback, follow, timed text, sleep): no zustand, acture or\n * zod. Import the transport and the commands from their subpaths.\n */\nexport * from './cues.js';\nexport * from './vtt.js';\nexport * from './playback.js';\nexport * from './follow.js';\nexport * from './timed-text.js';\nexport * from './sleep.js';\n","/**\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","/**\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 }\n return cues.sort((a, b) => a.start - b.start);\n}\n","/**\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","/**\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 detach() {\n offs.forEach((off) => off());\n },\n };\n}\n","/**\n * A timed text over a media port: which cue and word are being heard, and what a tap on a line\n * does. Renderer-agnostic; a transcript, a lyrics panel and a subtitle line all draw from it.\n *\n * A tap plays from the line by default (a transcript); `playOnTap: false` only moves there (a\n * lyrics panel whose player is elsewhere). Playing from a line uses `seekThenPlay`, so it plays\n * from the line on Safari too after the media has ended.\n */\nimport { cueAt, wordAt, type CueAtOptions, type CueLike } from './cues.js';\nimport { seekThenPlay, type SeekablePort } from './playback.js';\nimport type { Follow } from './follow.js';\n\n/** The part of a media element a timed text uses. */\nexport interface TimedTextPort extends SeekablePort {\n readonly paused: boolean;\n}\n\nexport interface TimedTextState {\n cue: number;\n word: number;\n}\n\nexport interface TimedTextOptions extends CueAtOptions {\n /** A tap on a line plays from it (default) or only moves there. */\n playOnTap?: boolean;\n /** What starting playback means, to catch a refusal; defaults to `port.play()`. */\n play?: () => Promise<void> | void;\n /** A follow state to resume when a line is tapped. */\n follow?: Follow;\n}\n\nexport interface TimedText {\n get(): TimedTextState;\n subscribe(listener: (state: TimedTextState, previous: TimedTextState) => void): () => void;\n /** Read the port's position; call on a frame while playing and on `seeked`. */\n tick(): void;\n /** A person chose line `index`. */\n tapCue(index: number): void;\n /** Cancel a play waiting for its seek (a pause tapped meanwhile). True if there was one. */\n cancelHeldPlay(): boolean;\n /** The view went away: cancel a held play and forget the listeners. */\n dispose(): void;\n}\n\nexport function createTimedText(cues: readonly CueLike[], port: TimedTextPort, options: TimedTextOptions = {}): TimedText {\n const { playOnTap = true, play, follow, ...lookup } = options;\n let state: TimedTextState = { cue: -1, word: -1 };\n const listeners = new Set<(state: TimedTextState, previous: TimedTextState) => void>();\n let held: AbortController | null = null;\n\n const tick = () => {\n const time = port.currentTime;\n const cue = cueAt(cues, time, lookup);\n const word = wordAt(cues[cue], time);\n if (cue === state.cue && word === state.word) return;\n const previous = state;\n state = { cue, word };\n listeners.forEach((l) => l(state, previous));\n };\n const cancelHeldPlay = () => {\n if (!held) return false;\n held.abort();\n held = null;\n return true;\n };\n\n return {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n tick,\n tapCue(index) {\n const cue = cues[index];\n if (!cue) return;\n follow?.resume();\n cancelHeldPlay();\n if (playOnTap && port.paused) {\n const mine = new AbortController();\n held = mine;\n seekThenPlay(port, cue.start, { play, signal: mine.signal }).then(\n () => { if (held === mine) held = null; },\n () => undefined, // cancelled, or refused: the host's `play` reports a refusal\n );\n } else {\n port.currentTime = cue.start;\n }\n tick();\n },\n cancelHeldPlay,\n dispose() {\n cancelHeldPlay();\n listeners.clear();\n },\n };\n}\n","/**\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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAQ,EAAE,GAAG,KAAK,OAAO;AACzB,WAAK;AAAA,IACP;AAAA,IACA,OAAO,SAAS;AACd,YAAM,SAAS,MAAM;AACrB,UAAI,CAAC,OAAQ,QAAO,MAAM,IAAI,EAAE,MAAM,SAAS,QAAQ,CAAC;AACxD,YAAM,OAAO,OAAO,SAAS,UAAU,SAAU,MAAM,eAAe;AACtE,YAAM,IAAI,EAAE,MAAM,SAAS,UAAU,OAAO,UAAU,OAAU,IAAO,CAAC;AAAA,IAC1E;AAAA,IACA,SAAS;AACP,UAAI,MAAM,OAAQ,MAAK,WAAW;AAAA,IACpC;AAAA,IACA;AAAA,IACA,UAAU;AACR,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":["seconds","SECONDS_PER_MINUTE","seconds"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/cues.ts","../src/vtt.ts","../src/playback.ts","../src/follow.ts","../src/timed-text.ts","../src/sleep.ts","../src/end-mode.ts"],"sourcesContent":["/**\n * `@zodal/media`: the fleet's audio and media UI affordances, headless first.\n *\n * - `./cues`: timed text looked up by time (`cueAt`, `wordAt`, `formatTime`).\n * - `./vtt`: `parseWebVtt`, WebVTT or SRT captions and chapters to cues.\n * - `./playback`: `seekThenPlay`, playing from a chosen point safely on every engine.\n * - `./follow`: keep the current line in view until a person scrolls, scrolling one container.\n * - `./timed-text`: a timed text over a media port: current cue and word, tap a line.\n * - `./sleep`: a sleep timer: pause after listening minutes or at a point, with a fade.\n * - `./end-mode`: what plays when an item ends (stop, repeat one, in order, repeat all, shuffle).\n * - `./transport`: a headless player with a queue over any `MediaPort`.\n * - `./commands`: the transport's and the sleep timer's actions as acture commands (needs `acture` and `zod`).\n *\n * The root re-exports the pure parts (cues, vtt, playback, follow, timed text, sleep, end mode): no zustand, acture or\n * zod. Import the transport and the commands from their subpaths.\n */\nexport * from './cues.js';\nexport * from './vtt.js';\nexport * from './playback.js';\nexport * from './follow.js';\nexport * from './timed-text.js';\nexport * from './sleep.js';\nexport * from './end-mode.js';\n","/**\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","/**\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 }\n return cues.sort((a, b) => a.start - b.start);\n}\n","/**\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","/**\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 detach() {\n offs.forEach((off) => off());\n },\n };\n}\n","/**\n * A timed text over a media port: which cue and word are being heard, and what a tap on a line\n * does. Renderer-agnostic; a transcript, a lyrics panel and a subtitle line all draw from it.\n *\n * A tap plays from the line by default (a transcript); `playOnTap: false` only moves there (a\n * lyrics panel whose player is elsewhere). Playing from a line uses `seekThenPlay`, so it plays\n * from the line on Safari too after the media has ended.\n */\nimport { cueAt, wordAt, type CueAtOptions, type CueLike } from './cues.js';\nimport { seekThenPlay, type SeekablePort } from './playback.js';\nimport type { Follow } from './follow.js';\n\n/** The part of a media element a timed text uses. */\nexport interface TimedTextPort extends SeekablePort {\n readonly paused: boolean;\n}\n\nexport interface TimedTextState {\n cue: number;\n word: number;\n}\n\nexport interface TimedTextOptions extends CueAtOptions {\n /** A tap on a line plays from it (default) or only moves there. */\n playOnTap?: boolean;\n /** What starting playback means, to catch a refusal; defaults to `port.play()`. */\n play?: () => Promise<void> | void;\n /** A follow state to resume when a line is tapped. */\n follow?: Follow;\n}\n\nexport interface TimedText {\n get(): TimedTextState;\n subscribe(listener: (state: TimedTextState, previous: TimedTextState) => void): () => void;\n /** Read the port's position; call on a frame while playing and on `seeked`. */\n tick(): void;\n /** A person chose line `index`. */\n tapCue(index: number): void;\n /** Cancel a play waiting for its seek (a pause tapped meanwhile). True if there was one. */\n cancelHeldPlay(): boolean;\n /** The view went away: cancel a held play and forget the listeners. */\n dispose(): void;\n}\n\nexport function createTimedText(cues: readonly CueLike[], port: TimedTextPort, options: TimedTextOptions = {}): TimedText {\n const { playOnTap = true, play, follow, ...lookup } = options;\n let state: TimedTextState = { cue: -1, word: -1 };\n const listeners = new Set<(state: TimedTextState, previous: TimedTextState) => void>();\n let held: AbortController | null = null;\n\n const tick = () => {\n const time = port.currentTime;\n const cue = cueAt(cues, time, lookup);\n const word = wordAt(cues[cue], time);\n if (cue === state.cue && word === state.word) return;\n const previous = state;\n state = { cue, word };\n listeners.forEach((l) => l(state, previous));\n };\n const cancelHeldPlay = () => {\n if (!held) return false;\n held.abort();\n held = null;\n return true;\n };\n\n return {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n tick,\n tapCue(index) {\n const cue = cues[index];\n if (!cue) return;\n follow?.resume();\n cancelHeldPlay();\n if (playOnTap && port.paused) {\n const mine = new AbortController();\n held = mine;\n seekThenPlay(port, cue.start, { play, signal: mine.signal }).then(\n () => { if (held === mine) held = null; },\n () => undefined, // cancelled, or refused: the host's `play` reports a refusal\n );\n } else {\n port.currentTime = cue.start;\n }\n tick();\n },\n cancelHeldPlay,\n dispose() {\n cancelHeldPlay();\n listeners.clear();\n },\n };\n}\n","/**\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","/**\n * What plays when an item ends: one mode, chosen by the listener, applied to the set playback\n * started from (the list, filter, playlist or album the item was played from: its \"play context\").\n * Headless and pure apart from the shuffle's memory: no DOM, no zustand, no React.\n *\n * ```ts\n * const policy = createEndPolicy();\n * audio.addEventListener('ended', () => {\n * const d = policy.take(mode, setIds, currentId); // 'stop' | 'replay' | 'play' (an id)\n * if (d.kind === 'play') open(d.id); else if (d.kind === 'replay') restart();\n * });\n * policy.peek(mode, setIds, currentId); // the same decision, for an \"Up next\" line\n * nextButton.onclick = () => act(policy.skip(mode, setIds, currentId)); // ▶|\n * prevButton.onclick = () => act(policy.back(mode, setIds, currentId, audio.currentTime)); // |◀\n * ```\n *\n * The five modes are the classic players' states folded into one choice (Android's and Apple's\n * repeat off / one / all plus shuffle on / off, and foobar2000's single \"playback order\" menu with\n * \"stop after current\"), named in words, because a cycling repeat button whose only difference\n * between two states is a tiny \"1\" is the most reported confusion in the genre. Research and the\n * decision: `docs/research/end-of-item-modes.md` in this repository.\n *\n * Choices, each a default the host can change:\n * - **Shuffle is a shuffle, not a die.** Every item of the set plays once, in random order, before\n * any plays again; then a new round starts, never with the item that just ended. It goes on until\n * the listener stops (or a sleep timer does). Items added to the set join the current round;\n * items taken out are never picked.\n * - **Repeat one replays the item**; \"In order\" stops after the last item of the set; \"Repeat all\"\n * wraps to the first. A set of one item under \"Repeat all\" or \"Shuffle\" replays it.\n * - **An item not in the set** (taken out of the playlist while it played): \"In order\" stops,\n * \"Repeat all\" goes to the set's first item, \"Shuffle\" picks from the set.\n *\n * The transport's buttons follow the same set and mode, as every mainstream player does:\n * - **Next (▶|)** moves on now. \"Repeat this one\" and \"Stop after this one\" are about what happens\n * when an item *ends*, so they do not trap the button: it goes to the next item of the list in\n * order. Past the last item it wraps under \"Repeat all\", picks the next of the round under\n * \"Shuffle\", and otherwise does nothing (a host disables the button: `peekSkip` says so).\n * - **Previous (|◀)** restarts the current item when more than `restartAfterS` (3 s, the CD-player\n * rule) has played; otherwise it goes to the item before: the one played before it under\n * \"Shuffle\", the one above it in the list otherwise, wrapping to the last under \"Repeat all\". With\n * nothing before, it restarts.\n */\n\n/** The modes, in the order a menu lists them (stop first, then the loops). */\nexport const END_MODES = ['stop', 'repeat-one', 'next', 'repeat-all', 'shuffle'] as const;\nexport type EndMode = (typeof END_MODES)[number];\n\n/** The default: play on through the set, in order, and stop after its last item (a playlist played through). */\nexport const DEFAULT_END_MODE: EndMode = 'next';\n\nexport interface EndModeInfo {\n mode: EndMode;\n /** The menu's words: what happens when an item ends. */\n label: string;\n /** The word shown on the control beside its icon (always shown: the icon alone is ambiguous). */\n short: string;\n /** One sentence for a tooltip or a screen reader. */\n description: string;\n /** The standard icon's name in Material Symbols and in Lucide (a host draws it from either set). */\n icon: { material: string; lucide: string };\n}\n\n/** The terms and icons, one source for every host (chosen in `docs/research/end-of-item-modes.md`). */\nexport const END_MODE_INFO: Record<EndMode, EndModeInfo> = {\n stop: {\n mode: 'stop', label: 'Stop after this one', short: 'Then stop',\n description: 'When this item ends, playback stops.',\n icon: { material: 'keyboard_tab', lucide: 'arrow-right-to-line' },\n },\n 'repeat-one': {\n mode: 'repeat-one', label: 'Repeat this one', short: 'Repeat 1',\n description: 'This item plays again from the start each time it ends.',\n icon: { material: 'repeat_one', lucide: 'repeat-1' },\n },\n next: {\n mode: 'next', label: 'Play the list in order', short: 'In order',\n description: 'The next item of the list plays; playback stops after the last one.',\n icon: { material: 'playlist_play', lucide: 'list-video' },\n },\n 'repeat-all': {\n mode: 'repeat-all', label: 'Repeat the list', short: 'Repeat all',\n description: 'The list plays in order and starts again after its last item.',\n icon: { material: 'repeat', lucide: 'repeat' },\n },\n shuffle: {\n mode: 'shuffle', label: 'Shuffle the list', short: 'Shuffle',\n description: 'A random item of the list plays next; each plays once before any plays again.',\n icon: { material: 'shuffle', lucide: 'shuffle' },\n },\n};\n\n/** Whether a value is one of the modes (a persisted preference may hold an old or foreign value). */\nexport const isEndMode = (value: unknown): value is EndMode => (END_MODES as readonly unknown[]).includes(value);\n\n/** The mode after `mode` in menu order, wrapping: for a single key or button that steps through them. */\nexport function nextEndMode(mode: EndMode): EndMode {\n return END_MODES[(END_MODES.indexOf(mode) + 1) % END_MODES.length];\n}\n\n/** What to do when the current item ends. */\nexport type EndDecision =\n | { kind: 'stop' }\n /** Play the current item again from its start. */\n | { kind: 'replay' }\n /** Play this item of the set; `wrapped`: the set starts over (repeat all past the end, a new shuffle round). */\n | { kind: 'play'; id: string; wrapped: boolean };\n\n/** How far into an item (seconds) Previous restarts it instead of going to the item before: the CD-player rule. */\nexport const PREVIOUS_RESTARTS_AFTER_S = 3;\n\n/**\n * The mode the Next button follows: the end-of-item mode, except that \"Repeat this one\" and\n * \"Stop after this one\" say what happens at an item's end, not where Next goes, so Next goes on in order.\n */\nexport const skipMode = (mode: EndMode): EndMode => (mode === 'stop' || mode === 'repeat-one' ? 'next' : mode);\n\nexport interface EndPolicy {\n /** What `take` would decide now, without moving on (an \"Up next\" line). Stable until `take` or `reset`. */\n peek(mode: EndMode, ids: readonly string[], current: string): EndDecision;\n /** Decide at the end of `current`, and remember it (the shuffle's round). */\n take(mode: EndMode, ids: readonly string[], current: string): EndDecision;\n /**\n * What `skip` would do now (Next, ▶|), without moving on: `stop` means there is nothing next (disable the button).\n * Under \"Shuffle\" this draws (and keeps) the pick, as `peek` does, so the button and an \"Up next\" line agree.\n */\n peekSkip(mode: EndMode, ids: readonly string[], current: string): EndDecision;\n /** Next (▶|): go on now, in the list's order (see `skipMode`), and remember it like `take`. */\n skip(mode: EndMode, ids: readonly string[], current: string): EndDecision;\n /**\n * Previous (|◀) at `position` seconds into `current`: `replay` (restart it) when past `restartAfterS`\n * or when nothing comes before, else the item before. `wrapped` here means it went round backwards (from the\n * first to the last under \"Repeat all\"), not that a new round starts. Under \"Shuffle\", Next and the end then\n * go forward again through the items Previous came back from, before any new pick.\n */\n back(mode: EndMode, ids: readonly string[], current: string, position: number): EndDecision;\n /**\n * Tell the policy the host opened `to` itself (a row tapped), from `from` (null: nothing was playing).\n * Call it on every open; the opens that carry out this policy's own decisions are recognised and skipped.\n * Under \"Shuffle\" Previous then comes back to `from`, and `to` counts as played this round.\n */\n opened(from: string | null, to: string): void;\n /** Forget the shuffle's round and what was played before: call when the set changes to another one (a new list was played from). */\n reset(): void;\n}\n\nexport interface EndPolicyOptions {\n /** A number in [0, 1): `Math.random` by default; a seeded one for tests. */\n random?: () => number;\n /** Seconds into an item past which Previous restarts it (default `PREVIOUS_RESTARTS_AFTER_S`). */\n restartAfterS?: number;\n}\n\nconst STOP: EndDecision = { kind: 'stop' };\nconst REPLAY: EndDecision = { kind: 'replay' };\n\n/** At most this many items are remembered for Previous under \"Shuffle\". */\nconst HISTORY_LIMIT = 500;\n\n/** The policy for one player. Every mode but shuffle is a pure function of the set and the current item. */\nexport function createEndPolicy({ random = Math.random, restartAfterS = PREVIOUS_RESTARTS_AFTER_S }: EndPolicyOptions = {}): EndPolicy {\n /** Items played in this shuffle round. */\n let played = new Set<string>();\n /** Under \"Shuffle\", the items moved on from, latest last: where Previous goes. */\n let history: string[] = [];\n /** Under \"Shuffle\", the items Previous came back from, latest last: where Next (and the end) go again first. */\n let forward: string[] = [];\n /** The shuffle's pick for `after`, kept so `peek` and `take` agree and an \"Up next\" line does not flicker. */\n let picked: { after: string; id: string; wrapped: boolean } | null = null;\n /** The item the policy's last move went to, so the host's `opened` call for that move is not counted twice. */\n let moved: string | null = null;\n /** Whether the last call was under \"Shuffle\": leaving or entering it forgets the shuffle's back and forth. */\n let shuffling = false;\n\n const enter = (mode: EndMode) => {\n const s = mode === 'shuffle';\n if (s !== shuffling) { history = []; forward = []; shuffling = s; }\n };\n const remember = (id: string) => {\n if (history[history.length - 1] !== id) history.push(id);\n if (history.length > HISTORY_LIMIT) history.splice(0, history.length - HISTORY_LIMIT);\n };\n /** The top of `forward` still worth going to (in the set, not the current item), dropping the others. */\n const forwardTop = (ids: readonly string[], current: string): string | null => {\n while (forward.length) {\n const id = forward[forward.length - 1];\n if (id !== current && ids.includes(id)) return id;\n forward.pop();\n }\n return null;\n };\n\n const shufflePick = (ids: readonly string[], current: string): EndDecision => {\n const again = forwardTop(ids, current);\n if (again) return { kind: 'play', id: again, wrapped: false };\n if (picked && picked.after === current && ids.includes(picked.id) && picked.id !== current) {\n return { kind: 'play', id: picked.id, wrapped: picked.wrapped };\n }\n const others = ids.filter((id) => id !== current);\n if (!others.length) return ids.includes(current) ? REPLAY : STOP;\n const fresh = others.filter((id) => !played.has(id));\n const wrapped = fresh.length === 0;\n const pool = wrapped ? others : fresh;\n const id = pool[Math.min(pool.length - 1, Math.floor(random() * pool.length))];\n picked = { after: current, id, wrapped };\n return { kind: 'play', id, wrapped };\n };\n\n const decide = (mode: EndMode, ids: readonly string[], current: string): EndDecision => {\n enter(mode);\n if (mode === 'stop') return STOP;\n if (mode === 'repeat-one') return REPLAY;\n if (mode === 'shuffle') return shufflePick(ids, current);\n const i = ids.indexOf(current);\n if (mode === 'next') return i >= 0 && i + 1 < ids.length ? { kind: 'play', id: ids[i + 1], wrapped: false } : STOP;\n // repeat-all\n if (!ids.length) return STOP;\n if (i < 0) return { kind: 'play', id: ids[0], wrapped: false };\n if (ids.length === 1) return REPLAY;\n return i + 1 < ids.length ? { kind: 'play', id: ids[i + 1], wrapped: false } : { kind: 'play', id: ids[0], wrapped: true };\n };\n\n const take = (mode: EndMode, ids: readonly string[], current: string): EndDecision => {\n const d = decide(mode, ids, current);\n if (mode === 'shuffle') {\n if (d.kind === 'play' && forward[forward.length - 1] === d.id) forward.pop(); // forward again, through what Previous left\n // A new round: everything is fresh again, the item that just ended included (it only may not\n // start the round, which `others` already ensures).\n else if (d.kind === 'play' && d.wrapped) played = new Set();\n else played.add(current);\n if (d.kind === 'play') remember(current);\n }\n moved = d.kind === 'play' ? d.id : null;\n picked = null;\n return d;\n };\n\n const back = (mode: EndMode, ids: readonly string[], current: string, position: number): EndDecision => {\n enter(mode);\n moved = null;\n if (position > restartAfterS) return REPLAY;\n if (mode === 'shuffle') {\n // Back through what was played, skipping items that left the set (or the current one, met again).\n while (history.length) {\n const id = history.pop()!;\n if (id !== current && ids.includes(id)) {\n forward.push(current);\n picked = null;\n moved = id;\n return { kind: 'play', id, wrapped: false };\n }\n }\n return REPLAY;\n }\n const i = ids.indexOf(current);\n const d: EndDecision = i > 0 ? { kind: 'play', id: ids[i - 1], wrapped: false }\n // Under \"Repeat all\" the list goes round backwards too: from the first (or an item not in it) to the last.\n : mode === 'repeat-all' && ids.length > (i === 0 ? 1 : 0) ? { kind: 'play', id: ids[ids.length - 1], wrapped: i === 0 }\n : REPLAY;\n moved = d.kind === 'play' ? d.id : null;\n return d;\n };\n\n return {\n peek: decide,\n take,\n peekSkip: (mode, ids, current) => decide(skipMode(mode), ids, current),\n skip: (mode, ids, current) => take(skipMode(mode), ids, current),\n back,\n opened(from, to) {\n if (to === moved) { moved = null; return; } // the policy's own move, already counted\n moved = null;\n picked = null;\n forward = [];\n if (!shuffling) return;\n if (from && from !== to) remember(from);\n played.add(to);\n },\n reset() { played = new Set(); picked = null; history = []; forward = []; moved = null; },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,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,WA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,CAAC,GAAG,SAAS,MAAM,EAAE,IACpH;AACJ,YAAQ,EAAE,SAAS,SAAS,EAAE,KAAK;AACnC,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA,UAAU,CAAC,MAAM,KAAK,YAAY,OAAO,SAAS,IAAI,GAAG,KAAK,OAAO;AAAA,IACrE,MAAM,CAAC,MAAM,KAAK,YAAY,KAAK,SAAS,IAAI,GAAG,KAAK,OAAO;AAAA,IAC/D;AAAA,IACA,OAAO,MAAM,IAAI;AACf,UAAI,OAAO,OAAO;AAAE,gBAAQ;AAAM;AAAA,MAAQ;AAC1C,cAAQ;AACR,eAAS;AACT,gBAAU,CAAC;AACX,UAAI,CAAC,UAAW;AAChB,UAAI,QAAQ,SAAS,GAAI,UAAS,IAAI;AACtC,aAAO,IAAI,EAAE;AAAA,IACf;AAAA,IACA,QAAQ;AAAE,eAAS,oBAAI,IAAI;AAAG,eAAS;AAAM,gBAAU,CAAC;AAAG,gBAAU,CAAC;AAAG,cAAQ;AAAA,IAAM;AAAA,EACzF;AACF;","names":["seconds","SECONDS_PER_MINUTE","seconds","id"]}
package/dist/index.d.cts CHANGED
@@ -4,3 +4,4 @@ export { SEEK_LAND_TIMEOUT_MS, SeekThenPlayOptions, SeekablePort, seekLanded, se
4
4
  export { AttachFollowOptions, AttachedFollow, DEFAULT_FOLLOW_OPTIONS, DEFAULT_OWN_SCROLL_MS, Follow, FollowOptions, FollowState, SCROLL_KEYS, attachFollow, createFollow, scrollLineIntoContainer, scrollerOf } from './follow.cjs';
5
5
  export { TimedText, TimedTextOptions, TimedTextPort, TimedTextState, createTimedText } from './timed-text.cjs';
6
6
  export { DEFAULT_SLEEP_FADE_MS, DEFAULT_SLEEP_TICK_MS, SLEEP_MINUTES, SleepEndReason, SleepPort, SleepState, SleepTarget, SleepTimer, SleepTimerOptions, createSleepTimer, formatCountdown } from './sleep.cjs';
7
+ export { DEFAULT_END_MODE, END_MODES, END_MODE_INFO, EndDecision, EndMode, EndModeInfo, EndPolicy, EndPolicyOptions, PREVIOUS_RESTARTS_AFTER_S, createEndPolicy, isEndMode, nextEndMode, skipMode } from './end-mode.cjs';
package/dist/index.d.ts CHANGED
@@ -4,3 +4,4 @@ export { SEEK_LAND_TIMEOUT_MS, SeekThenPlayOptions, SeekablePort, seekLanded, se
4
4
  export { AttachFollowOptions, AttachedFollow, DEFAULT_FOLLOW_OPTIONS, DEFAULT_OWN_SCROLL_MS, Follow, FollowOptions, FollowState, SCROLL_KEYS, attachFollow, createFollow, scrollLineIntoContainer, scrollerOf } from './follow.js';
5
5
  export { TimedText, TimedTextOptions, TimedTextPort, TimedTextState, createTimedText } from './timed-text.js';
6
6
  export { DEFAULT_SLEEP_FADE_MS, DEFAULT_SLEEP_TICK_MS, SLEEP_MINUTES, SleepEndReason, SleepPort, SleepState, SleepTarget, SleepTimer, SleepTimerOptions, createSleepTimer, formatCountdown } from './sleep.js';
7
+ export { DEFAULT_END_MODE, END_MODES, END_MODE_INFO, EndDecision, EndMode, EndModeInfo, EndPolicy, EndPolicyOptions, PREVIOUS_RESTARTS_AFTER_S, createEndPolicy, isEndMode, nextEndMode, skipMode } from './end-mode.js';
package/dist/index.js CHANGED
@@ -20,6 +20,11 @@ import {
20
20
  formatTime,
21
21
  wordAt
22
22
  } from "./chunk-AMK7QKN7.js";
23
+ import {
24
+ SEEK_LAND_TIMEOUT_MS,
25
+ seekLanded,
26
+ seekThenPlay
27
+ } from "./chunk-NBKMSPYQ.js";
23
28
  import {
24
29
  DEFAULT_SLEEP_FADE_MS,
25
30
  DEFAULT_SLEEP_TICK_MS,
@@ -28,20 +33,30 @@ import {
28
33
  formatCountdown
29
34
  } from "./chunk-3JIQJ7J6.js";
30
35
  import {
31
- SEEK_LAND_TIMEOUT_MS,
32
- seekLanded,
33
- seekThenPlay
34
- } from "./chunk-NBKMSPYQ.js";
36
+ DEFAULT_END_MODE,
37
+ END_MODES,
38
+ END_MODE_INFO,
39
+ PREVIOUS_RESTARTS_AFTER_S,
40
+ createEndPolicy,
41
+ isEndMode,
42
+ nextEndMode,
43
+ skipMode
44
+ } from "./chunk-GALBANEF.js";
35
45
  export {
36
46
  CUE_EPSILON_S,
47
+ DEFAULT_END_MODE,
37
48
  DEFAULT_FOLLOW_OPTIONS,
38
49
  DEFAULT_OWN_SCROLL_MS,
39
50
  DEFAULT_SLEEP_FADE_MS,
40
51
  DEFAULT_SLEEP_TICK_MS,
52
+ END_MODES,
53
+ END_MODE_INFO,
54
+ PREVIOUS_RESTARTS_AFTER_S,
41
55
  SCROLL_KEYS,
42
56
  SEEK_LAND_TIMEOUT_MS,
43
57
  SLEEP_MINUTES,
44
58
  attachFollow,
59
+ createEndPolicy,
45
60
  createFollow,
46
61
  createSleepTimer,
47
62
  createTimedText,
@@ -49,11 +64,14 @@ export {
49
64
  cuesDuration,
50
65
  formatCountdown,
51
66
  formatTime,
67
+ isEndMode,
68
+ nextEndMode,
52
69
  parseWebVtt,
53
70
  scrollLineIntoContainer,
54
71
  scrollerOf,
55
72
  seekLanded,
56
73
  seekThenPlay,
74
+ skipMode,
57
75
  wordAt
58
76
  };
59
77
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zodal/media",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Headless audio and media UI affordances for zodal: timed text (transcripts, lyrics, subtitles) that follows the voice, a safe seek-and-play, a transport with a queue, and its commands.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -77,6 +77,16 @@
77
77
  "default": "./dist/sleep.cjs"
78
78
  }
79
79
  },
80
+ "./end-mode": {
81
+ "import": {
82
+ "types": "./dist/end-mode.d.ts",
83
+ "default": "./dist/end-mode.js"
84
+ },
85
+ "require": {
86
+ "types": "./dist/end-mode.d.cts",
87
+ "default": "./dist/end-mode.cjs"
88
+ }
89
+ },
80
90
  "./transport": {
81
91
  "import": {
82
92
  "types": "./dist/transport.d.ts",
@@ -105,12 +115,6 @@
105
115
  "dist"
106
116
  ],
107
117
  "sideEffects": false,
108
- "scripts": {
109
- "build": "tsup",
110
- "prepare": "tsup",
111
- "test": "vitest run",
112
- "typecheck": "tsc --noEmit"
113
- },
114
118
  "peerDependencies": {
115
119
  "zustand": "^5.0.3",
116
120
  "zod": "^4.0.0",
@@ -153,5 +157,9 @@
153
157
  "headless",
154
158
  "sleep-timer"
155
159
  ],
156
- "packageManager": "pnpm@9.15.0"
157
- }
160
+ "scripts": {
161
+ "build": "tsup",
162
+ "test": "vitest run",
163
+ "typecheck": "tsc --noEmit"
164
+ }
165
+ }