@arraypress/waveform-player 1.16.1 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,13 @@
1
1
  (() => {
2
2
  // src/js/utils.js
3
+ var DEFAULT_SAMPLES = 1800;
4
+ function maxOf(values) {
5
+ let max = -Infinity;
6
+ for (let i = 0; i < values.length; i++) {
7
+ if (values[i] > max) max = values[i];
8
+ }
9
+ return max;
10
+ }
3
11
  function escapeHtml(str) {
4
12
  return String(str == null ? "" : str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
5
13
  }
@@ -82,6 +90,7 @@
82
90
  setBool("showInfo");
83
91
  setBool("showTime");
84
92
  setBool("showHoverTime");
93
+ setBool("seekHandle");
85
94
  setBool("showBPM", "showBpm");
86
95
  setNum("bpm");
87
96
  setBool("singlePlay");
@@ -426,33 +435,19 @@
426
435
  const centerY = height / 2;
427
436
  const barHeight = 4;
428
437
  const borderRadius = barHeight / 2;
438
+ const active = !!options.seekActive;
429
439
  ctx.clearRect(0, 0, width, height);
430
440
  ctx.fillStyle = options.color || "rgba(255, 255, 255, 0.2)";
431
441
  capsulePath(ctx, borderRadius, width, centerY, barHeight);
432
442
  ctx.fill();
433
443
  if (progress > 0) {
434
444
  const progressWidth = Math.max(borderRadius * 2, progress * width);
435
- ctx.shadowBlur = 8;
436
- ctx.shadowColor = options.progressColor;
445
+ ctx.save();
446
+ ctx.globalAlpha = options.seekHandle && !active ? 0.7 : 1;
437
447
  ctx.fillStyle = options.progressColor || "rgba(255, 255, 255, 0.9)";
438
448
  capsulePath(ctx, borderRadius, progressWidth, centerY, barHeight);
439
449
  ctx.fill();
440
- ctx.shadowBlur = 0;
441
- const handleRadius = 8;
442
- const handleX = progressWidth;
443
- ctx.shadowBlur = 4;
444
- ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
445
- ctx.shadowOffsetY = 2;
446
- ctx.fillStyle = "#ffffff";
447
- ctx.beginPath();
448
- ctx.arc(handleX, centerY, handleRadius, 0, Math.PI * 2);
449
- ctx.fill();
450
- ctx.shadowBlur = 0;
451
- ctx.shadowOffsetY = 0;
452
- ctx.fillStyle = options.progressColor || "rgba(255, 255, 255, 0.9)";
453
- ctx.beginPath();
454
- ctx.arc(handleX, centerY, handleRadius * 0.4, 0, Math.PI * 2);
455
- ctx.fill();
450
+ ctx.restore();
456
451
  }
457
452
  }
458
453
  var DRAWING_STYLES = {
@@ -541,7 +536,7 @@
541
536
  }
542
537
 
543
538
  // src/js/audio.js
544
- function extractPeaks(buffer, samples = 200) {
539
+ function extractPeaks(buffer, samples = DEFAULT_SAMPLES) {
545
540
  const sampleSize = buffer.length / samples;
546
541
  const channels = buffer.numberOfChannels;
547
542
  const peaks = [];
@@ -563,10 +558,10 @@
563
558
  }
564
559
  }
565
560
  }
566
- const maxPeak = Math.max(...peaks);
561
+ const maxPeak = maxOf(peaks);
567
562
  return maxPeak > 0 ? peaks.map((peak) => peak / maxPeak) : peaks;
568
563
  }
