/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function t(t,e,i,n){return new(i||(i=Promise))((function(s,o){function r(t){try{h(n.next(t))}catch(t){o(t)}}function a(t){try{h(n.throw(t))}catch(t){o(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(r,a)}h((n=n.apply(t,e||[])).next())}))}const e={decode:function(e,i){return t(this,void 0,void 0,(function*(){const t=new AudioContext({sampleRate:i});return t.decodeAudioData(e).finally((()=>t.close()))}))},createBuffer:function(t,e){return"number"==typeof t[0]&&(t=[t]),function(t){const e=t[0];if(e.some((t=>t>1||t<-1))){const i=e.length;let n=0;for(let t=0;t<i;t++){const i=Math.abs(e[t]);i>n&&(n=i)}for(const e of t)for(let t=0;t<i;t++)e[t]/=n}}(t),{duration:e,length:t[0].length,sampleRate:t[0].length/e,numberOfChannels:t.length,getChannelData:e=>null==t?void 0:t[e],copyFromChannel:AudioBuffer.prototype.copyFromChannel,copyToChannel:AudioBuffer.prototype.copyToChannel}}},i={fetchBlob:function(e,i,n){return t(this,void 0,void 0,(function*(){const s=yield fetch(e,n);if(s.status>=400)throw new Error(`Failed to fetch ${e}: ${s.status} (${s.statusText})`);return function(e,i){t(this,void 0,void 0,(function*(){if(!e.body||!e.headers)return;const n=e.body.getReader(),s=Number(e.headers.get("Content-Length"))||0;let o=0;const r=e=>t(this,void 0,void 0,(function*(){o+=(null==e?void 0:e.length)||0;const t=Math.round(o/s*100);i(t)})),a=()=>t(this,void 0,void 0,(function*(){let t;try{t=yield n.read()}catch(t){return}t.done||(r(t.value),yield a())}));a()}))}(s.clone(),i),s.blob()}))}};let n=class{constructor(){this.listeners={}}on(t,e,i){if(this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),null==i?void 0:i.once){const i=()=>{this.un(t,i),this.un(t,e)};return this.on(t,i),i}return()=>this.un(t,e)}un(t,e){var i;null===(i=this.listeners[t])||void 0===i||i.delete(e)}once(t,e){return this.on(t,e,{once:!0})}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}},s=class extends n{constructor(t){super(),this.isExternalMedia=!1,t.media?(this.media=t.media,this.isExternalMedia=!0):this.media=document.createElement("audio"),t.mediaControls&&(this.media.controls=!0),t.autoplay&&(this.media.autoplay=!0),null!=t.playbackRate&&this.onceMediaEvent("canplay",(()=>{null!=t.playbackRate&&(this.media.playbackRate=t.playbackRate)}))}onMediaEvent(t,e,i){return this.media.addEventListener(t,e,i),()=>this.media.removeEventListener(t,e)}onceMediaEvent(t,e){return this.onMediaEvent(t,e,{once:!0})}getSrc(){return this.media.currentSrc||this.media.src||""}revokeSrc(){const t=this.getSrc();t.startsWith("blob:")&&URL.revokeObjectURL(t)}canPlayType(t){return""!==this.media.canPlayType(t)}setSrc(t,e){if(this.getSrc()===t)return;this.revokeSrc();const i=e instanceof Blob&&this.canPlayType(e.type)?URL.createObjectURL(e):t;this.media.src=i}destroy(){this.media.pause(),this.isExternalMedia||(this.media.remove(),this.revokeSrc(),this.media.src="",this.media.load())}setMediaElement(t){this.media=t}play(){return this.media.play()}pause(){this.media.pause()}isPlaying(){return!this.media.paused&&!this.media.ended}setTime(t){this.media.currentTime=t}getDuration(){return this.media.duration}getCurrentTime(){return this.media.currentTime}getVolume(){return this.media.volume}setVolume(t){this.media.volume=t}getMuted(){return this.media.muted}setMuted(t){this.media.muted=t}getPlaybackRate(){return this.media.playbackRate}setPlaybackRate(t,e){null!=e&&(this.media.preservesPitch=e),this.media.playbackRate=t}getMediaElement(){return this.media}setSinkId(t){return this.media.setSinkId(t)}},o=class e extends n{constructor(t,e){super(),this.timeouts=[],this.isScrollable=!1,this.audioData=null,this.resizeObserver=null,this.lastContainerWidth=0,this.isDragging=!1,this.options=t;const i=this.parentFromOptionsContainer(t.container);this.parent=i;const[n,s]=this.initHtml();i.appendChild(n),this.container=n,this.scrollContainer=s.querySelector(".scroll"),this.wrapper=s.querySelector(".wrapper"),this.canvasWrapper=s.querySelector(".canvases"),this.progressWrapper=s.querySelector(".progress"),this.cursor=s.querySelector(".cursor"),e&&s.appendChild(e),this.initEvents()}parentFromOptionsContainer(t){let e;if("string"==typeof t?e=document.querySelector(t):t instanceof HTMLElement&&(e=t),!e)throw new Error("Container not found");return e}initEvents(){const t=t=>{const e=this.wrapper.getBoundingClientRect(),i=t.clientX-e.left,n=t.clientX-e.left;return[i/e.width,n/e.height]};this.wrapper.addEventListener("click",(e=>{const[i,n]=t(e);this.emit("click",i,n)})),this.wrapper.addEventListener("dblclick",(e=>{const[i,n]=t(e);this.emit("dblclick",i,n)})),this.options.dragToSeek&&this.initDrag(),this.scrollContainer.addEventListener("scroll",(()=>{const{scrollLeft:t,scrollWidth:e,clientWidth:i}=this.scrollContainer,n=t/e,s=(t+i)/e;this.emit("scroll",n,s)}));const e=this.createDelay(100);this.resizeObserver=new ResizeObserver((()=>{e((()=>this.onContainerResize()))})),this.resizeObserver.observe(this.scrollContainer)}onContainerResize(){const t=this.parent.clientWidth;t===this.lastContainerWidth&&"auto"!==this.options.height||(this.lastContainerWidth=t,this.reRender())}initDrag(){!function(t,e,i,n,s=3,o=0){if(!t)return()=>{};let r=()=>{};t.addEventListener("pointerdown",(a=>{if(a.button!==o)return;a.preventDefault(),a.stopPropagation();let h=a.clientX,l=a.clientY,d=!1;const u=n=>{n.preventDefault(),n.stopPropagation();const o=n.clientX,r=n.clientY,a=o-h,u=r-l;if(d||Math.abs(a)>s||Math.abs(u)>s){const n=t.getBoundingClientRect(),{left:s,top:c}=n;d||(null==i||i(h-s,l-c),d=!0),e(a,u,o-s,r-c),h=o,l=r}},c=()=>{d&&(null==n||n()),r()},p=t=>{t.relatedTarget&&t.relatedTarget!==document.documentElement||c()},m=t=>{d&&(t.stopPropagation(),t.preventDefault())},v=t=>{d&&t.preventDefault()};document.addEventListener("pointermove",u),document.addEventListener("pointerup",c),document.addEventListener("pointerout",p),document.addEventListener("pointercancel",p),document.addEventListener("touchmove",v,{passive:!1}),document.addEventListener("click",m,{capture:!0}),r=()=>{document.removeEventListener("pointermove",u),document.removeEventListener("pointerup",c),document.removeEventListener("pointerout",p),document.removeEventListener("pointercancel",p),document.removeEventListener("touchmove",v),setTimeout((()=>{document.removeEventListener("click",m,{capture:!0})}),10)}}))}(this.wrapper,((t,e,i)=>{this.emit("drag",Math.max(0,Math.min(1,i/this.wrapper.getBoundingClientRect().width)))}),(()=>this.isDragging=!0),(()=>this.isDragging=!1))}getHeight(t){return null==t?128:isNaN(Number(t))?"auto"===t&&this.parent.clientHeight||128:Number(t)}initHtml(){const t=document.createElement("div"),e=t.attachShadow({mode:"open"});return e.innerHTML=`\n      <style>\n        :host {\n          user-select: none;\n          min-width: 1px;\n        }\n        :host audio {\n          display: block;\n          width: 100%;\n        }\n        :host .scroll {\n          overflow-x: auto;\n          overflow-y: hidden;\n          width: 100%;\n          position: relative;\n        }\n        :host .noScrollbar {\n          scrollbar-color: transparent;\n          scrollbar-width: none;\n        }\n        :host .noScrollbar::-webkit-scrollbar {\n          display: none;\n          -webkit-appearance: none;\n        }\n        :host .wrapper {\n          position: relative;\n          overflow: visible;\n          z-index: 2;\n        }\n        :host .canvases {\n          min-height: ${this.getHeight(this.options.height)}px;\n        }\n        :host .canvases > div {\n          position: relative;\n        }\n        :host canvas {\n          display: block;\n          position: absolute;\n          top: 0;\n          image-rendering: pixelated;\n        }\n        :host .progress {\n          pointer-events: none;\n          position: absolute;\n          z-index: 2;\n          top: 0;\n          left: 0;\n          width: 0;\n          height: 100%;\n          overflow: hidden;\n        }\n        :host .progress > div {\n          position: relative;\n        }\n        :host .cursor {\n          pointer-events: none;\n          position: absolute;\n          z-index: 5;\n          top: 0;\n          left: 0;\n          height: 100%;\n          border-radius: 2px;\n        }\n      </style>\n\n      <div class="scroll" part="scroll">\n        <div class="wrapper" part="wrapper">\n          <div class="canvases"></div>\n          <div class="progress" part="progress"></div>\n          <div class="cursor" part="cursor"></div>\n        </div>\n      </div>\n    `,[t,e]}setOptions(t){if(this.options.container!==t.container){const e=this.parentFromOptionsContainer(t.container);e.appendChild(this.container),this.parent=e}t.dragToSeek&&!this.options.dragToSeek&&this.initDrag(),this.options=t,this.reRender()}getWrapper(){return this.wrapper}getScroll(){return this.scrollContainer.scrollLeft}destroy(){var t;this.container.remove(),null===(t=this.resizeObserver)||void 0===t||t.disconnect()}createDelay(t=10){const e={};return this.timeouts.push(e),i=>{e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(i,t)}}convertColorValues(t){if(!Array.isArray(t))return t||"";if(t.length<2)return t[0]||"";const e=document.createElement("canvas"),i=e.getContext("2d"),n=e.height*(window.devicePixelRatio||1),s=i.createLinearGradient(0,0,0,n),o=1/(t.length-1);return t.forEach(((t,e)=>{const i=e*o;s.addColorStop(i,t)})),s}renderBarWaveform(t,e,i,n){const s=t[0],o=t[1]||t[0],r=s.length,{width:a,height:h}=i.canvas,l=h/2,d=window.devicePixelRatio||1,u=e.barWidth?e.barWidth*d:1,c=e.barGap?e.barGap*d:e.barWidth?u/2:0,p=e.barRadius||0,m=a/(u+c)/r,v=p&&"roundRect"in i?"roundRect":"rect";i.beginPath();let g=0,f=0,y=0;for(let t=0;t<=r;t++){const r=Math.round(t*m);if(r>g){const t=Math.round(f*l*n),s=t+Math.round(y*l*n)||1;let o=l-t;"top"===e.barAlign?o=0:"bottom"===e.barAlign&&(o=h-s),i[v](g*(u+c),o,u,s,p),g=r,f=0,y=0}const a=Math.abs(s[t]||0),d=Math.abs(o[t]||0);a>f&&(f=a),d>y&&(y=d)}i.fill(),i.closePath()}renderLineWaveform(t,e,i,n){const s=e=>{const s=t[e]||t[0],o=s.length,{height:r}=i.canvas,a=r/2,h=i.canvas.width/o;i.moveTo(0,a);let l=0,d=0;for(let t=0;t<=o;t++){const o=Math.round(t*h);if(o>l){const t=a+(Math.round(d*a*n)||1)*(0===e?-1:1);i.lineTo(l,t),l=o,d=0}const r=Math.abs(s[t]||0);r>d&&(d=r)}i.lineTo(l,a)};i.beginPath(),s(0),s(1),i.fill(),i.closePath()}renderWaveform(t,e,i){if(i.fillStyle=this.convertColorValues(e.waveColor),e.renderFunction)return void e.renderFunction(t,i);let n=e.barHeight||1;if(e.normalize){const e=Array.from(t[0]).reduce(((t,e)=>Math.max(t,Math.abs(e))),0);n=e?1/e:1}e.barWidth||e.barGap||e.barAlign?this.renderBarWaveform(t,e,i,n):this.renderLineWaveform(t,e,i,n)}renderSingleCanvas(t,e,i,n,s,o,r,a){const h=window.devicePixelRatio||1,l=document.createElement("canvas"),d=t[0].length;l.width=Math.round(i*(o-s)/d),l.height=n*h,l.style.width=`${Math.floor(l.width/h)}px`,l.style.height=`${n}px`,l.style.left=`${Math.floor(s*i/h/d)}px`,r.appendChild(l);const u=l.getContext("2d");if(this.renderWaveform(t.map((t=>t.slice(s,o))),e,u),l.width>0&&l.height>0){const t=l.cloneNode(),i=t.getContext("2d");i.drawImage(l,0,0),i.globalCompositeOperation="source-in",i.fillStyle=this.convertColorValues(e.progressColor),i.fillRect(0,0,l.width,l.height),a.appendChild(t)}}renderChannel(t,i,n){const s=document.createElement("div"),o=this.getHeight(i.height);s.style.height=`${o}px`,this.canvasWrapper.style.minHeight=`${o}px`,this.canvasWrapper.appendChild(s);const r=s.cloneNode();this.progressWrapper.appendChild(r);const{scrollLeft:a,scrollWidth:h,clientWidth:l}=this.scrollContainer,d=t[0].length,u=d/h;let c=Math.min(e.MAX_CANVAS_WIDTH,l);if(i.barWidth||i.barGap){const t=i.barWidth||.5,e=t+(i.barGap||t/2);c%e!=0&&(c=Math.floor(c/e)*e)}const p=Math.floor(Math.abs(a)*u),m=Math.floor(p+c*u),v=m-p,g=(e,a)=>{this.renderSingleCanvas(t,i,n,o,Math.max(0,e),Math.min(a,d),s,r)},f=this.createDelay(),y=this.createDelay(),b=(t,e)=>{g(t,e),t>0&&f((()=>{b(t-v,e-v)}))},A=(t,e)=>{g(t,e),e<d&&y((()=>{A(t+v,e+v)}))};b(p,m),m<d&&A(m,m+v)}render(t){this.timeouts.forEach((t=>t.timeout&&clearTimeout(t.timeout))),this.timeouts=[],this.canvasWrapper.innerHTML="",this.progressWrapper.innerHTML="",null!=this.options.width&&(this.scrollContainer.style.width="number"==typeof this.options.width?`${this.options.width}px`:this.options.width);const e=window.devicePixelRatio||1,i=this.scrollContainer.clientWidth,n=Math.ceil(t.duration*(this.options.minPxPerSec||0));this.isScrollable=n>i;const s=this.options.fillParent&&!this.isScrollable,o=(s?i:n)*e;if(this.wrapper.style.width=s?"100%":`${n}px`,this.scrollContainer.style.overflowX=this.isScrollable?"auto":"hidden",this.scrollContainer.classList.toggle("noScrollbar",!!this.options.hideScrollbar),this.cursor.style.backgroundColor=`${this.options.cursorColor||this.options.progressColor}`,this.cursor.style.width=`${this.options.cursorWidth}px`,this.options.splitChannels)for(let e=0;e<t.numberOfChannels;e++){const i=Object.assign(Object.assign({},this.options),this.options.splitChannels[e]);this.renderChannel([t.getChannelData(e)],i,o)}else{const e=[t.getChannelData(0)];t.numberOfChannels>1&&e.push(t.getChannelData(1)),this.renderChannel(e,this.options,o)}this.audioData=t,this.emit("render")}reRender(){if(!this.audioData)return;const{scrollWidth:t}=this.scrollContainer,e=this.progressWrapper.clientWidth;if(this.render(this.audioData),this.isScrollable&&t!==this.scrollContainer.scrollWidth){const t=this.progressWrapper.clientWidth;this.scrollContainer.scrollLeft+=t-e}}zoom(t){this.options.minPxPerSec=t,this.reRender()}scrollIntoView(t,e=!1){const{scrollLeft:i,scrollWidth:n,clientWidth:s}=this.scrollContainer,o=t*n,r=i,a=i+s,h=s/2;if(this.isDragging){const t=30;o+t>a?this.scrollContainer.scrollLeft+=t:o-t<r&&(this.scrollContainer.scrollLeft-=t)}else{(o<r||o>a)&&(this.scrollContainer.scrollLeft=o-(this.options.autoCenter?h:0));const t=o-i-h;e&&this.options.autoCenter&&t>0&&(this.scrollContainer.scrollLeft+=Math.min(t,10))}{const t=this.scrollContainer.scrollLeft,e=t/n,i=(t+s)/n;this.emit("scroll",e,i)}}renderProgress(t,e){if(isNaN(t))return;const i=100*t;this.canvasWrapper.style.clipPath=`polygon(${i}% 0, 100% 0, 100% 100%, ${i}% 100%)`,this.progressWrapper.style.width=`${i}%`,this.cursor.style.left=`${i}%`,this.cursor.style.marginLeft=100===Math.round(i)?`-${this.options.cursorWidth}px`:"",this.isScrollable&&this.options.autoScroll&&this.scrollIntoView(t,e)}exportImage(e,i,n){return t(this,void 0,void 0,(function*(){const t=this.canvasWrapper.querySelectorAll("canvas");if(!t.length)throw new Error("No waveform data");if("dataURL"===n){const n=Array.from(t).map((t=>t.toDataURL(e,i)));return Promise.resolve(n)}return Promise.all(Array.from(t).map((t=>new Promise(((n,s)=>{t.toBlob((t=>{t?n(t):s(new Error("Could not export image"))}),e,i)})))))}))}};o.MAX_CANVAS_WIDTH=4e3;let r=class extends n{constructor(){super(...arguments),this.unsubscribe=()=>{}}start(){this.unsubscribe=this.on("tick",(()=>{requestAnimationFrame((()=>{this.emit("tick")}))})),this.emit("tick")}stop(){this.unsubscribe()}destroy(){this.unsubscribe()}};class a extends n{constructor(t=new AudioContext){super(),this.bufferNode=null,this.autoplay=!1,this.playStartTime=0,this.playedDuration=0,this._muted=!1,this.buffer=null,this.currentSrc="",this.paused=!0,this.crossOrigin=null,this.addEventListener=this.on,this.removeEventListener=this.un,this.audioContext=t,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}load(){return t(this,void 0,void 0,(function*(){}))}get src(){return this.currentSrc}set src(t){if(this.currentSrc=t,!t)return this.buffer=null,void this.emit("emptied");fetch(t).then((t=>t.arrayBuffer())).then((e=>this.currentSrc!==t?null:this.audioContext.decodeAudioData(e))).then((e=>{this.currentSrc===t&&(this.buffer=e,this.emit("loadedmetadata"),this.emit("canplay"),this.autoplay&&this.play())}))}_play(){var t;this.paused&&(this.paused=!1,null===(t=this.bufferNode)||void 0===t||t.disconnect(),this.bufferNode=this.audioContext.createBufferSource(),this.bufferNode.buffer=this.buffer,this.bufferNode.connect(this.gainNode),this.playedDuration>=this.duration&&(this.playedDuration=0),this.bufferNode.start(this.audioContext.currentTime,this.playedDuration),this.playStartTime=this.audioContext.currentTime,this.bufferNode.onended=()=>{this.currentTime>=this.duration&&(this.pause(),this.emit("ended"))})}_pause(){var t;this.paused||(this.paused=!0,null===(t=this.bufferNode)||void 0===t||t.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime)}play(){return t(this,void 0,void 0,(function*(){this._play(),this.emit("play")}))}pause(){this._pause(),this.emit("pause")}stopAt(t){var e,i;const n=t-this.currentTime;null===(e=this.bufferNode)||void 0===e||e.stop(this.audioContext.currentTime+n),null===(i=this.bufferNode)||void 0===i||i.addEventListener("ended",(()=>{this.bufferNode=null,this.pause()}),{once:!0})}setSinkId(e){return t(this,void 0,void 0,(function*(){return this.audioContext.setSinkId(e)}))}get playbackRate(){var t,e;return null!==(e=null===(t=this.bufferNode)||void 0===t?void 0:t.playbackRate.value)&&void 0!==e?e:1}set playbackRate(t){this.bufferNode&&(this.bufferNode.playbackRate.value=t)}get currentTime(){return this.paused?this.playedDuration:this.playedDuration+this.audioContext.currentTime-this.playStartTime}set currentTime(t){this.emit("seeking"),this.paused?this.playedDuration=t:(this._pause(),this.playedDuration=t,this._play()),this.emit("timeupdate")}get duration(){var t;return(null===(t=this.buffer)||void 0===t?void 0:t.duration)||0}get volume(){return this.gainNode.gain.value}set volume(t){this.gainNode.gain.value=t,this.emit("volumechange")}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}canPlayType(t){return/^(audio|video)\//.test(t)}getGainNode(){return this.gainNode}getChannelData(){const t=[];if(!this.buffer)return t;const e=this.buffer.numberOfChannels;for(let i=0;i<e;i++)t.push(this.buffer.getChannelData(i));return t}}const h={waveColor:"#999",progressColor:"#555",cursorWidth:1,minPxPerSec:0,fillParent:!0,interact:!0,dragToSeek:!1,autoScroll:!0,autoCenter:!0,sampleRate:8e3};let l=class n extends s{static create(t){return new n(t)}constructor(t){const e=t.media||("WebAudio"===t.backend?new a:void 0);super({media:e,mediaControls:t.mediaControls,autoplay:t.autoplay,playbackRate:t.audioRate}),this.plugins=[],this.decodedData=null,this.subscriptions=[],this.mediaSubscriptions=[],this.options=Object.assign({},h,t),this.timer=new r;const i=e?void 0:this.getMediaElement();this.renderer=new o(this.options,i),this.initPlayerEvents(),this.initRendererEvents(),this.initTimerEvents(),this.initPlugins(),Promise.resolve().then((()=>{this.emit("init");const t=this.options.url||this.getSrc()||"";(t||this.options.peaks&&this.options.duration)&&this.load(t,this.options.peaks,this.options.duration)}))}initTimerEvents(){this.subscriptions.push(this.timer.on("tick",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),!0),this.emit("timeupdate",t),this.emit("audioprocess",t)})))}initPlayerEvents(){this.isPlaying()&&(this.emit("play"),this.timer.start()),this.mediaSubscriptions.push(this.onMediaEvent("timeupdate",(()=>{const t=this.getCurrentTime();this.renderer.renderProgress(t/this.getDuration(),this.isPlaying()),this.emit("timeupdate",t)})),this.onMediaEvent("play",(()=>{this.emit("play"),this.timer.start()})),this.onMediaEvent("pause",(()=>{this.emit("pause"),this.timer.stop()})),this.onMediaEvent("emptied",(()=>{this.timer.stop()})),this.onMediaEvent("ended",(()=>{this.emit("finish")})),this.onMediaEvent("seeking",(()=>{this.emit("seeking",this.getCurrentTime())})))}initRendererEvents(){this.subscriptions.push(this.renderer.on("click",((t,e)=>{this.options.interact&&(this.seekTo(t),this.emit("interaction",t*this.getDuration()),this.emit("click",t,e))})),this.renderer.on("dblclick",((t,e)=>{this.emit("dblclick",t,e)})),this.renderer.on("scroll",((t,e)=>{const i=this.getDuration();this.emit("scroll",t*i,e*i)})),this.renderer.on("render",(()=>{this.emit("redraw")})));{let t;this.subscriptions.push(this.renderer.on("drag",(e=>{this.options.interact&&(this.renderer.renderProgress(e),clearTimeout(t),t=setTimeout((()=>{this.seekTo(e)}),this.isPlaying()?0:200),this.emit("interaction",e*this.getDuration()),this.emit("drag",e))})))}}initPlugins(){var t;(null===(t=this.options.plugins)||void 0===t?void 0:t.length)&&this.options.plugins.forEach((t=>{this.registerPlugin(t)}))}unsubscribePlayerEvents(){this.mediaSubscriptions.forEach((t=>t())),this.mediaSubscriptions=[]}setOptions(t){this.options=Object.assign({},this.options,t),this.renderer.setOptions(this.options),t.audioRate&&this.setPlaybackRate(t.audioRate),null!=t.mediaControls&&(this.getMediaElement().controls=t.mediaControls)}registerPlugin(t){return t._init(this),this.plugins.push(t),this.subscriptions.push(t.once("destroy",(()=>{this.plugins=this.plugins.filter((e=>e!==t))}))),t}getWrapper(){return this.renderer.getWrapper()}getScroll(){return this.renderer.getScroll()}getActivePlugins(){return this.plugins}loadAudio(n,s,o,r){return t(this,void 0,void 0,(function*(){if(this.emit("load",n),!this.options.media&&this.isPlaying()&&this.pause(),this.decodedData=null,!s&&!o){const t=t=>this.emit("loading",t);s=yield i.fetchBlob(n,t,this.options.fetchParams)}this.setSrc(n,s);const t=r||this.getDuration()||(yield new Promise((t=>{this.onceMediaEvent("loadedmetadata",(()=>t(this.getDuration())))})));if(o)this.decodedData=e.createBuffer(o,t||0);else if(s){const t=yield s.arrayBuffer();this.decodedData=yield e.decode(t,this.options.sampleRate)}this.decodedData&&(this.emit("decode",this.getDuration()),this.renderer.render(this.decodedData)),this.emit("ready",this.getDuration())}))}load(e,i,n){return t(this,void 0,void 0,(function*(){yield this.loadAudio(e,void 0,i,n)}))}loadBlob(e,i,n){return t(this,void 0,void 0,(function*(){yield this.loadAudio("blob",e,i,n)}))}zoom(t){if(!this.decodedData)throw new Error("No audio loaded");this.renderer.zoom(t),this.emit("zoom",t)}getDecodedData(){return this.decodedData}exportPeaks({channels:t=2,maxLength:e=8e3,precision:i=1e4}={}){if(!this.decodedData)throw new Error("The audio has not been decoded yet");const n=Math.min(t,this.decodedData.numberOfChannels),s=[];for(let t=0;t<n;t++){const n=this.decodedData.getChannelData(t),o=[],r=Math.round(n.length/e);for(let t=0;t<e;t++){const e=n.slice(t*r,(t+1)*r);let s=0;for(let t=0;t<e.length;t++){const i=e[t];Math.abs(i)>Math.abs(s)&&(s=i)}o.push(Math.round(s*i)/i)}s.push(o)}return s}getDuration(){let t=super.getDuration()||0;return 0!==t&&t!==1/0||!this.decodedData||(t=this.decodedData.duration),t}toggleInteraction(t){this.options.interact=t}seekTo(t){const e=this.getDuration()*t;this.setTime(e)}playPause(){return t(this,void 0,void 0,(function*(){return this.isPlaying()?this.pause():this.play()}))}stop(){this.pause(),this.setTime(0)}skip(t){this.setTime(this.getCurrentTime()+t)}empty(){this.load("",[[0]],.001)}setMediaElement(t){this.unsubscribePlayerEvents(),super.setMediaElement(t),this.initPlayerEvents()}exportImage(e="image/png",i=1,n="dataURL"){return t(this,void 0,void 0,(function*(){return this.renderer.exportImage(e,i,n)}))}destroy(){this.emit("destroy"),this.plugins.forEach((t=>t.destroy())),this.subscriptions.forEach((t=>t())),this.unsubscribePlayerEvents(),this.timer.destroy(),this.renderer.destroy(),super.destroy()}},d=class{constructor(){this.listeners={}}on(t,e,i){if(this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),null==i?void 0:i.once){const i=()=>{this.un(t,i),this.un(t,e)};return this.on(t,i),i}return()=>this.un(t,e)}un(t,e){var i;null===(i=this.listeners[t])||void 0===i||i.delete(e)}once(t,e){return this.on(t,e,{once:!0})}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}},u=class extends d{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}_init(t){this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t()))}};function c(t,e,i,n,s=3,o=0){if(!t)return()=>{};let r=()=>{};const a=a=>{if(a.button!==o)return;a.preventDefault(),a.stopPropagation();let h=a.clientX,l=a.clientY,d=!1;const u=n=>{n.preventDefault(),n.stopPropagation();const o=n.clientX,r=n.clientY,a=o-h,u=r-l;if(d||Math.abs(a)>s||Math.abs(u)>s){const n=t.getBoundingClientRect(),{left:s,top:c}=n;d||(null==i||i(h-s,l-c),d=!0),e(a,u,o-s,r-c),h=o,l=r}},c=()=>{d&&(null==n||n()),r()},p=t=>{t.relatedTarget&&t.relatedTarget!==document.documentElement||c()},m=t=>{d&&(t.stopPropagation(),t.preventDefault())},v=t=>{d&&t.preventDefault()};document.addEventListener("pointermove",u),document.addEventListener("pointerup",c),document.addEventListener("pointerout",p),document.addEventListener("pointercancel",p),document.addEventListener("touchmove",v,{passive:!1}),document.addEventListener("click",m,{capture:!0}),r=()=>{document.removeEventListener("pointermove",u),document.removeEventListener("pointerup",c),document.removeEventListener("pointerout",p),document.removeEventListener("pointercancel",p),document.removeEventListener("touchmove",v),setTimeout((()=>{document.removeEventListener("click",m,{capture:!0})}),10)}};return t.addEventListener("pointerdown",a),()=>{r(),t.removeEventListener("pointerdown",a)}}function p(t,e){const i=e.xmlns?document.createElementNS(e.xmlns,t):document.createElement(t);for(const[t,n]of Object.entries(e))if("children"===t)for(const[t,n]of Object.entries(e))"string"==typeof n?i.appendChild(document.createTextNode(n)):i.appendChild(p(t,n));else"style"===t?Object.assign(i.style,n):"textContent"===t?i.textContent=n:i.setAttribute(t,n.toString());return i}function m(t,e,i){const n=p(t,e||{});return null==i||i.appendChild(n),n}let v=class extends d{constructor(t,e,i=0){var n,s,o,r,a,h,l,d;super(),this.totalDuration=e,this.numberOfChannels=i,this.minLength=0,this.maxLength=1/0,this.contentEditable=!1,this.id=t.id||`region-${Math.random().toString(32).slice(2)}`,this.start=this.clampPosition(t.start),this.end=this.clampPosition(null!==(n=t.end)&&void 0!==n?n:t.start),this.drag=null===(s=t.drag)||void 0===s||s,this.resize=null===(o=t.resize)||void 0===o||o,this.color=null!==(r=t.color)&&void 0!==r?r:"rgba(0, 0, 0, 0.1)",this.minLength=null!==(a=t.minLength)&&void 0!==a?a:this.minLength,this.maxLength=null!==(h=t.maxLength)&&void 0!==h?h:this.maxLength,this.channelIdx=null!==(l=t.channelIdx)&&void 0!==l?l:-1,this.contentEditable=null!==(d=t.contentEditable)&&void 0!==d?d:this.contentEditable,this.element=this.initElement(),this.setContent(t.content),this.setPart(),this.renderPosition(),this.initMouseEvents()}clampPosition(t){return Math.max(0,Math.min(this.totalDuration,t))}setPart(){const t=this.start===this.end;this.element.setAttribute("part",`${t?"marker":"region"} ${this.id}`)}addResizeHandles(t){const e={position:"absolute",zIndex:"2",width:"6px",height:"100%",top:"0",cursor:"ew-resize",wordBreak:"keep-all"},i=m("div",{part:"region-handle region-handle-left",style:Object.assign(Object.assign({},e),{left:"0",borderLeft:"2px solid rgba(0, 0, 0, 0.5)",borderRadius:"2px 0 0 2px"})},t),n=m("div",{part:"region-handle region-handle-right",style:Object.assign(Object.assign({},e),{right:"0",borderRight:"2px solid rgba(0, 0, 0, 0.5)",borderRadius:"0 2px 2px 0"})},t);c(i,(t=>this.onResize(t,"start")),(()=>null),(()=>this.onEndResizing()),1),c(n,(t=>this.onResize(t,"end")),(()=>null),(()=>this.onEndResizing()),1)}removeResizeHandles(t){const e=t.querySelector('[part*="region-handle-left"]'),i=t.querySelector('[part*="region-handle-right"]');e&&t.removeChild(e),i&&t.removeChild(i)}initElement(){const t=this.start===this.end;let e=0,i=100;this.channelIdx>=0&&this.channelIdx<this.numberOfChannels&&(i=100/this.numberOfChannels,e=i*this.channelIdx);const n=m("div",{style:{position:"absolute",top:`${e}%`,height:`${i}%`,backgroundColor:t?"none":this.color,borderLeft:t?"2px solid "+this.color:"none",borderRadius:"2px",boxSizing:"border-box",transition:"background-color 0.2s ease",cursor:this.drag?"grab":"default",pointerEvents:"all"}});return!t&&this.resize&&this.addResizeHandles(n),n}renderPosition(){const t=this.start/this.totalDuration,e=(this.totalDuration-this.end)/this.totalDuration;this.element.style.left=100*t+"%",this.element.style.right=100*e+"%"}toggleCursor(t){this.drag&&(this.element.style.cursor=t?"grabbing":"grab")}initMouseEvents(){const{element:t}=this;t&&(t.addEventListener("click",(t=>this.emit("click",t))),t.addEventListener("mouseenter",(t=>this.emit("over",t))),t.addEventListener("mouseleave",(t=>this.emit("leave",t))),t.addEventListener("dblclick",(t=>this.emit("dblclick",t))),t.addEventListener("pointerdown",(()=>this.toggleCursor(!0))),t.addEventListener("pointerup",(()=>this.toggleCursor(!1))),c(t,(t=>this.onMove(t)),(()=>this.toggleCursor(!0)),(()=>{this.toggleCursor(!1),this.drag&&this.emit("update-end")})),this.contentEditable&&this.content&&(this.content.addEventListener("click",(t=>this.onContentClick(t))),this.content.addEventListener("blur",(()=>this.onContentBlur()))))}_onUpdate(t,e){if(!this.element.parentElement)return;const{width:i}=this.element.parentElement.getBoundingClientRect(),n=t/i*this.totalDuration,s=e&&"start"!==e?this.start:this.start+n,o=e&&"end"!==e?this.end:this.end+n,r=o-s;s>=0&&o<=this.totalDuration&&s<=o&&r>=this.minLength&&r<=this.maxLength&&(this.start=s,this.end=o,this.renderPosition(),this.emit("update"))}onMove(t){this.drag&&this._onUpdate(t)}onResize(t,e){this.resize&&this._onUpdate(t,e)}onEndResizing(){this.resize&&this.emit("update-end")}onContentClick(t){t.stopPropagation(),t.target.focus(),this.emit("click",t)}onContentBlur(){this.emit("update-end")}_setTotalDuration(t){this.totalDuration=t,this.renderPosition()}play(){this.emit("play")}setContent(t){var e;if(null===(e=this.content)||void 0===e||e.remove(),t){if("string"==typeof t){const e=this.start===this.end;this.content=m("div",{style:{padding:`0.2em ${e?.2:.4}em`,display:"inline-block"},textContent:t})}else this.content=t;this.contentEditable&&(this.content.contentEditable="true"),this.content.setAttribute("part","region-content"),this.element.appendChild(this.content)}else this.content=void 0}setOptions(t){var e,i;if(t.color&&(this.color=t.color,this.element.style.backgroundColor=this.color),void 0!==t.drag&&(this.drag=t.drag,this.element.style.cursor=this.drag?"grab":"default"),void 0!==t.start||void 0!==t.end){const n=this.start===this.end;this.start=this.clampPosition(null!==(e=t.start)&&void 0!==e?e:this.start),this.end=this.clampPosition(null!==(i=t.end)&&void 0!==i?i:n?this.start:this.end),this.renderPosition(),this.setPart()}if(t.content&&this.setContent(t.content),t.id&&(this.id=t.id,this.setPart()),void 0!==t.resize&&t.resize!==this.resize){const e=this.start===this.end;this.resize=t.resize,this.resize&&!e?this.addResizeHandles(this.element):this.removeResizeHandles(this.element)}}remove(){this.emit("remove"),this.element.remove(),this.element=null}},g=class t extends u{constructor(t){super(t),this.regions=[],this.regionsContainer=this.initRegionsContainer()}static create(e){return new t(e)}onInit(){if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");this.wavesurfer.getWrapper().appendChild(this.regionsContainer);let t=[];this.subscriptions.push(this.wavesurfer.on("timeupdate",(e=>{const i=this.regions.filter((t=>t.start<=e&&(t.end===t.start?t.start+.05:t.end)>=e));i.forEach((e=>{t.includes(e)||this.emit("region-in",e)})),t.forEach((t=>{i.includes(t)||this.emit("region-out",t)})),t=i})))}initRegionsContainer(){return m("div",{style:{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",zIndex:"3",pointerEvents:"none"}})}getRegions(){return this.regions}avoidOverlapping(t){if(!t.content)return;const e=t.content,i=e.getBoundingClientRect(),n=this.regions.map((e=>{if(e===t||!e.content)return 0;const n=e.content.getBoundingClientRect();return i.left<n.left+n.width&&n.left<i.left+i.width?n.height:0})).reduce(((t,e)=>t+e),0);e.style.marginTop=`${n}px`}adjustScroll(t){var e,i;const n=null===(i=null===(e=this.wavesurfer)||void 0===e?void 0:e.getWrapper())||void 0===i?void 0:i.parentElement;if(!n)return;const{clientWidth:s,scrollWidth:o}=n;if(o<=s)return;const r=n.getBoundingClientRect(),a=t.element.getBoundingClientRect(),h=a.left-r.left,l=a.right-r.left;h<0?n.scrollLeft+=h:l>s&&(n.scrollLeft+=l-s)}saveRegion(t){this.regionsContainer.appendChild(t.element),this.avoidOverlapping(t),this.regions.push(t);const e=[t.on("update",(()=>{this.adjustScroll(t)})),t.on("update-end",(()=>{this.avoidOverlapping(t),this.emit("region-updated",t)})),t.on("play",(()=>{var e,i;null===(e=this.wavesurfer)||void 0===e||e.play(),null===(i=this.wavesurfer)||void 0===i||i.setTime(t.start)})),t.on("click",(e=>{this.emit("region-clicked",t,e)})),t.on("dblclick",(e=>{this.emit("region-double-clicked",t,e)})),t.once("remove",(()=>{e.forEach((t=>t())),this.regions=this.regions.filter((e=>e!==t)),this.emit("region-removed",t)}))];this.subscriptions.push(...e),this.emit("region-created",t)}addRegion(t){var e,i;if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");const n=this.wavesurfer.getDuration(),s=null===(i=null===(e=this.wavesurfer)||void 0===e?void 0:e.getDecodedData())||void 0===i?void 0:i.numberOfChannels,o=new v(t,n,s);return n?this.saveRegion(o):this.subscriptions.push(this.wavesurfer.once("ready",(t=>{o._setTotalDuration(t),this.saveRegion(o)}))),o}enableDragSelection(t,e=3){var i;const n=null===(i=this.wavesurfer)||void 0===i?void 0:i.getWrapper();if(!(n&&n instanceof HTMLElement))return()=>{};let s=null,o=0;return c(n,((t,e,i)=>{s&&s._onUpdate(t,i>o?"end":"start")}),(e=>{var i,n;if(o=e,!this.wavesurfer)return;const r=this.wavesurfer.getDuration(),a=null===(n=null===(i=this.wavesurfer)||void 0===i?void 0:i.getDecodedData())||void 0===n?void 0:n.numberOfChannels,{width:h}=this.wavesurfer.getWrapper().getBoundingClientRect(),l=e/h*r,d=(e+5)/h*r;s=new v(Object.assign(Object.assign({},t),{start:l,end:d}),r,a),this.regionsContainer.appendChild(s.element)}),(()=>{s&&(this.saveRegion(s),s=null)}),e)}clearRegions(){this.regions.forEach((t=>t.remove()))}destroy(){this.clearRegions(),super.destroy(),this.regionsContainer.remove()}},f=class{constructor(){this.listeners={}}on(t,e,i){if(this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),null==i?void 0:i.once){const i=()=>{this.un(t,i),this.un(t,e)};return this.on(t,i),i}return()=>this.un(t,e)}un(t,e){var i;null===(i=this.listeners[t])||void 0===i||i.delete(e)}once(t,e){return this.on(t,e,{once:!0})}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}},y=class extends f{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}_init(t){this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t()))}};function b(t,e){const i=e.xmlns?document.createElementNS(e.xmlns,t):document.createElement(t);for(const[t,n]of Object.entries(e))if("children"===t)for(const[t,n]of Object.entries(e))"string"==typeof n?i.appendChild(document.createTextNode(n)):i.appendChild(b(t,n));else"style"===t?Object.assign(i.style,n):"textContent"===t?i.textContent=n:i.setAttribute(t,n.toString());return i}function A(t,e,i){const n=b(t,e||{});return null==i||i.appendChild(n),n}const C={height:20,formatTimeCallback:t=>t/60>1?`${Math.floor(t/60)}:${(t=Math.round(t%60))<10?"0":""}${t}`:""+Math.round(1e3*t)/1e3};let E=class t extends y{constructor(t){super(t||{}),this.options=Object.assign({},C,t),this.timelineWrapper=this.initTimelineWrapper()}static create(e){return new t(e)}onInit(){var t;if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");let e=this.wavesurfer.getWrapper();if(this.options.container instanceof HTMLElement)e=this.options.container;else if("string"==typeof this.options.container){const t=document.querySelector(this.options.container);if(!t)throw Error(`No Timeline container found matching ${this.options.container}`);e=t}this.options.insertPosition?(e.firstElementChild||e).insertAdjacentElement(this.options.insertPosition,this.timelineWrapper):e.appendChild(this.timelineWrapper),this.subscriptions.push(this.wavesurfer.on("redraw",(()=>this.initTimeline()))),((null===(t=this.wavesurfer)||void 0===t?void 0:t.getDuration())||this.options.duration)&&this.initTimeline()}destroy(){this.timelineWrapper.remove(),super.destroy()}initTimelineWrapper(){return A("div",{part:"timeline-wrapper",style:{pointerEvents:"none"}})}defaultTimeInterval(t){return t>=25?1:5*t>=25?5:15*t>=25?15:60*Math.ceil(.5/t)}defaultPrimaryLabelInterval(t){return t>=25?10:5*t>=25?6:4}defaultSecondaryLabelInterval(t){return t>=25?5:2}initTimeline(){var t,e,i,n,s,o,r;const a=null!==(i=null!==(e=null===(t=this.wavesurfer)||void 0===t?void 0:t.getDuration())&&void 0!==e?e:this.options.duration)&&void 0!==i?i:0,h=this.timelineWrapper.scrollWidth/a,l=null!==(n=this.options.timeInterval)&&void 0!==n?n:this.defaultTimeInterval(h),d=null!==(s=this.options.primaryLabelInterval)&&void 0!==s?s:this.defaultPrimaryLabelInterval(h),u=this.options.primaryLabelSpacing,c=null!==(o=this.options.secondaryLabelInterval)&&void 0!==o?o:this.defaultSecondaryLabelInterval(h),p=this.options.secondaryLabelSpacing,m="beforebegin"===this.options.insertPosition,v=A("div",{style:Object.assign({height:`${this.options.height}px`,overflow:"hidden",fontSize:this.options.height/2+"px",whiteSpace:"nowrap"},m?{position:"absolute",top:"0",left:"0",right:"0",zIndex:"2"}:{position:"relative"})});"string"==typeof this.options.style?v.setAttribute("style",v.getAttribute("style")+this.options.style):"object"==typeof this.options.style&&Object.assign(v.style,this.options.style);const g=A("div",{style:{width:"0",height:"50%",display:"flex",flexDirection:"column",justifyContent:m?"flex-start":"flex-end",top:m?"0":"auto",bottom:m?"auto":"0",overflow:"visible",borderLeft:"1px solid currentColor",opacity:`${null!==(r=this.options.secondaryLabelOpacity)&&void 0!==r?r:.25}`,position:"absolute",zIndex:"1"}});for(let t=0,e=0;t<a;t+=l,e++){const i=g.cloneNode(),n=Math.round(100*t)/100%d==0||u&&e%u==0,s=Math.round(100*t)/100%c==0||p&&e%p==0;(n||s)&&(i.style.height="100%",i.style.textIndent="3px",i.textContent=this.options.formatTimeCallback(t),n&&(i.style.opacity="1"));const o=n?"primary":s?"secondary":"tick";i.setAttribute("part",`timeline-notch timeline-notch-${o}`),i.style.left=t*h+"px",v.appendChild(i)}this.timelineWrapper.innerHTML="",this.timelineWrapper.appendChild(v),this.emit("ready")}};class w{constructor(){this.listeners={}}on(t,e,i){if(this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),null==i?void 0:i.once){const i=()=>{this.un(t,i),this.un(t,e)};return this.on(t,i),i}return()=>this.un(t,e)}un(t,e){var i;null===(i=this.listeners[t])||void 0===i||i.delete(e)}once(t,e){return this.on(t,e,{once:!0})}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}class x extends w{constructor(t){super(),this.subscriptions=[],this.options=t}onInit(){}_init(t){this.wavesurfer=t,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((t=>t()))}}function P(t,e,i,n,s=3,o=0){if(!t)return()=>{};let r=()=>{};const a=a=>{if(a.button!==o)return;a.preventDefault(),a.stopPropagation();let h=a.clientX,l=a.clientY,d=!1;const u=n=>{n.preventDefault(),n.stopPropagation();const o=n.clientX,r=n.clientY,a=o-h,u=r-l;if(d||Math.abs(a)>s||Math.abs(u)>s){const n=t.getBoundingClientRect(),{left:s,top:c}=n;d||(null==i||i(h-s,l-c),d=!0),e(a,u,o-s,r-c),h=o,l=r}},c=()=>{d&&(null==n||n()),r()},p=t=>{t.relatedTarget&&t.relatedTarget!==document.documentElement||c()},m=t=>{d&&(t.stopPropagation(),t.preventDefault())},v=t=>{d&&t.preventDefault()};document.addEventListener("pointermove",u),document.addEventListener("pointerup",c),document.addEventListener("pointerout",p),document.addEventListener("pointercancel",p),document.addEventListener("touchmove",v,{passive:!1}),document.addEventListener("click",m,{capture:!0}),r=()=>{document.removeEventListener("pointermove",u),document.removeEventListener("pointerup",c),document.removeEventListener("pointerout",p),document.removeEventListener("pointercancel",p),document.removeEventListener("touchmove",v),setTimeout((()=>{document.removeEventListener("click",m,{capture:!0})}),10)}};return t.addEventListener("pointerdown",a),()=>{r(),t.removeEventListener("pointerdown",a)}}function k(t,e){const i=e.xmlns?document.createElementNS(e.xmlns,t):document.createElement(t);for(const[t,n]of Object.entries(e))if("children"===t)for(const[t,n]of Object.entries(e))"string"==typeof n?i.appendChild(document.createTextNode(n)):i.appendChild(k(t,n));else"style"===t?Object.assign(i.style,n):"textContent"===t?i.textContent=n:i.setAttribute(t,n.toString());return i}function D(t,e,i){const n=k(t,e||{});return null==i||i.appendChild(n),n}const L={points:[],lineWidth:4,lineColor:"rgba(0, 0, 255, 0.5)",dragPointSize:10,dragPointFill:"rgba(255, 255, 255, 0.8)",dragPointStroke:"rgba(255, 255, 255, 0.8)"};class S extends w{constructor(t,e){super(),this.options=t,this.polyPoints=new Map;const i=e.clientWidth,n=e.clientHeight,s=D("svg",{xmlns:"http://www.w3.org/2000/svg",width:"100%",height:"100%",viewBox:`0 0 ${i} ${n}`,preserveAspectRatio:"none",style:{position:"absolute",left:"0",top:"0",zIndex:"4"},part:"envelope"},e);this.svg=s;const o=D("polyline",{xmlns:"http://www.w3.org/2000/svg",points:`0,${n} ${i},${n}`,stroke:t.lineColor,"stroke-width":t.lineWidth,fill:"none",part:"polyline",style:t.dragLine?{cursor:"row-resize",pointerEvents:"stroke"}:{}},s);t.dragLine&&P(o,((t,e)=>{const{height:i}=s.viewBox.baseVal,{points:n}=o;for(let t=1;t<n.numberOfItems-1;t++){const s=n.getItem(t);s.y=Math.min(i,Math.max(0,s.y+e))}const r=s.querySelectorAll("ellipse");Array.from(r).forEach((t=>{const n=Math.min(i,Math.max(0,Number(t.getAttribute("cy"))+e));t.setAttribute("cy",n.toString())})),this.emit("line-move",e/i)})),s.addEventListener("dblclick",(t=>{const e=s.getBoundingClientRect(),i=t.clientX-e.left,n=t.clientY-e.top;this.emit("point-create",i/e.width,n/e.height)}));{let t;const e=()=>clearTimeout(t);s.addEventListener("touchstart",(i=>{1===i.touches.length?t=window.setTimeout((()=>{i.preventDefault();const t=s.getBoundingClientRect(),e=i.touches[0].clientX-t.left,n=i.touches[0].clientY-t.top;this.emit("point-create",e/t.width,n/t.height)}),500):e()})),s.addEventListener("touchmove",e),s.addEventListener("touchend",e)}}makeDraggable(t,e){P(t,e,(()=>t.style.cursor="grabbing"),(()=>t.style.cursor="grab"),1)}createCircle(t,e){const i=this.options.dragPointSize/2;return D("ellipse",{xmlns:"http://www.w3.org/2000/svg",cx:t,cy:e,rx:i,ry:i,fill:this.options.dragPointFill,stroke:this.options.dragPointStroke,"stroke-width":"2",style:{cursor:"grab",pointerEvents:"all"},part:"envelope-circle"},this.svg)}removePolyPoint(t){const e=this.polyPoints.get(t);if(!e)return;const{polyPoint:i,circle:n}=e,{points:s}=this.svg.querySelector("polyline"),o=Array.from(s).findIndex((t=>t.x===i.x&&t.y===i.y));s.removeItem(o),n.remove(),this.polyPoints.delete(t)}addPolyPoint(t,e,i){const{svg:n}=this,{width:s,height:o}=n.viewBox.baseVal,r=t*s,a=o-e*o,h=this.options.dragPointSize/2,l=n.createSVGPoint();l.x=t*s,l.y=o-e*o;const d=this.createCircle(r,a),{points:u}=n.querySelector("polyline"),c=Array.from(u).findIndex((t=>t.x>=r));u.insertItemBefore(l,Math.max(c,1)),this.polyPoints.set(i,{polyPoint:l,circle:d}),this.makeDraggable(d,((t,e)=>{const n=l.x+t,r=l.y+e;if(n<-h||r<-h||n>s+h||r>o+h)return void this.emit("point-dragout",i);const a=Array.from(u).find((t=>t.x>l.x)),c=Array.from(u).findLast((t=>t.x<l.x));a&&n>=a.x||c&&n<=c.x||(l.x=n,l.y=r,d.setAttribute("cx",n.toString()),d.setAttribute("cy",r.toString()),this.emit("point-move",i,n/s,r/o))}))}update(){const{svg:t}=this,e=t.viewBox.baseVal.width/t.clientWidth,i=t.viewBox.baseVal.height/t.clientHeight;t.querySelectorAll("ellipse").forEach((t=>{const n=this.options.dragPointSize/2,s=n*e,o=n*i;t.setAttribute("rx",s.toString()),t.setAttribute("ry",o.toString())}))}destroy(){this.polyPoints.clear(),this.svg.remove()}}class T extends x{constructor(t){super(t),this.polyline=null,this.throttleTimeout=null,this.volume=1,this.points=t.points||[],this.options=Object.assign({},L,t),this.options.lineColor=this.options.lineColor||L.lineColor,this.options.dragPointFill=this.options.dragPointFill||L.dragPointFill,this.options.dragPointStroke=this.options.dragPointStroke||L.dragPointStroke,this.options.dragPointSize=this.options.dragPointSize||L.dragPointSize}static create(t){return new T(t)}addPoint(t){var e;t.id||(t.id=Math.random().toString(36).slice(2));const i=this.points.findLastIndex((e=>e.time<t.time));this.points.splice(i+1,0,t),this.emitPoints();const n=null===(e=this.wavesurfer)||void 0===e?void 0:e.getDuration();n&&this.addPolyPoint(t,n)}removePoint(t){var e;const i=this.points.indexOf(t);i>-1&&(this.points.splice(i,1),null===(e=this.polyline)||void 0===e||e.removePolyPoint(t),this.emitPoints())}getPoints(){return this.points}setPoints(t){this.points.slice().forEach((t=>this.removePoint(t))),t.forEach((t=>this.addPoint(t)))}destroy(){var t;null===(t=this.polyline)||void 0===t||t.destroy(),super.destroy()}getCurrentVolume(){return this.volume}setVolume(t){var e;this.volume=t,null===(e=this.wavesurfer)||void 0===e||e.setVolume(t)}onInit(){var t;if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");const{options:e}=this;e.volume=null!==(t=e.volume)&&void 0!==t?t:this.wavesurfer.getVolume(),this.setVolume(e.volume),this.subscriptions.push(this.wavesurfer.on("decode",(t=>{this.initPolyline(),this.points.forEach((e=>{this.addPolyPoint(e,t)}))})),this.wavesurfer.on("redraw",(()=>{var t;null===(t=this.polyline)||void 0===t||t.update()})),this.wavesurfer.on("timeupdate",(t=>{this.onTimeUpdate(t)})))}emitPoints(){this.throttleTimeout&&clearTimeout(this.throttleTimeout),this.throttleTimeout=setTimeout((()=>{this.emit("points-change",this.points)}),200)}initPolyline(){if(this.polyline&&this.polyline.destroy(),!this.wavesurfer)return;const t=this.wavesurfer.getWrapper();this.polyline=new S(this.options,t),this.subscriptions.push(this.polyline.on("point-move",((t,e,i)=>{var n;const s=(null===(n=this.wavesurfer)||void 0===n?void 0:n.getDuration())||0;t.time=e*s,t.volume=1-i,this.emitPoints()})),this.polyline.on("point-dragout",(t=>{this.removePoint(t)})),this.polyline.on("point-create",((t,e)=>{var i;this.addPoint({time:t*((null===(i=this.wavesurfer)||void 0===i?void 0:i.getDuration())||0),volume:1-e})})),this.polyline.on("line-move",(t=>{var e;this.points.forEach((e=>{e.volume=Math.min(1,Math.max(0,e.volume-t))})),this.emitPoints(),this.onTimeUpdate((null===(e=this.wavesurfer)||void 0===e?void 0:e.getCurrentTime())||0)})))}addPolyPoint(t,e){var i;null===(i=this.polyline)||void 0===i||i.addPolyPoint(t.time/e,t.volume,t)}onTimeUpdate(t){if(!this.wavesurfer)return;let e=this.points.find((e=>e.time>t));e||(e={time:this.wavesurfer.getDuration()||0,volume:0});let i=this.points.findLast((e=>e.time<=t));i||(i={time:0,volume:0});const n=e.time-i.time,s=e.volume-i.volume,o=i.volume+(t-i.time)*(s/n),r=Math.min(1,Math.max(0,o)),a=Math.round(100*r)/100;a!==this.getCurrentVolume()&&(this.setVolume(a),this.emit("volume-change",a))}}class M{constructor(){this.listeners={}}on(t,e,i){if(this.listeners[t]||(this.listeners[t]=new Set),this.listeners[t].add(e),null==i?void 0:i.once){const i=()=>{this.un(t,i),this.un(t,e)};return this.on(t,i),i}return()=>this.un(t,e)}un(t,e){var i;null===(i=this.listeners[t])||void 0===i||i.delete(e)}once(t,e){return this.on(t,e,{once:!0})}unAll(){this.listeners={}}emit(t,...e){this.listeners[t]&&this.listeners[t].forEach((t=>t(...e)))}}class R{constructor(t=new AudioContext){this.bufferNode=null,this.listeners=new Map,this.autoplay=!1,this.playStartTime=0,this.playedDuration=0,this._src="",this._duration=0,this._muted=!1,this.buffer=null,this.paused=!0,this.crossOrigin=null,this.audioContext=t,this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination)}addEventListener(t,e,i){if(this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t)?.add(e),i?.once){const i=()=>{this.removeEventListener(t,i),this.removeEventListener(t,e)};this.addEventListener(t,i)}}removeEventListener(t,e){this.listeners.has(t)&&this.listeners.get(t)?.delete(e)}emitEvent(t){this.listeners.get(t)?.forEach((t=>t()))}get src(){return this._src}set src(t){if(this._src=t,!t)return this.buffer=null,this._duration=0,void this.emitEvent("emptied");fetch(t).then((t=>t.arrayBuffer())).then((e=>this.src!==t?null:this.audioContext.decodeAudioData(e))).then((e=>{if(this.src!==t||!e)return null;this.buffer=e,this._duration=e.duration,this.emitEvent("loadedmetadata"),this.emitEvent("canplay"),this.autoplay&&this.play()}))}getChannelData(){const t=this.buffer?.getChannelData(0);return t?[t]:void 0}async play(){if(!this.paused)return;this.paused=!1,this.bufferNode?.disconnect(),this.bufferNode=this.audioContext.createBufferSource(),this.bufferNode.buffer=this.buffer,this.bufferNode.connect(this.gainNode);const t=this.playedDuration>0?this.playedDuration:0,e=this.playedDuration>0?this.audioContext.currentTime:this.audioContext.currentTime-this.playedDuration;this.bufferNode.start(e,t),this.playStartTime=this.audioContext.currentTime,this.emitEvent("play")}pause(){this.paused||(this.paused=!0,this.bufferNode?.stop(),this.playedDuration+=this.audioContext.currentTime-this.playStartTime,this.emitEvent("pause"))}async setSinkId(t){return this.audioContext.setSinkId(t)}get playbackRate(){return this.bufferNode?.playbackRate.value??1}set playbackRate(t){this.bufferNode&&(this.bufferNode.playbackRate.value=t)}get currentTime(){return this.paused?this.playedDuration:this.playedDuration+this.audioContext.currentTime-this.playStartTime}set currentTime(t){this.emitEvent("seeking"),this.paused?this.playedDuration=t:(this.pause(),this.playedDuration=t,this.play()),this.emitEvent("timeupdate")}get duration(){return this._duration}set duration(t){this._duration=t}get volume(){return this.gainNode.gain.value}set volume(t){this.gainNode.gain.value=t,this.emitEvent("volumechange")}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this._muted?this.gainNode.disconnect():this.gainNode.connect(this.audioContext.destination))}}const W={id:"placeholder",url:"data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU2LjM2LjEwMAAAAAAAAAAAAAAA//OEAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAAEAAABIADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV6urq6urq6urq6urq6urq6urq6urq6urq6v////////////////////////////////8AAAAATGF2YzU2LjQxAAAAAAAAAAAAAAAAJAAAAAAAAAAAASDs90hvAAAAAAAAAAAAAAAAAAAA//MUZAAAAAGkAAAAAAAAA0gAAAAATEFN//MUZAMAAAGkAAAAAAAAA0gAAAAARTMu//MUZAYAAAGkAAAAAAAAA0gAAAAAOTku//MUZAkAAAGkAAAAAAAAA0gAAAAANVVV",peaks:[[0]],startPosition:0,options:{height:0}};class O extends M{static create(t,e){return new O(t,e)}constructor(t,e){super(),this.audios=[],this.wavesurfers=[],this.envelopes=[],this.durations=[],this.currentTime=0,this.maxDuration=0,this.frameRequest=null,this.subscriptions=[],this.audioContext=new AudioContext,this.tracks=t.concat({...W}).map((t=>({...t,startPosition:t.startPosition||0,peaks:t.peaks||(t.url||t.options?.media?void 0:[new Float32Array])}))),this.options=e,this.rendering=function(t,e){let i=0,n=[],s=0;const o=document.createElement("div");o.setAttribute("style","width: 100%; overflow-x: scroll; overflow-y: hidden; user-select: none;");const r=document.createElement("div");r.style.position="relative",o.appendChild(r),e.container.appendChild(o);const a=document.createElement("div");a.setAttribute("style","height: 100%; position: absolute; z-index: 10; top: 0; left: 0; pointer-events: none;"),a.style.backgroundColor=e.cursorColor||"#000",a.style.width=`${e.cursorWidth??1}px`,r.appendChild(a);const{clientWidth:h}=r,l=t.map(((t,i)=>{const n=document.createElement("div");if(n.style.position="relative",t.id===W.id&&(n.style.display="none"),e.trackBorderColor&&i>0){const t=document.createElement("div");t.setAttribute("style",`width: 100%; height: 2px; background-color: ${e.trackBorderColor}`),r.appendChild(t)}if(e.trackBackground&&(t.url||t.options?.media)&&(n.style.background=e.trackBackground),!t.url&&!t.options?.media){const t=document.createElement("div");t.setAttribute("style",`position: absolute; z-index: 10; left: 10px; top: 10px; right: 10px; bottom: 10px; border: 2px dashed ${e.trackBorderColor};`),t.addEventListener("dragover",(i=>{i.preventDefault(),t.style.background=e.trackBackground||""})),t.addEventListener("dragleave",(e=>{e.preventDefault(),t.style.background=""})),t.addEventListener("drop",(e=>{e.preventDefault(),t.style.background=""})),n.appendChild(t)}return r.appendChild(n),n})),d=()=>{l.forEach(((e,s)=>{const o=t[s].startPosition*i;n[s]&&(e.style.width=n[s]*i+"px"),e.style.transform=`translateX(${o}px)`}))};return{containers:l,setContainerOffsets:d,setMainWidth:(t,o)=>{n=t,i=Math.max(e.minPxPerSec||0,h/o),s=i*o,r.style.width=`${s}px`,d()},updateCursor:(t,e)=>{a.style.left=`${Math.min(100,100*t)}%`;const{clientWidth:i,scrollLeft:n}=o,r=i/2,h=t*s;(h>n+(e?r:i)||h<n)&&(o.scrollLeft=h-r)},addClickHandler:t=>{r.addEventListener("click",(e=>{const i=r.getBoundingClientRect(),n=(e.clientX-i.left)/r.offsetWidth;t(n)}))},destroy:()=>{o.remove()},addDropHandler:e=>{t.forEach(((t,i)=>{if(!t.url&&!t.options?.media){const n=l[i].querySelector("div");n?.addEventListener("drop",(i=>{i.preventDefault(),e(t.id)}))}}))}}}(this.tracks,this.options),this.rendering.addDropHandler((t=>{this.emit("drop",{id:t})})),this.initAllAudios().then((i=>{this.initDurations(i),this.initAllWavesurfers(),this.rendering.containers.forEach(((i,n)=>{if(t[n]?.draggable){const t=z(i,(t=>this.onDrag(n,t)),e.rightButtonDrag);this.wavesurfers[n].once("destroy",t)}})),this.rendering.addClickHandler((t=>{this.seekTo(t)})),this.emit("canplay")}))}initDurations(t){this.durations=t,this.maxDuration=this.tracks.reduce(((e,i,n)=>Math.max(e,i.startPosition+t[n])),0);const e=this.audios.findIndex((t=>t.src===W.url)),i=this.audios[e];i&&(i.duration=this.maxDuration,this.durations[e]=this.maxDuration),this.rendering.setMainWidth(t,this.maxDuration)}initAudio(t){const e=/iPhone|iPad/.test(navigator.userAgent),i=t.id===W.id,n=t.options?.media||(e||i?new R(this.audioContext):new Audio);return n.crossOrigin="anonymous",t.url&&(n.src=t.url),void 0!==t.volume&&(n.volume=t.volume),new Promise((t=>{if(!n.src)return t(n);n.addEventListener("loadedmetadata",(()=>t(n)),{once:!0})}))}async initAllAudios(){return this.audios=await Promise.all(this.tracks.map((t=>this.initAudio(t)))),this.audios.map((t=>t.src?t.duration:0))}initWavesurfer(t,e){const i=this.rendering.containers[e],n=l.create({...t.options,container:i,minPxPerSec:0,media:this.audios[e],peaks:t.peaks||(this.audios[e]instanceof R?this.audios[e].getChannelData():void 0),duration:this.durations[e],cursorColor:"transparent",cursorWidth:0,interact:!1,hideScrollbar:!0});t.id===W.id&&n.registerPlugin(E.create({container:this.rendering.containers[0].parentElement,...this.options.timelineOptions}));const s=g.create();if(n.registerPlugin(s),this.subscriptions.push(n.once("decode",(()=>{if(null!=t.startCue||null!=t.endCue){const{startCue:i=0,endCue:n=this.durations[e]}=t,o=s.addRegion({start:0,end:i,color:"rgba(0, 0, 0, 0.7)",drag:!1}),r=s.addRegion({start:n,end:this.durations[e],color:"rgba(0, 0, 0, 0.7)",drag:!1});o.element.firstElementChild?.remove(),r.element.lastChild?.remove(),this.subscriptions.push(o.on("update-end",(()=>{t.startCue=o.end,this.emit("start-cue-change",{id:t.id,startCue:t.startCue})})),r.on("update-end",(()=>{t.endCue=r.start,this.emit("end-cue-change",{id:t.id,endCue:t.endCue})})))}if(t.intro){const e=s.addRegion({start:0,end:t.intro.endTime,content:t.intro.label,color:this.options.trackBackground,drag:!1});if(e.element.querySelector('[part*="region-handle-left"]')?.remove(),e.element.parentElement.style.mixBlendMode="plus-lighter",t.intro.color){const i=e.element.querySelector('[part*="region-handle-right"]');i&&(i.style.borderColor=t.intro.color)}this.subscriptions.push(e.on("update-end",(()=>{this.emit("intro-end-change",{id:t.id,endTime:e.end})})))}t.markers&&t.markers.forEach((t=>{s.addRegion({start:t.time,content:t.label,color:t.color,resize:!1})}))}))),t.envelope){const i=n.registerPlugin(T.create({...this.options.envelopeOptions,volume:t.volume}));Array.isArray(t.envelope)&&i.setPoints(t.envelope),t.fadeInEnd&&(t.startCue&&i.addPoint({time:t.startCue||0,volume:0,id:"startCue"}),i.addPoint({time:t.fadeInEnd||0,volume:t.volume??1,id:"fadeInEnd"})),t.fadeOutStart&&(i.addPoint({time:t.fadeOutStart,volume:t.volume??1,id:"fadeOutStart"}),t.endCue&&i.addPoint({time:t.endCue,volume:0,id:"endCue"})),this.envelopes[e]=i;const s=(t,e)=>{const n=i.getPoints().map((i=>i.id===t?{...i,time:e}:i));i.setPoints(n)};let o=t.fadeInEnd,r=t.fadeOutStart;this.subscriptions.push(i.on("volume-change",(e=>{this.emit("volume-change",{id:t.id,volume:e})})),i.on("points-change",(e=>{const i=e.find((t=>"fadeInEnd"===t.id));i&&i.time!==o&&(this.emit("fade-in-change",{id:t.id,fadeInEnd:i.time}),o=i.time);const n=e.find((t=>"fadeOutStart"===t.id));n&&n.time!==r&&(this.emit("fade-out-change",{id:t.id,fadeOutStart:n.time}),r=n.time),this.emit("envelope-points-change",{id:t.id,points:e})})),this.on("start-cue-change",(({id:e,startCue:i})=>{e===t.id&&s("startCue",i)})),this.on("end-cue-change",(({id:e,endCue:i})=>{e===t.id&&s("endCue",i)})),n.on("decode",(()=>{i.setVolume(t.volume??1)})))}return n}initAllWavesurfers(){const t=this.tracks.map(((t,e)=>this.initWavesurfer(t,e)));this.wavesurfers=t}updatePosition(t,e=!1){const i=!this.isPlaying();t!==this.currentTime&&(this.currentTime=t,this.rendering.updateCursor(t/this.maxDuration,e)),this.tracks.forEach(((e,n)=>{const s=this.audios[n],o=this.durations[n],r=t-e.startPosition;Math.abs(s.currentTime-r)>.3&&(s.currentTime=Math.max(0,r)),i||r<0||r>o?!s.paused&&s.pause():i||s.paused&&s.play();const a=r<(e.startCue||0)||r>(e.endCue||1/0);a!=s.muted&&(s.muted=a)}))}onDrag(t,e){const i=this.tracks[t];if(!i.draggable)return;const n=i.startPosition+e*this.maxDuration,s=this.options.dragBounds?0:-this.durations[t]-1,o=this.maxDuration-this.durations[t];n>=s&&n<=o&&(i.startPosition=n,this.initDurations(this.durations),this.rendering.setContainerOffsets(),this.updatePosition(this.currentTime),this.emit("start-position-change",{id:i.id,startPosition:n}))}findCurrentTracks(){const t=[];if(this.tracks.forEach(((e,i)=>{(e.url||e.options?.media)&&this.currentTime>=e.startPosition&&this.currentTime<e.startPosition+this.durations[i]&&t.push(i)})),0===t.length){const e=Math.min(...this.tracks.filter((t=>t.url)).map((t=>t.startPosition)));t.push(this.tracks.findIndex((t=>t.startPosition===e)))}return t}startSync(){const t=()=>{const e=this.audios.reduce(((t,e,i)=>(e.paused||(t=Math.max(t,e.currentTime+this.tracks[i].startPosition)),t)),this.currentTime);e>this.currentTime&&this.updatePosition(e,!0),this.frameRequest=requestAnimationFrame(t)};t()}play(){this.audioContext&&"suspended"===this.audioContext.state&&this.audioContext.resume(),this.startSync();this.findCurrentTracks().forEach((t=>{this.audios[t]?.play()}))}pause(){this.audios.forEach((t=>t.pause()))}isPlaying(){return this.audios.some((t=>!t.paused))}getCurrentTime(){return this.currentTime}seekTo(t){const e=this.isPlaying();this.updatePosition(t*this.maxDuration),e&&this.play()}setTime(t){const e=this.isPlaying();this.updatePosition(t),e&&this.play()}zoom(t){this.options.minPxPerSec=t,this.wavesurfers.forEach(((e,i)=>this.tracks[i].url&&e.zoom(t))),this.rendering.setMainWidth(this.durations,this.maxDuration),this.rendering.setContainerOffsets()}addTrack(t){const e=this.tracks.findIndex((e=>e.id===t.id));-1!==e&&(this.tracks[e]=t,this.initAudio(t).then((i=>{this.audios[e]=i,this.durations[e]=i.duration,this.initDurations(this.durations);const n=this.rendering.containers[e];n.innerHTML="",this.wavesurfers[e].destroy(),this.wavesurfers[e]=this.initWavesurfer(t,e);const s=z(n,(t=>this.onDrag(e,t)),this.options.rightButtonDrag);this.wavesurfers[e].once("destroy",s),this.emit("canplay")})))}destroy(){this.frameRequest&&cancelAnimationFrame(this.frameRequest),this.rendering.destroy(),this.audios.forEach((t=>{t.pause(),t.src=""})),this.wavesurfers.forEach((t=>{t.destroy()}))}setSinkId(t){return Promise.all(this.wavesurfers.map((e=>e.setSinkId(t))))}setTrackVolume(t,e){(this.envelopes[t]||this.wavesurfers[t])?.setVolume(e)}setTrackStartPosition(t,e){const i=this.tracks[t];if(!i.draggable)return;const n=e,s=this.options.dragBounds?0:-this.durations[t]-1,o=this.maxDuration-this.durations[t];n>=s&&n<=o&&(i.startPosition=n,this.initDurations(this.durations),this.rendering.setContainerOffsets(),this.updatePosition(this.currentTime),this.emit("start-position-change",{id:i.id,startPosition:n}))}getEnvelopePoints(t){return this.envelopes[t]?.getPoints()}setEnvelopePoints(t,e){this.envelopes[t]?.setPoints(e)}}function z(t,e,i=!1){let n=0;const s=function(t,e,i,n,s=3,o=0){if(!t)return()=>{};let r=()=>{};const a=a=>{if(a.button!==o)return;a.preventDefault(),a.stopPropagation();let h=a.clientX,l=a.clientY,d=!1;const u=n=>{n.preventDefault(),n.stopPropagation();const o=n.clientX,r=n.clientY,a=o-h,u=r-l;if(d||Math.abs(a)>s||Math.abs(u)>s){const n=t.getBoundingClientRect(),{left:s,top:c}=n;d||(null==i||i(h-s,l-c),d=!0),e(a,u,o-s,r-c),h=o,l=r}},c=()=>{d&&(null==n||n()),r()},p=t=>{t.relatedTarget&&t.relatedTarget!==document.documentElement||c()},m=t=>{d&&(t.stopPropagation(),t.preventDefault())},v=t=>{d&&t.preventDefault()};document.addEventListener("pointermove",u),document.addEventListener("pointerup",c),document.addEventListener("pointerout",p),document.addEventListener("pointercancel",p),document.addEventListener("touchmove",v,{passive:!1}),document.addEventListener("click",m,{capture:!0}),r=()=>{document.removeEventListener("pointermove",u),document.removeEventListener("pointerup",c),document.removeEventListener("pointerout",p),document.removeEventListener("pointercancel",p),document.removeEventListener("touchmove",v),setTimeout((()=>{document.removeEventListener("click",m,{capture:!0})}),10)}};return t.addEventListener("pointerdown",a),()=>{r(),t.removeEventListener("pointerdown",a)}}(t,(t=>{e(t/n)}),(()=>{t.style.cursor="grabbing",n=t.parentElement?.offsetWidth??0}),(()=>{t.style.cursor="grab"}),5,i?2:0),o=t=>t.preventDefault();return t.style.cursor="grab",i&&t.addEventListener("contextmenu",o),()=>{t.style.cursor="",s(),i&&t.removeEventListener("contextmenu",o)}}export{O as default};
