@scalemule/nextjs 0.1.60 → 0.1.61

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 (41) hide show
  1. package/package.json +2 -2
  2. package/dist/audio.css +0 -857
  3. package/dist/audio.d.mts +0 -334
  4. package/dist/audio.d.ts +0 -334
  5. package/dist/audio.js +0 -2178
  6. package/dist/audio.mjs +0 -2156
  7. package/dist/client.d.mts +0 -240
  8. package/dist/client.d.ts +0 -240
  9. package/dist/client.js +0 -938
  10. package/dist/client.mjs +0 -935
  11. package/dist/index-CEi5Nd4L.d.mts +0 -980
  12. package/dist/index-CEi5Nd4L.d.ts +0 -980
  13. package/dist/index.d.mts +0 -1306
  14. package/dist/index.d.ts +0 -1306
  15. package/dist/index.js +0 -5991
  16. package/dist/index.mjs +0 -5928
  17. package/dist/ledvery-CxPzZpxP.d.mts +0 -44
  18. package/dist/ledvery-CxPzZpxP.d.ts +0 -44
  19. package/dist/listening-hub.global.js +0 -1
  20. package/dist/server/auth.d.mts +0 -43
  21. package/dist/server/auth.d.ts +0 -43
  22. package/dist/server/auth.js +0 -1988
  23. package/dist/server/auth.mjs +0 -1982
  24. package/dist/server/index.d.mts +0 -1302
  25. package/dist/server/index.d.ts +0 -1302
  26. package/dist/server/index.js +0 -3633
  27. package/dist/server/index.mjs +0 -3554
  28. package/dist/server/ledvery.d.mts +0 -1
  29. package/dist/server/ledvery.d.ts +0 -1
  30. package/dist/server/ledvery.js +0 -336
  31. package/dist/server/ledvery.mjs +0 -333
  32. package/dist/server/webhook-handler.d.mts +0 -3
  33. package/dist/server/webhook-handler.d.ts +0 -3
  34. package/dist/server/webhook-handler.js +0 -59
  35. package/dist/server/webhook-handler.mjs +0 -57
  36. package/dist/testing.d.mts +0 -109
  37. package/dist/testing.d.ts +0 -109
  38. package/dist/testing.js +0 -144
  39. package/dist/testing.mjs +0 -138
  40. package/dist/webhook-handler-B2GL4SDl.d.ts +0 -826
  41. package/dist/webhook-handler-D--VG8bN.d.mts +0 -826
