@scalemule/nextjs 0.1.56 → 0.1.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/audio.js CHANGED
@@ -24,6 +24,7 @@ var audio_exports = {};
24
24
  __export(audio_exports, {
25
25
  ArticleAudioControls: () => ArticleAudioControls,
26
26
  AudioPlayer: () => AudioPlayer,
27
+ ListeningLibrary: () => ListeningLibrary,
27
28
  NarrationHighlighter: () => NarrationHighlighter,
28
29
  NetworkAudioController: () => NetworkAudioController,
29
30
  NetworkAudioPlayer: () => NetworkAudioPlayer,
@@ -814,9 +815,16 @@ var EMPTY_SNAPSHOT = {
814
815
  rate: 1,
815
816
  volume: 1,
816
817
  status: "idle",
817
- error: null
818
+ error: null,
819
+ history: [],
820
+ autoplayNext: true,
821
+ allowRepeats: false,
822
+ hidden: false,
823
+ sessionMinutes: 0
818
824
  };
819
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));
820
828
  var finite = (n) => typeof n === "number" && Number.isFinite(n);
821
829
  function safeHttpUrl(value) {
822
830
  if (typeof value !== "string" || value.length > 4096) return false;
@@ -830,19 +838,39 @@ function safeHttpUrl(value) {
830
838
  function validTrack(value) {
831
839
  if (!value || typeof value !== "object") return false;
832
840
  const t = value;
833
- 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);
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");
834
842
  }
835
843
  var copyTrack = (t) => ({
836
844
  id: t.id,
837
845
  publicationId: t.publicationId,
838
846
  title: t.title,
839
847
  ...t.publicationName ? { publicationName: t.publicationName } : {},
840
- articleUrl: t.articleUrl
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 } : {}
841
855
  });
842
856
  function validSnapshot(value) {
843
857
  if (!value || typeof value !== "object") return false;
844
858
  const s = value;
845
- 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.error === null || typeof s.error === "string" && s.error.length <= 1e3);
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);
846
874
  }
