@vocasync/astro 1.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +735 -93
- package/dist/api/client.d.ts.map +1 -1
- package/dist/api/client.js.map +1 -1
- package/dist/api/index.d.ts +1 -1
- package/dist/api/index.d.ts.map +1 -1
- package/dist/api/index.js +1 -1
- package/dist/api/index.js.map +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/components/AudioPlayer.astro +305 -1141
- package/dist/components/index.d.ts +10 -32
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +1 -3
- package/dist/components/index.js.map +1 -1
- package/dist/components/types.d.ts +117 -0
- package/dist/components/types.d.ts.map +1 -0
- package/dist/components/types.js +2 -0
- package/dist/components/types.js.map +1 -0
- package/dist/config/index.d.ts +3 -2
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +2 -1
- package/dist/config/index.js.map +1 -1
- package/dist/config/languages.d.ts +33 -0
- package/dist/config/languages.d.ts.map +1 -0
- package/dist/config/languages.js +167 -0
- package/dist/config/languages.js.map +1 -0
- package/dist/config/schema.d.ts +225 -172
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +45 -24
- package/dist/config/schema.js.map +1 -1
- package/dist/core/content-loader.js +1 -1
- package/dist/core/content-loader.js.map +1 -1
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -2
- package/dist/core/index.js.map +1 -1
- package/dist/core/speech-builder.js.map +1 -1
- package/dist/index.d.ts +6 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -6
- package/dist/index.js.map +1 -1
- package/dist/integration.d.ts +28 -2
- package/dist/integration.d.ts.map +1 -1
- package/dist/integration.js +40 -3
- package/dist/integration.js.map +1 -1
- package/dist/lib/latex-to-speech/index.d.ts.map +1 -1
- package/dist/lib/latex-to-speech/index.js.map +1 -1
- package/dist/player-core/boot.d.ts +9 -0
- package/dist/player-core/boot.d.ts.map +1 -0
- package/dist/player-core/boot.js +59 -0
- package/dist/player-core/boot.js.map +1 -0
- package/dist/player-core/highlighter.d.ts +31 -0
- package/dist/player-core/highlighter.d.ts.map +1 -0
- package/dist/player-core/highlighter.js +103 -0
- package/dist/player-core/highlighter.js.map +1 -0
- package/dist/player-core/index.d.ts +17 -0
- package/dist/player-core/index.d.ts.map +1 -0
- package/dist/player-core/index.js +24 -0
- package/dist/player-core/index.js.map +1 -0
- package/dist/player-core/media-url.d.ts +18 -0
- package/dist/player-core/media-url.d.ts.map +1 -0
- package/dist/player-core/media-url.js +33 -0
- package/dist/player-core/media-url.js.map +1 -0
- package/dist/player-core/player.d.ts +9 -0
- package/dist/player-core/player.d.ts.map +1 -0
- package/dist/player-core/player.js +622 -0
- package/dist/player-core/player.js.map +1 -0
- package/dist/player-core/registry.d.ts +20 -0
- package/dist/player-core/registry.d.ts.map +1 -0
- package/dist/player-core/registry.js +31 -0
- package/dist/player-core/registry.js.map +1 -0
- package/dist/player-core/seek-delegate.d.ts +24 -0
- package/dist/player-core/seek-delegate.d.ts.map +1 -0
- package/dist/player-core/seek-delegate.js +64 -0
- package/dist/player-core/seek-delegate.js.map +1 -0
- package/dist/player-core/storage.d.ts +38 -0
- package/dist/player-core/storage.d.ts.map +1 -0
- package/dist/player-core/storage.js +107 -0
- package/dist/player-core/storage.js.map +1 -0
- package/dist/player-core/strings.d.ts +53 -0
- package/dist/player-core/strings.d.ts.map +1 -0
- package/dist/player-core/strings.js +45 -0
- package/dist/player-core/strings.js.map +1 -0
- package/dist/player-core/timings.d.ts +56 -0
- package/dist/player-core/timings.d.ts.map +1 -0
- package/dist/player-core/timings.js +90 -0
- package/dist/player-core/timings.js.map +1 -0
- package/dist/rehype/audio-words.d.ts +9 -3
- package/dist/rehype/audio-words.d.ts.map +1 -1
- package/dist/rehype/audio-words.js +17 -9
- package/dist/rehype/audio-words.js.map +1 -1
- package/dist/rehype/index.d.ts +2 -2
- package/dist/rehype/index.d.ts.map +1 -1
- package/dist/rehype/index.js.map +1 -1
- package/dist/rehype/rehype-math-speech.d.ts.map +1 -1
- package/dist/rehype/rehype-math-speech.js +2 -0
- package/dist/rehype/rehype-math-speech.js.map +1 -1
- package/dist/styles/content.css +41 -0
- package/dist/styles/layers.css +13 -0
- package/dist/styles/player.css +517 -0
- package/dist/styles/preset-shadcn.css +31 -0
- package/dist/styles/tokens.css +266 -0
- package/dist/styles/vocasync.css +10 -0
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/index.js +1 -1
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/orchestrator.d.ts.map +1 -1
- package/dist/sync/orchestrator.js +101 -47
- package/dist/sync/orchestrator.js.map +1 -1
- package/dist/types/index.d.ts +19 -5
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +39 -17
- package/src/api/index.ts +4 -4
- package/src/components/AudioPlayer.astro +305 -1141
- package/src/components/index.ts +19 -34
- package/src/components/types.ts +140 -0
- package/src/config/index.ts +29 -24
- package/src/config/languages.ts +171 -0
- package/src/config/schema.ts +47 -24
- package/src/core/content-loader.ts +1 -1
- package/src/core/index.ts +7 -7
- package/src/env.d.ts +2 -0
- package/src/index.ts +23 -28
- package/src/integration.ts +66 -4
- package/src/player-core/boot.ts +62 -0
- package/src/player-core/highlighter.ts +159 -0
- package/src/player-core/index.ts +45 -0
- package/src/player-core/media-url.ts +35 -0
- package/src/player-core/player.ts +725 -0
- package/src/player-core/registry.ts +40 -0
- package/src/player-core/seek-delegate.ts +92 -0
- package/src/player-core/storage.ts +112 -0
- package/src/player-core/strings.ts +89 -0
- package/src/player-core/timings.ts +115 -0
- package/src/rehype/audio-words.ts +25 -12
- package/src/rehype/index.ts +2 -3
- package/src/rehype/rehype-math-speech.ts +3 -1
- package/src/styles/content.css +41 -0
- package/src/styles/layers.css +13 -0
- package/src/styles/player.css +517 -0
- package/src/styles/preset-shadcn.css +31 -0
- package/src/styles/tokens.css +266 -0
- package/src/styles/vocasync.css +10 -0
- package/src/sync/index.ts +1 -1
- package/src/sync/orchestrator.ts +120 -56
- package/src/types/index.ts +19 -5
- package/dist/styles/variables.css +0 -164
- package/src/styles/variables.css +0 -164
|
@@ -0,0 +1,725 @@
|
|
|
1
|
+
import { createHighlighter, type Highlighter } from "./highlighter.js";
|
|
2
|
+
import { resolveAudioSrc } from "./media-url.js";
|
|
3
|
+
import * as registry from "./registry.js";
|
|
4
|
+
import { registerSeekRoot } from "./seek-delegate.js";
|
|
5
|
+
import {
|
|
6
|
+
clearPosition,
|
|
7
|
+
getStorage,
|
|
8
|
+
readPosition,
|
|
9
|
+
readPrefs,
|
|
10
|
+
resumePoint,
|
|
11
|
+
writePosition,
|
|
12
|
+
writePrefs,
|
|
13
|
+
} from "./storage.js";
|
|
14
|
+
import { defaultStrings, describeTime, formatString, type PlayerStrings } from "./strings.js";
|
|
15
|
+
import type { WordTiming } from "./timings.js";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The player controller: everything the shipped component's inline script did, minus
|
|
19
|
+
* the markup.
|
|
20
|
+
*
|
|
21
|
+
* Every element lookup is scoped to the region that owns it. The original resolved
|
|
22
|
+
* `[data-action="play-pause"]` against the player root, which matches the main button
|
|
23
|
+
* and the mini player's button, and relied on document order to pick the right one.
|
|
24
|
+
* Nothing here reads a DOM `id`, so duplicate ids -- two players for one slug -- no
|
|
25
|
+
* longer make two instances drive the same audio element.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
interface PlayerAudio {
|
|
29
|
+
audioUrl?: string;
|
|
30
|
+
words?: WordTiming[];
|
|
31
|
+
duration?: number;
|
|
32
|
+
publishableKey?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface PlayerOptions {
|
|
36
|
+
articleSelector?: string;
|
|
37
|
+
trailLength?: number;
|
|
38
|
+
highlighting?: boolean;
|
|
39
|
+
clickToSeek?: boolean;
|
|
40
|
+
autoScroll?: "off" | "paragraph";
|
|
41
|
+
dock?: boolean;
|
|
42
|
+
exclusive?: boolean;
|
|
43
|
+
skipSeconds?: number;
|
|
44
|
+
rememberPreferences?: boolean;
|
|
45
|
+
rememberPosition?: boolean;
|
|
46
|
+
mediaSession?: boolean;
|
|
47
|
+
slug?: string;
|
|
48
|
+
title?: string;
|
|
49
|
+
artwork?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface PlayerConfig {
|
|
53
|
+
audio: PlayerAudio | null;
|
|
54
|
+
options?: PlayerOptions;
|
|
55
|
+
strings?: Partial<PlayerStrings>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface PlayerInstance {
|
|
59
|
+
readonly root: HTMLElement;
|
|
60
|
+
pause(): void;
|
|
61
|
+
destroy(): void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const SPEED_STEP_SELECTOR = "[data-speed]";
|
|
65
|
+
|
|
66
|
+
/** M:SS, matching the shipped player including its zero fallback. */
|
|
67
|
+
export function formatTime(seconds: unknown): string {
|
|
68
|
+
if (typeof seconds !== "number" || !seconds || !Number.isFinite(seconds)) return "0:00";
|
|
69
|
+
const m = Math.floor(seconds / 60);
|
|
70
|
+
const s = Math.floor(seconds % 60);
|
|
71
|
+
return `${m}:${s.toString().padStart(2, "0")}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function readConfig(root: HTMLElement): PlayerConfig | null {
|
|
75
|
+
const script = root.querySelector("script.vocasync-data");
|
|
76
|
+
if (!script) return null;
|
|
77
|
+
try {
|
|
78
|
+
const parsed = JSON.parse(script.textContent ?? "{}");
|
|
79
|
+
return parsed && typeof parsed === "object" ? (parsed as PlayerConfig) : null;
|
|
80
|
+
} catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function createPlayer(root: HTMLElement): PlayerInstance | null {
|
|
86
|
+
const doc = root.ownerDocument;
|
|
87
|
+
const maybeView = doc.defaultView;
|
|
88
|
+
const maybeAudio = root.querySelector("audio") as HTMLAudioElement | null;
|
|
89
|
+
const maybeControls = root.querySelector('[data-state="ready"]') as HTMLElement | null;
|
|
90
|
+
if (!maybeView || !maybeAudio || !maybeControls) return null;
|
|
91
|
+
|
|
92
|
+
// Rebound as non-null so the narrowing holds inside the closures below.
|
|
93
|
+
const view = maybeView;
|
|
94
|
+
const audio: HTMLAudioElement = maybeAudio;
|
|
95
|
+
const controlsEl: HTMLElement = maybeControls;
|
|
96
|
+
|
|
97
|
+
const loadingEl = root.querySelector('[data-state="loading"]') as HTMLElement | null;
|
|
98
|
+
const placeholderEl = root.querySelector('[data-state="no-audio"]') as HTMLElement | null;
|
|
99
|
+
const errorEl = root.querySelector('[data-state="error"]') as HTMLElement | null;
|
|
100
|
+
const retryBtn = root.querySelector('[data-action="retry"]') as HTMLElement | null;
|
|
101
|
+
const miniEl = root.querySelector("[data-mini-player]") as HTMLElement | null;
|
|
102
|
+
|
|
103
|
+
// Scoped so the mini player's duplicate hooks never shadow the main controls.
|
|
104
|
+
const playBtn = controlsEl.querySelector('[data-action="play-pause"]') as HTMLElement | null;
|
|
105
|
+
const progressInput = controlsEl.querySelector('[data-action="seek"]') as HTMLInputElement | null;
|
|
106
|
+
const volumeInput = controlsEl.querySelector('[data-action="volume"]') as HTMLInputElement | null;
|
|
107
|
+
const muteBtn = controlsEl.querySelector('[data-action="mute"]') as HTMLElement | null;
|
|
108
|
+
const speedBtn = controlsEl.querySelector('[data-action="speed"]') as HTMLElement | null;
|
|
109
|
+
const speedMenu = controlsEl.querySelector(".vocasync-player__speed-menu") as HTMLElement | null;
|
|
110
|
+
const speedLabel = controlsEl.querySelector("[data-speed-label]") as HTMLElement | null;
|
|
111
|
+
const highlightBtn = controlsEl.querySelector(
|
|
112
|
+
'[data-action="toggle-highlighting"]'
|
|
113
|
+
) as HTMLElement | null;
|
|
114
|
+
const currentTimeEl = controlsEl.querySelector('[data-time="current"]') as HTMLElement | null;
|
|
115
|
+
const durationTimeEl = controlsEl.querySelector('[data-time="duration"]') as HTMLElement | null;
|
|
116
|
+
|
|
117
|
+
const miniPlayBtn = miniEl?.querySelector('[data-action="play-pause"]') as HTMLElement | null;
|
|
118
|
+
const miniCloseBtn = miniEl?.querySelector('[data-action="close-mini"]') as HTMLElement | null;
|
|
119
|
+
const miniProgressBar = miniEl?.querySelector("[data-progress]") as HTMLElement | null;
|
|
120
|
+
const miniTimeEl = miniEl?.querySelector('[data-time="current"]') as HTMLElement | null;
|
|
121
|
+
|
|
122
|
+
const config = readConfig(root);
|
|
123
|
+
const opts = config?.options ?? {};
|
|
124
|
+
const strings: PlayerStrings = { ...defaultStrings, ...(config?.strings ?? {}) };
|
|
125
|
+
|
|
126
|
+
const articleSelector = opts.articleSelector || "[data-article-body]";
|
|
127
|
+
const trailLength = Number.isFinite(opts.trailLength) ? (opts.trailLength as number) : 4;
|
|
128
|
+
const miniEnabled = opts.dock !== false && !!miniEl;
|
|
129
|
+
const clickToSeekEnabled = opts.clickToSeek !== false;
|
|
130
|
+
const autoScrollEnabled = opts.autoScroll === "paragraph";
|
|
131
|
+
const exclusive = opts.exclusive !== false;
|
|
132
|
+
const skipSeconds = Number.isFinite(opts.skipSeconds) ? (opts.skipSeconds as number) : 15;
|
|
133
|
+
const storage = opts.rememberPreferences === false ? null : getStorage(view);
|
|
134
|
+
const positionStore = opts.rememberPosition ? getStorage(view) : null;
|
|
135
|
+
const slug = opts.slug ?? "";
|
|
136
|
+
|
|
137
|
+
let highlightingEnabled = opts.highlighting !== false;
|
|
138
|
+
let isPlaying = false;
|
|
139
|
+
let miniVisible = false;
|
|
140
|
+
let miniDismissed = false;
|
|
141
|
+
let animationFrame: number | null = null;
|
|
142
|
+
let highlighter: Highlighter | null = null;
|
|
143
|
+
let destroyed = false;
|
|
144
|
+
|
|
145
|
+
const cleanups: Array<() => void> = [];
|
|
146
|
+
|
|
147
|
+
function on<T extends EventTarget>(target: T | null, type: string, fn: EventListener) {
|
|
148
|
+
if (!target) return;
|
|
149
|
+
target.addEventListener(type, fn);
|
|
150
|
+
cleanups.push(() => target.removeEventListener(type, fn));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/* ---------------------------------------------------------------- rendering */
|
|
154
|
+
|
|
155
|
+
type State = "loading" | "no-audio" | "error" | "ready";
|
|
156
|
+
|
|
157
|
+
function setState(state: State) {
|
|
158
|
+
if (loadingEl) loadingEl.hidden = state !== "loading";
|
|
159
|
+
if (placeholderEl) placeholderEl.hidden = state !== "no-audio";
|
|
160
|
+
if (errorEl) errorEl.hidden = state !== "error";
|
|
161
|
+
controlsEl.hidden = state !== "ready";
|
|
162
|
+
root.setAttribute("data-player-state", state);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Events on the root, so a host can hook analytics without owning the markup.
|
|
167
|
+
* Nothing was emitted before, so there was no way in at all short of forking.
|
|
168
|
+
*/
|
|
169
|
+
function emit(name: string, detail?: unknown) {
|
|
170
|
+
root.dispatchEvent(
|
|
171
|
+
new CustomEvent(`vocasync:${name}`, { detail, bubbles: true, composed: true })
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function swapIcons(scope: Element | null, showFirst: string, hideFirst: string, on_: boolean) {
|
|
176
|
+
if (!scope) return;
|
|
177
|
+
scope.querySelector(showFirst)?.classList.toggle("vocasync-hidden", on_);
|
|
178
|
+
scope.querySelector(hideFirst)?.classList.toggle("vocasync-hidden", !on_);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function renderPlayState(playing: boolean) {
|
|
182
|
+
swapIcons(playBtn, ".vocasync-icon--play", ".vocasync-icon--pause", playing);
|
|
183
|
+
playBtn?.setAttribute("aria-label", playing ? strings.pause : strings.play);
|
|
184
|
+
miniPlayBtn?.setAttribute("aria-label", playing ? strings.pause : strings.play);
|
|
185
|
+
swapIcons(miniPlayBtn, ".vocasync-icon--play", ".vocasync-icon--pause", playing);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The shipped player passed `audio.volume === 0` when the slider moved and
|
|
190
|
+
* `audio.muted` when the button was clicked, so the two could disagree: drag to
|
|
191
|
+
* zero, mute, unmute, and the icon claimed sound was playing. Silence is silence.
|
|
192
|
+
*/
|
|
193
|
+
function renderVolume() {
|
|
194
|
+
const silent = audio.muted || audio.volume === 0;
|
|
195
|
+
swapIcons(muteBtn, ".vocasync-icon--volume-high", ".vocasync-icon--volume-mute", silent);
|
|
196
|
+
muteBtn?.setAttribute("aria-label", silent ? strings.unmute : strings.mute);
|
|
197
|
+
if (volumeInput) {
|
|
198
|
+
volumeInput.setAttribute("aria-valuetext", `${Math.round(audio.volume * 100)}%`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Reflect the current playback rate in the label, the menu selection and the
|
|
204
|
+
* announced state. Restoring a saved preference used to set the media element
|
|
205
|
+
* without touching any of this, so the controls claimed 1x while playing at 1.5x.
|
|
206
|
+
*/
|
|
207
|
+
function renderSpeed() {
|
|
208
|
+
const rate = audio.playbackRate;
|
|
209
|
+
if (speedLabel) speedLabel.textContent = formatString(strings.speedValue, { rate });
|
|
210
|
+
if (!speedMenu) return;
|
|
211
|
+
for (const step of Array.from(speedMenu.querySelectorAll(SPEED_STEP_SELECTOR))) {
|
|
212
|
+
const match = Number.parseFloat((step as HTMLElement).dataset.speed ?? "") === rate;
|
|
213
|
+
step.toggleAttribute("data-active", match);
|
|
214
|
+
step.setAttribute("aria-checked", match ? "true" : "false");
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function renderHighlightButton() {
|
|
219
|
+
if (!highlightBtn) return;
|
|
220
|
+
swapIcons(
|
|
221
|
+
highlightBtn,
|
|
222
|
+
".vocasync-icon--highlight-on",
|
|
223
|
+
".vocasync-icon--highlight-off",
|
|
224
|
+
!highlightingEnabled
|
|
225
|
+
);
|
|
226
|
+
highlightBtn.setAttribute("data-highlighting", highlightingEnabled ? "on" : "off");
|
|
227
|
+
highlightBtn.setAttribute(
|
|
228
|
+
"aria-label",
|
|
229
|
+
highlightingEnabled ? "Disable word highlighting" : "Enable word highlighting"
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The loaded-so-far range, exposed as a percentage the stylesheet paints behind the
|
|
235
|
+
* seek bar. Without it there is no way to tell a slow network from a broken one.
|
|
236
|
+
*/
|
|
237
|
+
function renderBuffered() {
|
|
238
|
+
if (!progressInput || !Number.isFinite(audio.duration) || audio.duration <= 0) return;
|
|
239
|
+
let end = 0;
|
|
240
|
+
for (let i = 0; i < audio.buffered.length; i++) {
|
|
241
|
+
if (audio.buffered.start(i) <= audio.currentTime) end = Math.max(end, audio.buffered.end(i));
|
|
242
|
+
}
|
|
243
|
+
const percent = Math.min(100, (end / audio.duration) * 100);
|
|
244
|
+
progressInput.style.setProperty("--vocasync-buffered", `${percent}%`);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function renderProgress() {
|
|
248
|
+
const t = audio.currentTime;
|
|
249
|
+
if (currentTimeEl) currentTimeEl.textContent = formatTime(t);
|
|
250
|
+
if (progressInput) {
|
|
251
|
+
progressInput.value = String(t);
|
|
252
|
+
// Without this a screen reader reads the raw seconds: "43".
|
|
253
|
+
progressInput.setAttribute(
|
|
254
|
+
"aria-valuetext",
|
|
255
|
+
formatString(strings.seekPosition, {
|
|
256
|
+
current: describeTime(t),
|
|
257
|
+
total: describeTime(audio.duration),
|
|
258
|
+
})
|
|
259
|
+
);
|
|
260
|
+
// Painted behind the bar by player.css, alongside the buffered range.
|
|
261
|
+
progressInput.style.setProperty(
|
|
262
|
+
"--vocasync-played",
|
|
263
|
+
audio.duration > 0 ? `${(t / audio.duration) * 100}%` : "0%"
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
if (miniTimeEl) miniTimeEl.textContent = formatTime(t);
|
|
267
|
+
if (miniProgressBar) {
|
|
268
|
+
const percent = audio.duration ? (t / audio.duration) * 100 : 0;
|
|
269
|
+
miniProgressBar.style.width = `${Number.isFinite(percent) ? percent : 0}%`;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/* -------------------------------------------------------------- highlighting */
|
|
274
|
+
|
|
275
|
+
function updateHighlighting() {
|
|
276
|
+
if (!highlightingEnabled) return;
|
|
277
|
+
highlighter?.update(audio.currentTime);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function tick() {
|
|
281
|
+
if (destroyed) return;
|
|
282
|
+
// Driving the progress readout from the animation loop as well as `timeupdate`
|
|
283
|
+
// makes the bar smooth; `timeupdate` alone fires about four times a second.
|
|
284
|
+
renderProgress();
|
|
285
|
+
updateHighlighting();
|
|
286
|
+
if (!audio.paused && !audio.ended) {
|
|
287
|
+
animationFrame = view.requestAnimationFrame(tick);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function startLoop() {
|
|
292
|
+
stopLoop();
|
|
293
|
+
animationFrame = view.requestAnimationFrame(tick);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function stopLoop() {
|
|
297
|
+
if (animationFrame !== null) view.cancelAnimationFrame(animationFrame);
|
|
298
|
+
animationFrame = null;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function toggleHighlighting() {
|
|
302
|
+
highlightingEnabled = !highlightingEnabled;
|
|
303
|
+
writePrefs(storage, { highlighting: highlightingEnabled });
|
|
304
|
+
renderHighlightButton();
|
|
305
|
+
if (!highlightingEnabled) {
|
|
306
|
+
highlighter?.clear();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
updateHighlighting();
|
|
310
|
+
if (!audio.paused && !audio.ended) startLoop();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/* ------------------------------------------------------------------ playback */
|
|
314
|
+
|
|
315
|
+
function play() {
|
|
316
|
+
// An unhandled rejection here is how an autoplay-policy block disappears
|
|
317
|
+
// silently; surface it instead.
|
|
318
|
+
const result = audio.play();
|
|
319
|
+
if (result && typeof result.catch === "function") {
|
|
320
|
+
result.catch((error: unknown) => {
|
|
321
|
+
if ((error as { name?: string })?.name === "NotAllowedError") return;
|
|
322
|
+
console.warn("[vocasync] Playback failed", error);
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function togglePlay() {
|
|
328
|
+
if (audio.paused) play();
|
|
329
|
+
else audio.pause();
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Publish to the OS media controls: lock screen, media keys, the notification
|
|
334
|
+
* shade. Entirely optional -- unsupported browsers simply have no navigator.
|
|
335
|
+
* mediaSession, and a failure here must never affect playback.
|
|
336
|
+
*/
|
|
337
|
+
function publishMediaSession() {
|
|
338
|
+
if (opts.mediaSession === false) return;
|
|
339
|
+
const session = (
|
|
340
|
+
view.navigator as unknown as {
|
|
341
|
+
mediaSession?: {
|
|
342
|
+
metadata: unknown;
|
|
343
|
+
setActionHandler(action: string, handler: (() => void) | null): void;
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
).mediaSession;
|
|
347
|
+
const MetadataCtor = (view as unknown as { MediaMetadata?: new (init: unknown) => unknown })
|
|
348
|
+
.MediaMetadata;
|
|
349
|
+
if (!session || !MetadataCtor) return;
|
|
350
|
+
try {
|
|
351
|
+
session.metadata = new MetadataCtor({
|
|
352
|
+
title: opts.title || strings.label,
|
|
353
|
+
artwork: opts.artwork ? [{ src: opts.artwork }] : undefined,
|
|
354
|
+
});
|
|
355
|
+
session.setActionHandler("play", () => play());
|
|
356
|
+
session.setActionHandler("pause", () => audio.pause());
|
|
357
|
+
session.setActionHandler("seekbackward", () => skip(-skipSeconds));
|
|
358
|
+
session.setActionHandler("seekforward", () => skip(skipSeconds));
|
|
359
|
+
} catch {
|
|
360
|
+
// Some browsers reject individual action handlers; metadata alone is fine.
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function skip(delta: number) {
|
|
365
|
+
const max = Number.isFinite(audio.duration) ? audio.duration : Number.POSITIVE_INFINITY;
|
|
366
|
+
audio.currentTime = Math.min(max, Math.max(0, audio.currentTime + delta));
|
|
367
|
+
renderProgress();
|
|
368
|
+
updateHighlighting();
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/* ---------------------------------------------------------------- mini player */
|
|
372
|
+
|
|
373
|
+
function setMiniVisible(visible: boolean) {
|
|
374
|
+
if (!miniEl || visible === miniVisible) return;
|
|
375
|
+
miniEl.hidden = !visible;
|
|
376
|
+
miniVisible = visible;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function setupMiniPlayer() {
|
|
380
|
+
if (!miniEnabled || !miniEl || typeof view.IntersectionObserver !== "function") return;
|
|
381
|
+
const observer = new view.IntersectionObserver(
|
|
382
|
+
(entries) => {
|
|
383
|
+
const [entry] = entries;
|
|
384
|
+
setMiniVisible(!entry.isIntersecting && isPlaying && !miniDismissed);
|
|
385
|
+
},
|
|
386
|
+
{ threshold: 0 }
|
|
387
|
+
);
|
|
388
|
+
observer.observe(root);
|
|
389
|
+
cleanups.push(() => observer.disconnect());
|
|
390
|
+
|
|
391
|
+
on(miniPlayBtn, "click", togglePlay);
|
|
392
|
+
on(miniCloseBtn, "click", () => {
|
|
393
|
+
miniDismissed = true;
|
|
394
|
+
setMiniVisible(false);
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/* ---------------------------------------------------------------------- init */
|
|
399
|
+
|
|
400
|
+
const audioConfig = config?.audio ?? null;
|
|
401
|
+
const src = resolveAudioSrc(audioConfig?.audioUrl, audioConfig?.publishableKey, doc.baseURI);
|
|
402
|
+
if (!audioConfig || !src) {
|
|
403
|
+
setState("no-audio");
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
setState("loading");
|
|
408
|
+
audio.src = src;
|
|
409
|
+
|
|
410
|
+
// Restore what the reader chose last time, before anything renders, so the controls
|
|
411
|
+
// never show one value and then visibly correct themselves.
|
|
412
|
+
const prefs = readPrefs(storage);
|
|
413
|
+
if (prefs.rate !== undefined) audio.playbackRate = prefs.rate;
|
|
414
|
+
if (prefs.volume !== undefined) audio.volume = prefs.volume;
|
|
415
|
+
if (prefs.muted !== undefined) audio.muted = prefs.muted;
|
|
416
|
+
if (prefs.highlighting !== undefined) highlightingEnabled = prefs.highlighting;
|
|
417
|
+
|
|
418
|
+
const instance: PlayerInstance & registry.RegisteredPlayer = {
|
|
419
|
+
root,
|
|
420
|
+
pause() {
|
|
421
|
+
if (!audio.paused) audio.pause();
|
|
422
|
+
},
|
|
423
|
+
destroy() {
|
|
424
|
+
if (destroyed) return;
|
|
425
|
+
destroyed = true;
|
|
426
|
+
stopLoop();
|
|
427
|
+
for (const fn of cleanups.splice(0)) fn();
|
|
428
|
+
highlighter?.destroy();
|
|
429
|
+
highlighter = null;
|
|
430
|
+
audio.pause();
|
|
431
|
+
audio.removeAttribute("src");
|
|
432
|
+
root.removeAttribute("data-vocasync-ready");
|
|
433
|
+
registry.unregister(instance);
|
|
434
|
+
},
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
/* ------------------------------------------------------------------ listeners */
|
|
438
|
+
|
|
439
|
+
on(playBtn, "click", togglePlay);
|
|
440
|
+
on(highlightBtn, "click", toggleHighlighting);
|
|
441
|
+
on(controlsEl.querySelector('[data-action="skip-back"]'), "click", () => skip(-skipSeconds));
|
|
442
|
+
on(controlsEl.querySelector('[data-action="skip-forward"]'), "click", () => skip(skipSeconds));
|
|
443
|
+
|
|
444
|
+
on(audio, "play", () => {
|
|
445
|
+
isPlaying = true;
|
|
446
|
+
miniDismissed = false;
|
|
447
|
+
if (exclusive) registry.pauseOthers(instance);
|
|
448
|
+
renderPlayState(true);
|
|
449
|
+
startLoop();
|
|
450
|
+
emit("play");
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
on(audio, "pause", () => {
|
|
454
|
+
isPlaying = false;
|
|
455
|
+
renderPlayState(false);
|
|
456
|
+
stopLoop();
|
|
457
|
+
setMiniVisible(false);
|
|
458
|
+
emit("pause");
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
on(audio, "ended", () => {
|
|
462
|
+
isPlaying = false;
|
|
463
|
+
renderPlayState(false);
|
|
464
|
+
stopLoop();
|
|
465
|
+
// A finished article should reopen at the beginning, not at its last second.
|
|
466
|
+
clearPosition(positionStore, slug);
|
|
467
|
+
emit("ended");
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
on(audio, "seeking", updateHighlighting);
|
|
471
|
+
on(audio, "seeked", () => {
|
|
472
|
+
updateHighlighting();
|
|
473
|
+
renderProgress();
|
|
474
|
+
if (!audio.paused && !audio.ended) startLoop();
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
// The shipped player never listened for `error`, so an expired publishable key or a
|
|
478
|
+
// 404 left the controls visible and permanently dead with no message anywhere.
|
|
479
|
+
on(audio, "error", () => {
|
|
480
|
+
stopLoop();
|
|
481
|
+
highlighter?.clear();
|
|
482
|
+
setState("error");
|
|
483
|
+
emit("error", { src: audio.currentSrc || audio.src });
|
|
484
|
+
});
|
|
485
|
+
|
|
486
|
+
on(retryBtn, "click", () => {
|
|
487
|
+
setState("loading");
|
|
488
|
+
// Re-assigning the same src is not enough; the element caches the failure.
|
|
489
|
+
audio.removeAttribute("src");
|
|
490
|
+
audio.load();
|
|
491
|
+
audio.src = src;
|
|
492
|
+
audio.load();
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
on(audio, "loadedmetadata", () => {
|
|
496
|
+
if (durationTimeEl) durationTimeEl.textContent = formatTime(audio.duration);
|
|
497
|
+
if (progressInput && Number.isFinite(audio.duration)) {
|
|
498
|
+
progressInput.max = String(audio.duration);
|
|
499
|
+
}
|
|
500
|
+
const resume = resumePoint(readPosition(positionStore, slug), audio.duration);
|
|
501
|
+
if (resume !== null) audio.currentTime = resume;
|
|
502
|
+
renderProgress();
|
|
503
|
+
renderBuffered();
|
|
504
|
+
setState("ready");
|
|
505
|
+
publishMediaSession();
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
on(audio, "progress", renderBuffered);
|
|
509
|
+
|
|
510
|
+
// Distinguish "still loading" from "broken". Previously a stalled request left the
|
|
511
|
+
// controls looking interactive with no feedback at all.
|
|
512
|
+
on(audio, "waiting", () => root.setAttribute("data-player-buffering", ""));
|
|
513
|
+
on(audio, "stalled", () => root.setAttribute("data-player-buffering", ""));
|
|
514
|
+
on(audio, "playing", () => root.removeAttribute("data-player-buffering"));
|
|
515
|
+
on(audio, "canplay", () => root.removeAttribute("data-player-buffering"));
|
|
516
|
+
|
|
517
|
+
on(audio, "canplay", () => setState("ready"));
|
|
518
|
+
on(audio, "timeupdate", () => {
|
|
519
|
+
renderProgress();
|
|
520
|
+
if (positionStore && !audio.paused) writePosition(positionStore, slug, audio.currentTime);
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
on(progressInput, "input", () => {
|
|
524
|
+
if (!progressInput) return;
|
|
525
|
+
const next = Number.parseFloat(progressInput.value);
|
|
526
|
+
if (Number.isFinite(next)) audio.currentTime = next;
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
on(volumeInput, "input", () => {
|
|
530
|
+
if (!volumeInput) return;
|
|
531
|
+
const next = Number.parseFloat(volumeInput.value);
|
|
532
|
+
if (Number.isFinite(next)) audio.volume = Math.min(1, Math.max(0, next / 100));
|
|
533
|
+
renderVolume();
|
|
534
|
+
writePrefs(storage, { volume: audio.volume });
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
on(muteBtn, "click", () => {
|
|
538
|
+
audio.muted = !audio.muted;
|
|
539
|
+
renderVolume();
|
|
540
|
+
writePrefs(storage, { muted: audio.muted });
|
|
541
|
+
});
|
|
542
|
+
|
|
543
|
+
function speedItems(): HTMLElement[] {
|
|
544
|
+
return speedMenu
|
|
545
|
+
? (Array.from(speedMenu.querySelectorAll(SPEED_STEP_SELECTOR)) as HTMLElement[])
|
|
546
|
+
: [];
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function openSpeedMenu(focusIndex: number | null = null) {
|
|
550
|
+
if (!speedMenu) return;
|
|
551
|
+
speedMenu.hidden = false;
|
|
552
|
+
speedBtn?.setAttribute("aria-expanded", "true");
|
|
553
|
+
const items = speedItems();
|
|
554
|
+
const active = items.findIndex((i) => i.hasAttribute("data-active"));
|
|
555
|
+
items[focusIndex ?? (active === -1 ? 0 : active)]?.focus();
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function closeSpeedMenu(returnFocus = false) {
|
|
559
|
+
if (!speedMenu || speedMenu.hidden) return;
|
|
560
|
+
speedMenu.hidden = true;
|
|
561
|
+
speedBtn?.setAttribute("aria-expanded", "false");
|
|
562
|
+
if (returnFocus) speedBtn?.focus();
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
on(speedBtn, "click", () => {
|
|
566
|
+
if (!speedMenu) return;
|
|
567
|
+
if (speedMenu.hidden) openSpeedMenu();
|
|
568
|
+
else closeSpeedMenu();
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
// A menu you can open but not navigate is only half a menu.
|
|
572
|
+
on(speedMenu, "keydown", (event) => {
|
|
573
|
+
const e = event as KeyboardEvent;
|
|
574
|
+
const items = speedItems();
|
|
575
|
+
const index = items.indexOf(e.target as HTMLElement);
|
|
576
|
+
if (index === -1) return;
|
|
577
|
+
switch (e.key) {
|
|
578
|
+
case "ArrowDown":
|
|
579
|
+
e.preventDefault();
|
|
580
|
+
items[(index + 1) % items.length]?.focus();
|
|
581
|
+
break;
|
|
582
|
+
case "ArrowUp":
|
|
583
|
+
e.preventDefault();
|
|
584
|
+
items[(index - 1 + items.length) % items.length]?.focus();
|
|
585
|
+
break;
|
|
586
|
+
case "Home":
|
|
587
|
+
e.preventDefault();
|
|
588
|
+
items[0]?.focus();
|
|
589
|
+
break;
|
|
590
|
+
case "End":
|
|
591
|
+
e.preventDefault();
|
|
592
|
+
items[items.length - 1]?.focus();
|
|
593
|
+
break;
|
|
594
|
+
case "Escape":
|
|
595
|
+
e.preventDefault();
|
|
596
|
+
e.stopPropagation();
|
|
597
|
+
closeSpeedMenu(true);
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
on(speedMenu, "click", (event) => {
|
|
603
|
+
const btn = (event.target as Element | null)?.closest?.(
|
|
604
|
+
SPEED_STEP_SELECTOR
|
|
605
|
+
) as HTMLElement | null;
|
|
606
|
+
if (!btn || !speedMenu) return;
|
|
607
|
+
const speed = Number.parseFloat(btn.dataset.speed ?? "");
|
|
608
|
+
if (!Number.isFinite(speed)) return;
|
|
609
|
+
audio.playbackRate = speed;
|
|
610
|
+
renderSpeed();
|
|
611
|
+
closeSpeedMenu(true);
|
|
612
|
+
writePrefs(storage, { rate: speed });
|
|
613
|
+
emit("ratechange", { rate: speed });
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
on(root, "keydown", (event) => {
|
|
617
|
+
const e = event as KeyboardEvent;
|
|
618
|
+
// Range inputs handle their own arrow keys; do not fight them.
|
|
619
|
+
if ((e.target as HTMLElement | null)?.tagName === "INPUT") return;
|
|
620
|
+
switch (e.code) {
|
|
621
|
+
case "Space":
|
|
622
|
+
e.preventDefault();
|
|
623
|
+
togglePlay();
|
|
624
|
+
break;
|
|
625
|
+
case "ArrowLeft":
|
|
626
|
+
e.preventDefault();
|
|
627
|
+
skip(-skipSeconds);
|
|
628
|
+
break;
|
|
629
|
+
case "ArrowRight":
|
|
630
|
+
e.preventDefault();
|
|
631
|
+
skip(skipSeconds);
|
|
632
|
+
break;
|
|
633
|
+
case "KeyM":
|
|
634
|
+
e.preventDefault();
|
|
635
|
+
audio.muted = !audio.muted;
|
|
636
|
+
renderVolume();
|
|
637
|
+
writePrefs(storage, { muted: audio.muted });
|
|
638
|
+
break;
|
|
639
|
+
case "KeyH":
|
|
640
|
+
e.preventDefault();
|
|
641
|
+
toggleHighlighting();
|
|
642
|
+
break;
|
|
643
|
+
case "Escape":
|
|
644
|
+
if (speedMenu && !speedMenu.hidden) {
|
|
645
|
+
e.preventDefault();
|
|
646
|
+
closeSpeedMenu(true);
|
|
647
|
+
}
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
/* --------------------------------------------------------- highlighting setup */
|
|
653
|
+
|
|
654
|
+
function initHighlighting() {
|
|
655
|
+
if (destroyed) return;
|
|
656
|
+
const words = Array.isArray(audioConfig?.words) ? audioConfig.words : [];
|
|
657
|
+
if (!words.length) return;
|
|
658
|
+
|
|
659
|
+
const articleRoot = doc.querySelector(articleSelector);
|
|
660
|
+
if (!articleRoot) return;
|
|
661
|
+
|
|
662
|
+
highlighter = createHighlighter({
|
|
663
|
+
articleRoot,
|
|
664
|
+
words,
|
|
665
|
+
trailLength: Number.isFinite(trailLength) ? trailLength : 4,
|
|
666
|
+
autoScroll: autoScrollEnabled,
|
|
667
|
+
prefersReducedMotion: () =>
|
|
668
|
+
view.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches ?? false,
|
|
669
|
+
onWordChange: (el) =>
|
|
670
|
+
emit("wordchange", el ? { index: Number.parseInt(el.dataset.i ?? "", 10), el } : null),
|
|
671
|
+
});
|
|
672
|
+
|
|
673
|
+
if (clickToSeekEnabled) {
|
|
674
|
+
const unregister = registerSeekRoot(articleRoot, (dataI) => {
|
|
675
|
+
const start = highlighter?.startOfToken(dataI);
|
|
676
|
+
if (start === null || start === undefined) return;
|
|
677
|
+
audio.currentTime = start;
|
|
678
|
+
if (audio.paused) play();
|
|
679
|
+
});
|
|
680
|
+
cleanups.push(unregister);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// The article body renders after the player in the document, so its spans may not
|
|
685
|
+
// exist yet when the module script runs.
|
|
686
|
+
if (doc.readyState === "loading") {
|
|
687
|
+
on(doc, "DOMContentLoaded", initHighlighting);
|
|
688
|
+
} else {
|
|
689
|
+
initHighlighting();
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// Following the spoken word is helpful until the reader scrolls somewhere else, at
|
|
693
|
+
// which point continuing to drag them back is hostile. Resume when playback moves on
|
|
694
|
+
// to a new paragraph rather than fighting for the scroll position.
|
|
695
|
+
if (autoScrollEnabled) {
|
|
696
|
+
let suspendUntil = 0;
|
|
697
|
+
on(view, "wheel", () => {
|
|
698
|
+
suspendUntil = Date.now() + 4000;
|
|
699
|
+
highlighter?.setAutoScroll(false);
|
|
700
|
+
});
|
|
701
|
+
on(view, "touchmove", () => {
|
|
702
|
+
suspendUntil = Date.now() + 4000;
|
|
703
|
+
highlighter?.setAutoScroll(false);
|
|
704
|
+
});
|
|
705
|
+
const resume = view.setInterval(() => {
|
|
706
|
+
if (suspendUntil && Date.now() > suspendUntil) {
|
|
707
|
+
suspendUntil = 0;
|
|
708
|
+
highlighter?.setAutoScroll(true);
|
|
709
|
+
}
|
|
710
|
+
}, 1000);
|
|
711
|
+
cleanups.push(() => view.clearInterval(resume));
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
setupMiniPlayer();
|
|
715
|
+
renderHighlightButton();
|
|
716
|
+
renderSpeed();
|
|
717
|
+
if (volumeInput) volumeInput.value = String(Math.round(audio.volume * 100));
|
|
718
|
+
renderVolume();
|
|
719
|
+
setState("ready");
|
|
720
|
+
emit("ready");
|
|
721
|
+
registry.register(instance);
|
|
722
|
+
root.setAttribute("data-vocasync-ready", "");
|
|
723
|
+
|
|
724
|
+
return instance;
|
|
725
|
+
}
|