package/dist/audio.js DELETED
@@ -1,2178 +0,0 @@
1
- 'use client';
2
- "use strict";
3
- "use client";
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
-
22
- // src/audio.ts
23
- var audio_exports = {};
24
- __export(audio_exports, {
25
- ArticleAudioControls: () => ArticleAudioControls,
26
- AudioPlayer: () => AudioPlayer,
27
- ListeningLibrary: () => ListeningLibrary,
28
- NarrationHighlighter: () => NarrationHighlighter,
29
- NetworkAudioController: () => NetworkAudioController,
30
- NetworkAudioPlayer: () => NetworkAudioPlayer,
31
- NetworkAudioProvider: () => NetworkAudioProvider,
32
- SENTENCE_HIGHLIGHT: () => SENTENCE_HIGHLIGHT,
33
- WORD_HIGHLIGHT: () => WORD_HIGHLIGHT,
34
- narrationHighlightSupported: () => narrationHighlightSupported,
35
- parseTimingsPayload: () => parseTimingsPayload,
36
- useArticleNarration: () => useArticleNarration,
37
- useNetworkAudio: () => useNetworkAudio
38
- });
39
- module.exports = __toCommonJS(audio_exports);
40
-
41
- // src/components/audio-player.tsx
42
- var import_react = require("react");
43
-
44
- // src/components/narration-highlight.ts
45
- var WORD_HIGHLIGHT = "sm-narration-word";
46
- var SENTENCE_HIGHLIGHT = "sm-narration-sentence";
47
- function normalizeWord(raw) {
48
- return raw.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "");
49
- }
50
- var SKIPPED_TAGS = /* @__PURE__ */ new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"]);
51
- function collectDomWords(root) {
52
- const doc = root.ownerDocument ?? root;
53
- const walker = doc.createTreeWalker(root, 4, {
54
- acceptNode(node) {
55
- const parent = node.parentElement;
56
- if (parent && SKIPPED_TAGS.has(parent.tagName)) return 2;
57
- return 1;
58
- }
59
- });
60
- const out = [];
61
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
62
- const text = node.data;
63
- const matcher = /\S+/g;
64
- for (let m = matcher.exec(text); m; m = matcher.exec(text)) {
65
- const norm = normalizeWord(m[0]);
66
- if (norm) {
67
- out.push({ node, start: m.index, end: m.index + m[0].length, norm });
68
- }
69
- }
70
- }
71
- return out;
72
- }
73
- function alignWords(timingNorms, domNorms, window2 = 6) {
74
- const out = new Array(timingNorms.length).fill(-1);
75
- let j = 0;
76
- for (let i = 0; i < timingNorms.length; i++) {
77
- const target = timingNorms[i];
78
- if (!target) continue;
79
- let found = -1;
80
- for (let k = j; k < Math.min(domNorms.length, j + window2); k++) {
81
- if (domNorms[k] === target) {
82
- found = k;
83
- break;
84
- }
85
- }
86
- if (found === -1) {
87
- continue;
88
- }
89
- out[i] = found;
90
- j = found + 1;
91
- }
92
- return out;
93
- }
94
- function wordIndexAt(words, timeMs) {
95
- let lo = 0;
96
- let hi = words.length - 1;
97
- let ans = -1;
98
- while (lo <= hi) {
99
- const mid = lo + hi >> 1;
100
- if (words[mid][1] <= timeMs) {
101
- ans = mid;
102
- lo = mid + 1;
103
- } else {
104
- hi = mid - 1;
105
- }
106
- }
107
- return ans;
108
- }
109
- function mergeLineBoxes(rects) {
110
- const lines = [];
111
- const sorted = rects.filter((r) => r.width > 0 && r.height > 0).sort((a, b) => a.top - b.top || a.left - b.left);
112
- for (const r of sorted) {
113
- const center = r.top + r.height / 2;
114
- const line = lines.find((l) => {
115
- const lc = l.top + l.height / 2;
116
- return Math.abs(lc - center) < Math.min(l.height, r.height) / 2;
117
- });
118
- if (!line) {
119
- lines.push({ ...r });
120
- continue;
121
- }
122
- const right = Math.max(line.left + line.width, r.left + r.width);
123
- const bottom = Math.max(line.top + line.height, r.top + r.height);
124
- line.left = Math.min(line.left, r.left);
125
- line.top = Math.min(line.top, r.top);
126
- line.width = right - line.left;
127
- line.height = bottom - line.top;
128
- }
129
- return lines;
130
- }
131
- function narrationHighlightSupported() {
132
- return typeof window !== "undefined" && typeof document !== "undefined" && typeof Range !== "undefined" && typeof Range.prototype.getClientRects === "function";
133
- }
134
- var PAD_X = 2;
135
- var PAD_Y = 1;
136
- var NarrationHighlighter = class {
137
- constructor(root, timings) {
138
- this.currentWord = -2;
139
- this.currentSentence = -2;
140
- this.follow = true;
141
- this.detachUserScroll = null;
142
- this.layer = null;
143
- this.sentenceLayer = null;
144
- this.wordLayer = null;
145
- this.restoreRootStyle = null;
146
- this.resizeObserver = null;
147
- this.onWindowResize = null;
148
- this.root = root;
149
- this.words = timings.words;
150
- const domWords = collectDomWords(root);
151
- const matches = alignWords(
152
- this.words.map((w) => normalizeWord(w[0])),
153
- domWords.map((w) => w.norm)
154
- );
155
- const doc = root.ownerDocument;
156
- this.ranges = matches.map((m) => {
157
- if (m === -1) return null;
158
- const w = domWords[m];
159
- try {
160
- const range = doc.createRange();
161
- range.setStart(w.node, w.start);
162
- range.setEnd(w.node, w.end);
163
- return range;
164
- } catch {
165
- return null;
166
- }
167
- });
168
- this.sentenceWords = /* @__PURE__ */ new Map();
169
- this.words.forEach((w, i) => {
170
- if (!this.ranges[i]) return;
171
- const list = this.sentenceWords.get(w[3]);
172
- if (list) list.push(i);
173
- else this.sentenceWords.set(w[3], [i]);
174
- });
175
- this.reducedMotion = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
176
- this.attachUserScroll(doc);
177
- }
178
- /** Fraction of narration words found in the article body. A low
179
- * ratio means the body diverged from the script; callers may prefer
180
- * to hide the toggle below ~0.5. */
181
- matchRatio() {
182
- if (this.ranges.length === 0) return 0;
183
- return this.ranges.filter(Boolean).length / this.ranges.length;
184
- }
185
- attachUserScroll(doc) {
186
- const stopFollowing = () => {
187
- this.follow = false;
188
- };
189
- const opts = { passive: true };
190
- doc.addEventListener("wheel", stopFollowing, opts);
191
- doc.addEventListener("touchmove", stopFollowing, opts);
192
- this.detachUserScroll = () => {
193
- doc.removeEventListener("wheel", stopFollowing, opts);
194
- doc.removeEventListener("touchmove", stopFollowing, opts);
195
- };
196
- }
197
- /** Re-engage auto-scroll (the reader pressed the toggle or sought). */
198
- resumeFollowing() {
199
- this.follow = true;
200
- this.currentSentence = -2;
201
- }
202
- /** Lazily creates the overlay layer behind the article text. */
203
- ensureLayer() {
204
- if (this.layer) return true;
205
- const root = this.root;
206
- const doc = root.ownerDocument;
207
- if (!doc || typeof root.style === "undefined") return false;
208
- const view = doc.defaultView;
209
- const computed = view?.getComputedStyle(root);
210
- const previous = { position: root.style.position, isolation: root.style.isolation };
211
- if (!computed || computed.position === "static") root.style.position = "relative";
212
- root.style.isolation = "isolate";
213
- this.restoreRootStyle = () => {
214
- root.style.position = previous.position;
215
- root.style.isolation = previous.isolation;
216
- };
217
- const make = () => {
218
- const el = doc.createElement("div");
219
- el.style.position = "absolute";
220
- el.style.inset = "0";
221
- el.style.pointerEvents = "none";
222
- return el;
223
- };
224
- this.layer = make();
225
- this.layer.setAttribute("aria-hidden", "true");
226
- this.layer.setAttribute("data-sm-narration-layer", "");
227
- this.layer.style.zIndex = "-1";
228
- this.sentenceLayer = make();
229
- this.wordLayer = make();
230
- this.layer.append(this.sentenceLayer, this.wordLayer);
231
- root.prepend(this.layer);
232
- if (typeof ResizeObserver !== "undefined") {
233
- this.resizeObserver = new ResizeObserver(() => this.repaint());
234
- this.resizeObserver.observe(root);
235
- }
236
- if (view) {
237
- this.onWindowResize = () => this.repaint();
238
- view.addEventListener("resize", this.onWindowResize, { passive: true });
239
- }
240
- return true;
241
- }
242
- /** Line boxes for the given word indexes, in layer coordinates. */
243
- boxesFor(wordIndexes) {
244
- const root = this.root;
245
- const origin = root.getBoundingClientRect();
246
- const rects = [];
247
- for (const i of wordIndexes) {
248
- const range = this.ranges[i];
249
- if (!range || typeof range.getClientRects !== "function") continue;
250
- for (const r of Array.from(range.getClientRects())) {
251
- rects.push({
252
- left: r.left - origin.left - root.clientLeft + root.scrollLeft,
253
- top: r.top - origin.top - root.clientTop + root.scrollTop,
254
- width: r.width,
255
- height: r.height
256
- });
257
- }
258
- }
259
- return mergeLineBoxes(rects);
260
- }
261
- paint(target, boxes, kind) {
262
- if (!target) return;
263
- const doc = target.ownerDocument;
264
- const color = kind === "word" ? "var(--sm-narration-word, rgba(36, 99, 70, 0.32))" : "var(--sm-narration-sentence, rgba(36, 99, 70, 0.12))";
265
- const nodes = boxes.map((b) => {
266
- const el = doc.createElement("div");
267
- el.setAttribute("data-sm-narration", kind);
268
- el.className = kind === "word" ? WORD_HIGHLIGHT : SENTENCE_HIGHLIGHT;
269
- el.style.position = "absolute";
270
- el.style.left = `${b.left - PAD_X}px`;
271
- el.style.top = `${b.top - PAD_Y}px`;
272
- el.style.width = `${b.width + PAD_X * 2}px`;
273
- el.style.height = `${b.height + PAD_Y * 2}px`;
274
- el.style.borderRadius = "4px";
275
- el.style.background = color;
276
- return el;
277
- });
278
- target.replaceChildren(...nodes);
279
- }
280
- /** Re-lays out the current highlight (after resize / reflow). */
281
- repaint() {
282
- if (this.currentWord < 0) return;
283
- const sentence = this.words[this.currentWord]?.[3];
284
- this.paint(this.sentenceLayer, this.boxesFor(this.sentenceWords.get(sentence) ?? []), "sentence");
285
- this.paint(this.wordLayer, this.boxesFor([this.currentWord]), "word");
286
- }
287
- update(timeMs) {
288
- if (!narrationHighlightSupported()) return;
289
- const idx = wordIndexAt(this.words, timeMs);
290
- if (idx === this.currentWord) return;
291
- this.currentWord = idx;
292
- if (idx < 0) {
293
- this.clear();
294
- return;
295
- }
296
- if (!this.ensureLayer()) return;
297
- this.paint(this.wordLayer, this.ranges[idx] ? this.boxesFor([idx]) : [], "word");
298
- const sentence = this.words[idx][3];
299
- if (sentence !== this.currentSentence) {
300
- this.currentSentence = sentence;
301
- const members = this.sentenceWords.get(sentence) ?? [];
302
- this.paint(this.sentenceLayer, this.boxesFor(members), "sentence");
303
- const first = members.length ? this.ranges[members[0]] : null;
304
- if (first) this.scrollTo(first);
305
- }
306
- }
307
- scrollTo(range) {
308
- if (!this.follow) return;
309
- try {
310
- const rect = range.getBoundingClientRect();
311
- const viewport = window.innerHeight || 0;
312
- if (rect.top < viewport * 0.15 || rect.bottom > viewport * 0.7) {
313
- const target = window.scrollY + rect.top - viewport * 0.3;
314
- window.scrollTo({ top: target, behavior: this.reducedMotion ? "auto" : "smooth" });
315
- }
316
- } catch {
317
- }
318
- }
319
- clear() {
320
- this.sentenceLayer?.replaceChildren();
321
- this.wordLayer?.replaceChildren();
322
- this.currentWord = -2;
323
- this.currentSentence = -2;
324
- }
325
- destroy() {
326
- this.clear();
327
- this.resizeObserver?.disconnect();
328
- this.resizeObserver = null;
329
- if (this.onWindowResize) {
330
- this.root.ownerDocument?.defaultView?.removeEventListener("resize", this.onWindowResize);
331
- this.onWindowResize = null;
332
- }
333
- this.layer?.remove();
334
- this.layer = this.sentenceLayer = this.wordLayer = null;
335
- this.restoreRootStyle?.();
336
- this.restoreRootStyle = null;
337
- this.detachUserScroll?.();
338
- this.detachUserScroll = null;
339
- }
340
- };
341
- function parseTimingsPayload(body) {
342
- const candidate = body?.timings ?? body?.data?.timings ?? body;
343
- const t = candidate;
344
- if (!t || t.version !== 1 || !Array.isArray(t.words) || t.words.length === 0) return null;
345
- const valid = t.words.every(
346
- (w) => Array.isArray(w) && w.length === 4 && typeof w[0] === "string" && typeof w[1] === "number" && typeof w[2] === "number" && typeof w[3] === "number"
347
- );
348
- return valid ? t : null;
349
- }
350
-
351
- // src/components/audio-player.tsx
352
- var import_jsx_runtime = require("react/jsx-runtime");
353
- var subscribeNever = () => () => {
354
- };
355
- var SPEEDS = [1, 1.25, 1.5, 2, 3];
356
- var PLAY_EVENT = "scalemule:audio:play";
357
- var HIGHLIGHT_PREF_KEY = "scalemule:audio:highlight";
358
- var positive = (n) => n != null && Number.isFinite(n) && n > 0 ? n : 0;
359
- var durationOf = (audio) => positive(audio.duration_ms) / 1e3;
360
- function time(seconds) {
361
- const s = Math.floor(positive(seconds));
362
- return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
363
- }
364
- function AudioPlayer(props) {
365
- if (!props.audio.url) return null;
366
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PlayerSession, { ...props }, props.audioKey ?? props.audio.url);
367
- }
368
- function PlayerSession({
369
- audio,
370
- variant = "waveform",
371
- label,
372
- className,
373
- style,
374
- preload = "none",
375
- onRefresh,
376
- onPlaybackError,
377
- playbackRateStorageKey = "scalemule:audio:playback-rate",
378
- exclusivePlayback = true,
379
- narration
380
- }) {
381
- const media = (0, import_react.useRef)(null);
382
- const alive = (0, import_react.useRef)(true);
383
- const request = (0, import_react.useRef)(null);
384
- const triedRefresh = (0, import_react.useRef)(false);
385
- const intent = (0, import_react.useRef)(false);
386
- const resume = (0, import_react.useRef)(null);
387
- const [source, setSource] = (0, import_react.useState)(audio);
388
- const [duration, setDuration] = (0, import_react.useState)(durationOf(audio));
389
- const [position, setPosition] = (0, import_react.useState)(0);
390
- const [speed, setSpeed] = (0, import_react.useState)(1);
391
- const [playing, setPlaying] = (0, import_react.useState)(false);
392
- const [pendingPlay, setPendingPlay] = (0, import_react.useState)(false);
393
- const [busy, setBusy] = (0, import_react.useState)(false);
394
- const [error, setError] = (0, import_react.useState)(null);
395
- const sliderId = (0, import_react.useId)();
396
- const labelId = (0, import_react.useId)();
397
- const rate = (0, import_react.useRef)(1);
398
- const highlightSupported = (0, import_react.useSyncExternalStore)(
399
- subscribeNever,
400
- narrationHighlightSupported,
401
- // The server can't detect support; render the toggle only after
402
- // hydration so server and client markup always match.
403
- () => false
404
- );
405
- const narrationOffered = !!narration && audio.has_word_timings !== false && highlightSupported;
406
- const [highlightOn, setHighlightOn] = (0, import_react.useState)(false);
407
- const [highlightBusy, setHighlightBusy] = (0, import_react.useState)(false);
408
- const highlighter = (0, import_react.useRef)(null);
409
- const highlightAbort = (0, import_react.useRef)(null);
410
- (0, import_react.useEffect)(() => {
411
- if (!narrationOffered) return;
412
- try {
413
- if (window.localStorage.getItem(HIGHLIGHT_PREF_KEY) === "1") {
414
- void enableHighlight(false);
415
- }
416
- } catch {
417
- }
418
- }, [narrationOffered]);
419
- (0, import_react.useEffect)(() => {
420
- return () => {
421
- highlightAbort.current?.abort();
422
- highlighter.current?.destroy();
423
- highlighter.current = null;
424
- };
425
- }, []);
426
- async function enableHighlight(persist) {
427
- if (!narration) return;
428
- if (persist) {
429
- try {
430
- window.localStorage.setItem(HIGHLIGHT_PREF_KEY, "1");
431
- } catch {
432
- }
433
- }
434
- if (highlighter.current) {
435
- highlighter.current.resumeFollowing();
436
- setHighlightOn(true);
437
- return;
438
- }
439
- if (highlightBusy) return;
440
- const controller = new AbortController();
441
- highlightAbort.current = controller;
442
- setHighlightBusy(true);
443
- try {
444
- const resp = await fetch(narration.timingsUrl, { signal: controller.signal });
445
- if (!resp.ok) throw new Error(`timings ${resp.status}`);
446
- const timings = parseTimingsPayload(await resp.json());
447
- const target = document.getElementById(narration.targetId);
448
- if (!timings || !target) throw new Error("timings or target missing");
449
- const instance = new NarrationHighlighter(target, timings);
450
- if (instance.matchRatio() < 0.5) {
451
- instance.destroy();
452
- throw new Error("article text does not match narration");
453
- }
454
- highlighter.current = instance;
455
- setHighlightOn(true);
456
- const element = media.current;
457
- if (element) instance.update(element.currentTime * 1e3);
458
- } catch {
459
- setHighlightOn(false);
460
- } finally {
461
- if (highlightAbort.current === controller) highlightAbort.current = null;
462
- setHighlightBusy(false);
463
- }
464
- }
465
- function disableHighlight() {
466
- try {
467
- window.localStorage.setItem(HIGHLIGHT_PREF_KEY, "0");
468
- } catch {
469
- }
470
- highlightAbort.current?.abort();
471
- highlighter.current?.clear();
472
- setHighlightOn(false);
473
- }
474
- (0, import_react.useEffect)(() => {
475
- if (!highlightOn || !highlighter.current) return;
476
- const element = media.current;
477
- if (!element) return;
478
- if (!playing) {
479
- highlighter.current.update(element.currentTime * 1e3);
480
- return;
481
- }
482
- let frame = 0;
483
- const tick = () => {
484
- highlighter.current?.update(element.currentTime * 1e3);
485
- frame = requestAnimationFrame(tick);
486
- };
487
- frame = requestAnimationFrame(tick);
488
- return () => cancelAnimationFrame(frame);
489
- }, [highlightOn, playing, position]);
490
- (0, import_react.useEffect)(() => {
491
- alive.current = true;
492
- const element = media.current;
493
- return () => {
494
- alive.current = false;
495
- intent.current = false;
496
- request.current?.abort();
497
- element?.pause();
498
- };
499
- }, []);
500
- (0, import_react.useEffect)(() => {
501
- request.current?.abort();
502
- request.current = null;
503
- setBusy(false);
504
- resume.current = media.current?.currentTime ?? 0;
505
- setSource(audio);
506
- setDuration(durationOf(audio));
507
- }, [audio.url, audio.expires_at, audio.duration_ms]);
508
- (0, import_react.useEffect)(() => {
509
- if (!playbackRateStorageKey) return;
510
- try {
511
- const saved = Number(window.localStorage.getItem(playbackRateStorageKey));
512
- if (SPEEDS.includes(saved)) {
513
- setSpeed(saved);
514
- rate.current = saved;
515
- }
516
- } catch {
517
- }
518
- }, [playbackRateStorageKey]);
519
- (0, import_react.useEffect)(() => {
520
- if (media.current) {
521
- media.current.playbackRate = speed;
522
- media.current.preservesPitch = true;
523
- }
524
- }, [speed, source.url]);
525
- (0, import_react.useEffect)(() => {
526
- if (!exclusivePlayback) return;
527
- const stop = (event) => {
528
- if (event.detail !== media.current) {
529
- intent.current = false;
530
- setPendingPlay(false);
531
- media.current?.pause();
532
- }
533
- };
534
- document.addEventListener(PLAY_EVENT, stop);
535
- return () => document.removeEventListener(PLAY_EVENT, stop);
536
- }, [exclusivePlayback]);
537
- function fail() {
538
- if (!alive.current) return;
539
- intent.current = false;
540
- setPendingPlay(false);
541
- setPlaying(false);
542
- setBusy(false);
543
- setError("Audio could not be played. Try again.");
544
- onPlaybackError?.();
545
- }
546
- async function play() {
547
- const element = media.current;
548
- if (!element || !intent.current) return;
549
- try {
550
- await element.play();
551
- } catch (e) {
552
- if (!alive.current || !intent.current) return;
553
- if (e.name === "NotAllowedError") {
554
- fail();
555
- return;
556
- }
557
- await recover();
558
- }
559
- }
560
- async function recover(manual = false) {
561
- if (!alive.current || request.current) return;
562
- if (!onRefresh || !manual && triedRefresh.current) {
563
- fail();
564
- return;
565
- }
566
- triedRefresh.current = true;
567
- const controller = new AbortController();
568
- request.current = controller;
569
- resume.current = media.current?.currentTime ?? position;
570
- setBusy(true);
571
- setError(null);
572
- try {
573
- const fresh = await onRefresh(controller.signal);
574
- if (!alive.current || controller.signal.aborted) return;
575
- if (!fresh.url) throw new Error("No audio URL");
576
- setDuration(durationOf(fresh) || duration);
577
- if (fresh.url === source.url) {
578
- media.current?.load();
579
- } else {
580
- setSource(fresh);
581
- }
582
- } catch {
583
- if (!controller.signal.aborted) fail();
584
- } finally {
585
- if (request.current === controller) {
586
- request.current = null;
587
- if (alive.current) setBusy(false);
588
- }
589
- }
590
- }
591
- function toggle() {
592
- if (intent.current || playing) {
593
- intent.current = false;
594
- setPendingPlay(false);
595
- media.current?.pause();
596
- return;
597
- }
598
- intent.current = true;
599
- setPendingPlay(true);
600
- triedRefresh.current = false;
601
- setError(null);
602
- if (exclusivePlayback)
603
- document.dispatchEvent(
604
- new CustomEvent(PLAY_EVENT, { detail: media.current })
605
- );
606
- if (request.current) return;
607
- const expiry = Date.parse(source.expires_at ?? "");
608
- if (onRefresh && Number.isFinite(expiry) && expiry - Date.now() <= 6e4) {
609
- void recover();
610
- } else {
611
- void play();
612
- }
613
- }
614
- function seek(value) {
615
- if (!media.current || !duration || !Number.isFinite(value)) return;
616
- const target = Math.max(0, Math.min(duration, value));
617
- try {
618
- media.current.currentTime = target;
619
- resume.current = target;
620
- setPosition(target);
621
- highlighter.current?.resumeFollowing();
622
- } catch {
623
- }
624
- }
625
- function changeSpeed() {
626
- const next = SPEEDS[(SPEEDS.indexOf(rate.current) + 1) % SPEEDS.length];
627
- rate.current = next;
628
- setSpeed(next);
629
- if (playbackRateStorageKey) {
630
- try {
631
- window.localStorage.setItem(playbackRateStorageKey, String(next));
632
- } catch {
633
- }
634
- }
635
- }
636
- const peaks = (0, import_react.useMemo)(() => {
637
- const input = source.waveform_peaks;
638
- if (!input?.length) return [];
639
- const count = Math.min(64, input.length);
640
- return Array.from({ length: count }, (_, i) => {
641
- const value = input[Math.floor(i * input.length / count)];
642
- return Number.isFinite(value) ? Math.min(1, Math.max(0.08, Math.abs(value))) : 0.08;
643
- });
644
- }, [source.waveform_peaks]);
645
- const mediaPreload = durationOf(source) > 0 ? preload : "metadata";
646
- const current = Math.min(positive(position), duration || Infinity);
647
- const progress = duration ? Math.max(0, Math.min(100, current / duration * 100)) : 0;
648
- const remaining = duration ? `${time((duration - current) / speed)} remaining` : "Duration available when played";
649
- const title = label ?? (source.ai_generated === false ? "Listen to narration" : "Listen to AI narration");
650
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
651
- "div",
652
- {
653
- className: `sm-audio sm-audio--${variant}${className ? ` ${className}` : ""}`,
654
- style,
655
- role: "group",
656
- "aria-labelledby": labelId,
657
- "data-audio-variant": variant,
658
- children: [
659
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
660
- "audio",
661
- {
662
- ref: media,
663
- src: source.url ?? void 0,
664
- preload: mediaPreload,
665
- onLoadedMetadata: (e) => {
666
- const element = e.currentTarget;
667
- const total = positive(element.duration) || durationOf(source);
668
- setDuration(total);
669
- element.playbackRate = rate.current;
670
- element.preservesPitch = true;
671
- if (resume.current != null) {
672
- try {
673
- element.currentTime = Math.min(
674
- resume.current,
675
- total || resume.current
676
- );
677
- } catch {
678
- }
679
- resume.current = null;
680
- }
681
- setPosition(positive(element.currentTime));
682
- if (intent.current) void play();
683
- },
684
- onDurationChange: (e) => {
685
- const d = positive(e.currentTarget.duration);
686
- if (d) setDuration(d);
687
- },
688
- onTimeUpdate: (e) => {
689
- if (e.currentTarget.readyState === 0 && resume.current != null) return;
690
- setPosition(positive(e.currentTarget.currentTime));
691
- },
692
- onPlay: () => {
693
- intent.current = true;
694
- setPlaying(true);
695
- setError(null);
696
- if (exclusivePlayback)
697
- document.dispatchEvent(
698
- new CustomEvent(PLAY_EVENT, { detail: media.current })
699
- );
700
- },
701
- onPause: () => setPlaying(false),
702
- onEnded: () => {
703
- intent.current = false;
704
- setPendingPlay(false);
705
- setPlaying(false);
706
- setPosition(duration);
707
- },
708
- onError: () => {
709
- if (intent.current) void recover();
710
- else if (!request.current) {
711
- setError("Audio is unavailable. Press play to retry.");
712
- }
713
- }
714
- }
715
- ),
716
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
717
- "button",
718
- {
719
- type: "button",
720
- className: "sm-audio__play",
721
- onClick: toggle,
722
- "aria-label": playing || busy && pendingPlay ? "Pause narration" : "Play narration",
723
- children: playing || busy && pendingPlay ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M6 4h4v16H6zm8 0h4v16h-4z" }) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M8 4v16l12-8z" }) })
724
- }
725
- ),
726
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "sm-audio__content", children: [
727
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "sm-audio__label", id: labelId, children: title }),
728
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "sm-audio__times", children: [
729
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
730
- time(current),
731
- " ",
732
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "sm-audio__elapsed", children: "elapsed" })
733
- ] }),
734
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: remaining })
735
- ] }),
736
- variant !== "inline" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
737
- "div",
738
- {
739
- className: "sm-audio__seek",
740
- style: { "--sm-audio-progress": `${progress}%` },
741
- children: [
742
- variant === "waveform" && peaks.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "sm-audio__waveform", "aria-hidden": "true", children: peaks.map((peak, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
743
- "span",
744
- {
745
- style: {
746
- height: `${peak * 100}%`,
747
- background: (i + 0.5) / peaks.length * 100 <= progress ? "var(--sm-audio-accent)" : "var(--sm-audio-wave)"
748
- }
749
- },
750
- i
751
- )) }),
752
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { className: "sm-audio__sr", htmlFor: sliderId, children: "Seek narration" }),
753
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
754
- "input",
755
- {
756
- id: sliderId,
757
- className: "sm-audio__range",
758
- type: "range",
759
- min: "0",
760
- max: duration || 1,
761
- step: "0.1",
762
- disabled: !duration,
763
- value: Math.min(current, duration || 1),
764
- "aria-valuetext": `${time(current)} elapsed; ${remaining}`,
765
- onChange: (e) => seek(Number(e.currentTarget.value))
766
- }
767
- )
768
- ]
769
- }
770
- )
771
- ] }),
772
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "sm-audio__actions", children: [
773
- narrationOffered && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
774
- "button",
775
- {
776
- type: "button",
777
- className: `sm-audio__highlight${highlightOn ? " sm-audio__highlight--on" : ""}`,
778
- "aria-pressed": highlightOn,
779
- disabled: highlightBusy,
780
- onClick: () => highlightOn ? disableHighlight() : void enableHighlight(true),
781
- "aria-label": highlightOn ? "Turn off follow-along highlighting" : "Highlight the text as it is read",
782
- title: highlightOn ? "Turn off follow-along highlighting" : "Highlight the text as it is read",
783
- children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M4 5h16v2.5H4zm0 5.75h16v2.5H4zM4 16.5h9v2.5H4z" }) })
784
- }
785
- ),
786
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
787
- "button",
788
- {
789
- type: "button",
790
- className: "sm-audio__speed",
791
- onClick: changeSpeed,
792
- "aria-label": `Change playback speed (current ${speed}\xD7)`,
793
- children: [
794
- speed,
795
- "\xD7"
796
- ]
797
- }
798
- )
799
- ] }),
800
- (busy || error) && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "sm-audio__status", role: "status", children: busy ? "Loading audio\u2026" : error })
801
- ]
802
- }
803
- );
804
- }
805
-
806
- // src/components/network-audio-player.tsx
807
- var import_react2 = require("react");
808
-
809
- // src/network-audio/controller.ts
810
- var EMPTY_SNAPSHOT = {
811
- queue: [],
812
- index: -1,
813
- position: 0,
814
- duration: 0,
815
- rate: 1,
816
- volume: 1,
817
- status: "idle",
818
- error: null,
819
- history: [],
820
- autoplayNext: true,
821
- allowRepeats: false,
822
- hidden: false,
823
- sessionMinutes: 0
824
- };
825
- var trackKey = (track) => JSON.stringify([track.publicationId, track.id]);
826
- var storyKey = (track) => JSON.stringify([track.storyId ?? trackKey(track), track.revision ?? ""]);
827
- var listeningRecord = (snapshot, track) => snapshot.history?.find((item) => storyKey(item.track) === storyKey(track));
828
- var finite = (n) => typeof n === "number" && Number.isFinite(n);
829
- function safeHttpUrl(value) {
830
- if (typeof value !== "string" || value.length > 4096) return false;
831
- try {
832
- const url = new URL(value);
833
- return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password;
834
- } catch {
835
- return false;
836
- }
837
- }
838
- function validTrack(value) {
839
- if (!value || typeof value !== "object") return false;
840
- const t = value;
841
- return [t.id, t.publicationId, t.title].every((v) => typeof v === "string" && v.length > 0 && v.length <= 1e3) && (t.publicationName === void 0 || typeof t.publicationName === "string" && t.publicationName.length <= 1e3) && safeHttpUrl(t.articleUrl) && [t.storyId, t.revision, t.section, t.publishedAt].every((v) => v === void 0 || typeof v === "string" && v.length <= 4096) && (t.durationSeconds === void 0 || finite(t.durationSeconds) && t.durationSeconds > 0 && t.durationSeconds <= 86400) && (t.automatic === void 0 || typeof t.automatic === "boolean");
842
- }
843
- var copyTrack = (t) => ({
844
- id: t.id,
845
- publicationId: t.publicationId,
846
- title: t.title,
847
- ...t.publicationName ? { publicationName: t.publicationName } : {},
848
- articleUrl: t.articleUrl,
849
- ...t.storyId ? { storyId: t.storyId } : {},
850
- ...t.revision ? { revision: t.revision } : {},
851
- ...t.durationSeconds ? { durationSeconds: t.durationSeconds } : {},
852
- ...t.section ? { section: t.section } : {},
853
- ...t.publishedAt ? { publishedAt: t.publishedAt } : {},
854
- ...t.automatic ? { automatic: true } : {}
855
- });
856
- function validSnapshot(value) {
857
- if (!value || typeof value !== "object") return false;
858
- const s = value;
859
- return Array.isArray(s.queue) && s.queue.length <= 100 && s.queue.every(validTrack) && new Set(s.queue.map(trackKey)).size === s.queue.length && Number.isInteger(s.index) && (s.queue.length ? s.index >= 0 && s.index < s.queue.length : s.index === -1) && finite(s.position) && s.position >= 0 && finite(s.duration) && s.duration >= 0 && finite(s.rate) && s.rate >= 0.5 && s.rate <= 3 && finite(s.volume) && s.volume >= 0 && s.volume <= 1 && ["idle", "loading", "playing", "paused", "error"].includes(s.status) && (s.history === void 0 || Array.isArray(s.history) && s.history.length <= 500 && s.history.every(validRecord)) && [s.autoplayNext, s.allowRepeats, s.hidden].every((v) => v === void 0 || typeof v === "boolean") && (s.historyClearedAt === void 0 || finite(s.historyClearedAt) && s.historyClearedAt >= 0 && s.historyClearedAt <= Date.now() + 6e4) && (s.settingsUpdatedAt === void 0 || finite(s.settingsUpdatedAt) && s.settingsUpdatedAt >= 0 && s.settingsUpdatedAt <= Date.now() + 6e4) && (s.sessionMinutes === void 0 || [0, 5, 10, 20].includes(s.sessionMinutes)) && (s.error === null || typeof s.error === "string" && s.error.length <= 1e3);
860
- }
861
- function validRecord(value) {
862
- if (!value || typeof value !== "object") return false;
863
- const r = value;
864
- return validTrack(r.track) && finite(r.position) && r.position >= 0 && finite(r.duration) && r.duration >= 0 && finite(r.updatedAt) && r.updatedAt >= 0 && r.updatedAt <= Date.now() + 6e4 && [r.completedAt, r.skippedAt].every((v) => v === void 0 || finite(v) && v > 0) && Array.isArray(r.ranges) && r.ranges.length <= 100 && r.ranges.every((v) => Array.isArray(v) && v.length === 2 && finite(v[0]) && finite(v[1]) && v[0] >= 0 && v[1] >= v[0] && v[1] <= r.duration + 1);
865
- }
866
- function mergeRanges(ranges) {
867
- const merged = [];
868
- for (const [start, end] of ranges.sort((a, b) => a[0] - b[0])) {
869
- const last = merged.at(-1);
870
- if (last && start <= last[1] + 0.1) last[1] = Math.max(last[1], end);
871
- else merged.push([start, end]);
872
- }
873
- return merged.slice(-100);
874
- }
875
- var NetworkAudioController = class {
876
- constructor(resolve) {
877
- this.resolve = resolve;
878
- this.snapshot = EMPTY_SNAPSHOT;
879
- this.listeners = /* @__PURE__ */ new Set();
880
- this.audio = null;
881
- this.cleanup = null;
882
- this.request = null;
883
- this.generation = 0;
884
- this.intent = false;
885
- this.source = null;
886
- this.refreshed = false;
887
- this.resumePosition = null;
888
- this.candidates = [];
889
- this.getSnapshot = () => this.snapshot;
890
- this.subscribe = (listener) => {
891
- this.listeners.add(listener);
892
- return () => {
893
- this.listeners.delete(listener);
894
- };
895
- };
896
- }
897
- mergeListeningMemory(memory) {
898
- this.patch({ rate: memory.rate, autoplayNext: memory.autoplayNext, allowRepeats: memory.allowRepeats, settingsUpdatedAt: memory.settingsUpdatedAt, historyClearedAt: memory.historyClearedAt, history: memory.history });
899
- if (this.audio) this.audio.playbackRate = memory.rate;
900
- }
901
- setResolver(resolve) {
902
- this.resolve = resolve;
903
- }
904
- patch(patch) {
905
- this.snapshot = { ...this.snapshot, ...patch };
906
- this.listeners.forEach((listener) => listener());
907
- }
908
- attach(audio) {
909
- this.detach();
910
- this.audio = audio;
911
- audio.preload = "metadata";
912
- audio.playbackRate = this.snapshot.rate;
913
- audio.volume = this.snapshot.volume;
914
- const on = (name, fn) => {
915
- audio.addEventListener(name, fn);
916
- return () => audio.removeEventListener(name, fn);
917
- };
918
- const off = [
919
- on("loadedmetadata", () => {
920
- const duration = finite(audio.duration) && audio.duration > 0 ? audio.duration : this.snapshot.duration;
921
- if (this.resumePosition !== null) {
922
- audio.currentTime = duration > 0 ? Math.min(this.resumePosition, duration) : this.resumePosition;
923
- this.resumePosition = null;
924
- }
925
- audio.playbackRate = this.snapshot.rate;
926
- this.patch({ duration, position: audio.currentTime });
927
- }),
928
- on("durationchange", () => {
929
- if (finite(audio.duration) && audio.duration > 0) this.patch({ duration: audio.duration });
930
- }),
931
- on("timeupdate", () => {
932
- if (this.resumePosition === null) {
933
- this.patch({ position: audio.currentTime });
934
- this.remember();
935
- }
936
- }),
937
- on("playing", () => {
938
- if (!this.intent) {
939
- audio.pause();
940
- return;
941
- }
942
- this.patch({ status: "playing", error: null });
943
- document.dispatchEvent(new CustomEvent("scalemule:audio:play", { detail: audio }));
944
- }),
945
- on("pause", () => {
946
- if (this.snapshot.status === "playing") this.patch({ status: "paused" });
947
- }),
948
- on("ended", () => {
949
- if (!this.intent) return;
950
- this.finish();
951
- }),
952
- on("error", () => {
953
- if (this.intent && !this.request) void this.recover();
954
- })
955
- ];
956
- const exclusive = (event) => {
957
- if (event.detail !== audio) this.pause();
958
- };
959
- document.addEventListener("scalemule:audio:play", exclusive);
960
- this.cleanup = () => {
961
- off.forEach((fn) => fn());
962
- document.removeEventListener("scalemule:audio:play", exclusive);
963
- };
964
- }
965
- detach() {
966
- this.generation++;
967
- this.intent = false;
968
- this.request?.abort();
969
- this.request = null;
970
- this.cleanup?.();
971
- this.cleanup = null;
972
- this.audio?.pause();
973
- this.audio?.removeAttribute("src");
974
- this.audio = null;
975
- this.source = null;
976
- }
977
- enqueue(track) {
978
- if (!validTrack(track)) throw new Error("A valid publication, article identity, title and HTTP(S) article URL are required.");
979
- this.patch({ hidden: false });
980
- const found = this.snapshot.queue.findIndex((t) => storyKey(t) === storyKey(track));
981
- if (found !== -1) return found;
982
- if (this.snapshot.queue.length >= 100) throw new Error("The listening queue holds up to 100 articles.");
983
- const queue = [...this.snapshot.queue];
984
- const protectCurrent = this.source !== null || this.snapshot.status === "loading" || this.snapshot.status === "playing";
985
- const automatic = queue.findIndex((item, i) => item.automatic && (protectCurrent ? i > this.snapshot.index : i >= this.snapshot.index));
986
- const at = !track.automatic && automatic >= 0 ? automatic : queue.length;
987
- queue.splice(at, 0, copyTrack(track));
988
- const initial = this.snapshot.index === -1 || !protectCurrent && at <= this.snapshot.index;
989
- const record = listeningRecord(this.snapshot, track);
990
- this.patch({
991
- queue,
992
- index: initial ? at : this.snapshot.index,
993
- ...initial ? { position: record?.completedAt ? 0 : record?.position ?? 0, duration: record?.duration ?? track.durationSeconds ?? 0 } : {}
994
- });
995
- return at;
996
- }
997
- playTrack(track) {
998
- const index = this.enqueue(track);
999
- if (index === this.snapshot.index) void this.play();
1000
- else this.select(index);
1001
- }
1002
- select(index) {
1003
- if (!Number.isInteger(index) || index < 0 || index >= this.snapshot.queue.length) return;
1004
- if (index === this.snapshot.index) {
1005
- void this.play();
1006
- return;
1007
- }
1008
- this.remember();
1009
- this.cancel();
1010
- this.source = null;
1011
- const record = listeningRecord(this.snapshot, this.snapshot.queue[index]);
1012
- this.patch({ index, position: record?.completedAt ? 0 : record?.position ?? 0, duration: record?.duration ?? 0, error: null, status: "paused", hidden: false });
1013
- void this.play();
1014
- }
1015
- remove(index) {
1016
- if (!Number.isInteger(index) || index < 0 || index >= this.snapshot.queue.length) return;
1017
- this.remember();
1018
- const wasPlaying = this.intent;
1019
- const current = this.snapshot.index;
1020
- const queue = this.snapshot.queue.filter((_, i) => i !== index);
1021
- if (index !== current) {
1022
- this.patch({ queue, index: index < current ? current - 1 : current });
1023
- return;
1024
- }
1025
- this.cancel();
1026
- this.source = null;
1027
- const nextIndex = queue.length ? Math.min(index, queue.length - 1) : -1;
1028
- const nextRecord = nextIndex >= 0 ? listeningRecord(this.snapshot, queue[nextIndex]) : void 0;
1029
- this.patch({ queue, index: nextIndex, position: nextRecord?.completedAt ? 0 : nextRecord?.position ?? 0, duration: nextRecord?.duration ?? 0, status: "paused", error: null });
1030
- if (wasPlaying && queue.length) void this.play();
1031
- }
1032
- cancel() {
1033
- this.intent = false;
1034
- this.generation++;
1035
- this.request?.abort();
1036
- this.request = null;
1037
- this.resumePosition = null;
1038
- this.audio?.pause();
1039
- }
1040
- pause() {
1041
- this.remember();
1042
- const pendingPosition = this.resumePosition;
1043
- this.cancel();
1044
- this.resumePosition = pendingPosition;
1045
- this.patch({ status: this.snapshot.queue.length ? "paused" : "idle" });
1046
- }
1047
- clear() {
1048
- this.remember();
1049
- this.cancel();
1050
- this.source = null;
1051
- this.audio?.removeAttribute("src");
1052
- this.patch({ ...this.snapshot, queue: [], index: -1, position: 0, duration: 0, status: "idle", error: null, hidden: false });
1053
- }
1054
- close() {
1055
- this.pause();
1056
- this.patch({ hidden: true });
1057
- }
1058
- setAutoplay(value) {
1059
- this.patch({ autoplayNext: value, settingsUpdatedAt: Date.now() });
1060
- }
1061
- setRepeats(value) {
1062
- this.patch({ allowRepeats: value, settingsUpdatedAt: Date.now() });
1063
- }
1064
- forgetHistory() {
1065
- this.patch({ history: [], historyClearedAt: Date.now() });
1066
- }
1067
- restart() {
1068
- this.seek(0);
1069
- void this.play();
1070
- }
1071
- skip() {
1072
- this.remember({ skippedAt: Date.now() });
1073
- this.remove(this.snapshot.index);
1074
- }
1075
- remember(extra = {}) {
1076
- const track = this.snapshot.queue[this.snapshot.index];
1077
- if (!track || !this.snapshot.duration) return;
1078
- const previous = listeningRecord(this.snapshot, track);
1079
- const ranges = [...previous?.ranges ?? []];
1080
- if (this.source && this.audio) for (let i = 0; i < this.audio.played.length; i++) ranges.push([this.audio.played.start(i), Math.min(this.snapshot.duration, this.audio.played.end(i))]);
1081
- const record = {
1082
- ...previous,
1083
- track: copyTrack(track),
1084
- position: this.snapshot.position,
1085
- duration: this.snapshot.duration,
1086
- ranges: mergeRanges(ranges),
1087
- updatedAt: Date.now(),
1088
- ...extra
1089
- };
1090
- this.patch({ history: [record, ...(this.snapshot.history ?? []).filter((item) => storyKey(item.track) !== storyKey(track))].slice(0, 500) });
1091
- }
1092
- finish() {
1093
- this.remember();
1094
- const track = this.snapshot.queue[this.snapshot.index];
1095
- const record = track && listeningRecord(this.snapshot, track);
1096
- const coverage = record?.ranges.reduce((sum, [start, end]) => sum + end - start, 0) ?? 0;
1097
- if (this.snapshot.duration > 0 && coverage >= this.snapshot.duration * 0.9) this.remember({ completedAt: Date.now(), position: this.snapshot.duration });
1098
- else {
1099
- this.patch({ position: 0 });
1100
- this.remember({ skippedAt: Date.now(), position: 0 });
1101
- }
1102
- const autoplay = this.snapshot.autoplayNext !== false;
1103
- this.intent = false;
1104
- this.remove(this.snapshot.index);
1105
- if (autoplay && this.snapshot.queue.length) void this.play();
1106
- }
1107
- setRecommendations(tracks) {
1108
- this.candidates = tracks.filter(validTrack).slice(0, 100);
1109
- }
1110
- /** Manual selections retain their order; recommendations are bounded and never replace them. */
1111
- catchUp(minutes = 10) {
1112
- if (![5, 10, 20].includes(minutes)) return;
1113
- const active = this.snapshot.queue[this.snapshot.index];
1114
- const manual = this.snapshot.queue.filter((item) => !item.automatic || item === active);
1115
- const queueKeys = new Set(manual.map(storyKey));
1116
- const eligible = this.candidates.filter((item) => !queueKeys.has(storyKey(item)));
1117
- const unheard = eligible.filter((item) => {
1118
- const record = listeningRecord(this.snapshot, item);
1119
- return !record?.completedAt && (!record?.skippedAt || Date.now() - record.skippedAt > 864e5);
1120
- });
1121
- const pool = unheard.length || !this.snapshot.allowRepeats ? unheard : eligible.filter((item) => !listeningRecord(this.snapshot, item)?.skippedAt || Date.now() - listeningRecord(this.snapshot, item).skippedAt > 864e5);
1122
- let budget = minutes * 60 - manual.reduce((sum, item) => sum + Math.max(0, (item.durationSeconds ?? 0) - (item === active ? this.snapshot.position : 0)) / this.snapshot.rate, 0);
1123
- const added = [];
1124
- let lastSection = active?.section;
1125
- const remaining = [...pool];
1126
- while (remaining.length && added.length + manual.length < 100) {
1127
- let at = remaining.findIndex((item2) => item2.section !== lastSection && (item2.durationSeconds ?? Infinity) / this.snapshot.rate <= budget);
1128
- if (at < 0) at = remaining.findIndex((item2) => (item2.durationSeconds ?? Infinity) / this.snapshot.rate <= budget);
1129
- if (at < 0) break;
1130
- const [item] = remaining.splice(at, 1);
1131
- if (queueKeys.has(storyKey(item))) continue;
1132
- queueKeys.add(storyKey(item));
1133
- added.push({ ...copyTrack(item), automatic: true });
1134
- budget -= item.durationSeconds / this.snapshot.rate;
1135
- lastSection = item.section;
1136
- }
1137
- const queue = [...manual, ...added];
1138
- const firstRecord = !active && queue[0] ? listeningRecord(this.snapshot, queue[0]) : void 0;
1139
- this.patch({ queue, index: active ? queue.findIndex((item) => trackKey(item) === trackKey(active)) : queue.length ? 0 : -1, hidden: false, sessionMinutes: minutes, ...!active ? { position: firstRecord?.completedAt ? 0 : firstRecord?.position ?? 0, duration: firstRecord?.duration ?? queue[0]?.durationSeconds ?? 0 } : {} });
1140
- }
1141
- seek(position) {
1142
- if (!finite(position)) return;
1143
- const value = Math.max(0, this.snapshot.duration ? Math.min(position, this.snapshot.duration) : position);
1144
- if (this.audio?.readyState && this.source) this.audio.currentTime = value;
1145
- else this.resumePosition = value;
1146
- this.patch({ position: value });
1147
- }
1148
- setRate(rate) {
1149
- if (!finite(rate) || rate < 0.5 || rate > 3) return;
1150
- if (this.audio) this.audio.playbackRate = rate;
1151
- this.patch({ rate, settingsUpdatedAt: Date.now() });
1152
- }
1153
- setVolume(volume) {
1154
- if (!finite(volume) || volume < 0 || volume > 1) return;
1155
- if (this.audio) this.audio.volume = volume;
1156
- this.patch({ volume });
1157
- }
1158
- restore(snapshot) {
1159
- if (!validSnapshot(snapshot)) return;
1160
- this.cancel();
1161
- this.source = null;
1162
- this.patch({
1163
- queue: snapshot.queue.map(copyTrack),
1164
- index: snapshot.index,
1165
- position: snapshot.position,
1166
- duration: snapshot.duration,
1167
- rate: snapshot.rate,
1168
- volume: snapshot.volume,
1169
- status: snapshot.queue.length ? "paused" : "idle",
1170
- error: null,
1171
- history: (snapshot.history ?? []).map((item) => ({
1172
- track: copyTrack(item.track),
1173
- position: item.position,
1174
- duration: item.duration,
1175
- ranges: item.ranges.map((range) => [...range]),
1176
- updatedAt: item.updatedAt,
1177
- ...item.completedAt ? { completedAt: item.completedAt } : {},
1178
- ...item.skippedAt ? { skippedAt: item.skippedAt } : {}
1179
- })),
1180
- autoplayNext: snapshot.autoplayNext !== false,
1181
- allowRepeats: snapshot.allowRepeats === true,
1182
- hidden: snapshot.hidden === true,
1183
- historyClearedAt: snapshot.historyClearedAt ?? 0,
1184
- settingsUpdatedAt: snapshot.settingsUpdatedAt ?? 0,
1185
- sessionMinutes: snapshot.sessionMinutes ?? 0
1186
- });
1187
- if (this.audio) {
1188
- this.audio.playbackRate = snapshot.rate;
1189
- this.audio.volume = snapshot.volume;
1190
- }
1191
- }
1192
- async play() {
1193
- if (!this.audio || !this.snapshot.queue[this.snapshot.index] || this.request) return;
1194
- this.intent = true;
1195
- this.refreshed = false;
1196
- this.patch({ error: null, hidden: false });
1197
- const expires = this.source?.expires_at ? Date.parse(this.source.expires_at) : Infinity;
1198
- if (!this.source || expires <= Date.now() + 3e4) await this.load();
1199
- else {
1200
- if (this.snapshot.duration && this.snapshot.position >= this.snapshot.duration) this.seek(0);
1201
- await this.start(this.generation);
1202
- }
1203
- }
1204
- async load() {
1205
- const track = this.snapshot.queue[this.snapshot.index];
1206
- if (!track || !this.audio) return;
1207
- const generation = ++this.generation;
1208
- const request = new AbortController();
1209
- this.request?.abort();
1210
- this.request = request;
1211
- this.patch({ status: "loading", error: null });
1212
- let timeout;
1213
- try {
1214
- const source = await Promise.race([
1215
- this.resolve(track, request.signal),
1216
- new Promise((_, reject) => {
1217
- timeout = setTimeout(() => {
1218
- request.abort();
1219
- reject(new Error("Audio request timed out"));
1220
- }, 15e3);
1221
- })
1222
- ]);
1223
- if (generation !== this.generation || request.signal.aborted || !this.audio) return;
1224
- if (!safeHttpUrl(source.url)) throw new Error("No playable audio source");
1225
- this.source = source;
1226
- this.resumePosition = this.snapshot.position;
1227
- this.audio.src = source.url;
1228
- this.audio.playbackRate = this.snapshot.rate;
1229
- this.audio.volume = this.snapshot.volume;
1230
- this.patch({ duration: source.duration_ms && source.duration_ms > 0 ? source.duration_ms / 1e3 : 0 });
1231
- this.request = null;
1232
- await this.start(generation);
1233
- } catch {
1234
- if (generation === this.generation) this.fail("This article could not be loaded. Try playing it again or choose another article.");
1235
- } finally {
1236
- clearTimeout(timeout);
1237
- if (this.request === request) this.request = null;
1238
- }
1239
- }
1240
- async start(generation) {
1241
- if (!this.intent || !this.audio) return;
1242
- try {
1243
- await this.audio.play();
1244
- } catch (error) {
1245
- if (generation !== this.generation || !this.intent) return;
1246
- if (error.name === "NotAllowedError") this.fail("Press Play here to continue listening.");
1247
- else await this.recover();
1248
- }
1249
- }
1250
- async recover() {
1251
- if (this.refreshed) {
1252
- this.fail("Audio playback stopped. Try playing again or choose another article.");
1253
- return;
1254
- }
1255
- this.refreshed = true;
1256
- await this.load();
1257
- }
1258
- fail(error) {
1259
- this.intent = false;
1260
- this.audio?.pause();
1261
- this.patch({ status: "error", error });
1262
- }
1263
- };
1264
-
1265
- // src/network-audio/bridge.ts
1266
- var PROTOCOL = "scalemule:network-audio:v1";
1267
- function runCommand(controller, command) {
1268
- if (!command || typeof command !== "object") return false;
1269
- const c = command;
1270
- switch (c.action) {
1271
- case "play":
1272
- void controller.play();
1273
- return true;
1274
- case "pause":
1275
- controller.pause();
1276
- return true;
1277
- case "clear":
1278
- case "close":
1279
- case "skip":
1280
- case "restart":
1281
- case "forgetHistory":
1282
- controller[c.action]();
1283
- return true;
1284
- case "autoplay":
1285
- case "repeats":
1286
- if (typeof c.value !== "boolean") return false;
1287
- if (c.action === "autoplay") controller.setAutoplay(c.value);
1288
- else controller.setRepeats(c.value);
1289
- return true;
1290
- case "catchUp":
1291
- controller.catchUp(c.value);
1292
- return true;
1293
- case "enqueue":
1294
- case "playTrack":
1295
- if (!validTrack(c.track)) return false;
1296
- controller[c.action](c.track);
1297
- return true;
1298
- case "select":
1299
- case "remove":
1300
- case "seek":
1301
- case "rate":
1302
- case "volume":
1303
- if (!Number.isFinite(c.value)) return false;
1304
- if (c.action === "rate") controller.setRate(c.value);
1305
- else if (c.action === "volume") controller.setVolume(c.value);
1306
- else controller[c.action](c.value);
1307
- return true;
1308
- default:
1309
- return false;
1310
- }
1311
- }
1312
- function hostNetworkPlayer(controller, options) {
1313
- const origins = new Set(options.allowedOrigins.map((value) => {
1314
- if (!safeHttpUrl(value) || new URL(value).origin !== value) throw new Error("Use exact HTTP(S) origins for the network player.");
1315
- return value;
1316
- }));
1317
- const reader = window.opener;
1318
- if (!reader) return () => {
1319
- };
1320
- const trackAllowed = (t) => origins.has(new URL(t.articleUrl).origin);
1321
- const send = () => {
1322
- if (reader.closed) return;
1323
- const data = { protocol: PROTOCOL, networkId: options.networkId, kind: "state", snapshot: controller.getSnapshot() };
1324
- origins.forEach((origin) => reader.postMessage(data, origin));
1325
- };
1326
- const receive = (event) => {
1327
- if (event.source !== reader || !origins.has(event.origin)) return;
1328
- const data = event.data;
1329
- if (!data || data.protocol !== PROTOCOL || data.networkId !== options.networkId) return;
1330
- try {
1331
- if (data.kind === "adopt" && validSnapshot(data.snapshot) && data.snapshot.queue.every(trackAllowed) && !controller.getSnapshot().queue.length) {
1332
- controller.restore(data.snapshot);
1333
- if (data.play === true) void controller.play();
1334
- } else if (data.kind === "command") {
1335
- const command = data.command;
1336
- if (command && (command.action === "enqueue" || command.action === "playTrack") && (!validTrack(command.track) || !trackAllowed(command.track))) return;
1337
- runCommand(controller, command);
1338
- }
1339
- } catch {
1340
- reader.postMessage({
1341
- protocol: PROTOCOL,
1342
- networkId: options.networkId,
1343
- kind: "error",
1344
- error: "The article could not be added. The queue holds up to 100 articles."
1345
- }, event.origin);
1346
- }
1347
- send();
1348
- };
1349
- window.addEventListener("message", receive);
1350
- const timer = window.setInterval(send, 250);
1351
- send();
1352
- return () => {
1353
- clearInterval(timer);
1354
- window.removeEventListener("message", receive);
1355
- };
1356
- }
1357
- var NetworkPlayerClient = class {
1358
- constructor(controller, options, update) {
1359
- this.controller = controller;
1360
- this.options = options;
1361
- this.update = update;
1362
- this.target = null;
1363
- this.connected = false;
1364
- this.pending = false;
1365
- this.handoffRequested = false;
1366
- this.openedAt = 0;
1367
- this.lastSeen = 0;
1368
- this.latest = null;
1369
- this.receive = (event) => {
1370
- if (event.origin !== this.origin || !event.source || this.target && event.source !== this.target) return;
1371
- const data = event.data;
1372
- if (!data || data.protocol !== PROTOCOL || data.networkId !== this.options.networkId) return;
1373
- if (data.kind === "error" && this.connected) {
1374
- this.update(this.latest, "The article could not be added. The queue holds up to 100 articles.");
1375
- return;
1376
- }
1377
- if (data.kind !== "state" || !validSnapshot(data.snapshot)) return;
1378
- this.target = event.source;
1379
- this.lastSeen = Date.now();
1380
- if (!this.connected) {
1381
- const local = this.controller.getSnapshot();
1382
- const handoff = this.handoffRequested && !data.snapshot.queue.length && local.queue.length > 0;
1383
- this.controller.pause();
1384
- this.connected = true;
1385
- this.pending = false;
1386
- this.handoffRequested = false;
1387
- if (handoff) this.post({ kind: "adopt", snapshot: local, play: local.status === "playing" || local.status === "loading" });
1388
- }
1389
- this.latest = data.snapshot;
1390
- this.update(data.snapshot, null);
1391
- };
1392
- if (!safeHttpUrl(options.playerUrl)) throw new Error("The network player needs a fully qualified HTTP(S) URL.");
1393
- this.origin = new URL(options.playerUrl).origin;
1394
- window.addEventListener("message", this.receive);
1395
- this.timer = window.setInterval(() => {
1396
- if (this.pending && Date.now() - this.openedAt > 1e4) {
1397
- this.pending = false;
1398
- this.update(null, "The network player did not connect. Playback is still on this page.");
1399
- }
1400
- if (this.connected && this.target?.closed) this.disconnect("The network player closed. Press Play to resume here.");
1401
- else if (this.connected && Date.now() - this.lastSeen > 5e3) {
1402
- this.update(this.latest, "Waiting for the network player. Open its window to check playback.");
1403
- }
1404
- }, 1e3);
1405
- }
1406
- post(data) {
1407
- this.target?.postMessage({ protocol: PROTOCOL, networkId: this.options.networkId, ...data }, this.origin);
1408
- }
1409
- open() {
1410
- if (this.target && !this.target.closed) {
1411
- this.target.focus();
1412
- return;
1413
- }
1414
- this.target = window.open(this.options.playerUrl, "_blank", "popup,width=520,height=720");
1415
- if (!this.target || this.target.closed) {
1416
- this.target = null;
1417
- this.update(null, "Allow the network player window to open, then try again. Playback is still on this page.");
1418
- return;
1419
- }
1420
- this.pending = true;
1421
- this.handoffRequested = true;
1422
- this.openedAt = Date.now();
1423
- }
1424
- command(command) {
1425
- if (this.connected && this.target?.closed) this.disconnect("The network player closed. Press Play to resume here.");
1426
- if (!this.connected || !this.target || this.target.closed) return false;
1427
- this.post({ kind: "command", command });
1428
- return true;
1429
- }
1430
- disconnect(notice) {
1431
- if (this.latest) this.controller.restore(this.latest);
1432
- this.connected = false;
1433
- this.handoffRequested = false;
1434
- this.target = null;
1435
- this.latest = null;
1436
- this.update(null, notice);
1437
- }
1438
- dispose() {
1439
- clearInterval(this.timer);
1440
- window.removeEventListener("message", this.receive);
1441
- }
1442
- };
1443
-
1444
- // src/network-audio/memory.ts
1445
- function validMemory(value) {
1446
- if (!value || typeof value !== "object") return false;
1447
- const v = value;
1448
- return v.version === 1 && Number.isFinite(v.rate) && v.rate >= 0.5 && v.rate <= 3 && typeof v.autoplayNext === "boolean" && typeof v.allowRepeats === "boolean" && Number.isFinite(v.historyClearedAt) && v.historyClearedAt >= 0 && v.historyClearedAt <= Date.now() + 6e4 && Number.isFinite(v.settingsUpdatedAt) && v.settingsUpdatedAt >= 0 && v.settingsUpdatedAt <= Date.now() + 6e4 && Array.isArray(v.history) && v.history.length <= 500 && v.history.every(validRecord);
1449
- }
1450
- function toMemory(snapshot) {
1451
- return {
1452
- version: 1,
1453
- rate: snapshot.rate,
1454
- autoplayNext: snapshot.autoplayNext !== false,
1455
- allowRepeats: snapshot.allowRepeats === true,
1456
- settingsUpdatedAt: snapshot.settingsUpdatedAt ?? 0,
1457
- historyClearedAt: snapshot.historyClearedAt ?? 0,
1458
- history: (snapshot.history ?? []).map((item) => ({ ...item, track: copyTrack(item.track) }))
1459
- };
1460
- }
1461
- function mergeMemory(local, remote) {
1462
- const historyClearedAt = Math.max(local.historyClearedAt, remote.historyClearedAt);
1463
- const records = /* @__PURE__ */ new Map();
1464
- for (const item of [...remote.history, ...local.history]) {
1465
- if (item.updatedAt <= historyClearedAt) continue;
1466
- const key = storyKey(item.track);
1467
- const previous = records.get(key);
1468
- if (!previous) records.set(key, item);
1469
- else {
1470
- const newest = item.updatedAt >= previous.updatedAt ? item : previous;
1471
- records.set(key, {
1472
- ...newest,
1473
- ranges: mergeRanges([...previous.ranges, ...item.ranges]).filter((range) => range[1] <= newest.duration + 1),
1474
- ...previous.completedAt || item.completedAt ? { completedAt: Math.max(previous.completedAt ?? 0, item.completedAt ?? 0) } : {}
1475
- });
1476
- }
1477
- }
1478
- return {
1479
- ...remote.settingsUpdatedAt > local.settingsUpdatedAt ? remote : local,
1480
- historyClearedAt,
1481
- history: [...records.values()].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 500)
1482
- };
1483
- }
1484
-
1485
- // src/network-audio/persistence.ts
1486
- function persistListening(controller, options) {
1487
- const allowed = new Set(options.allowedOrigins);
1488
- let ready = false;
1489
- let iframe = null;
1490
- let lastWrite = 0;
1491
- let lastHubWrite = 0;
1492
- let request = 0;
1493
- const hubOrigin = options.hubUrl ? new URL(options.hubUrl).origin : null;
1494
- try {
1495
- const saved = JSON.parse(localStorage.getItem(options.storageKey) ?? "null");
1496
- if (validSnapshot(saved) && saved.queue.every((item) => allowed.has(new URL(item.articleUrl).origin))) controller.restore(options.restoreQueue === false ? { ...saved, queue: [], index: -1, position: 0, duration: 0, hidden: false } : saved);
1497
- } catch {
1498
- }
1499
- const url = new URL(window.location.href);
1500
- const rate = Number(url.searchParams.get("sm_audio_rate"));
1501
- if (url.searchParams.has("sm_audio_rate")) {
1502
- if (rate >= 0.5 && rate <= 3) controller.setRate(rate);
1503
- url.searchParams.delete("sm_audio_rate");
1504
- window.history.replaceState(window.history.state, "", url);
1505
- }
1506
- const sync = () => {
1507
- if (!ready || !iframe?.contentWindow || !hubOrigin) return;
1508
- iframe.contentWindow.postMessage({
1509
- type: "SM_LISTENING_SYNC",
1510
- networkId: options.networkId,
1511
- requestId: String(++request),
1512
- memory: toMemory(controller.getSnapshot())
1513
- }, hubOrigin);
1514
- };
1515
- const save = () => {
1516
- try {
1517
- localStorage.setItem(options.storageKey, JSON.stringify(controller.getSnapshot()));
1518
- } catch {
1519
- }
1520
- };
1521
- let previousQueue = controller.getSnapshot().queue;
1522
- let previousCompleted = controller.getSnapshot().history?.[0]?.completedAt;
1523
- let previousHidden = controller.getSnapshot().hidden;
1524
- let previousClear = controller.getSnapshot().historyClearedAt;
1525
- let previousSettings = controller.getSnapshot().settingsUpdatedAt;
1526
- const unsubscribe = controller.subscribe(() => {
1527
- const changed = previousSettings !== controller.getSnapshot().settingsUpdatedAt || previousClear !== controller.getSnapshot().historyClearedAt;
1528
- const urgent = changed || previousQueue !== controller.getSnapshot().queue || previousCompleted !== controller.getSnapshot().history?.[0]?.completedAt || previousHidden !== controller.getSnapshot().hidden;
1529
- previousQueue = controller.getSnapshot().queue;
1530
- previousCompleted = controller.getSnapshot().history?.[0]?.completedAt;
1531
- previousHidden = controller.getSnapshot().hidden;
1532
- previousClear = controller.getSnapshot().historyClearedAt;
1533
- previousSettings = controller.getSnapshot().settingsUpdatedAt;
1534
- if (urgent || Date.now() - lastWrite > 1e3) {
1535
- lastWrite = Date.now();
1536
- save();
1537
- }
1538
- if (urgent || Date.now() - lastHubWrite > 5e3) {
1539
- lastHubWrite = Date.now();
1540
- sync();
1541
- }
1542
- });
1543
- const receive = (event) => {
1544
- if (!iframe || event.source !== iframe.contentWindow || event.origin !== hubOrigin) return;
1545
- const data = event.data;
1546
- if (data?.type !== "SM_LISTENING_STATE" || data.networkId !== options.networkId || data.requestId !== String(request) || !validMemory(data.memory)) return;
1547
- if (!data.memory.history.every((item) => allowed.has(new URL(item.track.articleUrl).origin))) return;
1548
- controller.mergeListeningMemory(mergeMemory(toMemory(controller.getSnapshot()), data.memory));
1549
- };
1550
- window.addEventListener("message", receive);
1551
- if (options.hubUrl && hubOrigin && allowed.has(hubOrigin)) {
1552
- iframe = document.createElement("iframe");
1553
- iframe.src = options.hubUrl;
1554
- iframe.hidden = true;
1555
- iframe.title = "Shared listening preferences";
1556
- iframe.setAttribute("aria-hidden", "true");
1557
- iframe.onload = () => {
1558
- ready = true;
1559
- sync();
1560
- };
1561
- document.body.appendChild(iframe);
1562
- }
1563
- const decorate = (event) => {
1564
- const anchor = event.target instanceof Element ? event.target.closest("a[href]") : null;
1565
- if (!(anchor instanceof HTMLAnchorElement)) return;
1566
- try {
1567
- const target = new URL(anchor.href);
1568
- if (!allowed.has(target.origin) || target.origin === window.location.origin) return;
1569
- target.searchParams.set("sm_audio_rate", String(controller.getSnapshot().rate));
1570
- anchor.href = target.toString();
1571
- } catch {
1572
- }
1573
- };
1574
- const flush = () => {
1575
- save();
1576
- sync();
1577
- };
1578
- document.addEventListener("click", decorate, true);
1579
- document.addEventListener("auxclick", decorate, true);
1580
- window.addEventListener("pagehide", flush);
1581
- return () => {
1582
- save();
1583
- unsubscribe();
1584
- iframe?.remove();
1585
- document.removeEventListener("click", decorate, true);
1586
- document.removeEventListener("auxclick", decorate, true);
1587
- window.removeEventListener("pagehide", flush);
1588
- window.removeEventListener("message", receive);
1589
- };
1590
- }
1591
-
1592
- // src/components/network-audio-player.tsx
1593
- var import_jsx_runtime2 = require("react/jsx-runtime");
1594
- var Context = (0, import_react2.createContext)(null);
1595
- var NarrationRegistration = (0, import_react2.createContext)(null);
1596
- var serverSnapshot = () => EMPTY_SNAPSHOT;
1597
- function NetworkAudioProvider({ children, resolveAudio, connection, host, checkpointStorageKey, persistence, loadRecommendations }) {
1598
- if (connection && host) throw new Error("Use connection on reader pages and host on the dedicated player route, not both.");
1599
- const [controller] = (0, import_react2.useState)(() => new NetworkAudioController(resolveAudio));
1600
- const snapshot = (0, import_react2.useSyncExternalStore)(controller.subscribe, controller.getSnapshot, serverSnapshot);
1601
- const [remoteSnapshot, setRemoteSnapshot] = (0, import_react2.useState)(null);
1602
- const [recommendationsLoading, setRecommendationsLoading] = (0, import_react2.useState)(false);
1603
- const recommendationRequest = (0, import_react2.useRef)(null);
1604
- const [notice, setNotice] = (0, import_react2.useState)(null);
1605
- const [highlightEnabled, setHighlightEnabled] = (0, import_react2.useState)(false);
1606
- const [narrationTracks, setNarrationTracks] = (0, import_react2.useState)(() => /* @__PURE__ */ new Map());
1607
- const registerNarration = (0, import_react2.useCallback)((key) => {
1608
- const id = /* @__PURE__ */ Symbol();
1609
- setNarrationTracks((previous) => new Map(previous).set(id, key));
1610
- return () => setNarrationTracks((previous) => {
1611
- const next = new Map(previous);
1612
- next.delete(id);
1613
- return next;
1614
- });
1615
- }, []);
1616
- const client = (0, import_react2.useRef)(null);
1617
- (0, import_react2.useEffect)(() => {
1618
- controller.setResolver(resolveAudio);
1619
- }, [controller, resolveAudio]);
1620
- (0, import_react2.useEffect)(() => {
1621
- const audio = document.createElement("audio");
1622
- controller.attach(audio);
1623
- return () => controller.detach();
1624
- }, [controller]);
1625
- (0, import_react2.useEffect)(() => {
1626
- if (!checkpointStorageKey) return;
1627
- try {
1628
- const data = JSON.parse(sessionStorage.getItem(checkpointStorageKey) ?? "null");
1629
- if (validSnapshot(data)) controller.restore(data);
1630
- } catch {
1631
- }
1632
- let lastWrite = 0;
1633
- const save = () => {
1634
- try {
1635
- sessionStorage.setItem(checkpointStorageKey, JSON.stringify(controller.getSnapshot()));
1636
- } catch {
1637
- }
1638
- };
1639
- const unsubscribe = controller.subscribe(() => {
1640
- if (Date.now() - lastWrite > 1e3) {
1641
- lastWrite = Date.now();
1642
- save();
1643
- }
1644
- });
1645
- window.addEventListener("pagehide", save);
1646
- return () => {
1647
- save();
1648
- unsubscribe();
1649
- window.removeEventListener("pagehide", save);
1650
- };
1651
- }, [controller, checkpointStorageKey]);
1652
- const persistenceOrigins = JSON.stringify(persistence?.allowedOrigins ?? []);
1653
- (0, import_react2.useEffect)(() => {
1654
- if (persistence) return persistListening(controller, { ...persistence, restoreQueue: host && window.opener ? false : persistence.restoreQueue, allowedOrigins: JSON.parse(persistenceOrigins) });
1655
- }, [controller, persistence?.storageKey, persistence?.networkId, persistence?.hubUrl, persistence?.restoreQueue, host?.networkId, persistenceOrigins]);
1656
- (0, import_react2.useEffect)(() => () => recommendationRequest.current?.abort(), []);
1657
- const catchUp = (0, import_react2.useCallback)(async (minutes) => {
1658
- if (!loadRecommendations) return;
1659
- recommendationRequest.current?.abort();
1660
- const request = new AbortController();
1661
- recommendationRequest.current = request;
1662
- setRecommendationsLoading(true);
1663
- setNotice(null);
1664
- const timeout = setTimeout(() => request.abort(), 2e4);
1665
- try {
1666
- const tracks = await loadRecommendations(request.signal);
1667
- if (request.signal.aborted) return;
1668
- controller.setRecommendations(tracks.filter(validTrack));
1669
- controller.catchUp(minutes);
1670
- if (!controller.getSnapshot().queue.length) setNotice("No stories available for this queue. Try a longer session or replay a story from Recently listened.");
1671
- } catch {
1672
- if (recommendationRequest.current === request) setNotice("Could not load your catch-up queue. Your saved queue is still here. Please try again.");
1673
- } finally {
1674
- clearTimeout(timeout);
1675
- if (recommendationRequest.current === request) setRecommendationsLoading(false);
1676
- }
1677
- }, [controller, loadRecommendations]);
1678
- const allowedOrigins = JSON.stringify(host?.allowedOrigins ?? []);
1679
- (0, import_react2.useEffect)(() => {
1680
- if (!host) return;
1681
- return hostNetworkPlayer(controller, { networkId: host.networkId, allowedOrigins: JSON.parse(allowedOrigins) });
1682
- }, [controller, host?.networkId, allowedOrigins]);
1683
- (0, import_react2.useEffect)(() => {
1684
- if (!connection) return;
1685
- const instance = new NetworkPlayerClient(controller, connection, (state, message) => {
1686
- setRemoteSnapshot(state);
1687
- setNotice(message);
1688
- });
1689
- client.current = instance;
1690
- return () => {
1691
- instance.dispose();
1692
- client.current = null;
1693
- };
1694
- }, [controller, connection?.playerUrl, connection?.networkId]);
1695
- const command = (0, import_react2.useCallback)((value) => {
1696
- setNotice(null);
1697
- try {
1698
- if (value.action === "close") setHighlightEnabled(false);
1699
- if (!client.current?.command(value)) runCommand(controller, value);
1700
- } catch (error) {
1701
- setNotice(error instanceof Error ? error.message : "The article could not be added.");
1702
- }
1703
- }, [controller]);
1704
- const openNetworkPlayer = (0, import_react2.useCallback)(() => client.current?.open(), []);
1705
- const activeSnapshot = remoteSnapshot ?? snapshot;
1706
- const activeTrack = activeSnapshot.queue[activeSnapshot.index];
1707
- const highlightAvailable = !!activeTrack && [...narrationTracks.values()].includes(trackKey(activeTrack));
1708
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Context.Provider, { value: {
1709
- snapshot: activeSnapshot,
1710
- remote: remoteSnapshot !== null,
1711
- hosted: !!host,
1712
- notice,
1713
- command,
1714
- openNetworkPlayer: connection ? openNetworkPlayer : void 0,
1715
- highlightAvailable,
1716
- highlightEnabled,
1717
- setHighlightEnabled,
1718
- catchUp: loadRecommendations ? catchUp : void 0,
1719
- recommendationsLoading
1720
- }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(NarrationRegistration.Provider, { value: registerNarration, children: [
1721
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(NetworkMediaSession, {}),
1722
- children
1723
- ] }) });
1724
- }
1725
- function useNetworkAudio() {
1726
- const context = (0, import_react2.useContext)(Context);
1727
- if (!context) throw new Error("Mount NetworkAudioProvider above the player and article controls.");
1728
- return context;
1729
- }
1730
- function NetworkMediaSession() {
1731
- const { snapshot, remote, command } = useNetworkAudio();
1732
- const track = snapshot.queue[snapshot.index];
1733
- (0, import_react2.useEffect)(() => {
1734
- if (remote || !track || !("mediaSession" in navigator)) return;
1735
- const mediaSession = navigator.mediaSession;
1736
- if (typeof MediaMetadata !== "undefined") mediaSession.metadata = new MediaMetadata({ title: track.title, artist: track.publicationName ?? "" });
1737
- const handlers = [
1738
- ["play", () => command({ action: "play" })],
1739
- ["pause", () => command({ action: "pause" })],
1740
- ["seekto", (details) => {
1741
- if (details.seekTime != null) command({ action: "seek", value: details.seekTime });
1742
- }]
1743
- ];
1744
- handlers.forEach(([action, handler]) => {
1745
- try {
1746
- mediaSession.setActionHandler(action, handler);
1747
- } catch {
1748
- }
1749
- });
1750
- return () => {
1751
- handlers.forEach(([action]) => {
1752
- try {
1753
- mediaSession.setActionHandler(action, null);
1754
- } catch {
1755
- }
1756
- });
1757
- mediaSession.metadata = null;
1758
- mediaSession.playbackState = "none";
1759
- };
1760
- }, [remote, track, command]);
1761
- (0, import_react2.useEffect)(() => {
1762
- if (remote || !track || !("mediaSession" in navigator)) return;
1763
- navigator.mediaSession.playbackState = snapshot.status === "playing" ? "playing" : "paused";
1764
- if (snapshot.duration > 0) {
1765
- try {
1766
- navigator.mediaSession.setPositionState({
1767
- duration: snapshot.duration,
1768
- playbackRate: snapshot.rate,
1769
- position: Math.min(snapshot.position, snapshot.duration)
1770
- });
1771
- } catch {
1772
- }
1773
- }
1774
- }, [remote, track, snapshot.status, snapshot.position, snapshot.duration, snapshot.rate]);
1775
- return null;
1776
- }
1777
- var subscribeCapabilities = () => () => {
1778
- };
1779
- function useArticleNarration(track, narration) {
1780
- const { snapshot, highlightEnabled, setHighlightEnabled } = useNetworkAudio();
1781
- const supported = (0, import_react2.useSyncExternalStore)(subscribeCapabilities, narrationHighlightSupported, () => false);
1782
- const registerNarration = (0, import_react2.useContext)(NarrationRegistration);
1783
- const narrationKey = trackKey(track);
1784
- const available = !!narration && supported;
1785
- (0, import_react2.useEffect)(() => {
1786
- if (available) return registerNarration?.(narrationKey);
1787
- }, [available, narrationKey, registerNarration]);
1788
- const active = snapshot.queue[snapshot.index];
1789
- const matching = !!active && trackKey(active) === trackKey(track);
1790
- const clock = (0, import_react2.useRef)({ snapshot, received: 0 });
1791
- (0, import_react2.useEffect)(() => {
1792
- clock.current = { snapshot, received: performance.now() };
1793
- }, [snapshot]);
1794
- (0, import_react2.useEffect)(() => {
1795
- if (!narration || !matching || !highlightEnabled || !supported || snapshot.hidden) return;
1796
- const controller = new AbortController();
1797
- let highlighter = null;
1798
- let frame = 0;
1799
- const render = () => {
1800
- const { snapshot: current, received } = clock.current;
1801
- const elapsed = current.status === "playing" ? Math.min((performance.now() - received) / 1e3, 0.5) * current.rate : 0;
1802
- highlighter?.update((current.position + elapsed) * 1e3);
1803
- frame = requestAnimationFrame(render);
1804
- };
1805
- const visibility = () => {
1806
- cancelAnimationFrame(frame);
1807
- if (document.visibilityState === "hidden") highlighter?.clear();
1808
- else if (highlighter) frame = requestAnimationFrame(render);
1809
- };
1810
- const timeout = setTimeout(() => controller.abort(), 15e3);
1811
- void (async () => {
1812
- try {
1813
- const response = await fetch(narration.timingsUrl, { signal: controller.signal });
1814
- if (!response.ok) return;
1815
- const timings = parseTimingsPayload(await response.json());
1816
- const target = document.getElementById(narration.targetId);
1817
- if (controller.signal.aborted || !timings || !target) return;
1818
- highlighter = new NarrationHighlighter(target, timings);
1819
- if (highlighter.matchRatio() < 0.5) {
1820
- highlighter.destroy();
1821
- highlighter = null;
1822
- return;
1823
- }
1824
- visibility();
1825
- } catch {
1826
- } finally {
1827
- clearTimeout(timeout);
1828
- }
1829
- })();
1830
- document.addEventListener("visibilitychange", visibility);
1831
- return () => {
1832
- controller.abort();
1833
- clearTimeout(timeout);
1834
- cancelAnimationFrame(frame);
1835
- highlighter?.destroy();
1836
- document.removeEventListener("visibilitychange", visibility);
1837
- };
1838
- }, [snapshot.hidden, matching, highlightEnabled, supported, narration?.targetId, narration?.timingsUrl, track.id, track.publicationId]);
1839
- return { highlightAvailable: !!narration && supported, highlightEnabled, setHighlightEnabled, matching };
1840
- }
1841
- function AudioIcon({ name }) {
1842
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("svg", { className: "sm-network-icon", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: [
1843
- name === "play" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "m9 5 11 7-11 7Z", fill: "currentColor", stroke: "none" }),
1844
- name === "pause" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M7 5h3v14H7zm7 0h3v14h-3z", fill: "currentColor", stroke: "none" }),
1845
- name === "queue" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M4 6h16M4 12h10M4 18h8m7-5v8m-4-4h8" }) }),
1846
- name === "check" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "m5 12 4 4L19 6" }),
1847
- name === "highlight" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "m7 14 7-9 5 4-7 9-5-4Zm0 0-3 5h8M16 3l5 4M3 22h17" }) }),
1848
- name === "next" && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1849
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "m6 5 10 7-10 7Z", fill: "currentColor", stroke: "none" }),
1850
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M19 5v14" })
1851
- ] }),
1852
- name === "chevron" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "m7 10 5 5 5-5" }),
1853
- name === "external" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M14 4h6v6m0-6L10 14m10 1v5H4V4h5" }),
1854
- name === "close" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "m6 6 12 12M18 6 6 18" })
1855
- ] });
1856
- }
1857
- var formatTime = (seconds) => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
1858
- var PLAYBACK_RATES = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3];
1859
- function ArticleAudioControls({ track, narration, durationMs, className = "" }) {
1860
- const { snapshot, command } = useNetworkAudio();
1861
- const { highlightAvailable, highlightEnabled, setHighlightEnabled, matching } = useArticleNarration(track, narration);
1862
- const playing = matching && (snapshot.status === "playing" || snapshot.status === "loading");
1863
- const record = listeningRecord(snapshot, track);
1864
- const resume = !record?.completedAt && (matching ? snapshot.position : record?.position ?? 0) > 2;
1865
- const updated = !record && snapshot.history?.some((item) => item.completedAt && item.track.storyId && item.track.storyId === track.storyId);
1866
- const caption = playing ? "Pause this story" : record?.completedAt ? "Listen again" : resume ? "Resume this story" : "Listen to this story";
1867
- const queued = snapshot.queue.some((item) => storyKey(item) === storyKey(track));
1868
- const duration = matching && snapshot.duration > 0 ? snapshot.duration : (durationMs ?? 0) / 1e3;
1869
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1870
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: `sm-network-article ${className}`, role: "group", "aria-label": "Article audio", children: [
1871
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1872
- "button",
1873
- {
1874
- type: "button",
1875
- className: "sm-network-article__listen",
1876
- "aria-label": caption,
1877
- onClick: () => command(playing ? { action: "pause" } : { action: "playTrack", track }),
1878
- children: [
1879
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-article__disc", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: playing ? "pause" : "play" }) }),
1880
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "sm-network-article__caption", children: [
1881
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: caption }),
1882
- updated && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("small", { children: "Updated since you listened" }),
1883
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-article__duration", children: matching && snapshot.status === "loading" ? "Loading audio\u2026" : duration > 0 ? `${formatTime(Math.max(0, duration - (resume ? matching ? snapshot.position : record?.position ?? 0 : 0)) / snapshot.rate)} ${resume ? "remaining" : "listening time"}` : "Article audio" })
1884
- ] })
1885
- ]
1886
- }
1887
- ),
1888
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-article__actions", children: [
1889
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { type: "button", "aria-label": `Article playback speed ${snapshot.rate}\xD7`, onClick: () => command({ action: "rate", value: PLAYBACK_RATES.find((rate) => rate > snapshot.rate) ?? 1 }), children: [
1890
- snapshot.rate,
1891
- "\xD7"
1892
- ] }),
1893
- resume && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", onClick: () => {
1894
- command({ action: "playTrack", track });
1895
- command({ action: "restart" });
1896
- }, children: "Start over" }),
1897
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1898
- "button",
1899
- {
1900
- type: "button",
1901
- className: "sm-network-article__queue",
1902
- "aria-label": queued ? "Queued" : "Add to queue",
1903
- disabled: queued,
1904
- onClick: () => command({ action: "enqueue", track }),
1905
- children: [
1906
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: queued ? "check" : "queue" }),
1907
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: queued ? "Queued" : "Queue" })
1908
- ]
1909
- }
1910
- ),
1911
- highlightAvailable && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1912
- "button",
1913
- {
1914
- type: "button",
1915
- "aria-label": "Follow along: highlight words",
1916
- "aria-pressed": highlightEnabled,
1917
- title: "Highlight words as you listen",
1918
- onClick: () => setHighlightEnabled(!highlightEnabled),
1919
- children: [
1920
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "highlight" }),
1921
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "Follow along" }),
1922
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-toggle", "aria-hidden": "true" })
1923
- ]
1924
- }
1925
- )
1926
- ] })
1927
- ] }),
1928
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ListeningLibrary, {})
1929
- ] });
1930
- }
1931
- function NetworkAudioPlayer({ networkName = "Your listening queue", advertisement, className = "", style, fixed = true, renderArticleLink }) {
1932
- const { snapshot, remote, hosted, notice, command, openNetworkPlayer, highlightAvailable, highlightEnabled, setHighlightEnabled } = useNetworkAudio();
1933
- const [expanded, setExpanded] = (0, import_react2.useState)(false);
1934
- const [height, setHeight] = (0, import_react2.useState)(0);
1935
- const bar = (0, import_react2.useRef)(null);
1936
- const detailsId = (0, import_react2.useId)();
1937
- const track = snapshot.queue[snapshot.index];
1938
- const playing = snapshot.status === "playing" || snapshot.status === "loading";
1939
- const nextRate = PLAYBACK_RATES.find((rate) => rate > snapshot.rate) ?? 1;
1940
- (0, import_react2.useEffect)(() => {
1941
- const element = bar.current;
1942
- if (!fixed || !element) return;
1943
- const measure = () => setHeight(element.getBoundingClientRect().height);
1944
- measure();
1945
- if (typeof ResizeObserver === "undefined") {
1946
- window.addEventListener("resize", measure);
1947
- return () => window.removeEventListener("resize", measure);
1948
- }
1949
- const observer = new ResizeObserver(measure);
1950
- observer.observe(element);
1951
- return () => observer.disconnect();
1952
- }, [fixed, !!track, expanded, notice, snapshot.error]);
1953
- if (!track || snapshot.hidden) return notice ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { role: "status", children: notice }) : null;
1954
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1955
- fixed && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { "aria-hidden": "true", style: { height } }),
1956
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("section", { ref: bar, className: `sm-network-player ${fixed ? "sm-network-player--fixed" : ""} ${className}`, style, "aria-label": "Network audio player", children: [
1957
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-player__row", children: [
1958
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", className: "sm-network-player__play", "aria-label": playing ? "Pause playback" : "Play playback", onClick: () => command({ action: playing ? "pause" : "play" }), children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: playing ? "pause" : "play" }) }),
1959
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-player__story", children: [
1960
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: remote ? "Playing in network window" : networkName }),
1961
- !hosted && renderArticleLink ? renderArticleLink(track) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("a", { href: track.articleUrl, target: "_blank", rel: "noopener noreferrer", children: track.title }),
1962
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("small", { children: track.publicationName })
1963
- ] }),
1964
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-player__timeline", children: [
1965
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { style: { "--sm-progress": `${snapshot.duration ? Math.min(100, snapshot.position / snapshot.duration * 100) : 0}%` }, type: "range", min: "0", max: snapshot.duration || 0, step: "0.1", value: Math.min(snapshot.position, snapshot.duration), disabled: !snapshot.duration, "aria-label": "Seek article audio", onChange: (e) => command({ action: "seek", value: Number(e.target.value) }) }),
1966
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
1967
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: formatTime(snapshot.position) }),
1968
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "sm-network-player__remaining", "aria-label": `${formatTime(Math.max(0, snapshot.duration - snapshot.position) / snapshot.rate)} remaining`, children: [
1969
- formatTime(Math.max(0, snapshot.duration - snapshot.position) / snapshot.rate),
1970
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-player__remaining-label", children: " remaining" })
1971
- ] })
1972
- ] })
1973
- ] }),
1974
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-player__shortcuts", role: "group", "aria-label": "Playback shortcuts", children: [
1975
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1976
- "button",
1977
- {
1978
- type: "button",
1979
- className: "sm-network-player__rate",
1980
- "aria-label": `Playback speed ${snapshot.rate}\xD7. ${nextRate > snapshot.rate ? "Speed up" : "Reset"} to ${nextRate}\xD7`,
1981
- title: `Playback speed: ${snapshot.rate}\xD7. Click for ${nextRate}\xD7`,
1982
- onClick: () => command({ action: "rate", value: nextRate }),
1983
- children: [
1984
- snapshot.rate,
1985
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "\xD7" })
1986
- ]
1987
- }
1988
- ),
1989
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1990
- "button",
1991
- {
1992
- type: "button",
1993
- className: "sm-network-player__highlight",
1994
- "aria-label": "Follow along: highlight article words",
1995
- "aria-pressed": highlightAvailable && highlightEnabled,
1996
- disabled: !highlightAvailable,
1997
- title: highlightAvailable ? "Highlight words as you listen" : "Open the playing article to use word highlighting when available",
1998
- onClick: () => setHighlightEnabled(!highlightEnabled),
1999
- children: [
2000
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "highlight" }),
2001
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "Follow along" })
2002
- ]
2003
- }
2004
- ),
2005
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2006
- "button",
2007
- {
2008
- type: "button",
2009
- className: "sm-network-player__next",
2010
- "aria-label": "Next article",
2011
- title: "Next article",
2012
- onClick: () => command({ action: "skip" }),
2013
- children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "next" })
2014
- }
2015
- ),
2016
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2017
- "button",
2018
- {
2019
- type: "button",
2020
- className: "sm-network-player__queue",
2021
- "aria-label": expanded ? "Close queue" : `Queue (${snapshot.queue.length})`,
2022
- "aria-expanded": expanded,
2023
- "aria-controls": detailsId,
2024
- onClick: () => setExpanded(!expanded),
2025
- children: [
2026
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "queue" }),
2027
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-player__queue-label", children: expanded ? "Close queue" : "Queue" }),
2028
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-player__count", children: snapshot.queue.length }),
2029
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "chevron" })
2030
- ]
2031
- }
2032
- )
2033
- ] }),
2034
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2035
- "button",
2036
- {
2037
- type: "button",
2038
- className: "sm-network-player__close",
2039
- "aria-label": "Close player",
2040
- title: "Pause and close player. Your queue is saved.",
2041
- onClick: () => {
2042
- setExpanded(false);
2043
- command({ action: "close" });
2044
- },
2045
- children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "close" })
2046
- }
2047
- )
2048
- ] }),
2049
- (notice || snapshot.error) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { role: "status", className: "sm-network-player__notice", children: notice ?? snapshot.error }),
2050
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { id: detailsId, hidden: !expanded, className: "sm-network-player__details", children: [
2051
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-player__tools", children: [
2052
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", onClick: () => command({ action: "seek", value: snapshot.position - 15 }), children: "Back 15 seconds" }),
2053
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", onClick: () => command({ action: "seek", value: snapshot.position + 30 }), children: "Forward 30 seconds" }),
2054
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { children: [
2055
- "Speed ",
2056
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "sm-network-player__select", children: [
2057
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("select", { value: snapshot.rate, onChange: (e) => command({ action: "rate", value: Number(e.target.value) }), children: PLAYBACK_RATES.map((rate) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("option", { value: rate, children: [
2058
- rate,
2059
- "\xD7"
2060
- ] }, rate)) }),
2061
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "chevron" })
2062
- ] })
2063
- ] }),
2064
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { children: [
2065
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "checkbox", checked: snapshot.autoplayNext !== false, onChange: (e) => command({ action: "autoplay", value: e.target.checked }) }),
2066
- "Play next automatically"
2067
- ] }),
2068
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { children: [
2069
- "Volume ",
2070
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "range", min: "0", max: "1", step: "0.05", value: snapshot.volume, onChange: (e) => command({ action: "volume", value: Number(e.target.value) }) })
2071
- ] }),
2072
- openNetworkPlayer && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { type: "button", onClick: openNetworkPlayer, children: [
2073
- remote ? "Open player window" : "Listen across sites",
2074
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "external" })
2075
- ] }),
2076
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", onClick: () => command({ action: "clear" }), children: "Stop and clear queue" })
2077
- ] }),
2078
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-player__expanded", children: [
2079
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
2080
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("h2", { children: "Up next" }),
2081
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ol", { children: snapshot.queue.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { "aria-current": index === snapshot.index ? "true" : void 0, children: [
2082
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { type: "button", className: "sm-network-player__queue-title", onClick: () => command({ action: "select", value: index }), children: [
2083
- item.title,
2084
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("small", { children: [
2085
- item.publicationName,
2086
- index === snapshot.index ? " \u2014 Current article" : ""
2087
- ] })
2088
- ] }),
2089
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", "aria-label": `Remove ${item.title} from queue`, onClick: () => command({ action: "remove", value: index }), children: "Remove" })
2090
- ] }, trackKey(item))) })
2091
- ] }),
2092
- advertisement && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("aside", { "aria-label": "Advertisement", children: [
2093
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "Advertisement" }),
2094
- advertisement
2095
- ] })
2096
- ] })
2097
- ] })
2098
- ] })
2099
- ] });
2100
- }
2101
- function ListeningLibrary({ open = false }) {
2102
- const { snapshot, command, catchUp, recommendationsLoading, remote, notice } = useNetworkAudio();
2103
- const [minutes, setMinutes] = (0, import_react2.useState)(10);
2104
- const recent = (snapshot.history ?? []).filter((item) => item.completedAt).slice(0, 20);
2105
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("details", { className: "sm-listening-library", open: open || void 0, children: [
2106
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("summary", { children: [
2107
- "Your listening ",
2108
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: snapshot.queue.length ? `${snapshot.queue.length} queued` : recent.length ? "Recently listened" : "Queue & catch up" })
2109
- ] }),
2110
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-listening-library__body", children: [
2111
- catchUp && !remote && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-listening-library__catchup", children: [
2112
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { children: [
2113
- "Catch me up in ",
2114
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("select", { "aria-label": "Catch-up length", value: minutes, onChange: (e) => setMinutes(Number(e.target.value)), children: [5, 10, 20].map((value) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("option", { value, children: [
2115
- value,
2116
- " minutes"
2117
- ] }, value)) })
2118
- ] }),
2119
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", disabled: recommendationsLoading, onClick: () => void catchUp(minutes), children: recommendationsLoading ? "Finding stories\u2026" : "Build my queue" }),
2120
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("small", { children: [
2121
- "Unheard stories first, timed at ",
2122
- snapshot.rate,
2123
- "\xD7. Your selections stay first."
2124
- ] })
2125
- ] }),
2126
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { className: "sm-listening-library__option", children: [
2127
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "checkbox", checked: snapshot.allowRepeats === true, onChange: (e) => command({ action: "repeats", value: e.target.checked }) }),
2128
- "Include repeats when I\u2019m caught up"
2129
- ] }),
2130
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { className: "sm-listening-library__option", children: [
2131
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("input", { type: "checkbox", checked: snapshot.autoplayNext !== false, onChange: (e) => command({ action: "autoplay", value: e.target.checked }) }),
2132
- "Play next automatically"
2133
- ] }),
2134
- notice && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { role: "status", children: notice }),
2135
- snapshot.queue.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
2136
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("h3", { children: "Up next" }),
2137
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { children: [
2138
- snapshot.queue.length,
2139
- " stories \xB7 ",
2140
- formatTime(snapshot.queue.reduce((sum, item, index) => sum + Math.max(0, (item.durationSeconds ?? 0) - (index === snapshot.index ? snapshot.position : 0)) / snapshot.rate, 0)),
2141
- " at ",
2142
- snapshot.rate,
2143
- "\xD7"
2144
- ] }),
2145
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ol", { children: snapshot.queue.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { children: [
2146
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", onClick: () => command({ action: "select", value: index }), children: item.title }),
2147
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", "aria-label": `Remove ${item.title}`, onClick: () => command({ action: "remove", value: index }), children: "Remove" })
2148
- ] }, trackKey(item))) }),
2149
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", onClick: () => command({ action: "clear" }), children: "Clear queue" })
2150
- ] }),
2151
- recent.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
2152
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("h3", { children: "Recently listened" }),
2153
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ol", { children: recent.map((item) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { children: [
2154
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: item.track.title }),
2155
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", "aria-label": `Replay ${item.track.title}`, onClick: () => command({ action: "playTrack", track: { ...item.track, automatic: false } }), children: "Replay" })
2156
- ] }, storyKey(item.track))) })
2157
- ] }),
2158
- recent.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { type: "button", onClick: () => command({ action: "forgetHistory" }), children: "Clear listening history" }),
2159
- !snapshot.queue.length && !notice && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { children: recent.length ? "You\u2019re caught up with your queue." : "Add a story or build a catch-up queue to start listening." })
2160
- ] })
2161
- ] });
2162
- }
2163
- // Annotate the CommonJS export names for ESM import in node:
2164
- 0 && (module.exports = {
2165
- ArticleAudioControls,
2166
- AudioPlayer,
2167
- ListeningLibrary,
2168
- NarrationHighlighter,
2169
- NetworkAudioController,
2170
- NetworkAudioPlayer,
2171
- NetworkAudioProvider,
2172
- SENTENCE_HIGHLIGHT,
2173
- WORD_HIGHLIGHT,
2174
- narrationHighlightSupported,
2175
- parseTimingsPayload,
2176
- useArticleNarration,
2177
- useNetworkAudio
2178
- });