847
875
  var NetworkAudioController = class {
848
876
  constructor(resolve) {
@@ -857,6 +885,7 @@ var NetworkAudioController = class {
857
885
  this.source = null;
858
886
  this.refreshed = false;
859
887
  this.resumePosition = null;
888
+ this.candidates = [];
860
889
  this.getSnapshot = () => this.snapshot;
861
890
  this.subscribe = (listener) => {
862
891
  this.listeners.add(listener);
@@ -865,6 +894,10 @@ var NetworkAudioController = class {
865
894
  };
866
895
  };
867
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
+ }
868
901
  setResolver(resolve) {
869
902
  this.resolve = resolve;
870
903
  }
@@ -896,7 +929,10 @@ var NetworkAudioController = class {
896
929
  if (finite(audio.duration) && audio.duration > 0) this.patch({ duration: audio.duration });
897
930
  }),
898
931
  on("timeupdate", () => {
899
- if (this.resumePosition === null) this.patch({ position: audio.currentTime });
932
+ if (this.resumePosition === null) {
933
+ this.patch({ position: audio.currentTime });
934
+ this.remember();
935
+ }
900
936
  }),
901
937
  on("playing", () => {
902
938
  if (!this.intent) {
@@ -911,11 +947,7 @@ var NetworkAudioController = class {
911
947
  }),
912
948
  on("ended", () => {
913
949
  if (!this.intent) return;
914
- if (this.snapshot.index + 1 < this.snapshot.queue.length) this.select(this.snapshot.index + 1);
915
- else {
916
- this.intent = false;
917
- this.patch({ status: "paused", position: this.snapshot.duration });
918
- }
950
+ this.finish();
919
951
  }),
920
952
  on("error", () => {
921
953
  if (this.intent && !this.request) void this.recover();
@@ -944,12 +976,23 @@ var NetworkAudioController = class {
944
976
  }
945
977
  enqueue(track) {
946
978
  if (!validTrack(track)) throw new Error("A valid publication, article identity, title and HTTP(S) article URL are required.");
947
- const found = this.snapshot.queue.findIndex((t) => trackKey(t) === trackKey(track));
979
+ this.patch({ hidden: false });
980
+ const found = this.snapshot.queue.findIndex((t) => storyKey(t) === storyKey(track));
948
981
  if (found !== -1) return found;
949
982
  if (this.snapshot.queue.length >= 100) throw new Error("The listening queue holds up to 100 articles.");
950
- const queue = [...this.snapshot.queue, copyTrack(track)];
951
- this.patch({ queue, index: this.snapshot.index === -1 ? 0 : this.snapshot.index });
952
- return queue.length - 1;
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;
953
996
  }
954
997
  playTrack(track) {
955
998
  const index = this.enqueue(track);
@@ -962,13 +1005,16 @@ var NetworkAudioController = class {
962
1005
  void this.play();
963
1006
  return;
964
1007
  }
1008
+ this.remember();
965
1009
  this.cancel();
966
1010
  this.source = null;
967
- this.patch({ index, position: 0, duration: 0, error: null, status: "paused" });
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 });
968
1013
  void this.play();
969
1014
  }
970
1015
  remove(index) {
971
1016
  if (!Number.isInteger(index) || index < 0 || index >= this.snapshot.queue.length) return;
1017
+ this.remember();
972
1018
  const wasPlaying = this.intent;
973
1019
  const current = this.snapshot.index;
974
1020
  const queue = this.snapshot.queue.filter((_, i) => i !== index);
@@ -978,7 +1024,9 @@ var NetworkAudioController = class {
978
1024
  }
979
1025
  this.cancel();
980
1026
  this.source = null;
981
- this.patch({ queue, index: queue.length ? Math.min(index, queue.length - 1) : -1, position: 0, duration: 0, status: "paused", error: 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 });
982
1030
  if (wasPlaying && queue.length) void this.play();
983
1031
  }
984
1032
  cancel() {
@@ -990,16 +1038,105 @@ var NetworkAudioController = class {
990
1038
  this.audio?.pause();
991
1039
  }
992
1040
  pause() {
1041
+ this.remember();
993
1042
  const pendingPosition = this.resumePosition;
994
1043
  this.cancel();
995
1044
  this.resumePosition = pendingPosition;
996
1045
  this.patch({ status: this.snapshot.queue.length ? "paused" : "idle" });
997
1046
  }
998
1047
  clear() {
1048
+ this.remember();
999
1049
  this.cancel();
1000
1050
  this.source = null;
1001
1051
  this.audio?.removeAttribute("src");
1002
- this.patch({ ...EMPTY_SNAPSHOT, rate: this.snapshot.rate, volume: this.snapshot.volume });
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 } : {} });
1003
1140
  }
1004
1141
  seek(position) {
1005
1142
  if (!finite(position)) return;
@@ -1011,7 +1148,7 @@ var NetworkAudioController = class {
1011
1148
  setRate(rate) {
1012
1149
  if (!finite(rate) || rate < 0.5 || rate > 3) return;
1013
1150
  if (this.audio) this.audio.playbackRate = rate;
1014
- this.patch({ rate });
1151
+ this.patch({ rate, settingsUpdatedAt: Date.now() });
1015
1152
  }
1016
1153
  setVolume(volume) {
1017
1154
  if (!finite(volume) || volume < 0 || volume > 1) return;
@@ -1030,7 +1167,22 @@ var NetworkAudioController = class {
1030
1167
  rate: snapshot.rate,
1031
1168
  volume: snapshot.volume,
1032
1169
  status: snapshot.queue.length ? "paused" : "idle",
1033
- error: null
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
1034
1186
  });
1035
1187
  if (this.audio) {
1036
1188
  this.audio.playbackRate = snapshot.rate;
@@ -1041,7 +1193,7 @@ var NetworkAudioController = class {
1041
1193
  if (!this.audio || !this.snapshot.queue[this.snapshot.index] || this.request) return;
1042
1194
  this.intent = true;
1043
1195
  this.refreshed = false;
1044
- this.patch({ error: null });
1196
+ this.patch({ error: null, hidden: false });
1045
1197
  const expires = this.source?.expires_at ? Date.parse(this.source.expires_at) : Infinity;
1046
1198
  if (!this.source || expires <= Date.now() + 3e4) await this.load();
1047
1199
  else {
@@ -1123,7 +1275,20 @@ function runCommand(controller, command) {
1123
1275
  controller.pause();
1124
1276
  return true;
1125
1277
  case "clear":
1126
- controller.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);
1127
1292
  return true;
1128
1293
  case "enqueue":
1129
1294
  case "playTrack":
@@ -1276,16 +1441,166 @@ var NetworkPlayerClient = class {
1276
1441
  }
1277
1442
  };
1278
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(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
+
1279
1592
  // src/components/network-audio-player.tsx
1280
1593
  var import_jsx_runtime2 = require("react/jsx-runtime");
1281
1594
  var Context = (0, import_react2.createContext)(null);
1282
1595
  var NarrationRegistration = (0, import_react2.createContext)(null);
1283
1596
  var serverSnapshot = () => EMPTY_SNAPSHOT;
1284
- function NetworkAudioProvider({ children, resolveAudio, connection, host, checkpointStorageKey }) {
1597
+ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkpointStorageKey, persistence, loadRecommendations }) {
1285
1598
  if (connection && host) throw new Error("Use connection on reader pages and host on the dedicated player route, not both.");
1286
1599
  const [controller] = (0, import_react2.useState)(() => new NetworkAudioController(resolveAudio));
1287
1600
  const snapshot = (0, import_react2.useSyncExternalStore)(controller.subscribe, controller.getSnapshot, serverSnapshot);
1288
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);
1289
1604
  const [notice, setNotice] = (0, import_react2.useState)(null);
1290
1605
  const [highlightEnabled, setHighlightEnabled] = (0, import_react2.useState)(false);
1291
1606
  const [narrationTracks, setNarrationTracks] = (0, import_react2.useState)(() => /* @__PURE__ */ new Map());
@@ -1334,6 +1649,32 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1334
1649
  window.removeEventListener("pagehide", save);
1335
1650
  };
1336
1651
  }, [controller, checkpointStorageKey]);
1652
+ const persistenceOrigins = JSON.stringify(persistence?.allowedOrigins ?? []);
1653
+ (0, import_react2.useEffect)(() => {
1654
+ if (persistence) return persistListening(controller, { ...persistence, allowedOrigins: JSON.parse(persistenceOrigins) });
1655
+ }, [controller, persistence?.storageKey, persistence?.networkId, persistence?.hubUrl, 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]);
1337
1678
  const allowedOrigins = JSON.stringify(host?.allowedOrigins ?? []);
1338
1679
  (0, import_react2.useEffect)(() => {
1339
1680
  if (!host) return;
@@ -1354,6 +1695,7 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1354
1695
  const command = (0, import_react2.useCallback)((value) => {
1355
1696
  setNotice(null);
1356
1697
  try {
1698
+ if (value.action === "close") setHighlightEnabled(false);
1357
1699
  if (!client.current?.command(value)) runCommand(controller, value);
1358
1700
  } catch (error) {
1359
1701
  setNotice(error instanceof Error ? error.message : "The article could not be added.");
@@ -1372,7 +1714,9 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1372
1714
  openNetworkPlayer: connection ? openNetworkPlayer : void 0,
1373
1715
  highlightAvailable,
1374
1716
  highlightEnabled,
1375
- setHighlightEnabled
1717
+ setHighlightEnabled,
1718
+ catchUp: loadRecommendations ? catchUp : void 0,
1719
+ recommendationsLoading
1376
1720
  }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(NarrationRegistration.Provider, { value: registerNarration, children: [
1377
1721
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(NetworkMediaSession, {}),
1378
1722
  children
@@ -1448,7 +1792,7 @@ function useArticleNarration(track, narration) {
1448
1792
  clock.current = { snapshot, received: performance.now() };
1449
1793
  }, [snapshot]);
1450
1794
  (0, import_react2.useEffect)(() => {
1451
- if (!narration || !matching || !highlightEnabled || !supported) return;
1795
+ if (!narration || !matching || !highlightEnabled || !supported || snapshot.hidden) return;
1452
1796
  const controller = new AbortController();
1453
1797
  let highlighter = null;
1454
1798
  let frame = 0;
@@ -1491,7 +1835,7 @@ function useArticleNarration(track, narration) {
1491
1835
  highlighter?.destroy();
1492
1836
  document.removeEventListener("visibilitychange", visibility);
1493
1837
  };
1494
- }, [matching, highlightEnabled, supported, narration?.targetId, narration?.timingsUrl, track.id, track.publicationId]);
1838
+ }, [snapshot.hidden, matching, highlightEnabled, supported, narration?.targetId, narration?.timingsUrl, track.id, track.publicationId]);
1495
1839
  return { highlightAvailable: !!narration && supported, highlightEnabled, setHighlightEnabled, matching };
1496
1840
  }
1497
1841
  function AudioIcon({ name }) {
@@ -1516,56 +1860,72 @@ function ArticleAudioControls({ track, narration, durationMs, className = "" })
1516
1860
  const { snapshot, command } = useNetworkAudio();
1517
1861
  const { highlightAvailable, highlightEnabled, setHighlightEnabled, matching } = useArticleNarration(track, narration);
1518
1862
  const playing = matching && (snapshot.status === "playing" || snapshot.status === "loading");
1519
- const queued = snapshot.queue.some((item) => trackKey(item) === trackKey(track));
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));
1520
1868
  const duration = matching && snapshot.duration > 0 ? snapshot.duration : (durationMs ?? 0) / 1e3;
1521
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: `sm-network-article ${className}`, role: "group", "aria-label": "Article audio", children: [
1522
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1523
- "button",
1524
- {
1525
- type: "button",
1526
- className: "sm-network-article__listen",
1527
- "aria-label": playing ? "Pause this story" : "Listen to this story",
1528
- onClick: () => command(playing ? { action: "pause" } : { action: "playTrack", track }),
1529
- children: [
1530
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-article__disc", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: playing ? "pause" : "play" }) }),
1531
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "sm-network-article__caption", children: [
1532
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: playing ? "Pause this story" : "Listen to this story" }),
1533
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-article__duration", children: matching && snapshot.status === "loading" ? "Loading audio\u2026" : duration > 0 ? `${formatTime(duration)} listening time` : "Article audio" })
1534
- ] })
1535
- ]
1536
- }
1537
- ),
1538
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "sm-network-article__actions", children: [
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: [
1539
1871
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1540
1872
  "button",
1541
1873
  {
1542
1874
  type: "button",
1543
- className: "sm-network-article__queue",
1544
- "aria-label": queued ? "Queued" : "Add to queue",
1545
- disabled: queued,
1546
- onClick: () => command({ action: "enqueue", track }),
1875
+ className: "sm-network-article__listen",
1876
+ "aria-label": caption,
1877
+ onClick: () => command(playing ? { action: "pause" } : { action: "playTrack", track }),
1547
1878
  children: [
1548
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: queued ? "check" : "queue" }),
1549
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: queued ? "Queued" : "Queue" })
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
+ ] })
1550
1885
  ]
