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