@scarlett-player/embed 1.2.0 → 1.4.1

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/embed.js CHANGED
@@ -148,6 +148,7 @@ class StateManager {
148
148
  constructor(initialState) {
149
149
  this.signals = /* @__PURE__ */ new Map();
150
150
  this.changeSubscribers = /* @__PURE__ */ new Set();
151
+ this.definedDefaults = /* @__PURE__ */ new Map();
151
152
  this.initializeSignals(initialState);
152
153
  }
153
154
  /**
@@ -157,14 +158,52 @@ class StateManager {
157
158
  initializeSignals(overrides) {
158
159
  const initialState = { ...DEFAULT_STATE, ...overrides };
159
160
  for (const [key, value] of Object.entries(initialState)) {
160
- const stateKey = key;
161
- const stateSignal = signal(value);
162
- stateSignal.subscribe(() => {
163
- this.notifyChangeSubscribers(stateKey);
164
- });
165
- this.signals.set(stateKey, stateSignal);
161
+ this.createSignal(key, value);
166
162
  }
167
163
  }
164
+ /**
165
+ * Create and register a signal, wired to the global change subscribers.
166
+ *
167
+ * Shared by initializeSignals() and define() so a plugin-defined key behaves
168
+ * exactly like a built-in one and the two paths cannot drift apart.
169
+ *
170
+ * @private
171
+ */
172
+ createSignal(key, value) {
173
+ const stateSignal = signal(value);
174
+ stateSignal.subscribe(() => {
175
+ this.notifyChangeSubscribers(key);
176
+ });
177
+ this.signals.set(key, stateSignal);
178
+ }
179
+ /**
180
+ * Register a state key at runtime, for state a plugin owns.
181
+ *
182
+ * Core cannot know every plugin's keys, and {@link get} deliberately throws
183
+ * for unregistered ones — that throw is a useful typo-catcher and is worth
184
+ * keeping — so a plugin declares its keys before first use.
185
+ *
186
+ * Idempotent by design: re-defining an existing key leaves the current value
187
+ * untouched. Plugins commonly re-run setup after a source change, and that
188
+ * must not reset state that is already live.
189
+ *
190
+ * Namespace plugin keys with the plugin's own name to avoid collisions.
191
+ *
192
+ * @param key - State property key
193
+ * @param initialValue - Value used only when the key is new
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * state.define('highlightSelection', null);
198
+ * ```
199
+ */
200
+ define(key, initialValue) {
201
+ if (this.signals.has(key)) {
202
+ return;
203
+ }
204
+ this.definedDefaults.set(key, initialValue);
205
+ this.createSignal(key, initialValue);
206
+ }
168
207
  /**
169
208
  * Get the signal for a state property.
170
209
  *
@@ -307,7 +346,10 @@ class StateManager {
307
346
  * ```
308
347
  */
309
348
  reset() {
310
- this.update(DEFAULT_STATE);
349
+ this.update({
350
+ ...DEFAULT_STATE,
351
+ ...Object.fromEntries(this.definedDefaults)
352
+ });
311
353
  }
312
354
  /**
313
355
  * Reset a specific state property to its default value.
@@ -320,7 +362,7 @@ class StateManager {
320
362
  * ```
321
363
  */
322
364
  resetKey(key) {
323
- const defaultValue = DEFAULT_STATE[key];
365
+ const defaultValue = key in DEFAULT_STATE ? DEFAULT_STATE[key] : this.definedDefaults.get(key);
324
366
  this.set(key, defaultValue);
325
367
  }
326
368
  /**
@@ -1214,6 +1256,18 @@ class PluginAPI {
1214
1256
  setState(key, value) {
1215
1257
  this.stateManager.set(key, value);
1216
1258
  }
1259
+ /**
1260
+ * Register a state key this plugin owns, before first use.
1261
+ *
1262
+ * Idempotent — re-defining an existing key keeps its current value.
1263
+ * See {@link IPluginAPI.defineState}.
1264
+ *
1265
+ * @param key - State property key
1266
+ * @param initialValue - Value used only when the key is new
1267
+ */
1268
+ defineState(key, initialValue) {
1269
+ this.stateManager.define(key, initialValue);
1270
+ }
1217
1271
  /**
1218
1272
  * Subscribe to an event.
1219
1273
  *
@@ -5968,6 +6022,17 @@ var BandwidthIndicator = class {
5968
6022
  this.el.remove();
5969
6023
  }
5970
6024
  };
6025
+ var registry = /* @__PURE__ */ new Map();
6026
+ var listeners = /* @__PURE__ */ new Set();
6027
+ function getControlFactory(id) {
6028
+ return registry.get(id) ?? null;
6029
+ }
6030
+ function onControlRegistered(listener) {
6031
+ listeners.add(listener);
6032
+ return () => {
6033
+ listeners.delete(listener);
6034
+ };
6035
+ }
5971
6036
  var DEFAULT_LAYOUT = [
5972
6037
  "play",
5973
6038
  "skip-backward",
@@ -5996,6 +6061,7 @@ function uiPlugin(config = {}) {
5996
6061
  let controls = [];
5997
6062
  let hideTimeout = null;
5998
6063
  let stateUnsubscribe = null;
6064
+ let controlRegistryUnsubscribe = null;
5999
6065
  let errorUnsubscribe = null;
6000
6066
  let reconnectingUnsubscribe = null;
6001
6067
  let recoveredUnsubscribe = null;
@@ -6037,9 +6103,42 @@ function uiPlugin(config = {}) {
6037
6103
  return new FullscreenButton(api);
6038
6104
  case "spacer":
6039
6105
  return new Spacer();
6040
- default:
6106
+ default: {
6107
+ const factory = getControlFactory(slot);
6108
+ if (factory) {
6109
+ try {
6110
+ return factory(api);
6111
+ } catch (error) {
6112
+ api.logger.error(`Control factory for "${slot}" threw`, { error });
6113
+ return null;
6114
+ }
6115
+ }
6116
+ api.logger.warn(`Unknown control slot: ${slot}`);
6041
6117
  return null;
6118
+ }
6119
+ }
6120
+ };
6121
+ const populateControlBar = () => {
6122
+ if (!controlBar) {
6123
+ return;
6124
+ }
6125
+ for (const slot of layout) {
6126
+ const control = createControl(slot);
6127
+ if (control) {
6128
+ controls.push(control);
6129
+ controlBar.appendChild(control.render());
6130
+ }
6131
+ }
6132
+ };
6133
+ const rebuildControlBar = () => {
6134
+ if (!controlBar) {
6135
+ return;
6042
6136
  }
6137
+ controls.forEach((c) => c.destroy());
6138
+ controls = [];
6139
+ controlBar.replaceChildren();
6140
+ populateControlBar();
6141
+ updateControls();
6043
6142
  };
6044
6143
  const updateControls = () => {
6045
6144
  controls.forEach((c) => c.update());
@@ -6213,14 +6312,15 @@ function uiPlugin(config = {}) {
6213
6312
  controlBar.className = isPlaying ? "sp-controls sp-controls--hidden" : "sp-controls sp-controls--visible";
6214
6313
  controlBar.setAttribute("role", "toolbar");
6215
6314
  controlBar.setAttribute("aria-label", "Video controls");
6216
- for (const slot of layout) {
6217
- const control = createControl(slot);
6218
- if (control) {
6219
- controls.push(control);
6220
- controlBar.appendChild(control.render());
6221
- }
6222
- }
6315
+ populateControlBar();
6223
6316
  container.appendChild(controlBar);
6317
+ controlRegistryUnsubscribe = onControlRegistered((id) => {
6318
+ if (!layout.includes(id)) {
6319
+ return;
6320
+ }
6321
+ api.logger.debug(`Control "${id}" registered after init, rebuilding control bar`);
6322
+ rebuildControlBar();
6323
+ });
6224
6324
  container.addEventListener("mousemove", handleInteraction);
6225
6325
  container.addEventListener("mouseenter", handleInteraction);
6226
6326
  container.addEventListener("mouseleave", handleMouseLeave);
@@ -6266,6 +6366,8 @@ function uiPlugin(config = {}) {
6266
6366
  }
6267
6367
  document.removeEventListener("keydown", handleKeyDown);
6268
6368
  document.removeEventListener("fullscreenchange", scheduleUpdate);
6369
+ controlRegistryUnsubscribe?.();
6370
+ controlRegistryUnsubscribe = null;
6269
6371
  controls.forEach((c) => c.destroy());
6270
6372
  controls = [];
6271
6373
  progressBar?.destroy();
@@ -8464,10 +8566,17 @@ function createWatermarkPlugin(config = {}) {
8464
8566
  }
8465
8567
  };
8466
8568
  }
8569
+ var HLS_SUBTITLE_TRACKS_UPDATED = "hlsSubtitleTracksUpdated";
8570
+ var HLS_INSTANCE_RETRY_MS = 500;
8467
8571
  function createCaptionsPlugin(config = {}) {
8468
8572
  let api = null;
8469
8573
  let video = null;
8470
8574
  let addedTrackElements = [];
8575
+ let hlsSubtitleHandler = null;
8576
+ let observedTextTracks = null;
8577
+ let hlsRetryTimer = null;
8578
+ let hlsRetryUsed = false;
8579
+ let hasAutoSelected = false;
8471
8580
  const extractFromHLS = config.extractFromHLS !== false;
8472
8581
  const autoSelect = config.autoSelect ?? false;
8473
8582
  const defaultLanguage = config.defaultLanguage ?? "en";
@@ -8526,6 +8635,7 @@ function createCaptionsPlugin(config = {}) {
8526
8635
  const selectTrack = (trackId) => {
8527
8636
  const videoEl = getVideo2();
8528
8637
  if (!videoEl) return;
8638
+ hasAutoSelected = true;
8529
8639
  for (let i = 0; i < videoEl.textTracks.length; i++) {
8530
8640
  const track = videoEl.textTracks[i];
8531
8641
  if (track.kind !== "subtitles" && track.kind !== "captions") continue;
@@ -8538,45 +8648,90 @@ function createCaptionsPlugin(config = {}) {
8538
8648
  }
8539
8649
  syncTracksToState();
8540
8650
  };
8651
+ const maybeAutoSelect = () => {
8652
+ if (!autoSelect || hasAutoSelected) return;
8653
+ if (api?.getState("currentTextTrack")) {
8654
+ hasAutoSelected = true;
8655
+ return;
8656
+ }
8657
+ const tracks = api?.getState("textTracks") || [];
8658
+ const match = tracks.find((t) => t.language === defaultLanguage);
8659
+ if (!match) return;
8660
+ selectTrack(match.id);
8661
+ api?.logger.debug("Auto-selected caption track", { language: defaultLanguage, id: match.id });
8662
+ };
8663
+ const handleTextTracksChanged = () => {
8664
+ syncTracksToState();
8665
+ maybeAutoSelect();
8666
+ };
8667
+ const observeTextTracks = () => {
8668
+ const videoEl = getVideo2();
8669
+ if (!videoEl || observedTextTracks === videoEl.textTracks) return;
8670
+ unobserveTextTracks();
8671
+ const list = videoEl.textTracks;
8672
+ if (typeof list?.addEventListener !== "function") return;
8673
+ observedTextTracks = list;
8674
+ observedTextTracks.addEventListener("addtrack", handleTextTracksChanged);
8675
+ observedTextTracks.addEventListener("removetrack", handleTextTracksChanged);
8676
+ observedTextTracks.addEventListener("change", handleTextTracksChanged);
8677
+ };
8678
+ const unobserveTextTracks = () => {
8679
+ if (typeof observedTextTracks?.removeEventListener !== "function") {
8680
+ observedTextTracks = null;
8681
+ return;
8682
+ }
8683
+ observedTextTracks.removeEventListener("addtrack", handleTextTracksChanged);
8684
+ observedTextTracks.removeEventListener("removetrack", handleTextTracksChanged);
8685
+ observedTextTracks.removeEventListener("change", handleTextTracksChanged);
8686
+ observedTextTracks = null;
8687
+ };
8541
8688
  const extractHlsSubtitles = () => {
8542
8689
  if (!extractFromHLS || !api) return;
8543
8690
  const hlsPlugin = api.getPlugin("hls-provider");
8544
8691
  if (!hlsPlugin || hlsPlugin.isNativeHLS()) return;
8545
8692
  const hlsInstance = hlsPlugin.getHlsInstance();
8546
8693
  if (!hlsInstance?.subtitleTracks?.length) return;
8547
- api.logger.debug("Extracting HLS subtitle tracks", {
8694
+ api.logger.debug("Syncing HLS subtitle tracks", {
8548
8695
  count: hlsInstance.subtitleTracks.length
8549
8696
  });
8550
- for (const hlsTrack of hlsInstance.subtitleTracks) {
8551
- addTrackElement({
8552
- language: hlsTrack.lang || "unknown",
8553
- label: hlsTrack.name || `Subtitle ${hlsTrack.id}`,
8554
- src: hlsTrack.url,
8555
- kind: "subtitles"
8556
- });
8557
- }
8558
8697
  syncTracksToState();
8559
- if (autoSelect) {
8560
- autoSelectTrack();
8561
- }
8698
+ maybeAutoSelect();
8562
8699
  };
8563
- const autoSelectTrack = () => {
8564
- const tracks = api?.getState("textTracks") || [];
8565
- const match = tracks.find((t) => t.language === defaultLanguage);
8566
- if (match) {
8567
- selectTrack(match.id);
8568
- api?.logger.debug("Auto-selected caption track", { language: defaultLanguage, id: match.id });
8700
+ const unsubscribeFromHls = () => {
8701
+ if (hlsRetryTimer) {
8702
+ clearTimeout(hlsRetryTimer);
8703
+ hlsRetryTimer = null;
8704
+ }
8705
+ if (!hlsSubtitleHandler) return;
8706
+ const hlsInstance = api?.getPlugin("hls-provider")?.getHlsInstance();
8707
+ hlsInstance?.off(HLS_SUBTITLE_TRACKS_UPDATED, hlsSubtitleHandler);
8708
+ hlsSubtitleHandler = null;
8709
+ };
8710
+ const syncFromHls = () => {
8711
+ if (!extractFromHLS || !api) return;
8712
+ const hlsPlugin = api.getPlugin("hls-provider");
8713
+ if (!hlsPlugin || hlsPlugin.isNativeHLS()) return;
8714
+ const hlsInstance = hlsPlugin.getHlsInstance();
8715
+ if (!hlsInstance) {
8716
+ if (!hlsRetryUsed) {
8717
+ hlsRetryUsed = true;
8718
+ hlsRetryTimer = setTimeout(() => {
8719
+ hlsRetryTimer = null;
8720
+ syncFromHls();
8721
+ }, HLS_INSTANCE_RETRY_MS);
8722
+ }
8723
+ return;
8569
8724
  }
8725
+ unsubscribeFromHls();
8726
+ hlsSubtitleHandler = () => extractHlsSubtitles();
8727
+ hlsInstance.on(HLS_SUBTITLE_TRACKS_UPDATED, hlsSubtitleHandler);
8728
+ extractHlsSubtitles();
8570
8729
  };
8571
8730
  const initSources = () => {
8572
8731
  if (!config.sources?.length) return;
8573
8732
  for (const source of config.sources) {
8574
8733
  addTrackElement(source);
8575
8734
  }
8576
- syncTracksToState();
8577
- if (autoSelect) {
8578
- autoSelectTrack();
8579
- }
8580
8735
  };
8581
8736
  return {
8582
8737
  id: "captions",
@@ -8594,25 +8749,36 @@ function createCaptionsPlugin(config = {}) {
8594
8749
  });
8595
8750
  const unsubLoaded = api.on("media:loaded", () => {
8596
8751
  video = null;
8752
+ hasAutoSelected = false;
8753
+ hlsRetryUsed = false;
8597
8754
  cleanupTracks();
8598
8755
  initSources();
8599
- if (extractFromHLS) {
8600
- setTimeout(extractHlsSubtitles, 500);
8601
- }
8756
+ observeTextTracks();
8757
+ syncTracksToState();
8758
+ maybeAutoSelect();
8759
+ syncFromHls();
8602
8760
  });
8603
8761
  const unsubLoadRequest = api.on("media:load-request", () => {
8604
8762
  video = null;
8763
+ hasAutoSelected = false;
8764
+ hlsRetryUsed = false;
8765
+ unsubscribeFromHls();
8766
+ unobserveTextTracks();
8605
8767
  cleanupTracks();
8606
8768
  });
8607
8769
  api.onDestroy(() => {
8608
8770
  unsubTrackText();
8609
8771
  unsubLoaded();
8610
8772
  unsubLoadRequest();
8773
+ unsubscribeFromHls();
8774
+ unobserveTextTracks();
8611
8775
  cleanupTracks();
8612
8776
  });
8613
8777
  },
8614
8778
  destroy() {
8615
8779
  api?.logger.debug("Captions plugin destroyed");
8780
+ unsubscribeFromHls();
8781
+ unobserveTextTracks();
8616
8782
  cleanupTracks();
8617
8783
  video = null;
8618
8784
  api = null;