1551
1886
  }
1552
1887
  ),
1553
- highlightAvailable && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1554
- "button",
1555
- {
1556
- type: "button",
1557
- "aria-label": "Follow along: highlight words",
1558
- "aria-pressed": highlightEnabled,
1559
- title: "Highlight words as you listen",
1560
- onClick: () => setHighlightEnabled(!highlightEnabled),
1561
- children: [
1562
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "highlight" }),
1563
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "Follow along" }),
1564
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sm-network-toggle", "aria-hidden": "true" })
1565
- ]
1566
- }
1567
- )
1568
- ] })
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, {})
1569
1929
  ] });
1570
1930
  }
1571
1931
  function NetworkAudioPlayer({ networkName = "Your listening queue", advertisement, className = "", style, fixed = true, renderArticleLink }) {
@@ -1590,7 +1950,7 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1590
1950
  observer.observe(element);
1591
1951
  return () => observer.disconnect();
1592
1952
  }, [fixed, !!track, expanded, notice, snapshot.error]);
1593
- if (!track) return notice ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { role: "status", children: notice }) : null;
1953
+ if (!track || snapshot.hidden) return notice ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { role: "status", children: notice }) : null;
1594
1954
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1595
1955
  fixed && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { "aria-hidden": "true", style: { height } }),
