@scalemule/nextjs 0.1.55 → 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.mjs CHANGED
@@ -794,9 +794,16 @@ var EMPTY_SNAPSHOT = {
794
794
  rate: 1,
795
795
  volume: 1,
796
796
  status: "idle",
797
- error: null
797
+ error: null,
798
+ history: [],
799
+ autoplayNext: true,
800
+ allowRepeats: false,
801
+ hidden: false,
802
+ sessionMinutes: 0
798
803
  };
799
804
  var trackKey = (track) => JSON.stringify([track.publicationId, track.id]);
805
+ var storyKey = (track) => JSON.stringify([track.storyId ?? trackKey(track), track.revision ?? ""]);
806
+ var listeningRecord = (snapshot, track) => snapshot.history?.find((item) => storyKey(item.track) === storyKey(track));
800
807
  var finite = (n) => typeof n === "number" && Number.isFinite(n);
801
808
  function safeHttpUrl(value) {
802
809
  if (typeof value !== "string" || value.length > 4096) return false;
@@ -810,19 +817,39 @@ function safeHttpUrl(value) {
810
817
  function validTrack(value) {
811
818
  if (!value || typeof value !== "object") return false;
812
819
  const t = value;
813
- 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);
820
+ 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");
814
821
  }
815
822
  var copyTrack = (t) => ({
816
823
  id: t.id,
817
824
  publicationId: t.publicationId,
818
825
  title: t.title,
819
826
  ...t.publicationName ? { publicationName: t.publicationName } : {},
820
- articleUrl: t.articleUrl
827
+ articleUrl: t.articleUrl,
828
+ ...t.storyId ? { storyId: t.storyId } : {},
829
+ ...t.revision ? { revision: t.revision } : {},
830
+ ...t.durationSeconds ? { durationSeconds: t.durationSeconds } : {},
831
+ ...t.section ? { section: t.section } : {},
832
+ ...t.publishedAt ? { publishedAt: t.publishedAt } : {},
833
+ ...t.automatic ? { automatic: true } : {}
821
834
  });
822
835
  function validSnapshot(value) {
823
836
  if (!value || typeof value !== "object") return false;
824
837
  const s = value;
825
- 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);
838
+ 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);
839
+ }
840
+ function validRecord(value) {
841
+ if (!value || typeof value !== "object") return false;
842
+ const r = value;
843
+ 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);
844
+ }
845
+ function mergeRanges(ranges) {
846
+ const merged = [];
847
+ for (const [start, end] of ranges.sort((a, b) => a[0] - b[0])) {
848
+ const last = merged.at(-1);
849
+ if (last && start <= last[1] + 0.1) last[1] = Math.max(last[1], end);
850
+ else merged.push([start, end]);
851
+ }
852
+ return merged.slice(-100);
826
853
  }
