@arraypress/waveform-player 1.24.0 → 1.24.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/waveform-player.cjs +57 -31
- package/dist/waveform-player.esm.js +3 -3
- package/dist/waveform-player.js +57 -31
- package/dist/waveform-player.min.js +3 -3
- package/index.d.ts +7 -0
- package/package.json +5 -4
- package/src/js/core.js +7 -5
- package/src/js/index.js +8 -3
- package/src/js/themes.js +119 -33
- package/src/js/utils.js +52 -12
- package/dist/waveform-player.cjs.map +0 -7
- package/dist/waveform-player.esm.js.map +0 -7
- package/dist/waveform-player.min.js.map +0 -7
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(()=>{function B(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function S(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function W(e){return S(typeof e=="number"?`${e}px`:e)}function V(e){if(typeof e!="string"||e==="")return!1;try{let t=new URL(e,"http://localhost/");return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function m(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function nt(e){return e===void 0?void 0:e==="true"}function N(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function D(e){let t={},i=(o,l=o)=>{let n=nt(e.dataset[l]);n!==void 0&&(t[o]=n)},s=(o,l=o,n=!1)=>{let h=e.dataset[l];h&&(t[o]=n?parseFloat(h):parseInt(h,10))},r=(o,l=o)=>{let n=e.dataset[l];n&&(t[o]=/^\d+(\.\d+)?$/.test(n.trim())?parseFloat(n):n)},a=(o,l=o)=>{let n=e.dataset[l];if(n)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),s("height"),s("samples"),e.dataset.preload&&(t.preload=e.dataset.preload),e.dataset.crossOrigin&&(t.crossOrigin=e.dataset.crossOrigin),e.dataset.audioMode&&(t.audioMode=e.dataset.audioMode),e.dataset.style&&(t.waveformStyle=e.dataset.style),e.dataset.waveformStyle&&(t.waveformStyle=e.dataset.waveformStyle),e.dataset.waveformGradient&&(t.waveformGradient=e.dataset.waveformGradient),s("barWidth"),s("barSpacing"),s("barRadius"),e.dataset.buttonAlign&&(t.buttonAlign=e.dataset.buttonAlign),e.dataset.layout&&(t.layout=e.dataset.layout),e.dataset.buttonStyle&&(t.buttonStyle=e.dataset.buttonStyle),r("buttonSize"),r("buttonRadius"),e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=N(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=N(e.dataset.progressColor)),e.dataset.color&&(t.waveformColor=e.dataset.color),e.dataset.theme&&(t.colorPreset=e.dataset.theme),i("autoplay"),i("showControls"),i("showInfo"),i("showTime"),i("showHoverTime"),i("seekHandle"),i("showBPM","showBpm"),s("bpm"),i("singlePlay"),i("playOnSeek"),e.dataset.title&&(t.title=e.dataset.title),e.dataset.artist&&(t.artist=e.dataset.artist),e.dataset.album&&(t.album=e.dataset.album),e.dataset.artwork&&(t.artwork=e.dataset.artwork),e.dataset.artworkPosition&&(t.artworkPosition=e.dataset.artworkPosition),e.dataset.waveform&&(t.waveform=e.dataset.waveform),a("markers"),s("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),a("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 j(e,...t){let i=0;return e.replace(/%(?:(\d+)\$)?s/g,(s,r)=>{let a=r?Number(r)-1:i++;return t[a]??s})}function E(e){if(!e||isNaN(e)||e<0)return"0:00";let t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);return t>0?`${t}:${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${i}:${s.toString().padStart(2,"0")}`}var lt=0;function G(e){let t=e||"audio",i=5381;for(let s=0;s<t.length;s++)i=(i<<5)+i+t.charCodeAt(s)|0;return`wp_${(i>>>0).toString(36)}_${(lt++).toString(36)}`}function H(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function J(e){let t=typeof e=="string"?e.match(/\d+/g):null;if(!t||t.length<3)return null;let[i,s,r]=t.map(Number);return(i*299+s*587+r*114)/1e3}function O(...e){let t={};for(let i of e)for(let s in i)i[s]!==null&&i[s]!==void 0&&(t[s]=i[s]);return t}function K(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}function x(e,t){if(e.length===t)return e;if(e.length===0||t===0)return[];let i=[];if(t>e.length){let s=(e.length-1)/(t-1);for(let r=0;r<t;r++){let a=r*s,o=Math.floor(a),l=Math.ceil(a),n=a-o;if(l>=e.length)i.push(e[e.length-1]);else if(o===l)i.push(e[o]);else{let h=e[o]*(1-n)+e[l]*n;i.push(h)}}}else{let s=e.length/t;for(let r=0;r<t;r++){let a=Math.floor(r*s),o=Math.floor((r+1)*s),l=0,n=0;for(let h=a;h<=o&&h<e.length;h++)e[h]>l&&(l=e[h]),n++;if(n===0){let h=Math.min(Math.round(r*s),e.length-1);l=e[h]}i.push(l)}}return i}function P(e,t,i,s){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let r=i.width,a=i.height,o=s&&s.waveformGradient,[l,n,h,c]=o==="horizontal"?[0,0,r,0]:o==="diagonal"?[0,0,r,a]:[0,0,0,a];try{let u=e.createLinearGradient(l,n,h,c);return t.forEach((w,g)=>u.addColorStop(g/(t.length-1),w)),u}catch{return t[0]}}function L(e,t,i,s,r,a){if((Array.isArray(a)?a.some(l=>l>0):a>0)&&typeof e.roundRect=="function"){let l=Math.min(s/2,Math.abs(r)/2),n=h=>m(h,0,l);e.beginPath(),e.roundRect(t,i,s,r,Array.isArray(a)?a.map(n):n(a)),e.fill()}else e.fillRect(t,i,s,r)}function Z(e,t){return(e.barRadius||0)*t}function ht(e,t){let i=Z(e,t);return[i,i,0,0]}function Y(e,t,i,s,r){let a=r/2;e.beginPath(),e.moveTo(t,s-a),e.lineTo(i-a,s-a),e.arc(i-a,s,a,-Math.PI/2,Math.PI/2),e.lineTo(t,s+a),e.arc(t,s,a,Math.PI/2,-Math.PI/2),e.closePath()}function I(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,l=r.barSpacing*a,n=Math.floor(t.width/(o+l)),h=x(i,n),c=t.height,u=s*t.width,w=ht(r,a),g=P(e,r.color,t,r),k=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=g;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p+o>t.width)break;let y=h[f]*c*.9,d=c-y;L(e,p,d,o,y,w)}e.save(),e.beginPath(),e.rect(0,0,u,c),e.clip(),e.fillStyle=k;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p>u)break;let y=h[f]*c*.9,d=c-y;L(e,p,d,o,y,w)}e.restore()}function ct(e,t,i,s,r){let a=window.devicePixelRatio||1,o=r.barWidth*a,l=r.barSpacing*a,n=Math.floor(t.width/(o+l)),h=x(i,n),c=t.height,u=c/2,w=s*t.width,g=Z(r,a),k=[g,g,0,0],f=[0,0,g,g],p=P(e,r.color,t,r),y=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height),e.fillStyle=p;for(let d=0;d<h.length;d++){let v=d*(o+l);if(v+o>t.width)break;let b=h[d]*c*.45;L(e,v,u-b,o,b,k),L(e,v,u,o,b,f)}e.save(),e.beginPath(),e.rect(0,0,w,c),e.clip(),e.fillStyle=y;for(let d=0;d<h.length;d++){let v=d*(o+l);if(v>w)break;let b=h[d]*c*.45;L(e,v,u-b,o,b,k),L(e,v,u,o,b,f)}e.restore()}function dt(e,t,i,s,r){let a=t.width,o=t.height,l=o/2,n=o*.35;e.clearRect(0,0,a,o);let h=(c,u,w=1,g=!1)=>{let k=P(e,c,t,r),f=Array.isArray(c)?c[c.length-1]:c;g&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=k,e.lineWidth=u,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,l);let p=[],y=Math.floor(i.length*w);for(let d=0;d<y;d++){let v=d/(i.length-1)*a,b=i[d],T=Math.sin(d*.1)*b,C=l+T*n;p.push({x:v,y:C})}for(let d=0;d<p.length-1;d++){let v=p[d].x+(p[d+1].x-p[d].x)*.5,b=p[d].y,T=p[d+1].x-(p[d+1].x-p[d].x)*.5,C=p[d+1].y;e.bezierCurveTo(v,b,T,C,p[d+1].x,p[d+1].y)}e.stroke(),g&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,l),e.lineTo(a,l),e.stroke();for(let c=0;c<=10;c++){let u=a/10*c;e.beginPath(),e.moveTo(u,0),e.lineTo(u,o),e.stroke()}h(r.color,2,1,!1),s>0&&h(r.progressColor,3,s,!0)}function X(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||3)*a,l=(r.barSpacing||1)*a,n=Math.floor(t.width/(o+l)),h=x(i,n),c=t.height,u=4*a,w=2*a,g=s*t.width,k=c/2,f=P(e,r.color,t,r),p=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let y=0;y<h.length;y++){let d=y*(o+l);if(d+o>t.width)break;let v=h[y]*c*.9,b=Math.floor(v/(u+w));e.fillStyle=d<g?p:f;for(let T=0;T<b;T++){let C=T*(u+w);e.fillRect(d,k-C-u,o,u),T>0&&e.fillRect(d,k+C,o,u)}}}function Q(e,t,i,s,r){let a=window.devicePixelRatio||1,o=(r.barWidth||2)*a,l=(r.barSpacing||3)*a,n=Math.floor(t.width/(o+l)),h=x(i,n),c=t.height,u=Math.max(1.5*a,o/2),w=s*t.width,g=c/2,k=P(e,r.color,t,r),f=P(e,r.progressColor,t,r);e.clearRect(0,0,t.width,t.height);for(let p=0;p<h.length;p++){let y=p*(o+l)+o/2;if(y>t.width)break;let d=h[p]*c*.9;e.fillStyle=y<w?f:k,e.beginPath(),e.arc(y,g-d/2,u,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(y,g+d/2,u,0,Math.PI*2),e.fill()}}function ut(e,t,i,s,r){let a=t.width,o=t.height,l=o/2,n=4,h=n/2,c=!!r.seekActive;if(e.clearRect(0,0,a,o),e.fillStyle=P(e,r.color,t,r)||"rgba(255, 255, 255, 0.2)",Y(e,h,a,l,n),e.fill(),s>0){let u=Math.max(h*2,s*a);e.save(),e.globalAlpha=r.seekHandle&&!c?.7:1,e.fillStyle=P(e,r.progressColor,t,r)||"rgba(255, 255, 255, 0.9)",Y(e,h,u,l,n),e.fill(),e.restore()}}var pt={bars:I,bar:I,mirror:ct,line:dt,blocks:X,block:X,dots:Q,dot:Q,seekbar:ut};function tt(e,t,i,s,r){(pt[r.waveformStyle]||I)(e,t,i,s,r)}function et(e){try{let t=e.getChannelData(0),i=e.sampleRate,s=ft(t,i);if(s.length<2)return 120;let r=[];for(let n=1;n<s.length;n++)r.push((s[n]-s[n-1])/i);let a={};r.forEach(n=>{let h=60/n,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,l=120;for(let[n,h]of Object.entries(a))h>o&&(o=h,l=parseInt(n));return l<70&&a[l*2]?l*=2:l>160&&a[Math.round(l/2)]&&(l=Math.round(l/2)),l-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function ft(e,t){let r=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let l=0;for(let c=o;c<o+2048;c++)l+=e[c]*e[c];l=l/2048;let n=l-a,h=a*1.8+.01;if(n>h&&l>.01){let c=r[r.length-1]||0,u=t*.15;o-c>u&&r.push(o)}a=l*.8+a*.2}return r}function mt(e,t=1800){let i=e.length/t,s=e.numberOfChannels,r=[];for(let o=0;o<s;o++){let l=e.getChannelData(o);for(let n=0;n<t;n++){let h=~~(n*i),c=~~(h+i),u=0,w=0;for(let k=h;k<c;k++){let f=l[k];f>w&&(w=f),f<u&&(u=f)}let g=Math.max(Math.abs(w),Math.abs(u));(o===0||g>r[n])&&(r[n]=g)}}let a=B(r);return a>0?r.map(o=>o/a):r}async function F(e,t=1800,i=!1){let s;try{let r=window.AudioContext||window.webkitAudioContext;s=new r;let o=await(await fetch(e)).arrayBuffer(),l=await s.decodeAudioData(o),n=mt(l,t);n=gt(n);let h=null;return i&&(h=et(l)),{peaks:n,bpm:h}}finally{s&&s.close()}}function it(e=1800){let t=[];for(let i=0;i<e;i++){let s=Math.random()*.5+.3,r=Math.sin(i/e*Math.PI*4)*.2;t.push(m(s+r,.1,1))}return t}function gt(e,t=.95){let i=B(e);if(i===0||i>t)return e;let s=t/i;return e.map(r=>r*s)}function st(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 R(){if(st("dark"))return"dark";if(st("light"))return"light";try{let e=getComputedStyle(document.body).backgroundColor,t=J(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 _={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 $(e){if(e&&_[e])return _[e];let t=R();return _[t]}var z={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},rt={bars:{barWidth:3,barSpacing:1},mirror:{barWidth:2,barSpacing:2},line:{barWidth:2,barSpacing:0},blocks:{barWidth:4,barSpacing:2},dots:{barWidth:3,barSpacing:3},seekbar:{barWidth:1,barSpacing:0}};var yt="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>'),at=5,ot=10,wt='button, a[href], input, [role="slider"]',A=class e{static instances=new Map;static currentlyPlaying=null;constructor(t,i={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("[WaveformPlayer] Container element not found");let s=D(this.container),r={...i};r.style&&!r.waveformStyle&&(r.waveformStyle=r.style),r.src&&!r.url&&(r.url=r.src),this.options=O(z,s,r);let a=$(this.options.colorPreset);this._autoTheme=this.options.colorPreset==null||!_[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&_[this.options.colorPreset]?this.options.colorPreset:R();for(let[l,n]of Object.entries(a))(this.options[l]===null||this.options[l]===void 0)&&(this.options[l]=n,this._presetKeys.push(l));let o=rt[this.options.waveformStyle];o&&(s.barWidth===void 0&&i.barWidth===void 0&&(this.options.barWidth=o.barWidth),s.barSpacing===void 0&&i.barSpacing===void 0&&(this.options.barSpacing=o.barSpacing)),this.audio=null,this.canvas=null,this.ctx=null,this.waveformData=[],this.progress=0,this._activeMarkerIndex=-1,this._markerLabelTimer=null,this.isPlaying=!1,this.isLoading=!1,this.hasError=!1,this.updateTimer=null,this.resizeObserver=null,this._ac=new AbortController,this.id=this.container.id||G(this.options.url),e.instances.set(this.id,this),e._watchTheme(),this.init(),setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,s=!1){let r=new CustomEvent(t,{bubbles:!0,cancelable:s,detail:i});return this.container.dispatchEvent(r),r}_requestSeek(t){this._emit("waveformplayer:request-seek",{...this._buildTrackDetail(),percent:t},!0).defaultPrevented||(this.progress=t,this.drawWaveform?.())}init(){this.createDOM(),this.createAudio(),this.initPlaybackSpeed(),this.initKeyboardControls(),this.initSeekControl(),this.bindEvents(),this.setupResizeObserver(),requestAnimationFrame(()=>{this.resizeCanvas(),this.options.url&&this.load(this.options.url).then(()=>{this.options.autoplay&&this.play()?.catch(()=>{})}).catch(t=>{console.error("[WaveformPlayer] Failed to load audio:",t)})})}createDOM(){this.container.innerHTML="",this.container.className="waveform-player";let t=this.options.buttonAlign;t==="auto"&&(this.options.waveformStyle==="bars"?t="bottom":t="center"),this.options.layout==="preview"&&this.container.classList.add("waveform-layout-preview"),this.container.classList.toggle("waveform-theme-light",this._scheme==="light");let s=[];this.options.buttonSize!=null&&s.push(`--wfp-btn-size: ${W(this.options.buttonSize)}`),this.options.buttonRadius!=null&&s.push(`--wfp-btn-radius: ${W(this.options.buttonRadius)}`);let r=s.length?` style="${s.join("; ")};"`:"",a=this.options.artworkPosition==="button"&&this.options.artwork,o=a?`<img class="waveform-btn-artwork" src="${S(this.options.artwork)}" alt="" aria-hidden="true">`:"",l=this.options.showControls?`
|
|
2
|
-
<button class="waveform-btn${this.options.buttonStyle==="minimal"?" waveform-btn-minimal":""}${a?" waveform-btn-has-artwork":""}" aria-label="${S(this.options.playPauseLabel)}"${
|
|
1
|
+
(()=>{function B(e){let t=-1/0;for(let i=0;i<e.length;i++)e[i]>t&&(t=e[i]);return t}function S(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function W(e){return S(typeof e=="number"?`${e}px`:e)}function G(e){if(typeof e!="string"||e==="")return!1;try{let t=new URL(e,"http://localhost/");return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function m(e,t=0,i=1){return Math.max(t,Math.min(e,i))}function ht(e){return e===void 0?void 0:e==="true"}function j(e){if(typeof e=="string"&&e.trim().startsWith("["))try{return JSON.parse(e)}catch{}return e}function H(e){let t={},i=(o,l=o)=>{let n=ht(e.dataset[l]);n!==void 0&&(t[o]=n)},r=(o,l=o,n=!1)=>{let h=e.dataset[l];h&&(t[o]=n?parseFloat(h):parseInt(h,10))},s=(o,l=o)=>{let n=e.dataset[l];n&&(t[o]=/^\d+(\.\d+)?$/.test(n.trim())?parseFloat(n):n)},a=(o,l=o)=>{let n=e.dataset[l];if(n)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),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),s("buttonSize"),s("buttonRadius"),e.dataset.colorPreset&&(t.colorPreset=e.dataset.colorPreset),e.dataset.waveformColor&&(t.waveformColor=j(e.dataset.waveformColor)),e.dataset.progressColor&&(t.progressColor=j(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),a("markers"),r("playbackRate","playbackRate",!0),i("showPlaybackSpeed"),a("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 J(e,...t){let i=0;return e.replace(/%(?:(\d+)\$)?s/g,(r,s)=>{let a=s?Number(s)-1:i++;return t[a]??r})}function E(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),s=Math.floor(t%60);return i>0?`${i}:${r.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${r}:${s.toString().padStart(2,"0")}`}var ct=0;function K(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)}_${(ct++).toString(36)}`}function R(e){if(!e)return"Audio";let t=e.split("/");return t[t.length-1].split(".")[0].replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function O(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]),s=Number(t[3]);if(!Number.isFinite(i)||!Number.isFinite(r)||!Number.isFinite(s))return null;let a=t[4]===void 0?1:Number(t[4]);return Number.isFinite(a)?(t[5]==="%"&&(a/=100),{r:i,g:r,b:s,a:m(a,0,1)}):null}function Y(e){let t=O(e);return!t||t.a<=0?null:(t.r*299+t.g*587+t.b*114)/1e3}function F(...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 X(e,t){let i;return function(...s){let a=()=>{clearTimeout(i),e(...s)};clearTimeout(i),i=setTimeout(a,t)}}function D(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 s=0;s<t;s++){let a=s*r,o=Math.floor(a),l=Math.ceil(a),n=a-o;if(l>=e.length)i.push(e[e.length-1]);else if(o===l)i.push(e[o]);else{let h=e[o]*(1-n)+e[l]*n;i.push(h)}}}else{let r=e.length/t;for(let s=0;s<t;s++){let a=Math.floor(s*r),o=Math.floor((s+1)*r),l=0,n=0;for(let h=a;h<=o&&h<e.length;h++)e[h]>l&&(l=e[h]),n++;if(n===0){let h=Math.min(Math.round(s*r),e.length-1);l=e[h]}i.push(l)}}return i}function P(e,t,i,r){if(!Array.isArray(t))return t;if(t.length<2)return t[0];let s=i.width,a=i.height,o=r&&r.waveformGradient,[l,n,h,c]=o==="horizontal"?[0,0,s,0]:o==="diagonal"?[0,0,s,a]:[0,0,0,a];try{let u=e.createLinearGradient(l,n,h,c);return t.forEach((w,g)=>u.addColorStop(g/(t.length-1),w)),u}catch{return t[0]}}function L(e,t,i,r,s,a){if((Array.isArray(a)?a.some(l=>l>0):a>0)&&typeof e.roundRect=="function"){let l=Math.min(r/2,Math.abs(s)/2),n=h=>m(h,0,l);e.beginPath(),e.roundRect(t,i,r,s,Array.isArray(a)?a.map(n):n(a)),e.fill()}else e.fillRect(t,i,r,s)}function et(e,t){return(e.barRadius||0)*t}function dt(e,t){let i=et(e,t);return[i,i,0,0]}function Q(e,t,i,r,s){let a=s/2;e.beginPath(),e.moveTo(t,r-a),e.lineTo(i-a,r-a),e.arc(i-a,r,a,-Math.PI/2,Math.PI/2),e.lineTo(t,r+a),e.arc(t,r,a,Math.PI/2,-Math.PI/2),e.closePath()}function I(e,t,i,r,s){let a=window.devicePixelRatio||1,o=s.barWidth*a,l=s.barSpacing*a,n=Math.floor(t.width/(o+l)),h=D(i,n),c=t.height,u=r*t.width,w=dt(s,a),g=P(e,s.color,t,s),k=P(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height),e.fillStyle=g;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p+o>t.width)break;let y=h[f]*c*.9,d=c-y;L(e,p,d,o,y,w)}e.save(),e.beginPath(),e.rect(0,0,u,c),e.clip(),e.fillStyle=k;for(let f=0;f<h.length;f++){let p=f*(o+l);if(p>u)break;let y=h[f]*c*.9,d=c-y;L(e,p,d,o,y,w)}e.restore()}function ut(e,t,i,r,s){let a=window.devicePixelRatio||1,o=s.barWidth*a,l=s.barSpacing*a,n=Math.floor(t.width/(o+l)),h=D(i,n),c=t.height,u=c/2,w=r*t.width,g=et(s,a),k=[g,g,0,0],f=[0,0,g,g],p=P(e,s.color,t,s),y=P(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height),e.fillStyle=p;for(let d=0;d<h.length;d++){let b=d*(o+l);if(b+o>t.width)break;let v=h[d]*c*.45;L(e,b,u-v,o,v,k),L(e,b,u,o,v,f)}e.save(),e.beginPath(),e.rect(0,0,w,c),e.clip(),e.fillStyle=y;for(let d=0;d<h.length;d++){let b=d*(o+l);if(b>w)break;let v=h[d]*c*.45;L(e,b,u-v,o,v,k),L(e,b,u,o,v,f)}e.restore()}function pt(e,t,i,r,s){let a=t.width,o=t.height,l=o/2,n=o*.35;e.clearRect(0,0,a,o);let h=(c,u,w=1,g=!1)=>{let k=P(e,c,t,s),f=Array.isArray(c)?c[c.length-1]:c;g&&(e.shadowBlur=12,e.shadowColor=f),e.strokeStyle=k,e.lineWidth=u,e.lineCap="round",e.lineJoin="round",e.beginPath(),e.moveTo(0,l);let p=[],y=Math.floor(i.length*w);for(let d=0;d<y;d++){let b=d/(i.length-1)*a,v=i[d],T=Math.sin(d*.1)*v,C=l+T*n;p.push({x:b,y:C})}for(let d=0;d<p.length-1;d++){let b=p[d].x+(p[d+1].x-p[d].x)*.5,v=p[d].y,T=p[d+1].x-(p[d+1].x-p[d].x)*.5,C=p[d+1].y;e.bezierCurveTo(b,v,T,C,p[d+1].x,p[d+1].y)}e.stroke(),g&&(e.shadowBlur=0)};e.strokeStyle="rgba(255, 255, 255, 0.03)",e.lineWidth=.5,e.beginPath(),e.moveTo(0,l),e.lineTo(a,l),e.stroke();for(let c=0;c<=10;c++){let u=a/10*c;e.beginPath(),e.moveTo(u,0),e.lineTo(u,o),e.stroke()}h(s.color,2,1,!1),r>0&&h(s.progressColor,3,r,!0)}function Z(e,t,i,r,s){let a=window.devicePixelRatio||1,o=(s.barWidth||3)*a,l=(s.barSpacing||1)*a,n=Math.floor(t.width/(o+l)),h=D(i,n),c=t.height,u=4*a,w=2*a,g=r*t.width,k=c/2,f=P(e,s.color,t,s),p=P(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height);for(let y=0;y<h.length;y++){let d=y*(o+l);if(d+o>t.width)break;let b=h[y]*c*.9,v=Math.floor(b/(u+w));e.fillStyle=d<g?p:f;for(let T=0;T<v;T++){let C=T*(u+w);e.fillRect(d,k-C-u,o,u),T>0&&e.fillRect(d,k+C,o,u)}}}function tt(e,t,i,r,s){let a=window.devicePixelRatio||1,o=(s.barWidth||2)*a,l=(s.barSpacing||3)*a,n=Math.floor(t.width/(o+l)),h=D(i,n),c=t.height,u=Math.max(1.5*a,o/2),w=r*t.width,g=c/2,k=P(e,s.color,t,s),f=P(e,s.progressColor,t,s);e.clearRect(0,0,t.width,t.height);for(let p=0;p<h.length;p++){let y=p*(o+l)+o/2;if(y>t.width)break;let d=h[p]*c*.9;e.fillStyle=y<w?f:k,e.beginPath(),e.arc(y,g-d/2,u,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(y,g+d/2,u,0,Math.PI*2),e.fill()}}function ft(e,t,i,r,s){let a=t.width,o=t.height,l=o/2,n=4,h=n/2,c=!!s.seekActive;if(e.clearRect(0,0,a,o),e.fillStyle=P(e,s.color,t,s)||"rgba(255, 255, 255, 0.2)",Q(e,h,a,l,n),e.fill(),r>0){let u=Math.max(h*2,r*a);e.save(),e.globalAlpha=s.seekHandle&&!c?.7:1,e.fillStyle=P(e,s.progressColor,t,s)||"rgba(255, 255, 255, 0.9)",Q(e,h,u,l,n),e.fill(),e.restore()}}var mt={bars:I,bar:I,mirror:ut,line:pt,blocks:Z,block:Z,dots:tt,dot:tt,seekbar:ft};function it(e,t,i,r,s){(mt[s.waveformStyle]||I)(e,t,i,r,s)}function st(e){try{let t=e.getChannelData(0),i=e.sampleRate,r=gt(t,i);if(r.length<2)return 120;let s=[];for(let n=1;n<r.length;n++)s.push((r[n]-r[n-1])/i);let a={};s.forEach(n=>{let h=60/n,c=Math.round(h/3)*3;c>60&&c<200&&(a[c]=(a[c]||0)+1)});let o=0,l=120;for(let[n,h]of Object.entries(a))h>o&&(o=h,l=parseInt(n));return l<70&&a[l*2]?l*=2:l>160&&a[Math.round(l/2)]&&(l=Math.round(l/2)),l-1}catch(t){return console.warn("[WaveformPlayer] BPM detection failed:",t),null}}function gt(e,t){let s=[],a=0;for(let o=0;o<e.length-2048;o+=1024){let l=0;for(let c=o;c<o+2048;c++)l+=e[c]*e[c];l=l/2048;let n=l-a,h=a*1.8+.01;if(n>h&&l>.01){let c=s[s.length-1]||0,u=t*.15;o-c>u&&s.push(o)}a=l*.8+a*.2}return s}function yt(e,t=1800){let i=e.length/t,r=e.numberOfChannels,s=[];for(let o=0;o<r;o++){let l=e.getChannelData(o);for(let n=0;n<t;n++){let h=~~(n*i),c=~~(h+i),u=0,w=0;for(let k=h;k<c;k++){let f=l[k];f>w&&(w=f),f<u&&(u=f)}let g=Math.max(Math.abs(w),Math.abs(u));(o===0||g>s[n])&&(s[n]=g)}}let a=B(s);return a>0?s.map(o=>o/a):s}async function $(e,t=1800,i=!1){let r;try{let s=window.AudioContext||window.webkitAudioContext;r=new s;let o=await(await fetch(e)).arrayBuffer(),l=await r.decodeAudioData(o),n=yt(l,t);n=wt(n);let h=null;return i&&(h=st(l)),{peaks:n,bpm:h}}finally{r&&r.close()}}function rt(e=1800){let t=[];for(let i=0;i<e;i++){let r=Math.random()*.5+.3,s=Math.sin(i/e*Math.PI*4)*.2;t.push(m(r+s,.1,1))}return t}function wt(e,t=.95){let i=B(e);if(i===0||i>t)return e;let r=t/i;return e.map(s=>s*r)}var z=128;function at(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 kt(e){let t=0,i=0;for(let r=e;r&&r.nodeType===1&&i<.995;r=r.parentElement){let s=O(getComputedStyle(r).backgroundColor);if(!s||s.a<=0)continue;let a=s.a*(1-i);t+=(s.r*299+s.g*587+s.b*114)/1e3*a,i+=a}return{sum:t,alpha:i}}function bt(){let e=Y(getComputedStyle(document.body).color);if(e!==null)return e>z?"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 x(e){if(at("dark"))return"dark";if(at("light"))return"light";try{let t=e&&e.nodeType===1?e:document.body,{sum:i,alpha:r}=kt(t),s=bt(),a=i+(s==="dark"?0:255)*(1-r);return a>z?"light":a<z?"dark":s}catch{return"dark"}}var _={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 q(e,t){if(e&&_[e])return _[e];let i=x(t);return _[i]}var N={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},ot={bars:{barWidth:3,barSpacing:1},mirror:{barWidth:2,barSpacing:2},line:{barWidth:2,barSpacing:0},blocks:{barWidth:4,barSpacing:2},dots:{barWidth:3,barSpacing:3},seekbar:{barWidth:1,barSpacing:0}};var vt="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,lt=10,St='button, a[href], input, [role="slider"]',A=class e{static instances=new Map;static currentlyPlaying=null;constructor(t,i={}){if(this.container=typeof t=="string"?document.querySelector(t):t,!this.container)throw new Error("[WaveformPlayer] Container element not found");let r=H(this.container),s={...i};s.style&&!s.waveformStyle&&(s.waveformStyle=s.style),s.src&&!s.url&&(s.url=s.src),this.options=F(N,r,s);let a=q(this.options.colorPreset,this.container);this._autoTheme=this.options.colorPreset==null||!_[this.options.colorPreset],this._presetKeys=[],this._scheme=this.options.colorPreset&&_[this.options.colorPreset]?this.options.colorPreset:x(this.container);for(let[l,n]of Object.entries(a))(this.options[l]===null||this.options[l]===void 0)&&(this.options[l]=n,this._presetKeys.push(l));let o=ot[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||K(this.options.url),e.instances.set(this.id,this),e._watchTheme(),this.init(),setTimeout(()=>{this._emit("waveformplayer:ready",{player:this,url:this.options.url})},100)}_emit(t,i,r=!1){let s=new CustomEvent(t,{bubbles:!0,cancelable:r,detail:i});return this.container.dispatchEvent(s),s}_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 r=[];this.options.buttonSize!=null&&r.push(`--wfp-btn-size: ${W(this.options.buttonSize)}`),this.options.buttonRadius!=null&&r.push(`--wfp-btn-radius: ${W(this.options.buttonRadius)}`);let s=r.length?` style="${r.join("; ")};"`:"",a=this.options.artworkPosition==="button"&&this.options.artwork,o=a?`<img class="waveform-btn-artwork" src="${S(this.options.artwork)}" alt="" aria-hidden="true">`:"",l=this.options.showControls?`
|
|
2
|
+
<button class="waveform-btn${this.options.buttonStyle==="minimal"?" waveform-btn-minimal":""}${a?" waveform-btn-has-artwork":""}" aria-label="${S(this.options.playPauseLabel)}"${s}>
|
|
3
3
|
${o}
|
|
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>
|
|
@@ -61,4 +61,4 @@
|
|
|
61
61
|
${n}
|
|
62
62
|
</div>
|
|
63
63
|
</div>
|
|
64
|
-
`,this.playBtn=this.container.querySelector(".waveform-btn"),this.canvas=this.container.querySelector("canvas"),this.ctx=this.canvas.getContext("2d"),this.titleEl=this.container.querySelector(".waveform-title"),this.artistEl=this.container.querySelector(".waveform-artist"),this.artworkEl=this.container.querySelector(".waveform-artwork, .waveform-btn-artwork"),this.bindArtworkFallback(this.artworkEl),this.currentTimeEl=this.container.querySelector(".time-current"),this.totalTimeEl=this.container.querySelector(".time-total"),this.bpmEl=this.container.querySelector(".waveform-bpm"),this.bpmValueEl=this.container.querySelector(".bpm-value"),this.loadingEl=this.container.querySelector(".waveform-loading"),this.errorEl=this.container.querySelector(".waveform-error"),this.markersContainer=this.container.querySelector(".waveform-markers"),this.speedBtn=this.container.querySelector(".speed-btn"),this.speedMenu=this.container.querySelector(".speed-menu"),this.resizeCanvas(),this.updateBPMDisplay()}bindArtworkFallback(t){t&&t.addEventListener("error",()=>{t.src.startsWith("data:")||(t.src=yt)},{signal:this._ac.signal})}createArtworkElement(){let t=document.createElement("img");return t.className="waveform-artwork",t.style.width="40px",t.style.height="40px",t.style.borderRadius="4px",t.style.objectFit="cover",t.style.flexShrink="0",this.bindArtworkFallback(t),t}createButtonArtworkElement(){let t=document.createElement("img");return t.className="waveform-btn-artwork",t.alt="",t.setAttribute("aria-hidden","true"),this.bindArtworkFallback(t),t}createArtistElement(){let t=document.createElement("span");return t.className="waveform-artist",t}syncArtist(t){if(this.options.artist=t||null,!!this.options.showInfo){if(!t){this.artistEl?.remove(),this.artistEl=null;return}if(!this.artistEl){let i=this.container.querySelector(".waveform-title");if(!i)return;this.artistEl=this.createArtistElement(),i.after(this.artistEl)}this.artistEl.textContent=t,this.artistEl.style.display=""}}syncButtonArtwork(t){if(this.playBtn){if(!t){this.artworkEl?.remove(),this.artworkEl=null,this.playBtn.classList.remove("waveform-btn-has-artwork");return}this.artworkEl||(this.artworkEl=this.createButtonArtworkElement(),this.playBtn.prepend(this.artworkEl)),this.artworkEl.src=t,this.playBtn.classList.add("waveform-btn-has-artwork")}}syncArtwork(t,i=""){if(this.options.artwork=t||null,this.options.artworkAlt=i||"",this.options.artworkPosition==="button"){this.syncButtonArtwork(this.options.artwork);return}if(this.options.showInfo){if(!t){this.artworkEl?.remove(),this.artworkEl=null;return}if(!this.artworkEl){let s=this.container.querySelector(".waveform-text");if(!s)return;this.artworkEl=this.createArtworkElement(),s.before(this.artworkEl)}this.artworkEl.src=t,this.artworkEl.alt=i||""}}createAudio(){if(this.options.audioMode==="external"){this.audio=null;return}this.audio=new Audio,this.audio.preload=this.options.preload||"metadata",this.options.crossOrigin&&(this.audio.crossOrigin=this.options.crossOrigin)}initPlaybackSpeed(){this.audio&&this.options.playbackRate&&this.options.playbackRate!==1&&(this.audio.playbackRate=this.options.playbackRate),this.options.showPlaybackSpeed&&this.initSpeedControls()}initSpeedControls(){let t=this.container.querySelector(".speed-btn"),i=this.container.querySelector(".speed-menu");if(!t||!i)return;let s=()=>Array.from(i.querySelectorAll(".speed-option")),r=()=>i.style.display!=="none",a=n=>{if(i.style.display=n?"block":"none",t.setAttribute("aria-expanded",n?"true":"false"),n){let h=s();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=n=>{let h=s();h.length&&h[(n+h.length)%h.length].focus()},l=n=>{this.setPlaybackRate(parseFloat(n.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",n=>{n.stopPropagation(),a(!r())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",n=>{n.stopPropagation();let h=n.target.closest(".speed-option");h&&l(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",n=>{let h=s(),c=h.indexOf(document.activeElement);if(!r()){(n.key==="ArrowDown"||n.key==="ArrowUp")&&document.activeElement===t&&(n.preventDefault(),a(!0));return}switch(n.key){case"ArrowDown":n.preventDefault(),o(c<0?0:c+1);break;case"ArrowUp":n.preventDefault(),o(c<0?h.length-1:c-1);break;case"Home":n.preventDefault(),o(0);break;case"End":n.preventDefault(),o(h.length-1);break;case"Escape":n.preventDefault(),a(!1),t.focus();break;case"Tab":a(!1);break}},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(wt)||(e.getAllInstances().forEach(i=>{i!==this&&i.container.setAttribute("tabindex","-1")}),this.container.setAttribute("tabindex","0"),this.container.focus())},{signal:this._ac.signal}),this.container.addEventListener("keydown",t=>{if(document.activeElement!==this.container)return;let i=t.key,s=!!this.audio,r=s?this.audio.currentTime:0;if(s&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let a={" ":()=>this.togglePlay()};s&&(a.ArrowLeft=()=>this.seekTo(m(r-5,0,this.audio.duration)),a.ArrowRight=()=>this.seekTo(m(r+5,0,this.audio.duration)),a.ArrowUp=()=>this.setVolume(m(this.audio.volume+.1)),a.ArrowDown=()=>this.setVolume(m(this.audio.volume-.1)),a.m=a.M=()=>this.audio.muted=!this.audio.muted),a[i]&&(t.preventDefault(),a[i]())},{signal:this._ac.signal})}initSeekControl(){this.options.accessibleSeek&&(this.seekEl=this.container.querySelector(".waveform-container"),this.seekEl&&(this.seekEl.setAttribute("role","slider"),this.seekEl.setAttribute("tabindex","0"),this.seekEl.setAttribute("aria-valuemin","0"),this.applySeekLabel(),this.updateSeekAccessibility(),this.seekEl.addEventListener("keydown",t=>{if(t.key===" "||t.key==="Spacebar"){t.preventDefault(),t.stopPropagation(),this.togglePlay();return}let i=this.getSeekDuration();if(!i)return;let s=this.getSeekCurrentTime(),r;switch(t.key){case"ArrowLeft":case"ArrowDown":r=s-at;break;case"ArrowRight":case"ArrowUp":r=s+at;break;case"PageDown":r=s-ot;break;case"PageUp":r=s+ot;break;case"Home":r=0;break;case"End":r=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(r)},{signal:this._ac.signal})))}getSeekDuration(){return this.options.audioMode==="external"?this._extDuration||0:this.audio&&Number.isFinite(this.audio.duration)?this.audio.duration:0}getSeekCurrentTime(){return this.options.audioMode==="external"?this.progress*(this._extDuration||0):this.audio&&Number.isFinite(this.audio.currentTime)?this.audio.currentTime:0}seekToSeconds(t){let i=this.getSeekDuration();if(!i)return;let s=m(t,0,i);if(this.options.audioMode==="external"){this._requestSeek(s/i),this.updateSeekAccessibility();return}this.seekTo(s)}applySeekLabel(t=this.options.title){if(!this.seekEl)return;let i=this.options.seekLabel||t||"Seek";this.seekEl.setAttribute("aria-label",i)}updateSeekAccessibility(){if(!this.seekEl)return;let t=this.getSeekDuration(),i=Math.min(this.getSeekCurrentTime(),t);this.seekEl.setAttribute("aria-valuemax",String(Math.round(t))),this.seekEl.setAttribute("aria-valuenow",String(Math.round(i))),this.seekEl.setAttribute("aria-valuetext",j(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;this._applyMediaMetadata(),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(m(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(m(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",s=>{s.seekTime!==null&&this.seekTo(s.seekTime)});let t=this.options.onNextTrack,i=this.options.onPreviousTrack;try{navigator.mediaSession.setActionHandler("nexttrack",typeof t=="function"?()=>t(this):null)}catch{}try{navigator.mediaSession.setActionHandler("previoustrack",typeof i=="function"?()=>i(this):null)}catch{}}_applyMediaMetadata(){!("mediaSession"in navigator)||!this.options.enableMediaSession||(navigator.mediaSession.metadata=new MediaMetadata({title:this.options.title||this.options.unknownTrackText,artist:this.options.artist||"",album:this.options.album||"",artwork:this.options.artwork?[{src:this.options.artwork,sizes:"512x512",type:"image/jpeg"}]:[]}))}_updateMediaSession(t){if(!(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio))try{t==="playing"&&this.initMediaSession(),navigator.mediaSession.playbackState=t;let i=this.audio.duration;navigator.mediaSession.setPositionState&&i&&isFinite(i)&&navigator.mediaSession.setPositionState({duration:i,playbackRate:this.audio.playbackRate||1,position:m(this.audio.currentTime,0,i)})}catch{}}bindEvents(){this.playBtn&&this.playBtn.addEventListener("click",()=>this.togglePlay()),this.audio&&(this.audio.addEventListener("loadstart",()=>this.setLoading(!0)),this.audio.addEventListener("loadedmetadata",()=>this.onMetadataLoaded()),this.audio.addEventListener("canplay",()=>this.setLoading(!1)),this.audio.addEventListener("play",()=>this.onPlay()),this.audio.addEventListener("pause",()=>this.onPause()),this.audio.addEventListener("ended",()=>this.onEnded()),this.audio.addEventListener("error",i=>this.onError(i))),this.canvas.addEventListener("click",i=>this.handleCanvasClick(i)),this._dragging=!1,this._seekHover=!1,this._handleNear=!1,this.canvas.addEventListener("pointerenter",()=>{this._seekHover=!0,this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerleave",()=>{this._seekHover=!1,this._handleNear=!1,this._dragging||this._hideHoverTip(),this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerdown",i=>{if(!(i.pointerType==="mouse"&&i.button!==0)){this._dragging=!0;try{this.canvas.setPointerCapture(i.pointerId)}catch{}this._scrubTo(i.clientX)}}),this.canvas.addEventListener("pointermove",i=>{if(this._dragging){this._scrubTo(i.clientX);return}let s=this.canvas.getBoundingClientRect();s.width&&(this._handleNear=Math.abs(i.clientX-s.left-this.progress*s.width)<=10,this._updateSeekHandle())});let t=i=>{if(this._dragging){this._dragging=!1,this._suppressClick=!0;try{this.canvas.releasePointerCapture(i.pointerId)}catch{}this._seekFromPointer(i.clientX),!this._seekHover&&!this.options.showHoverTime&&this._hideHoverTip(),this._updateSeekHandle()}};this.canvas.addEventListener("pointerup",t),this.canvas.addEventListener("pointercancel",t),this.setupHoverTime(),this.setupSeekHandle(),this.resizeHandler=K(()=>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"),this.audio&&(this.audio.src=t,await new Promise((s,r)=>{let a=()=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),s()},o=l=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),r(l)};this.audio.addEventListener("loadedmetadata",a),this.audio.addEventListener("error",o)}));let i=this.options.title||H(t);if(this.titleEl&&(this.titleEl.textContent=i),this.applySeekLabel(i),this.options.waveform)this.setWaveformData(this.options.waveform);else try{let s=await F(t,this.options.samples,this.options.showBPM);this.waveformData=s.peaks,s.bpm&&(this.detectedBPM=s.bpm,this.updateBPMDisplay())}catch(s){console.warn("[WaveformPlayer] Using placeholder waveform:",s),this.waveformData=it(this.options.samples),this.container.classList.add("waveform-is-placeholder")}this.drawWaveform(),this.renderMarkers(),this.options.onLoad&&this.options.onLoad(this)}catch(i){this.onError(i)}finally{this.setLoading(!1)}}async loadTrack(t,i=null,s=null,r={}){let a=Object.prototype.hasOwnProperty.call(r,"artwork"),o=Object.prototype.hasOwnProperty.call(r,"artworkAlt");this.isPlaying&&this.pause(),this.audio&&(this.audio.src="",this.audio.load()),this.hasError=!1,this.errorEl&&(this.errorEl.style.display="none"),this.canvas&&(this.canvas.style.opacity="1"),this.playBtn&&(this.playBtn.disabled=!1),this.progress=0,this.waveformData=[],this.options=O(this.options,{url:t,title:i===null?this.options.title:i,artist:s===null?this.options.artist:s,...r}),a&&(this.options.artwork=r.artwork||null),o?this.options.artworkAlt=r.artworkAlt||"":a&&(this.options.artworkAlt=this.options.artwork?z.artworkAlt:""),r.preload&&this.audio&&(this.audio.preload=r.preload),r.crossOrigin&&this.audio&&(this.audio.crossOrigin=r.crossOrigin),s!==null&&this.syncArtist(s),(a||o)&&this.syncArtwork(a?r.artwork:this.options.artwork,o?r.artworkAlt:this.options.artworkAlt),this.options.markers=r.markers||[],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||tt(this.ctx,this.canvas,this.waveformData,this.progress,{...this.options,waveformStyle:this.options.waveformStyle||"bars",color:this.options.waveformColor,progressColor:this.options.progressColor,seekActive:this._seekHover||this._dragging})}resizeCanvas(){if(!this.canvas||this.isDestroying)return;let t=window.devicePixelRatio||1,i=this.canvas.parentElement.getBoundingClientRect();this.canvas.width=i.width*t,this.canvas.height=this.options.height*t,this.canvas.parentElement.style.height=this.options.height+"px",this.drawWaveform()}renderMarkers(){if(!this.markersContainer||(this.markersContainer.innerHTML="",this._activeMarkerIndex=-1,clearTimeout(this._markerLabelTimer),!this.options.showMarkers||!this.options.markers?.length))return;let t=this.getSeekDuration();t&&this.options.markers.forEach((i,s)=>{if(i.time>t){console.warn(`[WaveformPlayer] Marker "${i.label}" at ${i.time}s exceeds audio duration of ${t}s`);return}let r=i.time/t*100,a=document.createElement("button");a.className="waveform-marker",a.style.left=`${r}%`,a.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",a.setAttribute("aria-label",i.label),a.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,a.appendChild(o),a.addEventListener("click",l=>{l.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(a)})}setActiveMarker(t){if(!this.markersContainer)return;this.markersContainer.querySelectorAll(".waveform-marker").forEach((s,r)=>s.classList.toggle("active",r===t))}updateActiveMarker(){if(!this.markersContainer)return;let t=this.markersContainer.querySelectorAll(".waveform-marker");if(!t.length)return;let i=this.getSeekDuration(),s=i?this.progress*i:0,r=-1,a=-1/0;t.forEach((o,l)=>{let n=parseFloat(o.getAttribute("data-time"));Number.isFinite(n)&&n<=s+.05&&n>a&&(a=n,r=l)}),r!==this._activeMarkerIndex&&(this._activeMarkerIndex=r,this.setActiveMarker(r),clearTimeout(this._markerLabelTimer),t.forEach((o,l)=>o.classList.toggle("show-label",l===r)),r>=0&&(this._markerLabelTimer=setTimeout(()=>{this.markersContainer?.querySelectorAll(".waveform-marker").forEach(o=>o.classList.remove("show-label"))},2500)))}setupHoverTime(){if(!this.seekEl)return;let t=document.createElement("div");t.className="waveform-hover-time",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.hoverTimeEl=t,this.options.showHoverTime&&(this.seekEl.addEventListener("pointermove",i=>{this._dragging||this._updateHoverTip(i.clientX)}),this.seekEl.addEventListener("pointerleave",()=>{this._dragging||this._hideHoverTip()}))}_updateHoverTip(t){let i=this.hoverTimeEl;if(!i)return;let s=this.getSeekDuration();if(!s){i.style.opacity="0";return}let r=this.canvas.getBoundingClientRect(),a=m((t-r.left)/r.width);i.textContent=E(a*s),i.style.left=a*100+"%",i.style.opacity="1"}_hideHoverTip(){this.hoverTimeEl&&(this.hoverTimeEl.style.opacity="0")}_scrubTo(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;this.progress=m((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle();let s=this.getSeekDuration();s&&this.currentTimeEl?(this.currentTimeEl.textContent=E(this.progress*s),this._hideHoverTip()):this._updateHoverTip(t)}setupSeekHandle(){if(!this.options.seekHandle||this.options.waveformStyle!=="seekbar"||!this.seekEl)return;let t=document.createElement("div");t.className="waveform-seek-handle",t.setAttribute("aria-hidden","true"),this.seekEl.appendChild(t),this.seekHandleEl=t}_updateSeekHandle(){let t=this.seekHandleEl;t&&(t.style.left=this.progress*100+"%",t.classList.toggle("is-visible",this._seekHover||this._dragging),t.classList.toggle("is-active",this._dragging||this._handleNear))}handleCanvasClick(t){if(this._suppressClick){this._suppressClick=!1;return}this._seekFromPointer(t.clientX)}_seekFromPointer(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;let s=m((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(s);return}!this.audio||!this.audio.duration||this.seekToPercent(s)}setLoading(t){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=E(this.audio.duration)),this.renderMarkers(),this.updateSeekAccessibility())}setPlayButtonState(t){if(!this.playBtn)return;this.playBtn.classList.toggle("playing",t);let i=this.playBtn.querySelector(".waveform-icon-play"),s=this.playBtn.querySelector(".waveform-icon-pause");i&&(i.style.display=t?"none":"flex"),s&&(s.style.display=t?"flex":"none")}onPlay(){this.isDestroying||(this.isPlaying=!0,this.setPlayButtonState(!0),this.startSmoothUpdate(),this._updateMediaSession("playing"),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this))}onPause(){this.isDestroying||(this.isPlaying=!1,this.setPlayButtonState(!1),this.stopSmoothUpdate(),this._updateMediaSession("paused"),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}onEnded(){if(this.isDestroying)return;let t=this.audio.duration;this.progress=0,this.audio.currentTime=0,this.drawWaveform(),this.currentTimeEl&&(this.currentTimeEl.textContent="0:00"),this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:t,duration:t}),this.onPause(),this.options.onEnd&&this.options.onEnd(this)}onError(t){this.isDestroying||(console.error("[WaveformPlayer] Audio error:",t),this.hasError=!0,this.setLoading(!1),this.errorEl&&(this.errorEl.style.display="flex"),this.canvas&&(this.canvas.style.opacity="0.2"),this.playBtn&&(this.playBtn.disabled=!0),this.options.onError&&this.options.onError(t,this))}startSmoothUpdate(){this.stopSmoothUpdate();let t=()=>{this.isPlaying&&this.audio&&this.audio.duration&&(this.updateProgress(),this.updateTimer=requestAnimationFrame(t))};this.updateTimer=requestAnimationFrame(t)}stopSmoothUpdate(){this.updateTimer&&(cancelAnimationFrame(this.updateTimer),this.updateTimer=null)}updateProgress(){if(!this.audio||!this.audio.duration||this._dragging)return;let t=this.audio.currentTime/this.audio.duration;Math.abs(t-this.progress)>.001&&(this.progress=t,this.drawWaveform(),this._updateSeekHandle()),this.currentTimeEl&&(this.currentTimeEl.textContent=E(this.audio.currentTime)),this._emit("waveformplayer:timeupdate",{player:this,currentTime:this.audio.currentTime,duration:this.audio.duration,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(this.audio.currentTime,this.audio.duration,this),this.updateActiveMarker(),this.updateSeekAccessibility()}updateBPMDisplay(){let t=this.options.bpm||this.detectedBPM;this.bpmEl&&this.bpmValueEl&&t&&(this.bpmValueEl.textContent=Math.round(t),this.bpmEl.style.display="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=R();let t=$(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(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(a=>{try{a.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},s=new MutationObserver(t);s.observe(document.documentElement,i),document.body&&s.observe(document.body,i);let r=null;try{r=window.matchMedia("(prefers-color-scheme: dark)"),r.addEventListener("change",t)}catch{}e._themeWatch={obs:s,mq:r,refresh:t}}updateSpeedUI(){if(!this.audio)return;let t=this.container.querySelector(".speed-value");if(t){let i=this.audio.playbackRate;t.textContent=i===1?"1x":`${i}x`}this.container.querySelectorAll(".speed-option").forEach(i=>{let s=parseFloat(i.dataset.rate)===this.audio.playbackRate;i.classList.toggle("active",s),i.setAttribute("aria-checked",s?"true":"false")})}play(){if(this.options.singlePlay&&e.currentlyPlaying&&e.currentlyPlaying!==this&&e.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(e.currentlyPlaying=this);return}return e.currentlyPlaying=this,this.audio.play()}pause(){if(e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.options.audioMode==="external"){this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0);return}this.audio.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,artist:this.options.artist,artwork:this.options.artwork,markers:this.options.markers,waveform:this.options.waveform,id:this.id,player:this}}setPlayingState(t){let i=this.isPlaying;this.isPlaying=!!t,this.setPlayButtonState(this.isPlaying),this.isPlaying&&!i?(this.startSmoothUpdate?.(),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this)):!this.isPlaying&&i&&(this.stopSmoothUpdate?.(),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}setProgress(t,i){!i||i<=0||(this.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=E(i),this.totalTimeEl.dataset._extSet="1",this.totalTimeEl.dataset._extDur=String(i)),this.drawWaveform?.(),this.updateActiveMarker(),this._emit("waveformplayer:timeupdate",{player:this,currentTime:t,duration:i,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(t,i,this),this.progress>=1?this._extEnded||(this._extEnded=!0,this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:i,duration:i}),this.options.onEnd&&this.options.onEnd(this)):this._extEnded=!1,this.updateSeekAccessibility())}togglePlay(){this.isPlaying?this.pause():this.play()}seekTo(t){this.audio&&this.audio.duration&&(this.audio.currentTime=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=m(i))}setPlaybackRate(t){if(!this.audio)return;let i=m(t,.5,2);this.audio.playbackRate=i,this.options.playbackRate=i,this.updateSpeedUI()}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.pause(),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),this._ac?.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),e.instances.delete(this.id),e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",this.canvas=null,this.ctx=null,this.playBtn=null,this.waveformData=[]}static getInstance(t){if(typeof t=="string"){let i=this.instances.get(t);if(i)return i;let s=document.getElementById(t);if(s)return Array.from(this.instances.values()).find(r=>r.container===s)}if(t instanceof HTMLElement)return Array.from(this.instances.values()).find(i=>i.container===t)}static getAllInstances(){return Array.from(this.instances.values())}static destroyAll(){this.instances.forEach(t=>t.destroy()),this.instances.clear()}static async generateWaveformData(t,i=1800){try{return(await F(t,i)).peaks}catch(s){throw console.error("[WaveformPlayer] Failed to generate waveform:",s),s}}static getPeaksUrl(t){if(!t)return;let i=t.replace(/\.(mp3|wav|ogg|flac|m4a|aac)(\?[^#]*)?(#.*)?$/i,".json$2$3");return i===t?void 0:i}};A.utils={formatTime:E,extractTitleFromUrl:H,escapeHtml:S,isSafeHref:V,parseDataAttributes:D};var U=()=>typeof window<"u"&&typeof document<"u";function q(){if(!U())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(t.dataset.waveformInitialized!=="true")try{new A(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}U()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",q):q());A.init=q;U()&&(window.WaveformPlayer=A);var Bt=A;})();
|
|
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=vt)},{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")),s=()=>i.style.display!=="none",a=n=>{if(i.style.display=n?"block":"none",t.setAttribute("aria-expanded",n?"true":"false"),n){let h=r();(h.find(c=>c.getAttribute("aria-checked")==="true")||h[0])?.focus()}},o=n=>{let h=r();h.length&&h[(n+h.length)%h.length].focus()},l=n=>{this.setPlaybackRate(parseFloat(n.dataset.rate)),a(!1),t.focus()};t.addEventListener("click",n=>{n.stopPropagation(),a(!s())},{signal:this._ac.signal}),document.addEventListener("click",()=>a(!1),{signal:this._ac.signal}),i.addEventListener("click",n=>{n.stopPropagation();let h=n.target.closest(".speed-option");h&&l(h)},{signal:this._ac.signal}),t.closest(".waveform-speed")?.addEventListener("keydown",n=>{let h=r(),c=h.indexOf(document.activeElement);if(!s()){(n.key==="ArrowDown"||n.key==="ArrowUp")&&document.activeElement===t&&(n.preventDefault(),a(!0));return}switch(n.key){case"ArrowDown":n.preventDefault(),o(c<0?0:c+1);break;case"ArrowUp":n.preventDefault(),o(c<0?h.length-1:c-1);break;case"Home":n.preventDefault(),o(0);break;case"End":n.preventDefault(),o(h.length-1);break;case"Escape":n.preventDefault(),a(!1),t.focus();break;case"Tab":a(!1);break}},{signal:this._ac.signal}),this.updateSpeedUI()}initKeyboardControls(){this.container.setAttribute("tabindex","-1"),this.container.addEventListener("click",t=>{t.target.closest(St)||(e.getAllInstances().forEach(i=>{i!==this&&i.container.setAttribute("tabindex","-1")}),this.container.setAttribute("tabindex","0"),this.container.focus())},{signal:this._ac.signal}),this.container.addEventListener("keydown",t=>{if(document.activeElement!==this.container)return;let i=t.key,r=!!this.audio,s=r?this.audio.currentTime:0;if(r&&i>="0"&&i<="9"){t.preventDefault(),this.seekToPercent(parseInt(i)/10);return}let a={" ":()=>this.togglePlay()};r&&(a.ArrowLeft=()=>this.seekTo(m(s-5,0,this.audio.duration)),a.ArrowRight=()=>this.seekTo(m(s+5,0,this.audio.duration)),a.ArrowUp=()=>this.setVolume(m(this.audio.volume+.1)),a.ArrowDown=()=>this.setVolume(m(this.audio.volume-.1)),a.m=a.M=()=>this.audio.muted=!this.audio.muted),a[i]&&(t.preventDefault(),a[i]())},{signal:this._ac.signal})}initSeekControl(){this.options.accessibleSeek&&(this.seekEl=this.container.querySelector(".waveform-container"),this.seekEl&&(this.seekEl.setAttribute("role","slider"),this.seekEl.setAttribute("tabindex","0"),this.seekEl.setAttribute("aria-valuemin","0"),this.applySeekLabel(),this.updateSeekAccessibility(),this.seekEl.addEventListener("keydown",t=>{if(t.key===" "||t.key==="Spacebar"){t.preventDefault(),t.stopPropagation(),this.togglePlay();return}let i=this.getSeekDuration();if(!i)return;let r=this.getSeekCurrentTime(),s;switch(t.key){case"ArrowLeft":case"ArrowDown":s=r-nt;break;case"ArrowRight":case"ArrowUp":s=r+nt;break;case"PageDown":s=r-lt;break;case"PageUp":s=r+lt;break;case"Home":s=0;break;case"End":s=i;break;default:return}t.preventDefault(),t.stopPropagation(),this.seekToSeconds(s)},{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=m(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",J(this.options.seekValueText||"%1$s of %2$s",E(i),E(t)))}initMediaSession(){if(!("mediaSession"in navigator)||!this.options.enableMediaSession||!this.audio)return;this._applyMediaMetadata(),navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("seekbackward",()=>{this.seekTo(m(this.audio.currentTime-10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekforward",()=>{this.seekTo(m(this.audio.currentTime+10,0,this.audio.duration))}),navigator.mediaSession.setActionHandler("seekto",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:m(this.audio.currentTime,0,i)})}catch{}}bindEvents(){this.playBtn&&this.playBtn.addEventListener("click",()=>this.togglePlay()),this.audio&&(this.audio.addEventListener("loadstart",()=>this.setLoading(!0)),this.audio.addEventListener("loadedmetadata",()=>this.onMetadataLoaded()),this.audio.addEventListener("canplay",()=>this.setLoading(!1)),this.audio.addEventListener("play",()=>this.onPlay()),this.audio.addEventListener("pause",()=>this.onPause()),this.audio.addEventListener("ended",()=>this.onEnded()),this.audio.addEventListener("error",i=>this.onError(i))),this.canvas.addEventListener("click",i=>this.handleCanvasClick(i)),this._dragging=!1,this._seekHover=!1,this._handleNear=!1,this.canvas.addEventListener("pointerenter",()=>{this._seekHover=!0,this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerleave",()=>{this._seekHover=!1,this._handleNear=!1,this._dragging||this._hideHoverTip(),this.drawWaveform(),this._updateSeekHandle()}),this.canvas.addEventListener("pointerdown",i=>{if(!(i.pointerType==="mouse"&&i.button!==0)){this._dragging=!0;try{this.canvas.setPointerCapture(i.pointerId)}catch{}this._scrubTo(i.clientX)}}),this.canvas.addEventListener("pointermove",i=>{if(this._dragging){this._scrubTo(i.clientX);return}let 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=X(()=>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"),this.audio&&(this.audio.src=t,await new Promise((r,s)=>{let a=()=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),r()},o=l=>{this.audio.removeEventListener("loadedmetadata",a),this.audio.removeEventListener("error",o),s(l)};this.audio.addEventListener("loadedmetadata",a),this.audio.addEventListener("error",o)}));let i=this.options.title||R(t);if(this.titleEl&&(this.titleEl.textContent=i),this.applySeekLabel(i),this.options.waveform)this.setWaveformData(this.options.waveform);else try{let r=await $(t,this.options.samples,this.options.showBPM);this.waveformData=r.peaks,r.bpm&&(this.detectedBPM=r.bpm,this.updateBPMDisplay())}catch(r){console.warn("[WaveformPlayer] Using placeholder waveform:",r),this.waveformData=rt(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,s={}){let a=Object.prototype.hasOwnProperty.call(s,"artwork"),o=Object.prototype.hasOwnProperty.call(s,"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=F(this.options,{url:t,title:i===null?this.options.title:i,artist:r===null?this.options.artist:r,...s}),a&&(this.options.artwork=s.artwork||null),o?this.options.artworkAlt=s.artworkAlt||"":a&&(this.options.artworkAlt=this.options.artwork?N.artworkAlt:""),s.preload&&this.audio&&(this.audio.preload=s.preload),s.crossOrigin&&this.audio&&(this.audio.crossOrigin=s.crossOrigin),r!==null&&this.syncArtist(r),(a||o)&&this.syncArtwork(a?s.artwork:this.options.artwork,o?s.artworkAlt:this.options.artworkAlt),this.options.markers=s.markers||[],this.options.waveform=s.waveform||null,await this.load(t),s.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||it(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 s=i.time/t*100,a=document.createElement("button");a.className="waveform-marker",a.style.left=`${s}%`,a.style.backgroundColor=i.color||"rgba(255, 255, 255, 0.5)",a.setAttribute("aria-label",i.label),a.setAttribute("data-time",i.time);let o=document.createElement("span");o.className="waveform-marker-tooltip",o.textContent=i.label,a.appendChild(o),a.addEventListener("click",l=>{l.stopPropagation(),this.seekTo(i.time),this.options.playOnSeek&&!this.isPlaying&&this.play()}),this.markersContainer.appendChild(a)})}setActiveMarker(t){if(!this.markersContainer)return;this.markersContainer.querySelectorAll(".waveform-marker").forEach((r,s)=>r.classList.toggle("active",s===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,s=-1,a=-1/0;t.forEach((o,l)=>{let n=parseFloat(o.getAttribute("data-time"));Number.isFinite(n)&&n<=r+.05&&n>a&&(a=n,s=l)}),s!==this._activeMarkerIndex&&(this._activeMarkerIndex=s,this.setActiveMarker(s),clearTimeout(this._markerLabelTimer),t.forEach((o,l)=>o.classList.toggle("show-label",l===s)),s>=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 s=this.canvas.getBoundingClientRect(),a=m((t-s.left)/s.width);i.textContent=E(a*r),i.style.left=a*100+"%",i.style.opacity="1"}_hideHoverTip(){this.hoverTimeEl&&(this.hoverTimeEl.style.opacity="0")}_scrubTo(t){let i=this.canvas.getBoundingClientRect();if(!i.width)return;this.progress=m((t-i.left)/i.width),this.drawWaveform(),this._updateSeekHandle();let r=this.getSeekDuration();r&&this.currentTimeEl?(this.currentTimeEl.textContent=E(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=m((t-i.left)/i.width);if(this.options.audioMode==="external"){this._requestSeek(r);return}!this.audio||!this.audio.duration||this.seekToPercent(r)}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=E(this.audio.duration)),this.renderMarkers(),this.updateSeekAccessibility())}setPlayButtonState(t){if(!this.playBtn)return;this.playBtn.classList.toggle("playing",t);let i=this.playBtn.querySelector(".waveform-icon-play"),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=E(this.audio.currentTime)),this._emit("waveformplayer:timeupdate",{player:this,currentTime:this.audio.currentTime,duration:this.audio.duration,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(this.audio.currentTime,this.audio.duration,this),this.updateActiveMarker(),this.updateSeekAccessibility()}updateBPMDisplay(){let t=this.options.bpm||this.detectedBPM;this.bpmEl&&this.bpmValueEl&&t&&(this.bpmValueEl.textContent=Math.round(t),this.bpmEl.style.display="inline-flex")}refreshTheme(){if(!this._autoTheme)return;this._scheme=x(this.container);let t=q(this.options.colorPreset,this.container);for(let i of this._presetKeys||[])i in t&&(this.options[i]=t[i]);this._applyThemeColors()}_applyThemeColors(){this.container.classList.toggle("waveform-theme-light",this._scheme==="light"),this.canvas&&this.drawWaveform()}static _watchTheme(){if(e._themeWatch||typeof document>"u")return;let t=()=>requestAnimationFrame(()=>{e.instances.forEach(a=>{try{a.refreshTheme()}catch{}})}),i={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]},r=new MutationObserver(t);r.observe(document.documentElement,i),document.body&&r.observe(document.body,i);let s=null;try{s=window.matchMedia("(prefers-color-scheme: dark)"),s.addEventListener("change",t)}catch{}e._themeWatch={obs:r,mq:s,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&&e.currentlyPlaying&&e.currentlyPlaying!==this&&e.currentlyPlaying.pause(),this.options.audioMode==="external"){this._emit("waveformplayer:request-play",this._buildTrackDetail(),!0).defaultPrevented||(e.currentlyPlaying=this);return}return e.currentlyPlaying=this,this.audio.play()}pause(){if(e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.options.audioMode==="external"){this._emit("waveformplayer:request-pause",this._buildTrackDetail(),!0);return}this.audio.pause()}_buildTrackDetail(){return{url:this.options.url,title:this.options.title,artist:this.options.artist,artwork:this.options.artwork,markers:this.options.markers,waveform:this.options.waveform,id:this.id,player:this}}setPlayingState(t){let i=this.isPlaying;this.isPlaying=!!t,this.setPlayButtonState(this.isPlaying),this.isPlaying&&!i?(this.startSmoothUpdate?.(),this._emit("waveformplayer:play",{player:this,url:this.options.url}),this.options.onPlay&&this.options.onPlay(this)):!this.isPlaying&&i&&(this.stopSmoothUpdate?.(),this._emit("waveformplayer:pause",{player:this,url:this.options.url}),this.options.onPause&&this.options.onPause(this))}setProgress(t,i){!i||i<=0||(this.progress=m(t/i),this.currentTimeEl&&(this.currentTimeEl.textContent=E(t)),this._extDuration=i,this.totalTimeEl&&(!this.totalTimeEl.dataset._extSet||this.totalTimeEl.dataset._extDur!==String(i))&&(this.totalTimeEl.textContent=E(i),this.totalTimeEl.dataset._extSet="1",this.totalTimeEl.dataset._extDur=String(i)),this.drawWaveform?.(),this.updateActiveMarker(),this._emit("waveformplayer:timeupdate",{player:this,currentTime:t,duration:i,progress:this.progress,url:this.options.url}),this.options.onTimeUpdate&&this.options.onTimeUpdate(t,i,this),this.progress>=1?this._extEnded||(this._extEnded=!0,this._emit("waveformplayer:ended",{player:this,url:this.options.url,currentTime:i,duration:i}),this.options.onEnd&&this.options.onEnd(this)):this._extEnded=!1,this.updateSeekAccessibility())}togglePlay(){this.isPlaying?this.pause():this.play()}seekTo(t){this.audio&&this.audio.duration&&(this.audio.currentTime=m(t,0,this.audio.duration),this.updateProgress())}seekToPercent(t){this.audio&&this.audio.duration&&(this.audio.currentTime=this.audio.duration*m(t),this.updateProgress())}setVolume(t){let i=Number(t);this.audio&&Number.isFinite(i)&&(this.audio.volume=m(i))}setPlaybackRate(t){if(!this.audio)return;let i=m(t,.5,2);this.audio.playbackRate=i,this.options.playbackRate=i,this.updateSpeedUI()}destroy(){this.isDestroying=!0,this._emit("waveformplayer:destroy",{player:this,url:this.options.url}),this.pause(),this.stopSmoothUpdate(),clearTimeout(this._markerLabelTimer),this._ac?.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeHandler&&(window.removeEventListener("resize",this.resizeHandler),this.resizeHandler=null),e.instances.delete(this.id),e.currentlyPlaying===this&&(e.currentlyPlaying=null),this.audio&&(this.audio.pause(),this.audio.src="",this.audio.load(),this.audio=null),this.container.innerHTML="",this.canvas=null,this.ctx=null,this.playBtn=null,this.waveformData=[]}static getInstance(t){if(typeof t=="string"){let i=this.instances.get(t);if(i)return i;let r=document.getElementById(t);if(r)return Array.from(this.instances.values()).find(s=>s.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 $(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}};A.utils={formatTime:E,extractTitleFromUrl:R,escapeHtml:S,isSafeHref:G,parseDataAttributes:H,detectColorScheme:x};var V=()=>typeof window<"u"&&typeof document<"u";function U(){if(!V())return;document.querySelectorAll("[data-waveform-player]").forEach(t=>{if(t.dataset.waveformInitialized!=="true")try{new A(t),t.dataset.waveformInitialized="true"}catch(i){console.error("[WaveformPlayer] Failed to initialize:",i,t)}})}V()&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",U):U());A.init=U;V()&&(window.WaveformPlayer=A);var $t=A;})();
|
package/index.d.ts
CHANGED
|
@@ -413,6 +413,13 @@ export declare class WaveformPlayer {
|
|
|
413
413
|
* Lets wrappers inherit the complete option surface without drifting.
|
|
414
414
|
*/
|
|
415
415
|
parseDataAttributes(element: HTMLElement): Partial<WaveformPlayerOptions>;
|
|
416
|
+
/**
|
|
417
|
+
* Detect whether the page around `element` reads as light or dark —
|
|
418
|
+
* explicit theme classes/attributes first, then the backdrop actually
|
|
419
|
+
* visible behind it (every ancestor background composited over the UA
|
|
420
|
+
* canvas). Pass the element the caller is theming; defaults to `<body>`.
|
|
421
|
+
*/
|
|
422
|
+
detectColorScheme(element?: Element): 'dark' | 'light';
|
|
416
423
|
};
|
|
417
424
|
}
|
|
418
425
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arraypress/waveform-player",
|
|
3
|
-
"version": "1.24.
|
|
3
|
+
"version": "1.24.3",
|
|
4
4
|
"description": "Lightweight, customizable audio player with waveform visualization",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./index.d.ts",
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
"build": "npm run build:css && npm run build:iife && npm run build:esm && npm run build:cjs && npm run build:min",
|
|
30
30
|
"build:css": "esbuild src/css/waveform-player.css --minify --outfile=dist/waveform-player.css",
|
|
31
31
|
"build:iife": "esbuild src/js/index.js --bundle --format=iife --outfile=dist/waveform-player.js",
|
|
32
|
-
"build:min": "esbuild src/js/index.js --bundle --format=iife --outfile=dist/waveform-player.min.js --minify
|
|
33
|
-
"build:esm": "esbuild src/js/index.js --bundle --format=esm --outfile=dist/waveform-player.esm.js --minify
|
|
34
|
-
"build:cjs": "esbuild src/js/index.js --bundle --format=cjs --outfile=dist/waveform-player.cjs
|
|
32
|
+
"build:min": "esbuild src/js/index.js --bundle --format=iife --outfile=dist/waveform-player.min.js --minify",
|
|
33
|
+
"build:esm": "esbuild src/js/index.js --bundle --format=esm --outfile=dist/waveform-player.esm.js --minify",
|
|
34
|
+
"build:cjs": "esbuild src/js/index.js --bundle --format=cjs --outfile=dist/waveform-player.cjs",
|
|
35
35
|
"dev": "npm run build:css && esbuild src/js/index.js --bundle --format=iife --outfile=dist/waveform-player.js --watch",
|
|
36
36
|
"dev:css": "esbuild src/css/waveform-player.css --outfile=dist/waveform-player.css --watch",
|
|
37
37
|
"dev:demo": "npm run build:css && concurrently \"npm run dev\" \"npm run dev:css\"",
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"serve": "npx http-server -p 8000",
|
|
40
40
|
"test": "vitest run",
|
|
41
41
|
"test:watch": "vitest",
|
|
42
|
+
"test:visual": "node test/visual/theme-matrix.mjs",
|
|
42
43
|
"prepublishOnly": "npm run test && npm run build"
|
|
43
44
|
},
|
|
44
45
|
"keywords": [
|
package/src/js/core.js
CHANGED
|
@@ -90,8 +90,10 @@ export class WaveformPlayer {
|
|
|
90
90
|
// Merge options: defaults < data attributes < constructor options
|
|
91
91
|
this.options = mergeOptions(DEFAULT_OPTIONS, dataOptions, userOptions);
|
|
92
92
|
|
|
93
|
-
// Apply color preset (auto-detect if not specified)
|
|
94
|
-
|
|
93
|
+
// Apply color preset (auto-detect if not specified). Detection reads
|
|
94
|
+
// the backdrop behind THIS container, so a player dropped into a themed
|
|
95
|
+
// card matches the card rather than the page.
|
|
96
|
+
const preset = getColorPreset(this.options.colorPreset, this.container);
|
|
95
97
|
|
|
96
98
|
// Track auto-theme state so the player can re-detect on a runtime light/
|
|
97
99
|
// dark switch. Only colours the user LEFT UNSET follow the preset; an
|
|
@@ -100,7 +102,7 @@ export class WaveformPlayer {
|
|
|
100
102
|
this._presetKeys = [];
|
|
101
103
|
// Resolved scheme name for the CSS theme class (CSS provides the DOM
|
|
102
104
|
// chrome colours via --wfp-* variables).
|
|
103
|
-
this._scheme = (this.options.colorPreset && COLOR_PRESETS[this.options.colorPreset]) ? this.options.colorPreset : detectColorScheme();
|
|
105
|
+
this._scheme = (this.options.colorPreset && COLOR_PRESETS[this.options.colorPreset]) ? this.options.colorPreset : detectColorScheme(this.container);
|
|
104
106
|
|
|
105
107
|
// Apply preset colors only if individual colors aren't explicitly set
|
|
106
108
|
for (const [key, value] of Object.entries(preset)) {
|
|
@@ -1989,8 +1991,8 @@ export class WaveformPlayer {
|
|
|
1989
1991
|
*/
|
|
1990
1992
|
refreshTheme() {
|
|
1991
1993
|
if (!this._autoTheme) return;
|
|
1992
|
-
this._scheme = detectColorScheme();
|
|
1993
|
-
const preset = getColorPreset(this.options.colorPreset);
|
|
1994
|
+
this._scheme = detectColorScheme(this.container);
|
|
1995
|
+
const preset = getColorPreset(this.options.colorPreset, this.container);
|
|
1994
1996
|
for (const key of (this._presetKeys || [])) {
|
|
1995
1997
|
if (key in preset) this.options[key] = preset[key];
|
|
1996
1998
|
}
|
package/src/js/index.js
CHANGED
|
@@ -13,14 +13,19 @@
|
|
|
13
13
|
// Import the main class
|
|
14
14
|
import {WaveformPlayer} from './core.js';
|
|
15
15
|
import {formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes} from './utils.js';
|
|
16
|
+
import {detectColorScheme} from './themes.js';
|
|
16
17
|
|
|
17
18
|
// Expose a small set of pure helpers as a single source of truth so consumers
|
|
18
19
|
// (e.g. @arraypress/waveform-bar, @arraypress/waveform-playlist) can reuse them
|
|
19
20
|
// instead of shipping divergent copies. `parseDataAttributes` lets wrappers read
|
|
20
21
|
// the player's full `data-*` option surface off a host element without
|
|
21
|
-
// re-implementing (and drifting from) the contract.
|
|
22
|
-
//
|
|
23
|
-
|
|
22
|
+
// re-implementing (and drifting from) the contract. `detectColorScheme` is here
|
|
23
|
+
// for the same reason: the bar used to carry its own copy of the heuristic and
|
|
24
|
+
// the two drifted (both shipped the transparent-background bug of #21, fixed
|
|
25
|
+
// independently). Attached to the class so it's reachable from the IIFE global
|
|
26
|
+
// too — which is how the bar reaches it, since it depends on this package as a
|
|
27
|
+
// runtime peer rather than importing the module.
|
|
28
|
+
WaveformPlayer.utils = {formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme};
|
|
24
29
|
|
|
25
30
|
/**
|
|
26
31
|
* Whether we're running in a browser (vs. SSR / Node), where `window` and
|
package/src/js/themes.js
CHANGED
|
@@ -3,7 +3,14 @@
|
|
|
3
3
|
* @description Color presets and default options for WaveformPlayer
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import {perceivedBrightness, DEFAULT_SAMPLES} from './utils.js';
|
|
6
|
+
import {parseColor, perceivedBrightness, DEFAULT_SAMPLES} from './utils.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Brightness (0–255) above which a backdrop counts as light.
|
|
10
|
+
* @type {number}
|
|
11
|
+
* @private
|
|
12
|
+
*/
|
|
13
|
+
const LIGHT_THRESHOLD = 128;
|
|
7
14
|
|
|
8
15
|
/**
|
|
9
16
|
* Does `<html>` or `<body>` explicitly signal the given colour scheme via a
|
|
@@ -28,6 +35,88 @@ function hasThemeHint(scheme) {
|
|
|
28
35
|
);
|
|
29
36
|
}
|
|
30
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Collect what the page paints behind `el`.
|
|
40
|
+
*
|
|
41
|
+
* Walks `el` and its ancestors up to `<html>`, alpha-compositing each element's
|
|
42
|
+
* background *colour* front-to-back. Walking the chain (rather than reading
|
|
43
|
+
* `<body>` alone) is what makes real layouts work: plenty of pages paint their
|
|
44
|
+
* background on a wrapper `<div>` or on `<html>` instead of `<body>`, and a
|
|
45
|
+
* player sitting inside a dark card on an otherwise light page should theme to
|
|
46
|
+
* the card.
|
|
47
|
+
*
|
|
48
|
+
* Compositing rather than taking the first colour found means translucent
|
|
49
|
+
* layers — an `rgba(0, 0, 0, 0.04)` tint over white, say — score as what the eye
|
|
50
|
+
* sees instead of as their own colour. Brightness is linear in R/G/B, so
|
|
51
|
+
* blending per-layer brightnesses is equivalent to blending the colours.
|
|
52
|
+
*
|
|
53
|
+
* Background *images* and gradients can't be scored from CSS, so a page painted
|
|
54
|
+
* only that way contributes no colour here and is classified by
|
|
55
|
+
* {@link detectCanvasScheme} instead.
|
|
56
|
+
*
|
|
57
|
+
* @param {Element} el - Element to start from (the player's container).
|
|
58
|
+
* @returns {{sum: number, alpha: number}} Premultiplied brightness, and how much
|
|
59
|
+
* of the stack is opaque (0–1).
|
|
60
|
+
* @private
|
|
61
|
+
*/
|
|
62
|
+
function collectBackdrop(el) {
|
|
63
|
+
let sum = 0;
|
|
64
|
+
let alpha = 0;
|
|
65
|
+
|
|
66
|
+
for (let node = el; node && node.nodeType === 1 && alpha < 0.995; node = node.parentElement) {
|
|
67
|
+
const c = parseColor(getComputedStyle(node).backgroundColor);
|
|
68
|
+
if (!c || c.a <= 0) continue;
|
|
69
|
+
|
|
70
|
+
// Each layer only shows through however much is still see-through.
|
|
71
|
+
const weight = c.a * (1 - alpha);
|
|
72
|
+
sum += ((c.r * 299 + c.g * 587 + c.b * 114) / 1000) * weight;
|
|
73
|
+
alpha += weight;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return {sum, alpha};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Scheme of the canvas — what is visible wherever the page paints no background
|
|
81
|
+
* colour of its own.
|
|
82
|
+
*
|
|
83
|
+
* Read from the page's *resolved text colour*. `color` initially resolves to the
|
|
84
|
+
* `canvastext` system colour, which browsers flip to white exactly when the
|
|
85
|
+
* document's used colour-scheme is dark, so it reports the palette the page is
|
|
86
|
+
* actually designed for. It is also the only signal that sees the
|
|
87
|
+
* `<meta name="color-scheme" content="light dark">` form — Chrome reports
|
|
88
|
+
* `normal` for the computed `color-scheme` property there, so reading that
|
|
89
|
+
* instead would miss the exact setup in #21.
|
|
90
|
+
*
|
|
91
|
+
* Deliberately NOT `prefers-color-scheme`. That describes the **user**, not the
|
|
92
|
+
* page, and what browsers paint behind an unpainted page under a dark
|
|
93
|
+
* preference turns out to be engine-specific — measured by screenshotting the
|
|
94
|
+
* same page in both engines: Chromium composites a dark `#121212` base
|
|
95
|
+
* background, WebKit keeps it white. Since no scripted signal can tell those
|
|
96
|
+
* apart, we believe the page instead: black text means it was designed light,
|
|
97
|
+
* so it gets the light preset. That is right in WebKit, and in Chromium it only
|
|
98
|
+
* loses on a page whose own text is already unreadable against that same dark
|
|
99
|
+
* base background. The media query survives purely as a last resort for
|
|
100
|
+
* environments with no resolvable text colour.
|
|
101
|
+
*
|
|
102
|
+
* @returns {'dark'|'light'} Scheme of the canvas behind the page.
|
|
103
|
+
* @private
|
|
104
|
+
*/
|
|
105
|
+
function detectCanvasScheme() {
|
|
106
|
+
// Light text ⇒ the page is painted for a dark canvas, and vice versa.
|
|
107
|
+
const text = perceivedBrightness(getComputedStyle(document.body).color);
|
|
108
|
+
if (text !== null) return text > LIGHT_THRESHOLD ? 'dark' : 'light';
|
|
109
|
+
|
|
110
|
+
if (window.matchMedia) {
|
|
111
|
+
if (window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';
|
|
112
|
+
if (window.matchMedia('(prefers-color-scheme: light)').matches) return 'light';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Knowing nothing at all keeps the historic default — most audio players
|
|
116
|
+
// are dark.
|
|
117
|
+
return 'dark';
|
|
118
|
+
}
|
|
119
|
+
|
|
31
120
|
/**
|
|
32
121
|
* Detect the appropriate color scheme for the player from the surrounding page.
|
|
33
122
|
*
|
|
@@ -35,46 +124,41 @@ function hasThemeHint(scheme) {
|
|
|
35
124
|
* 1. Explicit theme hints on `<html>`/`<body>` — class names
|
|
36
125
|
* (`dark`, `dark-mode`, `theme-dark`, light equivalents) and data
|
|
37
126
|
* attributes (`data-theme`, `data-color-scheme`).
|
|
38
|
-
* 2. The
|
|
39
|
-
* {@link
|
|
40
|
-
*
|
|
41
|
-
* 3. The
|
|
42
|
-
*
|
|
127
|
+
* 2. The backdrop actually visible behind the player — every background from
|
|
128
|
+
* `el` up through `<html>` ({@link collectBackdrop}), composited over the
|
|
129
|
+
* canvas ({@link detectCanvasScheme}). >128 = light, <128 = dark.
|
|
130
|
+
* 3. The canvas scheme alone, for the knife-edge case where the composite
|
|
131
|
+
* lands exactly on the threshold.
|
|
43
132
|
*
|
|
133
|
+
* @param {Element} [el] - The player's container, so a player inside a themed
|
|
134
|
+
* card picks up that card. Defaults to `<body>`.
|
|
44
135
|
* @returns {string} The detected scheme, either `'dark'` or `'light'`.
|
|
45
136
|
*/
|
|
46
|
-
export function detectColorScheme() {
|
|
137
|
+
export function detectColorScheme(el) {
|
|
47
138
|
// 1. Explicit theme class names / data attributes win.
|
|
48
139
|
if (hasThemeHint('dark')) return 'dark';
|
|
49
140
|
if (hasThemeHint('light')) return 'light';
|
|
50
141
|
|
|
51
|
-
// 2. Try to detect website's theme from background color
|
|
52
142
|
try {
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
// Clear determination: bright background = light theme. Exactly 128
|
|
57
|
-
// (or unparseable) is ambiguous — fall through to the next method.
|
|
58
|
-
if (brightness !== null) {
|
|
59
|
-
if (brightness > 128) return 'light';
|
|
60
|
-
if (brightness < 128) return 'dark';
|
|
61
|
-
}
|
|
62
|
-
} catch (e) {
|
|
63
|
-
// If background detection fails, continue to next method
|
|
64
|
-
}
|
|
143
|
+
// 2. What the player is actually sitting on.
|
|
144
|
+
const start = (el && el.nodeType === 1) ? el : document.body;
|
|
145
|
+
const {sum, alpha} = collectBackdrop(start);
|
|
65
146
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
71
|
-
if (window.matchMedia('(prefers-color-scheme: light)').matches) {
|
|
72
|
-
return 'light';
|
|
73
|
-
}
|
|
74
|
-
}
|
|
147
|
+
// Whatever transparency is left over after the page's own layers shows
|
|
148
|
+
// the canvas through.
|
|
149
|
+
const canvas = detectCanvasScheme();
|
|
150
|
+
const brightness = sum + (canvas === 'dark' ? 0 : 255) * (1 - alpha);
|
|
75
151
|
|
|
76
|
-
|
|
77
|
-
|
|
152
|
+
if (brightness > LIGHT_THRESHOLD) return 'light';
|
|
153
|
+
if (brightness < LIGHT_THRESHOLD) return 'dark';
|
|
154
|
+
|
|
155
|
+
// 3. Dead-centre grey tells us nothing; go with the canvas.
|
|
156
|
+
return canvas;
|
|
157
|
+
} catch (e) {
|
|
158
|
+
// No usable computed styles (SSR shim, detached document) — most audio
|
|
159
|
+
// players are dark, so that stays the fallback.
|
|
160
|
+
return 'dark';
|
|
161
|
+
}
|
|
78
162
|
}
|
|
79
163
|
|
|
80
164
|
/**
|
|
@@ -110,17 +194,19 @@ export const COLOR_PRESETS = {
|
|
|
110
194
|
*
|
|
111
195
|
* @param {string|null} presetName - Preset name (`'dark'` or `'light'`), or
|
|
112
196
|
* null/invalid to trigger auto-detection.
|
|
197
|
+
* @param {Element} [el] - Container passed through to {@link detectColorScheme}
|
|
198
|
+
* so detection reads the backdrop behind this player, not just `<body>`.
|
|
113
199
|
* @returns {Object<string, string>} The matching colour token map from
|
|
114
200
|
* {@link COLOR_PRESETS}.
|
|
115
201
|
*/
|
|
116
|
-
export function getColorPreset(presetName) {
|
|
202
|
+
export function getColorPreset(presetName, el) {
|
|
117
203
|
// If explicitly set to a valid preset, use it
|
|
118
204
|
if (presetName && COLOR_PRESETS[presetName]) {
|
|
119
205
|
return COLOR_PRESETS[presetName];
|
|
120
206
|
}
|
|
121
207
|
|
|
122
208
|
// Auto-detect if not specified or invalid
|
|
123
|
-
const detected = detectColorScheme();
|
|
209
|
+
const detected = detectColorScheme(el);
|
|
124
210
|
return COLOR_PRESETS[detected];
|
|
125
211
|
}
|
|
126
212
|
|
package/src/js/utils.js
CHANGED
|
@@ -283,17 +283,22 @@ export function formatSeekValueText(template, ...args) {
|
|
|
283
283
|
* Format a duration as a clock string.
|
|
284
284
|
*
|
|
285
285
|
* Renders `M:SS` for durations under an hour and `H:MM:SS` for longer ones,
|
|
286
|
-
* zero-padding the minutes and seconds. Falsy,
|
|
287
|
-
* treated as zero and return `'0:00'`.
|
|
286
|
+
* zero-padding the minutes and seconds. Falsy, non-numeric, non-finite, or
|
|
287
|
+
* negative inputs are treated as zero and return `'0:00'`.
|
|
288
|
+
*
|
|
289
|
+
* `Infinity` matters here, and an `isNaN` check does not catch it: a streamed or
|
|
290
|
+
* unseekable source reports `audio.duration === Infinity`, and `Infinity % 3600`
|
|
291
|
+
* is `NaN`, so the old guard rendered a literal `'Infinity:NaN:NaN'` into the UI.
|
|
288
292
|
* @param {number} seconds - Time in seconds.
|
|
289
293
|
* @returns {string} Formatted time, e.g. `'3:07'` or `'1:02:09'`.
|
|
290
294
|
*/
|
|
291
295
|
export function formatTime(seconds) {
|
|
292
|
-
|
|
296
|
+
const total = Number(seconds);
|
|
297
|
+
if (!total || !Number.isFinite(total) || total < 0) return '0:00';
|
|
293
298
|
|
|
294
|
-
const hrs = Math.floor(
|
|
295
|
-
const mins = Math.floor((
|
|
296
|
-
const secs = Math.floor(
|
|
299
|
+
const hrs = Math.floor(total / 3600);
|
|
300
|
+
const mins = Math.floor((total % 3600) / 60);
|
|
301
|
+
const secs = Math.floor(total % 60);
|
|
297
302
|
|
|
298
303
|
if (hrs > 0) {
|
|
299
304
|
return `${hrs}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
|
|
@@ -352,17 +357,52 @@ export function extractTitleFromUrl(url) {
|
|
|
352
357
|
.replace(/\b\w/g, l => l.toUpperCase());
|
|
353
358
|
}
|
|
354
359
|
|
|
360
|
+
/**
|
|
361
|
+
* Parse a CSS `rgb()`/`rgba()` colour into numeric channels.
|
|
362
|
+
*
|
|
363
|
+
* Handles both serializations a browser can hand back from `getComputedStyle`:
|
|
364
|
+
* the legacy comma form (`rgb(34, 34, 34)`, `rgba(34, 34, 34, 0.5)`) and the
|
|
365
|
+
* modern space/slash form (`rgb(34 34 34 / 50%)`). Anything else — the
|
|
366
|
+
* `transparent` keyword, a wide-gamut `color(srgb …)`, an empty string — is
|
|
367
|
+
* reported as `null` so callers treat it as *unknown* rather than as a colour.
|
|
368
|
+
*
|
|
369
|
+
* @param {string} color - CSS colour string.
|
|
370
|
+
* @returns {{r: number, g: number, b: number, a: number}|null} Channels 0–255
|
|
371
|
+
* with alpha 0–1, or `null` when the string isn't an rgb()/rgba() colour.
|
|
372
|
+
*/
|
|
373
|
+
export function parseColor(color) {
|
|
374
|
+
if (typeof color !== 'string') return null;
|
|
375
|
+
|
|
376
|
+
const m = color.match(/rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*(?:[,/]\s*([\d.]+)(%?))?/i);
|
|
377
|
+
if (!m) return null;
|
|
378
|
+
|
|
379
|
+
const r = Number(m[1]), g = Number(m[2]), b = Number(m[3]);
|
|
380
|
+
if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b)) return null;
|
|
381
|
+
|
|
382
|
+
let a = m[4] === undefined ? 1 : Number(m[4]);
|
|
383
|
+
if (!Number.isFinite(a)) return null;
|
|
384
|
+
if (m[5] === '%') a /= 100;
|
|
385
|
+
|
|
386
|
+
return {r, g, b, a: clamp(a, 0, 1)};
|
|
387
|
+
}
|
|
388
|
+
|
|
355
389
|
/**
|
|
356
390
|
* Perceived brightness (0–255) of a CSS colour, via the luminance formula.
|
|
357
|
-
*
|
|
391
|
+
*
|
|
392
|
+
* A fully transparent colour returns `null`, not `0`. That distinction matters:
|
|
393
|
+
* `rgba(0, 0, 0, 0)` is the computed background of *every* element the page
|
|
394
|
+
* never paints, so scoring it as pure black made auto-theme detection classify
|
|
395
|
+
* unpainted (i.e. white) pages as dark — see issue #21. Transparent means "this
|
|
396
|
+
* tells you nothing", which is a different answer from "this is black".
|
|
397
|
+
*
|
|
358
398
|
* @param {string} color - CSS colour string, e.g. `"rgb(34, 34, 34)"`.
|
|
359
|
-
* @returns {number|null} Brightness 0–255, or `null` if it can't be parsed
|
|
399
|
+
* @returns {number|null} Brightness 0–255, or `null` if it can't be parsed or
|
|
400
|
+
* is fully transparent.
|
|
360
401
|
*/
|
|
361
402
|
export function perceivedBrightness(color) {
|
|
362
|
-
const
|
|
363
|
-
if (!
|
|
364
|
-
|
|
365
|
-
return (r * 299 + g * 587 + b * 114) / 1000;
|
|
403
|
+
const c = parseColor(color);
|
|
404
|
+
if (!c || c.a <= 0) return null;
|
|
405
|
+
return (c.r * 299 + c.g * 587 + c.b * 114) / 1000;
|
|
366
406
|
}
|
|
367
407
|
|
|
368
408
|
/**
|