1596
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: [
@@ -1649,8 +2009,7 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1649
2009
  className: "sm-network-player__next",
1650
2010
  "aria-label": "Next article",
1651
2011
  title: "Next article",
1652
- disabled: snapshot.index + 1 >= snapshot.queue.length,
1653
- onClick: () => command({ action: "select", value: snapshot.index + 1 }),
2012
+ onClick: () => command({ action: "skip" }),
1654
2013
  children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "next" })
1655
2014
  }
1656
2015
  ),
@@ -1678,10 +2037,10 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1678
2037
  type: "button",
1679
2038
  className: "sm-network-player__close",
1680
2039
  "aria-label": "Close player",
1681
- title: "Stop playback, clear queue, and close player",
2040
+ title: "Pause and close player. Your queue is saved.",
1682
2041
  onClick: () => {
1683
2042
  setExpanded(false);
1684
- command({ action: "clear" });
2043
+ command({ action: "close" });
1685
2044
  },
1686
2045
  children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "close" })
1687
2046
  }
@@ -1702,6 +2061,10 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1702
2061
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AudioIcon, { name: "chevron" })
1703
2062
  ] })
1704
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
+ ] }),
1705
2068
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { children: [
1706
2069
  "Volume ",
1707
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) }) })
@@ -1735,10 +2098,73 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1735
2098
  ] })
1736
2099
  ] });
1737
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
+ }
1738
2163
  // Annotate the CommonJS export names for ESM import in node:
1739
2164
  0 && (module.exports = {
1740
2165
  ArticleAudioControls,
1741
2166
  AudioPlayer,
2167
+ ListeningLibrary,
1742
2168
  NarrationHighlighter,
1743
2169
  NetworkAudioController,
1744
2170
  NetworkAudioPlayer,