827
854
  var NetworkAudioController = class {
828
855
  constructor(resolve) {
@@ -837,6 +864,7 @@ var NetworkAudioController = class {
837
864
  this.source = null;
838
865
  this.refreshed = false;
839
866
  this.resumePosition = null;
867
+ this.candidates = [];
840
868
  this.getSnapshot = () => this.snapshot;
841
869
  this.subscribe = (listener) => {
842
870
  this.listeners.add(listener);
@@ -845,6 +873,10 @@ var NetworkAudioController = class {
845
873
  };
846
874
  };
847
875
  }
876
+ mergeListeningMemory(memory) {
877
+ this.patch({ rate: memory.rate, autoplayNext: memory.autoplayNext, allowRepeats: memory.allowRepeats, settingsUpdatedAt: memory.settingsUpdatedAt, historyClearedAt: memory.historyClearedAt, history: memory.history });
878
+ if (this.audio) this.audio.playbackRate = memory.rate;
879
+ }
848
880
  setResolver(resolve) {
849
881
  this.resolve = resolve;
850
882
  }
@@ -876,7 +908,10 @@ var NetworkAudioController = class {
876
908
  if (finite(audio.duration) && audio.duration > 0) this.patch({ duration: audio.duration });
877
909
  }),
878
910
  on("timeupdate", () => {
879
- if (this.resumePosition === null) this.patch({ position: audio.currentTime });
911
+ if (this.resumePosition === null) {
912
+ this.patch({ position: audio.currentTime });
913
+ this.remember();
914
+ }
880
915
  }),
881
916
  on("playing", () => {
882
917
  if (!this.intent) {
@@ -891,11 +926,7 @@ var NetworkAudioController = class {
891
926
  }),
892
927
  on("ended", () => {
893
928
  if (!this.intent) return;
894
- if (this.snapshot.index + 1 < this.snapshot.queue.length) this.select(this.snapshot.index + 1);
895
- else {
896
- this.intent = false;
897
- this.patch({ status: "paused", position: this.snapshot.duration });
898
- }
929
+ this.finish();
899
930
  }),
900
931
  on("error", () => {
901
932
  if (this.intent && !this.request) void this.recover();
@@ -924,12 +955,23 @@ var NetworkAudioController = class {
924
955
  }
925
956
  enqueue(track) {
926
957
  if (!validTrack(track)) throw new Error("A valid publication, article identity, title and HTTP(S) article URL are required.");
927
- const found = this.snapshot.queue.findIndex((t) => trackKey(t) === trackKey(track));
958
+ this.patch({ hidden: false });
959
+ const found = this.snapshot.queue.findIndex((t) => storyKey(t) === storyKey(track));
928
960
  if (found !== -1) return found;
929
961
  if (this.snapshot.queue.length >= 100) throw new Error("The listening queue holds up to 100 articles.");
930
- const queue = [...this.snapshot.queue, copyTrack(track)];
931
- this.patch({ queue, index: this.snapshot.index === -1 ? 0 : this.snapshot.index });
932
- return queue.length - 1;
962
+ const queue = [...this.snapshot.queue];
963
+ const protectCurrent = this.source !== null || this.snapshot.status === "loading" || this.snapshot.status === "playing";
964
+ const automatic = queue.findIndex((item, i) => item.automatic && (protectCurrent ? i > this.snapshot.index : i >= this.snapshot.index));
965
+ const at = !track.automatic && automatic >= 0 ? automatic : queue.length;
966
+ queue.splice(at, 0, copyTrack(track));
967
+ const initial = this.snapshot.index === -1 || !protectCurrent && at <= this.snapshot.index;
968
+ const record = listeningRecord(this.snapshot, track);
969
+ this.patch({
970
+ queue,
971
+ index: initial ? at : this.snapshot.index,
972
+ ...initial ? { position: record?.completedAt ? 0 : record?.position ?? 0, duration: record?.duration ?? track.durationSeconds ?? 0 } : {}
973
+ });
974
+ return at;
933
975
  }
934
976
  playTrack(track) {
935
977
  const index = this.enqueue(track);
@@ -942,13 +984,16 @@ var NetworkAudioController = class {
942
984
  void this.play();
943
985
  return;
944
986
  }
987
+ this.remember();
945
988
  this.cancel();
946
989
  this.source = null;
947
- this.patch({ index, position: 0, duration: 0, error: null, status: "paused" });
990
+ const record = listeningRecord(this.snapshot, this.snapshot.queue[index]);
991
+ this.patch({ index, position: record?.completedAt ? 0 : record?.position ?? 0, duration: record?.duration ?? 0, error: null, status: "paused", hidden: false });
948
992
  void this.play();
949
993
  }
950
994
  remove(index) {
951
995
  if (!Number.isInteger(index) || index < 0 || index >= this.snapshot.queue.length) return;
996
+ this.remember();
952
997
  const wasPlaying = this.intent;
953
998
  const current = this.snapshot.index;
954
999
  const queue = this.snapshot.queue.filter((_, i) => i !== index);
@@ -958,7 +1003,9 @@ var NetworkAudioController = class {
958
1003
  }
959
1004
  this.cancel();
960
1005
  this.source = null;
961
- this.patch({ queue, index: queue.length ? Math.min(index, queue.length - 1) : -1, position: 0, duration: 0, status: "paused", error: null });
1006
+ const nextIndex = queue.length ? Math.min(index, queue.length - 1) : -1;
1007
+ const nextRecord = nextIndex >= 0 ? listeningRecord(this.snapshot, queue[nextIndex]) : void 0;
1008
+ this.patch({ queue, index: nextIndex, position: nextRecord?.completedAt ? 0 : nextRecord?.position ?? 0, duration: nextRecord?.duration ?? 0, status: "paused", error: null });
962
1009
  if (wasPlaying && queue.length) void this.play();
963
1010
  }
964
1011
  cancel() {
@@ -970,16 +1017,105 @@ var NetworkAudioController = class {
970
1017
  this.audio?.pause();
971
1018
  }
972
1019
  pause() {
1020
+ this.remember();
973
1021
  const pendingPosition = this.resumePosition;
974
1022
  this.cancel();
975
1023
  this.resumePosition = pendingPosition;
976
1024
  this.patch({ status: this.snapshot.queue.length ? "paused" : "idle" });
977
1025
  }
978
1026
  clear() {
1027
+ this.remember();
979
1028
  this.cancel();
980
1029
  this.source = null;
981
1030
  this.audio?.removeAttribute("src");
982
- this.patch({ ...EMPTY_SNAPSHOT, rate: this.snapshot.rate, volume: this.snapshot.volume });
1031
+ this.patch({ ...this.snapshot, queue: [], index: -1, position: 0, duration: 0, status: "idle", error: null, hidden: false });
1032
+ }
1033
+ close() {
1034
+ this.pause();
1035
+ this.patch({ hidden: true });
1036
+ }
1037
+ setAutoplay(value) {
1038
+ this.patch({ autoplayNext: value, settingsUpdatedAt: Date.now() });
1039
+ }
1040
+ setRepeats(value) {
1041
+ this.patch({ allowRepeats: value, settingsUpdatedAt: Date.now() });
1042
+ }
1043
+ forgetHistory() {
1044
+ this.patch({ history: [], historyClearedAt: Date.now() });
1045
+ }
1046
+ restart() {
1047
+ this.seek(0);
1048
+ void this.play();
1049
+ }
1050
+ skip() {
1051
+ this.remember({ skippedAt: Date.now() });
1052
+ this.remove(this.snapshot.index);
1053
+ }
1054
+ remember(extra = {}) {
1055
+ const track = this.snapshot.queue[this.snapshot.index];
1056
+ if (!track || !this.snapshot.duration) return;
1057
+ const previous = listeningRecord(this.snapshot, track);
1058
+ const ranges = [...previous?.ranges ?? []];
1059
+ 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))]);
1060
+ const record = {
1061
+ ...previous,
1062
+ track: copyTrack(track),
1063
+ position: this.snapshot.position,
1064
+ duration: this.snapshot.duration,
1065
+ ranges: mergeRanges(ranges),
1066
+ updatedAt: Date.now(),
1067
+ ...extra
1068
+ };
1069
+ this.patch({ history: [record, ...(this.snapshot.history ?? []).filter((item) => storyKey(item.track) !== storyKey(track))].slice(0, 500) });
1070
+ }
1071
+ finish() {
1072
+ this.remember();
1073
+ const track = this.snapshot.queue[this.snapshot.index];
1074
+ const record = track && listeningRecord(this.snapshot, track);
1075
+ const coverage = record?.ranges.reduce((sum, [start, end]) => sum + end - start, 0) ?? 0;
1076
+ if (this.snapshot.duration > 0 && coverage >= this.snapshot.duration * 0.9) this.remember({ completedAt: Date.now(), position: this.snapshot.duration });
1077
+ else {
1078
+ this.patch({ position: 0 });
1079
+ this.remember({ skippedAt: Date.now(), position: 0 });
1080
+ }
1081
+ const autoplay = this.snapshot.autoplayNext !== false;
1082
+ this.intent = false;
1083
+ this.remove(this.snapshot.index);
1084
+ if (autoplay && this.snapshot.queue.length) void this.play();
1085
+ }
1086
+ setRecommendations(tracks) {
1087
+ this.candidates = tracks.filter(validTrack).slice(0, 100);
1088
+ }
1089
+ /** Manual selections retain their order; recommendations are bounded and never replace them. */
1090
+ catchUp(minutes = 10) {
1091
+ if (![5, 10, 20].includes(minutes)) return;
1092
+ const active = this.snapshot.queue[this.snapshot.index];
1093
+ const manual = this.snapshot.queue.filter((item) => !item.automatic || item === active);
1094
+ const queueKeys = new Set(manual.map(storyKey));
1095
+ const eligible = this.candidates.filter((item) => !queueKeys.has(storyKey(item)));
1096
+ const unheard = eligible.filter((item) => {
1097
+ const record = listeningRecord(this.snapshot, item);
1098
+ return !record?.completedAt && (!record?.skippedAt || Date.now() - record.skippedAt > 864e5);
1099
+ });
1100
+ const pool = unheard.length || !this.snapshot.allowRepeats ? unheard : eligible.filter((item) => !listeningRecord(this.snapshot, item)?.skippedAt || Date.now() - listeningRecord(this.snapshot, item).skippedAt > 864e5);
1101
+ 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);
1102
+ const added = [];
1103
+ let lastSection = active?.section;
1104
+ const remaining = [...pool];
1105
+ while (remaining.length && added.length + manual.length < 100) {
1106
+ let at = remaining.findIndex((item2) => item2.section !== lastSection && (item2.durationSeconds ?? Infinity) / this.snapshot.rate <= budget);
1107
+ if (at < 0) at = remaining.findIndex((item2) => (item2.durationSeconds ?? Infinity) / this.snapshot.rate <= budget);
1108
+ if (at < 0) break;
1109
+ const [item] = remaining.splice(at, 1);
1110
+ if (queueKeys.has(storyKey(item))) continue;
1111
+ queueKeys.add(storyKey(item));
1112
+ added.push({ ...copyTrack(item), automatic: true });
1113
+ budget -= item.durationSeconds / this.snapshot.rate;
1114
+ lastSection = item.section;
1115
+ }
1116
+ const queue = [...manual, ...added];
1117
+ const firstRecord = !active && queue[0] ? listeningRecord(this.snapshot, queue[0]) : void 0;
1118
+ 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 } : {} });
983
1119
  }