569
- async function generateWaveform(url, samples = 200, shouldDetectBPM = false) {
564
+ async function generateWaveform(url, samples = DEFAULT_SAMPLES, shouldDetectBPM = false) {
570
565
  let audioContext;
571
566
  try {
572
567
  const AudioCtx = window.AudioContext || /** @type {any} */
@@ -586,7 +581,7 @@
586
581
  if (audioContext) audioContext.close();
587
582
  }
588
583
  }
589
- function generatePlaceholderWaveform(samples = 200) {
584
+ function generatePlaceholderWaveform(samples = DEFAULT_SAMPLES) {
590
585
  const data = [];
591
586
  for (let i = 0; i < samples; i++) {
592
587
  const base = Math.random() * 0.5 + 0.3;
@@ -596,7 +591,7 @@
596
591
  return data;
597
592
  }
598
593
  function normalizePeaks(peaks, targetMax = 0.95) {
599
- const maxPeak = Math.max(...peaks);
594
+ const maxPeak = maxOf(peaks);
600
595
  if (maxPeak === 0 || maxPeak > targetMax) return peaks;
601
596
  const scaleFactor = targetMax / maxPeak;
602
597
  return peaks.map((peak) => peak * scaleFactor);
@@ -668,7 +663,7 @@
668
663
  // bars, so this is fidelity headroom, not the visible bar count. 1800 (the
669
664
  // SoundCloud/WaveformGen figure) keeps wide / high-DPI waveforms crisp; the
670
665
  // every-frame scan means a higher value costs no extra extraction time.
671
- samples: 1800,
666
+ samples: DEFAULT_SAMPLES,
672
667
  preload: "metadata",
673
668
  // Audio mode — 'self' = player owns the <audio> element (default, current
674
669
  // behavior). 'external' = player is a visualization-only surface; no audio
@@ -719,6 +714,11 @@
719
714
  showInfo: true,
720
715
  showTime: true,
721
716
  showHoverTime: false,
717
+ // Show a draggable circle handle + hover brightness-lift on the SEEKBAR
718
+ // style only (it's meaningless on a waveform, where the fill-edge is the
719
+ // playhead). Off by default; the bar turns it on. Drag-to-scrub works
720
+ // regardless of this.
721
+ seekHandle: false,
722
722
  showBPM: false,
723
723
  // Known BPM to display in the badge (with showBPM). Wins over auto-detection
724
724
  // — set it when peaks are pre-generated so the tempo still shows. null = auto.
@@ -768,6 +768,7 @@
768
768
  );
769
769
  var SEEK_STEP_SECONDS = 5;
770
770
  var SEEK_PAGE_SECONDS = 10;
771
+ var INTERACTIVE_ELEMENTS = 'button, a[href], input, [role="slider"]';
771
772
  var WaveformPlayer = class _WaveformPlayer {
772
773
  /** @type {Map<string, WaveformPlayer>} */
773
774
  static instances = /* @__PURE__ */ new Map();
@@ -963,7 +964,7 @@
963
964
  ` : ""}
964
965
  ${this.options.showPlaybackSpeed ? `
965
966
  <div class="waveform-speed">
966
- <button class="speed-btn" aria-label="Playback speed">
967
+ <button class="speed-btn" aria-label="Playback speed" aria-haspopup="true" aria-expanded="false">
967
968
  <span class="speed-value">1x</span>
968
969
  </button>
969
970
  <div class="speed-menu" style="display: none;">
@@ -1062,8 +1063,9 @@
1062
1063
  }
1063
1064
  /**
1064
1065
  * Wire up the playback-speed menu: toggle it open on the speed button,
1065
- * close it on any outside click, and apply the chosen rate when a
1066
- * `.speed-option` is clicked. All listeners are registered against the
1066
+ * close it on outside click or Escape (keeping `aria-expanded` on the
1067
+ * trigger in sync), and apply the chosen rate when a `.speed-option` is
1068
+ * clicked, returning focus to the trigger. All listeners are registered against the
1067
1069
  * instance `AbortController` signal so {@link WaveformPlayer#destroy} tears
1068
1070
  * them down. No-op if the speed elements are absent.
1069
1071
  * @private
@@ -1072,19 +1074,27 @@
1072
1074
  const speedBtn = this.container.querySelector(".speed-btn");
1073
1075
  const speedMenu = this.container.querySelector(".speed-menu");
1074
1076
  if (!speedBtn || !speedMenu) return;
1077
+ const setSpeedMenu = (open) => {
1078
+ speedMenu.style.display = open ? "block" : "none";
1079
+ speedBtn.setAttribute("aria-expanded", open ? "true" : "false");
1080
+ };
1075
1081
  speedBtn.addEventListener("click", (e) => {
1076
1082
  e.stopPropagation();
1077
- speedMenu.style.display = speedMenu.style.display === "none" ? "block" : "none";
1078
- }, { signal: this._ac.signal });
1079
- document.addEventListener("click", () => {
1080
- speedMenu.style.display = "none";
1083
+ setSpeedMenu(speedMenu.style.display === "none");
1081
1084
  }, { signal: this._ac.signal });
1085
+ document.addEventListener("click", () => setSpeedMenu(false), { signal: this._ac.signal });
1082
1086
  speedMenu.addEventListener("click", (e) => {
1083
1087
  e.stopPropagation();
1084
1088
  if (e.target.classList.contains("speed-option")) {
1085
- const rate = parseFloat(e.target.dataset.rate);
1086
- this.setPlaybackRate(rate);
1087
- speedMenu.style.display = "none";
1089
+ this.setPlaybackRate(parseFloat(e.target.dataset.rate));
1090
+ setSpeedMenu(false);
1091
+ speedBtn.focus();
1092
+ }
1093
+ }, { signal: this._ac.signal });
1094
+ speedBtn.closest(".waveform-speed")?.addEventListener("keydown", (e) => {
1095
+ if (e.key === "Escape" && speedMenu.style.display !== "none") {
1096
+ setSpeedMenu(false);
1097
+ speedBtn.focus();
1088
1098
  }
1089
1099
  }, { signal: this._ac.signal });
1090
1100
  this.updateSpeedUI();
@@ -1102,7 +1112,8 @@
1102
1112
  */
1103
1113
  initKeyboardControls() {
1104
1114
  this.container.setAttribute("tabindex", "-1");
1105
- this.container.addEventListener("click", () => {
1115
+ this.container.addEventListener("click", (e) => {
1116
+ if (e.target.closest(INTERACTIVE_ELEMENTS)) return;
1106
1117
  _WaveformPlayer.getAllInstances().forEach((player) => {
1107
1118
  if (player !== this) {
1108
1119
  player.container.setAttribute("tabindex", "-1");
@@ -1314,7 +1325,56 @@
1314
1325
  this.audio.addEventListener("error", (e) => this.onError(e));
1315
1326
  }
1316
1327
  this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
1328
+ this._dragging = false;
1329
+ this._seekHover = false;
1330
+ this._handleNear = false;
1331
+ this.canvas.addEventListener("pointerenter", () => {
1332
+ this._seekHover = true;
1333
+ this.drawWaveform();
1334
+ this._updateSeekHandle();
1335
+ });
1336
+ this.canvas.addEventListener("pointerleave", () => {
1337
+ this._seekHover = false;
1338
+ this._handleNear = false;
1339
+ if (!this._dragging) this._hideHoverTip();
1340
+ this.drawWaveform();
1341
+ this._updateSeekHandle();
1342
+ });
1343
+ this.canvas.addEventListener("pointerdown", (e) => {
1344
+ if (e.pointerType === "mouse" && e.button !== 0) return;
1345
+ this._dragging = true;
1346
+ try {
1347
+ this.canvas.setPointerCapture(e.pointerId);
1348
+ } catch (err) {
1349
+ }
1350
+ this._scrubTo(e.clientX);
1351
+ });
1352
+ this.canvas.addEventListener("pointermove", (e) => {
1353
+ if (this._dragging) {
1354
+ this._scrubTo(e.clientX);
1355
+ return;
1356
+ }
1357
+ const rect = this.canvas.getBoundingClientRect();
1358
+ if (rect.width) {
1359
+ this._handleNear = Math.abs(e.clientX - rect.left - this.progress * rect.width) <= 10;
1360
+ this._updateSeekHandle();
1361
+ }
1362
+ });
1363
+ const endDrag = (e) => {
1364
+ if (!this._dragging) return;
1365
+ this._dragging = false;
1366
+ try {
1367
+ this.canvas.releasePointerCapture(e.pointerId);
1368
+ } catch (err) {
1369
+ }
1370
+ this._seekFromPointer(e.clientX);
1371
+ if (!this._seekHover) this._hideHoverTip();
1372
+ this._updateSeekHandle();
1373
+ };
1374
+ this.canvas.addEventListener("pointerup", endDrag);
1375
+ this.canvas.addEventListener("pointercancel", endDrag);
1317
1376
  this.setupHoverTime();
1377
+ this.setupSeekHandle();
1318
1378
  this.resizeHandler = debounce(() => this.resizeCanvas(), 100);
1319
1379
  window.addEventListener("resize", this.resizeHandler);
1320
1380
  }
@@ -1523,7 +1583,8 @@
1523
1583
  ...this.options,
1524
1584
  waveformStyle: this.options.waveformStyle || "bars",
1525
1585
  color: this.options.waveformColor,
1526
- progressColor: this.options.progressColor
1586
+ progressColor: this.options.progressColor,
1587
+ seekActive: this._seekHover || this._dragging
1527
1588
  });
1528
1589
  }
1529
1590
  /**
@@ -1653,21 +1714,78 @@
1653
1714
  this.seekEl.appendChild(tip);
1654
1715
  this.hoverTimeEl = tip;
1655
1716
  this.seekEl.addEventListener("pointermove", (e) => {
1656
- const dur = this.getSeekDuration();
1657
- if (!dur) {
1658
- tip.style.opacity = "0";
1659
- return;
1660
- }
1661
- const rect = this.canvas.getBoundingClientRect();
1662
- const pct = clamp((e.clientX - rect.left) / rect.width);
1663
- tip.textContent = formatTime(pct * dur);
1664
- tip.style.left = pct * 100 + "%";
1665
- tip.style.opacity = "1";
1717
+ if (!this._dragging) this._updateHoverTip(e.clientX);
1666
1718
  });
1667
1719
  this.seekEl.addEventListener("pointerleave", () => {
1668
- tip.style.opacity = "0";
1720
+ if (!this._dragging) this._hideHoverTip();
1669
1721
  });
1670
1722
  }
1723
+ /**
1724
+ * Position + fill the hover-time tooltip for a given client-X. Shared by
1725
+ * hover and drag-scrub. No-op when the tooltip isn't enabled
1726
+ * (`showHoverTime` off).
1727
+ * @param {number} clientX - Pointer client-X coordinate.
1728
+ * @private
1729
+ */
1730
+ _updateHoverTip(clientX) {
1731
+ const tip = this.hoverTimeEl;
1732
+ if (!tip) return;
1733
+ const dur = this.getSeekDuration();
1734
+ if (!dur) {
1735
+ tip.style.opacity = "0";
1736
+ return;
1737
+ }
1738
+ const rect = this.canvas.getBoundingClientRect();
1739
+ const pct = clamp((clientX - rect.left) / rect.width);
1740
+ tip.textContent = formatTime(pct * dur);
1741
+ tip.style.left = pct * 100 + "%";
1742
+ tip.style.opacity = "1";
1743
+ }
1744
+ /** Hide the hover-time tooltip. @private */
1745
+ _hideHoverTip() {
1746
+ if (this.hoverTimeEl) this.hoverTimeEl.style.opacity = "0";
1747
+ }
1748
+ /**
1749
+ * Visually preview a seek during a drag — moves the playhead + handle +
1750
+ * tooltip to the cursor WITHOUT touching the audio (playback continues; the
1751
+ * real seek is committed on release).
1752
+ * @param {number} clientX - Pointer client-X coordinate.
1753
+ * @private
1754
+ */
1755
+ _scrubTo(clientX) {
1756
+ const rect = this.canvas.getBoundingClientRect();
1757
+ if (!rect.width) return;
1758
+ this.progress = clamp((clientX - rect.left) / rect.width);
1759
+ this.drawWaveform();
1760
+ this._updateSeekHandle();
1761
+ this._updateHoverTip(clientX);
1762
+ }
1763
+ /**
1764
+ * Create the draggable seek handle — a DOM circle over the playhead, shown
1765
+ * only on hover / drag (Spotify-style). Pointer-events are off so it never
1766
+ * blocks the canvas scrub; size + visibility are CSS.
1767
+ * @private
1768
+ */
1769
+ setupSeekHandle() {
1770
+ if (!this.options.seekHandle || this.options.waveformStyle !== "seekbar" || !this.seekEl) return;
1771
+ const h = document.createElement("div");
1772
+ h.className = "waveform-seek-handle";
1773
+ h.setAttribute("aria-hidden", "true");
1774
+ this.seekEl.appendChild(h);
1775
+ this.seekHandleEl = h;
1776
+ }
1777
+ /**
1778
+ * Position the seek handle at the current progress and toggle its
1779
+ * visibility (hover / drag) + expanded (drag / direct-hover) classes.
1780
+ * @private
1781
+ */
1782
+ _updateSeekHandle() {
1783
+ const h = this.seekHandleEl;
1784
+ if (!h) return;
1785
+ h.style.left = this.progress * 100 + "%";
1786
+ h.classList.toggle("is-visible", this._seekHover || this._dragging);
1787
+ h.classList.toggle("is-active", this._dragging || this._handleNear);
1788
+ }
1671
1789
  // ============================================
1672
1790
  // Event Handlers
1673
1791
  // ============================================
@@ -1684,9 +1802,23 @@
1684
1802
  * @fires WaveformPlayer#waveformplayer:request-seek
1685
1803
  */
1686
1804
  handleCanvasClick(event) {
1805
+ this._seekFromPointer(event.clientX);
1806
+ }
1807
+ /**
1808
+ * Seek to a horizontal client-X position over the canvas — shared by
1809
+ * click and drag. In external mode the player has no audio of its own,
1810
+ * so it dispatches a cancelable `waveformplayer:request-seek` with the
1811
+ * target percentage (updating the local visual optimistically); in self
1812
+ * mode it seeks the owned `<audio>` via
1813
+ * {@link WaveformPlayer#seekToPercent}.
1814
+ * @param {number} clientX - Pointer client-X coordinate.
1815
+ * @private
1816
+ * @fires WaveformPlayer#waveformplayer:request-seek
1817
+ */
1818
+ _seekFromPointer(clientX) {
1687
1819
  const rect = this.canvas.getBoundingClientRect();
1688
- const x = event.clientX - rect.left;
1689
- const targetPercent = clamp(x / rect.width);
1820
+ if (!rect.width) return;
1821
+ const targetPercent = clamp((clientX - rect.left) / rect.width);
1690
1822
  if (this.options.audioMode === "external") {
1691
1823
  this._requestSeek(targetPercent);
1692
1824
  return;
@@ -1868,10 +2000,12 @@
1868
2000
  */
1869
2001
  updateProgress() {
1870
2002
  if (!this.audio || !this.audio.duration) return;
2003
+ if (this._dragging) return;
1871
2004
  const newProgress = this.audio.currentTime / this.audio.duration;
1872
2005
  if (Math.abs(newProgress - this.progress) > 1e-3) {
1873
2006
  this.progress = newProgress;
1874
2007
  this.drawWaveform();
2008
+ this._updateSeekHandle();
1875
2009
  }
1876
2010
  if (this.currentTimeEl) {
1877
2011
  this.currentTimeEl.textContent = formatTime(this.audio.currentTime);
@@ -2283,7 +2417,7 @@
2283
2417
  * @param {number} samples - Number of samples
2284
2418
  * @returns {Promise<number[]>} Waveform peak data
2285
2419
  */
2286
- static async generateWaveformData(url, samples = 200) {
2420
+ static async generateWaveformData(url, samples = DEFAULT_SAMPLES) {
2287
2421
  try {
2288
2422
  const result = await generateWaveform(url, samples);
2289
2423
  return result.peaks;
@@ -1,4 +1,4 @@
1
- (()=>{function L(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function O(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 g(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function it(e){return e===void 0?void 0:e==="true"}function H(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function x(e){let t={},i=(r,a=r)=>{let n=it(e.dataset[a]);n!==void 0&&(t[r]=n)},s=(r,a=r,n=!1)=>{let l=e.dataset[a];l&&(t[r]=n?parseFloat(l):parseInt(l,10))},o=(r,a=r)=>{let n=e.dataset[a];if(n)try{t[r]=JSON.parse(n)}catch(l){console.warn(`[WaveformPlayer] Invalid ${a} JSON:`,l)}};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.audioMode&&(t.audioMode=e.dataset.audioMode),e.dataset.style&&(t.waveformStyle=e.dataset.style),e.dataset.waveformStyle&&(t.waveformStyle=e.dataset.waveformStyle),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),e.dataset.buttonSize){let r=e.dataset.buttonSize;t.buttonSize=/^\d+(\.\d+)?$/.test(r.trim())?parseFloat(r):r}return e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=H(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=H(e.dataset.progressColor)),e.dataset.buttonColor&&(t.buttonColor=e.dataset.buttonColor),e.dataset.buttonHoverColor&&(t.buttonHoverColor=e.dataset.buttonHoverColor),e.dataset.textColor&&(t.textColor=e.dataset.textColor),e.dataset.textSecondaryColor&&(t.textSecondaryColor=e.dataset.textSecondaryColor),e.dataset.backgroundColor&&(t.backgroundColor=e.dataset.backgroundColor),e.dataset.borderColor&&(t.borderColor=e.dataset.borderColor),e.dataset.color&&(t.waveformColor=e.dataset.color),e.dataset.theme&&(t.colorPreset=e.dataset.theme),i("autoplay"),i("showControls"),i("showInfo"),i("showTime"),i("showHoverTime"),i("showBPM","showBpm"),s("bpm"),i("singlePlay"),i("playOnSeek"),e.dataset.title&&(t.title=e.dataset.title),e.dataset.subtitle&&(t.subtitle=e.dataset.subtitle),e.dataset.album&&(t.album=e.dataset.album),e.dataset.artwork&&(t.artwork=e.dataset.artwork),e.dataset.waveform&&(t.waveform=e.dataset.waveform),o("markers"),s("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),o("playbackRates"),i("enableMediaSession"),i("showMarkers"),i("accessibleSeek"),e.dataset.seekLabel&&(t.seekLabel=e.dataset.seekLabel),e.dataset.errorText&&(t.errorText=e.dataset.errorText),e.dataset.playIcon&&(t.playIcon=e.dataset.playIcon),e.dataset.pauseIcon&&(t.pauseIcon=e.dataset.pauseIcon),t}function S(e){if(!e||isNaN(e)||e<0)return"0:00";let t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);return t>0?`${t}:${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${i}:${s.toString().padStart(2,"0")}`}var st=0;function q(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)}_${(st++).toString(36)}`}function D(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,o=>o.toUpperCase())}function F(e){let t=typeof e=="string"?e.match(/\d+/g):null;if(!t||t.length<3)return null;let[i,s,o]=t.map(Number);return(i*299+s*587+o*114)/1e3}function R(...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 U(e,t){let i;return function(...o){let r=()=>{clearTimeout(i),e(...o)};clearTimeout(i),i=setTimeout(r,t)}}function T(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 o=0;o<t;o++){let r=o*s,a=Math.floor(r),n=Math.ceil(r),l=r-a;if(n>=e.length)i.push(e[e.length-1]);else if(a===n)i.push(e[a]);else{let d=e[a]*(1-l)+e[n]*l;i.push(d)}}}else{let s=e.length/t;for(let o=0;o<t;o++){let r=Math.floor(o*s),a=Math.floor((o+1)*s),n=0,l=0;for(let d=r;d<=a&&d<e.length;d++)e[d]>n&&(n=e[d]),l++;if(l===0){let d=Math.min(Math.round(o*s),e.length-1);n=e[d]}i.push(n)}}return i}function E(e,t,i){if(!Array.isArray(t))return t;if(t.length===1)return t[0];let s=e.createLinearGradient(0,0,0,i);return t.forEach((o,r)=>s.addColorStop(r/(t.length-1),o)),s}function P(e,t,i,s,o,r){if((Array.isArray(r)?r.some(n=>n>0):r>0)&&typeof e.roundRect=="function"){let n=Math.min(s/2,Math.abs(o)/2),l=d=>g(d,0,n);e.beginPath(),e.roundRect(t,i,s,o,Array.isArray(r)?r.map(l):l(r)),e.fill()}else e.fillRect(t,i,s,o)}function K(e,t){return(e.barRadius||0)*t}function ot(e,t){let i=K(e,t);return[i,i,0,0]}function N(e,t,i,s,o){let r=o/2;e.beginPath(),e.moveTo(t,s-r),e.lineTo(i-r,s-r),e.arc(i-r,s,r,-Math.PI/2,Math.PI/2),e.lineTo(t,s+r),e.arc(t,s,r,Math.PI/2,-Math.PI/2),e.closePath()}function B(e,t,i,s,o){let r=window.devicePixelRatio||1,a=o.barWidth*r,n=o.barSpacing*r,l=Math.floor(t.width/(a+n)),d=T(i,l),h=t.height,u=s*t.width,b=ot(o,r),w=E(e,o.color,h),p=E(e,o.progressColor,h);e.clearRect(0,0,t.width,t.height),e.fillStyle=w;for(let m=0;m<d.length;m++){let c=m*(a+n);if(c+a>t.width)break;let y=d[m]*h*.9,f=h-y;P(e,c,f,a,y,b)}e.save(),e.beginPath(),e.rect(0,0,u,h),e.clip(),e.fillStyle=p;for(let m=0;m<d.length;m++){let c=m*(a+n);if(c>u)break;let y=d[m]*h*.9,f=h-y;P(e,c,f,a,y,b)}e.restore()}function rt(e,t,i,s,o){let r=window.devicePixelRatio||1,a=o.barWidth*r,n=o.barSpacing*r,l=Math.floor(t.width/(a+n)),d=T(i,l),h=t.height,u=h/2,b=s*t.width,w=K(o,r),p=[w,w,0,0],m=[0,0,w,w],c=E(e,o.color,h),y=E(e,o.progressColor,h);e.clearRect(0,0,t.width,t.height),e.fillStyle=c;for(let f=0;f<d.length;f++){let v=f*(a+n);if(v+a>t.width)break;let k=d[f]*h*.45;P(e,v,u-k,a,k,p),P(e,v,u,a,k,m)}e.save(),e.beginPath(),e.rect(0,0,b,h),e.clip(),e.fillStyle=y;for(let f=0;f<d.length;f++){let v=f*(a+n);if(v>b)break;let k=d[f]*h*.45;P(e,v,u-k,a,k,p),P(e,v,u,a,k,m)}e.restore()}function at(e,t,i,s,o){let r=t.width,a=t.height,n=a/2,l=a*.35;e.clearRect(0,0,r,a);let d=(h,u,b=1,w=!1)=>{w&&(e.shadowBlur=12,e.shadowColor=h),e.strokeStyle=h,e.lineWidth=u,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],m=Math.floor(i.length*b);for(let c=0;c<m;c++){let y=c/(i.length-1)*r,f=i[c],v=Math.sin(c*.1)*f,k=n+v*l;p.push({x:y,y:k})}for(let c=0;c<p.length-1;c++){let y=p[c].x+(p[c+1].x-p[c].x)*.5,f=p[c].y,v=p[c+1].x-(p[c+1].x-p[c].x)*.5,k=p[c+1].y;e.bezierCurveTo(y,f,v,k,p[c+1].x,p[c+1].y)}e.stroke(),w&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(r,n),e.stroke();for(let h=0;h<=10;h++){let u=r/10*h;e.beginPath(),e.moveTo(u,0),e.lineTo(u,a),e.stroke()}d(o.color,2,1,!1),s>0&&d(o.progressColor,3,s,!0)}function V(e,t,i,s,o){let r=window.devicePixelRatio||1,a=(o.barWidth||3)*r,n=(o.barSpacing||1)*r,l=Math.floor(t.width/(a+n)),d=T(i,l),h=t.height,u=4*r,b=2*r,w=s*t.width,p=h/2,m=E(e,o.color,h),c=E(e,o.progressColor,h);e.clearRect(0,0,t.width,t.height);for(let y=0;y<d.length;y++){let f=y*(a+n);if(f+a>t.width)break;let v=d[y]*h*.9,k=Math.floor(v/(u+b));e.fillStyle=f<w?c:m;for(let A=0;A<k;A++){let $=A*(u+b);e.fillRect(f,p-$-u,a,u),A>0&&e.fillRect(f,p+$,a,u)}}}function j(e,t,i,s,o){let r=window.devicePixelRatio||1,a=(o.barWidth||2)*r,n=(o.barSpacing||3)*r,l=Math.floor(t.width/(a+n)),d=T(i,l),h=t.height,u=Math.max(1.5*r,a/2),b=s*t.width,w=h/2,p=E(e,o.color,h),m=E(e,o.progressColor,h);e.clearRect(0,0,t.width,t.height);for(let c=0;c<d.length;c++){let y=c*(a+n)+a/2;if(y>t.width)break;let f=d[c]*h*.9;e.fillStyle=y<b?m:p,e.beginPath(),e.arc(y,w-f/2,u,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(y,w+f/2,u,0,Math.PI*2),e.fill()}}function nt(e,t,i,s,o){let r=t.width,a=t.height,n=a/2,l=4,d=l/2;if(e.clearRect(0,0,r,a),e.fillStyle=o.color||"rgba(255, 255, 255, 0.2)",N(e,d,r,n,l),e.fill(),s>0){let h=Math.max(d*2,s*r);e.shadowBlur=8,e.shadowColor=o.progressColor,e.fillStyle=o.progressColor||"rgba(255, 255, 255, 0.9)",N(e,d,h,n,l),e.fill(),e.shadowBlur=0;let u=8,b=h;e.shadowBlur=4,e.shadowColor="rgba(0, 0, 0, 0.3)",e.shadowOffsetY=2,e.fillStyle="#ffffff",e.beginPath(),e.arc(b,n,u,0,Math.PI*2),e.fill(),e.shadowBlur=0,e.shadowOffsetY=0,e.fillStyle=o.progressColor||"rgba(255, 255, 255, 0.9)",e.beginPath(),e.arc(b,n,u*.4,0,Math.PI*2),e.fill()}}var lt={bars:B,bar:B,mirror:rt,line:at,blocks:V,block:V,dots:j,dot:j,seekbar:nt};function J(e,t,i,s,o){(lt[o.waveformStyle]||B)(e,t,i,s,o)}function Y(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=ht(t,i);if(s.length<2)return 120;let o=[];for(let l=1;l<s.length;l++)o.push((s[l]-s[l-1])/i);let r={};o.forEach(l=>{let d=60/l,h=Math.round(d/3)*3;h>60&&h<200&&(r[h]=(r[h]||0)+1)});let a=0,n=120;for(let[l,d]of Object.entries(r))d>a&&(a=d,n=parseInt(l));return n<70&&r[n*2]?n*=2:n>160&&r[Math.round(n/2)]&&(n=Math.round(n/2)),n-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function ht(e,t){let o=[],r=0;for(let a=0;a<e.length-2048;a+=1024){let n=0;for(let h=a;h<a+2048;h++)n+=e[h]*e[h];n=n/2048;let l=n-r,d=r*1.8+.01;if(l>d&&n>.01){let h=o[o.length-1]||0,u=t*.15;a-h>u&&o.push(a)}r=n*.8+r*.2}return o}function dt(e,t=200){let i=e.length/t,s=e.numberOfChannels,o=[];for(let a=0;a<s;a++){let n=e.getChannelData(a);for(let l=0;l<t;l++){let d=~~(l*i),h=~~(d+i),u=0,b=0;for(let p=d;p<h;p++){let m=n[p];m>b&&(b=m),m<u&&(u=m)}let w=Math.max(Math.abs(b),Math.abs(u));(a===0||w>o[l])&&(o[l]=w)}}let r=Math.max(...o);return r>0?o.map(a=>a/r):o}async function W(e,t=200,i=!1){let s;try{let o=window.AudioContext||window.webkitAudioContext;s=new o;let a=await(await fetch(e)).arrayBuffer(),n=await s.decodeAudioData(a),l=dt(n,t);l=ct(l);let d=null;return i&&(d=Y(n)),{peaks:l,bpm:d}}finally{s&&s.close()}}function G(e=200){let t=[];for(let i=0;i<e;i++){let s=Math.random()*.5+.3,o=Math.sin(i/e*Math.PI*4)*.2;t.push(g(s+o,.1,1))}return t}function ct(e,t=.95){let i=Math.max(...e);if(i===0||i>t)return e;let s=t/i;return e.map(o=>o*s)}function Q(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 ut(){if(Q("dark"))return"dark";if(Q("light"))return"light";try{let e=getComputedStyle(document.body).backgroundColor,t=F(e);if(t!==null){if(t>128)return"light";if(t<128)return"dark"}}catch{}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"}var M={dark:{waveformColor:"rgba(255, 255, 255, 0.3)",progressColor:"rgba(255, 255, 255, 0.9)",buttonColor:"rgba(255, 255, 255, 0.9)",buttonHoverColor:"rgba(255, 255, 255, 1)",textColor:"#ffffff",textSecondaryColor:"rgba(255, 255, 255, 0.6)",backgroundColor:"rgba(255, 255, 255, 0.03)",borderColor:"rgba(255, 255, 255, 0.1)"},light:{waveformColor:"rgba(0, 0, 0, 0.2)",progressColor:"rgba(0, 0, 0, 0.8)",buttonColor:"rgba(0, 0, 0, 0.8)",buttonHoverColor:"rgba(0, 0, 0, 0.9)",textColor:"#333333",textSecondaryColor:"rgba(0, 0, 0, 0.6)",backgroundColor:"rgba(0, 0, 0, 0.02)",borderColor:"rgba(0, 0, 0, 0.1)"}};function _(e){if(e&&M[e])return M[e];let t=ut();return M[t]}var X={url:"",height:64,samples:1800,preload:"metadata",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,waveformStyle:"mirror",barWidth:2,barSpacing:0,barRadius:1,colorPreset:null,waveformColor:null,progressColor:null,buttonColor:null,buttonHoverColor:null,textColor:null,textSecondaryColor:null,backgroundColor:null,borderColor:null,autoplay:!1,showControls:!0,showInfo:!0,showTime:!0,showHoverTime:!1,showBPM:!1,bpm:null,singlePlay:!0,playOnSeek:!0,enableMediaSession:!0,markers:[],showMarkers:!0,accessibleSeek:!0,seekLabel:null,title:null,subtitle:null,artwork:null,album:"",errorText:"Unable to load audio",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},Z={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}};var pt="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>'),tt=5,et=10,C=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=x(this.container),o={...i};o.style&&!o.waveformStyle&&(o.waveformStyle=o.style),o.src&&!o.url&&(o.url=o.src),this.options=R(X,s,o);let r=_(this.options.colorPreset);this._autoTheme=this.options.colorPreset==null||!M[this.options.colorPreset],this._presetKeys=[];for(let[n,l]of Object.entries(r))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let a=Z[this.options.waveformStyle];a&&(s.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=a.barWidth),s.barSpacing===void 0&&i.barSpacing===void 0&&(this.options.barSpacing=a.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._ac=new AbortController,this.id=this.container.id||q(this.options.url),e.instances.set(this.id,this),e._watchTheme(),this.init(),setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,s=!1){let o=new CustomEvent(t,{bubbles:!0,cancelable:s,detail:i});return this.container.dispatchEvent(o),o}_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.resizeCanvas(),this.options.url&&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=this.options.buttonAlign;t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview");let s=this.options.showControls?`
1
+ (()=>{function D(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function L(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function q(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 g(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function rt(e){return e===void 0?void 0:e==="true"}function O(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function x(e){let t={},i=(o,a=o)=>{let n=rt(e.dataset[a]);n!==void 0&&(t[o]=n)},s=(o,a=o,n=!1)=>{let l=e.dataset[a];l&&(t[o]=n?parseFloat(l):parseInt(l,10))},r=(o,a=o)=>{let n=e.dataset[a];if(n)try{t[o]=JSON.parse(n)}catch(l){console.warn(`[WaveformPlayer] Invalid ${a} JSON:`,l)}};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.audioMode&&(t.audioMode=e.dataset.audioMode),e.dataset.style&&(t.waveformStyle=e.dataset.style),e.dataset.waveformStyle&&(t.waveformStyle=e.dataset.waveformStyle),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),e.dataset.buttonSize){let o=e.dataset.buttonSize;t.buttonSize=/^\d+(\.\d+)?$/.test(o.trim())?parseFloat(o):o}return e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=O(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=O(e.dataset.progressColor)),e.dataset.buttonColor&&(t.buttonColor=e.dataset.buttonColor),e.dataset.buttonHoverColor&&(t.buttonHoverColor=e.dataset.buttonHoverColor),e.dataset.textColor&&(t.textColor=e.dataset.textColor),e.dataset.textSecondaryColor&&(t.textSecondaryColor=e.dataset.textSecondaryColor),e.dataset.backgroundColor&&(t.backgroundColor=e.dataset.backgroundColor),e.dataset.borderColor&&(t.borderColor=e.dataset.borderColor),e.dataset.color&&(t.waveformColor=e.dataset.color),e.dataset.theme&&(t.colorPreset=e.dataset.theme),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.subtitle&&(t.subtitle=e.dataset.subtitle),e.dataset.album&&(t.album=e.dataset.album),e.dataset.artwork&&(t.artwork=e.dataset.artwork),e.dataset.waveform&&(t.waveform=e.dataset.waveform),r("markers"),s("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),r("playbackRates"),i("enableMediaSession"),i("showMarkers"),i("accessibleSeek"),e.dataset.seekLabel&&(t.seekLabel=e.dataset.seekLabel),e.dataset.errorText&&(t.errorText=e.dataset.errorText),e.dataset.playIcon&&(t.playIcon=e.dataset.playIcon),e.dataset.pauseIcon&&(t.pauseIcon=e.dataset.pauseIcon),t}function S(e){if(!e||isNaN(e)||e<0)return"0:00";let t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);return t>0?`${t}:${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${i}:${s.toString().padStart(2,"0")}`}var ot=0;function U(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)}_${(ot++).toString(36)}`}function H(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 N(e){let t=typeof e=="string"?e.match(/\d+/g):null;if(!t||t.length<3)return null;let[i,s,r]=t.map(Number);return(i*299+s*587+r*114)/1e3}function R(...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 V(e,t){let i;return function(...r){let o=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(o,t)}}function M(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 o=r*s,a=Math.floor(o),n=Math.ceil(o),l=o-a;if(n>=e.length)i.push(e[e.length-1]);else if(a===n)i.push(e[a]);else{let h=e[a]*(1-l)+e[n]*l;i.push(h)}}}else{let s=e.length/t;for(let r=0;r<t;r++){let o=Math.floor(r*s),a=Math.floor((r+1)*s),n=0,l=0;for(let h=o;h<=a&&h<e.length;h++)e[h]>n&&(n=e[h]),l++;if(l===0){let h=Math.min(Math.round(r*s),e.length-1);n=e[h]}i.push(n)}}return i}function E(e,t,i){if(!Array.isArray(t))return t;if(t.length===1)return t[0];let s=e.createLinearGradient(0,0,0,i);return t.forEach((r,o)=>s.addColorStop(o/(t.length-1),r)),s}function T(e,t,i,s,r,o){if((Array.isArray(o)?o.some(n=>n>0):o>0)&&typeof e.roundRect=="function"){let n=Math.min(s/2,Math.abs(r)/2),l=h=>g(h,0,n);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(o)?o.map(l):l(o)),e.fill()}else e.fillRect(t,i,s,r)}function G(e,t){return(e.barRadius||0)*t}function at(e,t){let i=G(e,t);return[i,i,0,0]}function j(e,t,i,s,r){let o=r/2;e.beginPath(),e.moveTo(t,s-o),e.lineTo(i-o,s-o),e.arc(i-o,s,o,-Math.PI/2,Math.PI/2),e.lineTo(t,s+o),e.arc(t,s,o,Math.PI/2,-Math.PI/2),e.closePath()}function W(e,t,i,s,r){let o=window.devicePixelRatio||1,a=r.barWidth*o,n=r.barSpacing*o,l=Math.floor(t.width/(a+n)),h=M(i,l),d=t.height,u=s*t.width,v=at(r,o),b=E(e,r.color,d),p=E(e,r.progressColor,d);e.clearRect(0,0,t.width,t.height),e.fillStyle=b;for(let m=0;m<h.length;m++){let c=m*(a+n);if(c+a>t.width)break;let y=h[m]*d*.9,f=d-y;T(e,c,f,a,y,v)}e.save(),e.beginPath(),e.rect(0,0,u,d),e.clip(),e.fillStyle=p;for(let m=0;m<h.length;m++){let c=m*(a+n);if(c>u)break;let y=h[m]*d*.9,f=d-y;T(e,c,f,a,y,v)}e.restore()}function nt(e,t,i,s,r){let o=window.devicePixelRatio||1,a=r.barWidth*o,n=r.barSpacing*o,l=Math.floor(t.width/(a+n)),h=M(i,l),d=t.height,u=d/2,v=s*t.width,b=G(r,o),p=[b,b,0,0],m=[0,0,b,b],c=E(e,r.color,d),y=E(e,r.progressColor,d);e.clearRect(0,0,t.width,t.height),e.fillStyle=c;for(let f=0;f<h.length;f++){let w=f*(a+n);if(w+a>t.width)break;let k=h[f]*d*.45;T(e,w,u-k,a,k,p),T(e,w,u,a,k,m)}e.save(),e.beginPath(),e.rect(0,0,v,d),e.clip(),e.fillStyle=y;for(let f=0;f<h.length;f++){let w=f*(a+n);if(w>v)break;let k=h[f]*d*.45;T(e,w,u-k,a,k,p),T(e,w,u,a,k,m)}e.restore()}function lt(e,t,i,s,r){let o=t.width,a=t.height,n=a/2,l=a*.35;e.clearRect(0,0,o,a);let h=(d,u,v=1,b=!1)=>{b&&(e.shadowBlur=12,e.shadowColor=d),e.strokeStyle=d,e.lineWidth=u,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],m=Math.floor(i.length*v);for(let c=0;c<m;c++){let y=c/(i.length-1)*o,f=i[c],w=Math.sin(c*.1)*f,k=n+w*l;p.push({x:y,y:k})}for(let c=0;c<p.length-1;c++){let y=p[c].x+(p[c+1].x-p[c].x)*.5,f=p[c].y,w=p[c+1].x-(p[c+1].x-p[c].x)*.5,k=p[c+1].y;e.bezierCurveTo(y,f,w,k,p[c+1].x,p[c+1].y)}e.stroke(),b&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(o,n),e.stroke();for(let d=0;d<=10;d++){let u=o/10*d;e.beginPath(),e.moveTo(u,0),e.lineTo(u,a),e.stroke()}h(r.color,2,1,!1),s>0&&h(r.progressColor,3,s,!0)}function K(e,t,i,s,r){let o=window.devicePixelRatio||1,a=(r.barWidth||3)*o,n=(r.barSpacing||1)*o,l=Math.floor(t.width/(a+n)),h=M(i,l),d=t.height,u=4*o,v=2*o,b=s*t.width,p=d/2,m=E(e,r.color,d),c=E(e,r.progressColor,d);e.clearRect(0,0,t.width,t.height);for(let y=0;y<h.length;y++){let f=y*(a+n);if(f+a>t.width)break;let w=h[y]*d*.9,k=Math.floor(w/(u+v));e.fillStyle=f<b?c:m;for(let _=0;_<k;_++){let F=_*(u+v);e.fillRect(f,p-F-u,a,u),_>0&&e.fillRect(f,p+F,a,u)}}}function J(e,t,i,s,r){let o=window.devicePixelRatio||1,a=(r.barWidth||2)*o,n=(r.barSpacing||3)*o,l=Math.floor(t.width/(a+n)),h=M(i,l),d=t.height,u=Math.max(1.5*o,a/2),v=s*t.width,b=d/2,p=E(e,r.color,d),m=E(e,r.progressColor,d);e.clearRect(0,0,t.width,t.height);for(let c=0;c<h.length;c++){let y=c*(a+n)+a/2;if(y>t.width)break;let f=h[c]*d*.9;e.fillStyle=y<v?m:p,e.beginPath(),e.arc(y,b-f/2,u,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(y,b+f/2,u,0,Math.PI*2),e.fill()}}function ht(e,t,i,s,r){let o=t.width,a=t.height,n=a/2,l=4,h=l/2,d=!!r.seekActive;if(e.clearRect(0,0,o,a),e.fillStyle=r.color||"rgba(255, 255, 255, 0.2)",j(e,h,o,n,l),e.fill(),s>0){let u=Math.max(h*2,s*o);e.save(),e.globalAlpha=r.seekHandle&&!d?.7:1,e.fillStyle=r.progressColor||"rgba(255, 255, 255, 0.9)",j(e,h,u,n,l),e.fill(),e.restore()}}var dt={bars:W,bar:W,mirror:nt,line:lt,blocks:K,block:K,dots:J,dot:J,seekbar:ht};function Y(e,t,i,s,r){(dt[r.waveformStyle]||W)(e,t,i,s,r)}function X(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=ct(t,i);if(s.length<2)return 120;let r=[];for(let l=1;l<s.length;l++)r.push((s[l]-s[l-1])/i);let o={};r.forEach(l=>{let h=60/l,d=Math.round(h/3)*3;d>60&&d<200&&(o[d]=(o[d]||0)+1)});let a=0,n=120;for(let[l,h]of Object.entries(o))h>a&&(a=h,n=parseInt(l));return n<70&&o[n*2]?n*=2:n>160&&o[Math.round(n/2)]&&(n=Math.round(n/2)),n-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function ct(e,t){let r=[],o=0;for(let a=0;a<e.length-2048;a+=1024){let n=0;for(let d=a;d<a+2048;d++)n+=e[d]*e[d];n=n/2048;let l=n-o,h=o*1.8+.01;if(l>h&&n>.01){let d=r[r.length-1]||0,u=t*.15;a-d>u&&r.push(a)}o=n*.8+o*.2}return r}function ut(e,t=1800){let i=e.length/t,s=e.numberOfChannels,r=[];for(let a=0;a<s;a++){let n=e.getChannelData(a);for(let l=0;l<t;l++){let h=~~(l*i),d=~~(h+i),u=0,v=0;for(let p=h;p<d;p++){let m=n[p];m>v&&(v=m),m<u&&(u=m)}let b=Math.max(Math.abs(v),Math.abs(u));(a===0||b>r[l])&&(r[l]=b)}}let o=D(r);return o>0?r.map(a=>a/o):r}async function B(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let a=await(await fetch(e)).arrayBuffer(),n=await s.decodeAudioData(a),l=ut(n,t);l=pt(l);let h=null;return i&&(h=X(n)),{peaks:l,bpm:h}}finally{s&&s.close()}}function Q(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(g(s+r,.1,1))}return t}function pt(e,t=.95){let i=D(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}function Z(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 ft(){if(Z("dark"))return"dark";if(Z("light"))return"light";try{let e=getComputedStyle(document.body).backgroundColor,t=N(e);if(t!==null){if(t>128)return"light";if(t<128)return"dark"}}catch{}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"}var A={dark:{waveformColor:"rgba(255, 255, 255, 0.3)",progressColor:"rgba(255, 255, 255, 0.9)",buttonColor:"rgba(255, 255, 255, 0.9)",buttonHoverColor:"rgba(255, 255, 255, 1)",textColor:"#ffffff",textSecondaryColor:"rgba(255, 255, 255, 0.6)",backgroundColor:"rgba(255, 255, 255, 0.03)",borderColor:"rgba(255, 255, 255, 0.1)"},light:{waveformColor:"rgba(0, 0, 0, 0.2)",progressColor:"rgba(0, 0, 0, 0.8)",buttonColor:"rgba(0, 0, 0, 0.8)",buttonHoverColor:"rgba(0, 0, 0, 0.9)",textColor:"#333333",textSecondaryColor:"rgba(0, 0, 0, 0.6)",backgroundColor:"rgba(0, 0, 0, 0.02)",borderColor:"rgba(0, 0, 0, 0.1)"}};function I(e){if(e&&A[e])return A[e];let t=ft();return A[t]}var tt={url:"",height:64,samples:1800,preload:"metadata",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,waveformStyle:"mirror",barWidth:2,barSpacing:0,barRadius:1,colorPreset:null,waveformColor:null,progressColor:null,buttonColor:null,buttonHoverColor:null,textColor:null,textSecondaryColor:null,backgroundColor:null,borderColor: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,title:null,subtitle:null,artwork:null,album:"",errorText:"Unable to load audio",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},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}};var mt="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>'),it=5,st=10,yt='button, a[href], input, [role="slider"]',C=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=x(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=R(tt,s,r);let o=I(this.options.colorPreset);this._autoTheme=this.options.colorPreset==null||!A[this.options.colorPreset],this._presetKeys=[];for(let[n,l]of Object.entries(o))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let a=et[this.options.waveformStyle];a&&(s.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=a.barWidth),s.barSpacing===void 0&&i.barSpacing===void 0&&(this.options.barSpacing=a.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._ac=new AbortController,this.id=this.container.id||U(this.options.url),e.instances.set(this.id,this),e._watchTheme(),this.init(),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.resizeCanvas(),this.options.url&&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=this.options.buttonAlign;t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview");let s=this.options.showControls?`
2
2
  <button class="waveform-btn${this.options.buttonStyle==="minimal"?" waveform-btn-minimal":""}" aria-label="Play/Pause" style="
3
3
  border-color: ${this.options.buttonColor};
4
4
  color: ${this.options.buttonColor};
@@ -7,7 +7,7 @@
7
7
  <span class="waveform-icon-play">${this.options.playIcon}</span>
8
8
  <span class="waveform-icon-pause" style="display:none;">${this.options.pauseIcon}</span>
9
9
  </button>
10
- `:"",o=this.options.showInfo?`
10
+ `:"",r=this.options.showInfo?`
11
11
  <div class="waveform-info">
12
12
  ${this.options.artwork?`
13
13
  <img class="waveform-artwork" src="${this.options.artwork}" alt="Album artwork" style="
@@ -30,11 +30,11 @@
30
30
  `:""}
31
31
  ${this.options.showPlaybackSpeed?`
32
32
  <div class="waveform-speed">
33
- <button class="speed-btn" aria-label="Playback speed">
33
+ <button class="speed-btn" aria-label="Playback speed" aria-haspopup="true" aria-expanded="false">
34
34
  <span class="speed-value">1x</span>
35
35
  </button>
36
36
  <div class="speed-menu" style="display: none;">
37
- ${this.options.playbackRates.map(r=>`<button class="speed-option" data-rate="${r}">${r}x</button>`).join("")}
37
+ ${this.options.playbackRates.map(o=>`<button class="speed-option" data-rate="${o}">${o}x</button>`).join("")}
38
38
  </div>
39
39
  </div>
40
40
  `:""}
@@ -61,7 +61,7 @@
61
61
  </div>
62
62
  </div>
63
63
 
64
- ${o}
64
+ ${r}
65
65
  </div>
66
66
  </div>
67
- `,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.subtitleEl=this.container.querySelector(".waveform-subtitle"),this.artworkEl=this.container.querySelector(".waveform-artwork"),this.artworkEl&&this.artworkEl.addEventListener("error",()=>{this.artworkEl.src.startsWith("data:")||(this.artworkEl.src=pt)}),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()}createAudio(){if(this.options.audioMode==="external"){this.audio=null;return}this.audio=new Audio,this.audio.preload=this.options.preload||"metadata",this.audio.crossOrigin="anonymous"}initPlaybackSpeed(){this.audio&&this.options.playbackRate&&this.options.playbackRate!==1&&(this.audio.playbackRate=this.options.playbackRate),this.options.showPlaybackSpeed&&this.initSpeedControls()}initSpeedControls(){let t=this.container.querySelector(".speed-btn"),i=this.container.querySelector(".speed-menu");!t||!i||(t.addEventListener("click",s=>{s.stopPropagation(),i.style.display=i.style.display==="none"?"block":"none"},{signal:this._ac.signal}),document.addEventListener("click",()=>{i.style.display="none"},{signal:this._ac.signal}),i.addEventListener("click",s=>{if(s.stopPropagation(),s.target.classList.contains("speed-option")){let o=parseFloat(s.target.dataset.rate);this.setPlaybackRate(o),i.style.display="none"}},{signal:this._ac.signal}),this.updateSpeedUI())}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",()=>{e.getAllInstances().forEach(t=>{t!==this&&t.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,o=s?this.audio.currentTime:0;if(s&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let r={" ":()=>this.togglePlay()};s&&(r.ArrowLeft=()=>this.seekTo(g(o-5,0,this.audio.duration)),r.ArrowRight=()=>this.seekTo(g(o+5,0,this.audio.duration)),r.ArrowUp=()=>this.setVolume(g(this.audio.volume+.1)),r.ArrowDown=()=>this.setVolume(g(this.audio.volume-.1)),r.m=r.M=()=>this.audio.muted=!this.audio.muted),r[i]&&(t.preventDefault(),r[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=>{let i=this.getSeekDuration();if(!i)return;let s=this.getSeekCurrentTime(),o;switch(t.key){case"ArrowLeft":case"ArrowDown":o=s-tt;break;case"ArrowRight":case"ArrowUp":o=s+tt;break;case"PageDown":o=s-et;break;case"PageUp":o=s+et;break;case"Home":o=0;break;case"End":o=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(o)},{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=g(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",`${S(i)} of ${S(t)}`)}initMediaSession(){!("mediaSession"in navigator)||!this.options.enableMediaSession||this.audio&&(navigator.mediaSession.metadata=new MediaMetadata({title:this.options.title||"Unknown Track",artist:this.options.subtitle||"",album:this.options.album||"",artwork:this.options.artwork?[{src:this.options.artwork,sizes:"512x512",type:"image/jpeg"}]:[]}),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(g(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(g(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",t=>{t.seekTime!==null&&this.seekTo(t.seekTime)}))}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",t=>this.onError(t))),this.canvas.addEventListener("click",t=>this.handleCanvasClick(t)),this.setupHoverTime(),this.resizeHandler=U(()=>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){try{this.setLoading(!0),this.progress=0,this.hasError=!1,this.audio&&(this.audio.src=t,await new Promise((s,o)=>{let r=()=>{this.audio.removeEventListener("loadedmetadata",r),this.audio.removeEventListener("error",a),s()},a=n=>{this.audio.removeEventListener("loadedmetadata",r),this.audio.removeEventListener("error",a),o(n)};this.audio.addEventListener("loadedmetadata",r),this.audio.addEventListener("error",a)}));let i=this.options.title||D(t);if(this.titleEl&&(this.titleEl.textContent=i),this.applySeekLabel(i),this.options.waveform)this.setWaveformData(this.options.waveform);else try{let s=await W(t,this.options.samples,this.options.showBPM);this.waveformData=s.peaks,s.bpm&&(this.detectedBPM=s.bpm,this.updateBPMDisplay())}catch(s){console.warn("[WaveformPlayer] Using placeholder waveform:",s),this.waveformData=G(this.options.samples)}this.drawWaveform(),this.renderMarkers(),this.initMediaSession(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}async loadTrack(t,i=null,s=null,o={}){this.isPlaying&&this.pause(),this.audio&&(this.audio.src="",this.audio.load()),this.hasError=!1,this.errorEl&&(this.errorEl.style.display="none"),this.canvas&&(this.canvas.style.opacity="1"),this.playBtn&&(this.playBtn.disabled=!1),this.progress=0,this.waveformData=[],this.options=R(this.options,{url:t,title:i||this.options.title,subtitle:s||this.options.subtitle,...o}),o.preload&&this.audio&&(this.audio.preload=o.preload),this.subtitleEl&&(s?(this.subtitleEl.textContent=s,this.subtitleEl.style.display=""):s===""&&(this.subtitleEl.style.display="none")),o.artwork&&this.artworkEl&&(this.artworkEl.src=o.artwork),this.options.markers=o.markers||[],this.options.waveform=o.waveform||null,await this.load(t),o.autoplay!==!1&&this.play()?.catch(()=>{})}setWaveformData(t){if(typeof t=="string"&&t.trim().endsWith(".json")){fetch(t.trim()).then(i=>i.json()).then(i=>{this.waveformData=Array.isArray(i)?i:i.peaks||[],i.markers&&!this.options.markers?.length&&(this.options.markers=i.markers,this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}if(typeof t=="string")try{let i=JSON.parse(t);this.waveformData=Array.isArray(i)?i:[]}catch{this.waveformData=t.split(",").map(Number)}else this.waveformData=Array.isArray(t)?t:[];this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||J(this.ctx,this.canvas,this.waveformData,this.progress,{...this.options,waveformStyle:this.options.waveformStyle||"bars",color:this.options.waveformColor,progressColor:this.options.progressColor})}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 o=i.time/t*100,r=document.createElement("button");r.className="waveform-marker",r.style.left=`${o}%`,r.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",r.setAttribute("aria-label",i.label),r.setAttribute("data-time",i.time);let a=document.createElement("span");a.className="waveform-marker-tooltip",a.textContent=i.label,r.appendChild(a),r.addEventListener("click",n=>{n.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(r)})}setActiveMarker(t){if(!this.markersContainer)return;this.markersContainer.querySelectorAll(".waveform-marker").forEach((s,o)=>s.classList.toggle("active",o===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,o=-1,r=-1/0;t.forEach((a,n)=>{let l=parseFloat(a.getAttribute("data-time"));Number.isFinite(l)&&l<=s+.05&&l>r&&(r=l,o=n)}),o!==this._activeMarkerIndex&&(this._activeMarkerIndex=o,this.setActiveMarker(o),clearTimeout(this._markerLabelTimer),t.forEach((a,n)=>a.classList.toggle("show-label",n===o)),o>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(a=>a.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.options.showHoverTime||!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.seekEl.addEventListener("pointermove",i=>{let s=this.getSeekDuration();if(!s){t.style.opacity="0";return}let o=this.canvas.getBoundingClientRect(),r=g((i.clientX-o.left)/o.width);t.textContent=S(r*s),t.style.left=r*100+"%",t.style.opacity="1"}),this.seekEl.addEventListener("pointerleave",()=>{t.style.opacity="0"})}handleCanvasClick(t){let i=this.canvas.getBoundingClientRect(),s=t.clientX-i.left,o=g(s/i.width);if(this.options.audioMode==="external"){this._requestSeek(o);return}!this.audio||!this.audio.duration||this.seekToPercent(o)}setLoading(t){this.isLoading=t,this.loadingEl&&(this.loadingEl.style.display=t?"block":"none"),this.seekEl&&this.seekEl.setAttribute("aria-busy",t?"true":"false")}onMetadataLoaded(){this.isDestroying||(this.totalTimeEl&&(this.totalTimeEl.textContent=S(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._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._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.onPause(),this.options.onEnd&&this.options.onEnd(this)}onError(t){this.isDestroying||(console.error("[WaveformPlayer] Audio error:",t),this.hasError=!0,this.setLoading(!1),this.errorEl&&(this.errorEl.style.display="flex"),this.canvas&&(this.canvas.style.opacity="0.2"),this.playBtn&&(this.playBtn.disabled=!0),this.options.onError&&this.options.onError(t,this))}startSmoothUpdate(){this.stopSmoothUpdate();let t=()=>{this.isPlaying&&this.audio&&this.audio.duration&&(this.updateProgress(),this.updateTimer=requestAnimationFrame(t))};this.updateTimer=requestAnimationFrame(t)}stopSmoothUpdate(){this.updateTimer&&(cancelAnimationFrame(this.updateTimer),this.updateTimer=null)}updateProgress(){if(!this.audio||!this.audio.duration)return;let t=this.audio.currentTime/this.audio.duration;Math.abs(t-this.progress)>.001&&(this.progress=t,this.drawWaveform()),this.currentTimeEl&&(this.currentTimeEl.textContent=S(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="inline-flex")}refreshTheme(){if(!this._autoTheme||!this._presetKeys||!this._presetKeys.length)return;let t=_(this.options.colorPreset),i=!1;for(let s of this._presetKeys)this.options[s]!==t[s]&&(this.options[s]=t[s],i=!0);i&&this._applyThemeColors()}_applyThemeColors(){let t=this.options;this.playBtn&&(this.playBtn.style.borderColor=t.buttonColor,this.playBtn.style.color=t.buttonColor),this.titleEl&&(this.titleEl.style.color=t.textColor),this.subtitleEl&&(this.subtitleEl.style.color=t.textSecondaryColor),this.container.querySelectorAll(".waveform-time, .waveform-bpm").forEach(i=>{i.style.color=t.textSecondaryColor}),this.canvas&&this.drawWaveform()}static _watchTheme(){if(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(r=>{try{r.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 o=null;try{o=window.matchMedia("(prefers-color-scheme: dark)"),o.addEventListener("change",t)}catch{}e._themeWatch={obs:s,mq:o,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=>{i.classList.toggle("active",parseFloat(i.dataset.rate)===this.audio.playbackRate)})}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(){if(e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.options.audioMode==="external"){this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0);return}this.audio.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,subtitle:this.options.subtitle,artist:this.options.artist||this.options.subtitle,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.progress=g(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=S(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=S(i),this.totalTimeEl.dataset._extSet="1",this.totalTimeEl.dataset._extDur=String(i)),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){this.audio&&this.audio.duration&&(this.audio.currentTime=g(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*g(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=g(i))}setPlaybackRate(t){if(!this.audio)return;let i=g(t,.5,2);this.audio.playbackRate=i,this.options.playbackRate=i,this.updateSpeedUI()}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.pause(),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),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),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",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(o=>o.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=200){try{return(await W(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}};C.utils={formatTime:S,extractTitleFromUrl:D,escapeHtml:L,isSafeHref:O,parseDataAttributes:x};var I=()=>typeof window<"u"&&typeof document<"u";function z(){if(!I())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(t.dataset.waveformInitialized!=="true")try{new C(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}I()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",z):z());C.init=z;I()&&(window.WaveformPlayer=C);var xt=C;})();
67
+ `,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.subtitleEl=this.container.querySelector(".waveform-subtitle"),this.artworkEl=this.container.querySelector(".waveform-artwork"),this.artworkEl&&this.artworkEl.addEventListener("error",()=>{this.artworkEl.src.startsWith("data:")||(this.artworkEl.src=mt)}),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()}createAudio(){if(this.options.audioMode==="external"){this.audio=null;return}this.audio=new Audio,this.audio.preload=this.options.preload||"metadata",this.audio.crossOrigin="anonymous"}initPlaybackSpeed(){this.audio&&this.options.playbackRate&&this.options.playbackRate!==1&&(this.audio.playbackRate=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=r=>{i.style.display=r?"block":"none",t.setAttribute("aria-expanded",r?"true":"false")};t.addEventListener("click",r=>{r.stopPropagation(),s(i.style.display==="none")},{signal:this._ac.signal}),document.addEventListener("click",()=>s(!1),{signal:this._ac.signal}),i.addEventListener("click",r=>{r.stopPropagation(),r.target.classList.contains("speed-option")&&(this.setPlaybackRate(parseFloat(r.target.dataset.rate)),s(!1),t.focus())},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",r=>{r.key==="Escape"&&i.style.display!=="none"&&(s(!1),t.focus())},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(yt)||(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 o={" ":()=>this.togglePlay()};s&&(o.ArrowLeft=()=>this.seekTo(g(r-5,0,this.audio.duration)),o.ArrowRight=()=>this.seekTo(g(r+5,0,this.audio.duration)),o.ArrowUp=()=>this.setVolume(g(this.audio.volume+.1)),o.ArrowDown=()=>this.setVolume(g(this.audio.volume-.1)),o.m=o.M=()=>this.audio.muted=!this.audio.muted),o[i]&&(t.preventDefault(),o[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=>{let i=this.getSeekDuration();if(!i)return;let s=this.getSeekCurrentTime(),r;switch(t.key){case"ArrowLeft":case"ArrowDown":r=s-it;break;case"ArrowRight":case"ArrowUp":r=s+it;break;case"PageDown":r=s-st;break;case"PageUp":r=s+st;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=g(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",`${S(i)} of ${S(t)}`)}initMediaSession(){!("mediaSession"in navigator)||!this.options.enableMediaSession||this.audio&&(navigator.mediaSession.metadata=new MediaMetadata({title:this.options.title||"Unknown Track",artist:this.options.subtitle||"",album:this.options.album||"",artwork:this.options.artwork?[{src:this.options.artwork,sizes:"512x512",type:"image/jpeg"}]:[]}),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(g(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(g(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",t=>{t.seekTime!==null&&this.seekTo(t.seekTime)}))}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.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;try{this.canvas.releasePointerCapture(i.pointerId)}catch{}this._seekFromPointer(i.clientX),this._seekHover||this._hideHoverTip(),this._updateSeekHandle()}};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",t),this.setupHoverTime(),this.setupSeekHandle(),this.resizeHandler=V(()=>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){try{this.setLoading(!0),this.progress=0,this.hasError=!1,this.audio&&(this.audio.src=t,await new Promise((s,r)=>{let o=()=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",a),s()},a=n=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",a),r(n)};this.audio.addEventListener("loadedmetadata",o),this.audio.addEventListener("error",a)}));let i=this.options.title||H(t);if(this.titleEl&&(this.titleEl.textContent=i),this.applySeekLabel(i),this.options.waveform)this.setWaveformData(this.options.waveform);else try{let s=await B(t,this.options.samples,this.options.showBPM);this.waveformData=s.peaks,s.bpm&&(this.detectedBPM=s.bpm,this.updateBPMDisplay())}catch(s){console.warn("[WaveformPlayer] Using placeholder waveform:",s),this.waveformData=Q(this.options.samples)}this.drawWaveform(),this.renderMarkers(),this.initMediaSession(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}async loadTrack(t,i=null,s=null,r={}){this.isPlaying&&this.pause(),this.audio&&(this.audio.src="",this.audio.load()),this.hasError=!1,this.errorEl&&(this.errorEl.style.display="none"),this.canvas&&(this.canvas.style.opacity="1"),this.playBtn&&(this.playBtn.disabled=!1),this.progress=0,this.waveformData=[],this.options=R(this.options,{url:t,title:i||this.options.title,subtitle:s||this.options.subtitle,...r}),r.preload&&this.audio&&(this.audio.preload=r.preload),this.subtitleEl&&(s?(this.subtitleEl.textContent=s,this.subtitleEl.style.display=""):s===""&&(this.subtitleEl.style.display="none")),r.artwork&&this.artworkEl&&(this.artworkEl.src=r.artwork),this.options.markers=r.markers||[],this.options.waveform=r.waveform||null,await this.load(t),r.autoplay!==!1&&this.play()?.catch(()=>{})}setWaveformData(t){if(typeof t=="string"&&t.trim().endsWith(".json")){fetch(t.trim()).then(i=>i.json()).then(i=>{this.waveformData=Array.isArray(i)?i:i.peaks||[],i.markers&&!this.options.markers?.length&&(this.options.markers=i.markers,this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}if(typeof t=="string")try{let i=JSON.parse(t);this.waveformData=Array.isArray(i)?i:[]}catch{this.waveformData=t.split(",").map(Number)}else this.waveformData=Array.isArray(t)?t:[];this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||Y(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,o=document.createElement("button");o.className="waveform-marker",o.style.left=`${r}%`,o.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",o.setAttribute("aria-label",i.label),o.setAttribute("data-time",i.time);let a=document.createElement("span");a.className="waveform-marker-tooltip",a.textContent=i.label,o.appendChild(a),o.addEventListener("click",n=>{n.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(o)})}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,o=-1/0;t.forEach((a,n)=>{let l=parseFloat(a.getAttribute("data-time"));Number.isFinite(l)&&l<=s+.05&&l>o&&(o=l,r=n)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((a,n)=>a.classList.toggle("show-label",n===r)),r>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(a=>a.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.options.showHoverTime||!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.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(),o=g((t-r.left)/r.width);i.textContent=S(o*s),i.style.left=o*100+"%",i.style.opacity="1"}_hideHoverTip(){this.hoverTimeEl&&(this.hoverTimeEl.style.opacity="0")}_scrubTo(t){let i=this.canvas.getBoundingClientRect();i.width&&(this.progress=g((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle(),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){this._seekFromPointer(t.clientX)}_seekFromPointer(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;let s=g((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(s);return}!this.audio||!this.audio.duration||this.seekToPercent(s)}setLoading(t){this.isLoading=t,this.loadingEl&&(this.loadingEl.style.display=t?"block":"none"),this.seekEl&&this.seekEl.setAttribute("aria-busy",t?"true":"false")}onMetadataLoaded(){this.isDestroying||(this.totalTimeEl&&(this.totalTimeEl.textContent=S(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._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._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.onPause(),this.options.onEnd&&this.options.onEnd(this)}onError(t){this.isDestroying||(console.error("[WaveformPlayer] Audio error:",t),this.hasError=!0,this.setLoading(!1),this.errorEl&&(this.errorEl.style.display="flex"),this.canvas&&(this.canvas.style.opacity="0.2"),this.playBtn&&(this.playBtn.disabled=!0),this.options.onError&&this.options.onError(t,this))}startSmoothUpdate(){this.stopSmoothUpdate();let t=()=>{this.isPlaying&&this.audio&&this.audio.duration&&(this.updateProgress(),this.updateTimer=requestAnimationFrame(t))};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=S(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="inline-flex")}refreshTheme(){if(!this._autoTheme||!this._presetKeys||!this._presetKeys.length)return;let t=I(this.options.colorPreset),i=!1;for(let s of this._presetKeys)this.options[s]!==t[s]&&(this.options[s]=t[s],i=!0);i&&this._applyThemeColors()}_applyThemeColors(){let t=this.options;this.playBtn&&(this.playBtn.style.borderColor=t.buttonColor,this.playBtn.style.color=t.buttonColor),this.titleEl&&(this.titleEl.style.color=t.textColor),this.subtitleEl&&(this.subtitleEl.style.color=t.textSecondaryColor),this.container.querySelectorAll(".waveform-time, .waveform-bpm").forEach(i=>{i.style.color=t.textSecondaryColor}),this.canvas&&this.drawWaveform()}static _watchTheme(){if(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(o=>{try{o.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=>{i.classList.toggle("active",parseFloat(i.dataset.rate)===this.audio.playbackRate)})}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(){if(e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.options.audioMode==="external"){this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0);return}this.audio.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,subtitle:this.options.subtitle,artist:this.options.artist||this.options.subtitle,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.progress=g(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=S(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=S(i),this.totalTimeEl.dataset._extSet="1",this.totalTimeEl.dataset._extDur=String(i)),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){this.audio&&this.audio.duration&&(this.audio.currentTime=g(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*g(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=g(i))}setPlaybackRate(t){if(!this.audio)return;let i=g(t,.5,2);this.audio.playbackRate=i,this.options.playbackRate=i,this.updateSpeedUI()}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.pause(),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),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),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",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 B(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}};C.utils={formatTime:S,extractTitleFromUrl:H,escapeHtml:L,isSafeHref:q,parseDataAttributes:x};var $=()=>typeof window<"u"&&typeof document<"u";function z(){if(!$())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(t.dataset.waveformInitialized!=="true")try{new C(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}$()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",z):z());C.init=z;$()&&(window.WaveformPlayer=C);var Dt=C;})();