@arraypress/waveform-player 1.24.4 → 1.25.0

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.
@@ -51,6 +51,44 @@ function isSafeHref(url) {
51
51
  function clamp(value, min = 0, max = 1) {
52
52
  return Math.max(min, Math.min(value, max));
53
53
  }
54
+ function toFiniteNumber(value, fallback = null, opts = {}) {
55
+ const { min = -Infinity, max = Infinity, integer = false } = opts;
56
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
57
+ if (!Number.isFinite(n)) return fallback;
58
+ const bounded = clamp(n, min, max);
59
+ return integer ? Math.round(bounded) : bounded;
60
+ }
61
+ function toArray(value, fallback = null) {
62
+ if (Array.isArray(value)) return value;
63
+ if (typeof value === "string" && value.trim().startsWith("[")) {
64
+ try {
65
+ const parsed = JSON.parse(value);
66
+ if (Array.isArray(parsed)) return parsed;
67
+ } catch (e) {
68
+ }
69
+ }
70
+ return fallback;
71
+ }
72
+ function toNumberArray(value, opts = {}) {
73
+ const { min = -Infinity, max = Infinity, fallback = null } = opts;
74
+ let list = toArray(value);
75
+ if (!list && typeof value === "string" && value.trim() !== "") {
76
+ list = value.split(/[,\s]+/);
77
+ }
78
+ if (!list) return fallback;
79
+ const numbers = list.map((v) => toFiniteNumber(v)).filter((n) => n !== null && n >= min && n <= max);
80
+ return numbers.length ? numbers : fallback;
81
+ }
82
+ function toEnum(value, allowed, fallback = null) {
83
+ return allowed.includes(value) ? value : fallback;
84
+ }
85
+ function toBool(value) {
86
+ if (typeof value === "string") {
87
+ const v = value.trim().toLowerCase();
88
+ return v !== "" && v !== "false" && v !== "0";
89
+ }
90
+ return !!value;
91
+ }
54
92
  function parseBoolAttr(value) {
55
93
  return value === void 0 ? void 0 : value === "true";
56
94
  }
@@ -78,14 +116,12 @@ function parseDataAttributes(element) {
78
116
  if (!raw) return;
79
117
  options[optKey] = /^\d+(\.\d+)?$/.test(raw.trim()) ? parseFloat(raw) : raw;
80
118
  };
81
- const setJson = (optKey, dataKey = optKey) => {
119
+ const setJsonArray = (optKey, dataKey = optKey) => {
82
120
  const raw = element.dataset[dataKey];
83
121
  if (!raw) return;
84
- try {
85
- options[optKey] = JSON.parse(raw);
86
- } catch (e) {
87
- console.warn(`[WaveformPlayer] Invalid ${dataKey} JSON:`, e);
88
- }
122
+ const parsed = toArray(raw);
123
+ if (parsed) options[optKey] = parsed;
124
+ else console.warn(`[WaveformPlayer] Invalid ${dataKey} attribute, expected a JSON array:`, raw);
89
125
  };
90
126
  if (element.dataset.src) options.url = element.dataset.src;
91
127
  if (element.dataset.url) options.url = element.dataset.url;
@@ -130,10 +166,14 @@ function parseDataAttributes(element) {
130
166
  if (element.dataset.artwork) options.artwork = element.dataset.artwork;
131
167
  if (element.dataset.artworkPosition) options.artworkPosition = element.dataset.artworkPosition;
132
168
  if (element.dataset.waveform) options.waveform = element.dataset.waveform;
133
- setJson("markers");
169
+ setJsonArray("markers");
134
170
  setNum("playbackRate", "playbackRate", true);
135
171
  setBool("showPlaybackSpeed");
136
- setJson("playbackRates");
172
+ if (element.dataset.playbackRates) {
173
+ const rates = toNumberArray(element.dataset.playbackRates);
174
+ if (rates) options.playbackRates = rates;
175
+ else console.warn("[WaveformPlayer] Invalid playbackRates attribute:", element.dataset.playbackRates);
176
+ }
137
177
  setBool("enableMediaSession");
138
178
  setBool("showMarkers");
139
179
  setBool("accessibleSeek");
@@ -873,6 +913,123 @@ var STYLE_DEFAULTS = {
873
913
  dots: { barWidth: 3, barSpacing: 3 },
874
914
  seekbar: { barWidth: 1, barSpacing: 0 }
875
915
  };
916
+ var BUTTON_ALIGNMENTS = ["auto", "top", "center", "bottom"];
917
+ var PLAYBACK_RATE_MIN = 0.25;
918
+ var PLAYBACK_RATE_MAX = 4;
919
+ var ENUMS = {
920
+ buttonAlign: BUTTON_ALIGNMENTS,
921
+ layout: ["default", "preview"],
922
+ buttonStyle: ["circle", "minimal"],
923
+ artworkPosition: ["info", "button"],
924
+ waveformStyle: Object.keys(STYLE_DEFAULTS),
925
+ waveformGradient: ["vertical", "horizontal", "diagonal"],
926
+ audioMode: ["self", "external"],
927
+ preload: ["none", "metadata", "auto"],
928
+ colorPreset: Object.keys(COLOR_PRESETS),
929
+ // Anything other than these two makes the browser fall back to 'anonymous',
930
+ // which forces a CORS request the caller never asked for — so a bad value
931
+ // has to resolve to null (no crossorigin attribute), not pass through.
932
+ crossOrigin: ["anonymous", "use-credentials"]
933
+ };
934
+ var NUMBERS = {
935
+ height: { min: 1, integer: true },
936
+ samples: { min: 1, integer: true },
937
+ barWidth: { min: 0 },
938
+ barSpacing: { min: 0 },
939
+ barRadius: { min: 0 },
940
+ bpm: { min: 1 },
941
+ // Matches the clamp in setPlaybackRate() — the menu must not offer a rate
942
+ // the setter would then silently refuse.
943
+ playbackRate: { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX }
944
+ };
945
+ var BOOLEANS = [
946
+ "autoplay",
947
+ "showControls",
948
+ "showInfo",
949
+ "showTime",
950
+ "showHoverTime",
951
+ "seekHandle",
952
+ "showBPM",
953
+ "singlePlay",
954
+ "playOnSeek",
955
+ "enableMediaSession",
956
+ "showMarkers",
957
+ "accessibleSeek",
958
+ "showPlaybackSpeed"
959
+ ];
960
+ var CALLBACKS = [
961
+ "onLoad",
962
+ "onPlay",
963
+ "onPause",
964
+ "onEnd",
965
+ "onError",
966
+ "onTimeUpdate",
967
+ "onNextTrack",
968
+ "onPreviousTrack"
969
+ ];
970
+ function warnInvalid(key, value) {
971
+ console.warn(`[WaveformPlayer] Invalid ${key} option, using default:`, value);
972
+ }
973
+ function normalizeMarkers(value) {
974
+ const list = toArray(value);
975
+ if (!list) {
976
+ if (value != null) warnInvalid("markers", value);
977
+ return [];
978
+ }
979
+ return list.reduce((markers, marker) => {
980
+ const time = marker && typeof marker === "object" ? toFiniteNumber(marker.time, null, { min: 0 }) : null;
981
+ if (time === null) {
982
+ warnInvalid("marker", marker);
983
+ return markers;
984
+ }
985
+ markers.push({ ...marker, time, label: marker.label == null ? "" : marker.label });
986
+ return markers;
987
+ }, []);
988
+ }
989
+ function normalizeOptions(options) {
990
+ const supplied = (key) => options[key] != null;
991
+ const reject = (key) => {
992
+ warnInvalid(key, options[key]);
993
+ options[key] = DEFAULT_OPTIONS[key];
994
+ };
995
+ for (const [key, range] of Object.entries(NUMBERS)) {
996
+ if (!supplied(key)) continue;
997
+ const n = toFiniteNumber(options[key], null, range);
998
+ if (n === null) reject(key);
999
+ else options[key] = n;
1000
+ }
1001
+ for (const [key, allowed] of Object.entries(ENUMS)) {
1002
+ if (supplied(key) && toEnum(options[key], allowed) === null) reject(key);
1003
+ }
1004
+ for (const key of BOOLEANS) {
1005
+ options[key] = toBool(options[key]);
1006
+ }
1007
+ for (const key of CALLBACKS) {
1008
+ if (supplied(key) && typeof options[key] !== "function") reject(key);
1009
+ }
1010
+ if (supplied("playbackRates")) {
1011
+ const rates = toNumberArray(options.playbackRates, {
1012
+ min: PLAYBACK_RATE_MIN,
1013
+ max: PLAYBACK_RATE_MAX,
1014
+ fallback: null
1015
+ });
1016
+ if (rates === null) reject("playbackRates");
1017
+ else options.playbackRates = rates;
1018
+ }
1019
+ options.markers = normalizeMarkers(options.markers);
1020
+ for (const key of ["buttonSize", "buttonRadius"]) {
1021
+ if (!supplied(key)) continue;
1022
+ const value = options[key];
1023
+ const ok = typeof value === "number" ? Number.isFinite(value) : typeof value === "string" && value.trim() !== "";
1024
+ if (!ok) reject(key);
1025
+ }
1026
+ for (const key of ["waveformColor", "progressColor"]) {
1027
+ if (!supplied(key)) continue;
1028
+ const value = options[key];
1029
+ if (!(typeof value === "string" && value.trim() !== "") && !Array.isArray(value)) reject(key);
1030
+ }
1031
+ return options;
1032
+ }
876
1033
 
877
1034
  // src/js/core.js
878
1035
  var ARTWORK_FALLBACK = "data:image/svg+xml," + encodeURIComponent(
@@ -881,7 +1038,6 @@ var ARTWORK_FALLBACK = "data:image/svg+xml," + encodeURIComponent(
881
1038
  var SEEK_STEP_SECONDS = 5;
882
1039
  var SEEK_PAGE_SECONDS = 10;
883
1040
  var INTERACTIVE_ELEMENTS = 'button, a[href], input, [role="slider"]';
884
- var BUTTON_ALIGNMENTS = ["auto", "top", "center", "bottom"];
885
1041
  var WaveformPlayer = class _WaveformPlayer {
886
1042
  /** @type {Map<string, WaveformPlayer>} */
887
1043
  static instances = /* @__PURE__ */ new Map();
@@ -913,7 +1069,7 @@ var WaveformPlayer = class _WaveformPlayer {
913
1069
  const userOptions = { ...options };
914
1070
  if (userOptions.style && !userOptions.waveformStyle) userOptions.waveformStyle = userOptions.style;
915
1071
  if (userOptions.src && !userOptions.url) userOptions.url = userOptions.src;
916
- this.options = mergeOptions(DEFAULT_OPTIONS, dataOptions, userOptions);
1072
+ this.options = normalizeOptions(mergeOptions(DEFAULT_OPTIONS, dataOptions, userOptions));
917
1073
  const preset = getColorPreset(this.options.colorPreset, this.container);
918
1074
  this._autoTheme = this.options.colorPreset == null || !COLOR_PRESETS[this.options.colorPreset];
919
1075
  this._presetKeys = [];
@@ -1761,9 +1917,10 @@ var WaveformPlayer = class _WaveformPlayer {
1761
1917
  * element, so the src/metadata step is skipped and only the visualization
1762
1918
  * is built (duration/time come from the controller via
1763
1919
  * {@link WaveformPlayer#setProgress}). Peaks come from the `waveform`
1764
- * option when provided, otherwise they are decoded from the audio; a
1765
- * decode failure falls back to a placeholder waveform. The `onLoad`
1766
- * callback fires on success.
1920
+ * option when provided — painted *before* the metadata wait, since they
1921
+ * need nothing from the audio element — otherwise they are decoded from
1922
+ * the audio; a decode failure falls back to a placeholder waveform. The
1923
+ * `onLoad` callback fires on success.
1767
1924
  * @param {string} url - Audio URL.
1768
1925
  * @returns {Promise<void>} Resolves once loading settles (errors are caught
1769
1926
  * internally and surfaced through {@link WaveformPlayer#onError}).
@@ -1774,31 +1931,35 @@ var WaveformPlayer = class _WaveformPlayer {
1774
1931
  this.progress = 0;
1775
1932
  this.hasError = false;
1776
1933
  this.container.classList.remove("waveform-is-placeholder");
1934
+ const hasInlinePeaks = !!this.options.waveform;
1935
+ if (hasInlinePeaks) {
1936
+ this.setWaveformData(this.options.waveform);
1937
+ }
1777
1938
  if (this.audio) {
1778
1939
  this.audio.src = url;
1779
- await new Promise((resolve, reject) => {
1780
- const metadataHandler = () => {
1781
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1782
- this.audio.removeEventListener("error", errorHandler);
1783
- resolve();
1784
- };
1785
- const errorHandler = (e) => {
1786
- this.audio.removeEventListener("loadedmetadata", metadataHandler);
1787
- this.audio.removeEventListener("error", errorHandler);
1788
- reject(e);
1789
- };
1790
- this.audio.addEventListener("loadedmetadata", metadataHandler);
1791
- this.audio.addEventListener("error", errorHandler);
1792
- });
1940
+ if (this.audio.preload !== "none") {
1941
+ await new Promise((resolve, reject) => {
1942
+ const metadataHandler = () => {
1943
+ this.audio.removeEventListener("loadedmetadata", metadataHandler);
1944
+ this.audio.removeEventListener("error", errorHandler);
1945
+ resolve();
1946
+ };
1947
+ const errorHandler = (e) => {
1948
+ this.audio.removeEventListener("loadedmetadata", metadataHandler);
1949
+ this.audio.removeEventListener("error", errorHandler);
1950
+ reject(e);
1951
+ };
1952
+ this.audio.addEventListener("loadedmetadata", metadataHandler);
1953
+ this.audio.addEventListener("error", errorHandler);
1954
+ });
1955
+ }
1793
1956
  }
1794
1957
  const title = this.options.title || extractTitleFromUrl(url);
1795
1958
  if (this.titleEl) {
1796
1959
  this.titleEl.textContent = title;
1797
1960
  }
1798
1961
  this.applySeekLabel(title);
1799
- if (this.options.waveform) {
1800
- this.setWaveformData(this.options.waveform);
1801
- } else {
1962
+ if (!hasInlinePeaks) {
1802
1963
  try {
1803
1964
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
1804
1965
  this.waveformData = result.peaks;
@@ -1862,12 +2023,12 @@ var WaveformPlayer = class _WaveformPlayer {
1862
2023
  }
1863
2024
  this.progress = 0;
1864
2025
  this.waveformData = [];
1865
- this.options = mergeOptions(this.options, {
2026
+ this.options = normalizeOptions(mergeOptions(this.options, {
1866
2027
  url,
1867
2028
  title: title === null ? this.options.title : title,
1868
2029
  artist: artist === null ? this.options.artist : artist,
1869
2030
  ...options
1870
- });
2031
+ }));
1871
2032
  if (hasArtworkOption) {
1872
2033
  this.options.artwork = options.artwork || null;
1873
2034
  }
@@ -1877,10 +2038,10 @@ var WaveformPlayer = class _WaveformPlayer {
1877
2038
  this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : "";
1878
2039
  }
1879
2040
  if (options.preload && this.audio) {
1880
- this.audio.preload = options.preload;
2041
+ this.audio.preload = this.options.preload;
1881
2042
  }
1882
2043
  if (options.crossOrigin && this.audio) {
1883
- this.audio.crossOrigin = options.crossOrigin;
2044
+ this.audio.crossOrigin = this.options.crossOrigin;
1884
2045
  }
1885
2046
  if (artist !== null) {
1886
2047
  this.syncArtist(artist);
@@ -1891,7 +2052,7 @@ var WaveformPlayer = class _WaveformPlayer {
1891
2052
  hasArtworkAltOption ? options.artworkAlt : this.options.artworkAlt
1892
2053
  );
1893
2054
  }
1894
- this.options.markers = options.markers || [];
2055
+ this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
1895
2056
  this.options.waveform = options.waveform || null;
1896
2057
  await this.load(url);
1897
2058
  if (options.autoplay !== false) {
@@ -1919,7 +2080,7 @@ var WaveformPlayer = class _WaveformPlayer {
1919
2080
  fetch(data.trim()).then((r) => r.json()).then((json) => {
1920
2081
  this.waveformData = Array.isArray(json) ? json : json.peaks || [];
1921
2082
  if (json.markers && !this.options.markers?.length) {
1922
- this.options.markers = json.markers;
2083
+ this.options.markers = normalizeMarkers(json.markers);
1923
2084
  this.renderMarkers();
1924
2085
  }
1925
2086
  this.drawWaveform();
@@ -1927,16 +2088,7 @@ var WaveformPlayer = class _WaveformPlayer {
1927
2088
  });
1928
2089
  return;
1929
2090
  }
1930
- if (typeof data === "string") {
1931
- try {
1932
- const parsed = JSON.parse(data);
1933
- this.waveformData = Array.isArray(parsed) ? parsed : [];
1934
- } catch {
1935
- this.waveformData = data.split(",").map(Number);
1936
- }
1937
- } else {
1938
- this.waveformData = Array.isArray(data) ? data : [];
1939
- }
2091
+ this.waveformData = toNumberArray(data, { fallback: [] });
1940
2092
  this.drawWaveform();
1941
2093
  }
1942
2094
  /**
@@ -2215,7 +2367,8 @@ var WaveformPlayer = class _WaveformPlayer {
2215
2367
  setLoading(loading) {
2216
2368
  this.isLoading = loading;
2217
2369
  if (this.loadingEl) {
2218
- this.loadingEl.style.display = loading ? "block" : "none";
2370
+ const showIndicator = loading && this.waveformData.length === 0;
2371
+ this.loadingEl.style.display = showIndicator ? "block" : "none";
2219
2372
  }
2220
2373
  if (this.seekEl) {
2221
2374
  this.seekEl.setAttribute("aria-busy", loading ? "true" : "false");
@@ -2688,14 +2841,20 @@ var WaveformPlayer = class _WaveformPlayer {
2688
2841
  }
2689
2842
  }
2690
2843
  /**
2691
- * Set the owned `<audio>` element's playback rate (clamped to 0.5–2),
2844
+ * Set the owned `<audio>` element's playback rate (clamped to 0.25–4),
2692
2845
  * persist it onto `this.options.playbackRate`, and refresh the speed UI.
2693
2846
  * Self mode only — a no-op in external mode.
2694
- * @param {number} rate - Desired playback rate; clamped to the 0.5–2 range.
2847
+ *
2848
+ * The clamp bounds the range browsers keep audible; the default speed menu
2849
+ * offers a narrower 0.5–2, which `playbackRates` can widen up to these
2850
+ * bounds. A non-numeric rate is ignored rather than assigned, since
2851
+ * `audio.playbackRate = NaN` throws.
2852
+ * @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
2695
2853
  */
2696
2854
  setPlaybackRate(rate) {
2697
2855
  if (!this.audio) return;
2698
- const clampedRate = clamp(rate, 0.5, 2);
2856
+ const clampedRate = toFiniteNumber(rate, null, { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX });
2857
+ if (clampedRate === null) return;
2699
2858
  this.audio.playbackRate = clampedRate;
2700
2859
  this.options.playbackRate = clampedRate;
2701
2860
  this.updateSpeedUI();