984
1120
  seek(position) {
985
1121
  if (!finite(position)) return;
@@ -991,7 +1127,7 @@ var NetworkAudioController = class {
991
1127
  setRate(rate) {
992
1128
  if (!finite(rate) || rate < 0.5 || rate > 3) return;
993
1129
  if (this.audio) this.audio.playbackRate = rate;
994
- this.patch({ rate });
1130
+ this.patch({ rate, settingsUpdatedAt: Date.now() });
995
1131
  }
996
1132
  setVolume(volume) {
997
1133
  if (!finite(volume) || volume < 0 || volume > 1) return;
@@ -1010,7 +1146,22 @@ var NetworkAudioController = class {
1010
1146
  rate: snapshot.rate,
1011
1147
  volume: snapshot.volume,
1012
1148
  status: snapshot.queue.length ? "paused" : "idle",
1013
- error: null
1149
+ error: null,
1150
+ history: (snapshot.history ?? []).map((item) => ({
1151
+ track: copyTrack(item.track),
1152
+ position: item.position,
1153
+ duration: item.duration,
1154
+ ranges: item.ranges.map((range) => [...range]),
1155
+ updatedAt: item.updatedAt,
1156
+ ...item.completedAt ? { completedAt: item.completedAt } : {},
1157
+ ...item.skippedAt ? { skippedAt: item.skippedAt } : {}
1158
+ })),
1159
+ autoplayNext: snapshot.autoplayNext !== false,
1160
+ allowRepeats: snapshot.allowRepeats === true,
1161
+ hidden: snapshot.hidden === true,
1162
+ historyClearedAt: snapshot.historyClearedAt ?? 0,
1163
+ settingsUpdatedAt: snapshot.settingsUpdatedAt ?? 0,
1164
+ sessionMinutes: snapshot.sessionMinutes ?? 0
1014
1165
  });
1015
1166
  if (this.audio) {
1016
1167
  this.audio.playbackRate = snapshot.rate;
@@ -1021,7 +1172,7 @@ var NetworkAudioController = class {
1021
1172
  if (!this.audio || !this.snapshot.queue[this.snapshot.index] || this.request) return;
1022
1173
  this.intent = true;
1023
1174
  this.refreshed = false;
1024
- this.patch({ error: null });
1175
+ this.patch({ error: null, hidden: false });
1025
1176
  const expires = this.source?.expires_at ? Date.parse(this.source.expires_at) : Infinity;
1026
1177
  if (!this.source || expires <= Date.now() + 3e4) await this.load();
1027
1178
  else {
@@ -1103,7 +1254,20 @@ function runCommand(controller, command) {
1103
1254
  controller.pause();
1104
1255
  return true;
1105
1256
  case "clear":
1106
- controller.clear();
1257
+ case "close":
1258
+ case "skip":
1259
+ case "restart":
1260
+ case "forgetHistory":
1261
+ controller[c.action]();
1262
+ return true;
1263
+ case "autoplay":
1264
+ case "repeats":
1265
+ if (typeof c.value !== "boolean") return false;
1266
+ if (c.action === "autoplay") controller.setAutoplay(c.value);
1267
+ else controller.setRepeats(c.value);
1268
+ return true;
1269
+ case "catchUp":
1270
+ controller.catchUp(c.value);
1107
1271
  return true;
1108
1272
  case "enqueue":
1109
1273
  case "playTrack":
@@ -1256,16 +1420,166 @@ var NetworkPlayerClient = class {
1256
1420
  }
1257
1421
  };
1258
1422
 
1423
+ // src/network-audio/memory.ts
1424
+ function validMemory(value) {
1425
+ if (!value || typeof value !== "object") return false;
1426
+ const v = value;
1427
+ 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);
1428
+ }
1429
+ function toMemory(snapshot) {
1430
+ return {
1431
+ version: 1,
1432
+ rate: snapshot.rate,
1433
+ autoplayNext: snapshot.autoplayNext !== false,
1434
+ allowRepeats: snapshot.allowRepeats === true,
1435
+ settingsUpdatedAt: snapshot.settingsUpdatedAt ?? 0,
1436
+ historyClearedAt: snapshot.historyClearedAt ?? 0,
1437
+ history: (snapshot.history ?? []).map((item) => ({ ...item, track: copyTrack(item.track) }))
1438
+ };
1439
+ }
1440
+ function mergeMemory(local, remote) {
1441
+ const historyClearedAt = Math.max(local.historyClearedAt, remote.historyClearedAt);
1442
+ const records = /* @__PURE__ */ new Map();
1443
+ for (const item of [...remote.history, ...local.history]) {
1444
+ if (item.updatedAt <= historyClearedAt) continue;
1445
+ const key = storyKey(item.track);
1446
+ const previous = records.get(key);
1447
+ if (!previous) records.set(key, item);
1448
+ else {
1449
+ const newest = item.updatedAt >= previous.updatedAt ? item : previous;
1450
+ records.set(key, {
1451
+ ...newest,
1452
+ ranges: mergeRanges([...previous.ranges, ...item.ranges]).filter((range) => range[1] <= newest.duration + 1),
1453
+ ...previous.completedAt || item.completedAt ? { completedAt: Math.max(previous.completedAt ?? 0, item.completedAt ?? 0) } : {}
1454
+ });
1455
+ }
1456
+ }
1457
+ return {
1458
+ ...remote.settingsUpdatedAt > local.settingsUpdatedAt ? remote : local,
1459
+ historyClearedAt,
1460
+ history: [...records.values()].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 500)
1461
+ };
1462
+ }
1463
+
1464
+ // src/network-audio/persistence.ts
1465
+ function persistListening(controller, options) {
1466
+ const allowed = new Set(options.allowedOrigins);
1467
+ let ready = false;
1468
+ let iframe = null;
1469
+ let lastWrite = 0;
1470
+ let lastHubWrite = 0;
1471
+ let request = 0;
1472
+ const hubOrigin = options.hubUrl ? new URL(options.hubUrl).origin : null;
1473
+ try {
1474
+ const saved = JSON.parse(localStorage.getItem(options.storageKey) ?? "null");
1475
+ if (validSnapshot(saved) && saved.queue.every((item) => allowed.has(new URL(item.articleUrl).origin))) controller.restore(saved);
1476
+ } catch {
1477
+ }
1478
+ const url = new URL(window.location.href);
1479
+ const rate = Number(url.searchParams.get("sm_audio_rate"));
1480
+ if (url.searchParams.has("sm_audio_rate")) {
1481
+ if (rate >= 0.5 && rate <= 3) controller.setRate(rate);
1482
+ url.searchParams.delete("sm_audio_rate");
1483
+ window.history.replaceState(window.history.state, "", url);
1484
+ }
1485
+ const sync = () => {
1486
+ if (!ready || !iframe?.contentWindow || !hubOrigin) return;
1487
+ iframe.contentWindow.postMessage({
1488
+ type: "SM_LISTENING_SYNC",
1489
+ networkId: options.networkId,
1490
+ requestId: String(++request),
1491
+ memory: toMemory(controller.getSnapshot())
1492
+ }, hubOrigin);
1493
+ };
1494
+ const save = () => {
1495
+ try {
1496
+ localStorage.setItem(options.storageKey, JSON.stringify(controller.getSnapshot()));
1497
+ } catch {
1498
+ }
1499
+ };
1500
+ let previousQueue = controller.getSnapshot().queue;
1501
+ let previousCompleted = controller.getSnapshot().history?.[0]?.completedAt;
1502
+ let previousHidden = controller.getSnapshot().hidden;
1503
+ let previousClear = controller.getSnapshot().historyClearedAt;
1504
+ let previousSettings = controller.getSnapshot().settingsUpdatedAt;
1505
+ const unsubscribe = controller.subscribe(() => {
1506
+ const changed = previousSettings !== controller.getSnapshot().settingsUpdatedAt || previousClear !== controller.getSnapshot().historyClearedAt;
1507
+ const urgent = changed || previousQueue !== controller.getSnapshot().queue || previousCompleted !== controller.getSnapshot().history?.[0]?.completedAt || previousHidden !== controller.getSnapshot().hidden;
1508
+ previousQueue = controller.getSnapshot().queue;
1509
+ previousCompleted = controller.getSnapshot().history?.[0]?.completedAt;
1510
+ previousHidden = controller.getSnapshot().hidden;
1511
+ previousClear = controller.getSnapshot().historyClearedAt;
1512
+ previousSettings = controller.getSnapshot().settingsUpdatedAt;
1513
+ if (urgent || Date.now() - lastWrite > 1e3) {
1514
+ lastWrite = Date.now();
1515
+ save();
1516
+ }
1517
+ if (urgent || Date.now() - lastHubWrite > 5e3) {
1518
+ lastHubWrite = Date.now();
1519
+ sync();
1520
+ }
1521
+ });
1522
+ const receive = (event) => {
1523
+ if (!iframe || event.source !== iframe.contentWindow || event.origin !== hubOrigin) return;
1524
+ const data = event.data;
1525
+ if (data?.type !== "SM_LISTENING_STATE" || data.networkId !== options.networkId || data.requestId !== String(request) || !validMemory(data.memory)) return;
1526
+ if (!data.memory.history.every((item) => allowed.has(new URL(item.track.articleUrl).origin))) return;
1527
+ controller.mergeListeningMemory(mergeMemory(toMemory(controller.getSnapshot()), data.memory));
1528
+ };
1529
+ window.addEventListener("message", receive);
1530
+ if (options.hubUrl && hubOrigin && allowed.has(hubOrigin)) {
1531
+ iframe = document.createElement("iframe");
1532
+ iframe.src = options.hubUrl;
1533
+ iframe.hidden = true;
1534
+ iframe.title = "Shared listening preferences";
1535
+ iframe.setAttribute("aria-hidden", "true");
1536
+ iframe.onload = () => {
1537
+ ready = true;
1538
+ sync();
1539
+ };
1540
+ document.body.appendChild(iframe);
1541
+ }
1542
+ const decorate = (event) => {
1543
+ const anchor = event.target instanceof Element ? event.target.closest("a[href]") : null;
1544
+ if (!(anchor instanceof HTMLAnchorElement)) return;
1545
+ try {
1546
+ const target = new URL(anchor.href);
1547
+ if (!allowed.has(target.origin) || target.origin === window.location.origin) return;
1548
+ target.searchParams.set("sm_audio_rate", String(controller.getSnapshot().rate));
1549
+ anchor.href = target.toString();
1550
+ } catch {
1551
+ }
1552
+ };
1553
+ const flush = () => {
1554
+ save();
1555
+ sync();
1556
+ };
1557
+ document.addEventListener("click", decorate, true);
1558
+ document.addEventListener("auxclick", decorate, true);
1559
+ window.addEventListener("pagehide", flush);
1560
+ return () => {
1561
+ save();
1562
+ unsubscribe();
1563
+ iframe?.remove();
1564
+ document.removeEventListener("click", decorate, true);
1565
+ document.removeEventListener("auxclick", decorate, true);
1566
+ window.removeEventListener("pagehide", flush);
1567
+ window.removeEventListener("message", receive);
1568
+ };
1569
+ }
1570
+
1259
1571
  // src/components/network-audio-player.tsx
1260
1572
  import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1261
1573
  var Context = createContext(null);
1262
1574
  var NarrationRegistration = createContext(null);
1263
1575
  var serverSnapshot = () => EMPTY_SNAPSHOT;
1264
- function NetworkAudioProvider({ children, resolveAudio, connection, host, checkpointStorageKey }) {
1576
+ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkpointStorageKey, persistence, loadRecommendations }) {
1265
1577
  if (connection && host) throw new Error("Use connection on reader pages and host on the dedicated player route, not both.");
1266
1578
  const [controller] = useState2(() => new NetworkAudioController(resolveAudio));
1267
1579
  const snapshot = useSyncExternalStore2(controller.subscribe, controller.getSnapshot, serverSnapshot);
1268
1580
  const [remoteSnapshot, setRemoteSnapshot] = useState2(null);
1581
+ const [recommendationsLoading, setRecommendationsLoading] = useState2(false);
1582
+ const recommendationRequest = useRef2(null);
1269
1583
  const [notice, setNotice] = useState2(null);
1270
1584
  const [highlightEnabled, setHighlightEnabled] = useState2(false);
1271
1585
  const [narrationTracks, setNarrationTracks] = useState2(() => /* @__PURE__ */ new Map());
@@ -1314,6 +1628,32 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1314
1628
  window.removeEventListener("pagehide", save);
1315
1629
  };
1316
1630
  }, [controller, checkpointStorageKey]);
