@scalemule/nextjs 0.1.48 → 0.1.50

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
@@ -772,11 +772,798 @@ function PlayerSession({
772
772
  }
773
773
  );
774
774
  }
775
+
776
+ // src/components/network-audio-player.tsx
777
+ import {
778
+ createContext,
779
+ useCallback,
780
+ useContext,
781
+ useEffect as useEffect2,
782
+ useId as useId2,
783
+ useRef as useRef2,
784
+ useState as useState2,
785
+ useSyncExternalStore as useSyncExternalStore2
786
+ } from "react";
787
+
788
+ // src/network-audio/controller.ts
789
+ var EMPTY_SNAPSHOT = {
790
+ queue: [],
791
+ index: -1,
792
+ position: 0,
793
+ duration: 0,
794
+ rate: 1,
795
+ volume: 1,
796
+ status: "idle",
797
+ error: null
798
+ };
799
+ var trackKey = (track) => JSON.stringify([track.publicationId, track.id]);
800
+ var finite = (n) => typeof n === "number" && Number.isFinite(n);
801
+ function safeHttpUrl(value) {
802
+ if (typeof value !== "string" || value.length > 4096) return false;
803
+ try {
804
+ const url = new URL(value);
805
+ return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password;
806
+ } catch {
807
+ return false;
808
+ }
809
+ }
810
+ function validTrack(value) {
811
+ if (!value || typeof value !== "object") return false;
812
+ 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);
814
+ }
815
+ var copyTrack = (t) => ({
816
+ id: t.id,
817
+ publicationId: t.publicationId,
818
+ title: t.title,
819
+ ...t.publicationName ? { publicationName: t.publicationName } : {},
820
+ articleUrl: t.articleUrl
821
+ });
822
+ function validSnapshot(value) {
823
+ if (!value || typeof value !== "object") return false;
824
+ 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);
826
+ }
827
+ var NetworkAudioController = class {
828
+ constructor(resolve) {
829
+ this.resolve = resolve;
830
+ this.snapshot = EMPTY_SNAPSHOT;
831
+ this.listeners = /* @__PURE__ */ new Set();
832
+ this.audio = null;
833
+ this.cleanup = null;
834
+ this.request = null;
835
+ this.generation = 0;
836
+ this.intent = false;
837
+ this.source = null;
838
+ this.refreshed = false;
839
+ this.resumePosition = null;
840
+ this.getSnapshot = () => this.snapshot;
841
+ this.subscribe = (listener) => {
842
+ this.listeners.add(listener);
843
+ return () => {
844
+ this.listeners.delete(listener);
845
+ };
846
+ };
847
+ }
848
+ setResolver(resolve) {
849
+ this.resolve = resolve;
850
+ }
851
+ patch(patch) {
852
+ this.snapshot = { ...this.snapshot, ...patch };
853
+ this.listeners.forEach((listener) => listener());
854
+ }
855
+ attach(audio) {
856
+ this.detach();
857
+ this.audio = audio;
858
+ audio.preload = "metadata";
859
+ audio.playbackRate = this.snapshot.rate;
860
+ audio.volume = this.snapshot.volume;
861
+ const on = (name, fn) => {
862
+ audio.addEventListener(name, fn);
863
+ return () => audio.removeEventListener(name, fn);
864
+ };
865
+ const off = [
866
+ on("loadedmetadata", () => {
867
+ const duration = finite(audio.duration) && audio.duration > 0 ? audio.duration : this.snapshot.duration;
868
+ if (this.resumePosition !== null) {
869
+ audio.currentTime = duration > 0 ? Math.min(this.resumePosition, duration) : this.resumePosition;
870
+ this.resumePosition = null;
871
+ }
872
+ audio.playbackRate = this.snapshot.rate;
873
+ this.patch({ duration, position: audio.currentTime });
874
+ }),
875
+ on("durationchange", () => {
876
+ if (finite(audio.duration) && audio.duration > 0) this.patch({ duration: audio.duration });
877
+ }),
878
+ on("timeupdate", () => {
879
+ if (this.resumePosition === null) this.patch({ position: audio.currentTime });
880
+ }),
881
+ on("playing", () => {
882
+ if (!this.intent) {
883
+ audio.pause();
884
+ return;
885
+ }
886
+ this.patch({ status: "playing", error: null });
887
+ document.dispatchEvent(new CustomEvent("scalemule:audio:play", { detail: audio }));
888
+ }),
889
+ on("pause", () => {
890
+ if (this.snapshot.status === "playing") this.patch({ status: "paused" });
891
+ }),
892
+ on("ended", () => {
893
+ 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
+ }
899
+ }),
900
+ on("error", () => {
901
+ if (this.intent && !this.request) void this.recover();
902
+ })
903
+ ];
904
+ const exclusive = (event) => {
905
+ if (event.detail !== audio) this.pause();
906
+ };
907
+ document.addEventListener("scalemule:audio:play", exclusive);
908
+ this.cleanup = () => {
909
+ off.forEach((fn) => fn());
910
+ document.removeEventListener("scalemule:audio:play", exclusive);
911
+ };
912
+ }
913
+ detach() {
914
+ this.generation++;
915
+ this.intent = false;
916
+ this.request?.abort();
917
+ this.request = null;
918
+ this.cleanup?.();
919
+ this.cleanup = null;
920
+ this.audio?.pause();
921
+ this.audio?.removeAttribute("src");
922
+ this.audio = null;
923
+ this.source = null;
924
+ }
925
+ enqueue(track) {
926
+ 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));
928
+ if (found !== -1) return found;
929
+ 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;
933
+ }
934
+ playTrack(track) {
935
+ const index = this.enqueue(track);
936
+ if (index === this.snapshot.index) void this.play();
937
+ else this.select(index);
938
+ }
939
+ select(index) {
940
+ if (!Number.isInteger(index) || index < 0 || index >= this.snapshot.queue.length) return;
941
+ if (index === this.snapshot.index) {
942
+ void this.play();
943
+ return;
944
+ }
945
+ this.cancel();
946
+ this.source = null;
947
+ this.patch({ index, position: 0, duration: 0, error: null, status: "paused" });
948
+ void this.play();
949
+ }
950
+ remove(index) {
951
+ if (!Number.isInteger(index) || index < 0 || index >= this.snapshot.queue.length) return;
952
+ const wasPlaying = this.intent;
953
+ const current = this.snapshot.index;
954
+ const queue = this.snapshot.queue.filter((_, i) => i !== index);
955
+ if (index !== current) {
956
+ this.patch({ queue, index: index < current ? current - 1 : current });
957
+ return;
958
+ }
959
+ this.cancel();
960
+ 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 });
962
+ if (wasPlaying && queue.length) void this.play();
963
+ }
964
+ cancel() {
965
+ this.intent = false;
966
+ this.generation++;
967
+ this.request?.abort();
968
+ this.request = null;
969
+ this.resumePosition = null;
970
+ this.audio?.pause();
971
+ }
972
+ pause() {
973
+ const pendingPosition = this.resumePosition;
974
+ this.cancel();
975
+ this.resumePosition = pendingPosition;
976
+ this.patch({ status: this.snapshot.queue.length ? "paused" : "idle" });
977
+ }
978
+ clear() {
979
+ this.cancel();
980
+ this.source = null;
981
+ this.audio?.removeAttribute("src");
982
+ this.patch({ ...EMPTY_SNAPSHOT, rate: this.snapshot.rate, volume: this.snapshot.volume });
983
+ }
984
+ seek(position) {
985
+ if (!finite(position)) return;
986
+ const value = Math.max(0, this.snapshot.duration ? Math.min(position, this.snapshot.duration) : position);
987
+ if (this.audio?.readyState && this.source) this.audio.currentTime = value;
988
+ else this.resumePosition = value;
989
+ this.patch({ position: value });
990
+ }
991
+ setRate(rate) {
992
+ if (!finite(rate) || rate < 0.5 || rate > 3) return;
993
+ if (this.audio) this.audio.playbackRate = rate;
994
+ this.patch({ rate });
995
+ }
996
+ setVolume(volume) {
997
+ if (!finite(volume) || volume < 0 || volume > 1) return;
998
+ if (this.audio) this.audio.volume = volume;
999
+ this.patch({ volume });
1000
+ }
1001
+ restore(snapshot) {
1002
+ if (!validSnapshot(snapshot)) return;
1003
+ this.cancel();
1004
+ this.source = null;
1005
+ this.patch({
1006
+ queue: snapshot.queue.map(copyTrack),
1007
+ index: snapshot.index,
1008
+ position: snapshot.position,
1009
+ duration: snapshot.duration,
1010
+ rate: snapshot.rate,
1011
+ volume: snapshot.volume,
1012
+ status: snapshot.queue.length ? "paused" : "idle",
1013
+ error: null
1014
+ });
1015
+ if (this.audio) {
1016
+ this.audio.playbackRate = snapshot.rate;
1017
+ this.audio.volume = snapshot.volume;
1018
+ }
1019
+ }
1020
+ async play() {
1021
+ if (!this.audio || !this.snapshot.queue[this.snapshot.index] || this.request) return;
1022
+ this.intent = true;
1023
+ this.refreshed = false;
1024
+ this.patch({ error: null });
1025
+ const expires = this.source?.expires_at ? Date.parse(this.source.expires_at) : Infinity;
1026
+ if (!this.source || expires <= Date.now() + 3e4) await this.load();
1027
+ else {
1028
+ if (this.snapshot.duration && this.snapshot.position >= this.snapshot.duration) this.seek(0);
1029
+ await this.start(this.generation);
1030
+ }
1031
+ }
1032
+ async load() {
1033
+ const track = this.snapshot.queue[this.snapshot.index];
1034
+ if (!track || !this.audio) return;
1035
+ const generation = ++this.generation;
1036
+ const request = new AbortController();
1037
+ this.request?.abort();
1038
+ this.request = request;
1039
+ this.patch({ status: "loading", error: null });
1040
+ let timeout;
1041
+ try {
1042
+ const source = await Promise.race([
1043
+ this.resolve(track, request.signal),
1044
+ new Promise((_, reject) => {
1045
+ timeout = setTimeout(() => {
1046
+ request.abort();
1047
+ reject(new Error("Audio request timed out"));
1048
+ }, 15e3);
1049
+ })
1050
+ ]);
1051
+ if (generation !== this.generation || request.signal.aborted || !this.audio) return;
1052
+ if (!safeHttpUrl(source.url)) throw new Error("No playable audio source");
1053
+ this.source = source;
1054
+ this.resumePosition = this.snapshot.position;
1055
+ this.audio.src = source.url;
1056
+ this.audio.playbackRate = this.snapshot.rate;
1057
+ this.audio.volume = this.snapshot.volume;
1058
+ this.patch({ duration: source.duration_ms && source.duration_ms > 0 ? source.duration_ms / 1e3 : 0 });
1059
+ this.request = null;
1060
+ await this.start(generation);
1061
+ } catch {
1062
+ if (generation === this.generation) this.fail("This article could not be loaded. Try playing it again or choose another article.");
1063
+ } finally {
1064
+ clearTimeout(timeout);
1065
+ if (this.request === request) this.request = null;
1066
+ }
1067
+ }
1068
+ async start(generation) {
1069
+ if (!this.intent || !this.audio) return;
1070
+ try {
1071
+ await this.audio.play();
1072
+ } catch (error) {
1073
+ if (generation !== this.generation || !this.intent) return;
1074
+ if (error.name === "NotAllowedError") this.fail("Press Play here to continue listening.");
1075
+ else await this.recover();
1076
+ }
1077
+ }
1078
+ async recover() {
1079
+ if (this.refreshed) {
1080
+ this.fail("Audio playback stopped. Try playing again or choose another article.");
1081
+ return;
1082
+ }
1083
+ this.refreshed = true;
1084
+ await this.load();
1085
+ }
1086
+ fail(error) {
1087
+ this.intent = false;
1088
+ this.audio?.pause();
1089
+ this.patch({ status: "error", error });
1090
+ }
1091
+ };
1092
+
1093
+ // src/network-audio/bridge.ts
1094
+ var PROTOCOL = "scalemule:network-audio:v1";
1095
+ function runCommand(controller, command) {
1096
+ if (!command || typeof command !== "object") return false;
1097
+ const c = command;
1098
+ switch (c.action) {
1099
+ case "play":
1100
+ void controller.play();
1101
+ return true;
1102
+ case "pause":
1103
+ controller.pause();
1104
+ return true;
1105
+ case "clear":
1106
+ controller.clear();
1107
+ return true;
1108
+ case "enqueue":
1109
+ case "playTrack":
1110
+ if (!validTrack(c.track)) return false;
1111
+ controller[c.action](c.track);
1112
+ return true;
1113
+ case "select":
1114
+ case "remove":
1115
+ case "seek":
1116
+ case "rate":
1117
+ case "volume":
1118
+ if (!Number.isFinite(c.value)) return false;
1119
+ if (c.action === "rate") controller.setRate(c.value);
1120
+ else if (c.action === "volume") controller.setVolume(c.value);
1121
+ else controller[c.action](c.value);
1122
+ return true;
1123
+ default:
1124
+ return false;
1125
+ }
1126
+ }
1127
+ function hostNetworkPlayer(controller, options) {
1128
+ const origins = new Set(options.allowedOrigins.map((value) => {
1129
+ if (!safeHttpUrl(value) || new URL(value).origin !== value) throw new Error("Use exact HTTP(S) origins for the network player.");
1130
+ return value;
1131
+ }));
1132
+ const reader = window.opener;
1133
+ if (!reader) return () => {
1134
+ };
1135
+ const trackAllowed = (t) => origins.has(new URL(t.articleUrl).origin);
1136
+ const send = () => {
1137
+ if (reader.closed) return;
1138
+ const data = { protocol: PROTOCOL, networkId: options.networkId, kind: "state", snapshot: controller.getSnapshot() };
1139
+ origins.forEach((origin) => reader.postMessage(data, origin));
1140
+ };
1141
+ const receive = (event) => {
1142
+ if (event.source !== reader || !origins.has(event.origin)) return;
1143
+ const data = event.data;
1144
+ if (!data || data.protocol !== PROTOCOL || data.networkId !== options.networkId) return;
1145
+ try {
1146
+ if (data.kind === "adopt" && validSnapshot(data.snapshot) && data.snapshot.queue.every(trackAllowed) && !controller.getSnapshot().queue.length) {
1147
+ controller.restore(data.snapshot);
1148
+ if (data.play === true) void controller.play();
1149
+ } else if (data.kind === "command") {
1150
+ const command = data.command;
1151
+ if (command && (command.action === "enqueue" || command.action === "playTrack") && (!validTrack(command.track) || !trackAllowed(command.track))) return;
1152
+ runCommand(controller, command);
1153
+ }
1154
+ } catch {
1155
+ reader.postMessage({
1156
+ protocol: PROTOCOL,
1157
+ networkId: options.networkId,
1158
+ kind: "error",
1159
+ error: "The article could not be added. The queue holds up to 100 articles."
1160
+ }, event.origin);
1161
+ }
1162
+ send();
1163
+ };
1164
+ window.addEventListener("message", receive);
1165
+ const timer = window.setInterval(send, 250);
1166
+ send();
1167
+ return () => {
1168
+ clearInterval(timer);
1169
+ window.removeEventListener("message", receive);
1170
+ };
1171
+ }
1172
+ var NetworkPlayerClient = class {
1173
+ constructor(controller, options, update) {
1174
+ this.controller = controller;
1175
+ this.options = options;
1176
+ this.update = update;
1177
+ this.target = null;
1178
+ this.connected = false;
1179
+ this.pending = false;
1180
+ this.handoffRequested = false;
1181
+ this.openedAt = 0;
1182
+ this.lastSeen = 0;
1183
+ this.latest = null;
1184
+ this.receive = (event) => {
1185
+ if (event.origin !== this.origin || !event.source || this.target && event.source !== this.target) return;
1186
+ const data = event.data;
1187
+ if (!data || data.protocol !== PROTOCOL || data.networkId !== this.options.networkId) return;
1188
+ if (data.kind === "error" && this.connected) {
1189
+ this.update(this.latest, "The article could not be added. The queue holds up to 100 articles.");
1190
+ return;
1191
+ }
1192
+ if (data.kind !== "state" || !validSnapshot(data.snapshot)) return;
1193
+ this.target = event.source;
1194
+ this.lastSeen = Date.now();
1195
+ if (!this.connected) {
1196
+ const local = this.controller.getSnapshot();
1197
+ const handoff = this.handoffRequested && !data.snapshot.queue.length && local.queue.length > 0;
1198
+ this.controller.pause();
1199
+ this.connected = true;
1200
+ this.pending = false;
1201
+ this.handoffRequested = false;
1202
+ if (handoff) this.post({ kind: "adopt", snapshot: local, play: local.status === "playing" || local.status === "loading" });
1203
+ }
1204
+ this.latest = data.snapshot;
1205
+ this.update(data.snapshot, null);
1206
+ };
1207
+ if (!safeHttpUrl(options.playerUrl)) throw new Error("The network player needs a fully qualified HTTP(S) URL.");
1208
+ this.origin = new URL(options.playerUrl).origin;
1209
+ window.addEventListener("message", this.receive);
1210
+ this.timer = window.setInterval(() => {
1211
+ if (this.pending && Date.now() - this.openedAt > 1e4) {
1212
+ this.pending = false;
1213
+ this.update(null, "The network player did not connect. Playback is still on this page.");
1214
+ }
1215
+ if (this.connected && this.target?.closed) this.disconnect("The network player closed. Press Play to resume here.");
1216
+ else if (this.connected && Date.now() - this.lastSeen > 5e3) {
1217
+ this.update(this.latest, "Waiting for the network player. Open its window to check playback.");
1218
+ }
1219
+ }, 1e3);
1220
+ }
1221
+ post(data) {
1222
+ this.target?.postMessage({ protocol: PROTOCOL, networkId: this.options.networkId, ...data }, this.origin);
1223
+ }
1224
+ open() {
1225
+ if (this.target && !this.target.closed) {
1226
+ this.target.focus();
1227
+ return;
1228
+ }
1229
+ this.target = window.open(this.options.playerUrl, "_blank", "popup,width=520,height=720");
1230
+ if (!this.target || this.target.closed) {
1231
+ this.target = null;
1232
+ this.update(null, "Allow the network player window to open, then try again. Playback is still on this page.");
1233
+ return;
1234
+ }
1235
+ this.pending = true;
1236
+ this.handoffRequested = true;
1237
+ this.openedAt = Date.now();
1238
+ }
1239
+ command(command) {
1240
+ if (this.connected && this.target?.closed) this.disconnect("The network player closed. Press Play to resume here.");
1241
+ if (!this.connected || !this.target || this.target.closed) return false;
1242
+ this.post({ kind: "command", command });
1243
+ return true;
1244
+ }
1245
+ disconnect(notice) {
1246
+ if (this.latest) this.controller.restore(this.latest);
1247
+ this.connected = false;
1248
+ this.handoffRequested = false;
1249
+ this.target = null;
1250
+ this.latest = null;
1251
+ this.update(null, notice);
1252
+ }
1253
+ dispose() {
1254
+ clearInterval(this.timer);
1255
+ window.removeEventListener("message", this.receive);
1256
+ }
1257
+ };
1258
+
1259
+ // src/components/network-audio-player.tsx
1260
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1261
+ var Context = createContext(null);
1262
+ var serverSnapshot = () => EMPTY_SNAPSHOT;
1263
+ function NetworkAudioProvider({ children, resolveAudio, connection, host, checkpointStorageKey }) {
1264
+ if (connection && host) throw new Error("Use connection on reader pages and host on the dedicated player route, not both.");
1265
+ const [controller] = useState2(() => new NetworkAudioController(resolveAudio));
1266
+ const snapshot = useSyncExternalStore2(controller.subscribe, controller.getSnapshot, serverSnapshot);
1267
+ const [remoteSnapshot, setRemoteSnapshot] = useState2(null);
1268
+ const [notice, setNotice] = useState2(null);
1269
+ const [highlightEnabled, setHighlightEnabled] = useState2(false);
1270
+ const client = useRef2(null);
1271
+ useEffect2(() => {
1272
+ controller.setResolver(resolveAudio);
1273
+ }, [controller, resolveAudio]);
1274
+ useEffect2(() => {
1275
+ const audio = document.createElement("audio");
1276
+ controller.attach(audio);
1277
+ return () => controller.detach();
1278
+ }, [controller]);
1279
+ useEffect2(() => {
1280
+ if (!checkpointStorageKey) return;
1281
+ try {
1282
+ const data = JSON.parse(sessionStorage.getItem(checkpointStorageKey) ?? "null");
1283
+ if (validSnapshot(data)) controller.restore(data);
1284
+ } catch {
1285
+ }
1286
+ let lastWrite = 0;
1287
+ const save = () => {
1288
+ try {
1289
+ sessionStorage.setItem(checkpointStorageKey, JSON.stringify(controller.getSnapshot()));
1290
+ } catch {
1291
+ }
1292
+ };
1293
+ const unsubscribe = controller.subscribe(() => {
1294
+ if (Date.now() - lastWrite > 1e3) {
1295
+ lastWrite = Date.now();
1296
+ save();
1297
+ }
1298
+ });
1299
+ window.addEventListener("pagehide", save);
1300
+ return () => {
1301
+ save();
1302
+ unsubscribe();
1303
+ window.removeEventListener("pagehide", save);
1304
+ };
1305
+ }, [controller, checkpointStorageKey]);
1306
+ const allowedOrigins = JSON.stringify(host?.allowedOrigins ?? []);
1307
+ useEffect2(() => {
1308
+ if (!host) return;
1309
+ return hostNetworkPlayer(controller, { networkId: host.networkId, allowedOrigins: JSON.parse(allowedOrigins) });
1310
+ }, [controller, host?.networkId, allowedOrigins]);
1311
+ useEffect2(() => {
1312
+ if (!connection) return;
1313
+ const instance = new NetworkPlayerClient(controller, connection, (state, message) => {
1314
+ setRemoteSnapshot(state);
1315
+ setNotice(message);
1316
+ });
1317
+ client.current = instance;
1318
+ return () => {
1319
+ instance.dispose();
1320
+ client.current = null;
1321
+ };
1322
+ }, [controller, connection?.playerUrl, connection?.networkId]);
1323
+ const command = useCallback((value) => {
1324
+ setNotice(null);
1325
+ try {
1326
+ if (!client.current?.command(value)) runCommand(controller, value);
1327
+ } catch (error) {
1328
+ setNotice(error instanceof Error ? error.message : "The article could not be added.");
1329
+ }
1330
+ }, [controller]);
1331
+ const openNetworkPlayer = useCallback(() => client.current?.open(), []);
1332
+ const activeSnapshot = remoteSnapshot ?? snapshot;
1333
+ return /* @__PURE__ */ jsxs2(Context.Provider, { value: {
1334
+ snapshot: activeSnapshot,
1335
+ remote: remoteSnapshot !== null,
1336
+ hosted: !!host,
1337
+ notice,
1338
+ command,
1339
+ openNetworkPlayer: connection ? openNetworkPlayer : void 0,
1340
+ highlightEnabled,
1341
+ setHighlightEnabled
1342
+ }, children: [
1343
+ /* @__PURE__ */ jsx2(NetworkMediaSession, {}),
1344
+ children
1345
+ ] });
1346
+ }
1347
+ function useNetworkAudio() {
1348
+ const context = useContext(Context);
1349
+ if (!context) throw new Error("Mount NetworkAudioProvider above the player and article controls.");
1350
+ return context;
1351
+ }
1352
+ function NetworkMediaSession() {
1353
+ const { snapshot, remote, command } = useNetworkAudio();
1354
+ const track = snapshot.queue[snapshot.index];
1355
+ useEffect2(() => {
1356
+ if (remote || !track || !("mediaSession" in navigator)) return;
1357
+ const mediaSession = navigator.mediaSession;
1358
+ if (typeof MediaMetadata !== "undefined") mediaSession.metadata = new MediaMetadata({ title: track.title, artist: track.publicationName ?? "" });
1359
+ const handlers = [
1360
+ ["play", () => command({ action: "play" })],
1361
+ ["pause", () => command({ action: "pause" })],
1362
+ ["seekto", (details) => {
1363
+ if (details.seekTime != null) command({ action: "seek", value: details.seekTime });
1364
+ }]
1365
+ ];
1366
+ handlers.forEach(([action, handler]) => {
1367
+ try {
1368
+ mediaSession.setActionHandler(action, handler);
1369
+ } catch {
1370
+ }
1371
+ });
1372
+ return () => {
1373
+ handlers.forEach(([action]) => {
1374
+ try {
1375
+ mediaSession.setActionHandler(action, null);
1376
+ } catch {
1377
+ }
1378
+ });
1379
+ mediaSession.metadata = null;
1380
+ mediaSession.playbackState = "none";
1381
+ };
1382
+ }, [remote, track, command]);
1383
+ useEffect2(() => {
1384
+ if (remote || !track || !("mediaSession" in navigator)) return;
1385
+ navigator.mediaSession.playbackState = snapshot.status === "playing" ? "playing" : "paused";
1386
+ if (snapshot.duration > 0) {
1387
+ try {
1388
+ navigator.mediaSession.setPositionState({
1389
+ duration: snapshot.duration,
1390
+ playbackRate: snapshot.rate,
1391
+ position: Math.min(snapshot.position, snapshot.duration)
1392
+ });
1393
+ } catch {
1394
+ }
1395
+ }
1396
+ }, [remote, track, snapshot.status, snapshot.position, snapshot.duration, snapshot.rate]);
1397
+ return null;
1398
+ }
1399
+ var subscribeCapabilities = () => () => {
1400
+ };
1401
+ function useArticleNarration(track, narration) {
1402
+ const { snapshot, highlightEnabled, setHighlightEnabled } = useNetworkAudio();
1403
+ const supported = useSyncExternalStore2(subscribeCapabilities, narrationHighlightSupported, () => false);
1404
+ const active = snapshot.queue[snapshot.index];
1405
+ const matching = !!active && trackKey(active) === trackKey(track);
1406
+ const clock = useRef2({ snapshot, received: 0 });
1407
+ useEffect2(() => {
1408
+ clock.current = { snapshot, received: performance.now() };
1409
+ }, [snapshot]);
1410
+ useEffect2(() => {
1411
+ if (!narration || !matching || !highlightEnabled || !supported) return;
1412
+ const controller = new AbortController();
1413
+ let highlighter = null;
1414
+ let frame = 0;
1415
+ const render = () => {
1416
+ const { snapshot: current, received } = clock.current;
1417
+ const elapsed = current.status === "playing" ? Math.min((performance.now() - received) / 1e3, 0.5) * current.rate : 0;
1418
+ highlighter?.update((current.position + elapsed) * 1e3);
1419
+ frame = requestAnimationFrame(render);
1420
+ };
1421
+ const visibility = () => {
1422
+ cancelAnimationFrame(frame);
1423
+ if (document.visibilityState === "hidden") highlighter?.clear();
1424
+ else if (highlighter) frame = requestAnimationFrame(render);
1425
+ };
1426
+ const timeout = setTimeout(() => controller.abort(), 15e3);
1427
+ void (async () => {
1428
+ try {
1429
+ const response = await fetch(narration.timingsUrl, { signal: controller.signal });
1430
+ if (!response.ok) return;
1431
+ const timings = parseTimingsPayload(await response.json());
1432
+ const target = document.getElementById(narration.targetId);
1433
+ if (controller.signal.aborted || !timings || !target) return;
1434
+ highlighter = new NarrationHighlighter(target, timings);
1435
+ if (highlighter.matchRatio() < 0.5) {
1436
+ highlighter.destroy();
1437
+ highlighter = null;
1438
+ return;
1439
+ }
1440
+ visibility();
1441
+ } catch {
1442
+ } finally {
1443
+ clearTimeout(timeout);
1444
+ }
1445
+ })();
1446
+ document.addEventListener("visibilitychange", visibility);
1447
+ return () => {
1448
+ controller.abort();
1449
+ clearTimeout(timeout);
1450
+ cancelAnimationFrame(frame);
1451
+ highlighter?.destroy();
1452
+ document.removeEventListener("visibilitychange", visibility);
1453
+ };
1454
+ }, [matching, highlightEnabled, supported, narration?.targetId, narration?.timingsUrl, track.id, track.publicationId]);
1455
+ return { highlightAvailable: !!narration && supported, highlightEnabled, setHighlightEnabled, matching };
1456
+ }
1457
+ function ArticleAudioControls({ track, narration, className = "" }) {
1458
+ const { snapshot, command } = useNetworkAudio();
1459
+ const { highlightAvailable, highlightEnabled, setHighlightEnabled, matching } = useArticleNarration(track, narration);
1460
+ const playing = matching && (snapshot.status === "playing" || snapshot.status === "loading");
1461
+ const queued = snapshot.queue.some((item) => trackKey(item) === trackKey(track));
1462
+ return /* @__PURE__ */ jsxs2("div", { className: `sm-network-article ${className}`, "aria-label": "Article audio", children: [
1463
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => command(playing ? { action: "pause" } : { action: "playTrack", track }), children: playing ? "Pause article" : "Listen to article" }),
1464
+ /* @__PURE__ */ jsx2("button", { type: "button", disabled: queued, onClick: () => command({ action: "enqueue", track }), children: queued ? "In your queue" : "Add to queue" }),
1465
+ highlightAvailable && /* @__PURE__ */ jsx2("button", { type: "button", "aria-pressed": highlightEnabled, onClick: () => setHighlightEnabled(!highlightEnabled), children: "Highlight words" })
1466
+ ] });
1467
+ }
1468
+ var formatTime = (seconds) => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
1469
+ function NetworkAudioPlayer({ networkName = "Your listening queue", advertisement, className = "", style, fixed = true, renderArticleLink }) {
1470
+ const { snapshot, remote, hosted, notice, command, openNetworkPlayer } = useNetworkAudio();
1471
+ const [expanded, setExpanded] = useState2(false);
1472
+ const [height, setHeight] = useState2(0);
1473
+ const bar = useRef2(null);
1474
+ const detailsId = useId2();
1475
+ const track = snapshot.queue[snapshot.index];
1476
+ const playing = snapshot.status === "playing" || snapshot.status === "loading";
1477
+ useEffect2(() => {
1478
+ const element = bar.current;
1479
+ if (!fixed || !element) return;
1480
+ const measure = () => setHeight(element.getBoundingClientRect().height);
1481
+ measure();
1482
+ if (typeof ResizeObserver === "undefined") {
1483
+ window.addEventListener("resize", measure);
1484
+ return () => window.removeEventListener("resize", measure);
1485
+ }
1486
+ const observer = new ResizeObserver(measure);
1487
+ observer.observe(element);
1488
+ return () => observer.disconnect();
1489
+ }, [fixed, !!track, expanded, notice, snapshot.error]);
1490
+ if (!track) return notice ? /* @__PURE__ */ jsx2("p", { role: "status", children: notice }) : null;
1491
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
1492
+ fixed && /* @__PURE__ */ jsx2("div", { "aria-hidden": "true", style: { height } }),
1493
+ /* @__PURE__ */ jsxs2("section", { ref: bar, className: `sm-network-player ${fixed ? "sm-network-player--fixed" : ""} ${className}`, style, "aria-label": "Network audio player", children: [
1494
+ /* @__PURE__ */ jsxs2("div", { className: "sm-network-player__row", children: [
1495
+ /* @__PURE__ */ jsx2("button", { type: "button", className: "sm-network-player__play", "aria-label": playing ? "Pause playback" : "Play playback", onClick: () => command({ action: playing ? "pause" : "play" }), children: /* @__PURE__ */ jsx2("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: playing ? /* @__PURE__ */ jsx2("path", { d: "M6 4h4v16H6zm8 0h4v16h-4z" }) : /* @__PURE__ */ jsx2("path", { d: "M7 3v18l15-9z" }) }) }),
1496
+ /* @__PURE__ */ jsxs2("div", { className: "sm-network-player__story", children: [
1497
+ /* @__PURE__ */ jsx2("span", { children: remote ? "Playing in network window" : networkName }),
1498
+ !hosted && renderArticleLink ? renderArticleLink(track) : /* @__PURE__ */ jsx2("a", { href: track.articleUrl, target: "_blank", rel: "noopener noreferrer", children: track.title }),
1499
+ /* @__PURE__ */ jsx2("small", { children: track.publicationName })
1500
+ ] }),
1501
+ /* @__PURE__ */ jsxs2("div", { className: "sm-network-player__timeline", children: [
1502
+ /* @__PURE__ */ jsx2("input", { type: "range", min: "0", max: snapshot.duration || 0, step: "0.1", value: Math.min(snapshot.position, snapshot.duration), disabled: !snapshot.duration, "aria-label": "Seek article audio", onChange: (e) => command({ action: "seek", value: Number(e.target.value) }) }),
1503
+ /* @__PURE__ */ jsxs2("div", { children: [
1504
+ /* @__PURE__ */ jsx2("span", { children: formatTime(snapshot.position) }),
1505
+ /* @__PURE__ */ jsxs2("span", { children: [
1506
+ formatTime(Math.max(0, snapshot.duration - snapshot.position) / snapshot.rate),
1507
+ " remaining"
1508
+ ] })
1509
+ ] })
1510
+ ] }),
1511
+ /* @__PURE__ */ jsx2("button", { type: "button", disabled: snapshot.index + 1 >= snapshot.queue.length, onClick: () => command({ action: "select", value: snapshot.index + 1 }), children: "Next" }),
1512
+ /* @__PURE__ */ jsx2("button", { type: "button", "aria-expanded": expanded, "aria-controls": detailsId, onClick: () => setExpanded(!expanded), children: expanded ? "Collapse" : `Queue (${snapshot.queue.length})` })
1513
+ ] }),
1514
+ (notice || snapshot.error) && /* @__PURE__ */ jsx2("p", { role: "status", className: "sm-network-player__notice", children: notice ?? snapshot.error }),
1515
+ /* @__PURE__ */ jsxs2("div", { id: detailsId, hidden: !expanded, className: "sm-network-player__details", children: [
1516
+ /* @__PURE__ */ jsxs2("div", { className: "sm-network-player__tools", children: [
1517
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => command({ action: "seek", value: snapshot.position - 15 }), children: "Back 15 seconds" }),
1518
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => command({ action: "seek", value: snapshot.position + 30 }), children: "Forward 30 seconds" }),
1519
+ /* @__PURE__ */ jsxs2("label", { children: [
1520
+ "Speed ",
1521
+ /* @__PURE__ */ jsx2("select", { value: snapshot.rate, onChange: (e) => command({ action: "rate", value: Number(e.target.value) }), children: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3].map((rate) => /* @__PURE__ */ jsxs2("option", { value: rate, children: [
1522
+ rate,
1523
+ "\xD7"
1524
+ ] }, rate)) })
1525
+ ] }),
1526
+ /* @__PURE__ */ jsxs2("label", { children: [
1527
+ "Volume ",
1528
+ /* @__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) }) })
1529
+ ] }),
1530
+ openNetworkPlayer && /* @__PURE__ */ jsx2("button", { type: "button", onClick: openNetworkPlayer, children: remote ? "Open player window" : "Listen across sites \u2197" }),
1531
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => command({ action: "clear" }), children: "Stop and clear queue" })
1532
+ ] }),
1533
+ /* @__PURE__ */ jsxs2("div", { className: "sm-network-player__expanded", children: [
1534
+ /* @__PURE__ */ jsxs2("div", { children: [
1535
+ /* @__PURE__ */ jsx2("h2", { children: "Up next" }),
1536
+ /* @__PURE__ */ jsx2("ol", { children: snapshot.queue.map((item, index) => /* @__PURE__ */ jsxs2("li", { "aria-current": index === snapshot.index ? "true" : void 0, children: [
1537
+ /* @__PURE__ */ jsxs2("button", { type: "button", className: "sm-network-player__queue-title", onClick: () => command({ action: "select", value: index }), children: [
1538
+ item.title,
1539
+ /* @__PURE__ */ jsxs2("small", { children: [
1540
+ item.publicationName,
1541
+ index === snapshot.index ? " \u2014 Current article" : ""
1542
+ ] })
1543
+ ] }),
1544
+ /* @__PURE__ */ jsx2("button", { type: "button", "aria-label": `Remove ${item.title} from queue`, onClick: () => command({ action: "remove", value: index }), children: "Remove" })
1545
+ ] }, trackKey(item))) })
1546
+ ] }),
1547
+ advertisement && /* @__PURE__ */ jsxs2("aside", { "aria-label": "Advertisement", children: [
1548
+ /* @__PURE__ */ jsx2("span", { children: "Advertisement" }),
1549
+ advertisement
1550
+ ] })
1551
+ ] })
1552
+ ] })
1553
+ ] })
1554
+ ] });
1555
+ }
775
1556
  export {
1557
+ ArticleAudioControls,
776
1558
  AudioPlayer,
777
1559
  NarrationHighlighter,
1560
+ NetworkAudioController,
1561
+ NetworkAudioPlayer,
1562
+ NetworkAudioProvider,
778
1563
  SENTENCE_HIGHLIGHT,
779
1564
  WORD_HIGHLIGHT,
780
1565
  narrationHighlightSupported,
781
- parseTimingsPayload
1566
+ parseTimingsPayload,
1567
+ useArticleNarration,
1568
+ useNetworkAudio
782
1569
  };