@arraypress/waveform-player 1.28.1 → 1.29.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/waveform-player-no-autoinit.cjs +183 -14
- package/dist/waveform-player-no-autoinit.esm.js +2 -2
- package/dist/waveform-player.cjs +183 -14
- package/dist/waveform-player.esm.js +2 -2
- package/dist/waveform-player.js +183 -14
- package/dist/waveform-player.min.js +2 -2
- package/index.d.ts +8 -0
- package/package.json +1 -1
- package/src/js/core.js +196 -16
- package/src/js/entry.js +5 -1
- package/src/js/themes.js +7 -2
- package/src/js/utils.js +33 -1
package/dist/waveform-player.cjs
CHANGED
|
@@ -305,6 +305,19 @@ function resampleData(data, targetLength) {
|
|
|
305
305
|
}
|
|
306
306
|
return result;
|
|
307
307
|
}
|
|
308
|
+
function inTimeRanges(ranges, time) {
|
|
309
|
+
for (let i = 0; i < ranges.length; i++) {
|
|
310
|
+
if (ranges.start(i) - 0.05 <= time && time <= ranges.end(i) + 0.05) return true;
|
|
311
|
+
}
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
function coversDuration(ranges, duration) {
|
|
315
|
+
if (!Number.isFinite(duration) || duration <= 0) return false;
|
|
316
|
+
for (let i = 0; i < ranges.length; i++) {
|
|
317
|
+
if (ranges.start(i) <= 0.05 && ranges.end(i) >= duration - 0.1) return true;
|
|
318
|
+
}
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
308
321
|
|
|
309
322
|
// src/js/drawing.js
|
|
310
323
|
function fitBars(canvas, pitch) {
|
|
@@ -717,7 +730,8 @@ function hasThemeHint(scheme) {
|
|
|
717
730
|
function collectBackdrop(el) {
|
|
718
731
|
let sum = 0;
|
|
719
732
|
let alpha = 0;
|
|
720
|
-
|
|
733
|
+
const up = (node) => node.parentElement || node.getRootNode?.().host || null;
|
|
734
|
+
for (let node = el; node && node.nodeType === 1 && alpha < 0.995; node = up(node)) {
|
|
721
735
|
const c = parseColor(getComputedStyle(node).backgroundColor);
|
|
722
736
|
if (!c || c.a <= 0) continue;
|
|
723
737
|
const weight = c.a * (1 - alpha);
|
|
@@ -1052,6 +1066,8 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
1052
1066
|
static instances = /* @__PURE__ */ new Map();
|
|
1053
1067
|
/** @type {WaveformPlayer|null} */
|
|
1054
1068
|
static currentlyPlaying = null;
|
|
1069
|
+
/** Audio URLs already warned about lacking byte-range support. @private */
|
|
1070
|
+
static _noRangeWarned = /* @__PURE__ */ new Set();
|
|
1055
1071
|
/**
|
|
1056
1072
|
* Create a new WaveformPlayer instance.
|
|
1057
1073
|
*
|
|
@@ -1119,6 +1135,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
1119
1135
|
this.init();
|
|
1120
1136
|
} catch (error) {
|
|
1121
1137
|
_WaveformPlayer.instances.delete(this.id);
|
|
1138
|
+
_WaveformPlayer._releaseThemeWatch();
|
|
1122
1139
|
this._ac.abort();
|
|
1123
1140
|
throw error;
|
|
1124
1141
|
}
|
|
@@ -1539,9 +1556,10 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
1539
1556
|
}, { signal: this._ac.signal });
|
|
1540
1557
|
speedBtn.closest(".waveform-speed")?.addEventListener("keydown", (e) => {
|
|
1541
1558
|
const opts = options();
|
|
1542
|
-
const
|
|
1559
|
+
const focused = this._activeElement();
|
|
1560
|
+
const i = opts.indexOf(focused);
|
|
1543
1561
|
if (!isOpen()) {
|
|
1544
|
-
if ((e.key === "ArrowDown" || e.key === "ArrowUp") &&
|
|
1562
|
+
if ((e.key === "ArrowDown" || e.key === "ArrowUp") && focused === speedBtn) {
|
|
1545
1563
|
e.preventDefault();
|
|
1546
1564
|
setSpeedMenu(true);
|
|
1547
1565
|
}
|
|
@@ -1587,6 +1605,17 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
1587
1605
|
* ±0.1) and `m`/`M` (mute). Listeners use the instance abort signal.
|
|
1588
1606
|
* @private
|
|
1589
1607
|
*/
|
|
1608
|
+
/**
|
|
1609
|
+
* The focused element as seen from this player's own tree. Inside a shadow
|
|
1610
|
+
* root `document.activeElement` is the shadow *host*, so comparing it with
|
|
1611
|
+
* the container (or a control) never matches and every keyboard shortcut
|
|
1612
|
+
* silently stops; the root node's `activeElement` is the real one.
|
|
1613
|
+
* @returns {Element|null}
|
|
1614
|
+
* @private
|
|
1615
|
+
*/
|
|
1616
|
+
_activeElement() {
|
|
1617
|
+
return this.container.getRootNode().activeElement ?? document.activeElement;
|
|
1618
|
+
}
|
|
1590
1619
|
initKeyboardControls() {
|
|
1591
1620
|
this.container.setAttribute("tabindex", "-1");
|
|
1592
1621
|
this.container.addEventListener("click", (e) => {
|
|
@@ -1600,7 +1629,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
1600
1629
|
this.container.focus();
|
|
1601
1630
|
}, { signal: this._ac.signal });
|
|
1602
1631
|
this.container.addEventListener("keydown", (e) => {
|
|
1603
|
-
if (
|
|
1632
|
+
if (this._activeElement() !== this.container) return;
|
|
1604
1633
|
const key = e.key;
|
|
1605
1634
|
const hasAudio = !!this.audio;
|
|
1606
1635
|
const currentTime = hasAudio ? this.audio.currentTime : 0;
|
|
@@ -1867,7 +1896,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
1867
1896
|
this.audio.addEventListener("seeked", () => this._updatePositionState());
|
|
1868
1897
|
this.audio.addEventListener("ratechange", () => this._updatePositionState());
|
|
1869
1898
|
this.audio.addEventListener("timeupdate", () => {
|
|
1870
|
-
if (this.isPlaying && Date.now() - this._frameAt > 500) this.updateProgress();
|
|
1899
|
+
if (this.isPlaying && !this._seekReload && Date.now() - this._frameAt > 500) this.updateProgress();
|
|
1871
1900
|
});
|
|
1872
1901
|
}
|
|
1873
1902
|
this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
|
|
@@ -2013,16 +2042,18 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2013
2042
|
try {
|
|
2014
2043
|
const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
|
|
2015
2044
|
if (id !== this._loadId) return;
|
|
2016
|
-
this.waveformData = result.peaks;
|
|
2045
|
+
if (this.options.waveform === inlinePeaks) this.waveformData = result.peaks;
|
|
2017
2046
|
if (result.bpm) {
|
|
2018
2047
|
this.detectedBPM = result.bpm;
|
|
2019
2048
|
this.updateBPMDisplay();
|
|
2020
2049
|
}
|
|
2021
2050
|
} catch (error) {
|
|
2022
2051
|
if (id !== this._loadId) return;
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2052
|
+
if (this.options.waveform === inlinePeaks) {
|
|
2053
|
+
console.warn("[WaveformPlayer] Using placeholder waveform:", error);
|
|
2054
|
+
this.waveformData = generatePlaceholderWaveform(this.options.samples);
|
|
2055
|
+
this.container.classList.add("waveform-is-placeholder");
|
|
2056
|
+
}
|
|
2026
2057
|
}
|
|
2027
2058
|
}
|
|
2028
2059
|
this.drawWaveform();
|
|
@@ -2046,6 +2077,8 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2046
2077
|
* @private
|
|
2047
2078
|
*/
|
|
2048
2079
|
_resetTrack() {
|
|
2080
|
+
this._cancelCacheSeek?.();
|
|
2081
|
+
this._seekReload = null;
|
|
2049
2082
|
this.progress = 0;
|
|
2050
2083
|
this.waveformData = [];
|
|
2051
2084
|
this._extDuration = 0;
|
|
@@ -2166,6 +2199,13 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2166
2199
|
* carries no peaks resolves `false` and leaves the canvas as it was —
|
|
2167
2200
|
* {@link WaveformPlayer#load} then decodes the audio instead. One that
|
|
2168
2201
|
* resolves after a newer load has started is discarded.
|
|
2202
|
+
*
|
|
2203
|
+
* The data also becomes the current track's `waveform` option, so it
|
|
2204
|
+
* outlives the load already in flight: the first load() runs a frame after
|
|
2205
|
+
* construction (see init()) and draws `options.waveform`, which used to
|
|
2206
|
+
* paint over peaks set before that frame — an easy race to lose with a
|
|
2207
|
+
* cached or fast fetch. A later reload of the same track reuses them too.
|
|
2208
|
+
* {@link WaveformPlayer#loadTrack} still replaces them for a new track.
|
|
2169
2209
|
* @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
|
|
2170
2210
|
* a URL to a `.json` peaks file.
|
|
2171
2211
|
* @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
|
|
@@ -2173,6 +2213,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2173
2213
|
* synchronously).
|
|
2174
2214
|
*/
|
|
2175
2215
|
setWaveformData(data) {
|
|
2216
|
+
this.options.waveform = data;
|
|
2176
2217
|
if (typeof data === "string" && /\.json(?:[?#]|$)/i.test(data.trim())) {
|
|
2177
2218
|
const id = this._loadId;
|
|
2178
2219
|
return fetch(data.trim()).then((r) => {
|
|
@@ -2183,6 +2224,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2183
2224
|
const peaks = toNumberArray(Array.isArray(json) ? json : json?.peaks, { fallback: [] });
|
|
2184
2225
|
if (!peaks.length) throw new Error("no peaks");
|
|
2185
2226
|
this.waveformData = peaks;
|
|
2227
|
+
this.container.classList.remove("waveform-is-placeholder");
|
|
2186
2228
|
if (json.markers && !this.options.markers?.length) {
|
|
2187
2229
|
this.options.markers = normalizeMarkers(json.markers);
|
|
2188
2230
|
this.renderMarkers();
|
|
@@ -2200,6 +2242,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2200
2242
|
});
|
|
2201
2243
|
}
|
|
2202
2244
|
this.waveformData = toNumberArray(data, { fallback: [] });
|
|
2245
|
+
this.container.classList.remove("waveform-is-placeholder");
|
|
2203
2246
|
this.drawWaveform();
|
|
2204
2247
|
}
|
|
2205
2248
|
/**
|
|
@@ -2525,7 +2568,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2525
2568
|
* @fires WaveformPlayer#waveformplayer:play
|
|
2526
2569
|
*/
|
|
2527
2570
|
onPlay() {
|
|
2528
|
-
if (this.isDestroying) return;
|
|
2571
|
+
if (this.isDestroying || this._seekReload) return;
|
|
2529
2572
|
this.isPlaying = true;
|
|
2530
2573
|
this.setPlayButtonState(true);
|
|
2531
2574
|
this.startSmoothUpdate();
|
|
@@ -2544,7 +2587,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2544
2587
|
* @fires WaveformPlayer#waveformplayer:pause
|
|
2545
2588
|
*/
|
|
2546
2589
|
onPause() {
|
|
2547
|
-
if (this.isDestroying) return;
|
|
2590
|
+
if (this.isDestroying || this._seekReload) return;
|
|
2548
2591
|
this.isPlaying = false;
|
|
2549
2592
|
this.setPlayButtonState(false);
|
|
2550
2593
|
this.stopSmoothUpdate();
|
|
@@ -2733,6 +2776,24 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2733
2776
|
}
|
|
2734
2777
|
_WaveformPlayer._themeWatch = { obs, mq, refresh };
|
|
2735
2778
|
}
|
|
2779
|
+
/**
|
|
2780
|
+
* Disconnect the shared theme watcher once no player is registered. The
|
|
2781
|
+
* watcher only ever refreshes registered instances, so with none left it
|
|
2782
|
+
* has nothing to do; the next constructor re-installs it lazily via
|
|
2783
|
+
* {@link WaveformPlayer._watchTheme}. Pages that swap players in and out
|
|
2784
|
+
* (SPAs, block editors) no longer keep a document observer alive forever.
|
|
2785
|
+
* @private
|
|
2786
|
+
*/
|
|
2787
|
+
static _releaseThemeWatch() {
|
|
2788
|
+
const watch = _WaveformPlayer._themeWatch;
|
|
2789
|
+
if (!watch || _WaveformPlayer.instances.size > 0) return;
|
|
2790
|
+
watch.obs.disconnect();
|
|
2791
|
+
try {
|
|
2792
|
+
watch.mq?.removeEventListener("change", watch.refresh);
|
|
2793
|
+
} catch (e) {
|
|
2794
|
+
}
|
|
2795
|
+
_WaveformPlayer._themeWatch = null;
|
|
2796
|
+
}
|
|
2736
2797
|
/**
|
|
2737
2798
|
* Sync the speed control's label and the menu's active-option highlight to
|
|
2738
2799
|
* the audio element's current `playbackRate`. No-op in external mode (no
|
|
@@ -2913,6 +2974,112 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2913
2974
|
this.play();
|
|
2914
2975
|
}
|
|
2915
2976
|
}
|
|
2977
|
+
/**
|
|
2978
|
+
* Move the owned `<audio>` to `time`. The single path every self-mode seek
|
|
2979
|
+
* takes ({@link WaveformPlayer#seekTo}, {@link WaveformPlayer#seekToPercent},
|
|
2980
|
+
* so clicks, drags, keys and the slider too).
|
|
2981
|
+
*
|
|
2982
|
+
* Some hosts ignore HTTP byte ranges: they answer a `Range` request with
|
|
2983
|
+
* `200` and the whole file (Cloudflare Pages and Workers static assets, and
|
|
2984
|
+
* plenty of plain servers). Chromium then can't seek the media at all —
|
|
2985
|
+
* `seekable` stays `0–0` even once every byte has arrived — which is the
|
|
2986
|
+
* "long tracks snap back to 0" symptom. The copy in the browser's HTTP
|
|
2987
|
+
* cache *is* seekable (why a page refresh "fixes" it), so when the target
|
|
2988
|
+
* isn't seekable this reloads the element from cache and seeks there; see
|
|
2989
|
+
* {@link WaveformPlayer#_seekViaCache}. Detection is by the element's own
|
|
2990
|
+
* `seekable`, not the browser, so engines that can already seek (WebKit,
|
|
2991
|
+
* Firefox) never take that path; it runs at most once per file.
|
|
2992
|
+
* @param {number} time - Target position in seconds.
|
|
2993
|
+
* @private
|
|
2994
|
+
*/
|
|
2995
|
+
_seekAudio(time) {
|
|
2996
|
+
const audio = this.audio;
|
|
2997
|
+
const seekable = audio.seekable;
|
|
2998
|
+
if (!Number.isFinite(audio.duration) || !seekable || seekable.length === 0 || inTimeRanges(seekable, time) || this._seekReloadedUrl === this.options.url) {
|
|
2999
|
+
audio.currentTime = time;
|
|
3000
|
+
return;
|
|
3001
|
+
}
|
|
3002
|
+
this._seekViaCache(time);
|
|
3003
|
+
}
|
|
3004
|
+
/**
|
|
3005
|
+
* Seek on a host without byte-range support: once the whole file is
|
|
3006
|
+
* downloaded (raising `preload` to `auto` until it is, then restoring it),
|
|
3007
|
+
* reload the element from the browser cache and seek there. Repeated seeks
|
|
3008
|
+
* while waiting just update the target. Warns once per URL, since the
|
|
3009
|
+
* real fix is serving audio from a range-capable host.
|
|
3010
|
+
* @param {number} time - Target position in seconds.
|
|
3011
|
+
* @private
|
|
3012
|
+
*/
|
|
3013
|
+
_seekViaCache(time) {
|
|
3014
|
+
const audio = this.audio;
|
|
3015
|
+
const url = this.options.url;
|
|
3016
|
+
this._cacheSeekTime = time;
|
|
3017
|
+
if (!_WaveformPlayer._noRangeWarned.has(url)) {
|
|
3018
|
+
_WaveformPlayer._noRangeWarned.add(url);
|
|
3019
|
+
console.warn(`[WaveformPlayer] ${url}: the host ignores HTTP Range requests, so seeking waits for the download and reloads from cache. Serve audio with Range support for instant seeks.`);
|
|
3020
|
+
}
|
|
3021
|
+
if (this._cancelCacheSeek) return;
|
|
3022
|
+
if (coversDuration(audio.buffered, audio.duration)) {
|
|
3023
|
+
this._reloadForSeek(url);
|
|
3024
|
+
return;
|
|
3025
|
+
}
|
|
3026
|
+
const preload = audio.preload;
|
|
3027
|
+
audio.preload = "auto";
|
|
3028
|
+
this.setLoading(true);
|
|
3029
|
+
const stop = () => {
|
|
3030
|
+
audio.removeEventListener("progress", check);
|
|
3031
|
+
audio.removeEventListener("canplaythrough", check);
|
|
3032
|
+
audio.preload = preload;
|
|
3033
|
+
this._cancelCacheSeek = null;
|
|
3034
|
+
};
|
|
3035
|
+
const check = () => {
|
|
3036
|
+
if (this.audio !== audio || this.options.url !== url) return stop();
|
|
3037
|
+
if (!coversDuration(audio.buffered, audio.duration)) return;
|
|
3038
|
+
stop();
|
|
3039
|
+
this._reloadForSeek(url);
|
|
3040
|
+
};
|
|
3041
|
+
this._cancelCacheSeek = stop;
|
|
3042
|
+
audio.addEventListener("progress", check, { signal: this._ac.signal });
|
|
3043
|
+
audio.addEventListener("canplaythrough", check, { signal: this._ac.signal });
|
|
3044
|
+
}
|
|
3045
|
+
/**
|
|
3046
|
+
* Reload the fully-downloaded file from cache, seek to the pending target
|
|
3047
|
+
* and resume. The element's own pause/play events during the reload are
|
|
3048
|
+
* internal plumbing, so onPause/onPlay ignore them while `_seekReload` is
|
|
3049
|
+
* set: consumers (the bar, waveform-tracker) see a seek, not a pause and a
|
|
3050
|
+
* new play, and the button doesn't flicker.
|
|
3051
|
+
* @param {string} url - The file being reloaded.
|
|
3052
|
+
* @private
|
|
3053
|
+
*/
|
|
3054
|
+
_reloadForSeek(url) {
|
|
3055
|
+
const audio = this.audio;
|
|
3056
|
+
const wasPlaying = !audio.paused && !audio.ended;
|
|
3057
|
+
const rate = audio.playbackRate;
|
|
3058
|
+
this._seekReloadedUrl = url;
|
|
3059
|
+
this._seekReload = { wasPlaying };
|
|
3060
|
+
const finish = () => {
|
|
3061
|
+
this._seekReload = null;
|
|
3062
|
+
this.setLoading(false);
|
|
3063
|
+
this.updateProgress();
|
|
3064
|
+
};
|
|
3065
|
+
audio.addEventListener("loadedmetadata", () => {
|
|
3066
|
+
if (this.audio !== audio || this.options.url !== url) return;
|
|
3067
|
+
audio.playbackRate = rate;
|
|
3068
|
+
audio.currentTime = this._cacheSeekTime;
|
|
3069
|
+
if (!wasPlaying) {
|
|
3070
|
+
finish();
|
|
3071
|
+
return;
|
|
3072
|
+
}
|
|
3073
|
+
audio.play().then(() => {
|
|
3074
|
+
finish();
|
|
3075
|
+
this.startSmoothUpdate();
|
|
3076
|
+
}, () => {
|
|
3077
|
+
finish();
|
|
3078
|
+
this.onPause();
|
|
3079
|
+
});
|
|
3080
|
+
}, { once: true, signal: this._ac.signal });
|
|
3081
|
+
audio.load();
|
|
3082
|
+
}
|
|
2916
3083
|
/**
|
|
2917
3084
|
* Seek the owned `<audio>` element to an absolute time, clamped to
|
|
2918
3085
|
* `[0, duration]`, and refresh progress. Self mode only — a no-op when
|
|
@@ -2924,7 +3091,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2924
3091
|
seekTo(seconds) {
|
|
2925
3092
|
const s = Number(seconds);
|
|
2926
3093
|
if (this.audio && this.audio.duration && Number.isFinite(s)) {
|
|
2927
|
-
this.
|
|
3094
|
+
this._seekAudio(clamp(s, 0, this.audio.duration));
|
|
2928
3095
|
this.updateProgress();
|
|
2929
3096
|
}
|
|
2930
3097
|
}
|
|
@@ -2937,7 +3104,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
2937
3104
|
seekToPercent(percent) {
|
|
2938
3105
|
const p = Number(percent);
|
|
2939
3106
|
if (this.audio && this.audio.duration && Number.isFinite(p)) {
|
|
2940
|
-
this.
|
|
3107
|
+
this._seekAudio(this.audio.duration * clamp(p));
|
|
2941
3108
|
this.updateProgress();
|
|
2942
3109
|
}
|
|
2943
3110
|
}
|
|
@@ -3000,6 +3167,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
3000
3167
|
this.resizeHandler = null;
|
|
3001
3168
|
}
|
|
3002
3169
|
_WaveformPlayer.instances.delete(this.id);
|
|
3170
|
+
_WaveformPlayer._releaseThemeWatch();
|
|
3003
3171
|
if (_WaveformPlayer.currentlyPlaying === this) {
|
|
3004
3172
|
_WaveformPlayer.currentlyPlaying = null;
|
|
3005
3173
|
}
|
|
@@ -3054,6 +3222,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
3054
3222
|
static destroyAll() {
|
|
3055
3223
|
this.instances.forEach((player) => player.destroy());
|
|
3056
3224
|
this.instances.clear();
|
|
3225
|
+
this._releaseThemeWatch();
|
|
3057
3226
|
}
|
|
3058
3227
|
/**
|
|
3059
3228
|
* Generate waveform data from audio URL
|
|
@@ -3120,7 +3289,7 @@ var WaveformPlayer = class _WaveformPlayer {
|
|
|
3120
3289
|
};
|
|
3121
3290
|
|
|
3122
3291
|
// src/js/entry.js
|
|
3123
|
-
WaveformPlayer.utils = { formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme };
|
|
3292
|
+
WaveformPlayer.utils = { formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme, extractPeaks };
|
|
3124
3293
|
function initElement(element) {
|
|
3125
3294
|
if (element.dataset.waveformInitialized === "true" || WaveformPlayer.getInstance(element)) {
|
|
3126
3295
|
return;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function I(){return typeof window<"u"&&typeof document<"u"}function j(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function S(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function G(e){return S(typeof e=="number"?`${e}px`:e)}function rt(e){if(typeof e!="string"||e==="")return!1;try{let t=new URL(e,"http://localhost/");return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function m(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function _(e,t=null,i={}){let{min:s=-1/0,max:r=1/0,integer:a=!1}=i,o=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;if(!Number.isFinite(o))return t;let l=m(o,s,r);return a?Math.round(l):l}function O(e,t=null){if(Array.isArray(e))return e;if(typeof e=="string"&&e.trim().startsWith("["))try{let i=JSON.parse(e);if(Array.isArray(i))return i}catch{}return t}function x(e,t={}){let{min:i=-1/0,max:s=1/0,fallback:r=null}=t,a=O(e);if(!a&&typeof e=="string"&&e.trim()!==""&&(a=e.split(/[,\s]+/)),!a)return r;let o=a.map(l=>_(l)).filter(l=>l!==null&&l>=i&&l<=s);return o.length?o:r}function at(e,t,i=null){return t.includes(e)?e:i}function ot(e){if(typeof e=="string"){let t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}function St(e){return e===void 0?void 0:e==="true"}function V(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function W(e){let t={},i=(o,l=o)=>{let n=St(e.dataset[l]);n!==void 0&&(t[o]=n)},s=(o,l=o,n=!1)=>{let h=e.dataset[l];h&&(t[o]=n?parseFloat(h):parseInt(h,10))},r=(o,l=o)=>{let n=e.dataset[l];n&&(t[o]=/^\d+(\.\d+)?$/.test(n.trim())?parseFloat(n):n)},a=(o,l=o)=>{let n=e.dataset[l];if(!n)return;let h=O(n);h?t[o]=h:console.warn(`[WaveformPlayer] Invalid ${l} attribute, expected a JSON array:`,n)};if(e.dataset.src&&(t.url=e.dataset.src),e.dataset.url&&(t.url=e.dataset.url),s("height"),s("samples"),e.dataset.preload&&(t.preload=e.dataset.preload),e.dataset.crossOrigin&&(t.crossOrigin=e.dataset.crossOrigin),e.dataset.audioMode&&(t.audioMode=e.dataset.audioMode),e.dataset.style&&(t.waveformStyle=e.dataset.style),e.dataset.waveformStyle&&(t.waveformStyle=e.dataset.waveformStyle),e.dataset.waveformGradient&&(t.waveformGradient=e.dataset.waveformGradient),s("barWidth"),s("barSpacing"),s("barRadius"),e.dataset.buttonAlign&&(t.buttonAlign=e.dataset.buttonAlign),e.dataset.layout&&(t.layout=e.dataset.layout),e.dataset.buttonStyle&&(t.buttonStyle=e.dataset.buttonStyle),r("buttonSize"),r("buttonRadius"),e.dataset.color&&(t.waveformColor=V(e.dataset.color)),e.dataset.theme&&(t.colorPreset=e.dataset.theme),e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=V(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=V(e.dataset.progressColor)),i("autoplay"),i("showControls"),i("showInfo"),i("showTime"),i("showHoverTime"),i("seekHandle"),i("showBPM","showBpm"),s("bpm"),i("singlePlay"),i("playOnSeek"),e.dataset.title&&(t.title=e.dataset.title),e.dataset.artist&&(t.artist=e.dataset.artist),e.dataset.album&&(t.album=e.dataset.album),e.dataset.artwork&&(t.artwork=e.dataset.artwork),e.dataset.artworkPosition&&(t.artworkPosition=e.dataset.artworkPosition),e.dataset.waveform&&(t.waveform=e.dataset.waveform),a("markers"),s("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),e.dataset.playbackRates){let o=x(e.dataset.playbackRates);o?t.playbackRates=o:console.warn("[WaveformPlayer] Invalid playbackRates attribute:",e.dataset.playbackRates)}return i("enableMediaSession"),i("showMarkers"),i("accessibleSeek"),e.dataset.seekLabel&&(t.seekLabel=e.dataset.seekLabel),e.dataset.seekValueText&&(t.seekValueText=e.dataset.seekValueText),e.dataset.errorText&&(t.errorText=e.dataset.errorText),e.dataset.playPauseLabel&&(t.playPauseLabel=e.dataset.playPauseLabel),e.dataset.speedLabel&&(t.speedLabel=e.dataset.speedLabel),e.dataset.artworkAlt&&(t.artworkAlt=e.dataset.artworkAlt),e.dataset.unknownTrackText&&(t.unknownTrackText=e.dataset.unknownTrackText),e.dataset.playIcon&&(t.playIcon=e.dataset.playIcon),e.dataset.pauseIcon&&(t.pauseIcon=e.dataset.pauseIcon),t}function nt(e,...t){let i=0;return e.replace(/%(?:(\d+)\$)?s/g,(s,r)=>{let a=r?Number(r)-1:i++;return t[a]??s})}function E(e){let t=Number(e);if(!t||!Number.isFinite(t)||t<0)return"0:00";let i=Math.floor(t/3600),s=Math.floor(t%3600/60),r=Math.floor(t%60);return i>0?`${i}:${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${s}:${r.toString().padStart(2,"0")}`}var Et=0;function lt(e){let t=e||"audio",i=5381;for(let s=0;s<t.length;s++)i=(i<<5)+i+t.charCodeAt(s)|0;return`wp_${(i>>>0).toString(36)}_${(Et++).toString(36)}`}function N(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function K(e){if(typeof e!="string")return null;let t=e.match(/rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*(?:[,/]\s*([\d.]+)(%?))?/i);if(!t)return null;let i=Number(t[1]),s=Number(t[2]),r=Number(t[3]);if(!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(r))return null;let a=t[4]===void 0?1:Number(t[4]);return Number.isFinite(a)?(t[5]==="%"&&(a/=100),{r:i,g:s,b:r,a:m(a,0,1)}):null}function ht(e){let t=K(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function Y(...e){let t={};for(let i of e)for(let s in i)i[s]!==null&&i[s]!==void 0&&(t[s]=i[s]);return t}function ct(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}function B(e,t){if(e.length===t)return e;if(e.length===0||t===0)return[];let i=[];if(t>e.length){let s=(e.length-1)/(t-1);for(let r=0;r<t;r++){let a=r*s,o=Math.floor(a),l=Math.ceil(a),n=a-o;if(l>=e.length)i.push(e[e.length-1]);else if(o===l)i.push(e[o]);else{let h=e[o]*(1-n)+e[l]*n;i.push(h)}}}else{let s=e.length/t;for(let r=0;r<t;r++){let a=Math.floor(r*s),o=Math.floor((r+1)*s),l=0,n=0;for(let h=a;h<=o&&h<e.length;h++)e[h]>l&&(l=e[h]),n++;if(n===0){let h=Math.min(Math.round(r*s),e.length-1);l=e[h]}i.push(l)}}return i}function F(e,t){return t>0?Math.floor(e.width/t):0}function P(e,t,i,s){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let r=i.width,a=i.height,o=s&&s.waveformGradient,[l,n,h,c]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let u=e.createLinearGradient(l,n,h,c);return t.forEach((y,g)=>u.addColorStop(g/(t.length-1),y)),u}catch{return t[0]}}function R(e,t,i,s,r,a){if((Array.isArray(a)?a.some(l=>l>0):a>0)&&typeof e.roundRect=="function"){let l=Math.min(s/2,Math.abs(r)/2),n=h=>m(h,0,l);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(n):n(a)),e.fill()}else e.fillRect(t,i,s,r)}function ft(e,t){return(e.barRadius||0)*t}function Pt(e,t){let i=ft(e,t);return[i,i,0,0]}function dt(e,t,i,s,r){let a=r/2;e.beginPath(),e.moveTo(t,s-a),e.lineTo(i-a,s-a),e.arc(i-a,s,a,-Math.PI/2,Math.PI/2),e.lineTo(t,s+a),e.arc(t,s,a,Math.PI/2,-Math.PI/2),e.closePath()}function J(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,l=r.barSpacing*a,n=F(t,o+l),h=B(i,n),c=t.height,u=s*t.width,y=Pt(r,a),g=P(e,r.color,t,r),b=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=g;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p+o>t.width)break;let w=h[f]*c*.9,d=c-w;R(e,p,d,o,w,y)}e.save(),e.beginPath(),e.rect(0,0,u,c),e.clip(),e.fillStyle=b;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p>u)break;let w=h[f]*c*.9,d=c-w;R(e,p,d,o,w,y)}e.restore()}function Tt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,l=r.barSpacing*a,n=F(t,o+l),h=B(i,n),c=t.height,u=c/2,y=s*t.width,g=ft(r,a),b=[g,g,0,0],f=[0,0,g,g],p=P(e,r.color,t,r),w=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=p;for(let d=0;d<h.length;d++){let k=d*(o+l);if(k+o>t.width)break;let v=h[d]*c*.45;R(e,k,u-v,o,v,b),R(e,k,u,o,v,f)}e.save(),e.beginPath(),e.rect(0,0,y,c),e.clip(),e.fillStyle=w;for(let d=0;d<h.length;d++){let k=d*(o+l);if(k>y)break;let v=h[d]*c*.45;R(e,k,u-v,o,v,b),R(e,k,u,o,v,f)}e.restore()}function At(e,t,i,s,r){let a=t.width,o=t.height,l=o/2,n=o*.35;e.clearRect(0,0,a,o);let h=(c,u,y=1,g=!1)=>{let b=P(e,c,t,r),f=Array.isArray(c)?c[c.length-1]:c;g&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=b,e.lineWidth=u,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,l);let p=[],w=Math.floor(i.length*y);for(let d=0;d<w;d++){let k=d/(i.length-1)*a,v=i[d],A=Math.sin(d*.1)*v,L=l+A*n;p.push({x:k,y:L})}for(let d=0;d<p.length-1;d++){let k=p[d].x+(p[d+1].x-p[d].x)*.5,v=p[d].y,A=p[d+1].x-(p[d+1].x-p[d].x)*.5,L=p[d+1].y;e.bezierCurveTo(k,v,A,L,p[d+1].x,p[d+1].y)}e.stroke(),g&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,l),e.lineTo(a,l),e.stroke();for(let c=0;c<=10;c++){let u=a/10*c;e.beginPath(),e.moveTo(u,0),e.lineTo(u,o),e.stroke()}h(r.color,2,1,!1),s>0&&h(r.progressColor,3,s,!0)}function ut(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,l=(r.barSpacing||1)*a,n=F(t,o+l),h=B(i,n),c=t.height,u=4*a,y=2*a,g=s*t.width,b=c/2,f=P(e,r.color,t,r),p=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let w=0;w<h.length;w++){let d=w*(o+l);if(d+o>t.width)break;let k=h[w]*c*.9,v=Math.floor(k/(u+y));e.fillStyle=d<g?p:f;for(let A=0;A<v;A++){let L=A*(u+y);e.fillRect(d,b-L-u,o,u),A>0&&e.fillRect(d,b+L,o,u)}}}function pt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,l=(r.barSpacing||3)*a,n=F(t,o+l),h=B(i,n),c=t.height,u=Math.max(1.5*a,o/2),y=s*t.width,g=c/2,b=P(e,r.color,t,r),f=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let p=0;p<h.length;p++){let w=p*(o+l)+o/2;if(w>t.width)break;let d=h[p]*c*.9;e.fillStyle=w<y?f:b,e.beginPath(),e.arc(w,g-d/2,u,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(w,g+d/2,u,0,Math.PI*2),e.fill()}}function _t(e,t,i,s,r){let a=t.width,o=t.height,l=o/2,n=4,h=n/2,c=!!r.seekActive;if(e.clearRect(0,0,a,o),e.fillStyle=P(e,r.color,t,r)||"rgba(255, 255, 255, 0.2)",dt(e,h,a,l,n),e.fill(),s>0){let u=Math.max(h*2,s*a);e.save(),e.globalAlpha=r.seekHandle&&!c?.7:1,e.fillStyle=P(e,r.progressColor,t,r)||"rgba(255, 255, 255, 0.9)",dt(e,h,u,l,n),e.fill(),e.restore()}}var Mt={bars:J,bar:J,mirror:Tt,line:At,blocks:ut,block:ut,dots:pt,dot:pt,seekbar:_t};function mt(e,t,i,s,r){(Mt[r.waveformStyle]||J)(e,t,i,s,r)}function yt(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=Ct(t,i);if(s.length<2)return null;let r=[];for(let n=1;n<s.length;n++)r.push((s[n]-s[n-1])/i);let a={};r.forEach(n=>{let h=60/n,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,l=null;for(let[n,h]of Object.entries(a))h>o&&(o=h,l=parseInt(n));return l===null?null:(l<70&&a[l*2]?l*=2:l>160&&a[Math.round(l/2)]&&(l=Math.round(l/2)),l-1)}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function Ct(e,t){let r=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let l=0;for(let c=o;c<o+2048;c++)l+=e[c]*e[c];l=l/2048;let n=l-a,h=a*1.8+.01;if(n>h&&l>.01){let c=r[r.length-1]||0,u=t*.15;o-c>u&&r.push(o)}a=l*.8+a*.2}return r}function Lt(e,t=1800){let i=e.length/t,s=e.numberOfChannels,r=[];for(let o=0;o<s;o++){let l=e.getChannelData(o);for(let n=0;n<t;n++){let h=~~(n*i),c=~~(h+i),u=0,y=0;for(let b=h;b<c;b++){let f=l[b];f>y&&(y=f),f<u&&(u=f)}let g=Math.max(Math.abs(y),Math.abs(u));(o===0||g>r[n])&&(r[n]=g)}}let a=j(r);return a>0?r.map(o=>o/a):r}async function X(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),l=await s.decodeAudioData(o),n=Lt(l,t);n=xt(n);let h=null;return i&&(h=yt(l)),{peaks:n,bpm:h}}finally{s&&s.close()}}function gt(e=1800){let t=[];for(let i=0;i<e;i++){let s=Math.random()*.5+.3,r=Math.sin(i/e*Math.PI*4)*.2;t.push(m(s+r,.1,1))}return t}function xt(e,t=.95){let i=j(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}var Q=128;function wt(e){let t=document.documentElement,i=document.body;return t.classList.contains(e)||t.classList.contains(`${e}-mode`)||t.classList.contains(`theme-${e}`)||t.getAttribute("data-theme")===e||t.getAttribute("data-color-scheme")===e||i.classList.contains(e)||i.classList.contains(`${e}-mode`)||i.getAttribute("data-theme")===e}function Rt(e){let t=0,i=0;for(let s=e;s&&s.nodeType===1&&i<.995;s=s.parentElement){let r=K(getComputedStyle(s).backgroundColor);if(!r||r.a<=0)continue;let a=r.a*(1-i);t+=(r.r*299+r.g*587+r.b*114)/1e3*a,i+=a}return{sum:t,alpha:i}}function Dt(){let e=ht(getComputedStyle(document.body).color);if(e!==null)return e>Q?"dark":"light";if(window.matchMedia){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return"dark";if(window.matchMedia("(prefers-color-scheme: light)").matches)return"light"}return"dark"}function D(e){if(wt("dark"))return"dark";if(wt("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:s}=Rt(t),r=Dt(),a=i+(r==="dark"?0:255)*(1-s);return a>Q?"light":a<Q?"dark":r}catch{return"dark"}}var C={dark:{waveformColor:"rgba(255, 255, 255, 0.3)",progressColor:"rgba(255, 255, 255, 0.9)"},light:{waveformColor:"rgba(0, 0, 0, 0.2)",progressColor:"rgba(0, 0, 0, 0.8)"}};function tt(e,t){if(e&&C[e])return C[e];let i=D(t);return C[i]}var H={url:"",height:64,samples:1800,preload:"metadata",crossOrigin:null,audioMode:"self",playbackRate:1,showPlaybackSpeed:!1,playbackRates:[.5,.75,1,1.25,1.5,1.75,2],buttonAlign:"auto",layout:"default",buttonStyle:"circle",buttonSize:null,buttonRadius:null,waveformStyle:"mirror",barWidth:2,barSpacing:0,barRadius:1,waveformGradient:"vertical",colorPreset:null,waveformColor:null,progressColor:null,autoplay:!1,showControls:!0,showInfo:!0,showTime:!0,showHoverTime:!1,seekHandle:!1,showBPM:!1,bpm:null,singlePlay:!0,playOnSeek:!0,enableMediaSession:!0,markers:[],showMarkers:!0,accessibleSeek:!0,seekLabel:null,seekValueText:null,title:null,artist:null,artwork:null,artworkPosition:"info",album:"",errorText:"Unable to load audio",playPauseLabel:"Play/Pause",speedLabel:"Playback speed",artworkAlt:"Album artwork",unknownTrackText:"Unknown Track",playIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 5v14l11-7z"/></svg>',pauseIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>',onLoad:null,onPlay:null,onPause:null,onEnd:null,onError:null,onTimeUpdate:null,onNextTrack:null,onPreviousTrack:null},et={bars:{barWidth:3,barSpacing:1},mirror:{barWidth:2,barSpacing:2},line:{barWidth:2,barSpacing:0},blocks:{barWidth:4,barSpacing:2},dots:{barWidth:3,barSpacing:3},seekbar:{barWidth:1,barSpacing:0}},it=["auto","top","center","bottom"],$=.25,z=4,It={buttonAlign:it,layout:["default","preview"],buttonStyle:["circle","minimal"],artworkPosition:["info","button"],waveformStyle:Object.keys(et),waveformGradient:["vertical","horizontal","diagonal"],audioMode:["self","external"],preload:["none","metadata","auto"],colorPreset:Object.keys(C),crossOrigin:["anonymous","use-credentials"]},Bt={height:{min:1,integer:!0},samples:{min:1,integer:!0},barWidth:{min:.1},barSpacing:{min:0},barRadius:{min:0},bpm:{min:1},playbackRate:{min:$,max:z}},Ht=["autoplay","showControls","showInfo","showTime","showHoverTime","seekHandle","showBPM","singlePlay","playOnSeek","enableMediaSession","showMarkers","accessibleSeek","showPlaybackSpeed"],Ot=["onLoad","onPlay","onPause","onEnd","onError","onTimeUpdate","onNextTrack","onPreviousTrack"];function Z(e,t){console.warn(`[WaveformPlayer] Invalid ${e} option, using default:`,t)}function q(e){let t=O(e);return t?t.reduce((i,s)=>{let r=s&&typeof s=="object"?_(s.time,null,{min:0}):null;return r===null?(Z("marker",s),i):(i.push({...s,time:r,label:s.label==null?"":s.label}),i)},[]):(e!=null&&Z("markers",e),[])}function st(e){let t=s=>e[s]!=null,i=s=>{Z(s,e[s]),e[s]=H[s]};for(let[s,r]of Object.entries(Bt)){if(!t(s))continue;let a=_(e[s],null,r);a===null?i(s):e[s]=a}for(let[s,r]of Object.entries(It))t(s)&&at(e[s],r)===null&&i(s);for(let s of Ht)e[s]=ot(e[s]);for(let s of Ot)t(s)&&typeof e[s]!="function"&&i(s);if(t("playbackRates")){let s=x(e.playbackRates,{min:$,max:z,fallback:null});s===null?i("playbackRates"):e.playbackRates=s}e.markers=q(e.markers);for(let s of["buttonSize","buttonRadius"]){if(!t(s))continue;let r=e[s];(typeof r=="number"?Number.isFinite(r):typeof r=="string"&&r.trim()!=="")||i(s)}for(let s of["waveformColor","progressColor"]){if(!t(s))continue;let r=e[s];!(typeof r=="string"&&r.trim()!=="")&&!Array.isArray(r)&&i(s)}return e}var Wt="data:image/svg+xml,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'),bt=5,kt=10,Nt='button, a[href], input, [role="slider"]',T=class e{static instances=new Map;static currentlyPlaying=null;constructor(t,i={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("[WaveformPlayer] Container element not found");let s=W(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=st(Y(H,s,r));let a=tt(this.options.colorPreset,this.container);this._autoTheme=this.options.colorPreset==null||!C[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&C[this.options.colorPreset]?this.options.colorPreset:D(this.container);for(let[l,n]of Object.entries(a))(this.options[l]===null||this.options[l]===void 0)&&(this.options[l]=n,this._presetKeys.push(l));let o=et[this.options.waveformStyle];o&&(s.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=o.barWidth),s.barSpacing===void 0&&i.barSpacing===void 0&&(this.options.barSpacing=o.barSpacing)),this.audio=null,this.canvas=null,this.ctx=null,this.waveformData=[],this.progress=0,this._activeMarkerIndex=-1,this._markerLabelTimer=null,this.isPlaying=!1,this.isLoading=!1,this.hasError=!1,this.updateTimer=null,this.resizeObserver=null,this._loadId=0,this._ac=new AbortController,this.id=this.container.id||lt(this.options.url),e.instances.set(this.id,this),e._watchTheme();try{this.init()}catch(l){throw e.instances.delete(this.id),this._ac.abort(),l}this._readyTimer=setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,s=!1){let r=new CustomEvent(t,{bubbles:!0,cancelable:s,detail:i});return this.container.dispatchEvent(r),r}_requestSeek(t){this._emit("waveformplayer:request-seek",{...this._buildTrackDetail(),percent:t},!0).defaultPrevented||(this.progress=t,this.drawWaveform?.())}init(){this.createDOM(),this.createAudio(),this.initPlaybackSpeed(),this.initKeyboardControls(),this.initSeekControl(),this.bindEvents(),this.setupResizeObserver(),requestAnimationFrame(()=>{this.isDestroying||(this.resizeCanvas(),this.options.url&&!this._loadId&&this.load(this.options.url).then(()=>{this.options.autoplay&&this.play()?.catch(()=>{})}).catch(t=>{console.error("[WaveformPlayer] Failed to load audio:",t)}))})}createDOM(){this.container.innerHTML="",this.container.className="waveform-player";let t=it.includes(this.options.buttonAlign)?this.options.buttonAlign:"auto";t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview"),this.container.classList.toggle("waveform-theme-light",this._scheme==="light");let s=[];this.options.buttonSize!=null&&s.push(`--wfp-btn-size: ${G(this.options.buttonSize)}`),this.options.buttonRadius!=null&&s.push(`--wfp-btn-radius: ${G(this.options.buttonRadius)}`);let r=s.length?` style="${s.join("; ")};"`:"",a=this.options.artworkPosition==="button"&&this.options.artwork,o=a?`<img class="waveform-btn-artwork" src="${S(this.options.artwork)}" alt="" aria-hidden="true">`:"",l=this.options.showControls?`
|
|
1
|
+
function I(){return typeof window<"u"&&typeof document<"u"}function j(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function S(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function G(e){return S(typeof e=="number"?`${e}px`:e)}function ot(e){if(typeof e!="string"||e==="")return!1;try{let t=new URL(e,"http://localhost/");return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function m(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function _(e,t=null,i={}){let{min:s=-1/0,max:r=1/0,integer:a=!1}=i,o=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;if(!Number.isFinite(o))return t;let l=m(o,s,r);return a?Math.round(l):l}function O(e,t=null){if(Array.isArray(e))return e;if(typeof e=="string"&&e.trim().startsWith("["))try{let i=JSON.parse(e);if(Array.isArray(i))return i}catch{}return t}function x(e,t={}){let{min:i=-1/0,max:s=1/0,fallback:r=null}=t,a=O(e);if(!a&&typeof e=="string"&&e.trim()!==""&&(a=e.split(/[,\s]+/)),!a)return r;let o=a.map(l=>_(l)).filter(l=>l!==null&&l>=i&&l<=s);return o.length?o:r}function nt(e,t,i=null){return t.includes(e)?e:i}function lt(e){if(typeof e=="string"){let t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}function Tt(e){return e===void 0?void 0:e==="true"}function V(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function W(e){let t={},i=(o,l=o)=>{let n=Tt(e.dataset[l]);n!==void 0&&(t[o]=n)},s=(o,l=o,n=!1)=>{let h=e.dataset[l];h&&(t[o]=n?parseFloat(h):parseInt(h,10))},r=(o,l=o)=>{let n=e.dataset[l];n&&(t[o]=/^\d+(\.\d+)?$/.test(n.trim())?parseFloat(n):n)},a=(o,l=o)=>{let n=e.dataset[l];if(!n)return;let h=O(n);h?t[o]=h:console.warn(`[WaveformPlayer] Invalid ${l} attribute, expected a JSON array:`,n)};if(e.dataset.src&&(t.url=e.dataset.src),e.dataset.url&&(t.url=e.dataset.url),s("height"),s("samples"),e.dataset.preload&&(t.preload=e.dataset.preload),e.dataset.crossOrigin&&(t.crossOrigin=e.dataset.crossOrigin),e.dataset.audioMode&&(t.audioMode=e.dataset.audioMode),e.dataset.style&&(t.waveformStyle=e.dataset.style),e.dataset.waveformStyle&&(t.waveformStyle=e.dataset.waveformStyle),e.dataset.waveformGradient&&(t.waveformGradient=e.dataset.waveformGradient),s("barWidth"),s("barSpacing"),s("barRadius"),e.dataset.buttonAlign&&(t.buttonAlign=e.dataset.buttonAlign),e.dataset.layout&&(t.layout=e.dataset.layout),e.dataset.buttonStyle&&(t.buttonStyle=e.dataset.buttonStyle),r("buttonSize"),r("buttonRadius"),e.dataset.color&&(t.waveformColor=V(e.dataset.color)),e.dataset.theme&&(t.colorPreset=e.dataset.theme),e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=V(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=V(e.dataset.progressColor)),i("autoplay"),i("showControls"),i("showInfo"),i("showTime"),i("showHoverTime"),i("seekHandle"),i("showBPM","showBpm"),s("bpm"),i("singlePlay"),i("playOnSeek"),e.dataset.title&&(t.title=e.dataset.title),e.dataset.artist&&(t.artist=e.dataset.artist),e.dataset.album&&(t.album=e.dataset.album),e.dataset.artwork&&(t.artwork=e.dataset.artwork),e.dataset.artworkPosition&&(t.artworkPosition=e.dataset.artworkPosition),e.dataset.waveform&&(t.waveform=e.dataset.waveform),a("markers"),s("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),e.dataset.playbackRates){let o=x(e.dataset.playbackRates);o?t.playbackRates=o:console.warn("[WaveformPlayer] Invalid playbackRates attribute:",e.dataset.playbackRates)}return i("enableMediaSession"),i("showMarkers"),i("accessibleSeek"),e.dataset.seekLabel&&(t.seekLabel=e.dataset.seekLabel),e.dataset.seekValueText&&(t.seekValueText=e.dataset.seekValueText),e.dataset.errorText&&(t.errorText=e.dataset.errorText),e.dataset.playPauseLabel&&(t.playPauseLabel=e.dataset.playPauseLabel),e.dataset.speedLabel&&(t.speedLabel=e.dataset.speedLabel),e.dataset.artworkAlt&&(t.artworkAlt=e.dataset.artworkAlt),e.dataset.unknownTrackText&&(t.unknownTrackText=e.dataset.unknownTrackText),e.dataset.playIcon&&(t.playIcon=e.dataset.playIcon),e.dataset.pauseIcon&&(t.pauseIcon=e.dataset.pauseIcon),t}function ht(e,...t){let i=0;return e.replace(/%(?:(\d+)\$)?s/g,(s,r)=>{let a=r?Number(r)-1:i++;return t[a]??s})}function E(e){let t=Number(e);if(!t||!Number.isFinite(t)||t<0)return"0:00";let i=Math.floor(t/3600),s=Math.floor(t%3600/60),r=Math.floor(t%60);return i>0?`${i}:${s.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${s}:${r.toString().padStart(2,"0")}`}var At=0;function ct(e){let t=e||"audio",i=5381;for(let s=0;s<t.length;s++)i=(i<<5)+i+t.charCodeAt(s)|0;return`wp_${(i>>>0).toString(36)}_${(At++).toString(36)}`}function N(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function K(e){if(typeof e!="string")return null;let t=e.match(/rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*(?:[,/]\s*([\d.]+)(%?))?/i);if(!t)return null;let i=Number(t[1]),s=Number(t[2]),r=Number(t[3]);if(!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(r))return null;let a=t[4]===void 0?1:Number(t[4]);return Number.isFinite(a)?(t[5]==="%"&&(a/=100),{r:i,g:s,b:r,a:m(a,0,1)}):null}function dt(e){let t=K(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function Y(...e){let t={};for(let i of e)for(let s in i)i[s]!==null&&i[s]!==void 0&&(t[s]=i[s]);return t}function ut(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}function B(e,t){if(e.length===t)return e;if(e.length===0||t===0)return[];let i=[];if(t>e.length){let s=(e.length-1)/(t-1);for(let r=0;r<t;r++){let a=r*s,o=Math.floor(a),l=Math.ceil(a),n=a-o;if(l>=e.length)i.push(e[e.length-1]);else if(o===l)i.push(e[o]);else{let h=e[o]*(1-n)+e[l]*n;i.push(h)}}}else{let s=e.length/t;for(let r=0;r<t;r++){let a=Math.floor(r*s),o=Math.floor((r+1)*s),l=0,n=0;for(let h=a;h<=o&&h<e.length;h++)e[h]>l&&(l=e[h]),n++;if(n===0){let h=Math.min(Math.round(r*s),e.length-1);l=e[h]}i.push(l)}}return i}function pt(e,t){for(let i=0;i<e.length;i++)if(e.start(i)-.05<=t&&t<=e.end(i)+.05)return!0;return!1}function J(e,t){if(!Number.isFinite(t)||t<=0)return!1;for(let i=0;i<e.length;i++)if(e.start(i)<=.05&&e.end(i)>=t-.1)return!0;return!1}function F(e,t){return t>0?Math.floor(e.width/t):0}function P(e,t,i,s){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let r=i.width,a=i.height,o=s&&s.waveformGradient,[l,n,h,c]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let d=e.createLinearGradient(l,n,h,c);return t.forEach((y,g)=>d.addColorStop(g/(t.length-1),y)),d}catch{return t[0]}}function R(e,t,i,s,r,a){if((Array.isArray(a)?a.some(l=>l>0):a>0)&&typeof e.roundRect=="function"){let l=Math.min(s/2,Math.abs(r)/2),n=h=>m(h,0,l);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(n):n(a)),e.fill()}else e.fillRect(t,i,s,r)}function gt(e,t){return(e.barRadius||0)*t}function _t(e,t){let i=gt(e,t);return[i,i,0,0]}function ft(e,t,i,s,r){let a=r/2;e.beginPath(),e.moveTo(t,s-a),e.lineTo(i-a,s-a),e.arc(i-a,s,a,-Math.PI/2,Math.PI/2),e.lineTo(t,s+a),e.arc(t,s,a,Math.PI/2,-Math.PI/2),e.closePath()}function X(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,l=r.barSpacing*a,n=F(t,o+l),h=B(i,n),c=t.height,d=s*t.width,y=_t(r,a),g=P(e,r.color,t,r),w=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=g;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p+o>t.width)break;let k=h[f]*c*.9,u=c-k;R(e,p,u,o,k,y)}e.save(),e.beginPath(),e.rect(0,0,d,c),e.clip(),e.fillStyle=w;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p>d)break;let k=h[f]*c*.9,u=c-k;R(e,p,u,o,k,y)}e.restore()}function Mt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,l=r.barSpacing*a,n=F(t,o+l),h=B(i,n),c=t.height,d=c/2,y=s*t.width,g=gt(r,a),w=[g,g,0,0],f=[0,0,g,g],p=P(e,r.color,t,r),k=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=p;for(let u=0;u<h.length;u++){let b=u*(o+l);if(b+o>t.width)break;let v=h[u]*c*.45;R(e,b,d-v,o,v,w),R(e,b,d,o,v,f)}e.save(),e.beginPath(),e.rect(0,0,y,c),e.clip(),e.fillStyle=k;for(let u=0;u<h.length;u++){let b=u*(o+l);if(b>y)break;let v=h[u]*c*.45;R(e,b,d-v,o,v,w),R(e,b,d,o,v,f)}e.restore()}function Ct(e,t,i,s,r){let a=t.width,o=t.height,l=o/2,n=o*.35;e.clearRect(0,0,a,o);let h=(c,d,y=1,g=!1)=>{let w=P(e,c,t,r),f=Array.isArray(c)?c[c.length-1]:c;g&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=w,e.lineWidth=d,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,l);let p=[],k=Math.floor(i.length*y);for(let u=0;u<k;u++){let b=u/(i.length-1)*a,v=i[u],A=Math.sin(u*.1)*v,L=l+A*n;p.push({x:b,y:L})}for(let u=0;u<p.length-1;u++){let b=p[u].x+(p[u+1].x-p[u].x)*.5,v=p[u].y,A=p[u+1].x-(p[u+1].x-p[u].x)*.5,L=p[u+1].y;e.bezierCurveTo(b,v,A,L,p[u+1].x,p[u+1].y)}e.stroke(),g&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,l),e.lineTo(a,l),e.stroke();for(let c=0;c<=10;c++){let d=a/10*c;e.beginPath(),e.moveTo(d,0),e.lineTo(d,o),e.stroke()}h(r.color,2,1,!1),s>0&&h(r.progressColor,3,s,!0)}function mt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,l=(r.barSpacing||1)*a,n=F(t,o+l),h=B(i,n),c=t.height,d=4*a,y=2*a,g=s*t.width,w=c/2,f=P(e,r.color,t,r),p=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let k=0;k<h.length;k++){let u=k*(o+l);if(u+o>t.width)break;let b=h[k]*c*.9,v=Math.floor(b/(d+y));e.fillStyle=u<g?p:f;for(let A=0;A<v;A++){let L=A*(d+y);e.fillRect(u,w-L-d,o,d),A>0&&e.fillRect(u,w+L,o,d)}}}function yt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,l=(r.barSpacing||3)*a,n=F(t,o+l),h=B(i,n),c=t.height,d=Math.max(1.5*a,o/2),y=s*t.width,g=c/2,w=P(e,r.color,t,r),f=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let p=0;p<h.length;p++){let k=p*(o+l)+o/2;if(k>t.width)break;let u=h[p]*c*.9;e.fillStyle=k<y?f:w,e.beginPath(),e.arc(k,g-u/2,d,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(k,g+u/2,d,0,Math.PI*2),e.fill()}}function Lt(e,t,i,s,r){let a=t.width,o=t.height,l=o/2,n=4,h=n/2,c=!!r.seekActive;if(e.clearRect(0,0,a,o),e.fillStyle=P(e,r.color,t,r)||"rgba(255, 255, 255, 0.2)",ft(e,h,a,l,n),e.fill(),s>0){let d=Math.max(h*2,s*a);e.save(),e.globalAlpha=r.seekHandle&&!c?.7:1,e.fillStyle=P(e,r.progressColor,t,r)||"rgba(255, 255, 255, 0.9)",ft(e,h,d,l,n),e.fill(),e.restore()}}var xt={bars:X,bar:X,mirror:Mt,line:Ct,blocks:mt,block:mt,dots:yt,dot:yt,seekbar:Lt};function kt(e,t,i,s,r){(xt[r.waveformStyle]||X)(e,t,i,s,r)}function wt(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=Rt(t,i);if(s.length<2)return null;let r=[];for(let n=1;n<s.length;n++)r.push((s[n]-s[n-1])/i);let a={};r.forEach(n=>{let h=60/n,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,l=null;for(let[n,h]of Object.entries(a))h>o&&(o=h,l=parseInt(n));return l===null?null:(l<70&&a[l*2]?l*=2:l>160&&a[Math.round(l/2)]&&(l=Math.round(l/2)),l-1)}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function Rt(e,t){let r=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let l=0;for(let c=o;c<o+2048;c++)l+=e[c]*e[c];l=l/2048;let n=l-a,h=a*1.8+.01;if(n>h&&l>.01){let c=r[r.length-1]||0,d=t*.15;o-c>d&&r.push(o)}a=l*.8+a*.2}return r}function Q(e,t=1800){let i=e.length/t,s=e.numberOfChannels,r=[];for(let o=0;o<s;o++){let l=e.getChannelData(o);for(let n=0;n<t;n++){let h=~~(n*i),c=~~(h+i),d=0,y=0;for(let w=h;w<c;w++){let f=l[w];f>y&&(y=f),f<d&&(d=f)}let g=Math.max(Math.abs(y),Math.abs(d));(o===0||g>r[n])&&(r[n]=g)}}let a=j(r);return a>0?r.map(o=>o/a):r}async function Z(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),l=await s.decodeAudioData(o),n=Q(l,t);n=Dt(n);let h=null;return i&&(h=wt(l)),{peaks:n,bpm:h}}finally{s&&s.close()}}function bt(e=1800){let t=[];for(let i=0;i<e;i++){let s=Math.random()*.5+.3,r=Math.sin(i/e*Math.PI*4)*.2;t.push(m(s+r,.1,1))}return t}function Dt(e,t=.95){let i=j(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}var tt=128;function vt(e){let t=document.documentElement,i=document.body;return t.classList.contains(e)||t.classList.contains(`${e}-mode`)||t.classList.contains(`theme-${e}`)||t.getAttribute("data-theme")===e||t.getAttribute("data-color-scheme")===e||i.classList.contains(e)||i.classList.contains(`${e}-mode`)||i.getAttribute("data-theme")===e}function It(e){let t=0,i=0,s=r=>r.parentElement||r.getRootNode?.().host||null;for(let r=e;r&&r.nodeType===1&&i<.995;r=s(r)){let a=K(getComputedStyle(r).backgroundColor);if(!a||a.a<=0)continue;let o=a.a*(1-i);t+=(a.r*299+a.g*587+a.b*114)/1e3*o,i+=o}return{sum:t,alpha:i}}function Bt(){let e=dt(getComputedStyle(document.body).color);if(e!==null)return e>tt?"dark":"light";if(window.matchMedia){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return"dark";if(window.matchMedia("(prefers-color-scheme: light)").matches)return"light"}return"dark"}function D(e){if(vt("dark"))return"dark";if(vt("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:s}=It(t),r=Bt(),a=i+(r==="dark"?0:255)*(1-s);return a>tt?"light":a<tt?"dark":r}catch{return"dark"}}var C={dark:{waveformColor:"rgba(255, 255, 255, 0.3)",progressColor:"rgba(255, 255, 255, 0.9)"},light:{waveformColor:"rgba(0, 0, 0, 0.2)",progressColor:"rgba(0, 0, 0, 0.8)"}};function it(e,t){if(e&&C[e])return C[e];let i=D(t);return C[i]}var H={url:"",height:64,samples:1800,preload:"metadata",crossOrigin:null,audioMode:"self",playbackRate:1,showPlaybackSpeed:!1,playbackRates:[.5,.75,1,1.25,1.5,1.75,2],buttonAlign:"auto",layout:"default",buttonStyle:"circle",buttonSize:null,buttonRadius:null,waveformStyle:"mirror",barWidth:2,barSpacing:0,barRadius:1,waveformGradient:"vertical",colorPreset:null,waveformColor:null,progressColor:null,autoplay:!1,showControls:!0,showInfo:!0,showTime:!0,showHoverTime:!1,seekHandle:!1,showBPM:!1,bpm:null,singlePlay:!0,playOnSeek:!0,enableMediaSession:!0,markers:[],showMarkers:!0,accessibleSeek:!0,seekLabel:null,seekValueText:null,title:null,artist:null,artwork:null,artworkPosition:"info",album:"",errorText:"Unable to load audio",playPauseLabel:"Play/Pause",speedLabel:"Playback speed",artworkAlt:"Album artwork",unknownTrackText:"Unknown Track",playIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 5v14l11-7z"/></svg>',pauseIcon:'<svg viewBox="0 0 24 24" width="16" height="16"><path d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>',onLoad:null,onPlay:null,onPause:null,onEnd:null,onError:null,onTimeUpdate:null,onNextTrack:null,onPreviousTrack:null},st={bars:{barWidth:3,barSpacing:1},mirror:{barWidth:2,barSpacing:2},line:{barWidth:2,barSpacing:0},blocks:{barWidth:4,barSpacing:2},dots:{barWidth:3,barSpacing:3},seekbar:{barWidth:1,barSpacing:0}},rt=["auto","top","center","bottom"],$=.25,z=4,Ht={buttonAlign:rt,layout:["default","preview"],buttonStyle:["circle","minimal"],artworkPosition:["info","button"],waveformStyle:Object.keys(st),waveformGradient:["vertical","horizontal","diagonal"],audioMode:["self","external"],preload:["none","metadata","auto"],colorPreset:Object.keys(C),crossOrigin:["anonymous","use-credentials"]},Ot={height:{min:1,integer:!0},samples:{min:1,integer:!0},barWidth:{min:.1},barSpacing:{min:0},barRadius:{min:0},bpm:{min:1},playbackRate:{min:$,max:z}},Wt=["autoplay","showControls","showInfo","showTime","showHoverTime","seekHandle","showBPM","singlePlay","playOnSeek","enableMediaSession","showMarkers","accessibleSeek","showPlaybackSpeed"],Nt=["onLoad","onPlay","onPause","onEnd","onError","onTimeUpdate","onNextTrack","onPreviousTrack"];function et(e,t){console.warn(`[WaveformPlayer] Invalid ${e} option, using default:`,t)}function U(e){let t=O(e);return t?t.reduce((i,s)=>{let r=s&&typeof s=="object"?_(s.time,null,{min:0}):null;return r===null?(et("marker",s),i):(i.push({...s,time:r,label:s.label==null?"":s.label}),i)},[]):(e!=null&&et("markers",e),[])}function at(e){let t=s=>e[s]!=null,i=s=>{et(s,e[s]),e[s]=H[s]};for(let[s,r]of Object.entries(Ot)){if(!t(s))continue;let a=_(e[s],null,r);a===null?i(s):e[s]=a}for(let[s,r]of Object.entries(Ht))t(s)&&nt(e[s],r)===null&&i(s);for(let s of Wt)e[s]=lt(e[s]);for(let s of Nt)t(s)&&typeof e[s]!="function"&&i(s);if(t("playbackRates")){let s=x(e.playbackRates,{min:$,max:z,fallback:null});s===null?i("playbackRates"):e.playbackRates=s}e.markers=U(e.markers);for(let s of["buttonSize","buttonRadius"]){if(!t(s))continue;let r=e[s];(typeof r=="number"?Number.isFinite(r):typeof r=="string"&&r.trim()!=="")||i(s)}for(let s of["waveformColor","progressColor"]){if(!t(s))continue;let r=e[s];!(typeof r=="string"&&r.trim()!=="")&&!Array.isArray(r)&&i(s)}return e}var Ft="data:image/svg+xml,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'),St=5,Et=10,$t='button, a[href], input, [role="slider"]',T=class e{static instances=new Map;static currentlyPlaying=null;static _noRangeWarned=new Set;constructor(t,i={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("[WaveformPlayer] Container element not found");let s=W(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=at(Y(H,s,r));let a=it(this.options.colorPreset,this.container);this._autoTheme=this.options.colorPreset==null||!C[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&C[this.options.colorPreset]?this.options.colorPreset:D(this.container);for(let[l,n]of Object.entries(a))(this.options[l]===null||this.options[l]===void 0)&&(this.options[l]=n,this._presetKeys.push(l));let o=st[this.options.waveformStyle];o&&(s.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=o.barWidth),s.barSpacing===void 0&&i.barSpacing===void 0&&(this.options.barSpacing=o.barSpacing)),this.audio=null,this.canvas=null,this.ctx=null,this.waveformData=[],this.progress=0,this._activeMarkerIndex=-1,this._markerLabelTimer=null,this.isPlaying=!1,this.isLoading=!1,this.hasError=!1,this.updateTimer=null,this.resizeObserver=null,this._loadId=0,this._ac=new AbortController,this.id=this.container.id||ct(this.options.url),e.instances.set(this.id,this),e._watchTheme();try{this.init()}catch(l){throw e.instances.delete(this.id),e._releaseThemeWatch(),this._ac.abort(),l}this._readyTimer=setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,s=!1){let r=new CustomEvent(t,{bubbles:!0,cancelable:s,detail:i});return this.container.dispatchEvent(r),r}_requestSeek(t){this._emit("waveformplayer:request-seek",{...this._buildTrackDetail(),percent:t},!0).defaultPrevented||(this.progress=t,this.drawWaveform?.())}init(){this.createDOM(),this.createAudio(),this.initPlaybackSpeed(),this.initKeyboardControls(),this.initSeekControl(),this.bindEvents(),this.setupResizeObserver(),requestAnimationFrame(()=>{this.isDestroying||(this.resizeCanvas(),this.options.url&&!this._loadId&&this.load(this.options.url).then(()=>{this.options.autoplay&&this.play()?.catch(()=>{})}).catch(t=>{console.error("[WaveformPlayer] Failed to load audio:",t)}))})}createDOM(){this.container.innerHTML="",this.container.className="waveform-player";let t=rt.includes(this.options.buttonAlign)?this.options.buttonAlign:"auto";t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview"),this.container.classList.toggle("waveform-theme-light",this._scheme==="light");let s=[];this.options.buttonSize!=null&&s.push(`--wfp-btn-size: ${G(this.options.buttonSize)}`),this.options.buttonRadius!=null&&s.push(`--wfp-btn-radius: ${G(this.options.buttonRadius)}`);let r=s.length?` style="${s.join("; ")};"`:"",a=this.options.artworkPosition==="button"&&this.options.artwork,o=a?`<img class="waveform-btn-artwork" src="${S(this.options.artwork)}" alt="" aria-hidden="true">`:"",l=this.options.showControls?`
|
|
2
2
|
<button class="waveform-btn${this.options.buttonStyle==="minimal"?" waveform-btn-minimal":""}${a?" waveform-btn-has-artwork":""}" aria-label="${S(this.options.playPauseLabel)}"${r}>
|
|
3
3
|
${o}
|
|
4
4
|
<span class="waveform-icon-play">${this.options.playIcon}</span>
|
|
@@ -61,4 +61,4 @@ function I(){return typeof window<"u"&&typeof document<"u"}function j(e){let t=-
|
|
|
61
61
|
${n}
|
|
62
62
|
</div>
|
|
63
63
|
</div>
|
|
64
|
-
`,this.playBtn=this.container.querySelector(".waveform-btn"),this.canvas=this.container.querySelector("canvas"),this.ctx=this.canvas.getContext("2d"),this.titleEl=this.container.querySelector(".waveform-title"),this.artistEl=this.container.querySelector(".waveform-artist"),this.artworkEl=this.container.querySelector(".waveform-artwork, .waveform-btn-artwork"),this.bindArtworkFallback(this.artworkEl),this.currentTimeEl=this.container.querySelector(".time-current"),this.totalTimeEl=this.container.querySelector(".time-total"),this.bpmEl=this.container.querySelector(".waveform-bpm"),this.bpmValueEl=this.container.querySelector(".bpm-value"),this.loadingEl=this.container.querySelector(".waveform-loading"),this.errorEl=this.container.querySelector(".waveform-error"),this.markersContainer=this.container.querySelector(".waveform-markers"),this.speedBtn=this.container.querySelector(".speed-btn"),this.speedMenu=this.container.querySelector(".speed-menu"),this.resizeCanvas(),this.updateBPMDisplay()}bindArtworkFallback(t){t&&t.addEventListener("error",()=>{t.src.startsWith("data:")||(t.src=Wt)},{signal:this._ac.signal})}createArtworkElement(){let t=document.createElement("img");return t.className="waveform-artwork",t.style.width="40px",t.style.height="40px",t.style.borderRadius="4px",t.style.objectFit="cover",t.style.flexShrink="0",this.bindArtworkFallback(t),t}createButtonArtworkElement(){let t=document.createElement("img");return t.className="waveform-btn-artwork",t.alt="",t.setAttribute("aria-hidden","true"),this.bindArtworkFallback(t),t}createArtistElement(){let t=document.createElement("span");return t.className="waveform-artist",t}syncArtist(t){if(this.options.artist=t||null,!!this.options.showInfo){if(!t){this.artistEl?.remove(),this.artistEl=null;return}if(!this.artistEl){let i=this.container.querySelector(".waveform-title");if(!i)return;this.artistEl=this.createArtistElement(),i.after(this.artistEl)}this.artistEl.textContent=t,this.artistEl.style.display=""}}syncButtonArtwork(t){if(this.playBtn){if(!t){this.artworkEl?.remove(),this.artworkEl=null,this.playBtn.classList.remove("waveform-btn-has-artwork");return}this.artworkEl||(this.artworkEl=this.createButtonArtworkElement(),this.playBtn.prepend(this.artworkEl)),this.artworkEl.src=t,this.playBtn.classList.add("waveform-btn-has-artwork")}}syncArtwork(t,i=""){if(this.options.artwork=t||null,this.options.artworkAlt=i||"",this.options.artworkPosition==="button"){this.syncButtonArtwork(this.options.artwork);return}if(this.options.showInfo){if(!t){this.artworkEl?.remove(),this.artworkEl=null;return}if(!this.artworkEl){let s=this.container.querySelector(".waveform-text");if(!s)return;this.artworkEl=this.createArtworkElement(),s.before(this.artworkEl)}this.artworkEl.src=t,this.artworkEl.alt=i||""}}createAudio(){if(this.options.audioMode==="external"){this.audio=null;return}this.audio=new Audio,this.audio.preload=this.options.preload||"metadata",this.options.crossOrigin&&(this.audio.crossOrigin=this.options.crossOrigin)}initPlaybackSpeed(){this.audio&&this.options.playbackRate&&this.options.playbackRate!==1&&(this.audio.playbackRate=this.audio.defaultPlaybackRate=this.options.playbackRate),this.options.showPlaybackSpeed&&this.initSpeedControls()}initSpeedControls(){let t=this.container.querySelector(".speed-btn"),i=this.container.querySelector(".speed-menu");if(!t||!i)return;let s=()=>Array.from(i.querySelectorAll(".speed-option")),r=()=>i.style.display!=="none",a=n=>{if(i.style.display=n?"block":"none",t.setAttribute("aria-expanded",n?"true":"false"),n){let h=s();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=n=>{let h=s();h.length&&h[(n+h.length)%h.length].focus()},l=n=>{this.setPlaybackRate(parseFloat(n.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",n=>{n.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",n=>{n.stopPropagation();let h=n.target.closest(".speed-option");h&&l(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",n=>{let h=s(),c=h.indexOf(document.activeElement);if(!r()){(n.key==="ArrowDown"||n.key==="ArrowUp")&&document.activeElement===t&&(n.preventDefault(),a(!0));return}switch(n.key){case"ArrowDown":n.preventDefault(),o(c<0?0:c+1);break;case"ArrowUp":n.preventDefault(),o(c<0?h.length-1:c-1);break;case"Home":n.preventDefault(),o(0);break;case"End":n.preventDefault(),o(h.length-1);break;case"Escape":n.preventDefault(),a(!1),t.focus();break;case"Tab":a(!1);break}},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(Nt)||(e.getAllInstances().forEach(i=>{i!==this&&i.container.setAttribute("tabindex","-1")}),this.container.setAttribute("tabindex","0"),this.container.focus())},{signal:this._ac.signal}),this.container.addEventListener("keydown",t=>{if(document.activeElement!==this.container)return;let i=t.key,s=!!this.audio,r=s?this.audio.currentTime:0;if(s&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let a={" ":()=>this.togglePlay()};s&&(a.ArrowLeft=()=>this.seekTo(m(r-5,0,this.audio.duration)),a.ArrowRight=()=>this.seekTo(m(r+5,0,this.audio.duration)),a.ArrowUp=()=>this.setVolume(m(this.audio.volume+.1)),a.ArrowDown=()=>this.setVolume(m(this.audio.volume-.1)),a.m=a.M=()=>this.audio.muted=!this.audio.muted),a[i]&&(t.preventDefault(),a[i]())},{signal:this._ac.signal})}initSeekControl(){this.options.accessibleSeek&&(this.seekEl=this.container.querySelector(".waveform-container"),this.seekEl&&(this.seekEl.setAttribute("role","slider"),this.seekEl.setAttribute("tabindex","0"),this.seekEl.setAttribute("aria-valuemin","0"),this.applySeekLabel(),this.updateSeekAccessibility(),this.seekEl.addEventListener("keydown",t=>{if(t.key===" "||t.key==="Spacebar"){t.preventDefault(),t.stopPropagation(),this.togglePlay();return}let i=this.getSeekDuration();if(!i)return;let s=this.getSeekCurrentTime(),r;switch(t.key){case"ArrowLeft":case"ArrowDown":r=s-bt;break;case"ArrowRight":case"ArrowUp":r=s+bt;break;case"PageDown":r=s-kt;break;case"PageUp":r=s+kt;break;case"Home":r=0;break;case"End":r=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(r)},{signal:this._ac.signal})))}getSeekDuration(){return this.options.audioMode==="external"?this._extDuration||0:this.audio&&Number.isFinite(this.audio.duration)?this.audio.duration:0}getSeekCurrentTime(){return this.options.audioMode==="external"?this.progress*(this._extDuration||0):this.audio&&Number.isFinite(this.audio.currentTime)?this.audio.currentTime:0}seekToSeconds(t){let i=this.getSeekDuration();if(!i)return;let s=m(t,0,i);if(this.options.audioMode==="external"){this._requestSeek(s/i),this.updateSeekAccessibility();return}this.seekTo(s)}applySeekLabel(t=this.options.title){if(!this.seekEl)return;let i=this.options.seekLabel||t||"Seek";this.seekEl.setAttribute("aria-label",i)}updateSeekAccessibility(){if(!this.seekEl)return;let t=this.getSeekDuration(),i=Math.min(this.getSeekCurrentTime(),t);this.seekEl.setAttribute("aria-valuemax",String(Math.round(t))),this.seekEl.setAttribute("aria-valuenow",String(Math.round(i))),this.seekEl.setAttribute("aria-valuetext",nt(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;e._sessionOwner=this,this._applyMediaMetadata(),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(m(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(m(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",s=>{s.seekTime!==null&&this.seekTo(s.seekTime)});let t=this.options.onNextTrack,i=this.options.onPreviousTrack;try{navigator.mediaSession.setActionHandler("nexttrack",typeof t=="function"?()=>t(this):null)}catch{}try{navigator.mediaSession.setActionHandler("previoustrack",typeof i=="function"?()=>i(this):null)}catch{}}_applyMediaMetadata(){!("mediaSession"in navigator)||!this.options.enableMediaSession||(navigator.mediaSession.metadata=new MediaMetadata({title:this.options.title||this.options.unknownTrackText,artist:this.options.artist||"",album:this.options.album||"",artwork:this.options.artwork?[{src:this.options.artwork,sizes:"512x512",type:"image/jpeg"}]:[]}))}_updateMediaSession(t){if(!(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio))try{t==="playing"&&this.initMediaSession(),navigator.mediaSession.playbackState=t,this._updatePositionState()}catch{}}_updatePositionState(){let t=this.audio?.duration;if(!(e._sessionOwner!==this||!navigator.mediaSession?.setPositionState||!(t&&isFinite(t))))try{navigator.mediaSession.setPositionState({duration:t,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,t)})}catch{}}bindEvents(){this.playBtn&&this.playBtn.addEventListener("click",()=>this.togglePlay()),this.audio&&(this.audio.addEventListener("loadstart",()=>this.setLoading(!0)),this.audio.addEventListener("loadedmetadata",()=>this.onMetadataLoaded()),this.audio.addEventListener("canplay",()=>this.setLoading(!1)),this.audio.addEventListener("play",()=>this.onPlay()),this.audio.addEventListener("pause",()=>this.onPause()),this.audio.addEventListener("ended",()=>this.onEnded()),this.audio.addEventListener("error",i=>this.onError(i)),this.audio.addEventListener("seeked",()=>this._updatePositionState()),this.audio.addEventListener("ratechange",()=>this._updatePositionState()),this.audio.addEventListener("timeupdate",()=>{this.isPlaying&&Date.now()-this._frameAt>500&&this.updateProgress()})),this.canvas.addEventListener("click",i=>this.handleCanvasClick(i)),this._dragging=!1,this._seekHover=!1,this._handleNear=!1,this.canvas.addEventListener("pointerenter",()=>{this._seekHover=!0,this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerleave",()=>{this._seekHover=!1,this._handleNear=!1,this._dragging||this._hideHoverTip(),this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerdown",i=>{if(!(i.pointerType==="mouse"&&i.button!==0)){this._dragging=!0;try{this.canvas.setPointerCapture(i.pointerId)}catch{}this._scrubTo(i.clientX)}}),this.canvas.addEventListener("pointermove",i=>{if(this._dragging){this._scrubTo(i.clientX);return}let s=this.canvas.getBoundingClientRect();s.width&&(this._handleNear=Math.abs(i.clientX-s.left-this.progress*s.width)<=10,this._updateSeekHandle())});let t=i=>{if(this._dragging){this._dragging=!1,this._suppressClick=!0;try{this.canvas.releasePointerCapture(i.pointerId)}catch{}this._seekFromPointer(i.clientX),!this._seekHover&&!this.options.showHoverTime&&this._hideHoverTip(),this._updateSeekHandle()}};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",t),this.setupHoverTime(),this.setupSeekHandle(),this.resizeHandler=ct(()=>this.resizeCanvas(),100),window.addEventListener("resize",this.resizeHandler)}setupResizeObserver(){"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver(()=>{this.resizeCanvas()}),this.canvas?.parentElement&&this.resizeObserver.observe(this.canvas.parentElement))}async load(t){let i=++this._loadId,s=this.audio;try{t!==this.options.url&&this._resetTrack(),this.setLoading(!0),this.progress=0,this._setError(!1),this.container.classList.remove("waveform-is-placeholder"),this.detectedBPM=null,this.updateBPMDisplay(),this.options.url=t;let r=this.options.waveform,a=r?this.setWaveformData(r):null,o=this.options.title||N(t);this.titleEl&&(this.titleEl.textContent=o),this.applySeekLabel(o),s&&(s.src=t,s.preload!=="none"&&await new Promise((n,h)=>{let c=g=>b=>{s.removeEventListener("loadedmetadata",u),s.removeEventListener("error",y),g(b)},u=c(n),y=c(h);s.addEventListener("loadedmetadata",u),s.addEventListener("error",y)}));let l=await a;if(i!==this._loadId)return;if(!r||l===!1)try{let n=await X(t,this.options.samples,this.options.showBPM);if(i!==this._loadId)return;this.waveformData=n.peaks,n.bpm&&(this.detectedBPM=n.bpm,this.updateBPMDisplay())}catch(n){if(i!==this._loadId)return;console.warn("[WaveformPlayer] Using placeholder waveform:",n),this.waveformData=gt(this.options.samples),this.container.classList.add("waveform-is-placeholder")}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(r){i===this._loadId&&!this.hasError&&this.onError(r)}finally{i===this._loadId&&this.setLoading(!1)}}_resetTrack(){this.progress=0,this.waveformData=[],this._extDuration=0,this._extEnded=!1,this.currentTimeEl&&(this.currentTimeEl.textContent="0:00"),this.totalTimeEl&&(this.totalTimeEl.textContent="0:00"),this.markersContainer&&(this.markersContainer.innerHTML="")}_setError(t){this.hasError=t,this.errorEl&&(this.errorEl.style.display=t?"flex":"none"),this.canvas&&(this.canvas.style.opacity=t?"0.2":"1"),this.playBtn&&(this.playBtn.disabled=t)}async loadTrack(t,i=null,s=null,r={}){let a=Object.prototype.hasOwnProperty.call(r,"artwork"),o=Object.prototype.hasOwnProperty.call(r,"artworkAlt");this.isPlaying&&this.pause(),this.audio&&(this.audio.src="",this.audio.load()),this._resetTrack(),this.options=st(Y(this.options,{url:t,title:i===null?this.options.title:i,artist:s===null?this.options.artist:s,...r})),a&&(this.options.artwork=r.artwork||null),o?this.options.artworkAlt=r.artworkAlt||"":a&&(this.options.artworkAlt=this.options.artwork?H.artworkAlt:"");for(let h of["bpm","album"])r[h]==null&&(this.options[h]=H[h]);r.preload&&this.audio&&(this.audio.preload=this.options.preload),r.crossOrigin&&this.audio&&(this.audio.crossOrigin=this.options.crossOrigin),s!==null&&this.syncArtist(s),(a||o)&&this.syncArtwork(a?r.artwork:this.options.artwork,o?r.artworkAlt:this.options.artworkAlt),this.options.markers=r.markers?q(r.markers):[],this.options.waveform=r.waveform||null;let l=this.load(t),n=this._loadId;await l,r.autoplay!==!1&&n===this._loadId&&this.play()?.catch(()=>{})}setWaveformData(t){if(typeof t=="string"&&/\.json(?:[?#]|$)/i.test(t.trim())){let i=this._loadId;return fetch(t.trim()).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}).then(s=>{if(i!==this._loadId)return!1;let r=x(Array.isArray(s)?s:s?.peaks,{fallback:[]});if(!r.length)throw new Error("no peaks");this.waveformData=r,s.markers&&!this.options.markers?.length&&(this.options.markers=q(s.markers),this.renderMarkers());let a=_(s.bpm,null,{min:1});return a&&(this.detectedBPM=a,this.updateBPMDisplay()),this.drawWaveform(),!0}).catch(s=>(console.warn("[WaveformPlayer] Could not use peaks file:",t,s),!1))}this.waveformData=x(t,{fallback:[]}),this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||mt(this.ctx,this.canvas,this.waveformData,this.progress,{...this.options,waveformStyle:this.options.waveformStyle||"bars",color:this.options.waveformColor,progressColor:this.options.progressColor,seekActive:this._seekHover||this._dragging})}resizeCanvas(){if(!this.canvas||this.isDestroying)return;let t=window.devicePixelRatio||1,i=this.canvas.parentElement.getBoundingClientRect();this.canvas.width=i.width*t,this.canvas.height=this.options.height*t,this.canvas.parentElement.style.height=this.options.height+"px",this.drawWaveform()}renderMarkers(){if(!this.markersContainer||(this.markersContainer.innerHTML="",this._activeMarkerIndex=-1,clearTimeout(this._markerLabelTimer),!this.options.showMarkers||!this.options.markers?.length))return;let t=this.getSeekDuration();t&&this.options.markers.forEach((i,s)=>{if(i.time>t){console.warn(`[WaveformPlayer] Marker "${i.label}" at ${i.time}s exceeds audio duration of ${t}s`);return}let r=i.time/t*100,a=document.createElement("button");a.className="waveform-marker",a.style.left=`${r}%`,a.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",a.setAttribute("aria-label",i.label),a.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,a.appendChild(o),a.addEventListener("click",l=>{l.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(a)})}setActiveMarker(t){if(!this.markersContainer)return;this.markersContainer.querySelectorAll(".waveform-marker").forEach((s,r)=>s.classList.toggle("active",r===t))}updateActiveMarker(){if(!this.markersContainer)return;let t=this.markersContainer.querySelectorAll(".waveform-marker");if(!t.length)return;let i=this.getSeekDuration(),s=i?this.progress*i:0,r=-1,a=-1/0;t.forEach((o,l)=>{let n=parseFloat(o.getAttribute("data-time"));Number.isFinite(n)&&n<=s+.05&&n>a&&(a=n,r=l)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,l)=>o.classList.toggle("show-label",l===r)),r>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(o=>o.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.seekEl)return;let t=document.createElement("div");t.className="waveform-hover-time",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.hoverTimeEl=t,this.options.showHoverTime&&(this.seekEl.addEventListener("pointermove",i=>{this._dragging||this._updateHoverTip(i.clientX)}),this.seekEl.addEventListener("pointerleave",()=>{this._dragging||this._hideHoverTip()}))}_updateHoverTip(t){let i=this.hoverTimeEl;if(!i)return;let s=this.getSeekDuration();if(!s){i.style.opacity="0";return}let r=this.canvas.getBoundingClientRect(),a=m((t-r.left)/r.width);i.textContent=E(a*s),i.style.left=a*100+"%",i.style.opacity="1"}_hideHoverTip(){this.hoverTimeEl&&(this.hoverTimeEl.style.opacity="0")}_scrubTo(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;this.progress=m((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle();let s=this.getSeekDuration();s&&this.currentTimeEl?(this.currentTimeEl.textContent=E(this.progress*s),this._hideHoverTip()):this._updateHoverTip(t)}setupSeekHandle(){if(!this.options.seekHandle||this.options.waveformStyle!=="seekbar"||!this.seekEl)return;let t=document.createElement("div");t.className="waveform-seek-handle",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.seekHandleEl=t}_updateSeekHandle(){let t=this.seekHandleEl;t&&(t.style.left=this.progress*100+"%",t.classList.toggle("is-visible",this._seekHover||this._dragging),t.classList.toggle("is-active",this._dragging||this._handleNear))}handleCanvasClick(t){if(this._suppressClick){this._suppressClick=!1;return}this._seekFromPointer(t.clientX)}_seekFromPointer(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;let s=m((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(s);return}!this.audio||!this.audio.duration||this.seekToPercent(s)}setLoading(t){if(this.isLoading=t,this.loadingEl){let i=t&&this.waveformData.length===0;this.loadingEl.style.display=i?"block":"none"}this.seekEl&&this.seekEl.setAttribute("aria-busy",t?"true":"false")}onMetadataLoaded(){this.isDestroying||(this.totalTimeEl&&(this.totalTimeEl.textContent=E(this.audio.duration)),this.renderMarkers(),this.updateSeekAccessibility())}setPlayButtonState(t){if(!this.playBtn)return;this.playBtn.classList.toggle("playing",t);let i=this.playBtn.querySelector(".waveform-icon-play"),s=this.playBtn.querySelector(".waveform-icon-pause");i&&(i.style.display=t?"none":"flex"),s&&(s.style.display=t?"flex":"none")}onPlay(){this.isDestroying||(this.isPlaying=!0,this.setPlayButtonState(!0),this.startSmoothUpdate(),this._updateMediaSession("playing"),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this))}onPause(){this.isDestroying||(this.isPlaying=!1,this.setPlayButtonState(!1),this.stopSmoothUpdate(),this._updateMediaSession("paused"),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}onEnded(){if(this.isDestroying)return;let t=this.audio.duration;this.progress=0,this.audio.currentTime=0,this.drawWaveform(),this.currentTimeEl&&(this.currentTimeEl.textContent="0:00"),this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:t,duration:t}),this.isPlaying&&this.onPause(),this.options.onEnd&&this.options.onEnd(this)}onError(t){this.isDestroying||(console.error("[WaveformPlayer] Audio error:",t),this._setError(!0),this.setLoading(!1),this.options.onError&&this.options.onError(t,this))}startSmoothUpdate(){this.stopSmoothUpdate();let t=()=>{this.isPlaying&&this.audio&&this.audio.duration&&(this._frameAt=Date.now(),this.updateProgress(),this.updateTimer=requestAnimationFrame(t))};this._frameAt=Date.now(),this.updateTimer=requestAnimationFrame(t)}stopSmoothUpdate(){this.updateTimer&&(cancelAnimationFrame(this.updateTimer),this.updateTimer=null)}updateProgress(){if(!this.audio||!this.audio.duration||this._dragging)return;let t=this.audio.currentTime/this.audio.duration;Math.abs(t-this.progress)>.001&&(this.progress=t,this.drawWaveform(),this._updateSeekHandle()),this.currentTimeEl&&(this.currentTimeEl.textContent=E(this.audio.currentTime)),this._emit("waveformplayer:timeupdate",{player:this,currentTime:this.audio.currentTime,duration:this.audio.duration,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(this.audio.currentTime,this.audio.duration,this),this.updateActiveMarker(),this.updateSeekAccessibility()}updateBPMDisplay(){let t=this.options.bpm||this.detectedBPM;this.bpmEl&&this.bpmValueEl&&(t&&(this.bpmValueEl.textContent=Math.round(t)),this.bpmEl.style.display=t?"inline-flex":"none")}refreshTheme(){if(!this._autoTheme)return;this._scheme=D(this.container);let t=tt(this.options.colorPreset,this.container);for(let i of this._presetKeys||[])i in t&&(this.options[i]=t[i]);this._applyThemeColors()}_applyThemeColors(){this.container.classList.toggle("waveform-theme-light",this._scheme==="light"),this.canvas&&this.drawWaveform()}static _watchTheme(){if(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(a=>{try{a.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},s=new MutationObserver(t);s.observe(document.documentElement,i),document.body&&s.observe(document.body,i);let r=null;try{r=window.matchMedia("(prefers-color-scheme: dark)"),r.addEventListener("change",t)}catch{}e._themeWatch={obs:s,mq:r,refresh:t}}updateSpeedUI(){if(!this.audio)return;let t=this.container.querySelector(".speed-value");if(t){let i=this.audio.playbackRate;t.textContent=i===1?"1x":`${i}x`}this.container.querySelectorAll(".speed-option").forEach(i=>{let s=parseFloat(i.dataset.rate)===this.audio.playbackRate;i.classList.toggle("active",s),i.setAttribute("aria-checked",s?"true":"false")})}play(){if(this.options.singlePlay&&e.currentlyPlaying&&e.currentlyPlaying!==this&&e.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(e.currentlyPlaying=this);return}return e.currentlyPlaying=this,this.audio.play()}pause(){(this.options.audioMode!=="external"||!this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0).defaultPrevented)&&e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.audio?.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,artist:this.options.artist,artwork:this.options.artwork,markers:this.options.markers,waveform:this.options.waveform,id:this.id,player:this}}setPlayingState(t){let i=this.isPlaying;this.isPlaying=!!t,this.setPlayButtonState(this.isPlaying),this.isPlaying&&!i?(this.startSmoothUpdate?.(),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this)):!this.isPlaying&&i&&(this.stopSmoothUpdate?.(),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}setProgress(t,i){!i||i<=0||this._dragging||(this.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),i!==this._extDuration&&(this._extDuration=i,this.totalTimeEl&&(this.totalTimeEl.textContent=E(i)),this.renderMarkers()),this.drawWaveform?.(),this.updateActiveMarker(),this._emit("waveformplayer:timeupdate",{player:this,currentTime:t,duration:i,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(t,i,this),this.progress>=1?this._extEnded||(this._extEnded=!0,this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:i,duration:i}),this.options.onEnd&&this.options.onEnd(this)):this._extEnded=!1,this.updateSeekAccessibility())}togglePlay(){this.isPlaying?this.pause():this.play()}seekTo(t){let i=Number(t);this.audio&&this.audio.duration&&Number.isFinite(i)&&(this.audio.currentTime=m(i,0,this.audio.duration),this.updateProgress())}seekToPercent(t){let i=Number(t);this.audio&&this.audio.duration&&Number.isFinite(i)&&(this.audio.currentTime=this.audio.duration*m(i),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=m(i))}setPlaybackRate(t){if(!this.audio)return;let i=_(t,null,{min:$,max:z});i!==null&&(this.audio.playbackRate=this.audio.defaultPlaybackRate=i,this.options.playbackRate=i,this.updateSpeedUI())}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),clearTimeout(this._readyTimer),this._loadId++,this._ac?.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),e.instances.delete(this.id),e.currentlyPlaying===this&&(e.currentlyPlaying=null),e._sessionOwner===this&&(e._sessionOwner=null),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",delete this.container.dataset.waveformInitialized,this.canvas=null,this.ctx=null,this.playBtn=null,this.waveformData=[]}static getInstance(t){if(typeof t=="string"){let i=this.instances.get(t);if(i)return i;let s=document.getElementById(t);if(s)return Array.from(this.instances.values()).find(r=>r.container===s)}if(t instanceof HTMLElement)return Array.from(this.instances.values()).find(i=>i.container===t)}static getAllInstances(){return Array.from(this.instances.values())}static destroyAll(){this.instances.forEach(t=>t.destroy()),this.instances.clear()}static async generateWaveformData(t,i=1800){try{return(await X(t,i)).peaks}catch(s){throw console.error("[WaveformPlayer] Failed to generate waveform:",s),s}}static getPeaksUrl(t){if(!t)return;let i=t.replace(/\.(mp3|wav|ogg|flac|m4a|aac)(\?[^#]*)?(#.*)?$/i,".json$2$3");return i===t?void 0:i}};T.utils={formatTime:E,extractTitleFromUrl:N,escapeHtml:S,isSafeHref:rt,parseDataAttributes:W,detectColorScheme:D};function vt(e){if(!(e.dataset.waveformInitialized==="true"||T.getInstance(e)))try{new T(e),e.dataset.waveformInitialized="true"}catch(t){console.error("[WaveformPlayer] Failed to initialize:",t,e)}}function Ft(e=document){if(!I())return;let t=e||document;t.matches?.("[data-waveform-player]")&&vt(t),t.querySelectorAll("[data-waveform-player]").forEach(vt)}T.init=Ft;I()&&(window.WaveformPlayer=T);var U=T;var $t=()=>document.documentElement?.dataset.waveformAutoinit==="false";I()&&!$t()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>U.init()):U.init());var le=U;export{U as WaveformPlayer,le as default};
|
|
64
|
+
`,this.playBtn=this.container.querySelector(".waveform-btn"),this.canvas=this.container.querySelector("canvas"),this.ctx=this.canvas.getContext("2d"),this.titleEl=this.container.querySelector(".waveform-title"),this.artistEl=this.container.querySelector(".waveform-artist"),this.artworkEl=this.container.querySelector(".waveform-artwork, .waveform-btn-artwork"),this.bindArtworkFallback(this.artworkEl),this.currentTimeEl=this.container.querySelector(".time-current"),this.totalTimeEl=this.container.querySelector(".time-total"),this.bpmEl=this.container.querySelector(".waveform-bpm"),this.bpmValueEl=this.container.querySelector(".bpm-value"),this.loadingEl=this.container.querySelector(".waveform-loading"),this.errorEl=this.container.querySelector(".waveform-error"),this.markersContainer=this.container.querySelector(".waveform-markers"),this.speedBtn=this.container.querySelector(".speed-btn"),this.speedMenu=this.container.querySelector(".speed-menu"),this.resizeCanvas(),this.updateBPMDisplay()}bindArtworkFallback(t){t&&t.addEventListener("error",()=>{t.src.startsWith("data:")||(t.src=Ft)},{signal:this._ac.signal})}createArtworkElement(){let t=document.createElement("img");return t.className="waveform-artwork",t.style.width="40px",t.style.height="40px",t.style.borderRadius="4px",t.style.objectFit="cover",t.style.flexShrink="0",this.bindArtworkFallback(t),t}createButtonArtworkElement(){let t=document.createElement("img");return t.className="waveform-btn-artwork",t.alt="",t.setAttribute("aria-hidden","true"),this.bindArtworkFallback(t),t}createArtistElement(){let t=document.createElement("span");return t.className="waveform-artist",t}syncArtist(t){if(this.options.artist=t||null,!!this.options.showInfo){if(!t){this.artistEl?.remove(),this.artistEl=null;return}if(!this.artistEl){let i=this.container.querySelector(".waveform-title");if(!i)return;this.artistEl=this.createArtistElement(),i.after(this.artistEl)}this.artistEl.textContent=t,this.artistEl.style.display=""}}syncButtonArtwork(t){if(this.playBtn){if(!t){this.artworkEl?.remove(),this.artworkEl=null,this.playBtn.classList.remove("waveform-btn-has-artwork");return}this.artworkEl||(this.artworkEl=this.createButtonArtworkElement(),this.playBtn.prepend(this.artworkEl)),this.artworkEl.src=t,this.playBtn.classList.add("waveform-btn-has-artwork")}}syncArtwork(t,i=""){if(this.options.artwork=t||null,this.options.artworkAlt=i||"",this.options.artworkPosition==="button"){this.syncButtonArtwork(this.options.artwork);return}if(this.options.showInfo){if(!t){this.artworkEl?.remove(),this.artworkEl=null;return}if(!this.artworkEl){let s=this.container.querySelector(".waveform-text");if(!s)return;this.artworkEl=this.createArtworkElement(),s.before(this.artworkEl)}this.artworkEl.src=t,this.artworkEl.alt=i||""}}createAudio(){if(this.options.audioMode==="external"){this.audio=null;return}this.audio=new Audio,this.audio.preload=this.options.preload||"metadata",this.options.crossOrigin&&(this.audio.crossOrigin=this.options.crossOrigin)}initPlaybackSpeed(){this.audio&&this.options.playbackRate&&this.options.playbackRate!==1&&(this.audio.playbackRate=this.audio.defaultPlaybackRate=this.options.playbackRate),this.options.showPlaybackSpeed&&this.initSpeedControls()}initSpeedControls(){let t=this.container.querySelector(".speed-btn"),i=this.container.querySelector(".speed-menu");if(!t||!i)return;let s=()=>Array.from(i.querySelectorAll(".speed-option")),r=()=>i.style.display!=="none",a=n=>{if(i.style.display=n?"block":"none",t.setAttribute("aria-expanded",n?"true":"false"),n){let h=s();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=n=>{let h=s();h.length&&h[(n+h.length)%h.length].focus()},l=n=>{this.setPlaybackRate(parseFloat(n.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",n=>{n.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",n=>{n.stopPropagation();let h=n.target.closest(".speed-option");h&&l(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",n=>{let h=s(),c=this._activeElement(),d=h.indexOf(c);if(!r()){(n.key==="ArrowDown"||n.key==="ArrowUp")&&c===t&&(n.preventDefault(),a(!0));return}switch(n.key){case"ArrowDown":n.preventDefault(),o(d<0?0:d+1);break;case"ArrowUp":n.preventDefault(),o(d<0?h.length-1:d-1);break;case"Home":n.preventDefault(),o(0);break;case"End":n.preventDefault(),o(h.length-1);break;case"Escape":n.preventDefault(),a(!1),t.focus();break;case"Tab":a(!1);break}},{signal:this._ac.signal}),this.updateSpeedUI()}_activeElement(){return this.container.getRootNode().activeElement??document.activeElement}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest($t)||(e.getAllInstances().forEach(i=>{i!==this&&i.container.setAttribute("tabindex","-1")}),this.container.setAttribute("tabindex","0"),this.container.focus())},{signal:this._ac.signal}),this.container.addEventListener("keydown",t=>{if(this._activeElement()!==this.container)return;let i=t.key,s=!!this.audio,r=s?this.audio.currentTime:0;if(s&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let a={" ":()=>this.togglePlay()};s&&(a.ArrowLeft=()=>this.seekTo(m(r-5,0,this.audio.duration)),a.ArrowRight=()=>this.seekTo(m(r+5,0,this.audio.duration)),a.ArrowUp=()=>this.setVolume(m(this.audio.volume+.1)),a.ArrowDown=()=>this.setVolume(m(this.audio.volume-.1)),a.m=a.M=()=>this.audio.muted=!this.audio.muted),a[i]&&(t.preventDefault(),a[i]())},{signal:this._ac.signal})}initSeekControl(){this.options.accessibleSeek&&(this.seekEl=this.container.querySelector(".waveform-container"),this.seekEl&&(this.seekEl.setAttribute("role","slider"),this.seekEl.setAttribute("tabindex","0"),this.seekEl.setAttribute("aria-valuemin","0"),this.applySeekLabel(),this.updateSeekAccessibility(),this.seekEl.addEventListener("keydown",t=>{if(t.key===" "||t.key==="Spacebar"){t.preventDefault(),t.stopPropagation(),this.togglePlay();return}let i=this.getSeekDuration();if(!i)return;let s=this.getSeekCurrentTime(),r;switch(t.key){case"ArrowLeft":case"ArrowDown":r=s-St;break;case"ArrowRight":case"ArrowUp":r=s+St;break;case"PageDown":r=s-Et;break;case"PageUp":r=s+Et;break;case"Home":r=0;break;case"End":r=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(r)},{signal:this._ac.signal})))}getSeekDuration(){return this.options.audioMode==="external"?this._extDuration||0:this.audio&&Number.isFinite(this.audio.duration)?this.audio.duration:0}getSeekCurrentTime(){return this.options.audioMode==="external"?this.progress*(this._extDuration||0):this.audio&&Number.isFinite(this.audio.currentTime)?this.audio.currentTime:0}seekToSeconds(t){let i=this.getSeekDuration();if(!i)return;let s=m(t,0,i);if(this.options.audioMode==="external"){this._requestSeek(s/i),this.updateSeekAccessibility();return}this.seekTo(s)}applySeekLabel(t=this.options.title){if(!this.seekEl)return;let i=this.options.seekLabel||t||"Seek";this.seekEl.setAttribute("aria-label",i)}updateSeekAccessibility(){if(!this.seekEl)return;let t=this.getSeekDuration(),i=Math.min(this.getSeekCurrentTime(),t);this.seekEl.setAttribute("aria-valuemax",String(Math.round(t))),this.seekEl.setAttribute("aria-valuenow",String(Math.round(i))),this.seekEl.setAttribute("aria-valuetext",ht(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;e._sessionOwner=this,this._applyMediaMetadata(),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(m(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(m(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",s=>{s.seekTime!==null&&this.seekTo(s.seekTime)});let t=this.options.onNextTrack,i=this.options.onPreviousTrack;try{navigator.mediaSession.setActionHandler("nexttrack",typeof t=="function"?()=>t(this):null)}catch{}try{navigator.mediaSession.setActionHandler("previoustrack",typeof i=="function"?()=>i(this):null)}catch{}}_applyMediaMetadata(){!("mediaSession"in navigator)||!this.options.enableMediaSession||(navigator.mediaSession.metadata=new MediaMetadata({title:this.options.title||this.options.unknownTrackText,artist:this.options.artist||"",album:this.options.album||"",artwork:this.options.artwork?[{src:this.options.artwork,sizes:"512x512",type:"image/jpeg"}]:[]}))}_updateMediaSession(t){if(!(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio))try{t==="playing"&&this.initMediaSession(),navigator.mediaSession.playbackState=t,this._updatePositionState()}catch{}}_updatePositionState(){let t=this.audio?.duration;if(!(e._sessionOwner!==this||!navigator.mediaSession?.setPositionState||!(t&&isFinite(t))))try{navigator.mediaSession.setPositionState({duration:t,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,t)})}catch{}}bindEvents(){this.playBtn&&this.playBtn.addEventListener("click",()=>this.togglePlay()),this.audio&&(this.audio.addEventListener("loadstart",()=>this.setLoading(!0)),this.audio.addEventListener("loadedmetadata",()=>this.onMetadataLoaded()),this.audio.addEventListener("canplay",()=>this.setLoading(!1)),this.audio.addEventListener("play",()=>this.onPlay()),this.audio.addEventListener("pause",()=>this.onPause()),this.audio.addEventListener("ended",()=>this.onEnded()),this.audio.addEventListener("error",i=>this.onError(i)),this.audio.addEventListener("seeked",()=>this._updatePositionState()),this.audio.addEventListener("ratechange",()=>this._updatePositionState()),this.audio.addEventListener("timeupdate",()=>{this.isPlaying&&!this._seekReload&&Date.now()-this._frameAt>500&&this.updateProgress()})),this.canvas.addEventListener("click",i=>this.handleCanvasClick(i)),this._dragging=!1,this._seekHover=!1,this._handleNear=!1,this.canvas.addEventListener("pointerenter",()=>{this._seekHover=!0,this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerleave",()=>{this._seekHover=!1,this._handleNear=!1,this._dragging||this._hideHoverTip(),this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerdown",i=>{if(!(i.pointerType==="mouse"&&i.button!==0)){this._dragging=!0;try{this.canvas.setPointerCapture(i.pointerId)}catch{}this._scrubTo(i.clientX)}}),this.canvas.addEventListener("pointermove",i=>{if(this._dragging){this._scrubTo(i.clientX);return}let s=this.canvas.getBoundingClientRect();s.width&&(this._handleNear=Math.abs(i.clientX-s.left-this.progress*s.width)<=10,this._updateSeekHandle())});let t=i=>{if(this._dragging){this._dragging=!1,this._suppressClick=!0;try{this.canvas.releasePointerCapture(i.pointerId)}catch{}this._seekFromPointer(i.clientX),!this._seekHover&&!this.options.showHoverTime&&this._hideHoverTip(),this._updateSeekHandle()}};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",t),this.setupHoverTime(),this.setupSeekHandle(),this.resizeHandler=ut(()=>this.resizeCanvas(),100),window.addEventListener("resize",this.resizeHandler)}setupResizeObserver(){"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver(()=>{this.resizeCanvas()}),this.canvas?.parentElement&&this.resizeObserver.observe(this.canvas.parentElement))}async load(t){let i=++this._loadId,s=this.audio;try{t!==this.options.url&&this._resetTrack(),this.setLoading(!0),this.progress=0,this._setError(!1),this.container.classList.remove("waveform-is-placeholder"),this.detectedBPM=null,this.updateBPMDisplay(),this.options.url=t;let r=this.options.waveform,a=r?this.setWaveformData(r):null,o=this.options.title||N(t);this.titleEl&&(this.titleEl.textContent=o),this.applySeekLabel(o),s&&(s.src=t,s.preload!=="none"&&await new Promise((n,h)=>{let c=g=>w=>{s.removeEventListener("loadedmetadata",d),s.removeEventListener("error",y),g(w)},d=c(n),y=c(h);s.addEventListener("loadedmetadata",d),s.addEventListener("error",y)}));let l=await a;if(i!==this._loadId)return;if(!r||l===!1)try{let n=await Z(t,this.options.samples,this.options.showBPM);if(i!==this._loadId)return;this.options.waveform===r&&(this.waveformData=n.peaks),n.bpm&&(this.detectedBPM=n.bpm,this.updateBPMDisplay())}catch(n){if(i!==this._loadId)return;this.options.waveform===r&&(console.warn("[WaveformPlayer] Using placeholder waveform:",n),this.waveformData=bt(this.options.samples),this.container.classList.add("waveform-is-placeholder"))}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(r){i===this._loadId&&!this.hasError&&this.onError(r)}finally{i===this._loadId&&this.setLoading(!1)}}_resetTrack(){this._cancelCacheSeek?.(),this._seekReload=null,this.progress=0,this.waveformData=[],this._extDuration=0,this._extEnded=!1,this.currentTimeEl&&(this.currentTimeEl.textContent="0:00"),this.totalTimeEl&&(this.totalTimeEl.textContent="0:00"),this.markersContainer&&(this.markersContainer.innerHTML="")}_setError(t){this.hasError=t,this.errorEl&&(this.errorEl.style.display=t?"flex":"none"),this.canvas&&(this.canvas.style.opacity=t?"0.2":"1"),this.playBtn&&(this.playBtn.disabled=t)}async loadTrack(t,i=null,s=null,r={}){let a=Object.prototype.hasOwnProperty.call(r,"artwork"),o=Object.prototype.hasOwnProperty.call(r,"artworkAlt");this.isPlaying&&this.pause(),this.audio&&(this.audio.src="",this.audio.load()),this._resetTrack(),this.options=at(Y(this.options,{url:t,title:i===null?this.options.title:i,artist:s===null?this.options.artist:s,...r})),a&&(this.options.artwork=r.artwork||null),o?this.options.artworkAlt=r.artworkAlt||"":a&&(this.options.artworkAlt=this.options.artwork?H.artworkAlt:"");for(let h of["bpm","album"])r[h]==null&&(this.options[h]=H[h]);r.preload&&this.audio&&(this.audio.preload=this.options.preload),r.crossOrigin&&this.audio&&(this.audio.crossOrigin=this.options.crossOrigin),s!==null&&this.syncArtist(s),(a||o)&&this.syncArtwork(a?r.artwork:this.options.artwork,o?r.artworkAlt:this.options.artworkAlt),this.options.markers=r.markers?U(r.markers):[],this.options.waveform=r.waveform||null;let l=this.load(t),n=this._loadId;await l,r.autoplay!==!1&&n===this._loadId&&this.play()?.catch(()=>{})}setWaveformData(t){if(this.options.waveform=t,typeof t=="string"&&/\.json(?:[?#]|$)/i.test(t.trim())){let i=this._loadId;return fetch(t.trim()).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}).then(s=>{if(i!==this._loadId)return!1;let r=x(Array.isArray(s)?s:s?.peaks,{fallback:[]});if(!r.length)throw new Error("no peaks");this.waveformData=r,this.container.classList.remove("waveform-is-placeholder"),s.markers&&!this.options.markers?.length&&(this.options.markers=U(s.markers),this.renderMarkers());let a=_(s.bpm,null,{min:1});return a&&(this.detectedBPM=a,this.updateBPMDisplay()),this.drawWaveform(),!0}).catch(s=>(console.warn("[WaveformPlayer] Could not use peaks file:",t,s),!1))}this.waveformData=x(t,{fallback:[]}),this.container.classList.remove("waveform-is-placeholder"),this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||kt(this.ctx,this.canvas,this.waveformData,this.progress,{...this.options,waveformStyle:this.options.waveformStyle||"bars",color:this.options.waveformColor,progressColor:this.options.progressColor,seekActive:this._seekHover||this._dragging})}resizeCanvas(){if(!this.canvas||this.isDestroying)return;let t=window.devicePixelRatio||1,i=this.canvas.parentElement.getBoundingClientRect();this.canvas.width=i.width*t,this.canvas.height=this.options.height*t,this.canvas.parentElement.style.height=this.options.height+"px",this.drawWaveform()}renderMarkers(){if(!this.markersContainer||(this.markersContainer.innerHTML="",this._activeMarkerIndex=-1,clearTimeout(this._markerLabelTimer),!this.options.showMarkers||!this.options.markers?.length))return;let t=this.getSeekDuration();t&&this.options.markers.forEach((i,s)=>{if(i.time>t){console.warn(`[WaveformPlayer] Marker "${i.label}" at ${i.time}s exceeds audio duration of ${t}s`);return}let r=i.time/t*100,a=document.createElement("button");a.className="waveform-marker",a.style.left=`${r}%`,a.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",a.setAttribute("aria-label",i.label),a.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,a.appendChild(o),a.addEventListener("click",l=>{l.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(a)})}setActiveMarker(t){if(!this.markersContainer)return;this.markersContainer.querySelectorAll(".waveform-marker").forEach((s,r)=>s.classList.toggle("active",r===t))}updateActiveMarker(){if(!this.markersContainer)return;let t=this.markersContainer.querySelectorAll(".waveform-marker");if(!t.length)return;let i=this.getSeekDuration(),s=i?this.progress*i:0,r=-1,a=-1/0;t.forEach((o,l)=>{let n=parseFloat(o.getAttribute("data-time"));Number.isFinite(n)&&n<=s+.05&&n>a&&(a=n,r=l)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,l)=>o.classList.toggle("show-label",l===r)),r>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(o=>o.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.seekEl)return;let t=document.createElement("div");t.className="waveform-hover-time",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.hoverTimeEl=t,this.options.showHoverTime&&(this.seekEl.addEventListener("pointermove",i=>{this._dragging||this._updateHoverTip(i.clientX)}),this.seekEl.addEventListener("pointerleave",()=>{this._dragging||this._hideHoverTip()}))}_updateHoverTip(t){let i=this.hoverTimeEl;if(!i)return;let s=this.getSeekDuration();if(!s){i.style.opacity="0";return}let r=this.canvas.getBoundingClientRect(),a=m((t-r.left)/r.width);i.textContent=E(a*s),i.style.left=a*100+"%",i.style.opacity="1"}_hideHoverTip(){this.hoverTimeEl&&(this.hoverTimeEl.style.opacity="0")}_scrubTo(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;this.progress=m((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle();let s=this.getSeekDuration();s&&this.currentTimeEl?(this.currentTimeEl.textContent=E(this.progress*s),this._hideHoverTip()):this._updateHoverTip(t)}setupSeekHandle(){if(!this.options.seekHandle||this.options.waveformStyle!=="seekbar"||!this.seekEl)return;let t=document.createElement("div");t.className="waveform-seek-handle",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.seekHandleEl=t}_updateSeekHandle(){let t=this.seekHandleEl;t&&(t.style.left=this.progress*100+"%",t.classList.toggle("is-visible",this._seekHover||this._dragging),t.classList.toggle("is-active",this._dragging||this._handleNear))}handleCanvasClick(t){if(this._suppressClick){this._suppressClick=!1;return}this._seekFromPointer(t.clientX)}_seekFromPointer(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;let s=m((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(s);return}!this.audio||!this.audio.duration||this.seekToPercent(s)}setLoading(t){if(this.isLoading=t,this.loadingEl){let i=t&&this.waveformData.length===0;this.loadingEl.style.display=i?"block":"none"}this.seekEl&&this.seekEl.setAttribute("aria-busy",t?"true":"false")}onMetadataLoaded(){this.isDestroying||(this.totalTimeEl&&(this.totalTimeEl.textContent=E(this.audio.duration)),this.renderMarkers(),this.updateSeekAccessibility())}setPlayButtonState(t){if(!this.playBtn)return;this.playBtn.classList.toggle("playing",t);let i=this.playBtn.querySelector(".waveform-icon-play"),s=this.playBtn.querySelector(".waveform-icon-pause");i&&(i.style.display=t?"none":"flex"),s&&(s.style.display=t?"flex":"none")}onPlay(){this.isDestroying||this._seekReload||(this.isPlaying=!0,this.setPlayButtonState(!0),this.startSmoothUpdate(),this._updateMediaSession("playing"),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this))}onPause(){this.isDestroying||this._seekReload||(this.isPlaying=!1,this.setPlayButtonState(!1),this.stopSmoothUpdate(),this._updateMediaSession("paused"),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}onEnded(){if(this.isDestroying)return;let t=this.audio.duration;this.progress=0,this.audio.currentTime=0,this.drawWaveform(),this.currentTimeEl&&(this.currentTimeEl.textContent="0:00"),this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:t,duration:t}),this.isPlaying&&this.onPause(),this.options.onEnd&&this.options.onEnd(this)}onError(t){this.isDestroying||(console.error("[WaveformPlayer] Audio error:",t),this._setError(!0),this.setLoading(!1),this.options.onError&&this.options.onError(t,this))}startSmoothUpdate(){this.stopSmoothUpdate();let t=()=>{this.isPlaying&&this.audio&&this.audio.duration&&(this._frameAt=Date.now(),this.updateProgress(),this.updateTimer=requestAnimationFrame(t))};this._frameAt=Date.now(),this.updateTimer=requestAnimationFrame(t)}stopSmoothUpdate(){this.updateTimer&&(cancelAnimationFrame(this.updateTimer),this.updateTimer=null)}updateProgress(){if(!this.audio||!this.audio.duration||this._dragging)return;let t=this.audio.currentTime/this.audio.duration;Math.abs(t-this.progress)>.001&&(this.progress=t,this.drawWaveform(),this._updateSeekHandle()),this.currentTimeEl&&(this.currentTimeEl.textContent=E(this.audio.currentTime)),this._emit("waveformplayer:timeupdate",{player:this,currentTime:this.audio.currentTime,duration:this.audio.duration,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(this.audio.currentTime,this.audio.duration,this),this.updateActiveMarker(),this.updateSeekAccessibility()}updateBPMDisplay(){let t=this.options.bpm||this.detectedBPM;this.bpmEl&&this.bpmValueEl&&(t&&(this.bpmValueEl.textContent=Math.round(t)),this.bpmEl.style.display=t?"inline-flex":"none")}refreshTheme(){if(!this._autoTheme)return;this._scheme=D(this.container);let t=it(this.options.colorPreset,this.container);for(let i of this._presetKeys||[])i in t&&(this.options[i]=t[i]);this._applyThemeColors()}_applyThemeColors(){this.container.classList.toggle("waveform-theme-light",this._scheme==="light"),this.canvas&&this.drawWaveform()}static _watchTheme(){if(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(a=>{try{a.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},s=new MutationObserver(t);s.observe(document.documentElement,i),document.body&&s.observe(document.body,i);let r=null;try{r=window.matchMedia("(prefers-color-scheme: dark)"),r.addEventListener("change",t)}catch{}e._themeWatch={obs:s,mq:r,refresh:t}}static _releaseThemeWatch(){let t=e._themeWatch;if(!(!t||e.instances.size>0)){t.obs.disconnect();try{t.mq?.removeEventListener("change",t.refresh)}catch{}e._themeWatch=null}}updateSpeedUI(){if(!this.audio)return;let t=this.container.querySelector(".speed-value");if(t){let i=this.audio.playbackRate;t.textContent=i===1?"1x":`${i}x`}this.container.querySelectorAll(".speed-option").forEach(i=>{let s=parseFloat(i.dataset.rate)===this.audio.playbackRate;i.classList.toggle("active",s),i.setAttribute("aria-checked",s?"true":"false")})}play(){if(this.options.singlePlay&&e.currentlyPlaying&&e.currentlyPlaying!==this&&e.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(e.currentlyPlaying=this);return}return e.currentlyPlaying=this,this.audio.play()}pause(){(this.options.audioMode!=="external"||!this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0).defaultPrevented)&&e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.audio?.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,artist:this.options.artist,artwork:this.options.artwork,markers:this.options.markers,waveform:this.options.waveform,id:this.id,player:this}}setPlayingState(t){let i=this.isPlaying;this.isPlaying=!!t,this.setPlayButtonState(this.isPlaying),this.isPlaying&&!i?(this.startSmoothUpdate?.(),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this)):!this.isPlaying&&i&&(this.stopSmoothUpdate?.(),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}setProgress(t,i){!i||i<=0||this._dragging||(this.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),i!==this._extDuration&&(this._extDuration=i,this.totalTimeEl&&(this.totalTimeEl.textContent=E(i)),this.renderMarkers()),this.drawWaveform?.(),this.updateActiveMarker(),this._emit("waveformplayer:timeupdate",{player:this,currentTime:t,duration:i,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(t,i,this),this.progress>=1?this._extEnded||(this._extEnded=!0,this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:i,duration:i}),this.options.onEnd&&this.options.onEnd(this)):this._extEnded=!1,this.updateSeekAccessibility())}togglePlay(){this.isPlaying?this.pause():this.play()}_seekAudio(t){let i=this.audio,s=i.seekable;if(!Number.isFinite(i.duration)||!s||s.length===0||pt(s,t)||this._seekReloadedUrl===this.options.url){i.currentTime=t;return}this._seekViaCache(t)}_seekViaCache(t){let i=this.audio,s=this.options.url;if(this._cacheSeekTime=t,e._noRangeWarned.has(s)||(e._noRangeWarned.add(s),console.warn(`[WaveformPlayer] ${s}: the host ignores HTTP Range requests, so seeking waits for the download and reloads from cache. Serve audio with Range support for instant seeks.`)),this._cancelCacheSeek)return;if(J(i.buffered,i.duration)){this._reloadForSeek(s);return}let r=i.preload;i.preload="auto",this.setLoading(!0);let a=()=>{i.removeEventListener("progress",o),i.removeEventListener("canplaythrough",o),i.preload=r,this._cancelCacheSeek=null},o=()=>{if(this.audio!==i||this.options.url!==s)return a();J(i.buffered,i.duration)&&(a(),this._reloadForSeek(s))};this._cancelCacheSeek=a,i.addEventListener("progress",o,{signal:this._ac.signal}),i.addEventListener("canplaythrough",o,{signal:this._ac.signal})}_reloadForSeek(t){let i=this.audio,s=!i.paused&&!i.ended,r=i.playbackRate;this._seekReloadedUrl=t,this._seekReload={wasPlaying:s};let a=()=>{this._seekReload=null,this.setLoading(!1),this.updateProgress()};i.addEventListener("loadedmetadata",()=>{if(!(this.audio!==i||this.options.url!==t)){if(i.playbackRate=r,i.currentTime=this._cacheSeekTime,!s){a();return}i.play().then(()=>{a(),this.startSmoothUpdate()},()=>{a(),this.onPause()})}},{once:!0,signal:this._ac.signal}),i.load()}seekTo(t){let i=Number(t);this.audio&&this.audio.duration&&Number.isFinite(i)&&(this._seekAudio(m(i,0,this.audio.duration)),this.updateProgress())}seekToPercent(t){let i=Number(t);this.audio&&this.audio.duration&&Number.isFinite(i)&&(this._seekAudio(this.audio.duration*m(i)),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=m(i))}setPlaybackRate(t){if(!this.audio)return;let i=_(t,null,{min:$,max:z});i!==null&&(this.audio.playbackRate=this.audio.defaultPlaybackRate=i,this.options.playbackRate=i,this.updateSpeedUI())}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),clearTimeout(this._readyTimer),this._loadId++,this._ac?.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),e.instances.delete(this.id),e._releaseThemeWatch(),e.currentlyPlaying===this&&(e.currentlyPlaying=null),e._sessionOwner===this&&(e._sessionOwner=null),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",delete this.container.dataset.waveformInitialized,this.canvas=null,this.ctx=null,this.playBtn=null,this.waveformData=[]}static getInstance(t){if(typeof t=="string"){let i=this.instances.get(t);if(i)return i;let s=document.getElementById(t);if(s)return Array.from(this.instances.values()).find(r=>r.container===s)}if(t instanceof HTMLElement)return Array.from(this.instances.values()).find(i=>i.container===t)}static getAllInstances(){return Array.from(this.instances.values())}static destroyAll(){this.instances.forEach(t=>t.destroy()),this.instances.clear(),this._releaseThemeWatch()}static async generateWaveformData(t,i=1800){try{return(await Z(t,i)).peaks}catch(s){throw console.error("[WaveformPlayer] Failed to generate waveform:",s),s}}static getPeaksUrl(t){if(!t)return;let i=t.replace(/\.(mp3|wav|ogg|flac|m4a|aac)(\?[^#]*)?(#.*)?$/i,".json$2$3");return i===t?void 0:i}};T.utils={formatTime:E,extractTitleFromUrl:N,escapeHtml:S,isSafeHref:ot,parseDataAttributes:W,detectColorScheme:D,extractPeaks:Q};function Pt(e){if(!(e.dataset.waveformInitialized==="true"||T.getInstance(e)))try{new T(e),e.dataset.waveformInitialized="true"}catch(t){console.error("[WaveformPlayer] Failed to initialize:",t,e)}}function zt(e=document){if(!I())return;let t=e||document;t.matches?.("[data-waveform-player]")&&Pt(t),t.querySelectorAll("[data-waveform-player]").forEach(Pt)}T.init=zt;I()&&(window.WaveformPlayer=T);var q=T;var Ut=()=>document.documentElement?.dataset.waveformAutoinit==="false";I()&&!Ut()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>q.init()):q.init());var de=q;export{q as WaveformPlayer,de as default};
|