1631
+ const persistenceOrigins = JSON.stringify(persistence?.allowedOrigins ?? []);
1632
+ useEffect2(() => {
1633
+ if (persistence) return persistListening(controller, { ...persistence, allowedOrigins: JSON.parse(persistenceOrigins) });
1634
+ }, [controller, persistence?.storageKey, persistence?.networkId, persistence?.hubUrl, persistenceOrigins]);
1635
+ useEffect2(() => () => recommendationRequest.current?.abort(), []);
1636
+ const catchUp = useCallback(async (minutes) => {
1637
+ if (!loadRecommendations) return;
1638
+ recommendationRequest.current?.abort();
1639
+ const request = new AbortController();
1640
+ recommendationRequest.current = request;
1641
+ setRecommendationsLoading(true);
1642
+ setNotice(null);
1643
+ const timeout = setTimeout(() => request.abort(), 2e4);
1644
+ try {
1645
+ const tracks = await loadRecommendations(request.signal);
1646
+ if (request.signal.aborted) return;
1647
+ controller.setRecommendations(tracks.filter(validTrack));
1648
+ controller.catchUp(minutes);
1649
+ if (!controller.getSnapshot().queue.length) setNotice("No stories available for this queue. Try a longer session or replay a story from Recently listened.");
1650
+ } catch {
1651
+ if (recommendationRequest.current === request) setNotice("Could not load your catch-up queue. Your saved queue is still here. Please try again.");
1652
+ } finally {
1653
+ clearTimeout(timeout);
1654
+ if (recommendationRequest.current === request) setRecommendationsLoading(false);
1655
+ }
1656
+ }, [controller, loadRecommendations]);
1317
1657
  const allowedOrigins = JSON.stringify(host?.allowedOrigins ?? []);
