@arraypress/waveform-player 1.25.0 → 1.26.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.
package/README.md CHANGED
@@ -38,6 +38,24 @@ import WaveformPlayer from '@arraypress/waveform-player';
38
38
  new WaveformPlayer('#player', { url: 'track.mp3', title: 'My Song', artist: 'The Artist' });
39
39
  ```
40
40
 
41
+ ### Initializing only what you control
42
+
43
+ Pages that render markup they don't author — user content, a CMS, an editor canvas — can turn the automatic scan off from the document element:
44
+
45
+ ```html
46
+ <html data-waveform-autoinit="false">
47
+ ```
48
+
49
+ Nothing is initialized until you ask for it. Pass `init()` a root to scan only the subtree you own:
50
+
51
+ ```js
52
+ WaveformPlayer.init( document.querySelector( '#my-app' ) );
53
+ ```
54
+
55
+ Constructing players directly still works too; only the scan on import is suppressed.
56
+
57
+ This scopes initialization — it isn't a sanitizer. `playIcon` / `pauseIcon` (and their `data-play-icon` / `data-pause-icon` equivalents) inject raw markup by design, for any player you do build. Untrusted content still needs sanitizing before it reaches the page.
58
+
41
59
  ## Documentation
42
60
 
43
61
  Every option, style, event and method is documented on the docs site.
@@ -1105,7 +1105,13 @@ var WaveformPlayer = class _WaveformPlayer {
1105
1105
  this.id = this.container.id || generateId(this.options.url);
1106
1106
  _WaveformPlayer.instances.set(this.id, this);
1107
1107
  _WaveformPlayer._watchTheme();
1108
- this.init();
1108
+ try {
1109
+ this.init();
1110
+ } catch (error) {
1111
+ _WaveformPlayer.instances.delete(this.id);
1112
+ this._ac.abort();
1113
+ throw error;
1114
+ }
1109
1115
  setTimeout(() => {
1110
1116
  this._emit("waveformplayer:ready", { player: this, url: this.options.url });
1111
1117
  }, 100);
@@ -1916,11 +1922,13 @@ var WaveformPlayer = class _WaveformPlayer {
1916
1922
  * `loadedmetadata` before proceeding. In external mode there is no audio
1917
1923
  * element, so the src/metadata step is skipped and only the visualization
1918
1924
  * is built (duration/time come from the controller via
1919
- * {@link WaveformPlayer#setProgress}). Peaks come from the `waveform`
1920
- * option when provided — painted *before* the metadata wait, since they
1921
- * need nothing from the audio element — otherwise they are decoded from
1922
- * the audio; a decode failure falls back to a placeholder waveform. The
1923
- * `onLoad` callback fires on success.
1925
+ * {@link WaveformPlayer#setProgress}). The title and the seek slider's
1926
+ * accessible name are written *before* the metadata wait, as are peaks
1927
+ * supplied via the `waveform` option — none of them need anything from the
1928
+ * audio element, and behind the wait they blink in on a slow origin.
1929
+ * Without inline peaks the waveform is decoded from the audio instead; a
1930
+ * decode failure falls back to a placeholder. The `onLoad` callback fires
1931
+ * on success.
1924
1932
  * @param {string} url - Audio URL.
1925
1933
  * @returns {Promise<void>} Resolves once loading settles (errors are caught
1926
1934
  * internally and surfaced through {@link WaveformPlayer#onError}).
@@ -1935,6 +1943,11 @@ var WaveformPlayer = class _WaveformPlayer {
1935
1943
  if (hasInlinePeaks) {
1936
1944
  this.setWaveformData(this.options.waveform);
1937
1945
  }
1946
+ const title = this.options.title || extractTitleFromUrl(url);
1947
+ if (this.titleEl) {
1948
+ this.titleEl.textContent = title;
1949
+ }
1950
+ this.applySeekLabel(title);
1938
1951
  if (this.audio) {
1939
1952
  this.audio.src = url;
1940
1953
  if (this.audio.preload !== "none") {
@@ -1954,11 +1967,6 @@ var WaveformPlayer = class _WaveformPlayer {
1954
1967
  });
1955
1968
  }
1956
1969
  }
1957
- const title = this.options.title || extractTitleFromUrl(url);
1958
- if (this.titleEl) {
1959
- this.titleEl.textContent = title;
1960
- }
1961
- this.applySeekLabel(title);
1962
1970
  if (!hasInlinePeaks) {
1963
1971
  try {
1964
1972
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
@@ -2896,6 +2904,7 @@ var WaveformPlayer = class _WaveformPlayer {
2896
2904
  this.audio = null;
2897
2905
  }
2898
2906
  this.container.innerHTML = "";
2907
+ delete this.container.dataset.waveformInitialized;
2899
2908
  this.canvas = null;
2900
2909
  this.ctx = null;
2901
2910
  this.playBtn = null;
@@ -3004,24 +3013,29 @@ var WaveformPlayer = class _WaveformPlayer {
3004
3013
  // src/js/index.js
3005
3014
  WaveformPlayer.utils = { formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme };
3006
3015
  var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
3007
- function autoInit() {
3016
+ var autoInitDisabled = () => document.documentElement?.dataset.waveformAutoinit === "false";
3017
+ function initElement(element) {
3018
+ if (element.dataset.waveformInitialized === "true" || WaveformPlayer.getInstance(element)) {
3019
+ return;
3020
+ }
3021
+ try {
3022
+ new WaveformPlayer(element);
3023
+ element.dataset.waveformInitialized = "true";
3024
+ } catch (error) {
3025
+ console.error("[WaveformPlayer] Failed to initialize:", error, element);
3026
+ }
3027
+ }
3028
+ function autoInit(root = document) {
3008
3029
  if (!isBrowser()) return;
3009
- const elements = document.querySelectorAll("[data-waveform-player]");
3010
- elements.forEach((element) => {
3011
- if (element.dataset.waveformInitialized === "true" || WaveformPlayer.getInstance(element)) {
3012
- return;
3013
- }
3014
- try {
3015
- new WaveformPlayer(element);
3016
- element.dataset.waveformInitialized = "true";
3017
- } catch (error) {
3018
- console.error("[WaveformPlayer] Failed to initialize:", error, element);
3019
- }
3020
- });
3030
+ const scope = root || document;
3031
+ if (scope.matches?.("[data-waveform-player]")) {
3032
+ initElement(scope);
3033
+ }
3034
+ scope.querySelectorAll("[data-waveform-player]").forEach(initElement);
3021
3035
  }
3022
- if (isBrowser()) {
3036
+ if (isBrowser() && !autoInitDisabled()) {
3023
3037
  if (document.readyState === "loading") {
3024
- document.addEventListener("DOMContentLoaded", autoInit);
3038
+ document.addEventListener("DOMContentLoaded", () => autoInit());
3025
3039
  } else {
3026
3040
  autoInit();
3027
3041
  }
@@ -1,4 +1,4 @@
1
- function $(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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function q(e){return S(typeof e=="number"?`${e}px`:e)}function st(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 n=m(o,s,r);return a?Math.round(n):n}function H(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 D(e,t={}){let{min:i=-1/0,max:s=1/0,fallback:r=null}=t,a=H(e);if(!a&&typeof e=="string"&&e.trim()!==""&&(a=e.split(/[,\s]+/)),!a)return r;let o=a.map(n=>_(n)).filter(n=>n!==null&&n>=i&&n<=s);return o.length?o:r}function rt(e,t,i=null){return t.includes(e)?e:i}function at(e){if(typeof e=="string"){let t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}function kt(e){return e===void 0?void 0:e==="true"}function it(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function O(e){let t={},i=(o,n=o)=>{let l=kt(e.dataset[n]);l!==void 0&&(t[o]=l)},s=(o,n=o,l=!1)=>{let h=e.dataset[n];h&&(t[o]=l?parseFloat(h):parseInt(h,10))},r=(o,n=o)=>{let l=e.dataset[n];l&&(t[o]=/^\d+(\.\d+)?$/.test(l.trim())?parseFloat(l):l)},a=(o,n=o)=>{let l=e.dataset[n];if(!l)return;let h=H(l);h?t[o]=h:console.warn(`[WaveformPlayer] Invalid ${n} attribute, expected a JSON array:`,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.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.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=it(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=it(e.dataset.progressColor)),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.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=D(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 ot(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 vt=0;function nt(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)}_${(vt++).toString(36)}`}function I(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 U(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 lt(e){let t=U(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function j(...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 ht(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),n=Math.ceil(a),l=a-o;if(n>=e.length)i.push(e[e.length-1]);else if(o===n)i.push(e[o]);else{let h=e[o]*(1-l)+e[n]*l;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),n=0,l=0;for(let h=a;h<=o&&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 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,[n,l,h,c]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let d=e.createLinearGradient(n,l,h,c);return t.forEach((b,y)=>d.addColorStop(y/(t.length-1),b)),d}catch{return t[0]}}function x(e,t,i,s,r,a){if((Array.isArray(a)?a.some(n=>n>0):a>0)&&typeof e.roundRect=="function"){let n=Math.min(s/2,Math.abs(r)/2),l=h=>m(h,0,n);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(l):l(a)),e.fill()}else e.fillRect(t,i,s,r)}function pt(e,t){return(e.barRadius||0)*t}function St(e,t){let i=pt(e,t);return[i,i,0,0]}function ct(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 V(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=s*t.width,b=St(r,a),y=P(e,r.color,t,r),w=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=y;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p+o>t.width)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}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+n);if(p>d)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}e.restore()}function Et(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=c/2,b=s*t.width,y=pt(r,a),w=[y,y,0,0],f=[0,0,y,y],p=P(e,r.color,t,r),g=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 k=u*(o+n);if(k+o>t.width)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.save(),e.beginPath(),e.rect(0,0,b,c),e.clip(),e.fillStyle=g;for(let u=0;u<h.length;u++){let k=u*(o+n);if(k>b)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.restore()}function Pt(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=o*.35;e.clearRect(0,0,a,o);let h=(c,d,b=1,y=!1)=>{let w=P(e,c,t,r),f=Array.isArray(c)?c[c.length-1]:c;y&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=w,e.lineWidth=d,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],g=Math.floor(i.length*b);for(let u=0;u<g;u++){let k=u/(i.length-1)*a,v=i[u],A=Math.sin(u*.1)*v,L=n+A*l;p.push({x:k,y:L})}for(let u=0;u<p.length-1;u++){let k=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(k,v,A,L,p[u+1].x,p[u+1].y)}e.stroke(),y&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(a,n),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 ut(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,n=(r.barSpacing||1)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=4*a,b=2*a,y=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 g=0;g<h.length;g++){let u=g*(o+n);if(u+o>t.width)break;let k=h[g]*c*.9,v=Math.floor(k/(d+b));e.fillStyle=u<y?p:f;for(let A=0;A<v;A++){let L=A*(d+b);e.fillRect(u,w-L-d,o,d),A>0&&e.fillRect(u,w+L,o,d)}}}function dt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,n=(r.barSpacing||3)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=Math.max(1.5*a,o/2),b=s*t.width,y=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 g=p*(o+n)+o/2;if(g>t.width)break;let u=h[p]*c*.9;e.fillStyle=g<b?f:w,e.beginPath(),e.arc(g,y-u/2,d,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(g,y+u/2,d,0,Math.PI*2),e.fill()}}function Tt(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=4,h=l/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)",ct(e,h,a,n,l),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)",ct(e,h,d,n,l),e.fill(),e.restore()}}var At={bars:V,bar:V,mirror:Et,line:Pt,blocks:ut,block:ut,dots:dt,dot:dt,seekbar:Tt};function ft(e,t,i,s,r){(At[r.waveformStyle]||V)(e,t,i,s,r)}function mt(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=Mt(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 a={};r.forEach(l=>{let h=60/l,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,n=120;for(let[l,h]of Object.entries(a))h>o&&(o=h,n=parseInt(l));return n<70&&a[n*2]?n*=2:n>160&&a[Math.round(n/2)]&&(n=Math.round(n/2)),n-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function Mt(e,t){let r=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let n=0;for(let c=o;c<o+2048;c++)n+=e[c]*e[c];n=n/2048;let l=n-a,h=a*1.8+.01;if(l>h&&n>.01){let c=r[r.length-1]||0,d=t*.15;o-c>d&&r.push(o)}a=n*.8+a*.2}return r}function Ct(e,t=1800){let i=e.length/t,s=e.numberOfChannels,r=[];for(let o=0;o<s;o++){let n=e.getChannelData(o);for(let l=0;l<t;l++){let h=~~(l*i),c=~~(h+i),d=0,b=0;for(let w=h;w<c;w++){let f=n[w];f>b&&(b=f),f<d&&(d=f)}let y=Math.max(Math.abs(b),Math.abs(d));(o===0||y>r[l])&&(r[l]=y)}}let a=$(r);return a>0?r.map(o=>o/a):r}async function G(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),n=await s.decodeAudioData(o),l=Ct(n,t);l=Lt(l);let h=null;return i&&(h=mt(n)),{peaks:l,bpm:h}}finally{s&&s.close()}}function yt(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 Lt(e,t=.95){let i=$(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}var K=128;function gt(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 _t(e){let t=0,i=0;for(let s=e;s&&s.nodeType===1&&i<.995;s=s.parentElement){let r=U(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 xt(){let e=lt(getComputedStyle(document.body).color);if(e!==null)return e>K?"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 R(e){if(gt("dark"))return"dark";if(gt("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:s}=_t(t),r=xt(),a=i+(r==="dark"?0:255)*(1-s);return a>K?"light":a<K?"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 J(e,t){if(e&&C[e])return C[e];let i=R(t);return C[i]}var W={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},X={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}},Q=["auto","top","center","bottom"],N=.25,F=4,Rt={buttonAlign:Q,layout:["default","preview"],buttonStyle:["circle","minimal"],artworkPosition:["info","button"],waveformStyle:Object.keys(X),waveformGradient:["vertical","horizontal","diagonal"],audioMode:["self","external"],preload:["none","metadata","auto"],colorPreset:Object.keys(C),crossOrigin:["anonymous","use-credentials"]},Dt={height:{min:1,integer:!0},samples:{min:1,integer:!0},barWidth:{min:0},barSpacing:{min:0},barRadius:{min:0},bpm:{min:1},playbackRate:{min:N,max:F}},Bt=["autoplay","showControls","showInfo","showTime","showHoverTime","seekHandle","showBPM","singlePlay","playOnSeek","enableMediaSession","showMarkers","accessibleSeek","showPlaybackSpeed"],Ht=["onLoad","onPlay","onPause","onEnd","onError","onTimeUpdate","onNextTrack","onPreviousTrack"];function Y(e,t){console.warn(`[WaveformPlayer] Invalid ${e} option, using default:`,t)}function z(e){let t=H(e);return t?t.reduce((i,s)=>{let r=s&&typeof s=="object"?_(s.time,null,{min:0}):null;return r===null?(Y("marker",s),i):(i.push({...s,time:r,label:s.label==null?"":s.label}),i)},[]):(e!=null&&Y("markers",e),[])}function Z(e){let t=s=>e[s]!=null,i=s=>{Y(s,e[s]),e[s]=W[s]};for(let[s,r]of Object.entries(Dt)){if(!t(s))continue;let a=_(e[s],null,r);a===null?i(s):e[s]=a}for(let[s,r]of Object.entries(Rt))t(s)&&rt(e[s],r)===null&&i(s);for(let s of Bt)e[s]=at(e[s]);for(let s of Ht)t(s)&&typeof e[s]!="function"&&i(s);if(t("playbackRates")){let s=D(e.playbackRates,{min:N,max:F,fallback:null});s===null?i("playbackRates"):e.playbackRates=s}e.markers=z(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 Ot="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,wt=10,It='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=O(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=Z(j(W,s,r));let a=J(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:R(this.container);for(let[n,l]of Object.entries(a))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let o=X[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._ac=new AbortController,this.id=this.container.id||nt(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=Q.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: ${q(this.options.buttonSize)}`),this.options.buttonRadius!=null&&s.push(`--wfp-btn-radius: ${q(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">`:"",n=this.options.showControls?`
1
+ function $(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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function q(e){return S(typeof e=="number"?`${e}px`:e)}function st(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 n=m(o,s,r);return a?Math.round(n):n}function H(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 D(e,t={}){let{min:i=-1/0,max:s=1/0,fallback:r=null}=t,a=H(e);if(!a&&typeof e=="string"&&e.trim()!==""&&(a=e.split(/[,\s]+/)),!a)return r;let o=a.map(n=>_(n)).filter(n=>n!==null&&n>=i&&n<=s);return o.length?o:r}function rt(e,t,i=null){return t.includes(e)?e:i}function at(e){if(typeof e=="string"){let t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}function vt(e){return e===void 0?void 0:e==="true"}function it(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function I(e){let t={},i=(o,n=o)=>{let l=vt(e.dataset[n]);l!==void 0&&(t[o]=l)},s=(o,n=o,l=!1)=>{let h=e.dataset[n];h&&(t[o]=l?parseFloat(h):parseInt(h,10))},r=(o,n=o)=>{let l=e.dataset[n];l&&(t[o]=/^\d+(\.\d+)?$/.test(l.trim())?parseFloat(l):l)},a=(o,n=o)=>{let l=e.dataset[n];if(!l)return;let h=H(l);h?t[o]=h:console.warn(`[WaveformPlayer] Invalid ${n} attribute, expected a JSON array:`,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.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.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=it(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=it(e.dataset.progressColor)),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.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=D(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 ot(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 St=0;function nt(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 O(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 U(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 lt(e){let t=U(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function j(...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 ht(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),n=Math.ceil(a),l=a-o;if(n>=e.length)i.push(e[e.length-1]);else if(o===n)i.push(e[o]);else{let h=e[o]*(1-l)+e[n]*l;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),n=0,l=0;for(let h=a;h<=o&&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 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,[n,l,h,c]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let d=e.createLinearGradient(n,l,h,c);return t.forEach((b,y)=>d.addColorStop(y/(t.length-1),b)),d}catch{return t[0]}}function x(e,t,i,s,r,a){if((Array.isArray(a)?a.some(n=>n>0):a>0)&&typeof e.roundRect=="function"){let n=Math.min(s/2,Math.abs(r)/2),l=h=>m(h,0,n);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(l):l(a)),e.fill()}else e.fillRect(t,i,s,r)}function pt(e,t){return(e.barRadius||0)*t}function Et(e,t){let i=pt(e,t);return[i,i,0,0]}function ct(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 V(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=s*t.width,b=Et(r,a),y=P(e,r.color,t,r),w=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=y;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p+o>t.width)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}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+n);if(p>d)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}e.restore()}function Pt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=c/2,b=s*t.width,y=pt(r,a),w=[y,y,0,0],f=[0,0,y,y],p=P(e,r.color,t,r),g=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 k=u*(o+n);if(k+o>t.width)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.save(),e.beginPath(),e.rect(0,0,b,c),e.clip(),e.fillStyle=g;for(let u=0;u<h.length;u++){let k=u*(o+n);if(k>b)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.restore()}function Tt(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=o*.35;e.clearRect(0,0,a,o);let h=(c,d,b=1,y=!1)=>{let w=P(e,c,t,r),f=Array.isArray(c)?c[c.length-1]:c;y&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=w,e.lineWidth=d,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],g=Math.floor(i.length*b);for(let u=0;u<g;u++){let k=u/(i.length-1)*a,v=i[u],A=Math.sin(u*.1)*v,L=n+A*l;p.push({x:k,y:L})}for(let u=0;u<p.length-1;u++){let k=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(k,v,A,L,p[u+1].x,p[u+1].y)}e.stroke(),y&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(a,n),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 ut(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,n=(r.barSpacing||1)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=4*a,b=2*a,y=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 g=0;g<h.length;g++){let u=g*(o+n);if(u+o>t.width)break;let k=h[g]*c*.9,v=Math.floor(k/(d+b));e.fillStyle=u<y?p:f;for(let A=0;A<v;A++){let L=A*(d+b);e.fillRect(u,w-L-d,o,d),A>0&&e.fillRect(u,w+L,o,d)}}}function dt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,n=(r.barSpacing||3)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=Math.max(1.5*a,o/2),b=s*t.width,y=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 g=p*(o+n)+o/2;if(g>t.width)break;let u=h[p]*c*.9;e.fillStyle=g<b?f:w,e.beginPath(),e.arc(g,y-u/2,d,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(g,y+u/2,d,0,Math.PI*2),e.fill()}}function At(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=4,h=l/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)",ct(e,h,a,n,l),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)",ct(e,h,d,n,l),e.fill(),e.restore()}}var Mt={bars:V,bar:V,mirror:Pt,line:Tt,blocks:ut,block:ut,dots:dt,dot:dt,seekbar:At};function ft(e,t,i,s,r){(Mt[r.waveformStyle]||V)(e,t,i,s,r)}function mt(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 a={};r.forEach(l=>{let h=60/l,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,n=120;for(let[l,h]of Object.entries(a))h>o&&(o=h,n=parseInt(l));return n<70&&a[n*2]?n*=2:n>160&&a[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=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let n=0;for(let c=o;c<o+2048;c++)n+=e[c]*e[c];n=n/2048;let l=n-a,h=a*1.8+.01;if(l>h&&n>.01){let c=r[r.length-1]||0,d=t*.15;o-c>d&&r.push(o)}a=n*.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 n=e.getChannelData(o);for(let l=0;l<t;l++){let h=~~(l*i),c=~~(h+i),d=0,b=0;for(let w=h;w<c;w++){let f=n[w];f>b&&(b=f),f<d&&(d=f)}let y=Math.max(Math.abs(b),Math.abs(d));(o===0||y>r[l])&&(r[l]=y)}}let a=$(r);return a>0?r.map(o=>o/a):r}async function G(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),n=await s.decodeAudioData(o),l=Lt(n,t);l=_t(l);let h=null;return i&&(h=mt(n)),{peaks:l,bpm:h}}finally{s&&s.close()}}function yt(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 _t(e,t=.95){let i=$(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}var K=128;function gt(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 xt(e){let t=0,i=0;for(let s=e;s&&s.nodeType===1&&i<.995;s=s.parentElement){let r=U(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 Rt(){let e=lt(getComputedStyle(document.body).color);if(e!==null)return e>K?"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 R(e){if(gt("dark"))return"dark";if(gt("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:s}=xt(t),r=Rt(),a=i+(r==="dark"?0:255)*(1-s);return a>K?"light":a<K?"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 J(e,t){if(e&&C[e])return C[e];let i=R(t);return C[i]}var W={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},X={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}},Q=["auto","top","center","bottom"],N=.25,F=4,Dt={buttonAlign:Q,layout:["default","preview"],buttonStyle:["circle","minimal"],artworkPosition:["info","button"],waveformStyle:Object.keys(X),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:0},barSpacing:{min:0},barRadius:{min:0},bpm:{min:1},playbackRate:{min:N,max:F}},Ht=["autoplay","showControls","showInfo","showTime","showHoverTime","seekHandle","showBPM","singlePlay","playOnSeek","enableMediaSession","showMarkers","accessibleSeek","showPlaybackSpeed"],It=["onLoad","onPlay","onPause","onEnd","onError","onTimeUpdate","onNextTrack","onPreviousTrack"];function Y(e,t){console.warn(`[WaveformPlayer] Invalid ${e} option, using default:`,t)}function z(e){let t=H(e);return t?t.reduce((i,s)=>{let r=s&&typeof s=="object"?_(s.time,null,{min:0}):null;return r===null?(Y("marker",s),i):(i.push({...s,time:r,label:s.label==null?"":s.label}),i)},[]):(e!=null&&Y("markers",e),[])}function Z(e){let t=s=>e[s]!=null,i=s=>{Y(s,e[s]),e[s]=W[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(Dt))t(s)&&rt(e[s],r)===null&&i(s);for(let s of Ht)e[s]=at(e[s]);for(let s of It)t(s)&&typeof e[s]!="function"&&i(s);if(t("playbackRates")){let s=D(e.playbackRates,{min:N,max:F,fallback:null});s===null?i("playbackRates"):e.playbackRates=s}e.markers=z(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 Ot="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,wt=10,Wt='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=I(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=Z(j(W,s,r));let a=J(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:R(this.container);for(let[n,l]of Object.entries(a))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let o=X[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._ac=new AbortController,this.id=this.container.id||nt(this.options.url),e.instances.set(this.id,this),e._watchTheme();try{this.init()}catch(n){throw e.instances.delete(this.id),this._ac.abort(),n}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=Q.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: ${q(this.options.buttonSize)}`),this.options.buttonRadius!=null&&s.push(`--wfp-btn-radius: ${q(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">`:"",n=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 $(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}fu
61
61
  ${l}
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=Ot)},{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.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=l=>{if(i.style.display=l?"block":"none",t.setAttribute("aria-expanded",l?"true":"false"),l){let h=s();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=l=>{let h=s();h.length&&h[(l+h.length)%h.length].focus()},n=l=>{this.setPlaybackRate(parseFloat(l.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",l=>{l.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",l=>{l.stopPropagation();let h=l.target.closest(".speed-option");h&&n(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",l=>{let h=s(),c=h.indexOf(document.activeElement);if(!r()){(l.key==="ArrowDown"||l.key==="ArrowUp")&&document.activeElement===t&&(l.preventDefault(),a(!0));return}switch(l.key){case"ArrowDown":l.preventDefault(),o(c<0?0:c+1);break;case"ArrowUp":l.preventDefault(),o(c<0?h.length-1:c-1);break;case"Home":l.preventDefault(),o(0);break;case"End":l.preventDefault(),o(h.length-1);break;case"Escape":l.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(It)||(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-wt;break;case"PageUp":r=s+wt;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",ot(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;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;let i=this.audio.duration;navigator.mediaSession.setPositionState&&i&&isFinite(i)&&navigator.mediaSession.setPositionState({duration:i,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,i)})}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.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=ht(()=>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.container.classList.remove("waveform-is-placeholder");let i=!!this.options.waveform;i&&this.setWaveformData(this.options.waveform),this.audio&&(this.audio.src=t,this.audio.preload!=="none"&&await new Promise((r,a)=>{let o=()=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),r()},n=l=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),a(l)};this.audio.addEventListener("loadedmetadata",o),this.audio.addEventListener("error",n)}));let s=this.options.title||I(t);if(this.titleEl&&(this.titleEl.textContent=s),this.applySeekLabel(s),!i)try{let r=await G(t,this.options.samples,this.options.showBPM);this.waveformData=r.peaks,r.bpm&&(this.detectedBPM=r.bpm,this.updateBPMDisplay())}catch(r){console.warn("[WaveformPlayer] Using placeholder waveform:",r),this.waveformData=yt(this.options.samples),this.container.classList.add("waveform-is-placeholder")}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}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.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=Z(j(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?W.artworkAlt:""),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?z(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=z(i.markers),this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}this.waveformData=D(t,{fallback:[]}),this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||ft(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",n=>{n.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,n)=>{let l=parseFloat(o.getAttribute("data-time"));Number.isFinite(l)&&l<=s+.05&&l>a&&(a=l,r=n)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,n)=>o.classList.toggle("show-label",n===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.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=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="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=R(this.container);let t=J(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(){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,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.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=E(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=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),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:N,max:F});i!==null&&(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 G(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:I,escapeHtml:S,isSafeHref:st,parseDataAttributes:O,detectColorScheme:R};var et=()=>typeof window<"u"&&typeof document<"u";function tt(){if(!et())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(!(t.dataset.waveformInitialized==="true"||T.getInstance(t)))try{new T(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}et()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",tt):tt());T.init=tt;et()&&(window.WaveformPlayer=T);var ee=T;export{T as WaveformPlayer,ee 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=Ot)},{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.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=l=>{if(i.style.display=l?"block":"none",t.setAttribute("aria-expanded",l?"true":"false"),l){let h=s();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=l=>{let h=s();h.length&&h[(l+h.length)%h.length].focus()},n=l=>{this.setPlaybackRate(parseFloat(l.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",l=>{l.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",l=>{l.stopPropagation();let h=l.target.closest(".speed-option");h&&n(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",l=>{let h=s(),c=h.indexOf(document.activeElement);if(!r()){(l.key==="ArrowDown"||l.key==="ArrowUp")&&document.activeElement===t&&(l.preventDefault(),a(!0));return}switch(l.key){case"ArrowDown":l.preventDefault(),o(c<0?0:c+1);break;case"ArrowUp":l.preventDefault(),o(c<0?h.length-1:c-1);break;case"Home":l.preventDefault(),o(0);break;case"End":l.preventDefault(),o(h.length-1);break;case"Escape":l.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(Wt)||(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-wt;break;case"PageUp":r=s+wt;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",ot(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;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;let i=this.audio.duration;navigator.mediaSession.setPositionState&&i&&isFinite(i)&&navigator.mediaSession.setPositionState({duration:i,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,i)})}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.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=ht(()=>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.container.classList.remove("waveform-is-placeholder");let i=!!this.options.waveform;i&&this.setWaveformData(this.options.waveform);let s=this.options.title||O(t);if(this.titleEl&&(this.titleEl.textContent=s),this.applySeekLabel(s),this.audio&&(this.audio.src=t,this.audio.preload!=="none"&&await new Promise((r,a)=>{let o=()=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),r()},n=l=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),a(l)};this.audio.addEventListener("loadedmetadata",o),this.audio.addEventListener("error",n)})),!i)try{let r=await G(t,this.options.samples,this.options.showBPM);this.waveformData=r.peaks,r.bpm&&(this.detectedBPM=r.bpm,this.updateBPMDisplay())}catch(r){console.warn("[WaveformPlayer] Using placeholder waveform:",r),this.waveformData=yt(this.options.samples),this.container.classList.add("waveform-is-placeholder")}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}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.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=Z(j(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?W.artworkAlt:""),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?z(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=z(i.markers),this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}this.waveformData=D(t,{fallback:[]}),this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||ft(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",n=>{n.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,n)=>{let l=parseFloat(o.getAttribute("data-time"));Number.isFinite(l)&&l<=s+.05&&l>a&&(a=l,r=n)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,n)=>o.classList.toggle("show-label",n===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.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=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="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=R(this.container);let t=J(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(){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,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.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=E(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=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),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:N,max:F});i!==null&&(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="",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 G(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:O,escapeHtml:S,isSafeHref:st,parseDataAttributes:I,detectColorScheme:R};var et=()=>typeof window<"u"&&typeof document<"u",Nt=()=>document.documentElement?.dataset.waveformAutoinit==="false";function kt(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 tt(e=document){if(!et())return;let t=e||document;t.matches?.("[data-waveform-player]")&&kt(t),t.querySelectorAll("[data-waveform-player]").forEach(kt)}et()&&!Nt()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>tt()):tt());T.init=tt;et()&&(window.WaveformPlayer=T);var se=T;export{T as WaveformPlayer,se as default};
@@ -1080,7 +1080,13 @@
1080
1080
  this.id = this.container.id || generateId(this.options.url);
1081
1081
  _WaveformPlayer.instances.set(this.id, this);
1082
1082
  _WaveformPlayer._watchTheme();
1083
- this.init();
1083
+ try {
1084
+ this.init();
1085
+ } catch (error) {
1086
+ _WaveformPlayer.instances.delete(this.id);
1087
+ this._ac.abort();
1088
+ throw error;
1089
+ }
1084
1090
  setTimeout(() => {
1085
1091
  this._emit("waveformplayer:ready", { player: this, url: this.options.url });
1086
1092
  }, 100);
@@ -1891,11 +1897,13 @@
1891
1897
  * `loadedmetadata` before proceeding. In external mode there is no audio
1892
1898
  * element, so the src/metadata step is skipped and only the visualization
1893
1899
  * is built (duration/time come from the controller via
1894
- * {@link WaveformPlayer#setProgress}). Peaks come from the `waveform`
1895
- * option when provided — painted *before* the metadata wait, since they
1896
- * need nothing from the audio element — otherwise they are decoded from
1897
- * the audio; a decode failure falls back to a placeholder waveform. The
1898
- * `onLoad` callback fires on success.
1900
+ * {@link WaveformPlayer#setProgress}). The title and the seek slider's
1901
+ * accessible name are written *before* the metadata wait, as are peaks
1902
+ * supplied via the `waveform` option — none of them need anything from the
1903
+ * audio element, and behind the wait they blink in on a slow origin.
1904
+ * Without inline peaks the waveform is decoded from the audio instead; a
1905
+ * decode failure falls back to a placeholder. The `onLoad` callback fires
1906
+ * on success.
1899
1907
  * @param {string} url - Audio URL.
1900
1908
  * @returns {Promise<void>} Resolves once loading settles (errors are caught
1901
1909
  * internally and surfaced through {@link WaveformPlayer#onError}).
@@ -1910,6 +1918,11 @@
1910
1918
  if (hasInlinePeaks) {
1911
1919
  this.setWaveformData(this.options.waveform);
1912
1920
  }
1921
+ const title = this.options.title || extractTitleFromUrl(url);
1922
+ if (this.titleEl) {
1923
+ this.titleEl.textContent = title;
1924
+ }
1925
+ this.applySeekLabel(title);
1913
1926
  if (this.audio) {
1914
1927
  this.audio.src = url;
1915
1928
  if (this.audio.preload !== "none") {
@@ -1929,11 +1942,6 @@
1929
1942
  });
1930
1943
  }
1931
1944
  }
1932
- const title = this.options.title || extractTitleFromUrl(url);
1933
- if (this.titleEl) {
1934
- this.titleEl.textContent = title;
1935
- }
1936
- this.applySeekLabel(title);
1937
1945
  if (!hasInlinePeaks) {
1938
1946
  try {
1939
1947
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
@@ -2871,6 +2879,7 @@
2871
2879
  this.audio = null;
2872
2880
  }
2873
2881
  this.container.innerHTML = "";
2882
+ delete this.container.dataset.waveformInitialized;
2874
2883
  this.canvas = null;
2875
2884
  this.ctx = null;
2876
2885
  this.playBtn = null;
@@ -2979,24 +2988,29 @@
2979
2988
  // src/js/index.js
2980
2989
  WaveformPlayer.utils = { formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme };
2981
2990
  var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
2982
- function autoInit() {
2991
+ var autoInitDisabled = () => document.documentElement?.dataset.waveformAutoinit === "false";
2992
+ function initElement(element) {
2993
+ if (element.dataset.waveformInitialized === "true" || WaveformPlayer.getInstance(element)) {
2994
+ return;
2995
+ }
2996
+ try {
2997
+ new WaveformPlayer(element);
2998
+ element.dataset.waveformInitialized = "true";
2999
+ } catch (error) {
3000
+ console.error("[WaveformPlayer] Failed to initialize:", error, element);
3001
+ }
3002
+ }
3003
+ function autoInit(root = document) {
2983
3004
  if (!isBrowser()) return;
2984
- const elements = document.querySelectorAll("[data-waveform-player]");
2985
- elements.forEach((element) => {
2986
- if (element.dataset.waveformInitialized === "true" || WaveformPlayer.getInstance(element)) {
2987
- return;
2988
- }
2989
- try {
2990
- new WaveformPlayer(element);
2991
- element.dataset.waveformInitialized = "true";
2992
- } catch (error) {
2993
- console.error("[WaveformPlayer] Failed to initialize:", error, element);
2994
- }
2995
- });
3005
+ const scope = root || document;
3006
+ if (scope.matches?.("[data-waveform-player]")) {
3007
+ initElement(scope);
3008
+ }
3009
+ scope.querySelectorAll("[data-waveform-player]").forEach(initElement);
2996
3010
  }
2997
- if (isBrowser()) {
3011
+ if (isBrowser() && !autoInitDisabled()) {
2998
3012
  if (document.readyState === "loading") {
2999
- document.addEventListener("DOMContentLoaded", autoInit);
3013
+ document.addEventListener("DOMContentLoaded", () => autoInit());
3000
3014
  } else {
3001
3015
  autoInit();
3002
3016
  }
@@ -1,4 +1,4 @@
1
- (()=>{function $(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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function q(e){return S(typeof e=="number"?`${e}px`:e)}function st(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 n=m(o,s,r);return a?Math.round(n):n}function H(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 D(e,t={}){let{min:i=-1/0,max:s=1/0,fallback:r=null}=t,a=H(e);if(!a&&typeof e=="string"&&e.trim()!==""&&(a=e.split(/[,\s]+/)),!a)return r;let o=a.map(n=>_(n)).filter(n=>n!==null&&n>=i&&n<=s);return o.length?o:r}function rt(e,t,i=null){return t.includes(e)?e:i}function at(e){if(typeof e=="string"){let t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}function kt(e){return e===void 0?void 0:e==="true"}function it(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function O(e){let t={},i=(o,n=o)=>{let l=kt(e.dataset[n]);l!==void 0&&(t[o]=l)},s=(o,n=o,l=!1)=>{let h=e.dataset[n];h&&(t[o]=l?parseFloat(h):parseInt(h,10))},r=(o,n=o)=>{let l=e.dataset[n];l&&(t[o]=/^\d+(\.\d+)?$/.test(l.trim())?parseFloat(l):l)},a=(o,n=o)=>{let l=e.dataset[n];if(!l)return;let h=H(l);h?t[o]=h:console.warn(`[WaveformPlayer] Invalid ${n} attribute, expected a JSON array:`,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.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.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=it(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=it(e.dataset.progressColor)),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.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=D(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 ot(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 vt=0;function nt(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)}_${(vt++).toString(36)}`}function I(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 U(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 lt(e){let t=U(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function j(...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 ht(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),n=Math.ceil(a),l=a-o;if(n>=e.length)i.push(e[e.length-1]);else if(o===n)i.push(e[o]);else{let h=e[o]*(1-l)+e[n]*l;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),n=0,l=0;for(let h=a;h<=o&&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 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,[n,l,h,c]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let d=e.createLinearGradient(n,l,h,c);return t.forEach((b,y)=>d.addColorStop(y/(t.length-1),b)),d}catch{return t[0]}}function x(e,t,i,s,r,a){if((Array.isArray(a)?a.some(n=>n>0):a>0)&&typeof e.roundRect=="function"){let n=Math.min(s/2,Math.abs(r)/2),l=h=>m(h,0,n);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(l):l(a)),e.fill()}else e.fillRect(t,i,s,r)}function pt(e,t){return(e.barRadius||0)*t}function St(e,t){let i=pt(e,t);return[i,i,0,0]}function ct(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 V(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=s*t.width,b=St(r,a),y=P(e,r.color,t,r),w=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=y;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p+o>t.width)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}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+n);if(p>d)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}e.restore()}function Et(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=c/2,b=s*t.width,y=pt(r,a),w=[y,y,0,0],f=[0,0,y,y],p=P(e,r.color,t,r),g=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 k=u*(o+n);if(k+o>t.width)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.save(),e.beginPath(),e.rect(0,0,b,c),e.clip(),e.fillStyle=g;for(let u=0;u<h.length;u++){let k=u*(o+n);if(k>b)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.restore()}function Pt(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=o*.35;e.clearRect(0,0,a,o);let h=(c,d,b=1,y=!1)=>{let w=P(e,c,t,r),f=Array.isArray(c)?c[c.length-1]:c;y&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=w,e.lineWidth=d,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],g=Math.floor(i.length*b);for(let u=0;u<g;u++){let k=u/(i.length-1)*a,v=i[u],A=Math.sin(u*.1)*v,L=n+A*l;p.push({x:k,y:L})}for(let u=0;u<p.length-1;u++){let k=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(k,v,A,L,p[u+1].x,p[u+1].y)}e.stroke(),y&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(a,n),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 ut(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,n=(r.barSpacing||1)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=4*a,b=2*a,y=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 g=0;g<h.length;g++){let u=g*(o+n);if(u+o>t.width)break;let k=h[g]*c*.9,v=Math.floor(k/(d+b));e.fillStyle=u<y?p:f;for(let A=0;A<v;A++){let L=A*(d+b);e.fillRect(u,w-L-d,o,d),A>0&&e.fillRect(u,w+L,o,d)}}}function dt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,n=(r.barSpacing||3)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=Math.max(1.5*a,o/2),b=s*t.width,y=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 g=p*(o+n)+o/2;if(g>t.width)break;let u=h[p]*c*.9;e.fillStyle=g<b?f:w,e.beginPath(),e.arc(g,y-u/2,d,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(g,y+u/2,d,0,Math.PI*2),e.fill()}}function Tt(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=4,h=l/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)",ct(e,h,a,n,l),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)",ct(e,h,d,n,l),e.fill(),e.restore()}}var At={bars:V,bar:V,mirror:Et,line:Pt,blocks:ut,block:ut,dots:dt,dot:dt,seekbar:Tt};function ft(e,t,i,s,r){(At[r.waveformStyle]||V)(e,t,i,s,r)}function mt(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=Mt(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 a={};r.forEach(l=>{let h=60/l,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,n=120;for(let[l,h]of Object.entries(a))h>o&&(o=h,n=parseInt(l));return n<70&&a[n*2]?n*=2:n>160&&a[Math.round(n/2)]&&(n=Math.round(n/2)),n-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function Mt(e,t){let r=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let n=0;for(let c=o;c<o+2048;c++)n+=e[c]*e[c];n=n/2048;let l=n-a,h=a*1.8+.01;if(l>h&&n>.01){let c=r[r.length-1]||0,d=t*.15;o-c>d&&r.push(o)}a=n*.8+a*.2}return r}function Ct(e,t=1800){let i=e.length/t,s=e.numberOfChannels,r=[];for(let o=0;o<s;o++){let n=e.getChannelData(o);for(let l=0;l<t;l++){let h=~~(l*i),c=~~(h+i),d=0,b=0;for(let w=h;w<c;w++){let f=n[w];f>b&&(b=f),f<d&&(d=f)}let y=Math.max(Math.abs(b),Math.abs(d));(o===0||y>r[l])&&(r[l]=y)}}let a=$(r);return a>0?r.map(o=>o/a):r}async function G(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),n=await s.decodeAudioData(o),l=Ct(n,t);l=Lt(l);let h=null;return i&&(h=mt(n)),{peaks:l,bpm:h}}finally{s&&s.close()}}function yt(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 Lt(e,t=.95){let i=$(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}var K=128;function gt(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 _t(e){let t=0,i=0;for(let s=e;s&&s.nodeType===1&&i<.995;s=s.parentElement){let r=U(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 xt(){let e=lt(getComputedStyle(document.body).color);if(e!==null)return e>K?"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 R(e){if(gt("dark"))return"dark";if(gt("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:s}=_t(t),r=xt(),a=i+(r==="dark"?0:255)*(1-s);return a>K?"light":a<K?"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 J(e,t){if(e&&C[e])return C[e];let i=R(t);return C[i]}var W={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},X={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}},Q=["auto","top","center","bottom"],N=.25,F=4,Rt={buttonAlign:Q,layout:["default","preview"],buttonStyle:["circle","minimal"],artworkPosition:["info","button"],waveformStyle:Object.keys(X),waveformGradient:["vertical","horizontal","diagonal"],audioMode:["self","external"],preload:["none","metadata","auto"],colorPreset:Object.keys(C),crossOrigin:["anonymous","use-credentials"]},Dt={height:{min:1,integer:!0},samples:{min:1,integer:!0},barWidth:{min:0},barSpacing:{min:0},barRadius:{min:0},bpm:{min:1},playbackRate:{min:N,max:F}},Bt=["autoplay","showControls","showInfo","showTime","showHoverTime","seekHandle","showBPM","singlePlay","playOnSeek","enableMediaSession","showMarkers","accessibleSeek","showPlaybackSpeed"],Ht=["onLoad","onPlay","onPause","onEnd","onError","onTimeUpdate","onNextTrack","onPreviousTrack"];function Y(e,t){console.warn(`[WaveformPlayer] Invalid ${e} option, using default:`,t)}function z(e){let t=H(e);return t?t.reduce((i,s)=>{let r=s&&typeof s=="object"?_(s.time,null,{min:0}):null;return r===null?(Y("marker",s),i):(i.push({...s,time:r,label:s.label==null?"":s.label}),i)},[]):(e!=null&&Y("markers",e),[])}function Z(e){let t=s=>e[s]!=null,i=s=>{Y(s,e[s]),e[s]=W[s]};for(let[s,r]of Object.entries(Dt)){if(!t(s))continue;let a=_(e[s],null,r);a===null?i(s):e[s]=a}for(let[s,r]of Object.entries(Rt))t(s)&&rt(e[s],r)===null&&i(s);for(let s of Bt)e[s]=at(e[s]);for(let s of Ht)t(s)&&typeof e[s]!="function"&&i(s);if(t("playbackRates")){let s=D(e.playbackRates,{min:N,max:F,fallback:null});s===null?i("playbackRates"):e.playbackRates=s}e.markers=z(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 Ot="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,wt=10,It='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=O(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=Z(j(W,s,r));let a=J(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:R(this.container);for(let[n,l]of Object.entries(a))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let o=X[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._ac=new AbortController,this.id=this.container.id||nt(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=Q.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: ${q(this.options.buttonSize)}`),this.options.buttonRadius!=null&&s.push(`--wfp-btn-radius: ${q(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">`:"",n=this.options.showControls?`
1
+ (()=>{function $(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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function q(e){return S(typeof e=="number"?`${e}px`:e)}function st(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 n=m(o,s,r);return a?Math.round(n):n}function H(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 D(e,t={}){let{min:i=-1/0,max:s=1/0,fallback:r=null}=t,a=H(e);if(!a&&typeof e=="string"&&e.trim()!==""&&(a=e.split(/[,\s]+/)),!a)return r;let o=a.map(n=>_(n)).filter(n=>n!==null&&n>=i&&n<=s);return o.length?o:r}function rt(e,t,i=null){return t.includes(e)?e:i}function at(e){if(typeof e=="string"){let t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}function vt(e){return e===void 0?void 0:e==="true"}function it(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function I(e){let t={},i=(o,n=o)=>{let l=vt(e.dataset[n]);l!==void 0&&(t[o]=l)},s=(o,n=o,l=!1)=>{let h=e.dataset[n];h&&(t[o]=l?parseFloat(h):parseInt(h,10))},r=(o,n=o)=>{let l=e.dataset[n];l&&(t[o]=/^\d+(\.\d+)?$/.test(l.trim())?parseFloat(l):l)},a=(o,n=o)=>{let l=e.dataset[n];if(!l)return;let h=H(l);h?t[o]=h:console.warn(`[WaveformPlayer] Invalid ${n} attribute, expected a JSON array:`,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.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.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=it(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=it(e.dataset.progressColor)),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.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=D(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 ot(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 St=0;function nt(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 O(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 U(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 lt(e){let t=U(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function j(...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 ht(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),n=Math.ceil(a),l=a-o;if(n>=e.length)i.push(e[e.length-1]);else if(o===n)i.push(e[o]);else{let h=e[o]*(1-l)+e[n]*l;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),n=0,l=0;for(let h=a;h<=o&&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 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,[n,l,h,c]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let d=e.createLinearGradient(n,l,h,c);return t.forEach((b,y)=>d.addColorStop(y/(t.length-1),b)),d}catch{return t[0]}}function x(e,t,i,s,r,a){if((Array.isArray(a)?a.some(n=>n>0):a>0)&&typeof e.roundRect=="function"){let n=Math.min(s/2,Math.abs(r)/2),l=h=>m(h,0,n);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(l):l(a)),e.fill()}else e.fillRect(t,i,s,r)}function pt(e,t){return(e.barRadius||0)*t}function Et(e,t){let i=pt(e,t);return[i,i,0,0]}function ct(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 V(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=s*t.width,b=Et(r,a),y=P(e,r.color,t,r),w=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=y;for(let f=0;f<h.length;f++){let p=f*(o+n);if(p+o>t.width)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}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+n);if(p>d)break;let g=h[f]*c*.9,u=c-g;x(e,p,u,o,g,b)}e.restore()}function Pt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,n=r.barSpacing*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=c/2,b=s*t.width,y=pt(r,a),w=[y,y,0,0],f=[0,0,y,y],p=P(e,r.color,t,r),g=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 k=u*(o+n);if(k+o>t.width)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.save(),e.beginPath(),e.rect(0,0,b,c),e.clip(),e.fillStyle=g;for(let u=0;u<h.length;u++){let k=u*(o+n);if(k>b)break;let v=h[u]*c*.45;x(e,k,d-v,o,v,w),x(e,k,d,o,v,f)}e.restore()}function Tt(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=o*.35;e.clearRect(0,0,a,o);let h=(c,d,b=1,y=!1)=>{let w=P(e,c,t,r),f=Array.isArray(c)?c[c.length-1]:c;y&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=w,e.lineWidth=d,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let p=[],g=Math.floor(i.length*b);for(let u=0;u<g;u++){let k=u/(i.length-1)*a,v=i[u],A=Math.sin(u*.1)*v,L=n+A*l;p.push({x:k,y:L})}for(let u=0;u<p.length-1;u++){let k=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(k,v,A,L,p[u+1].x,p[u+1].y)}e.stroke(),y&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,n),e.lineTo(a,n),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 ut(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,n=(r.barSpacing||1)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=4*a,b=2*a,y=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 g=0;g<h.length;g++){let u=g*(o+n);if(u+o>t.width)break;let k=h[g]*c*.9,v=Math.floor(k/(d+b));e.fillStyle=u<y?p:f;for(let A=0;A<v;A++){let L=A*(d+b);e.fillRect(u,w-L-d,o,d),A>0&&e.fillRect(u,w+L,o,d)}}}function dt(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,n=(r.barSpacing||3)*a,l=Math.floor(t.width/(o+n)),h=B(i,l),c=t.height,d=Math.max(1.5*a,o/2),b=s*t.width,y=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 g=p*(o+n)+o/2;if(g>t.width)break;let u=h[p]*c*.9;e.fillStyle=g<b?f:w,e.beginPath(),e.arc(g,y-u/2,d,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(g,y+u/2,d,0,Math.PI*2),e.fill()}}function At(e,t,i,s,r){let a=t.width,o=t.height,n=o/2,l=4,h=l/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)",ct(e,h,a,n,l),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)",ct(e,h,d,n,l),e.fill(),e.restore()}}var Mt={bars:V,bar:V,mirror:Pt,line:Tt,blocks:ut,block:ut,dots:dt,dot:dt,seekbar:At};function ft(e,t,i,s,r){(Mt[r.waveformStyle]||V)(e,t,i,s,r)}function mt(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 a={};r.forEach(l=>{let h=60/l,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,n=120;for(let[l,h]of Object.entries(a))h>o&&(o=h,n=parseInt(l));return n<70&&a[n*2]?n*=2:n>160&&a[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=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let n=0;for(let c=o;c<o+2048;c++)n+=e[c]*e[c];n=n/2048;let l=n-a,h=a*1.8+.01;if(l>h&&n>.01){let c=r[r.length-1]||0,d=t*.15;o-c>d&&r.push(o)}a=n*.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 n=e.getChannelData(o);for(let l=0;l<t;l++){let h=~~(l*i),c=~~(h+i),d=0,b=0;for(let w=h;w<c;w++){let f=n[w];f>b&&(b=f),f<d&&(d=f)}let y=Math.max(Math.abs(b),Math.abs(d));(o===0||y>r[l])&&(r[l]=y)}}let a=$(r);return a>0?r.map(o=>o/a):r}async function G(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),n=await s.decodeAudioData(o),l=Lt(n,t);l=_t(l);let h=null;return i&&(h=mt(n)),{peaks:l,bpm:h}}finally{s&&s.close()}}function yt(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 _t(e,t=.95){let i=$(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}var K=128;function gt(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 xt(e){let t=0,i=0;for(let s=e;s&&s.nodeType===1&&i<.995;s=s.parentElement){let r=U(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 Rt(){let e=lt(getComputedStyle(document.body).color);if(e!==null)return e>K?"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 R(e){if(gt("dark"))return"dark";if(gt("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:s}=xt(t),r=Rt(),a=i+(r==="dark"?0:255)*(1-s);return a>K?"light":a<K?"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 J(e,t){if(e&&C[e])return C[e];let i=R(t);return C[i]}var W={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},X={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}},Q=["auto","top","center","bottom"],N=.25,F=4,Dt={buttonAlign:Q,layout:["default","preview"],buttonStyle:["circle","minimal"],artworkPosition:["info","button"],waveformStyle:Object.keys(X),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:0},barSpacing:{min:0},barRadius:{min:0},bpm:{min:1},playbackRate:{min:N,max:F}},Ht=["autoplay","showControls","showInfo","showTime","showHoverTime","seekHandle","showBPM","singlePlay","playOnSeek","enableMediaSession","showMarkers","accessibleSeek","showPlaybackSpeed"],It=["onLoad","onPlay","onPause","onEnd","onError","onTimeUpdate","onNextTrack","onPreviousTrack"];function Y(e,t){console.warn(`[WaveformPlayer] Invalid ${e} option, using default:`,t)}function z(e){let t=H(e);return t?t.reduce((i,s)=>{let r=s&&typeof s=="object"?_(s.time,null,{min:0}):null;return r===null?(Y("marker",s),i):(i.push({...s,time:r,label:s.label==null?"":s.label}),i)},[]):(e!=null&&Y("markers",e),[])}function Z(e){let t=s=>e[s]!=null,i=s=>{Y(s,e[s]),e[s]=W[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(Dt))t(s)&&rt(e[s],r)===null&&i(s);for(let s of Ht)e[s]=at(e[s]);for(let s of It)t(s)&&typeof e[s]!="function"&&i(s);if(t("playbackRates")){let s=D(e.playbackRates,{min:N,max:F,fallback:null});s===null?i("playbackRates"):e.playbackRates=s}e.markers=z(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 Ot="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,wt=10,Wt='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=I(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=Z(j(W,s,r));let a=J(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:R(this.container);for(let[n,l]of Object.entries(a))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let o=X[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._ac=new AbortController,this.id=this.container.id||nt(this.options.url),e.instances.set(this.id,this),e._watchTheme();try{this.init()}catch(n){throw e.instances.delete(this.id),this._ac.abort(),n}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=Q.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: ${q(this.options.buttonSize)}`),this.options.buttonRadius!=null&&s.push(`--wfp-btn-radius: ${q(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">`:"",n=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 @@
61
61
  ${l}
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=Ot)},{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.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=l=>{if(i.style.display=l?"block":"none",t.setAttribute("aria-expanded",l?"true":"false"),l){let h=s();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=l=>{let h=s();h.length&&h[(l+h.length)%h.length].focus()},n=l=>{this.setPlaybackRate(parseFloat(l.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",l=>{l.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",l=>{l.stopPropagation();let h=l.target.closest(".speed-option");h&&n(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",l=>{let h=s(),c=h.indexOf(document.activeElement);if(!r()){(l.key==="ArrowDown"||l.key==="ArrowUp")&&document.activeElement===t&&(l.preventDefault(),a(!0));return}switch(l.key){case"ArrowDown":l.preventDefault(),o(c<0?0:c+1);break;case"ArrowUp":l.preventDefault(),o(c<0?h.length-1:c-1);break;case"Home":l.preventDefault(),o(0);break;case"End":l.preventDefault(),o(h.length-1);break;case"Escape":l.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(It)||(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-wt;break;case"PageUp":r=s+wt;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",ot(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;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;let i=this.audio.duration;navigator.mediaSession.setPositionState&&i&&isFinite(i)&&navigator.mediaSession.setPositionState({duration:i,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,i)})}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.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=ht(()=>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.container.classList.remove("waveform-is-placeholder");let i=!!this.options.waveform;i&&this.setWaveformData(this.options.waveform),this.audio&&(this.audio.src=t,this.audio.preload!=="none"&&await new Promise((r,a)=>{let o=()=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),r()},n=l=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),a(l)};this.audio.addEventListener("loadedmetadata",o),this.audio.addEventListener("error",n)}));let s=this.options.title||I(t);if(this.titleEl&&(this.titleEl.textContent=s),this.applySeekLabel(s),!i)try{let r=await G(t,this.options.samples,this.options.showBPM);this.waveformData=r.peaks,r.bpm&&(this.detectedBPM=r.bpm,this.updateBPMDisplay())}catch(r){console.warn("[WaveformPlayer] Using placeholder waveform:",r),this.waveformData=yt(this.options.samples),this.container.classList.add("waveform-is-placeholder")}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}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.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=Z(j(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?W.artworkAlt:""),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?z(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=z(i.markers),this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}this.waveformData=D(t,{fallback:[]}),this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||ft(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",n=>{n.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,n)=>{let l=parseFloat(o.getAttribute("data-time"));Number.isFinite(l)&&l<=s+.05&&l>a&&(a=l,r=n)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,n)=>o.classList.toggle("show-label",n===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.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=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="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=R(this.container);let t=J(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(){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,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.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=E(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=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),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:N,max:F});i!==null&&(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 G(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:I,escapeHtml:S,isSafeHref:st,parseDataAttributes:O,detectColorScheme:R};var et=()=>typeof window<"u"&&typeof document<"u";function tt(){if(!et())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(!(t.dataset.waveformInitialized==="true"||T.getInstance(t)))try{new T(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}et()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",tt):tt());T.init=tt;et()&&(window.WaveformPlayer=T);var ee=T;})();
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=Ot)},{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.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=l=>{if(i.style.display=l?"block":"none",t.setAttribute("aria-expanded",l?"true":"false"),l){let h=s();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=l=>{let h=s();h.length&&h[(l+h.length)%h.length].focus()},n=l=>{this.setPlaybackRate(parseFloat(l.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",l=>{l.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",l=>{l.stopPropagation();let h=l.target.closest(".speed-option");h&&n(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",l=>{let h=s(),c=h.indexOf(document.activeElement);if(!r()){(l.key==="ArrowDown"||l.key==="ArrowUp")&&document.activeElement===t&&(l.preventDefault(),a(!0));return}switch(l.key){case"ArrowDown":l.preventDefault(),o(c<0?0:c+1);break;case"ArrowUp":l.preventDefault(),o(c<0?h.length-1:c-1);break;case"Home":l.preventDefault(),o(0);break;case"End":l.preventDefault(),o(h.length-1);break;case"Escape":l.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(Wt)||(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-wt;break;case"PageUp":r=s+wt;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",ot(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;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;let i=this.audio.duration;navigator.mediaSession.setPositionState&&i&&isFinite(i)&&navigator.mediaSession.setPositionState({duration:i,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,i)})}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.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=ht(()=>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.container.classList.remove("waveform-is-placeholder");let i=!!this.options.waveform;i&&this.setWaveformData(this.options.waveform);let s=this.options.title||O(t);if(this.titleEl&&(this.titleEl.textContent=s),this.applySeekLabel(s),this.audio&&(this.audio.src=t,this.audio.preload!=="none"&&await new Promise((r,a)=>{let o=()=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),r()},n=l=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),a(l)};this.audio.addEventListener("loadedmetadata",o),this.audio.addEventListener("error",n)})),!i)try{let r=await G(t,this.options.samples,this.options.showBPM);this.waveformData=r.peaks,r.bpm&&(this.detectedBPM=r.bpm,this.updateBPMDisplay())}catch(r){console.warn("[WaveformPlayer] Using placeholder waveform:",r),this.waveformData=yt(this.options.samples),this.container.classList.add("waveform-is-placeholder")}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}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.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=Z(j(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?W.artworkAlt:""),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?z(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=z(i.markers),this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}this.waveformData=D(t,{fallback:[]}),this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||ft(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",n=>{n.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,n)=>{let l=parseFloat(o.getAttribute("data-time"));Number.isFinite(l)&&l<=s+.05&&l>a&&(a=l,r=n)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,n)=>o.classList.toggle("show-label",n===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.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=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="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=R(this.container);let t=J(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(){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,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.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=E(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=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),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:N,max:F});i!==null&&(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="",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 G(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:O,escapeHtml:S,isSafeHref:st,parseDataAttributes:I,detectColorScheme:R};var et=()=>typeof window<"u"&&typeof document<"u",Nt=()=>document.documentElement?.dataset.waveformAutoinit==="false";function kt(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 tt(e=document){if(!et())return;let t=e||document;t.matches?.("[data-waveform-player]")&&kt(t),t.querySelectorAll("[data-waveform-player]").forEach(kt)}et()&&!Nt()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>tt()):tt());T.init=tt;et()&&(window.WaveformPlayer=T);var se=T;})();
package/index.d.ts CHANGED
@@ -395,8 +395,15 @@ export declare class WaveformPlayer {
395
395
  static generateWaveformData(url: string, samples?: number): Promise<{ peaks: number[]; bpm: number | null }>;
396
396
  /** Convention helper: derive the sibling `.json` peaks URL for an audio URL. */
397
397
  static getPeaksUrl(audioUrl: string): string;
398
- /** Scan the document for `[data-waveform-player]` elements and initialise them. */
399
- static init(): void;
398
+ /**
399
+ * Scan for `[data-waveform-player]` elements and initialise them.
400
+ *
401
+ * Runs automatically on import over the whole document, unless the document
402
+ * element carries `data-waveform-autoinit="false"`; calling it by hand works
403
+ * either way. Pass `root` to scope the scan to a subtree you control — the
404
+ * root is matched as well as its descendants.
405
+ */
406
+ static init(root?: Document | Element): void;
400
407
  /**
401
408
  * Pure helper functions exposed as a single source of truth so consumers
402
409
  * (e.g. `@arraypress/waveform-bar`) can reuse them instead of shipping
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arraypress/waveform-player",
3
- "version": "1.25.0",
3
+ "version": "1.26.0",
4
4
  "description": "Lightweight, customizable audio player with waveform visualization",
5
5
  "type": "module",
6
6
  "types": "./index.d.ts",
@@ -81,7 +81,12 @@
81
81
  "registry": "https://registry.npmjs.org/"
82
82
  },
83
83
  "sideEffects": [
84
- "*.css"
84
+ "*.css",
85
+ "./dist/waveform-player.esm.js",
86
+ "./dist/waveform-player.cjs",
87
+ "./dist/waveform-player.js",
88
+ "./dist/waveform-player.min.js",
89
+ "./src/js/index.js"
85
90
  ],
86
91
  "devDependencies": {
87
92
  "concurrently": "^10.0.3",
package/src/js/core.js CHANGED
@@ -168,8 +168,22 @@ export class WaveformPlayer {
168
168
  // Re-detect the theme on runtime light/dark switches (shared watcher).
169
169
  WaveformPlayer._watchTheme();
170
170
 
171
- // Initialize
172
- this.init();
171
+ // Initialize. Registration above claims the id before any of this runs,
172
+ // so a throw partway through would otherwise strand a half-built player
173
+ // in the registry — and everything that walks it would then trip over
174
+ // it: `getInstance()` matches by container, so autoInit would skip that
175
+ // element forever (a transient failure becoming a permanent blank), and
176
+ // the shared theme watcher and `destroyAll()` both `forEach` the map,
177
+ // where one throw aborts the loop and strands every instance after it.
178
+ // Unregister and drop any listeners bound so far, then rethrow so the
179
+ // caller still sees the failure.
180
+ try {
181
+ this.init();
182
+ } catch (error) {
183
+ WaveformPlayer.instances.delete(this.id);
184
+ this._ac.abort();
185
+ throw error;
186
+ }
173
187
 
174
188
  // Dispatch ready event after initialization
175
189
  setTimeout(() => {
@@ -1161,11 +1175,13 @@ export class WaveformPlayer {
1161
1175
  * `loadedmetadata` before proceeding. In external mode there is no audio
1162
1176
  * element, so the src/metadata step is skipped and only the visualization
1163
1177
  * is built (duration/time come from the controller via
1164
- * {@link WaveformPlayer#setProgress}). Peaks come from the `waveform`
1165
- * option when provided — painted *before* the metadata wait, since they
1166
- * need nothing from the audio element — otherwise they are decoded from
1167
- * the audio; a decode failure falls back to a placeholder waveform. The
1168
- * `onLoad` callback fires on success.
1178
+ * {@link WaveformPlayer#setProgress}). The title and the seek slider's
1179
+ * accessible name are written *before* the metadata wait, as are peaks
1180
+ * supplied via the `waveform` option — none of them need anything from the
1181
+ * audio element, and behind the wait they blink in on a slow origin.
1182
+ * Without inline peaks the waveform is decoded from the audio instead; a
1183
+ * decode failure falls back to a placeholder. The `onLoad` callback fires
1184
+ * on success.
1169
1185
  * @param {string} url - Audio URL.
1170
1186
  * @returns {Promise<void>} Resolves once loading settles (errors are caught
1171
1187
  * internally and surfaced through {@link WaveformPlayer#onError}).
@@ -1187,6 +1203,18 @@ export class WaveformPlayer {
1187
1203
  this.setWaveformData(this.options.waveform);
1188
1204
  }
1189
1205
 
1206
+ // Same reasoning as the peaks above: the title comes from the
1207
+ // `title` option or the URL, so it needs nothing from the audio
1208
+ // element and has no business waiting on the network. Behind the
1209
+ // metadata wait it left the info row blank for the whole fetch and
1210
+ // then popped in — a visible blink on any slow origin. See #25.
1211
+ const title = this.options.title || extractTitleFromUrl(url);
1212
+ if (this.titleEl) {
1213
+ this.titleEl.textContent = title;
1214
+ }
1215
+ // Keep the seek slider's accessible name in sync with the track.
1216
+ this.applySeekLabel(title);
1217
+
1190
1218
  // In external mode we don't own an <audio> element — skip
1191
1219
  // src assignment + metadata-wait, but still generate the
1192
1220
  // waveform peaks so the canvas can render the visualization.
@@ -1198,7 +1226,7 @@ export class WaveformPlayer {
1198
1226
 
1199
1227
  // preload="none" tells the browser to fetch nothing until
1200
1228
  // play(), so `loadedmetadata` will never arrive and awaiting
1201
- // it would strand the rest of this method forever (no title,
1229
+ // it would strand the rest of this method forever (no peaks,
1202
1230
  // no markers, no onLoad, loading state stuck on). Skip the
1203
1231
  // wait; the bindEvents() `loadedmetadata` listener still
1204
1232
  // fires whenever metadata does land, and onMetadataLoaded()
@@ -1222,14 +1250,6 @@ export class WaveformPlayer {
1222
1250
  }
1223
1251
  }
1224
1252
 
1225
- // Set title
1226
- const title = this.options.title || extractTitleFromUrl(url);
1227
- if (this.titleEl) {
1228
- this.titleEl.textContent = title;
1229
- }
1230
- // Keep the seek slider's accessible name in sync with the track.
1231
- this.applySeekLabel(title);
1232
-
1233
1253
  // Peaks were drawn above; only the decode path is left.
1234
1254
  if (!hasInlinePeaks) {
1235
1255
  // Generate waveform
@@ -2414,6 +2434,16 @@ export class WaveformPlayer {
2414
2434
  // Clear the container
2415
2435
  this.container.innerHTML = '';
2416
2436
 
2437
+ // Drop the declarative-scan flag along with the markup it described.
2438
+ // autoInit() checks `data-waveform-initialized` *before* the instance
2439
+ // lookup, so leaving it behind on an emptied container makes the
2440
+ // element permanently un-initializable: destroy() wipes the DOM and
2441
+ // the instance, then every later WaveformPlayer.init() skips the
2442
+ // element on the stale flag and it stays blank. Matters most for
2443
+ // destroyAll() + init() resets and for teardown/remount cycles that
2444
+ // reuse the same element rather than re-rendering it.
2445
+ delete this.container.dataset.waveformInitialized;
2446
+
2417
2447
  // Clear all references
2418
2448
  this.canvas = null;
2419
2449
  this.ctx = null;
package/src/js/index.js CHANGED
@@ -7,7 +7,8 @@
7
7
  * `WaveformPlayer.init` hook, scans the DOM for declarative `[data-waveform-player]`
8
8
  * markup and auto-instantiates a player for each match, and attaches the class
9
9
  * to `window` for plain `<script>`/CDN usage. Loading this module is enough to
10
- * make any markup-driven players on the page come alive once the DOM is ready.
10
+ * make any markup-driven players on the page come alive once the DOM is ready —
11
+ * unless the page opts out of that scan (see {@link autoInitDisabled}).
11
12
  */
12
13
 
13
14
  // Import the main class
@@ -35,52 +36,104 @@ WaveformPlayer.utils = {formatTime, extractTitleFromUrl, escapeHtml, isSafeHref,
35
36
  const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
36
37
 
37
38
  /**
38
- * Scan the document for declarative player markup and instantiate one
39
- * {@link WaveformPlayer} per matching element.
39
+ * Whether the page has opted out of the scan that runs on import.
40
+ *
41
+ * A page that renders markup it does not author — user content, a CMS, an editor
42
+ * canvas — may not want every `[data-waveform-player]` on it to become a player.
43
+ * Setting `data-waveform-autoinit="false"` on the document element suppresses the
44
+ * automatic scan: nothing is initialized unless the page asks for it, either by
45
+ * constructing players itself or by calling {@link WaveformPlayer.init} against
46
+ * markup it trusts. Both remain available; only the automatic call is gated.
47
+ *
48
+ * Read off `<html>` rather than a global because ES module imports are evaluated
49
+ * before the importing module's body runs — a consumer with a static `import`
50
+ * never gets the chance to set a flag first. Markup is in place before any script
51
+ * executes, so an attribute is the one mechanism a bundled consumer can reach.
52
+ *
53
+ * This scopes initialization; it does not sanitize anything. `playIcon` /
54
+ * `pauseIcon` still inject raw markup for any player that *is* built.
55
+ *
56
+ * @returns {boolean}
57
+ */
58
+ const autoInitDisabled = () => document.documentElement?.dataset.waveformAutoinit === 'false';
59
+
60
+ /**
61
+ * Construct a player for one declarative element, unless it already has one.
62
+ *
63
+ * Skips elements already claimed by a player. The `data-waveform-initialized`
64
+ * flag only covers elements a scan built; an element constructed
65
+ * programmatically (`new WaveformPlayer(el)`) carries no flag, so without the
66
+ * instance lookup a later scan would build a second player over it.
67
+ *
68
+ * Construction errors are caught and logged rather than thrown, so one broken
69
+ * element cannot abort the rest of a scan.
70
+ *
71
+ * @param {HTMLElement} element - Element carrying `data-waveform-player`.
72
+ * @returns {void}
73
+ */
74
+ function initElement(element) {
75
+ if (
76
+ element.dataset.waveformInitialized === 'true' ||
77
+ WaveformPlayer.getInstance(element)
78
+ ) {
79
+ return;
80
+ }
81
+
82
+ try {
83
+ new WaveformPlayer(element);
84
+ element.dataset.waveformInitialized = 'true';
85
+ } catch (error) {
86
+ console.error('[WaveformPlayer] Failed to initialize:', error, element);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Scan for declarative player markup and instantiate one {@link WaveformPlayer}
92
+ * per matching element.
40
93
  *
41
94
  * Finds every element carrying the `data-waveform-player` attribute and, for
42
95
  * each one not already initialized, constructs a player from it (the constructor
43
96
  * reads the element's `data-*` attributes for configuration). Each successfully
44
97
  * initialized element is flagged with `data-waveform-initialized="true"` so
45
98
  * repeat calls are idempotent and never double-initialize the same element.
46
- * Elements already claimed by a programmatically constructed player carry no
47
- * such flag, so they are skipped by instance lookup instead. Construction errors
48
- * are caught and logged so one broken element cannot abort the rest of the scan.
49
99
  * A no-op in non-DOM environments (e.g. SSR).
50
100
  *
101
+ * `root` scopes the scan. It pairs with the {@link autoInitDisabled} opt-out:
102
+ * a page that suppresses the automatic document-wide scan can still initialize
103
+ * the subtree it owns, and gets the claim-checking and per-element error
104
+ * isolation above rather than hand-rolling a `querySelectorAll` loop that has
105
+ * neither.
106
+ *
107
+ * The scan itself is unconditional — the opt-out gates only the automatic
108
+ * invocation below, never a call made by hand.
109
+ *
110
+ * @param {Document|Element} [root=document] - Subtree to scan. Matched against
111
+ * itself as well as its descendants.
51
112
  * @returns {void}
52
113
  */
53
- function autoInit() {
114
+ function autoInit(root = document) {
54
115
  if (!isBrowser()) return;
55
116
 
56
- const elements = document.querySelectorAll('[data-waveform-player]');
117
+ const scope = root || document;
57
118
 
58
- elements.forEach(element => {
59
- // Skip elements already claimed by a player. The `data-waveform-initialized`
60
- // flag only covers elements this scan built; an element constructed
61
- // programmatically (`new WaveformPlayer(el)`) carries no flag, so without
62
- // the instance lookup a later scan would build a second player over it.
63
- if (
64
- element.dataset.waveformInitialized === 'true' ||
65
- WaveformPlayer.getInstance(element)
66
- ) {
67
- return;
68
- }
119
+ // `querySelectorAll` never matches its own root, so a caller scoping the
120
+ // scan to a single player (`init(playerEl)`) would silently get nothing.
121
+ if (scope.matches?.('[data-waveform-player]')) {
122
+ initElement(scope);
123
+ }
69
124
 
70
- try {
71
- new WaveformPlayer(element);
72
- element.dataset.waveformInitialized = 'true';
73
- } catch (error) {
74
- console.error('[WaveformPlayer] Failed to initialize:', error, element);
75
- }
76
- });
125
+ scope.querySelectorAll('[data-waveform-player]').forEach(initElement);
77
126
  }
78
127
 
79
128
  // Initialize when DOM is ready: defer until DOMContentLoaded if the document is
80
- // still parsing, otherwise run the scan immediately on import.
81
- if (isBrowser()) {
129
+ // still parsing, otherwise run the scan immediately on import. Skipped entirely
130
+ // when the document opts out — the gate sits here rather than inside autoInit()
131
+ // so `WaveformPlayer.init()` stays usable as a manual, page-controlled scan.
132
+ if (isBrowser() && !autoInitDisabled()) {
82
133
  if (document.readyState === 'loading') {
83
- document.addEventListener('DOMContentLoaded', autoInit);
134
+ // Wrapped, not passed by reference: a listener is called with the Event
135
+ // as its first argument, which `autoInit` would take as its `root`.
136
+ document.addEventListener('DOMContentLoaded', () => autoInit());
84
137
  } else {
85
138
  autoInit();
86
139
  }
@@ -91,7 +144,8 @@ if (isBrowser()) {
91
144
  *
92
145
  * Exposes {@link autoInit} as `WaveformPlayer.init` so callers can manually
93
146
  * (re-)scan the DOM after dynamically injecting `[data-waveform-player]` markup.
94
- * Already-initialized elements are skipped on subsequent calls.
147
+ * Already-initialized elements are skipped on subsequent calls. Works whether or
148
+ * not the document opted out of the automatic scan.
95
149
  *
96
150
  * @type {typeof autoInit}
97
151
  */