| @@ -1,14 +1,14 @@ | ||
| 1 | -import{store as Pe,getContext as N,getElement as Ae}from"@wordpress/interactivity";var $t={grad:.9,turn:360,rad:360/(2*Math.PI)},_=function(e){return typeof e=="string"?e.length>0:typeof e=="number"},b=function(e,t,i){return t===void 0&&(t=0),i===void 0&&(i=Math.pow(10,t)),Math.round(i*e)/i+0},T=function(e,t,i){return t===void 0&&(t=0),i===void 0&&(i=1),e>i?i:e>t?e:t},ht=function(e){return(e=isFinite(e)?e%360:0)>0?e:e+360},et=function(e){return{r:T(e.r,0,255),g:T(e.g,0,255),b:T(e.b,0,255),a:T(e.a)}},U=function(e){return{r:b(e.r),g:b(e.g),b:b(e.b),a:b(e.a,3)}},Nt=/^#([0-9a-f]{3,8})$/i,O=function(e){var t=e.toString(16);return t.length<2?"0"+t:t},ut=function(e){var t=e.r,i=e.g,a=e.b,r=e.a,s=Math.max(t,i,a),o=s-Math.min(t,i,a),l=o?s===t?(i-a)/o:s===i?2+(a-t)/o:4+(t-i)/o:0;return{h:60*(l<0?l+6:l),s:s?o/s*100:0,v:s/255*100,a:r}},dt=function(e){var t=e.h,i=e.s,a=e.v,r=e.a;t=t/360*6,i/=100,a/=100;var s=Math.floor(t),o=a*(1-i),l=a*(1-(t-s)*i),n=a*(1-(1-t+s)*i),h=s%6;return{r:255*[a,l,o,o,n,a][h],g:255*[n,a,a,l,o,o][h],b:255*[o,o,n,a,a,l][h],a:r}},it=function(e){return{h:ht(e.h),s:T(e.s,0,100),l:T(e.l,0,100),a:T(e.a)}},at=function(e){return{h:b(e.h),s:b(e.s),l:b(e.l),a:b(e.a,3)}},rt=function(e){return dt((i=(t=e).s,{h:t.h,s:(i*=((a=t.l)<50?a:100-a)/100)>0?2*i/(a+i)*100:0,v:a+i,a:t.a}));var t,i,a},B=function(e){return{h:(t=ut(e)).h,s:(r=(200-(i=t.s))*(a=t.v)/100)>0&&r<200?i*a/100/(r<=100?r:200-r)*100:0,l:r/2,a:t.a};var t,i,a,r},qt=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Ot=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,zt=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Ft=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,st={string:[[function(e){var t=Nt.exec(e);return t?(e=t[1]).length<=4?{r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:e.length===4?b(parseInt(e[3]+e[3],16)/255,2):1}:e.length===6||e.length===8?{r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16),a:e.length===8?b(parseInt(e.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(e){var t=zt.exec(e)||Ft.exec(e);return t?t[2]!==t[4]||t[4]!==t[6]?null:et({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(e){var t=qt.exec(e)||Ot.exec(e);if(!t)return null;var i,a,r=it({h:(i=t[1],a=t[2],a===void 0&&(a="deg"),Number(i)*($t[a]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)});return rt(r)},"hsl"]],object:[[function(e){var t=e.r,i=e.g,a=e.b,r=e.a,s=r===void 0?1:r;return _(t)&&_(i)&&_(a)?et({r:Number(t),g:Number(i),b:Number(a),a:Number(s)}):null},"rgb"],[function(e){var t=e.h,i=e.s,a=e.l,r=e.a,s=r===void 0?1:r;if(!_(t)||!_(i)||!_(a))return null;var o=it({h:Number(t),s:Number(i),l:Number(a),a:Number(s)});return rt(o)},"hsl"],[function(e){var t=e.h,i=e.s,a=e.v,r=e.a,s=r===void 0?1:r;if(!_(t)||!_(i)||!_(a))return null;var o=(function(l){return{h:ht(l.h),s:T(l.s,0,100),v:T(l.v,0,100),a:T(l.a)}})({h:Number(t),s:Number(i),v:Number(a),a:Number(s)});return dt(o)},"hsv"]]},ot=function(e,t){for(var i=0;i<t.length;i++){var a=t[i][0](e);if(a)return[a,t[i][1]]}return[null,void 0]},Ut=function(e){return typeof e=="string"?ot(e.trim(),st.string):typeof e=="object"&&e!==null?ot(e,st.object):[null,void 0]};var j=function(e,t){var i=B(e);return{h:i.h,s:T(i.s+100*t,0,100),l:i.l,a:i.a}},G=function(e){return(299*e.r+587*e.g+114*e.b)/1e3/255},nt=function(e,t){var i=B(e);return{h:i.h,s:i.s,l:T(i.l+100*t,0,100),a:i.a}},lt=(function(){function e(t){this.parsed=Ut(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return e.prototype.isValid=function(){return this.parsed!==null},e.prototype.brightness=function(){return b(G(this.rgba),2)},e.prototype.isDark=function(){return G(this.rgba)<.5},e.prototype.isLight=function(){return G(this.rgba)>=.5},e.prototype.toHex=function(){return t=U(this.rgba),i=t.r,a=t.g,r=t.b,o=(s=t.a)<1?O(b(255*s)):"","#"+O(i)+O(a)+O(r)+o;var t,i,a,r,s,o},e.prototype.toRgb=function(){return U(this.rgba)},e.prototype.toRgbString=function(){return t=U(this.rgba),i=t.r,a=t.g,r=t.b,(s=t.a)<1?"rgba("+i+", "+a+", "+r+", "+s+")":"rgb("+i+", "+a+", "+r+")";var t,i,a,r,s},e.prototype.toHsl=function(){return at(B(this.rgba))},e.prototype.toHslString=function(){return t=at(B(this.rgba)),i=t.h,a=t.s,r=t.l,(s=t.a)<1?"hsla("+i+", "+a+"%, "+r+"%, "+s+")":"hsl("+i+", "+a+"%, "+r+"%)";var t,i,a,r,s},e.prototype.toHsv=function(){return t=ut(this.rgba),{h:b(t.h),s:b(t.s),v:b(t.v),a:b(t.a,3)};var t},e.prototype.invert=function(){return k({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},e.prototype.saturate=function(t){return t===void 0&&(t=.1),k(j(this.rgba,t))},e.prototype.desaturate=function(t){return t===void 0&&(t=.1),k(j(this.rgba,-t))},e.prototype.grayscale=function(){return k(j(this.rgba,-1))},e.prototype.lighten=function(t){return t===void 0&&(t=.1),k(nt(this.rgba,t))},e.prototype.darken=function(t){return t===void 0&&(t=.1),k(nt(this.rgba,-t))},e.prototype.rotate=function(t){return t===void 0&&(t=15),this.hue(this.hue()+t)},e.prototype.alpha=function(t){return typeof t=="number"?k({r:(i=this.rgba).r,g:i.g,b:i.b,a:t}):b(this.rgba.a,3);var i},e.prototype.hue=function(t){var i=B(this.rgba);return typeof t=="number"?k({h:t,s:i.s,l:i.l,a:i.a}):b(i.h)},e.prototype.isEqual=function(t){return this.toHex()===k(t).toHex()},e})(),k=function(e){return e instanceof lt?e:new lt(e)};function Pt(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function L(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ct(e){return L(typeof e=="number"?`${e}px`:e)}function jt(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 w(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function Gt(e){return e===void 0?void 0:e==="true"}function pt(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function At(e){let t={},i=(o,l=o)=>{let n=Gt(e.dataset[l]);n!==void 0&&(t[o]=n)},a=(o,l=o,n=!1)=>{let h=e.dataset[l];h&&(t[o]=n?parseFloat(h):parseInt(h,10))},r=(o,l=o)=>{let n=e.dataset[l];n&&(t[o]=/^\d+(\.\d+)?$/.test(n.trim())?parseFloat(n):n)},s=(o,l=o)=>{let n=e.dataset[l];if(n)try{t[o]=JSON.parse(n)}catch(h){console.warn(`[WaveformPlayer] Invalid ${l} JSON:`,h)}};return e.dataset.src&&(t.url=e.dataset.src),e.dataset.url&&(t.url=e.dataset.url),a("height"),a("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),a("barWidth"),a("barSpacing"),a("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=pt(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=pt(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"),a("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),s("markers"),a("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),s("playbackRates"),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 Vt(e,...t){let i=0;return e.replace(/%(?:(\d+)\$)?s/g,(a,r)=>{let s=r?Number(r)-1:i++;return t[s]??a})}function I(e){if(!e||isNaN(e)||e<0)return"0:00";let t=Math.floor(e/3600),i=Math.floor(e%3600/60),a=Math.floor(e%60);return t>0?`${t}:${i.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`:`${i}:${a.toString().padStart(2,"0")}`}var Jt=0;function Kt(e){let t=e||"audio",i=5381;for(let a=0;a<t.length;a++)i=(i<<5)+i+t.charCodeAt(a)|0;return`wp_${(i>>>0).toString(36)}_${(Jt++).toString(36)}`}function Tt(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,i=>i.toUpperCase())}function Xt(e){let t=typeof e=="string"?e.match(/\d+/g):null;if(!t||t.length<3)return null;let[i,a,r]=t.map(Number);return(i*299+a*587+r*114)/1e3}function mt(...e){let t={};for(let i of e)for(let a in i)i[a]!==null&&i[a]!==void 0&&(t[a]=i[a]);return t}function Qt(e,t){let i;return function(...a){let r=()=>{clearTimeout(i),e(...a)};clearTimeout(i),i=setTimeout(r,t)}}function z(e,t){if(e.length===t)return e;if(e.length===0||t===0)return[];let i=[];if(t>e.length){let a=(e.length-1)/(t-1);for(let r=0;r<t;r++){let s=r*a,o=Math.floor(s),l=Math.ceil(s),n=s-o;if(l>=e.length)i.push(e[e.length-1]);else if(o===l)i.push(e[o]);else{let h=e[o]*(1-n)+e[l]*n;i.push(h)}}}else{let a=e.length/t;for(let r=0;r<t;r++){let s=Math.floor(r*a),o=Math.floor((r+1)*a),l=0,n=0;for(let h=s;h<=o&&h<e.length;h++)e[h]>l&&(l=e[h]),n++;if(n===0){let h=Math.min(Math.round(r*a),e.length-1);l=e[h]}i.push(l)}}return i}function x(e,t,i,a){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let r=i.width,s=i.height,o=a&&a.waveformGradient,[l,n,h,u]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,s]:[0,0,0,s];try{let c=e.createLinearGradient(l,n,h,u);return t.forEach((p,y)=>c.addColorStop(y/(t.length-1),p)),c}catch{return t[0]}}function D(e,t,i,a,r,s){if((Array.isArray(s)?s.some(o=>o>0):s>0)&&typeof e.roundRect=="function"){let o=Math.min(a/2,Math.abs(r)/2),l=n=>w(n,0,o);e.beginPath(),e.roundRect(t,i,a,r,Array.isArray(s)?s.map(l):l(s)),e.fill()}else e.fillRect(t,i,a,r)}function xt(e,t){return(e.barRadius||0)*t}function Yt(e,t){let i=xt(e,t);return[i,i,0,0]}function ft(e,t,i,a,r){let s=r/2;e.beginPath(),e.moveTo(t,a-s),e.lineTo(i-s,a-s),e.arc(i-s,a,s,-Math.PI/2,Math.PI/2),e.lineTo(t,a+s),e.arc(t,a,s,Math.PI/2,-Math.PI/2),e.closePath()}function V(e,t,i,a,r){let s=window.devicePixelRatio||1,o=r.barWidth*s,l=r.barSpacing*s,n=Math.floor(t.width/(o+l)),h=z(i,n),u=t.height,c=a*t.width,p=Yt(r,s),y=x(e,r.color,t,r),g=x(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=y;for(let m=0;m<h.length;m++){let f=m*(o+l);if(f+o>t.width)break;let v=h[m]*u*.9,d=u-v;D(e,f,d,o,v,p)}e.save(),e.beginPath(),e.rect(0,0,c,u),e.clip(),e.fillStyle=g;for(let m=0;m<h.length;m++){let f=m*(o+l);if(f>c)break;let v=h[m]*u*.9,d=u-v;D(e,f,d,o,v,p)}e.restore()}function Zt(e,t,i,a,r){let s=window.devicePixelRatio||1,o=r.barWidth*s,l=r.barSpacing*s,n=Math.floor(t.width/(o+l)),h=z(i,n),u=t.height,c=u/2,p=a*t.width,y=xt(r,s),g=[y,y,0,0],m=[0,0,y,y],f=x(e,r.color,t,r),v=x(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=f;for(let d=0;d<h.length;d++){let E=d*(o+l);if(E+o>t.width)break;let P=h[d]*u*.45;D(e,E,c-P,o,P,g),D(e,E,c,o,P,m)}e.save(),e.beginPath(),e.rect(0,0,p,u),e.clip(),e.fillStyle=v;for(let d=0;d<h.length;d++){let E=d*(o+l);if(E>p)break;let P=h[d]*u*.45;D(e,E,c-P,o,P,g),D(e,E,c,o,P,m)}e.restore()}function te(e,t,i,a,r){let s=t.width,o=t.height,l=o/2,n=o*.35;e.clearRect(0,0,s,o);let h=(u,c,p=1,y=!1)=>{let g=x(e,u,t,r),m=Array.isArray(u)?u[u.length-1]:u;y&&(e.shadowBlur=12,e.shadowColor=m),e.strokeStyle=g,e.lineWidth=c,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,l);let f=[],v=Math.floor(i.length*p);for(let d=0;d<v;d++){let E=d/(i.length-1)*s,P=i[d],C=Math.sin(d*.1)*P,M=l+C*n;f.push({x:E,y:M})}for(let d=0;d<f.length-1;d++){let E=f[d].x+(f[d+1].x-f[d].x)*.5,P=f[d].y,C=f[d+1].x-(f[d+1].x-f[d].x)*.5,M=f[d+1].y;e.bezierCurveTo(E,P,C,M,f[d+1].x,f[d+1].y)}e.stroke(),y&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,l),e.lineTo(s,l),e.stroke();for(let u=0;u<=10;u++){let c=s/10*u;e.beginPath(),e.moveTo(c,0),e.lineTo(c,o),e.stroke()}h(r.color,2,1,!1),a>0&&h(r.progressColor,3,a,!0)}function yt(e,t,i,a,r){let s=window.devicePixelRatio||1,o=(r.barWidth||3)*s,l=(r.barSpacing||1)*s,n=Math.floor(t.width/(o+l)),h=z(i,n),u=t.height,c=4*s,p=2*s,y=a*t.width,g=u/2,m=x(e,r.color,t,r),f=x(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let v=0;v<h.length;v++){let d=v*(o+l);if(d+o>t.width)break;let E=h[v]*u*.9,P=Math.floor(E/(c+p));e.fillStyle=d<y?f:m;for(let C=0;C<P;C++){let M=C*(c+p);e.fillRect(d,g-M-c,o,c),C>0&&e.fillRect(d,g+M,o,c)}}}function vt(e,t,i,a,r){let s=window.devicePixelRatio||1,o=(r.barWidth||2)*s,l=(r.barSpacing||3)*s,n=Math.floor(t.width/(o+l)),h=z(i,n),u=t.height,c=Math.max(1.5*s,o/2),p=a*t.width,y=u/2,g=x(e,r.color,t,r),m=x(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let f=0;f<h.length;f++){let v=f*(o+l)+o/2;if(v>t.width)break;let d=h[f]*u*.9;e.fillStyle=v<p?m:g,e.beginPath(),e.arc(v,y-d/2,c,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(v,y+d/2,c,0,Math.PI*2),e.fill()}}function ee(e,t,i,a,r){let s=t.width,o=t.height,l=o/2,n=4,h=n/2,u=!!r.seekActive;if(e.clearRect(0,0,s,o),e.fillStyle=x(e,r.color,t,r)||"rgba(255, 255, 255, 0.2)",ft(e,h,s,l,n),e.fill(),a>0){let c=Math.max(h*2,a*s);e.save(),e.globalAlpha=r.seekHandle&&!u?.7:1,e.fillStyle=x(e,r.progressColor,t,r)||"rgba(255, 255, 255, 0.9)",ft(e,h,c,l,n),e.fill(),e.restore()}}var ie={bars:V,bar:V,mirror:Zt,line:te,blocks:yt,block:yt,dots:vt,dot:vt,seekbar:ee};function ae(e,t,i,a,r){(ie[r.waveformStyle]||V)(e,t,i,a,r)}function re(e){try{let t=e.getChannelData(0),i=e.sampleRate,a=se(t,i);if(a.length<2)return 120;let r=[];for(let n=1;n<a.length;n++)r.push((a[n]-a[n-1])/i);let s={};r.forEach(n=>{let h=60/n,u=Math.round(h/3)*3;u>60&&u<200&&(s[u]=(s[u]||0)+1)});let o=0,l=120;for(let[n,h]of Object.entries(s))h>o&&(o=h,l=parseInt(n));return l<70&&s[l*2]?l*=2:l>160&&s[Math.round(l/2)]&&(l=Math.round(l/2)),l-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function se(e,t){let i=[],a=0;for(let r=0;r<e.length-2048;r+=1024){let s=0;for(let n=r;n<r+2048;n++)s+=e[n]*e[n];s=s/2048;let o=s-a,l=a*1.8+.01;if(o>l&&s>.01){let n=i[i.length-1]||0,h=t*.15;r-n>h&&i.push(r)}a=s*.8+a*.2}return i}function oe(e,t=1800){let i=e.length/t,a=e.numberOfChannels,r=[];for(let o=0;o<a;o++){let l=e.getChannelData(o);for(let n=0;n<t;n++){let h=~~(n*i),u=~~(h+i),c=0,p=0;for(let g=h;g<u;g++){let m=l[g];m>p&&(p=m),m<c&&(c=m)}let y=Math.max(Math.abs(p),Math.abs(c));(o===0||y>r[n])&&(r[n]=y)}}let s=Pt(r);return s>0?r.map(o=>o/s):r}async function gt(e,t=1800,i=!1){let a;try{let r=window.AudioContext||window.webkitAudioContext;a=new r;let s=await(await fetch(e)).arrayBuffer(),o=await a.decodeAudioData(s),l=oe(o,t);l=le(l);let n=null;return i&&(n=re(o)),{peaks:l,bpm:n}}finally{a&&a.close()}}function ne(e=1800){let t=[];for(let i=0;i<e;i++){let a=Math.random()*.5+.3,r=Math.sin(i/e*Math.PI*4)*.2;t.push(w(a+r,.1,1))}return t}function le(e,t=.95){let i=Pt(e);if(i===0||i>t)return e;let a=t/i;return e.map(r=>r*a)}function bt(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 J(){if(bt("dark"))return"dark";if(bt("light"))return"light";try{let e=getComputedStyle(document.body).backgroundColor,t=Xt(e);if(t!==null){if(t>128)return"light";if(t<128)return"dark"}}catch{}if(window.matchMedia){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return"dark";if(window.matchMedia("(prefers-color-scheme: light)").matches)return"light"}return"dark"}var R={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 wt(e){if(e&&R[e])return R[e];let t=J();return R[t]}var kt={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},he={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}},ue="data:image/svg+xml,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'),St=5,Et=10,de='button, a[href], input, [role="slider"]',W=class S{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 a=At(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=mt(kt,a,r);let s=wt(this.options.colorPreset);this._autoTheme=this.options.colorPreset==null||!R[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&R[this.options.colorPreset]?this.options.colorPreset:J();for(let[l,n]of Object.entries(s))(this.options[l]===null||this.options[l]===void 0)&&(this.options[l]=n,this._presetKeys.push(l));let o=he[this.options.waveformStyle];o&&(a.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=o.barWidth),a.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||Kt(this.options.url),S.instances.set(this.id,this),S._watchTheme(),this.init(),setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,a=!1){let r=new CustomEvent(t,{bubbles:!0,cancelable:a,detail:i});return this.container.dispatchEvent(r),r}_requestSeek(t){this._emit("waveformplayer:request-seek",{...this._buildTrackDetail(),percent:t},!0).defaultPrevented||(this.progress=t,this.drawWaveform?.())}init(){this.createDOM(),this.createAudio(),this.initPlaybackSpeed(),this.initKeyboardControls(),this.initSeekControl(),this.bindEvents(),this.setupResizeObserver(),requestAnimationFrame(()=>{this.resizeCanvas(),this.options.url&&this.load(this.options.url).then(()=>{this.options.autoplay&&this.play()?.catch(()=>{})}).catch(t=>{console.error("[WaveformPlayer] Failed to load audio:",t)})})}createDOM(){this.container.innerHTML="",this.container.className="waveform-player";let t=this.options.buttonAlign;t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview"),this.container.classList.toggle("waveform-theme-light",this._scheme==="light");let i=[];this.options.buttonSize!=null&&i.push(`--wfp-btn-size: ${ct(this.options.buttonSize)}`),this.options.buttonRadius!=null&&i.push(`--wfp-btn-radius: ${ct(this.options.buttonRadius)}`);let a=i.length?` style="${i.join("; ")};"`:"",r=this.options.artworkPosition==="button"&&this.options.artwork,s=r?`<img class="waveform-btn-artwork" src="${L(this.options.artwork)}" alt="" aria-hidden="true">`:"",o=this.options.showControls?` | |
| 2 | - <button class="waveform-btn${this.options.buttonStyle==="minimal"?" waveform-btn-minimal":""}${r?" waveform-btn-has-artwork":""}" aria-label="${L(this.options.playPauseLabel)}"${a}> | |
| 1 | +import{store as Xe,getContext as F,getElement as Qe}from"@wordpress/interactivity";for(Pt={grad:.9,turn:360,rad:360/(2*Math.PI)},L=function(e){return typeof e=="string"?e.length>0:typeof e=="number"},S=function(e,t,i){return t===void 0&&(t=0),i===void 0&&(i=Math.pow(10,t)),Math.round(i*e)/i+0},A=function(e,t,i){return t===void 0&&(t=0),i===void 0&&(i=1),e>i?i:e>t?e:t},et=function(e){return(e=isFinite(e)?e%360:0)<0?e+360:e},G=function(e,t){return t===void 0&&(t=0),S(e,t)%360},Z=function(e){return{r:A(e.r,0,255),g:A(e.g,0,255),b:A(e.b,0,255),a:A(e.a)}},j=function(e){return{r:S(e.r),g:S(e.g),b:S(e.b),a:S(e.a,3)}},At=/^#([0-9a-f]{3,8})$/i,D=function(e,t){var i=e.charCodeAt(t);return(15&i)+9*(i>>6)},O=function(e,t){return D(e,t)<<4|D(e,t+1)},tt=[],$=0;$<256;$++)tt.push(($<16?"0":"")+$.toString(16));var Pt,L,S,A,et,G,Z,j,At,D,O,tt,$,U=function(e){return tt[A(e,0,255)]},Tt=function(e){var t=e.r,i=e.g,r=e.b,a=e.a,s=Math.max(t,i,r),o=s-Math.min(t,i,r),n=o?s===t?(i-r)/o:s===i?2+(r-t)/o:4+(t-i)/o:0;return{h:60*(n<0?n+6:n),s:s?o/s*100:0,v:s/255*100,a}},xt=function(e){var t=e.h,i=e.s,r=e.v,a=e.a;t=t/360*6,i/=100,r/=100;var s=Math.floor(t),o=r*(1-i),n=r*(1-(t-s)*i),l=r*(1-(1-t+s)*i),h=s%6;return{r:255*[r,n,o,o,l,r][h],g:255*[l,r,r,n,o,o][h],b:255*[o,o,l,r,r,n][h],a}},vt=function(e){return{h:et(e.h),s:A(e.s,0,100),l:A(e.l,0,100),a:A(e.a)}},gt=function(e){return{h:G(e.h),s:S(e.s),l:S(e.l),a:S(e.a,3)}},bt=function(e){return xt((i=(t=e).s,{h:t.h,s:(i*=((r=t.l)<50?r:100-r)/100)>0?2*i/(r+i)*100:0,v:r+i,a:t.a}));var t,i,r},H=function(e){return{h:(t=Tt(e)).h,s:(a=(200-(i=t.s))*(r=t.v)/100)>0&&a<200?i*r/100/(a<=100?a:200-a)*100:0,l:a/2,a:t.a};var t,i,r,a},ae=/^hsla?\(\s*([+-]?(?:\d*\.\d+|\d+))(deg|rad|grad|turn)?\s*,\s*([+-]?(?:\d*\.\d+|\d+))%\s*,\s*([+-]?(?:\d*\.\d+|\d+))%\s*(?:,\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s*)?\)$/i,se=/^hsla?\(\s*([+-]?(?:\d*\.\d+|\d+))(deg|rad|grad|turn)?\s+([+-]?(?:\d*\.\d+|\d+))%\s+([+-]?(?:\d*\.\d+|\d+))%\s*(?:\/\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s*)?\)$/i,oe=/^rgba?\(\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s*,\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s*,\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s*(?:,\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s*)?\)$/i,ne=/^rgba?\(\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s+([+-]?(?:\d*\.\d+|\d+))(%)?\s+([+-]?(?:\d*\.\d+|\d+))(%)?\s*(?:\/\s*([+-]?(?:\d*\.\d+|\d+))(%)?\s*)?\)$/i,wt={string:[[function(e){if(!At.test(e))return null;var t=e.length;return t<=5?{r:17*D(e,1),g:17*D(e,2),b:17*D(e,3),a:t===5?S(17*D(e,4)/255,2):1}:t===7||t===9?{r:O(e,1),g:O(e,3),b:O(e,5),a:t===9?S(O(e,7)/255,2):1}:null},"hex"],[function(e){var t=oe.exec(e)||ne.exec(e);return t?t[2]!==t[4]||t[4]!==t[6]?null:Z({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(e){var t=ae.exec(e)||se.exec(e);if(!t)return null;var i,r,a=vt({h:(i=t[1],r=t[2],r===void 0&&(r="deg"),Number(i)*(Pt[r]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)});return bt(a)},"hsl"]],object:[[function(e){var t=e.r,i=e.g,r=e.b,a=e.a,s=a===void 0?1:a;return L(t)&&L(i)&&L(r)?Z({r:Number(t),g:Number(i),b:Number(r),a:Number(s)}):null},"rgb"],[function(e){var t=e.h,i=e.s,r=e.l,a=e.a,s=a===void 0?1:a;if(!L(t)||!L(i)||!L(r))return null;var o=vt({h:Number(t),s:Number(i),l:Number(r),a:Number(s)});return bt(o)},"hsl"],[function(e){var t=e.h,i=e.s,r=e.v,a=e.a,s=a===void 0?1:a;if(!L(t)||!L(i)||!L(r))return null;var o=(function(n){return{h:et(n.h),s:A(n.s,0,100),v:A(n.v,0,100),a:A(n.a)}})({h:Number(t),s:Number(i),v:Number(r),a:Number(s)});return xt(o)},"hsv"]]},kt=function(e,t){for(var i=0;i<t.length;i++){var r=t[i][0](e);if(r)return[r,t[i][1]]}return[null,void 0]},le=function(e){return typeof e=="string"?kt(e.trim(),wt.string):typeof e=="object"&&e!==null?kt(e,wt.object):[null,void 0]};var Q=function(e,t){var i=H(e);return{h:i.h,s:A(i.s+100*t,0,100),l:i.l,a:i.a}},Y=function(e){return(299*e.r+587*e.g+114*e.b)/1e3/255},St=function(e,t){var i=H(e);return{h:i.h,s:i.s,l:A(i.l+100*t,0,100),a:i.a}},Et=(function(){function e(t){this.parsed=le(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return e.prototype.isValid=function(){return this.parsed!==null},e.prototype.brightness=function(){return S(Y(this.rgba),2)},e.prototype.isDark=function(){return Y(this.rgba)<.5},e.prototype.isLight=function(){return Y(this.rgba)>=.5},e.prototype.toHex=function(){return t=j(this.rgba),i=t.r,r=t.g,a=t.b,o=(s=t.a)<1?U(S(255*s)):"","#"+U(i)+U(r)+U(a)+o;var t,i,r,a,s,o},e.prototype.toRgb=function(){return j(this.rgba)},e.prototype.toRgbString=function(){return t=j(this.rgba),i=t.r,r=t.g,a=t.b,(s=t.a)<1?"rgba("+i+", "+r+", "+a+", "+s+")":"rgb("+i+", "+r+", "+a+")";var t,i,r,a,s},e.prototype.toHsl=function(){return gt(H(this.rgba))},e.prototype.toHslString=function(){return t=gt(H(this.rgba)),i=t.h,r=t.s,a=t.l,(s=t.a)<1?"hsla("+i+", "+r+"%, "+a+"%, "+s+")":"hsl("+i+", "+r+"%, "+a+"%)";var t,i,r,a,s},e.prototype.toHsv=function(){return t=Tt(this.rgba),{h:G(t.h),s:S(t.s),v:S(t.v),a:S(t.a,3)};var t},e.prototype.invert=function(){return k({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},e.prototype.saturate=function(t){return t===void 0&&(t=.1),k(Q(this.rgba,t))},e.prototype.desaturate=function(t){return t===void 0&&(t=.1),k(Q(this.rgba,-t))},e.prototype.grayscale=function(){return k(Q(this.rgba,-1))},e.prototype.lighten=function(t){return t===void 0&&(t=.1),k(St(this.rgba,t))},e.prototype.darken=function(t){return t===void 0&&(t=.1),k(St(this.rgba,-t))},e.prototype.rotate=function(t){return t===void 0&&(t=15),this.hue(H(this.rgba).h+t)},e.prototype.alpha=function(t){return typeof t=="number"?k({r:(i=this.rgba).r,g:i.g,b:i.b,a:t}):S(this.rgba.a,3);var i},e.prototype.hue=function(t){var i=H(this.rgba);return typeof t=="number"?k({h:t,s:i.s,l:i.l,a:i.a}):G(i.h)},e.prototype.isEqual=function(t){return this.toHex()===k(t).toHex()},e})(),k=function(e){return e instanceof Et?e:new Et(e)};function qt(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function M(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ct(e){return M(typeof e=="number"?`${e}px`:e)}function he(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 b(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function J(e,t=null,i={}){let{min:r=-1/0,max:a=1/0,integer:s=!1}=i,o=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;if(!Number.isFinite(o))return t;let n=b(o,r,a);return s?Math.round(n):n}function lt(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 ht(e,t={}){let{min:i=-1/0,max:r=1/0,fallback:a=null}=t,s=lt(e);if(!s&&typeof e=="string"&&e.trim()!==""&&(s=e.split(/[,\s]+/)),!s)return a;let o=s.map(n=>J(n)).filter(n=>n!==null&&n>=i&&n<=r);return o.length?o:a}function ue(e,t,i=null){return t.includes(e)?e:i}function de(e){if(typeof e=="string"){let t=e.trim().toLowerCase();return t!==""&&t!=="false"&&t!=="0"}return!!e}function ce(e){return e===void 0?void 0:e==="true"}function Lt(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function Ft(e){let t={},i=(o,n=o)=>{let l=ce(e.dataset[n]);l!==void 0&&(t[o]=l)},r=(o,n=o,l=!1)=>{let h=e.dataset[n];h&&(t[o]=l?parseFloat(h):parseInt(h,10))},a=(o,n=o)=>{let l=e.dataset[n];l&&(t[o]=/^\d+(\.\d+)?$/.test(l.trim())?parseFloat(l):l)},s=(o,n=o)=>{let l=e.dataset[n];if(!l)return;let h=lt(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),r("height"),r("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),r("barWidth"),r("barSpacing"),r("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),a("buttonSize"),a("buttonRadius"),e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=Lt(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=Lt(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"),r("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),s("markers"),r("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),e.dataset.playbackRates){let o=ht(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),t}function pe(e,...t){let i=0;return e.replace(/%(?:(\d+)\$)?s/g,(r,a)=>{let s=a?Number(a)-1:i++;return t[s]??r})}function R(e){let t=Number(e);if(!t||!Number.isFinite(t)||t<0)return"0:00";let i=Math.floor(t/3600),r=Math.floor(t%3600/60),a=Math.floor(t%60);return i>0?`${i}:${r.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`:`${r}:${a.toString().padStart(2,"0")}`}var me=0;function fe(e){let t=e||"audio",i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return`wp_${(i>>>0).toString(36)}_${(me++).toString(36)}`}function zt(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,i=>i.toUpperCase())}function Ut(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]),r=Number(t[2]),a=Number(t[3]);if(!Number.isFinite(i)||!Number.isFinite(r)||!Number.isFinite(a))return null;let s=t[4]===void 0?1:Number(t[4]);return Number.isFinite(s)?(t[5]==="%"&&(s/=100),{r:i,g:r,b:a,a:b(s,0,1)}):null}function ye(e){let t=Ut(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function Mt(...e){let t={};for(let i of e)for(let r in i)i[r]!==null&&i[r]!==void 0&&(t[r]=i[r]);return t}function ve(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}function K(e,t){if(e.length===t)return e;if(e.length===0||t===0)return[];let i=[];if(t>e.length){let r=(e.length-1)/(t-1);for(let a=0;a<t;a++){let s=a*r,o=Math.floor(s),n=Math.ceil(s),l=s-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 r=e.length/t;for(let a=0;a<t;a++){let s=Math.floor(a*r),o=Math.floor((a+1)*r),n=0,l=0;for(let h=s;h<=o&&h<e.length;h++)e[h]>n&&(n=e[h]),l++;if(l===0){let h=Math.min(Math.round(a*r),e.length-1);n=e[h]}i.push(n)}}return i}function x(e,t,i,r){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let a=i.width,s=i.height,o=r&&r.waveformGradient,[n,l,h,u]=o==="horizontal"?[0,0,a,0]:o==="diagonal"?[0,0,a,s]:[0,0,0,s];try{let c=e.createLinearGradient(n,l,h,u);return t.forEach((p,y)=>c.addColorStop(y/(t.length-1),p)),c}catch{return t[0]}}function B(e,t,i,r,a,s){if((Array.isArray(s)?s.some(o=>o>0):s>0)&&typeof e.roundRect=="function"){let o=Math.min(r/2,Math.abs(a)/2),n=l=>b(l,0,o);e.beginPath(),e.roundRect(t,i,r,a,Array.isArray(s)?s.map(n):n(s)),e.fill()}else e.fillRect(t,i,r,a)}function jt(e,t){return(e.barRadius||0)*t}function ge(e,t){let i=jt(e,t);return[i,i,0,0]}function _t(e,t,i,r,a){let s=a/2;e.beginPath(),e.moveTo(t,r-s),e.lineTo(i-s,r-s),e.arc(i-s,r,s,-Math.PI/2,Math.PI/2),e.lineTo(t,r+s),e.arc(t,r,s,Math.PI/2,-Math.PI/2),e.closePath()}function it(e,t,i,r,a){let s=window.devicePixelRatio||1,o=a.barWidth*s,n=a.barSpacing*s,l=Math.floor(t.width/(o+n)),h=K(i,l),u=t.height,c=r*t.width,p=ge(a,s),y=x(e,a.color,t,a),g=x(e,a.progressColor,t,a);e.clearRect(0,0,t.width,t.height),e.fillStyle=y;for(let m=0;m<h.length;m++){let f=m*(o+n);if(f+o>t.width)break;let v=h[m]*u*.9,d=u-v;B(e,f,d,o,v,p)}e.save(),e.beginPath(),e.rect(0,0,c,u),e.clip(),e.fillStyle=g;for(let m=0;m<h.length;m++){let f=m*(o+n);if(f>c)break;let v=h[m]*u*.9,d=u-v;B(e,f,d,o,v,p)}e.restore()}function be(e,t,i,r,a){let s=window.devicePixelRatio||1,o=a.barWidth*s,n=a.barSpacing*s,l=Math.floor(t.width/(o+n)),h=K(i,l),u=t.height,c=u/2,p=r*t.width,y=jt(a,s),g=[y,y,0,0],m=[0,0,y,y],f=x(e,a.color,t,a),v=x(e,a.progressColor,t,a);e.clearRect(0,0,t.width,t.height),e.fillStyle=f;for(let d=0;d<h.length;d++){let E=d*(o+n);if(E+o>t.width)break;let P=h[d]*u*.45;B(e,E,c-P,o,P,g),B(e,E,c,o,P,m)}e.save(),e.beginPath(),e.rect(0,0,p,u),e.clip(),e.fillStyle=v;for(let d=0;d<h.length;d++){let E=d*(o+n);if(E>p)break;let P=h[d]*u*.45;B(e,E,c-P,o,P,g),B(e,E,c,o,P,m)}e.restore()}function we(e,t,i,r,a){let s=t.width,o=t.height,n=o/2,l=o*.35;e.clearRect(0,0,s,o);let h=(u,c,p=1,y=!1)=>{let g=x(e,u,t,a),m=Array.isArray(u)?u[u.length-1]:u;y&&(e.shadowBlur=12,e.shadowColor=m),e.strokeStyle=g,e.lineWidth=c,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,n);let f=[],v=Math.floor(i.length*p);for(let d=0;d<v;d++){let E=d/(i.length-1)*s,P=i[d],C=Math.sin(d*.1)*P,_=n+C*l;f.push({x:E,y:_})}for(let d=0;d<f.length-1;d++){let E=f[d].x+(f[d+1].x-f[d].x)*.5,P=f[d].y,C=f[d+1].x-(f[d+1].x-f[d].x)*.5,_=f[d+1].y;e.bezierCurveTo(E,P,C,_,f[d+1].x,f[d+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(s,n),e.stroke();for(let u=0;u<=10;u++){let c=s/10*u;e.beginPath(),e.moveTo(c,0),e.lineTo(c,o),e.stroke()}h(a.color,2,1,!1),r>0&&h(a.progressColor,3,r,!0)}function Rt(e,t,i,r,a){let s=window.devicePixelRatio||1,o=(a.barWidth||3)*s,n=(a.barSpacing||1)*s,l=Math.floor(t.width/(o+n)),h=K(i,l),u=t.height,c=4*s,p=2*s,y=r*t.width,g=u/2,m=x(e,a.color,t,a),f=x(e,a.progressColor,t,a);e.clearRect(0,0,t.width,t.height);for(let v=0;v<h.length;v++){let d=v*(o+n);if(d+o>t.width)break;let E=h[v]*u*.9,P=Math.floor(E/(c+p));e.fillStyle=d<y?f:m;for(let C=0;C<P;C++){let _=C*(c+p);e.fillRect(d,g-_-c,o,c),C>0&&e.fillRect(d,g+_,o,c)}}}function Dt(e,t,i,r,a){let s=window.devicePixelRatio||1,o=(a.barWidth||2)*s,n=(a.barSpacing||3)*s,l=Math.floor(t.width/(o+n)),h=K(i,l),u=t.height,c=Math.max(1.5*s,o/2),p=r*t.width,y=u/2,g=x(e,a.color,t,a),m=x(e,a.progressColor,t,a);e.clearRect(0,0,t.width,t.height);for(let f=0;f<h.length;f++){let v=f*(o+n)+o/2;if(v>t.width)break;let d=h[f]*u*.9;e.fillStyle=v<p?m:g,e.beginPath(),e.arc(v,y-d/2,c,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(v,y+d/2,c,0,Math.PI*2),e.fill()}}function ke(e,t,i,r,a){let s=t.width,o=t.height,n=o/2,l=4,h=l/2,u=!!a.seekActive;if(e.clearRect(0,0,s,o),e.fillStyle=x(e,a.color,t,a)||"rgba(255, 255, 255, 0.2)",_t(e,h,s,n,l),e.fill(),r>0){let c=Math.max(h*2,r*s);e.save(),e.globalAlpha=a.seekHandle&&!u?.7:1,e.fillStyle=x(e,a.progressColor,t,a)||"rgba(255, 255, 255, 0.9)",_t(e,h,c,n,l),e.fill(),e.restore()}}var Se={bars:it,bar:it,mirror:be,line:we,blocks:Rt,block:Rt,dots:Dt,dot:Dt,seekbar:ke};function Ee(e,t,i,r,a){(Se[a.waveformStyle]||it)(e,t,i,r,a)}function Pe(e){try{let t=e.getChannelData(0),i=e.sampleRate,r=Ae(t,i);if(r.length<2)return 120;let a=[];for(let l=1;l<r.length;l++)a.push((r[l]-r[l-1])/i);let s={};a.forEach(l=>{let h=60/l,u=Math.round(h/3)*3;u>60&&u<200&&(s[u]=(s[u]||0)+1)});let o=0,n=120;for(let[l,h]of Object.entries(s))h>o&&(o=h,n=parseInt(l));return n<70&&s[n*2]?n*=2:n>160&&s[Math.round(n/2)]&&(n=Math.round(n/2)),n-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function Ae(e,t){let i=[],r=0;for(let a=0;a<e.length-2048;a+=1024){let s=0;for(let l=a;l<a+2048;l++)s+=e[l]*e[l];s=s/2048;let o=s-r,n=r*1.8+.01;if(o>n&&s>.01){let l=i[i.length-1]||0,h=t*.15;a-l>h&&i.push(a)}r=s*.8+r*.2}return i}function Te(e,t=1800){let i=e.length/t,r=e.numberOfChannels,a=[];for(let o=0;o<r;o++){let n=e.getChannelData(o);for(let l=0;l<t;l++){let h=~~(l*i),u=~~(h+i),c=0,p=0;for(let g=h;g<u;g++){let m=n[g];m>p&&(p=m),m<c&&(c=m)}let y=Math.max(Math.abs(p),Math.abs(c));(o===0||y>a[l])&&(a[l]=y)}}let s=qt(a);return s>0?a.map(o=>o/s):a}async function Ht(e,t=1800,i=!1){let r;try{let a=window.AudioContext||window.webkitAudioContext;r=new a;let s=await(await fetch(e)).arrayBuffer(),o=await r.decodeAudioData(s),n=Te(o,t);n=Ce(n);let l=null;return i&&(l=Pe(o)),{peaks:n,bpm:l}}finally{r&&r.close()}}function xe(e=1800){let t=[];for(let i=0;i<e;i++){let r=Math.random()*.5+.3,a=Math.sin(i/e*Math.PI*4)*.2;t.push(b(r+a,.1,1))}return t}function Ce(e,t=.95){let i=qt(e);if(i===0||i>t)return e;let r=t/i;return e.map(a=>a*r)}var rt=128;function Bt(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 Le(e){let t=0,i=0;for(let r=e;r&&r.nodeType===1&&i<.995;r=r.parentElement){let a=Ut(getComputedStyle(r).backgroundColor);if(!a||a.a<=0)continue;let s=a.a*(1-i);t+=(a.r*299+a.g*587+a.b*114)/1e3*s,i+=s}return{sum:t,alpha:i}}function Me(){let e=ye(getComputedStyle(document.body).color);if(e!==null)return e>rt?"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 V(e){if(Bt("dark"))return"dark";if(Bt("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:r}=Le(t),a=Me(),s=i+(a==="dark"?0:255)*(1-r);return s>rt?"light":s<rt?"dark":a}catch{return"dark"}}var W={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 Wt(e,t){if(e&&W[e])return W[e];let i=V(t);return W[i]}var at={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},Gt={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}},Vt=["auto","top","center","bottom"],ut=.25,dt=4,_e={buttonAlign:Vt,layout:["default","preview"],buttonStyle:["circle","minimal"],artworkPosition:["info","button"],waveformStyle:Object.keys(Gt),waveformGradient:["vertical","horizontal","diagonal"],audioMode:["self","external"],preload:["none","metadata","auto"],colorPreset:Object.keys(W),crossOrigin:["anonymous","use-credentials"]},Re={height:{min:1,integer:!0},samples:{min:1,integer:!0},barWidth:{min:0},barSpacing:{min:0},barRadius:{min:0},bpm:{min:1},playbackRate:{min:ut,max:dt}},De=["autoplay","showControls","showInfo","showTime","showHoverTime","seekHandle","showBPM","singlePlay","playOnSeek","enableMediaSession","showMarkers","accessibleSeek","showPlaybackSpeed"],He=["onLoad","onPlay","onPause","onEnd","onError","onTimeUpdate","onNextTrack","onPreviousTrack"];function st(e,t){console.warn(`[WaveformPlayer] Invalid ${e} option, using default:`,t)}function ot(e){let t=lt(e);return t?t.reduce((i,r)=>{let a=r&&typeof r=="object"?J(r.time,null,{min:0}):null;return a===null?(st("marker",r),i):(i.push({...r,time:a,label:r.label==null?"":r.label}),i)},[]):(e!=null&&st("markers",e),[])}function It(e){let t=r=>e[r]!=null,i=r=>{st(r,e[r]),e[r]=at[r]};for(let[r,a]of Object.entries(Re)){if(!t(r))continue;let s=J(e[r],null,a);s===null?i(r):e[r]=s}for(let[r,a]of Object.entries(_e))t(r)&&ue(e[r],a)===null&&i(r);for(let r of De)e[r]=de(e[r]);for(let r of He)t(r)&&typeof e[r]!="function"&&i(r);if(t("playbackRates")){let r=ht(e.playbackRates,{min:ut,max:dt,fallback:null});r===null?i("playbackRates"):e.playbackRates=r}e.markers=ot(e.markers);for(let r of["buttonSize","buttonRadius"]){if(!t(r))continue;let a=e[r];(typeof a=="number"?Number.isFinite(a):typeof a=="string"&&a.trim()!=="")||i(r)}for(let r of["waveformColor","progressColor"]){if(!t(r))continue;let a=e[r];!(typeof a=="string"&&a.trim()!=="")&&!Array.isArray(a)&&i(r)}return e}var Be="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>'),Nt=5,$t=10,We='button, a[href], input, [role="slider"]',I=class w{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 r=Ft(this.container),a={...i};a.style&&!a.waveformStyle&&(a.waveformStyle=a.style),a.src&&!a.url&&(a.url=a.src),this.options=It(Mt(at,r,a));let s=Wt(this.options.colorPreset,this.container);this._autoTheme=this.options.colorPreset==null||!W[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&W[this.options.colorPreset]?this.options.colorPreset:V(this.container);for(let[n,l]of Object.entries(s))(this.options[n]===null||this.options[n]===void 0)&&(this.options[n]=l,this._presetKeys.push(n));let o=Gt[this.options.waveformStyle];o&&(r.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=o.barWidth),r.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||fe(this.options.url),w.instances.set(this.id,this),w._watchTheme();try{this.init()}catch(n){throw w.instances.delete(this.id),this._ac.abort(),n}setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,r=!1){let a=new CustomEvent(t,{bubbles:!0,cancelable:r,detail:i});return this.container.dispatchEvent(a),a}_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=Vt.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 i=[];this.options.buttonSize!=null&&i.push(`--wfp-btn-size: ${Ct(this.options.buttonSize)}`),this.options.buttonRadius!=null&&i.push(`--wfp-btn-radius: ${Ct(this.options.buttonRadius)}`);let r=i.length?` style="${i.join("; ")};"`:"",a=this.options.artworkPosition==="button"&&this.options.artwork,s=a?`<img class="waveform-btn-artwork" src="${M(this.options.artwork)}" alt="" aria-hidden="true">`:"",o=this.options.showControls?` | |
| 2 | + <button class="waveform-btn${this.options.buttonStyle==="minimal"?" waveform-btn-minimal":""}${a?" waveform-btn-has-artwork":""}" aria-label="${M(this.options.playPauseLabel)}"${r}> | |
| 3 | 3 | ${s} |
| 4 | 4 | <span class="waveform-icon-play">${this.options.playIcon}</span> |
| 5 | 5 | <span class="waveform-icon-pause" style="display:none;">${this.options.pauseIcon}</span> |
| 6 | 6 | </button> |
| 7 | - `:"",l=this.options.showInfo?` | |
| 7 | + `:"",n=this.options.showInfo?` | |
| 8 | 8 | <div class="waveform-info"> |
| 9 | 9 | ${this.options.artworkPosition!=="button"&&this.options.artwork?` |
| 10 | - <img class="waveform-artwork" src="${L(this.options.artwork)}" alt="${L(this.options.artworkAlt)}" style=" | |
| 10 | + <img class="waveform-artwork" src="${M(this.options.artwork)}" alt="${M(this.options.artworkAlt)}" style=" | |
| 11 | 11 | width: 40px; |
| 12 | 12 | height: 40px; |
| 13 | 13 | border-radius: 4px; |
| 14 | 14 | object-fit: cover; |
| @@ -16,9 +16,9 @@ | ||
| 16 | 16 | "> |
| 17 | 17 | `:""} |
| 18 | 18 | <div class="waveform-text"> |
| 19 | 19 | <span class="waveform-title"></span> |
| 20 | - ${this.options.artist?`<span class="waveform-artist">${L(this.options.artist)}</span>`:""} | |
| 20 | + ${this.options.artist?`<span class="waveform-artist">${M(this.options.artist)}</span>`:""} | |
| 21 | 21 | </div> |
| 22 | 22 | <div class="waveform-meta" style="display: flex; align-items: center; gap: 1rem;"> |
| 23 | 23 | ${this.options.showBPM?` |
| 24 | 24 | <span class="waveform-bpm" style="display: none;"> |
| @@ -26,13 +26,13 @@ | ||
| 26 | 26 | </span> |
| 27 | 27 | `:""} |
| 28 | 28 | ${this.options.showPlaybackSpeed?` |
| 29 | 29 | <div class="waveform-speed"> |
| 30 | - <button class="speed-btn" aria-label="${L(this.options.speedLabel)}" aria-haspopup="menu" aria-expanded="false"> | |
| 30 | + <button class="speed-btn" aria-label="${M(this.options.speedLabel)}" aria-haspopup="menu" aria-expanded="false"> | |
| 31 | 31 | <span class="speed-value">1x</span> |
| 32 | 32 | </button> |
| 33 | - <div class="speed-menu" role="menu" aria-label="${L(this.options.speedLabel)}" style="display: none;"> | |
| 34 | - ${this.options.playbackRates.map(n=>`<button class="speed-option" role="menuitemradio" tabindex="-1" aria-checked="false" data-rate="${n}">${n}x</button>`).join("")} | |
| 33 | + <div class="speed-menu" role="menu" aria-label="${M(this.options.speedLabel)}" style="display: none;"> | |
| 34 | + ${this.options.playbackRates.map(l=>`<button class="speed-option" role="menuitemradio" tabindex="-1" aria-checked="false" data-rate="${l}">${l}x</button>`).join("")} | |
| 35 | 35 | </div> |
| 36 | 36 | </div> |
| 37 | 37 | `:""} |
| 38 | 38 | ${this.options.showTime?` |
| @@ -52,14 +52,14 @@ | ||
| 52 | 52 | <canvas></canvas> |
| 53 | 53 | <div class="waveform-markers"></div> |
| 54 | 54 | <div class="waveform-loading" style="display:none;"></div> |
| 55 | 55 | <div class="waveform-error" style="display:none;" role="alert"> |
| 56 | - <span class="waveform-error-text">${L(this.options.errorText)}</span> | |
| 56 | + <span class="waveform-error-text">${M(this.options.errorText)}</span> | |
| 57 | 57 | </div> |
| 58 | 58 | </div> |
| 59 | 59 | </div> |
| 60 | 60 | |
| 61 | - ${l} | |
| 61 | + ${n} | |
| 62 | 62 | </div> |
| 63 | 63 | </div> |
| 64 | -`,this.playBtn=this.container.querySelector(".waveform-btn"),this.canvas=this.container.querySelector("canvas"),this.ctx=this.canvas.getContext("2d"),this.titleEl=this.container.querySelector(".waveform-title"),this.artistEl=this.container.querySelector(".waveform-artist"),this.artworkEl=this.container.querySelector(".waveform-artwork, .waveform-btn-artwork"),this.bindArtworkFallback(this.artworkEl),this.currentTimeEl=this.container.querySelector(".time-current"),this.totalTimeEl=this.container.querySelector(".time-total"),this.bpmEl=this.container.querySelector(".waveform-bpm"),this.bpmValueEl=this.container.querySelector(".bpm-value"),this.loadingEl=this.container.querySelector(".waveform-loading"),this.errorEl=this.container.querySelector(".waveform-error"),this.markersContainer=this.container.querySelector(".waveform-markers"),this.speedBtn=this.container.querySelector(".speed-btn"),this.speedMenu=this.container.querySelector(".speed-menu"),this.resizeCanvas(),this.updateBPMDisplay()}bindArtworkFallback(t){t&&t.addEventListener("error",()=>{t.src.startsWith("data:")||(t.src=ue)},{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 a=this.container.querySelector(".waveform-text");if(!a)return;this.artworkEl=this.createArtworkElement(),a.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 a=()=>Array.from(i.querySelectorAll(".speed-option")),r=()=>i.style.display!=="none",s=n=>{if(i.style.display=n?"block":"none",t.setAttribute("aria-expanded",n?"true":"false"),n){let h=a();(h.find(u=>u.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=n=>{let h=a();h.length&&h[(n+h.length)%h.length].focus()},l=n=>{this.setPlaybackRate(parseFloat(n.dataset.rate)),s(!1),t.focus()};t.addEventListener("click",n=>{n.stopPropagation(),s(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>s(!1),{signal:this._ac.signal}),i.addEventListener("click",n=>{n.stopPropagation();let h=n.target.closest(".speed-option");h&&l(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",n=>{let h=a(),u=h.indexOf(document.activeElement);if(!r()){(n.key==="ArrowDown"||n.key==="ArrowUp")&&document.activeElement===t&&(n.preventDefault(),s(!0));return}switch(n.key){case"ArrowDown":n.preventDefault(),o(u<0?0:u+1);break;case"ArrowUp":n.preventDefault(),o(u<0?h.length-1:u-1);break;case"Home":n.preventDefault(),o(0);break;case"End":n.preventDefault(),o(h.length-1);break;case"Escape":n.preventDefault(),s(!1),t.focus();break;case"Tab":s(!1);break}},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(de)||(S.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,a=!!this.audio,r=a?this.audio.currentTime:0;if(a&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let s={" ":()=>this.togglePlay()};a&&(s.ArrowLeft=()=>this.seekTo(w(r-5,0,this.audio.duration)),s.ArrowRight=()=>this.seekTo(w(r+5,0,this.audio.duration)),s.ArrowUp=()=>this.setVolume(w(this.audio.volume+.1)),s.ArrowDown=()=>this.setVolume(w(this.audio.volume-.1)),s.m=s.M=()=>this.audio.muted=!this.audio.muted),s[i]&&(t.preventDefault(),s[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 a=this.getSeekCurrentTime(),r;switch(t.key){case"ArrowLeft":case"ArrowDown":r=a-St;break;case"ArrowRight":case"ArrowUp":r=a+St;break;case"PageDown":r=a-Et;break;case"PageUp":r=a+Et;break;case"Home":r=0;break;case"End":r=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(r)},{signal:this._ac.signal})))}getSeekDuration(){return this.options.audioMode==="external"?this._extDuration||0:this.audio&&Number.isFinite(this.audio.duration)?this.audio.duration:0}getSeekCurrentTime(){return this.options.audioMode==="external"?this.progress*(this._extDuration||0):this.audio&&Number.isFinite(this.audio.currentTime)?this.audio.currentTime:0}seekToSeconds(t){let i=this.getSeekDuration();if(!i)return;let a=w(t,0,i);if(this.options.audioMode==="external"){this._requestSeek(a/i),this.updateSeekAccessibility();return}this.seekTo(a)}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",Vt(this.options.seekValueText||"%1$s of %2$s",I(i),I(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(w(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(w(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",a=>{a.seekTime!==null&&this.seekTo(a.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:w(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 a=this.canvas.getBoundingClientRect();a.width&&(this._handleNear=Math.abs(i.clientX-a.left-this.progress*a.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=Qt(()=>this.resizeCanvas(),100),window.addEventListener("resize",this.resizeHandler)}setupResizeObserver(){"ResizeObserver"in window&&(this.resizeObserver=new ResizeObserver(()=>{this.resizeCanvas()}),this.canvas?.parentElement&&this.resizeObserver.observe(this.canvas.parentElement))}async load(t){try{this.setLoading(!0),this.progress=0,this.hasError=!1,this.audio&&(this.audio.src=t,await new Promise((a,r)=>{let s=()=>{this.audio.removeEventListener("loadedmetadata",s),this.audio.removeEventListener("error",o),a()},o=l=>{this.audio.removeEventListener("loadedmetadata",s),this.audio.removeEventListener("error",o),r(l)};this.audio.addEventListener("loadedmetadata",s),this.audio.addEventListener("error",o)}));let i=this.options.title||Tt(t);if(this.titleEl&&(this.titleEl.textContent=i),this.applySeekLabel(i),this.options.waveform)this.setWaveformData(this.options.waveform);else try{let a=await gt(t,this.options.samples,this.options.showBPM);this.waveformData=a.peaks,a.bpm&&(this.detectedBPM=a.bpm,this.updateBPMDisplay())}catch(a){console.warn("[WaveformPlayer] Using placeholder waveform:",a),this.waveformData=ne(this.options.samples)}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,a=null,r={}){let s=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=mt(this.options,{url:t,title:i===null?this.options.title:i,artist:a===null?this.options.artist:a,...r}),s&&(this.options.artwork=r.artwork||null),o?this.options.artworkAlt=r.artworkAlt||"":s&&(this.options.artworkAlt=this.options.artwork?kt.artworkAlt:""),r.preload&&this.audio&&(this.audio.preload=r.preload),r.crossOrigin&&this.audio&&(this.audio.crossOrigin=r.crossOrigin),a!==null&&this.syncArtist(a),(s||o)&&this.syncArtwork(s?r.artwork:this.options.artwork,o?r.artworkAlt:this.options.artworkAlt),this.options.markers=r.markers||[],this.options.waveform=r.waveform||null,await this.load(t),r.autoplay!==!1&&this.play()?.catch(()=>{})}setWaveformData(t){if(typeof t=="string"&&t.trim().endsWith(".json")){fetch(t.trim()).then(i=>i.json()).then(i=>{this.waveformData=Array.isArray(i)?i:i.peaks||[],i.markers&&!this.options.markers?.length&&(this.options.markers=i.markers,this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}if(typeof t=="string")try{let i=JSON.parse(t);this.waveformData=Array.isArray(i)?i:[]}catch{this.waveformData=t.split(",").map(Number)}else this.waveformData=Array.isArray(t)?t:[];this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||ae(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,a)=>{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,s=document.createElement("button");s.className="waveform-marker",s.style.left=`${r}%`,s.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",s.setAttribute("aria-label",i.label),s.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,s.appendChild(o),s.addEventListener("click",l=>{l.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(s)})}setActiveMarker(t){this.markersContainer&&this.markersContainer.querySelectorAll(".waveform-marker").forEach((i,a)=>i.classList.toggle("active",a===t))}updateActiveMarker(){if(!this.markersContainer)return;let t=this.markersContainer.querySelectorAll(".waveform-marker");if(!t.length)return;let i=this.getSeekDuration(),a=i?this.progress*i:0,r=-1,s=-1/0;t.forEach((o,l)=>{let n=parseFloat(o.getAttribute("data-time"));Number.isFinite(n)&&n<=a+.05&&n>s&&(s=n,r=l)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,l)=>o.classList.toggle("show-label",l===r)),r>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(o=>o.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.seekEl)return;let t=document.createElement("div");t.className="waveform-hover-time",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.hoverTimeEl=t,this.options.showHoverTime&&(this.seekEl.addEventListener("pointermove",i=>{this._dragging||this._updateHoverTip(i.clientX)}),this.seekEl.addEventListener("pointerleave",()=>{this._dragging||this._hideHoverTip()}))}_updateHoverTip(t){let i=this.hoverTimeEl;if(!i)return;let a=this.getSeekDuration();if(!a){i.style.opacity="0";return}let r=this.canvas.getBoundingClientRect(),s=w((t-r.left)/r.width);i.textContent=I(s*a),i.style.left=s*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=w((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle();let a=this.getSeekDuration();a&&this.currentTimeEl?(this.currentTimeEl.textContent=I(this.progress*a),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 a=w((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(a);return}!this.audio||!this.audio.duration||this.seekToPercent(a)}setLoading(t){this.isLoading=t,this.loadingEl&&(this.loadingEl.style.display=t?"block":"none"),this.seekEl&&this.seekEl.setAttribute("aria-busy",t?"true":"false")}onMetadataLoaded(){this.isDestroying||(this.totalTimeEl&&(this.totalTimeEl.textContent=I(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"),a=this.playBtn.querySelector(".waveform-icon-pause");i&&(i.style.display=t?"none":"flex"),a&&(a.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=I(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=J();let t=wt(this.options.colorPreset);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(S._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{S.instances.forEach(s=>{try{s.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},a=new MutationObserver(t);a.observe(document.documentElement,i),document.body&&a.observe(document.body,i);let r=null;try{r=window.matchMedia("(prefers-color-scheme: dark)"),r.addEventListener("change",t)}catch{}S._themeWatch={obs:a,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 a=parseFloat(i.dataset.rate)===this.audio.playbackRate;i.classList.toggle("active",a),i.setAttribute("aria-checked",a?"true":"false")})}play(){if(this.options.singlePlay&&S.currentlyPlaying&&S.currentlyPlaying!==this&&S.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(S.currentlyPlaying=this);return}return S.currentlyPlaying=this,this.audio.play()}pause(){if(S.currentlyPlaying===this&&(S.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=w(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=I(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=I(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=w(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*w(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=w(i))}setPlaybackRate(t){if(!this.audio)return;let i=w(t,.5,2);this.audio.playbackRate=i,this.options.playbackRate=i,this.updateSpeedUI()}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.pause(),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),this._ac?.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),S.instances.delete(this.id),S.currentlyPlaying===this&&(S.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 a=document.getElementById(t);if(a)return Array.from(this.instances.values()).find(r=>r.container===a)}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 gt(t,i)).peaks}catch(a){throw console.error("[WaveformPlayer] Failed to generate waveform:",a),a}}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}};W.utils={formatTime:I,extractTitleFromUrl:Tt,escapeHtml:L,isSafeHref:jt,parseDataAttributes:At};var X=()=>typeof window<"u"&&typeof document<"u";function K(){X()&&document.querySelectorAll("[data-waveform-player]").forEach(e=>{if(e.dataset.waveformInitialized!=="true")try{new W(e),e.dataset.waveformInitialized="true"}catch(t){console.error("[WaveformPlayer] Failed to initialize:",t,e)}})}X()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",K):K());W.init=K;X()&&(window.WaveformPlayer=W);var Ct=W;var ce=100,pe="Seek";function _t(e){return e.ownerDocument.defaultView.getComputedStyle(e)}function It(e){let t=e?.trim().match(/^[\w-]+-gradient\((.*)\)$/i);if(!t)return[];let i=[],a=0,r="";for(let s of t[1]){if(s==="("?++a:s===")"&&--a,s===","&&a===0){i.push(r.trim()),r="";continue}r+=s}return r.trim()&&i.push(r.trim()),i}function me(e){let t=e.match(/^([\w-]+)\(/);if(!t||!["color","color-mix","hsl","hsla","hwb","lab","lch","oklab","oklch","rgb","rgba","var"].includes(t[1].toLowerCase()))return;let a=0,r=!1;for(let s=0;s<e.length;s++){let o=e[s];if(o==="("?(r=!0,++a):o===")"&&--a,r&&a===0)return e.slice(0,s+1)}}function fe(e){let t=me(e);if(t)return t;let[i]=e.split(/\s+/);if(k(i).isValid())return i}function ye(e){let i=It(e)[0],a=i?.match(/^(-?\d+(?:\.\d+)?)deg$/i);if(a){let l=(Number(a[1])%360+360)%360;return l===90||l===270?"horizontal":l===0||l===180?"vertical":"diagonal"}if(!i?.startsWith("to "))return;let r=i.toLowerCase().replace(/^to\s+/,""),s=r.includes("left")||r.includes("right"),o=r.includes("top")||r.includes("bottom");if(s&&o)return"diagonal";if(s)return"horizontal";if(o)return"vertical"}function ve(e,t){if(!t||k(t).isValid())return t;let i=e.ownerDocument.createElement("span");if(i.style.color=t,!i.style.color)return t;e.appendChild(i);let a=_t(i).color;return i.remove(),a&&k(a).isValid()?a:t}function Q(e,t){let i=ge(t)?.map(a=>ve(e,a)).filter(a=>k(a).isValid());return i?.length>1?i:void 0}function Lt(e,t){return Array.isArray(e)?e.map(i=>k(i).alpha(t).toRgbString()):k(e).alpha(t).toRgbString()}function Dt(e){return Array.isArray(e)?e[e.length-1]:e}function ge(e){let t=It(e).map(fe).filter(Boolean);return t.length>1?t:void 0}function Mt(e){return Array.isArray(e)?JSON.stringify(e):e}function be(e,t,i,a){let r=i||_t(e).color,s=Q(e,a),o=s||t||r,l=Lt(o,.3),n=Lt(o,.6),h=s?ye(a):void 0;return{textColor:r,waveformColor:l,progressColor:n,...h&&{waveformGradient:h}}}function we({url:e,title:t,artist:i,artwork:a,waveformColor:r,progressColor:s,waveformGradient:o,buttonColor:l,seekLabel:n,seekValueText:h,height:u=ce,waveformStyle:c="bars"}){let p=document.createElement("div");return p.setAttribute("data-waveform-player",""),p.setAttribute("data-url",e),p.setAttribute("data-height",String(u)),p.setAttribute("data-waveform-style",c),p.setAttribute("data-waveform-color",Mt(r)),p.setAttribute("data-progress-color",Mt(s)),o&&p.setAttribute("data-waveform-gradient",o),p.setAttribute("data-button-color",l),p.setAttribute("data-seek-label",Ht(n)),h&&p.setAttribute("data-seek-value-text",h),p.setAttribute("data-text-color",l),p.setAttribute("data-text-secondary-color",l),t&&p.setAttribute("data-title",t),i&&p.setAttribute("data-artist",i),a&&p.setAttribute("data-artwork",a),p}function ke(e,{backgroundColor:t,backgroundGradient:i,textColor:a,playButtonColor:r,playButtonGradient:s}={}){let o=e.querySelector(".waveform-container"),l=e.querySelector(".waveform-btn"),n=Dt(Q(e,s)||r);n?e.style.setProperty("--wfp-button-color",n):e.style.removeProperty("--wfp-button-color"),a?(e.style.setProperty("--wfp-text-color",a),e.style.setProperty("--wfp-text-secondary-color",a)):(e.style.removeProperty("--wfp-text-color"),e.style.removeProperty("--wfp-text-secondary-color")),l&&(s?l.style.background=s:l.style.removeProperty("background")),o&&(i?o.style.background=i:t?(o.style.removeProperty("background"),o.style.backgroundColor=t):(o.style.removeProperty("background"),o.style.removeProperty("background-color")))}function Se(e,t){let a=k(t).isDark()?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(s=>{s.style.fill=a})}function Ee(e,{play:t="Play",pause:i="Pause"}={}){let a=e.querySelector(".waveform-btn");if(!a)return;a.setAttribute("aria-label",t);let r=()=>a.setAttribute("aria-label",i),s=()=>a.setAttribute("aria-label",t);return e.addEventListener("waveformplayer:play",r),e.addEventListener("waveformplayer:pause",s),e.addEventListener("waveformplayer:ended",s),()=>{e.removeEventListener("waveformplayer:play",r),e.removeEventListener("waveformplayer:pause",s),e.removeEventListener("waveformplayer:ended",s)}}function Ht(e){return e||pe}function Bt(e,t){let i=Ht(t);e.options.seekLabel=i,e.applySeekLabel?.(i);let a=e?.container?.querySelector(".waveform-container");a&&a.setAttribute("aria-label",i)}function Y(e,t){if(!t){e.classList.remove("has-play-button-artwork"),e.style.removeProperty("--wp--playlist--play-button-artwork");return}e.classList.add("has-play-button-artwork"),e.style.setProperty("--wp--playlist--play-button-artwork",`url(${JSON.stringify(t)})`)}function $(e){e.name!=="AbortError"&&console.error("Playlist play error:",e)}function Rt(e,{src:t,title:i,artist:a,image:r,imageAlt:s,waveformColor:o,waveformGradient:l,textColor:n,backgroundColor:h,backgroundGradient:u,autoPlay:c,onEnded:p,labels:y,waveformStyle:g,showPlayButtonArtwork:m=!1}){let f=m?void 0:r,{textColor:v,waveformColor:d,progressColor:E,waveformGradient:P}=be(e,o,n,l),C=Q(e,l),M=Dt(C||o),A=we({url:t,title:i,artist:a,artwork:f,waveformColor:d,progressColor:E,waveformGradient:P,buttonColor:v,seekLabel:i||y?.seek,seekValueText:y?.seekValueText,waveformStyle:g});e.appendChild(A);let H=new Ct(A);H.artworkEl&&(H.artworkEl.alt=s||""),ke(A,{backgroundColor:h,backgroundGradient:u,textColor:v,playButtonColor:m?void 0:M,playButtonGradient:m?void 0:l});let tt,q={ready:()=>{Se(A,M||v),m&&Y(A,r),tt=Ee(A,y),c&&H.play()?.catch($)},ended:()=>p?.()};return A.addEventListener("waveformplayer:ready",q.ready),A.addEventListener("waveformplayer:ended",q.ended),{instance:H,container:A,destroy:()=>{tt?.(),A.removeEventListener("waveformplayer:ready",q.ready),A.removeEventListener("waveformplayer:ended",q.ended),H.destroy(),A.remove()}}}var F=new WeakMap,Z=new Map,{state:Wt}=Pe("core/playlist",{state:{playlists:{},get isCurrentTrack(){let{currentId:e,trackId:t}=N();return e===t},get isCurrentTrackPlaying(){let{currentId:e,isPlaying:t,trackId:i}=N();return e===i&&!!t},get trackButtonActionLabel(){let{labelPauseTrack:e,labelSelectTrack:t}=N();return Wt.isCurrentTrackPlaying?e:t}},actions:{changeTrack(){let e=N();if(e.currentId===e.trackId){let t=Z.get(e.playlistId)?.instance;t?.isPlaying?(e.isPlaying=!1,t.pause()):t?.play()?.catch($);return}e.isPlaying=!1,e.currentId=e.trackId}},callbacks:{initWaveformPlayer(){let e=N(),{ref:t}=Ae();if(!e.currentId||!t)return;let i=Wt.playlists[e.playlistId]?.tracks[e.currentId];if(!i?.url)return;let a=F.get(t);if(a?.url===i.url)return;let r=!!a?.url;Te(t,i,r,e)}}},{lock:!0});function Te(e,t,i,a){let r=F.get(e),s=a.showPlayButtonArtwork===!0,o=s?"":t.image;if(r?.instance)if(!!r.instance.artworkEl!=!!o)r.destroy?.(),F.delete(e);else{Z.set(a.playlistId,r),r.instance.loadTrack(t.url,t.title,t.artist,{artwork:o,artworkAlt:o?t.imageAlt:""}).then(()=>{r.url=t.url,r.instance.artworkEl&&(r.instance.artworkEl.alt=t.imageAlt||""),Bt(r.instance,t.title||e.dataset.labelSeek),s&&Y(r.container,t.image),i&&r.instance.play()?.catch($)}).catch($);return}let l={play:e.dataset.labelPlay,pause:e.dataset.labelPause,seek:e.dataset.labelSeek,seekValueText:e.dataset.labelSeekValue},n=Rt(e,{src:t.url,title:t.title,artist:t.artist,image:t.image,imageAlt:t.imageAlt,waveformColor:e.dataset.waveformPlayerColor,waveformGradient:e.dataset.waveformPlayerGradient,backgroundColor:e.dataset.waveformPlayerBackgroundColor,backgroundGradient:e.dataset.waveformPlayerBackgroundGradient,autoPlay:i,labels:l,waveformStyle:a.waveformStyle,showPlayButtonArtwork:s,onEnded:()=>{let g=a.tracks.findIndex(f=>f===a.currentId),m=a.tracks[g+1];m&&(a.currentId=m)}}),h=g=>{a.isPlaying=g},u=()=>h(!0),c=()=>h(!1);n.container.addEventListener("waveformplayer:play",u),n.container.addEventListener("waveformplayer:pause",c),n.container.addEventListener("waveformplayer:ended",c);let p=()=>{n.container.removeEventListener("waveformplayer:play",u),n.container.removeEventListener("waveformplayer:pause",c),n.container.removeEventListener("waveformplayer:ended",c),n.destroy()},y={url:t.url,instance:n.instance,container:n.container,destroy:p};F.set(e,y),Z.set(a.playlistId,y)} | |
| 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=Be)},{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 r=this.container.querySelector(".waveform-text");if(!r)return;this.artworkEl=this.createArtworkElement(),r.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 r=()=>Array.from(i.querySelectorAll(".speed-option")),a=()=>i.style.display!=="none",s=l=>{if(i.style.display=l?"block":"none",t.setAttribute("aria-expanded",l?"true":"false"),l){let h=r();(h.find(u=>u.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=l=>{let h=r();h.length&&h[(l+h.length)%h.length].focus()},n=l=>{this.setPlaybackRate(parseFloat(l.dataset.rate)),s(!1),t.focus()};t.addEventListener("click",l=>{l.stopPropagation(),s(!a())},{signal:this._ac.signal}),document.addEventListener("click",()=>s(!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=r(),u=h.indexOf(document.activeElement);if(!a()){(l.key==="ArrowDown"||l.key==="ArrowUp")&&document.activeElement===t&&(l.preventDefault(),s(!0));return}switch(l.key){case"ArrowDown":l.preventDefault(),o(u<0?0:u+1);break;case"ArrowUp":l.preventDefault(),o(u<0?h.length-1:u-1);break;case"Home":l.preventDefault(),o(0);break;case"End":l.preventDefault(),o(h.length-1);break;case"Escape":l.preventDefault(),s(!1),t.focus();break;case"Tab":s(!1);break}},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(We)||(w.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,r=!!this.audio,a=r?this.audio.currentTime:0;if(r&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let s={" ":()=>this.togglePlay()};r&&(s.ArrowLeft=()=>this.seekTo(b(a-5,0,this.audio.duration)),s.ArrowRight=()=>this.seekTo(b(a+5,0,this.audio.duration)),s.ArrowUp=()=>this.setVolume(b(this.audio.volume+.1)),s.ArrowDown=()=>this.setVolume(b(this.audio.volume-.1)),s.m=s.M=()=>this.audio.muted=!this.audio.muted),s[i]&&(t.preventDefault(),s[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 r=this.getSeekCurrentTime(),a;switch(t.key){case"ArrowLeft":case"ArrowDown":a=r-Nt;break;case"ArrowRight":case"ArrowUp":a=r+Nt;break;case"PageDown":a=r-$t;break;case"PageUp":a=r+$t;break;case"Home":a=0;break;case"End":a=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(a)},{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 r=b(t,0,i);if(this.options.audioMode==="external"){this._requestSeek(r/i),this.updateSeekAccessibility();return}this.seekTo(r)}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",pe(this.options.seekValueText||"%1$s of %2$s",R(i),R(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(b(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(b(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",r=>{r.seekTime!==null&&this.seekTo(r.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:b(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 r=this.canvas.getBoundingClientRect();r.width&&(this._handleNear=Math.abs(i.clientX-r.left-this.progress*r.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=ve(()=>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 r=this.options.title||zt(t);if(this.titleEl&&(this.titleEl.textContent=r),this.applySeekLabel(r),this.audio&&(this.audio.src=t,this.audio.preload!=="none"&&await new Promise((a,s)=>{let o=()=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),a()},n=l=>{this.audio.removeEventListener("loadedmetadata",o),this.audio.removeEventListener("error",n),s(l)};this.audio.addEventListener("loadedmetadata",o),this.audio.addEventListener("error",n)})),!i)try{let a=await Ht(t,this.options.samples,this.options.showBPM);this.waveformData=a.peaks,a.bpm&&(this.detectedBPM=a.bpm,this.updateBPMDisplay())}catch(a){console.warn("[WaveformPlayer] Using placeholder waveform:",a),this.waveformData=xe(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,r=null,a={}){let s=Object.prototype.hasOwnProperty.call(a,"artwork"),o=Object.prototype.hasOwnProperty.call(a,"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=It(Mt(this.options,{url:t,title:i===null?this.options.title:i,artist:r===null?this.options.artist:r,...a})),s&&(this.options.artwork=a.artwork||null),o?this.options.artworkAlt=a.artworkAlt||"":s&&(this.options.artworkAlt=this.options.artwork?at.artworkAlt:""),a.preload&&this.audio&&(this.audio.preload=this.options.preload),a.crossOrigin&&this.audio&&(this.audio.crossOrigin=this.options.crossOrigin),r!==null&&this.syncArtist(r),(s||o)&&this.syncArtwork(s?a.artwork:this.options.artwork,o?a.artworkAlt:this.options.artworkAlt),this.options.markers=a.markers?ot(a.markers):[],this.options.waveform=a.waveform||null,await this.load(t),a.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=ot(i.markers),this.renderMarkers()),this.drawWaveform()}).catch(()=>{});return}this.waveformData=ht(t,{fallback:[]}),this.drawWaveform()}drawWaveform(){!this.ctx||this.waveformData.length===0||Ee(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,r)=>{if(i.time>t){console.warn(`[WaveformPlayer] Marker "${i.label}" at ${i.time}s exceeds audio duration of ${t}s`);return}let a=i.time/t*100,s=document.createElement("button");s.className="waveform-marker",s.style.left=`${a}%`,s.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",s.setAttribute("aria-label",i.label),s.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,s.appendChild(o),s.addEventListener("click",n=>{n.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(s)})}setActiveMarker(t){this.markersContainer&&this.markersContainer.querySelectorAll(".waveform-marker").forEach((i,r)=>i.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(),r=i?this.progress*i:0,a=-1,s=-1/0;t.forEach((o,n)=>{let l=parseFloat(o.getAttribute("data-time"));Number.isFinite(l)&&l<=r+.05&&l>s&&(s=l,a=n)}),a!==this._activeMarkerIndex&&(this._activeMarkerIndex=a,this.setActiveMarker(a),clearTimeout(this._markerLabelTimer),t.forEach((o,n)=>o.classList.toggle("show-label",n===a)),a>=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 r=this.getSeekDuration();if(!r){i.style.opacity="0";return}let a=this.canvas.getBoundingClientRect(),s=b((t-a.left)/a.width);i.textContent=R(s*r),i.style.left=s*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=b((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle();let r=this.getSeekDuration();r&&this.currentTimeEl?(this.currentTimeEl.textContent=R(this.progress*r),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 r=b((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(r);return}!this.audio||!this.audio.duration||this.seekToPercent(r)}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=R(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"),r=this.playBtn.querySelector(".waveform-icon-pause");i&&(i.style.display=t?"none":"flex"),r&&(r.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=R(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=V(this.container);let t=Wt(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(w._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{w.instances.forEach(s=>{try{s.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},r=new MutationObserver(t);r.observe(document.documentElement,i),document.body&&r.observe(document.body,i);let a=null;try{a=window.matchMedia("(prefers-color-scheme: dark)"),a.addEventListener("change",t)}catch{}w._themeWatch={obs:r,mq:a,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 r=parseFloat(i.dataset.rate)===this.audio.playbackRate;i.classList.toggle("active",r),i.setAttribute("aria-checked",r?"true":"false")})}play(){if(this.options.singlePlay&&w.currentlyPlaying&&w.currentlyPlaying!==this&&w.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(w.currentlyPlaying=this);return}return w.currentlyPlaying=this,this.audio.play()}pause(){if(w.currentlyPlaying===this&&(w.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=b(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=R(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=R(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=b(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*b(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=b(i))}setPlaybackRate(t){if(!this.audio)return;let i=J(t,null,{min:ut,max:dt});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),w.instances.delete(this.id),w.currentlyPlaying===this&&(w.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 r=document.getElementById(t);if(r)return Array.from(this.instances.values()).find(a=>a.container===r)}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 Ht(t,i)).peaks}catch(r){throw console.error("[WaveformPlayer] Failed to generate waveform:",r),r}}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}};I.utils={formatTime:R,extractTitleFromUrl:zt,escapeHtml:M,isSafeHref:he,parseDataAttributes:Ft,detectColorScheme:V};var ct=()=>typeof window<"u"&&typeof document<"u",Ie=()=>!0;function Ot(e){if(!(e.dataset.waveformInitialized==="true"||I.getInstance(e)))try{new I(e),e.dataset.waveformInitialized="true"}catch(t){console.error("[WaveformPlayer] Failed to initialize:",t,e)}}function nt(e=document){if(!ct())return;let t=e||document;t.matches?.("[data-waveform-player]")&&Ot(t),t.querySelectorAll("[data-waveform-player]").forEach(Ot)}ct()&&!Ie()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>nt()):nt());I.init=nt;ct()&&(window.WaveformPlayer=I);var Jt=I;var Ne=100,$e="Seek";function Qt(e){return e.ownerDocument.defaultView.getComputedStyle(e)}function Yt(e){let t=e?.trim().match(/^[\w-]+-gradient\((.*)\)$/i);if(!t)return[];let i=[],r=0,a="";for(let s of t[1]){if(s==="("?++r:s===")"&&--r,s===","&&r===0){i.push(a.trim()),a="";continue}a+=s}return a.trim()&&i.push(a.trim()),i}function Oe(e){let t=e.match(/^([\w-]+)\(/);if(!t||!["color","color-mix","hsl","hsla","hwb","lab","lch","oklab","oklch","rgb","rgba","var"].includes(t[1].toLowerCase()))return;let r=0,a=!1;for(let s=0;s<e.length;s++){let o=e[s];if(o==="("?(a=!0,++r):o===")"&&--r,a&&r===0)return e.slice(0,s+1)}}function qe(e){let t=Oe(e);if(t)return t;let[i]=e.split(/\s+/);if(k(i).isValid())return i}function Fe(e){let i=Yt(e)[0],r=i?.match(/^(-?\d+(?:\.\d+)?)deg$/i);if(r){let n=(Number(r[1])%360+360)%360;return n===90||n===270?"horizontal":n===0||n===180?"vertical":"diagonal"}if(!i?.startsWith("to "))return;let a=i.toLowerCase().replace(/^to\s+/,""),s=a.includes("left")||a.includes("right"),o=a.includes("top")||a.includes("bottom");if(s&&o)return"diagonal";if(s)return"horizontal";if(o)return"vertical"}function ze(e,t){if(!t||k(t).isValid())return t;let i=e.ownerDocument.createElement("span");if(i.style.color=t,!i.style.color)return t;e.appendChild(i);let r=Qt(i).color;return i.remove(),r&&k(r).isValid()?r:t}function pt(e,t){let i=Ue(t)?.map(r=>ze(e,r)).filter(r=>k(r).isValid());return i?.length>1?i:void 0}function Kt(e,t){return Array.isArray(e)?e.map(i=>k(i).alpha(t).toRgbString()):k(e).alpha(t).toRgbString()}function Zt(e){return Array.isArray(e)?e[e.length-1]:e}function Ue(e){let t=Yt(e).map(qe).filter(Boolean);return t.length>1?t:void 0}function Xt(e){return Array.isArray(e)?JSON.stringify(e):e}function je(e,t,i,r){let a=i||Qt(e).color,s=pt(e,r),o=s||t||a,n=Kt(o,.3),l=Kt(o,.6),h=s?Fe(r):void 0;return{textColor:a,waveformColor:n,progressColor:l,...h&&{waveformGradient:h}}}function Ge({url:e,title:t,artist:i,artwork:r,waveformColor:a,progressColor:s,waveformGradient:o,buttonColor:n,seekLabel:l,seekValueText:h,height:u=Ne,waveformStyle:c="bars"}){let p=document.createElement("div");return p.setAttribute("data-waveform-player",""),p.setAttribute("data-url",e),p.setAttribute("data-height",String(u)),p.setAttribute("data-waveform-style",c),p.setAttribute("data-waveform-color",Xt(a)),p.setAttribute("data-progress-color",Xt(s)),o&&p.setAttribute("data-waveform-gradient",o),p.setAttribute("data-button-color",n),p.setAttribute("data-seek-label",te(l)),h&&p.setAttribute("data-seek-value-text",h),p.setAttribute("data-text-color",n),p.setAttribute("data-text-secondary-color",n),t&&p.setAttribute("data-title",t),i&&p.setAttribute("data-artist",i),r&&p.setAttribute("data-artwork",r),p}function Ve(e,{backgroundColor:t,backgroundGradient:i,textColor:r,playButtonColor:a,playButtonGradient:s}={}){let o=e.querySelector(".waveform-container"),n=e.querySelector(".waveform-btn"),l=Zt(pt(e,s)||a);l?e.style.setProperty("--wfp-button-color",l):e.style.removeProperty("--wfp-button-color"),r?(e.style.setProperty("--wfp-text-color",r),e.style.setProperty("--wfp-text-secondary-color",r)):(e.style.removeProperty("--wfp-text-color"),e.style.removeProperty("--wfp-text-secondary-color")),n&&(s?n.style.background=s:n.style.removeProperty("background")),o&&(i?o.style.background=i:t?(o.style.removeProperty("background"),o.style.backgroundColor=t):(o.style.removeProperty("background"),o.style.removeProperty("background-color")))}function Je(e,t){let r=k(t).isDark()?"#ffffff":"#000000";e.querySelectorAll("svg path").forEach(s=>{s.style.fill=r})}function Ke(e,{play:t="Play",pause:i="Pause"}={}){let r=e.querySelector(".waveform-btn");if(!r)return;r.setAttribute("aria-label",t);let a=()=>r.setAttribute("aria-label",i),s=()=>r.setAttribute("aria-label",t);return e.addEventListener("waveformplayer:play",a),e.addEventListener("waveformplayer:pause",s),e.addEventListener("waveformplayer:ended",s),()=>{e.removeEventListener("waveformplayer:play",a),e.removeEventListener("waveformplayer:pause",s),e.removeEventListener("waveformplayer:ended",s)}}function te(e){return e||$e}function ee(e,t){let i=te(t);e.options.seekLabel=i,e.applySeekLabel?.(i);let r=e?.container?.querySelector(".waveform-container");r&&r.setAttribute("aria-label",i)}function mt(e,t){if(!t){e.classList.remove("has-play-button-artwork"),e.style.removeProperty("--wp--playlist--play-button-artwork");return}e.classList.add("has-play-button-artwork"),e.style.setProperty("--wp--playlist--play-button-artwork",`url(${JSON.stringify(t)})`)}function q(e){e.name!=="AbortError"&&console.error("Playlist play error:",e)}function ie(e,{src:t,title:i,artist:r,image:a,imageAlt:s,waveformColor:o,waveformGradient:n,textColor:l,backgroundColor:h,backgroundGradient:u,autoPlay:c,onEnded:p,labels:y,waveformStyle:g,showPlayButtonArtwork:m=!1}){let f=m?void 0:a,{textColor:v,waveformColor:d,progressColor:E,waveformGradient:P}=je(e,o,l,n),C=pt(e,n),_=Zt(C||o),T=Ge({url:t,title:i,artist:r,artwork:f,waveformColor:d,progressColor:E,waveformGradient:P,buttonColor:v,seekLabel:i||y?.seek,seekValueText:y?.seekValueText,waveformStyle:g});e.appendChild(T);let N=new Jt(T);N.artworkEl&&(N.artworkEl.alt=s||""),Ve(T,{backgroundColor:h,backgroundGradient:u,textColor:v,playButtonColor:m?void 0:_,playButtonGradient:m?void 0:n});let yt,z={ready:()=>{Je(T,_||v),m&&mt(T,a),yt=Ke(T,y),c&&N.play()?.catch(q)},ended:()=>p?.()};return T.addEventListener("waveformplayer:ready",z.ready),T.addEventListener("waveformplayer:ended",z.ended),{instance:N,container:T,destroy:()=>{yt?.(),T.removeEventListener("waveformplayer:ready",z.ready),T.removeEventListener("waveformplayer:ended",z.ended),N.destroy(),T.remove()}}}var X=new WeakMap,ft=new Map,{state:re}=Xe("core/playlist",{state:{playlists:{},get isCurrentTrack(){let{currentId:e,trackId:t}=F();return e===t},get isCurrentTrackPlaying(){let{currentId:e,isPlaying:t,trackId:i}=F();return e===i&&!!t},get trackButtonActionLabel(){let{labelPauseTrack:e,labelSelectTrack:t}=F();return re.isCurrentTrackPlaying?e:t}},actions:{changeTrack(){let e=F();if(e.currentId===e.trackId){let t=ft.get(e.playlistId)?.instance;t?.isPlaying?(e.isPlaying=!1,t.pause()):t?.play()?.catch(q);return}e.isPlaying=!1,e.currentId=e.trackId}},callbacks:{initWaveformPlayer(){let e=F(),{ref:t}=Qe();if(!e.currentId||!t)return;let i=re.playlists[e.playlistId]?.tracks[e.currentId];if(!i?.url)return;let r=X.get(t);if(r?.url===i.url)return;let a=!!r?.url;Ye(t,i,a,e)}}},{lock:!0});function Ye(e,t,i,r){let a=X.get(e),s=r.showPlayButtonArtwork===!0,o=s?"":t.image;if(a?.instance)if(!!a.instance.artworkEl!=!!o)a.destroy?.(),X.delete(e);else{ft.set(r.playlistId,a),a.instance.loadTrack(t.url,t.title,t.artist,{artwork:o,artworkAlt:o?t.imageAlt:""}).then(()=>{a.url=t.url,a.instance.artworkEl&&(a.instance.artworkEl.alt=t.imageAlt||""),ee(a.instance,t.title||e.dataset.labelSeek),s&&mt(a.container,t.image),i&&a.instance.play()?.catch(q)}).catch(q);return}let n={play:e.dataset.labelPlay,pause:e.dataset.labelPause,seek:e.dataset.labelSeek,seekValueText:e.dataset.labelSeekValue},l=ie(e,{src:t.url,title:t.title,artist:t.artist,image:t.image,imageAlt:t.imageAlt,waveformColor:e.dataset.waveformPlayerColor,waveformGradient:e.dataset.waveformPlayerGradient,backgroundColor:e.dataset.waveformPlayerBackgroundColor,backgroundGradient:e.dataset.waveformPlayerBackgroundGradient,autoPlay:i,labels:n,waveformStyle:r.waveformStyle,showPlayButtonArtwork:s,onEnded:()=>{let g=r.tracks.findIndex(f=>f===r.currentId),m=r.tracks[g+1];m&&(r.currentId=m)}}),h=g=>{r.isPlaying=g},u=()=>h(!0),c=()=>h(!1);l.container.addEventListener("waveformplayer:play",u),l.container.addEventListener("waveformplayer:pause",c),l.container.addEventListener("waveformplayer:ended",c);let p=()=>{l.container.removeEventListener("waveformplayer:play",u),l.container.removeEventListener("waveformplayer:pause",c),l.container.removeEventListener("waveformplayer:ended",c),l.destroy()},y={url:t.url,instance:l.instance,container:l.container,destroy:p};X.set(e,y),ft.set(r.playlistId,y)} | |
| 65 | 65 | //# sourceMappingURL=view.min.js.map |