1318
1658
  useEffect2(() => {
1319
1659
  if (!host) return;
@@ -1334,6 +1674,7 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1334
1674
  const command = useCallback((value) => {
1335
1675
  setNotice(null);
1336
1676
  try {
1677
+ if (value.action === "close") setHighlightEnabled(false);
1337
1678
  if (!client.current?.command(value)) runCommand(controller, value);
1338
1679
  } catch (error) {
1339
1680
  setNotice(error instanceof Error ? error.message : "The article could not be added.");
@@ -1352,7 +1693,9 @@ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkp
1352
1693
  openNetworkPlayer: connection ? openNetworkPlayer : void 0,
1353
1694
  highlightAvailable,
1354
1695
  highlightEnabled,
1355
- setHighlightEnabled
1696
+ setHighlightEnabled,
1697
+ catchUp: loadRecommendations ? catchUp : void 0,
1698
+ recommendationsLoading
1356
1699
  }, children: /* @__PURE__ */ jsxs2(NarrationRegistration.Provider, { value: registerNarration, children: [
1357
1700
  /* @__PURE__ */ jsx2(NetworkMediaSession, {}),
1358
1701
  children
@@ -1428,7 +1771,7 @@ function useArticleNarration(track, narration) {
1428
1771
  clock.current = { snapshot, received: performance.now() };
1429
1772
  }, [snapshot]);
1430
1773
  useEffect2(() => {
1431
- if (!narration || !matching || !highlightEnabled || !supported) return;
1774
+ if (!narration || !matching || !highlightEnabled || !supported || snapshot.hidden) return;
1432
1775
  const controller = new AbortController();
1433
1776
  let highlighter = null;
1434
1777
  let frame = 0;
@@ -1471,7 +1814,7 @@ function useArticleNarration(track, narration) {
1471
1814
  highlighter?.destroy();
1472
1815
  document.removeEventListener("visibilitychange", visibility);
1473
1816
  };
1474
- }, [matching, highlightEnabled, supported, narration?.targetId, narration?.timingsUrl, track.id, track.publicationId]);
1817
+ }, [snapshot.hidden, matching, highlightEnabled, supported, narration?.targetId, narration?.timingsUrl, track.id, track.publicationId]);
1475
1818
  return { highlightAvailable: !!narration && supported, highlightEnabled, setHighlightEnabled, matching };
1476
1819
  }
1477
1820
  function AudioIcon({ name }) {
@@ -1486,7 +1829,8 @@ function AudioIcon({ name }) {
1486
1829
  /* @__PURE__ */ jsx2("path", { d: "M19 5v14" })
1487
1830
  ] }),
1488
1831
  name === "chevron" && /* @__PURE__ */ jsx2("path", { d: "m7 10 5 5 5-5" }),
1489
- name === "external" && /* @__PURE__ */ jsx2("path", { d: "M14 4h6v6m0-6L10 14m10 1v5H4V4h5" })
1832
+ name === "external" && /* @__PURE__ */ jsx2("path", { d: "M14 4h6v6m0-6L10 14m10 1v5H4V4h5" }),
1833
+ name === "close" && /* @__PURE__ */ jsx2("path", { d: "m6 6 12 12M18 6 6 18" })
1490
1834
  ] });
1491
1835
  }
1492
1836
  var formatTime = (seconds) => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
@@ -1495,56 +1839,72 @@ function ArticleAudioControls({ track, narration, durationMs, className = "" })
1495
1839
  const { snapshot, command } = useNetworkAudio();
1496
1840
  const { highlightAvailable, highlightEnabled, setHighlightEnabled, matching } = useArticleNarration(track, narration);
1497
1841
  const playing = matching && (snapshot.status === "playing" || snapshot.status === "loading");
1498
- const queued = snapshot.queue.some((item) => trackKey(item) === trackKey(track));
1842
+ const record = listeningRecord(snapshot, track);
1843
+ const resume = !record?.completedAt && (matching ? snapshot.position : record?.position ?? 0) > 2;
1844
+ const updated = !record && snapshot.history?.some((item) => item.completedAt && item.track.storyId && item.track.storyId === track.storyId);
1845
+ const caption = playing ? "Pause this story" : record?.completedAt ? "Listen again" : resume ? "Resume this story" : "Listen to this story";
1846
+ const queued = snapshot.queue.some((item) => storyKey(item) === storyKey(track));
1499
1847
  const duration = matching && snapshot.duration > 0 ? snapshot.duration : (durationMs ?? 0) / 1e3;
1500
- return /* @__PURE__ */ jsxs2("div", { className: `sm-network-article ${className}`, role: "group", "aria-label": "Article audio", children: [
1501
- /* @__PURE__ */ jsxs2(
1502
- "button",
1503
- {
1504
- type: "button",
1505
- className: "sm-network-article__listen",
1506
- "aria-label": playing ? "Pause this story" : "Listen to this story",
1507
- onClick: () => command(playing ? { action: "pause" } : { action: "playTrack", track }),
1508
- children: [
1509
- /* @__PURE__ */ jsx2("span", { className: "sm-network-article__disc", children: /* @__PURE__ */ jsx2(AudioIcon, { name: playing ? "pause" : "play" }) }),
1510
- /* @__PURE__ */ jsxs2("span", { className: "sm-network-article__caption", children: [
1511
- /* @__PURE__ */ jsx2("span", { children: playing ? "Pause this story" : "Listen to this story" }),
1512
- /* @__PURE__ */ jsx2("span", { className: "sm-network-article__duration", children: matching && snapshot.status === "loading" ? "Loading audio\u2026" : duration > 0 ? `${formatTime(duration)} listening time` : "Article audio" })
1513
- ] })
1514
- ]
1515
- }
1516
- ),
1517
- /* @__PURE__ */ jsxs2("div", { className: "sm-network-article__actions", children: [
1848
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
1849
+ /* @__PURE__ */ jsxs2("div", { className: `sm-network-article ${className}`, role: "group", "aria-label": "Article audio", children: [
1518
1850
  /* @__PURE__ */ jsxs2(
1519
1851
  "button",
1520
1852
  {
1521
1853
  type: "button",
1522
- className: "sm-network-article__queue",
1523
- "aria-label": queued ? "Queued" : "Add to queue",
1524
- disabled: queued,
1525
- onClick: () => command({ action: "enqueue", track }),
1854
+ className: "sm-network-article__listen",
1855
+ "aria-label": caption,
1856
+ onClick: () => command(playing ? { action: "pause" } : { action: "playTrack", track }),
1526
1857
  children: [
1527
- /* @__PURE__ */ jsx2(AudioIcon, { name: queued ? "check" : "queue" }),
1528
- /* @__PURE__ */ jsx2("span", { children: queued ? "Queued" : "Queue" })
1858
+ /* @__PURE__ */ jsx2("span", { className: "sm-network-article__disc", children: /* @__PURE__ */ jsx2(AudioIcon, { name: playing ? "pause" : "play" }) }),
1859
+ /* @__PURE__ */ jsxs2("span", { className: "sm-network-article__caption", children: [
1860
+ /* @__PURE__ */ jsx2("span", { children: caption }),
1861
+ updated && /* @__PURE__ */ jsx2("small", { children: "Updated since you listened" }),
1862
+ /* @__PURE__ */ jsx2("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" })
1863
+ ] })
1529
1864
  ]
1530
1865
  }
1531
1866
  ),
1532
- highlightAvailable && /* @__PURE__ */ jsxs2(
1533
- "button",
1534
- {
1535
- type: "button",
1536
- "aria-label": "Follow along: highlight words",
1537
- "aria-pressed": highlightEnabled,
1538
- title: "Highlight words as you listen",
1539
- onClick: () => setHighlightEnabled(!highlightEnabled),
1540
- children: [
1541
- /* @__PURE__ */ jsx2(AudioIcon, { name: "highlight" }),
1542
- /* @__PURE__ */ jsx2("span", { children: "Follow along" }),
1543
- /* @__PURE__ */ jsx2("span", { className: "sm-network-toggle", "aria-hidden": "true" })
1544
- ]
1545
- }
1546
- )
1547
- ] })
1867
+ /* @__PURE__ */ jsxs2("div", { className: "sm-network-article__actions", children: [
1868
+ /* @__PURE__ */ jsxs2("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: [
1869
+ snapshot.rate,
1870
+ "\xD7"
1871
+ ] }),
1872
+ resume && /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => {
1873
+ command({ action: "playTrack", track });
1874
+ command({ action: "restart" });
1875
+ }, children: "Start over" }),
1876
+ /* @__PURE__ */ jsxs2(
1877
+ "button",
1878
+ {
1879
+ type: "button",
1880
+ className: "sm-network-article__queue",
1881
+ "aria-label": queued ? "Queued" : "Add to queue",
1882
+ disabled: queued,
1883
+ onClick: () => command({ action: "enqueue", track }),
1884
+ children: [
1885
+ /* @__PURE__ */ jsx2(AudioIcon, { name: queued ? "check" : "queue" }),
1886
+ /* @__PURE__ */ jsx2("span", { children: queued ? "Queued" : "Queue" })
1887
+ ]
1888
+ }
1889
+ ),
1890
+ highlightAvailable && /* @__PURE__ */ jsxs2(
1891
+ "button",
1892
+ {
1893
+ type: "button",
1894
+ "aria-label": "Follow along: highlight words",
1895
+ "aria-pressed": highlightEnabled,
1896
+ title: "Highlight words as you listen",
1897
+ onClick: () => setHighlightEnabled(!highlightEnabled),
1898
+ children: [
1899
+ /* @__PURE__ */ jsx2(AudioIcon, { name: "highlight" }),
1900
+ /* @__PURE__ */ jsx2("span", { children: "Follow along" }),
1901
+ /* @__PURE__ */ jsx2("span", { className: "sm-network-toggle", "aria-hidden": "true" })
1902
+ ]
1903
+ }
1904
+ )
1905
+ ] })
1906
+ ] }),
1907
+ /* @__PURE__ */ jsx2(ListeningLibrary, {})
1548
1908
  ] });
1549
1909
  }
1550
1910
  function NetworkAudioPlayer({ networkName = "Your listening queue", advertisement, className = "", style, fixed = true, renderArticleLink }) {
@@ -1569,7 +1929,7 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1569
1929
  observer.observe(element);
1570
1930
  return () => observer.disconnect();
1571
1931
  }, [fixed, !!track, expanded, notice, snapshot.error]);
1572
- if (!track) return notice ? /* @__PURE__ */ jsx2("p", { role: "status", children: notice }) : null;
1932
+ if (!track || snapshot.hidden) return notice ? /* @__PURE__ */ jsx2("p", { role: "status", children: notice }) : null;
1573
1933
  return /* @__PURE__ */ jsxs2(Fragment, { children: [
1574
1934
  fixed && /* @__PURE__ */ jsx2("div", { "aria-hidden": "true", style: { height } }),
1575
1935
  /* @__PURE__ */ jsxs2("section", { ref: bar, className: `sm-network-player ${fixed ? "sm-network-player--fixed" : ""} ${className}`, style, "aria-label": "Network audio player", children: [
@@ -1628,8 +1988,7 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1628
1988
  className: "sm-network-player__next",
1629
1989
  "aria-label": "Next article",
1630
1990
  title: "Next article",
1631
- disabled: snapshot.index + 1 >= snapshot.queue.length,
1632
- onClick: () => command({ action: "select", value: snapshot.index + 1 }),
1991
+ onClick: () => command({ action: "skip" }),
1633
1992
  children: /* @__PURE__ */ jsx2(AudioIcon, { name: "next" })
1634
1993
  }
1635
1994
  ),
@@ -1650,7 +2009,21 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1650
2009
  ]
1651
2010
  }
1652
2011
  )
1653
- ] })
2012
+ ] }),
2013
+ /* @__PURE__ */ jsx2(
2014
+ "button",
2015
+ {
2016
+ type: "button",
2017
+ className: "sm-network-player__close",
2018
+ "aria-label": "Close player",
2019
+ title: "Pause and close player. Your queue is saved.",
2020
+ onClick: () => {
2021
+ setExpanded(false);
2022
+ command({ action: "close" });
2023
+ },
2024
+ children: /* @__PURE__ */ jsx2(AudioIcon, { name: "close" })
2025
+ }
2026
+ )
1654
2027
  ] }),
1655
2028
  (notice || snapshot.error) && /* @__PURE__ */ jsx2("p", { role: "status", className: "sm-network-player__notice", children: notice ?? snapshot.error }),
1656
2029
  /* @__PURE__ */ jsxs2("div", { id: detailsId, hidden: !expanded, className: "sm-network-player__details", children: [
@@ -1667,6 +2040,10 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1667
2040
  /* @__PURE__ */ jsx2(AudioIcon, { name: "chevron" })
1668
2041
  ] })
1669
2042
  ] }),
2043
+ /* @__PURE__ */ jsxs2("label", { children: [
2044
+ /* @__PURE__ */ jsx2("input", { type: "checkbox", checked: snapshot.autoplayNext !== false, onChange: (e) => command({ action: "autoplay", value: e.target.checked }) }),
2045
+ "Play next automatically"
2046
+ ] }),
1670
2047
  /* @__PURE__ */ jsxs2("label", { children: [
1671
2048
  "Volume ",
1672
2049
  /* @__PURE__ */ jsx2("input", { type: "range", min: "0", max: "1", step: "0.05", value: snapshot.volume, onChange: (e) => command({ action: "volume", value: Number(e.target.value) }) })
@@ -1700,9 +2077,72 @@ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisemen
1700
2077
  ] })
1701
2078
  ] });
1702
2079
  }
2080
+ function ListeningLibrary({ open = false }) {
2081
+ const { snapshot, command, catchUp, recommendationsLoading, remote, notice } = useNetworkAudio();
2082
+ const [minutes, setMinutes] = useState2(10);
2083
+ const recent = (snapshot.history ?? []).filter((item) => item.completedAt).slice(0, 20);
2084
+ return /* @__PURE__ */ jsxs2("details", { className: "sm-listening-library", open: open || void 0, children: [
2085
+ /* @__PURE__ */ jsxs2("summary", { children: [
2086
+ "Your listening ",
2087
+ /* @__PURE__ */ jsx2("span", { children: snapshot.queue.length ? `${snapshot.queue.length} queued` : recent.length ? "Recently listened" : "Queue & catch up" })
2088
+ ] }),
2089
+ /* @__PURE__ */ jsxs2("div", { className: "sm-listening-library__body", children: [
2090
+ catchUp && !remote && /* @__PURE__ */ jsxs2("div", { className: "sm-listening-library__catchup", children: [
2091
+ /* @__PURE__ */ jsxs2("label", { children: [
2092
+ "Catch me up in ",
2093
+ /* @__PURE__ */ jsx2("select", { "aria-label": "Catch-up length", value: minutes, onChange: (e) => setMinutes(Number(e.target.value)), children: [5, 10, 20].map((value) => /* @__PURE__ */ jsxs2("option", { value, children: [
2094
+ value,
2095
+ " minutes"
2096
+ ] }, value)) })
2097
+ ] }),
2098
+ /* @__PURE__ */ jsx2("button", { type: "button", disabled: recommendationsLoading, onClick: () => void catchUp(minutes), children: recommendationsLoading ? "Finding stories\u2026" : "Build my queue" }),
2099
+ /* @__PURE__ */ jsxs2("small", { children: [
2100
+ "Unheard stories first, timed at ",
2101
+ snapshot.rate,
2102
+ "\xD7. Your selections stay first."
2103
+ ] })
2104
+ ] }),
2105
+ /* @__PURE__ */ jsxs2("label", { className: "sm-listening-library__option", children: [
2106
+ /* @__PURE__ */ jsx2("input", { type: "checkbox", checked: snapshot.allowRepeats === true, onChange: (e) => command({ action: "repeats", value: e.target.checked }) }),
2107
+ "Include repeats when I\u2019m caught up"
2108
+ ] }),
2109
+ /* @__PURE__ */ jsxs2("label", { className: "sm-listening-library__option", children: [
2110
+ /* @__PURE__ */ jsx2("input", { type: "checkbox", checked: snapshot.autoplayNext !== false, onChange: (e) => command({ action: "autoplay", value: e.target.checked }) }),
2111
+ "Play next automatically"
2112
+ ] }),
2113
+ notice && /* @__PURE__ */ jsx2("p", { role: "status", children: notice }),
2114
+ snapshot.queue.length > 0 && /* @__PURE__ */ jsxs2(Fragment, { children: [
2115
+ /* @__PURE__ */ jsx2("h3", { children: "Up next" }),
2116
+ /* @__PURE__ */ jsxs2("p", { children: [
2117
+ snapshot.queue.length,
2118
+ " stories \xB7 ",
2119
+ formatTime(snapshot.queue.reduce((sum, item, index) => sum + Math.max(0, (item.durationSeconds ?? 0) - (index === snapshot.index ? snapshot.position : 0)) / snapshot.rate, 0)),
2120
+ " at ",
2121
+ snapshot.rate,
2122
+ "\xD7"
2123
+ ] }),
2124
+ /* @__PURE__ */ jsx2("ol", { children: snapshot.queue.map((item, index) => /* @__PURE__ */ jsxs2("li", { children: [
2125
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => command({ action: "select", value: index }), children: item.title }),
2126
+ /* @__PURE__ */ jsx2("button", { type: "button", "aria-label": `Remove ${item.title}`, onClick: () => command({ action: "remove", value: index }), children: "Remove" })
2127
+ ] }, trackKey(item))) }),
2128
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => command({ action: "clear" }), children: "Clear queue" })
2129
+ ] }),
2130
+ recent.length > 0 && /* @__PURE__ */ jsxs2(Fragment, { children: [
2131
+ /* @__PURE__ */ jsx2("h3", { children: "Recently listened" }),
2132
+ /* @__PURE__ */ jsx2("ol", { children: recent.map((item) => /* @__PURE__ */ jsxs2("li", { children: [
2133
+ /* @__PURE__ */ jsx2("span", { children: item.track.title }),
2134
+ /* @__PURE__ */ jsx2("button", { type: "button", "aria-label": `Replay ${item.track.title}`, onClick: () => command({ action: "playTrack", track: { ...item.track, automatic: false } }), children: "Replay" })
2135
+ ] }, storyKey(item.track))) })
2136
+ ] }),
2137
+ recent.length > 0 && /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => command({ action: "forgetHistory" }), children: "Clear listening history" }),
2138
+ !snapshot.queue.length && !notice && /* @__PURE__ */ jsx2("p", { children: recent.length ? "You\u2019re caught up with your queue." : "Add a story or build a catch-up queue to start listening." })
2139
+ ] })
2140
+ ] });
2141
+ }
1703
2142
  export {
1704
2143
  ArticleAudioControls,
1705
2144
  AudioPlayer,
2145
+ ListeningLibrary,
1706
2146
  NarrationHighlighter,
1707
2147
  NetworkAudioController,
1708
2148
  NetworkAudioPlayer,