@arraypress/waveform-sounds 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (()=>{var Pt=Object.freeze({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function O(s){return s==null?"":String(s).replace(/[&<>"']/g,t=>Pt[t])}var Ft=/[^\p{L}\p{N}]+/u,Nt=/\p{Mn}+/gu;function x(s){return!s||typeof s!="string"?"":s.toLowerCase().normalize("NFD").replace(Nt,"")}function $(s){return x(s).split(Ft).filter(t=>t!=="")}function rt(s,t){let e=Array.from(s??""),n=Array.from(t??""),r=[],o=Array.from({length:n.length+1},(i,a)=>a);for(let i=1;i<=e.length;i++){let a=[i];for(let l=1;l<=n.length;l++){let d=e[i-1]===n[l-1]?0:1;a[l]=Math.min(o[l]+1,a[l-1]+1,o[l-1]+d),i>1&&l>1&&e[i-1]===n[l-2]&&e[i-2]===n[l-1]&&(a[l]=Math.min(a[l],r[l-2]+1))}r=o,o=a}return o[n.length]}function ot(s,t,e={}){let n=e.fuzzyFrom??4,r=x(s),o=$(s);return $(t).every(i=>{if(r.includes(i))return!0;let a=Array.from(i).length;return a<n?!1:o.some(l=>rt(i,l)<=1||rt(i,Array.from(l).slice(0,a).join(""))<=1)})}function F(s){if(!Array.isArray(s))return"";let t="";for(let e of s){let n=Math.round(Math.min(Math.max(Number(e)||0,0),1)*255);t+=(n<16?"0":"")+n.toString(16)}return t}function j(s,t=1){if(s==null||s==="")return null;if(typeof s=="string"){if(!/^[0-9a-f]+$/i.test(s)||s.length%2)return null;let r=new Array(s.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(s.substr(o*2,2),16)/255;return r}if(!Array.isArray(s))return null;let e=Number(t)>0?Number(t):1,n=s.map(r=>Math.min(Math.max((Number(r)||0)/e,0),1));return n.length?n:null}function E(s){if(s==null)return"";let t=String(s).trim(),e=t.match(/^([A-Ga-g])[\s_-]*([#♯b♭]?)[\s_-]*(m|min|minor|maj|major)?$/i);if(!e)return t;let n=e[1].toUpperCase(),r=e[2]==="\u266F"?"#":e[2]==="\u266D"?"b":e[2],o=e[3]&&/^m(in(or)?)?$/i.test(e[3])&&e[3]!=="M";return n+r+(o?"m":"")}var Dt={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11};function P(s){if(!s)return 1/0;let t=s.endsWith("m"),e=t?s.slice(0,-1):s,n=Dt[e];return n===void 0?1e3:n*2+(t?1:0)}function N(s){if(s==null||s==="")return"";let t=Number(s);if(!Number.isFinite(t)||t<0)return"";if(t>0&&t<.95)return`${Math.max(.1,Math.round(t*10)/10).toFixed(1)}s`;let e=Math.round(t);return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function zt(s){if(s==null||s==="")return null;if(typeof s=="number")return Number.isFinite(s)&&s>=0?s:null;let t=String(s).trim();if(/^\d+(\.\d+)?$/.test(t))return Number(t);let e=t.split(":").map(Number);return e.length<2||e.some(n=>!Number.isFinite(n))?null:e.reduce((n,r)=>n*60+r,0)}function qt(s){let e=(String(s||"").split(/[?#]/)[0].split("/").pop()||"").replace(/\.[a-z0-9]+$/i,"");try{e=decodeURIComponent(e)}catch{}return e.replace(/[_]+/g," ").replace(/\s+/g," ").trim()}function G(s,t,e=1){if(!s||typeof s!="object"||!s.url)return null;let n=Number(s.bpm),r=Array.isArray(s.tags)?s.tags.map(o=>String(o).trim()).filter(Boolean):typeof s.tags=="string"?s.tags.split(",").map(o=>o.trim()).filter(Boolean):[];return{id:s.id!=null&&s.id!==""?String(s.id):`sound-${t+1}`,url:String(s.url),title:s.title?String(s.title):qt(s.url),type:s.type?String(s.type):"",bpm:Number.isFinite(n)&&n>0?Math.round(n*100)/100:null,key:E(s.key),duration:zt(s.duration),tags:r,peaks:j(s.peaks,e),waveform:s.waveform?String(s.waveform):null,download:s.download?String(s.download):null,loop:Bt(s.loop)}}var it=["loop","one-shot"];function Bt(s){return s===!0||s===1||s==="true"||s==="1"}function D(s){let t=Array.isArray(s)?s:Array.isArray(s?.sounds)?s.sounds:[],e=Array.isArray(s)?1:Number(s?.peakScale)||1;return S(t,e)}function S(s,t=1){let e=new Set,n=[];return(Array.isArray(s)?s:[]).forEach((r,o)=>{let i=G(r,o,t);if(!i)return;let a=i.id,l=2;for(;e.has(a);)a=`${i.id}-${l++}`;i.id=a,e.add(a),n.push(i)}),n}function _(s){let t=new Map,e=new Set,n=1/0,r=-1/0,o=!1,i=0;for(let a of s)a.type&&t.set(a.type,(t.get(a.type)||0)+1),a.key&&e.add(a.key),a.bpm!=null&&(n=Math.min(n,a.bpm),r=Math.max(r,a.bpm)),a.duration!=null&&(o=!0),a.loop&&i++;return{types:[...t].map(([a,l])=>({name:a,count:l})),keys:[...e].sort((a,l)=>P(a)-P(l)||a.localeCompare(l)),bpm:n===1/0?null:{min:n,max:r},hasDuration:o,loops:i,oneShots:s.length-i}}function z(s,t={}){if(t.type&&s.type!==t.type||t.key&&s.key!==E(t.key)||t.loop==="loop"&&!s.loop||t.loop==="one-shot"&&s.loop)return!1;let e=Number(t.bpmMin),n=Number(t.bpmMax);if((t.bpmMin!=null&&t.bpmMin!==""&&Number.isFinite(e)||t.bpmMax!=null&&t.bpmMax!==""&&Number.isFinite(n))&&(s.bpm==null||t.bpmMin!=null&&t.bpmMin!==""&&s.bpm<e||t.bpmMax!=null&&t.bpmMax!==""&&s.bpm>n))return!1;let r=$(t.query||"");if(r.length){let o=[s.title,s.type,s.key,...s.tags||[]].join(" "),i=x(o),a=r.filter(l=>!(/^\d+$/.test(l)&&!i.includes(l)&&s.bpm!=null&&Math.round(s.bpm)===Number(l)));if(a.length&&!ot(o,a.join(" ")))return!1}return!0}var T=["default","title","bpm","key","duration"],Ut={default:()=>!0,title:()=>!0,bpm:s=>s.bpm!==null,key:s=>s.keys.length>0,duration:s=>s.hasDuration};function q(s,t){return s.filter(e=>Ut[e]?.(t))}function k(s,t="default"){let e=s.map((o,i)=>({s:o,i})),n=o=>o??1/0,r={title:(o,i)=>o.s.title.localeCompare(i.s.title,void 0,{numeric:!0,sensitivity:"base"}),bpm:(o,i)=>n(o.s.bpm)-n(i.s.bpm),key:(o,i)=>P(o.s.key)-P(i.s.key),duration:(o,i)=>n(o.s.duration)-n(i.s.duration)}[t];return r&&e.sort((o,i)=>r(o,i)||o.i-i.i),e.map(o=>o.s)}function Kt(s){let t=s.getBoundingClientRect();if(!t.width||!t.height)return null;let e=Math.min(window.devicePixelRatio||1,3),n=Math.round(t.width*e),r=Math.round(t.height*e);return s.width!==n&&(s.width=n),s.height!==r&&(s.height=r),{width:t.width,height:t.height,dpr:e}}function W(s,t){if(!s?.length||t<=0)return[];if(s.length===t)return s;let e=new Array(t),n=s.length/t;for(let r=0;r<t;r++){let o=Math.floor(r*n),i=Math.max(o+1,Math.floor((r+1)*n)),a=0;for(let l=o;l<i&&l<s.length;l++)s[l]>a&&(a=s[l]);e[r]=a}return e}function Ht(s,t,e,n){let r=n.barWidth+n.barGap,o=W(s,Math.max(1,Math.floor((t+n.barGap)/r))),i=o.reduce((l,d)=>d>l?d:l,0),a=i>0?1/i:1;return o.map((l,d)=>{let c=Math.max(l*a,.04);if(n.style==="bars"){let I=Math.max(1,c*e);return{x:d*r,y:e-I,w:n.barWidth,h:I}}let h=Math.max(1,c*(e-2));return{x:d*r,y:e/2-h/2,w:n.barWidth,h}})}function at(s,t,e,n){let r=Kt(s),o=r&&s.getContext&&s.getContext("2d");if(!o)return;let{width:i,height:a,dpr:l}=r;if(o.setTransform(l,0,0,l,0,0),o.clearRect(0,0,i,a),!t?.length){o.fillStyle=n.color,o.fillRect(0,Math.floor(a/2),i,1);return}let d=new Path2D;for(let h of Ht(t,i,a,n))d.rect(h.x,h.y,h.w,h.h);o.fillStyle=n.color,o.fill(d);let c=Math.min(Math.max(e,0),1)*i;c>0&&(o.save(),o.beginPath(),o.rect(0,0,c,a),o.clip(),o.fillStyle=n.progressColor,o.fill(d),o.restore())}var jt=["onLoad","onPlay","onPause","onEnd","onTimeUpdate","onError"];function lt(s,t,e){let n=s||{},r=t==="strip",o={height:r?48:32,waveformStyle:r?"mirror":"bars",preload:"metadata",singlePlay:!0,...n,audioMode:"self"};for(let i of jt)o[i]=(...a)=>{e[i]?.(...a),typeof n[i]=="function"&&n[i](...a)};return o}function ut(s,t){return t==="strip"&&s.waveform||s.peaks||null}function Gt(s,t){let e=x(String(t??"")).trim();return!e||x(String(s??"")).includes(e)}function ct(s,t,e){return Math.max(0,Math.min(e-1,s+t))}function v(s){return{button:s.querySelector("[data-ws-menu-btn]"),pop:s.querySelector("[data-ws-menu-pop]"),search:s.querySelector("[data-ws-menu-search]"),list:s.querySelector("[data-ws-menu-list]"),none:s.querySelector("[data-ws-menu-none]"),value:s.querySelector("[data-ws-menu-value]")}}var V=s=>s.search||s.list,Y=(s,t=!1)=>[...s.list.querySelectorAll('[role="option"]')].filter(e=>!t||!e.hidden),B=class{constructor(t,{onPick:e,signal:n}){this.container=t,this.onPick=e,this.menus=Object.fromEntries([...t.querySelectorAll("[data-ws-menu]")].map(r=>[r.dataset.wsMenu,r])),this.openMenu=null,this._bind(n)}_bind(t){let e={signal:t};for(let[n,r]of Object.entries(this.menus)){let o=v(r);o.button.addEventListener("click",()=>this.openMenu===r?this.close(!0):this.open(r),e),o.button.addEventListener("keydown",i=>{(i.key==="ArrowDown"||i.key==="ArrowUp")&&(i.preventDefault(),this.open(r))},e),o.list.addEventListener("click",i=>{let a=i.target.closest('[role="option"]');a&&this._pick(n,a.dataset.value)},e),o.list.addEventListener("mousedown",i=>i.preventDefault(),e),o.search?.addEventListener("input",()=>this._filter(r,o.search.value),e),V(o).addEventListener("keydown",i=>this._onKey(i,n,r),e)}document.addEventListener("pointerdown",n=>{this.openMenu&&!this.openMenu.contains(n.target)&&this.close(!1)},e),this.container.addEventListener("focusout",n=>{this.openMenu&&!this.openMenu.contains(n.relatedTarget)&&this.close(!1)},e)}open(t){this.openMenu&&this.openMenu!==t&&this.close(!1);let e=v(t);e.button.setAttribute("aria-expanded","true"),e.pop.hidden=!1,this.openMenu=t,e.search&&(e.search.value="",this._filter(t,"")),t.classList.remove("ws-menu--end"),e.pop.getBoundingClientRect().right>this.container.getBoundingClientRect().right+1&&t.classList.add("ws-menu--end"),this._activate(t,e.list.querySelector('[role="option"][aria-selected="true"]')),V(e).focus()}close(t){let e=this.openMenu;if(!e)return;this.openMenu=null;let n=v(e);n.pop.hidden=!0,n.button.setAttribute("aria-expanded","false"),t&&n.button.focus()}setValue(t,e){let n=this.menus[t];if(!n)return;let r=v(n),o=null;for(let i of Y(r)){let a=i.dataset.value===String(e??"");i.setAttribute("aria-selected",String(a)),a&&(o=i.querySelector(".ws-menu-text")?.textContent??"")}o!==null&&(r.value.textContent=o)}_filter(t,e){let n=v(t),r=null;for(let o of Y(n))o.hidden=!Gt(o.textContent,e),o.hidden||(r??=o);n.none.hidden=r!==null,this._activate(t,r)}_activate(t,e){let n=v(t);for(let o of n.list.querySelectorAll(".is-active"))o.classList.remove("is-active");let r=V(n);if(!e||e.hidden){r.removeAttribute("aria-activedescendant");return}e.classList.add("is-active"),r.setAttribute("aria-activedescendant",e.id),e.scrollIntoView?.({block:"nearest"})}_onKey(t,e,n){let r=v(n),o=Y(r,!0),i=o.indexOf(r.list.querySelector(".is-active")),a=d=>{t.preventDefault(),this._activate(n,o[d])},l=t.target.matches("input");switch(t.key){case"ArrowDown":return a(ct(i,1,o.length));case"ArrowUp":return a(ct(i,-1,o.length));case"Home":return l?void 0:a(0);case"End":return l?void 0:a(o.length-1);case"Enter":t.preventDefault(),i>=0&&this._pick(e,o[i].dataset.value);return;case"Escape":return t.preventDefault(),t.stopPropagation(),this.close(!0);case"Tab":return this.close(!1);default:return}}_pick(t,e){this.close(!0),this.onPick(t,e)}};var w="[WaveformSounds]";function J(s,t=0,e=1){return Math.min(Math.max(s,t),e)}function pt(s,t){return t&&t.width?J((s-t.left)/t.width):0}function dt(s){return!!s&&(s.isContentEditable||/^(INPUT|SELECT|TEXTAREA)$/.test(s.tagName))}function ht(s,t,e){let n=new CustomEvent(`waveformsounds:${t}`,{bubbles:!0,detail:e});return s.dispatchEvent(n),n}function ft(s){let t=5381;for(let e of s)t=t*33+e.codePointAt(0)>>>0;return t}var mt=.1;function yt(s,t,e){if(!e)return null;switch(s){case"ArrowDown":return t+1<e?t+1:null;case"ArrowUp":return t>0?t-1:"search";case"Home":return 0;case"End":return e-1;default:return null}}function wt(s,t){return t!=="ArrowRight"&&t!=="ArrowLeft"?null:J(s+(t==="ArrowRight"?mt:-mt),0,.999)}function gt(s,t){let e=new Set(s.slice(0,t));return{visible:e,remaining:s.length-e.size}}function bt(s,t){return t>=s?t+1:s}var g={search:"Search sounds",searchPlaceholder:"Search sounds\u2026",all:"All",types:"Type",key:"Key",anyKey:"Any key",allTypes:"All types",findType:"Find a type\u2026",findKey:"Find a key\u2026",noMatches:"No matches",bpm:"BPM",bpmMin:"Min BPM",bpmMax:"Max BPM",sort:"Sort",sortBy:"Sort by",sortDefault:"Default",sortTitle:"Name",sortBpm:"BPM",sortKey:"Key",sortDuration:"Length",loop:"Loop",loopFilter:"Loops or one-shots",loops:"Loops",oneShots:"One-shots",isLoop:"Loop",play:"Play {title}",pause:"Pause {title}",seek:"Seek {title}",download:"Download {title}",count:"{count} sounds",countOne:"1 sound",countFiltered:"{count} of {total} sounds",showMore:"Show {count} more",empty:"No sounds match.",clear:"Clear filters",nowPlaying:"Playing {title}"},xt={default:"sortDefault",title:"sortTitle",bpm:"sortBpm",key:"sortKey",duration:"sortDuration"};function f(s,t={}){return String(s).replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e)}function U(s,t,e=g){return s!==t?f(e.countFiltered,{count:s,total:t}):t===1?e.countOne:f(e.count,{count:t})}var _t=["type","key","bpm","loop"],vt=["type","bpm","key","duration"],m={player:"inline",search:!0,filters:[..._t],sorts:[...T],loopToggle:!0,showCount:!0,menuSearch:8,pageSize:50,columns:[...vt],maxTypeChips:10};function St(s){let t={};for(let e in s??{})s[e]!==void 0&&(t[e]=s[e]);return t}function Q(s,t,e){return Array.isArray(s)?s.filter(n=>t.includes(n)):e}function X(s,t){let e=Number(s);return Number.isFinite(e)&&e>=0?Math.floor(e):t}function L(s={}){let t={...m,...St(s)};return{...t,player:t.player==="strip"?"strip":"inline",filters:Q(t.filters,_t,m.filters),sorts:Q(t.sorts,T,m.sorts),columns:Q(t.columns,vt,m.columns),menuSearch:X(t.menuSearch,m.menuSearch),maxTypeChips:X(t.maxTypeChips,m.maxTypeChips),pageSize:X(t.pageSize,m.pageSize),strings:{...g,...St(s.strings)}}}var K={...m,sounds:null,manifest:null,waveformStyle:"mirror",waveformColor:null,progressColor:null,barWidth:2,barGap:1,loop:!1,autoAdvance:!1,arrowAudition:!0,idPrefix:null,urlState:!1,playerOptions:null,playerClass:null,strings:null,onReady:null,onPlay:null,onPause:null,onEnd:null,onFilter:null,onError:null};function M(s){if(s===""||s==="true")return!0;if(s==="false")return!1}function Z(s){if(s!=null)return s.split(",").map(t=>t.trim()).filter(Boolean)}function C(s){return s===void 0||s===""?void 0:Number(s)}function Wt(s){if(s===void 0)return;let t=M(s);return t===void 0?s:t}function Mt(s,t){if(s)try{return JSON.parse(s)}catch{console.warn(`${w} Ignoring invalid JSON in data-${t}`);return}}function At(s){let t=s.dataset||{},e={player:t.player||void 0,manifest:t.manifest||void 0,search:M(t.search),filters:Z(t.filters),sorts:Z(t.sorts),showCount:M(t.showCount),menuSearch:C(t.menuSearch),idPrefix:t.idPrefix||void 0,urlState:Wt(t.urlState),loopToggle:M(t.loopToggle),pageSize:C(t.pageSize),maxTypeChips:C(t.maxTypeChips),columns:Z(t.columns),waveformStyle:t.waveformStyle||void 0,waveformColor:t.waveformColor||void 0,progressColor:t.progressColor||void 0,barWidth:C(t.barWidth),barGap:C(t.barGap),loop:M(t.loop),autoAdvance:M(t.autoAdvance),arrowAudition:M(t.arrowAudition),strings:Mt(t.strings,"strings"),playerOptions:Mt(t.playerOptions,"player-options")};for(let n of Object.keys(e))e[n]===void 0&&delete e[n];return e}function Et(...s){let t={};for(let e of s)if(e)for(let n in e)e[n]!==null&&e[n]!==void 0&&(t[n]=e[n]);return t}var Vt=new Set(["input","br","img"]);function p(s){return O(s??"")}function Yt(s={}){let t="";for(let[e,n]of Object.entries(s))n===!0?t+=` ${e}`:n!==!1&&n!=null&&(t+=` ${e}="${O(n)}"`);return t}function u(s,t={},...e){let n=`<${s}${Yt(t)}>`;return Vt.has(s)?n:n+e.flat(1/0).filter(r=>r!=null&&r!==!1&&r!=="").join("")+`</${s}>`}function A(s,t=""){return`<svg class="${t?`ws-icon ${t}`:"ws-icon"}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${s}"/></svg>`}var y={play:A("M8 5.5v13l11-6.5z","ws-icon-play"),pause:A("M7 5h3.5v14H7zM13.5 5H17v14h-3.5z","ws-icon-pause"),search:A("M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z"),chevron:A("M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z","ws-menu-chevron"),check:A("M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z","ws-menu-check"),download:A("M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z"),loop:A("M17 4l3 3-3 3V8H8a3 3 0 0 0-3 3v1H3v-1a5 5 0 0 1 5-5h9V4zM7 20l-3-3 3-3v2h9a3 3 0 0 0 3-3v-1h2v1a5 5 0 0 1-5 5H7v2z")};function Jt(s){let t=[s.length,...s.map(e=>e.url)].join("|");return`ws${ft(t).toString(36)}`}function Qt(s,t){let e=t.filters.includes("type")&&s.types.length>1,n=q(t.sorts,s);return{types:e?s.types.length>t.maxTypeChips?"menu":"chips":null,key:t.filters.includes("key")&&s.keys.length>1,bpm:t.filters.includes("bpm")&&s.bpm!==null&&s.bpm.max>s.bpm.min,loops:t.filters.includes("loop")&&s.loops>0&&s.oneShots>0,sorts:n.length>1?n:[],search:!!t.search,loop:!!t.loopToggle,count:!!t.showCount}}function Xt(s){return u("label",{class:"ws-search"},y.search,u("span",{class:"ws-sr"},p(s.search)),u("input",{type:"search",class:"ws-search-input","data-ws-search":!0,placeholder:s.searchPlaceholder,autocomplete:"off",spellcheck:"false"}))}function Zt(s,t){let e=`${t.id}-${s}-list`,n=t.options.find(l=>l.value===t.value)??t.options[0],r=t.placeholder&&t.options.length>t.searchFrom,o=u("button",{type:"button",class:"ws-menu-btn","data-ws-menu-btn":!0,"aria-haspopup":"listbox","aria-expanded":"false","aria-controls":e},t.prefix?u("span",{class:"ws-menu-prefix"},p(t.prefix)):u("span",{class:"ws-sr"},p(`${t.label}: `)),u("span",{class:"ws-menu-value","data-ws-menu-value":!0},p(n.label)),y.chevron),i=r&&u("input",{type:"search",class:"ws-menu-search","data-ws-menu-search":!0,role:"combobox","aria-expanded":"true","aria-controls":e,"aria-autocomplete":"list","aria-label":t.placeholder,placeholder:t.placeholder,autocomplete:"off",spellcheck:"false"}),a=t.options.map((l,d)=>u("li",{role:"option",id:`${t.id}-${s}-${d}`,class:"ws-menu-option","data-value":l.value,"aria-selected":String(l===n)},y.check,u("span",{class:"ws-menu-text"},p(l.label)),l.count!=null&&u("span",{class:"ws-menu-count"},p(l.count))));return u("div",{class:"ws-menu","data-ws-menu":s},o,u("div",{class:"ws-menu-pop","data-ws-menu-pop":!0,hidden:!0},i,u("ul",{class:"ws-menu-list",role:"listbox",id:e,"aria-label":t.label,tabindex:"-1","data-ws-menu-list":!0},a),u("p",{class:"ws-menu-none","data-ws-menu-none":!0,hidden:!0},p(t.noMatches))))}function te(s,t){let e=(n,r,o)=>u("input",{type:"number",inputmode:"numeric",[n]:!0,"aria-label":r,placeholder:o,min:"0",step:"1"});return u("span",{class:"ws-bpm-range",role:"group","aria-label":s.bpm},e("data-ws-bpm-min",s.bpmMin,t.min),u("span",{"aria-hidden":"true"},"\u2013"),e("data-ws-bpm-max",s.bpmMax,t.max),u("span",{class:"ws-bpm-unit","aria-hidden":"true"},p(s.bpm)))}function ee(s){let t=(e,n)=>u("button",{type:"button",class:"ws-seg-btn","data-ws-loop-filter":e,"aria-pressed":String(e==="")},u("span",{},p(n)));return u("div",{class:"ws-seg",role:"group","aria-label":s.loopFilter},t("",s.all),t("loop",s.loops),t("one-shot",s.oneShots))}function se(s){return u("button",{type:"button",class:"ws-loop","data-ws-loop":!0,"aria-pressed":"false"},y.loop,u("span",{},p(s.loop)))}function Tt(s,t,e,n){return u("button",{type:"button",class:"ws-chip","data-ws-type":s,"aria-pressed":String(n)},u("span",{class:"ws-chip-label"},p(t))," ",u("span",{class:"ws-chip-count"},p(e)))}function ne(s,{o:t,s:e,f:n,total:r,id:o}){let i=(c,h)=>Zt(c,{id:o,searchFrom:t.menuSearch,noMatches:e.noMatches,...h}),a=[s.types==="menu"&&i("type",{label:e.types,value:"",placeholder:e.findType,options:[{value:"",label:e.allTypes,count:r},...n.types.map(c=>({value:c.name,label:c.name,count:c.count}))]}),s.key&&i("key",{label:e.key,value:"",placeholder:e.findKey,options:[{value:"",label:e.anyKey},...n.keys.map(c=>({value:c,label:c}))]}),s.bpm&&te(e,n.bpm),s.loops&&ee(e),s.sorts.length>0&&i("sort",{label:e.sort,prefix:e.sortBy,value:s.sorts[0],options:s.sorts.map(c=>({value:c,label:e[xt[c]]}))}),s.loop&&se(e)].filter(Boolean),l=s.types==="chips"&&u("div",{class:"ws-types",role:"group","aria-label":e.types},Tt("",e.all,r,!0),n.types.map(c=>Tt(c.name,c.name,c.count,!1))),d=s.count&&u("p",{class:"ws-count","data-ws-count":!0,"aria-live":"polite"},p(U(r,r,e)));return u("div",{class:"ws-toolbar"},s.search&&Xt(e),a.length>0&&u("div",{class:"ws-controls"},a),(l||d)&&u("div",{class:"ws-meta"},l,d))}var re={type:s=>p(s.type),bpm:s=>p(s.bpm??""),key:s=>p(s.key),duration:s=>p(N(s.duration))};function oe(s,t,e,n=!1){let r=e.strings,o={title:s.title},i=e.columns.map(a=>u("span",{class:`ws-cell ws-${a}`},re[a](s)));return u("li",{class:"ws-row","data-ws-index":t,"data-ws-id":s.id,"data-url":s.url,"data-title":s.title,"data-type":s.type||null,"data-bpm":s.bpm,"data-key":s.key||null,"data-duration":s.duration,"data-tags":s.tags?.length?s.tags.join(","):null,"data-peaks":s.peaks?F(s.peaks):null,"data-waveform":s.waveform,"data-download":s.download,"data-loop":s.loop?"true":null,hidden:n},u("button",{type:"button",class:"ws-play","aria-pressed":"false","aria-label":f(r.play,o)},y.play,y.pause),u("span",{class:"ws-cell ws-title"},u("span",{class:"ws-title-text"},p(s.title)),s.loop&&u("span",{class:"ws-loop-mark",title:r.isLoop},y.loop,u("span",{class:"ws-sr"},p(r.isLoop)))),i.length>0&&u("span",{class:"ws-cells"},i),e.player==="inline"&&u("span",{class:"ws-wave",role:"slider","aria-label":f(r.seek,o),"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":"0",tabindex:"-1"},u("canvas",{class:"ws-canvas","aria-hidden":"true"})),s.download&&u("a",{class:"ws-download",href:s.download,download:!0,"aria-label":f(r.download,o)},y.download))}function ie({o:s,s:t,total:e}){let n=s.pageSize>0?s.pageSize:e,r=Math.max(0,e-n),o=s.player==="strip";return[u("p",{class:"ws-empty","data-ws-empty":!0,hidden:!0},p(t.empty)," ",u("button",{type:"button",class:"ws-clear","data-ws-clear":!0},p(t.clear))),u("button",{type:"button",class:"ws-more","data-ws-more":!0,hidden:r===0},p(f(t.showMore,{count:Math.min(r,n)}))),u("div",{class:o?"ws-engine ws-engine--strip":"ws-engine","data-ws-engine":!0,hidden:!o}),u("p",{class:"ws-sr","data-ws-status":!0,"aria-live":"polite"})].join("")}function R(s,t={}){let e=L(t),n=S(s),r={o:e,s:e.strings,f:_(n),total:n.length,id:e.idPrefix||Jt(n)},o=e.pageSize>0?e.pageSize:1/0;return ne(Qt(r.f,e),r)+u("ul",{class:`ws-list ws-list--${e.player}`,role:"list","data-ws-list":!0},n.map((i,a)=>oe(i,a,e,a>=o)))+ie(r)}function ae(s,t={},e=""){let n=L(t),r=["waveform-sounds",`waveform-sounds--${n.player}`,e].filter(Boolean).join(" ");return u("div",{class:r,"data-waveform-sounds":!0,"data-player":n.player},R(s,t))}var tt=":scope > [data-ws-index]";function kt(s){let t=[...s.querySelectorAll(tt)].sort((n,r)=>Number(n.dataset.wsIndex)-Number(r.dataset.wsIndex)),e=[];for(let n of t){let r=n.dataset,o=G({id:r.wsId,url:r.url,title:r.title,type:r.type,bpm:r.bpm,key:r.key,duration:r.duration,tags:r.tags,peaks:r.peaks,waveform:r.waveform,download:r.download,loop:r.loop},e.length);if(!o){n.remove();continue}n.dataset.wsIndex=String(e.length),e.push(o)}return e}function Lt(s){let t=[];return s.querySelectorAll(tt).forEach(e=>{t[Number(e.dataset.wsIndex)]=e}),t}function et(s){return[...s.querySelectorAll(tt)].filter(t=>!t.hidden)}function Ct(s,t){let e=document.createDocumentFragment();for(let n of t)n&&e.appendChild(n);s.appendChild(e)}function le(s){let t=String(s??"").trim();if(!t||t==="transparent")return 0;let e=t.match(/\/\s*([\d.]+)(%?)\s*\)$/);if(e)return Number(e[1])/(e[2]?100:1);let n=t.match(/^rgba\(\s*[^,]+,[^,]+,[^,]+,\s*([\d.]+)\s*\)$/);return n?Number(n[1]):1}function Rt(s,t=.95){for(let e=s;e&&e.nodeType===1;e=e.parentElement||e.getRootNode?.().host){let n=getComputedStyle(e).backgroundColor;if(le(n)>t)return n}return"#fff"}function st(s,t){let e=document.createElement("span");e.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden",e.style.color=t,s.appendChild(e);let n=getComputedStyle(e).color;return e.remove(),n}function nt(s){if(!s)return null;let t=typeof s=="string"?`${s}-`:"";return{q:`${t}q`,type:`${t}type`,key:`${t}key`,bpm:`${t}bpm`,loop:`${t}loop`,sort:`${t}sort`}}function ue(s){let t=String(s??"").match(/^(\d*)-(\d*)$/);return t&&(t[1]||t[2])?{bpmMin:t[1],bpmMax:t[2]}:null}function ce(s,t){let e=s??"",n=t??"";return e!==""||n!==""?`${e}-${n}`:""}function It(s,t,e,n){let r={filter:{},sort:null};if(!t)return r;let o=new URLSearchParams(s),i=o.get(t.q);i&&(r.filter.query=i);let a=o.get(t.type);a&&e.types.some(I=>I.name===a)&&(r.filter.type=a);let l=E(o.get(t.key));l&&e.keys.includes(l)&&(r.filter.key=l);let d=ue(o.get(t.bpm));d&&Object.assign(r.filter,d);let c=o.get(t.loop);it.includes(c)&&e.loops>0&&e.oneShots>0&&(r.filter.loop=c);let h=o.get(t.sort);return h&&n.includes(h)&&(r.sort=h),r}function $t(s,t,e,n,r){if(!t)return s;let o=new URL(s),i=(a,l)=>l?o.searchParams.set(a,l):o.searchParams.delete(a);return i(t.q,String(e.query??"").trim()),i(t.type,e.type),i(t.key,e.key),i(t.bpm,ce(e.bpmMin,e.bpmMax)),i(t.loop,e.loop),i(t.sort,n!==r?n:""),o.href}var Ot=Object.freeze({query:"",type:"",key:"",bpmMin:"",bpmMax:"",loop:""}),pe=120,de=200,he=250,b=class s{static instances=new Map;constructor(t,e={}){let n=typeof t=="string"?document.querySelector(t):t;if(!n)throw new Error(`${w} Container not found: ${t}`);this.container=n,this.options=Et(K,e,At(n)),this.options.waveformStyle=this.options.waveformStyle==="bars"?"bars":"mirror",this.strings={...g,...this.options.strings||{}},this.render={...L(this.options),strings:this.strings},this.sounds=[],this.rows=[],this.filter={...Ot},this.sortBy="default",this.limit=this._pageSize(),this.currentIndex=null,this.playing=!1,this.progress=0,this.loop=!!this.options.loop,this.engine=null,this.menus=null,this.destroyed=!1,this._ctl=new AbortController,this._originalHTML=null,this._pendingSeek=null,this._raf=0,s.instances.set(n,this),n.dataset.wsInitialized="true",this.ready=Promise.resolve().then(()=>this._init()).catch(r=>{console.error(`${w} Failed to initialise:`,r),this._emit("error",{error:r}),this.options.onError?.(r,this)})}async _init(){let t=this.container,e=t.querySelector("[data-ws-list]");if(e)this.sounds=kt(e);else{if(this._originalHTML=t.innerHTML,this.sounds=await this._loadSounds(),this.destroyed)return;t.innerHTML=R(this.sounds,{...this.render,idPrefix:this.options.idPrefix||t.id||void 0})}this.destroyed||(this._addedClasses=["waveform-sounds",`waveform-sounds--${this.render.player}`].filter(n=>!t.classList.contains(n)),t.classList.add(...this._addedClasses),this._cacheRefs(),this._bind(),this._observe(),this._resolveColors(),this._setLoop(this.loop),this._sorts=q(this.render.sorts,_(this.sounds)),this._sortSet||(this.sortBy=this._sorts[0]||"default"),this._readUrl(),this._syncControls(),this._apply({resort:this.sortBy!=="default"}),this._playerClass()&&this._ensureEngine(),this._emit("ready",{sounds:this.sounds.length}),this.options.onReady?.(this))}async _loadSounds(){if(this.options.sounds||!this.options.manifest)return S(this.options.sounds||[]);let t=await fetch(this.options.manifest);if(!t.ok)throw new Error(`${w} Manifest ${this.options.manifest}: HTTP ${t.status}`);return D(await t.json())}_cacheRefs(){let t=e=>this.container.querySelector(e);this.$={list:t("[data-ws-list]"),search:t("[data-ws-search]"),bpmMin:t("[data-ws-bpm-min]"),bpmMax:t("[data-ws-bpm-max]"),loop:t("[data-ws-loop]"),count:t("[data-ws-count]"),empty:t("[data-ws-empty]"),more:t("[data-ws-more]"),engine:t("[data-ws-engine]"),status:t("[data-ws-status]"),chips:[...this.container.querySelectorAll("[data-ws-type]")],loopFilter:[...this.container.querySelectorAll("[data-ws-loop-filter]")]},this.rows=Lt(this.$.list)}_bind(){let t={signal:this._ctl.signal},e=this.$,n=this.container;n.addEventListener("click",a=>this._onClick(a),t),n.addEventListener("pointerdown",a=>this._onPointerDown(a),t),n.addEventListener("keydown",a=>this._onKey(a),t);let r=0,o=0;e.search?.addEventListener("input",()=>{clearTimeout(r),r=setTimeout(()=>this.setFilter({query:e.search.value}),pe)},t),e.search?.addEventListener("keydown",a=>{a.key==="ArrowDown"&&(a.preventDefault(),this._focusRow(et(e.list)[0])),a.key==="Escape"&&e.search.value&&(a.preventDefault(),e.search.value="",this.setFilter({query:""}))},t);let i=()=>{clearTimeout(o),o=setTimeout(()=>this.setFilter({bpmMin:e.bpmMin?.value??"",bpmMax:e.bpmMax?.value??""}),de)};e.bpmMin?.addEventListener("input",i,t),e.bpmMax?.addEventListener("input",i,t),this.menus=new B(n,{signal:this._ctl.signal,onPick:(a,l)=>a==="sort"?this.setSort(l):this.setFilter({[a]:l})}),document.addEventListener("waveformplayer:play",a=>{let l=a.detail?.player;l&&l!==this.engine&&this.playing&&this.pause()},t)}_onClick(t){let e=t.target,n=e.closest("[data-ws-type]");if(n){this.setFilter({type:n.dataset.wsType});return}let r=e.closest("[data-ws-loop-filter]");if(r){this.setFilter({loop:r.dataset.wsLoopFilter});return}if(e.closest("[data-ws-more]")){this.showMore();return}if(e.closest("[data-ws-clear]")){this.clearFilters();return}if(e.closest("[data-ws-loop]")){this.setLoop(!this.loop);return}let o=e.closest(".ws-wave");if(o){this._lastPointer==="touch"&&this._seekAt(o,t.clientX);return}let i=e.closest("[data-ws-index]");!i||e.closest(".ws-download")||(this.toggle(Number(i.dataset.wsIndex)),this._focusRowQuietly(i))}_onPointerDown(t){this._lastPointer=t.pointerType;let e=t.target.closest(".ws-wave");!e||t.button!==0||t.pointerType==="touch"||(t.preventDefault(),this._seekAt(e,t.clientX))}_seekAt(t,e){let n=t.closest("[data-ws-index]");this._seekRow(Number(n.dataset.wsIndex),pt(e,t.getBoundingClientRect())),this._focusRowQuietly(n)}_onKey(t){if(t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey)return;if(t.key==="/"&&!dt(t.target)&&this.$.search){t.preventDefault(),this.$.search.focus();return}let e=t.target.closest?.("[data-ws-index]");if(!e)return;let n=Number(e.dataset.wsIndex),r=wt(this.progress,t.key);if(r!==null){if(n!==this.currentIndex||!this.engine)return;t.preventDefault(),this._seekRow(n,r);return}let o=et(this.$.list),i=yt(t.key,o.indexOf(e),o.length);if(i!==null){if(t.preventDefault(),i==="search"){this.$.search?.focus();return}this._focusRow(o[i]),this.options.arrowAudition&&this.playing&&this.play(Number(o[i].dataset.wsIndex))}}_focusRow(t){t?.querySelector(".ws-play")?.focus()}_focusRowQuietly(t){let e=t?.querySelector(".ws-play");e&&document.activeElement!==e&&e.focus({preventScroll:!0})}_observe(){if(this.render.player!=="inline"||typeof window>"u")return;if(this._drawn=new Set,"IntersectionObserver"in window?(this._io=new IntersectionObserver(n=>{for(let r of n){if(!r.isIntersecting)continue;let o=Number(r.target.dataset.wsIndex);this._drawn.add(o),this._drawRow(o)}},{rootMargin:"200px 0px"}),this.rows.forEach(n=>n&&this._io.observe(n))):this.rows.forEach((n,r)=>n&&this._drawn.add(r)),"ResizeObserver"in window){let n=0;this._ro=new ResizeObserver(([r])=>{let o=Math.round(r.contentRect.width);o!==n&&(n=o,this._redrawAll())}),this._ro.observe(this.$.list)}let t=()=>requestAnimationFrame(()=>{this._resolveColors(),this._redrawAll()});this._mo=new MutationObserver(t);let e={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]};this._mo.observe(document.documentElement,e),document.body&&this._mo.observe(document.body,e);try{window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",t,{signal:this._ctl.signal})}catch{}}_resolveColors(){(this._autoSurface||!getComputedStyle(this.container).getPropertyValue("--ws-surface").trim())&&(this._autoSurface=!0,this.container.style.removeProperty("--ws-surface"),this.container.style.setProperty("--ws-surface",Rt(this.container))),this.colors={wave:this.options.waveformColor||st(this.container,"var(--ws-wave-color)")||"rgba(128,128,128,.5)",progress:this.options.progressColor||st(this.container,"var(--ws-progress-color)")||"currentColor"}}_drawRow(t){if(this.render.player!=="inline"||t==null||!this._drawn?.has(t))return;let e=this.rows[t],n=e?.querySelector("canvas");if(!n||e.hidden)return;let r=Number(this.options.barGap);at(n,this.sounds[t].peaks,t===this.currentIndex?this.progress:0,{style:this.options.waveformStyle,color:this.colors?.wave||"rgba(128,128,128,.5)",progressColor:this.colors?.progress||"currentColor",barWidth:Math.max(1,Number(this.options.barWidth)||2),barGap:Number.isFinite(r)?Math.max(0,r):1})}_redrawAll(){this._drawn?.forEach(t=>this._drawRow(t))}_readUrl(){let t=nt(this.options.urlState);if(!t||typeof location>"u")return;let{filter:e,sort:n}=It(location.search,t,_(this.sounds),this._sorts);this.filter={...this.filter,...e},n&&(this.sortBy=n,this._sortSet=!0)}_queueUrl(){let t=nt(this.options.urlState);!t||typeof location>"u"||(clearTimeout(this._urlTimer),this._urlTimer=setTimeout(()=>{if(this.destroyed)return;let e=$t(location.href,t,this.filter,this.sortBy,this._sorts?.[0]||"default");e!==location.href&&history.replaceState(history.state,"",e)},he))}get visible(){return k(this.sounds.filter(t=>z(t,this.filter)),this.sortBy)}setFilter(t={}){this.filter={...this.filter,...t},this.limit=this._pageSize(),this._syncControls(),this._apply({resort:!1})}clearFilters(){this.setFilter(Ot)}setSort(t){this._sortSet=!0,this.sortBy=T.includes(t)?t:"default",this.menus?.setValue("sort",this.sortBy),this._apply({resort:!0})}showMore(){this.limit!==1/0&&(this.limit+=this.render.pageSize,this._apply({resort:!1}))}_pageSize(){return this.render.pageSize>0?this.render.pageSize:1/0}_syncControls(){let t=this.$,e=this.filter;t&&(t.search&&t.search.value!==e.query&&(t.search.value=e.query),this.menus?.setValue("type",e.type||""),this.menus?.setValue("key",e.key||""),this.menus?.setValue("sort",this.sortBy),t.bpmMin&&t.bpmMin.value!==String(e.bpmMin)&&(t.bpmMin.value=e.bpmMin),t.bpmMax&&t.bpmMax.value!==String(e.bpmMax)&&(t.bpmMax.value=e.bpmMax),t.chips.forEach(n=>n.setAttribute("aria-pressed",String(n.dataset.wsType===(e.type||"")))),t.loopFilter.forEach(n=>n.setAttribute("aria-pressed",String(n.dataset.wsLoopFilter===(e.loop||"")))))}_apply({resort:t}){let e=this.$;if(!e)return;(t||this.sortBy!==this._lastSort)&&(Ct(e.list,k(this.sounds,this.sortBy).map(i=>this.rows[this.sounds.indexOf(i)])),this._lastSort=this.sortBy);let n=this.visible,{visible:r,remaining:o}=gt(n,this.limit);this.sounds.forEach((i,a)=>{this.rows[a]&&(this.rows[a].hidden=!r.has(i))}),e.more&&(e.more.hidden=o<=0,e.more.textContent=f(this.strings.showMore,{count:Math.min(o,this.render.pageSize||o)})),e.empty&&(e.empty.hidden=n.length>0),e.count&&(e.count.textContent=U(n.length,this.sounds.length,this.strings)),this._queueUrl(),this._emit("filter",{visible:n.length,total:this.sounds.length,filter:{...this.filter},sort:this.sortBy}),this.options.onFilter?.(n,this)}_indexOf(t){if(t==null)return this.currentIndex??(this.visible[0]?this.sounds.indexOf(this.visible[0]):null);if(typeof t=="number")return this.sounds[t]?t:null;let e=typeof t=="object"?this.sounds.indexOf(t):this.sounds.findIndex(n=>n.id===String(t));return e>=0?e:null}_playerClass(){return this.options.playerClass||(typeof window<"u"?window.WaveformPlayer:null)||null}_engineMount(){let t=this.$.engine,e=t.querySelector(":scope > [data-ws-engine-mount]");return e||(e=document.createElement("div"),e.setAttribute("data-ws-engine-mount",""),t.appendChild(e)),e}_ensureEngine(){if(this.engine)return this.engine;let t=this._playerClass();return t?(this.engine=new t(this._engineMount(),lt(this.options.playerOptions,this.render.player,{onLoad:()=>this._onEngineLoad(),onPlay:()=>this._setPlaying(!0),onPause:()=>this._setPlaying(!1),onEnd:()=>this._onEnd(),onTimeUpdate:(e,n)=>this._onTime(e,n),onError:e=>this._onEngineError(e)})),this.engine):(console.error(`${w} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`),null)}play(t,e={}){if(!this.$){this.ready.then(()=>{this.destroyed||this.play(t,e)});return}let n=this._indexOf(t);if(n==null)return;let r=this._ensureEngine();if(!r)return;if(n===this.currentIndex&&r.audio?.src){e.at!=null&&this._seekRow(n,e.at),this.playing||r.play();return}let o=this.currentIndex;this.currentIndex=n,this.progress=0,this._pendingSeek=e.at??null,o!=null&&this._paintRow(o),this._paintRow(n);let i=this.sounds[n];r.loadTrack(i.url,i.title,i.type||null,{waveform:ut(i,this.render.player),autoplay:!0})}pause(){this.engine&&this.playing&&this.engine.pause()}toggle(t){let e=this._indexOf(t);e!=null&&(e===this.currentIndex&&this.playing?this.pause():this.play(e))}next(){this._step(1)}previous(){this._step(-1)}_step(t){let e=this.visible,n=this.currentIndex==null?-1:e.indexOf(this.sounds[this.currentIndex]),r=e[n+t];if(!r)return!1;let o=bt(this.limit,n+t);return o!==this.limit&&(this.limit=o,this._apply({resort:!1})),this.play(this.sounds.indexOf(r)),!0}setLoop(t){this.loop=!!t,this._setLoop(this.loop)}_setLoop(t){this.$?.loop?.setAttribute("aria-pressed",String(t)),this.engine?.audio&&(this.engine.audio.loop=this._repeats())}_repeats(){return this.loop?!this.sounds.some(e=>e.loop)||!!this.sounds[this.currentIndex]?.loop:!1}_seekRow(t,e){if(t!==this.currentIndex||!this.engine){this.play(t,{at:e});return}let n=this.engine.audio?.duration;if(!Number.isFinite(n)||n<=0){this._pendingSeek=e;return}this.engine.seekTo(e*n),this.progress=e,this._paintRow(t),this.playing||this.engine.play()}_onEngineLoad(){this.engine?.audio&&(this.engine.audio.loop=this._repeats());let t=this.sounds[this.currentIndex];t&&!t.peaks&&this.engine?.waveformData?.length&&(t.peaks=W(this.engine.waveformData,96),this._drawRow(this.currentIndex));let e=this.engine?.audio?.duration;this._pendingSeek!=null&&Number.isFinite(e)&&e>0&&(this.engine.seekTo(this._pendingSeek*e),this.progress=this._pendingSeek,this._pendingSeek=null)}_onTime(t,e){if(!(this.currentIndex==null||!e)){if(this._pendingSeek!=null){let n=this._pendingSeek;this._pendingSeek=null,this.engine.seekTo(n*e);return}this.progress=Math.min(Math.max(t/e,0),1),!this._raf&&(this._raf=requestAnimationFrame(()=>{this._raf=0,this._drawRow(this.currentIndex),this.rows[this.currentIndex]?.querySelector(".ws-wave")?.setAttribute("aria-valuenow",String(Math.round(this.progress*100)))}))}}_onEnd(){let t=this.sounds[this.currentIndex];this._emit("end",{sound:t,index:this.currentIndex}),this.options.onEnd?.(t,this),!(this.options.autoAdvance&&this._step(1))&&(this.progress=0,this._setPlaying(!1))}_onEngineError(t){this.rows[this.currentIndex]?.classList.add("is-error"),this._emit("error",{error:t,sound:this.sounds[this.currentIndex],index:this.currentIndex}),this.options.onError?.(t,this)}_setPlaying(t){let e=this.playing!==t;this.playing=t;let n=this.currentIndex;if(n==null||(this._paintRow(n),!e))return;let r=this.sounds[n];t&&this.$.status&&(this.$.status.textContent=f(this.strings.nowPlaying,{title:r.title})),this._emit(t?"play":"pause",{sound:r,index:n}),(t?this.options.onPlay:this.options.onPause)?.(r,this)}_paintRow(t){let e=this.rows[t];if(!e)return;let n=t===this.currentIndex,r=n&&this.playing;e.classList.toggle("is-current",n),e.classList.toggle("is-playing",r);let o=e.querySelector(".ws-play");o&&(o.setAttribute("aria-pressed",String(r)),o.setAttribute("aria-label",f(r?this.strings.pause:this.strings.play,{title:this.sounds[t].title})));let i=e.querySelector(".ws-wave");i&&(i.tabIndex=n?0:-1,n||i.setAttribute("aria-valuenow","0")),this._drawRow(t)}_emit(t,e={}){ht(this.container,t,{...e,instance:this})}get current(){return this.currentIndex==null?null:this.sounds[this.currentIndex]}destroy(){if(!this.destroyed){this.destroyed=!0,this._ctl.abort(),this._io?.disconnect(),this._ro?.disconnect(),this._mo?.disconnect(),this._raf&&cancelAnimationFrame(this._raf),clearTimeout(this._urlTimer);try{this.engine?.destroy()}catch{}this.engine=null,this.$?.engine?.querySelector(":scope > [data-ws-engine-mount]")?.remove(),this._originalHTML!=null&&(this.container.innerHTML=this._originalHTML),this._addedClasses?.length&&this.container.classList.remove(...this._addedClasses),this._autoSurface&&this.container.style.removeProperty("--ws-surface"),delete this.container.dataset.wsInitialized,s.instances.delete(this.container)}}static init(t=document){if(typeof document>"u")return[];let e=t||document,n=[...e.matches?.("[data-waveform-sounds]")?[e]:[],...e.querySelectorAll("[data-waveform-sounds]")],r=[];for(let o of n)if(!(o.dataset.wsInitialized==="true"||s.instances.has(o)))try{r.push(new s(o))}catch(i){console.error(`${w} Failed to initialise:`,i,o)}return r}static getInstance(t){let e=typeof t=="string"?document.querySelector(t):t;return e&&s.instances.get(e)||null}static prune(){for(let[t,e]of s.instances)t.isConnected||e.destroy()}};b.utils={encodePeaks:F,decodePeaks:j,normalizeKey:E,normalizeSounds:S,parseManifest:D,facets:_,matches:z,sortSounds:k,formatDuration:N,renderSounds:R};b.DEFAULT_OPTIONS=K;b.DEFAULT_STRINGS=g;typeof window<"u"&&(window.WaveformSounds=b);var H=b;var ds=H;typeof document<"u"&&document.documentElement?.dataset?.waveformAutoinit!=="false"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>H.init(),{once:!0}):H.init());})();
1
+ (()=>{var qt=Object.freeze({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function P(s){return s==null?"":String(s).replace(/[&<>"']/g,t=>qt[t])}var Ut=/[^\p{L}\p{N}]+/u,Kt=/\p{Mn}+/gu;function S(s){return!s||typeof s!="string"?"":s.toLowerCase().normalize("NFD").replace(Kt,"")}function $(s){return S(s).split(Ut).filter(t=>t!=="")}function ut(s,t){let e=Array.from(s??""),n=Array.from(t??""),r=[],o=Array.from({length:n.length+1},(i,a)=>a);for(let i=1;i<=e.length;i++){let a=[i];for(let l=1;l<=n.length;l++){let d=e[i-1]===n[l-1]?0:1;a[l]=Math.min(o[l]+1,a[l-1]+1,o[l-1]+d),i>1&&l>1&&e[i-1]===n[l-2]&&e[i-2]===n[l-1]&&(a[l]=Math.min(a[l],r[l-2]+1))}r=o,o=a}return o[n.length]}function ct(s,t,e={}){let n=e.fuzzyFrom??4,r=S(s),o=$(s);return $(t).every(i=>{if(r.includes(i))return!0;let a=Array.from(i).length;return a<n?!1:o.some(l=>ut(i,l)<=1||ut(i,Array.from(l).slice(0,a).join(""))<=1)})}function O(s){if(!Array.isArray(s))return"";let t="";for(let e of s){let n=Math.round(Math.min(Math.max(Number(e)||0,0),1)*255);t+=(n<16?"0":"")+n.toString(16)}return t}function W(s,t=1){if(s==null||s==="")return null;if(typeof s=="string"){if(!/^[0-9a-f]+$/i.test(s)||s.length%2)return null;let r=new Array(s.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(s.substr(o*2,2),16)/255;return r}if(!Array.isArray(s))return null;let e=Number(t)>0?Number(t):1,n=s.map(r=>Math.min(Math.max((Number(r)||0)/e,0),1));return n.length?n:null}function L(s){if(s==null)return"";let t=String(s).trim(),e=t.match(/^([A-Ga-g])[\s_-]*([#♯b♭]?)[\s_-]*(m|min|minor|maj|major)?$/i);if(!e)return t;let n=e[1].toUpperCase(),r=e[2]==="\u266F"?"#":e[2]==="\u266D"?"b":e[2],o=e[3]&&/^m(in(or)?)?$/i.test(e[3])&&e[3]!=="M";return n+r+(o?"m":"")}var Ht={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11};function N(s){if(!s)return 1/0;let t=s.endsWith("m"),e=t?s.slice(0,-1):s,n=Ht[e];return n===void 0?1e3:n*2+(t?1:0)}function D(s){if(s==null||s==="")return"";let t=Number(s);if(!Number.isFinite(t)||t<0)return"";if(t>0&&t<.95)return`${Math.max(.1,Math.round(t*10)/10).toFixed(1)}s`;let e=t<1?Math.ceil(t):Math.floor(t);return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function jt(s){if(s==null||s==="")return null;if(typeof s=="number")return Number.isFinite(s)&&s>=0?s:null;let t=String(s).trim();if(/^\d+(\.\d+)?$/.test(t))return Number(t);let e=t.split(":").map(Number);return e.length<2||e.some(n=>!Number.isFinite(n))?null:e.reduce((n,r)=>n*60+r,0)}function Gt(s){let e=(String(s||"").split(/[?#]/)[0].split("/").pop()||"").replace(/\.[a-z0-9]+$/i,"");try{e=decodeURIComponent(e)}catch{}return e.replace(/[_]+/g," ").replace(/\s+/g," ").trim()}function V(s,t,e=1){if(!s||typeof s!="object"||!s.url)return null;let n=Number(s.bpm),r=Array.isArray(s.tags)?s.tags.map(o=>String(o).trim()).filter(Boolean):typeof s.tags=="string"?s.tags.split(",").map(o=>o.trim()).filter(Boolean):[];return{id:s.id!=null&&s.id!==""?String(s.id):`sound-${t+1}`,url:String(s.url),title:s.title?String(s.title):Gt(s.url),type:s.type?String(s.type):"",bpm:Number.isFinite(n)&&n>0?Math.round(n*100)/100:null,key:L(s.key),duration:jt(s.duration),tags:r,peaks:W(s.peaks,e),waveform:s.waveform?String(s.waveform):null,download:s.download?String(s.download):null,loop:Wt(s.loop)}}var pt=["loop","one-shot"];function Wt(s){return s===!0||s===1||s==="true"||s==="1"}function B(s){let t=Array.isArray(s)?s:Array.isArray(s?.sounds)?s.sounds:[],e=Array.isArray(s)?1:Number(s?.peakScale)||1;return _(t,e)}function _(s,t=1){let e=new Set,n=[];return(Array.isArray(s)?s:[]).forEach((r,o)=>{let i=V(r,o,t);if(!i)return;let a=i.id,l=2;for(;e.has(a);)a=`${i.id}-${l++}`;i.id=a,e.add(a),n.push(i)}),n}function w(s){let t=new Map,e=new Set,n=1/0,r=-1/0,o=!1,i=0;for(let a of s)a.type&&t.set(a.type,(t.get(a.type)||0)+1),a.key&&e.add(a.key),a.bpm!=null&&(n=Math.min(n,a.bpm),r=Math.max(r,a.bpm)),a.duration!=null&&(o=!0),a.loop&&i++;return{types:[...t].map(([a,l])=>({name:a,count:l})),keys:[...e].sort((a,l)=>N(a)-N(l)||a.localeCompare(l)),bpm:n===1/0?null:{min:n,max:r},hasDuration:o,loops:i,oneShots:s.length-i}}function z(s,t={}){if(t.type&&s.type!==t.type||t.key&&s.key!==L(t.key)||t.loop==="loop"&&!s.loop||t.loop==="one-shot"&&s.loop)return!1;let e=Number(t.bpmMin),n=Number(t.bpmMax);if((t.bpmMin!=null&&t.bpmMin!==""&&Number.isFinite(e)||t.bpmMax!=null&&t.bpmMax!==""&&Number.isFinite(n))&&(s.bpm==null||t.bpmMin!=null&&t.bpmMin!==""&&s.bpm<e||t.bpmMax!=null&&t.bpmMax!==""&&s.bpm>n))return!1;let r=$(t.query||"");if(r.length){let o=[s.title,s.type,s.key,...s.tags||[]].join(" "),i=S(o),a=r.filter(l=>!(/^\d+$/.test(l)&&!i.includes(l)&&s.bpm!=null&&Math.round(s.bpm)===Number(l)));if(a.length&&!ct(o,a.join(" ")))return!1}return!0}var A=["default","title","bpm","key","duration"],Vt={default:()=>!0,title:()=>!0,bpm:s=>s.bpm!==null,key:s=>s.keys.length>0,duration:s=>s.hasDuration};function q(s,t){return s.filter(e=>Vt[e]?.(t))}function T(s,t="default"){let e=s.map((o,i)=>({s:o,i})),n=o=>o??1/0,r={title:(o,i)=>o.s.title.localeCompare(i.s.title,void 0,{numeric:!0,sensitivity:"base"}),bpm:(o,i)=>n(o.s.bpm)-n(i.s.bpm),key:(o,i)=>N(o.s.key)-N(i.s.key),duration:(o,i)=>n(o.s.duration)-n(i.s.duration)}[t];return r&&e.sort((o,i)=>r(o,i)||o.i-i.i),e.map(o=>o.s)}function Yt(s){let t=s.getBoundingClientRect();if(!t.width||!t.height)return null;let e=Math.min(window.devicePixelRatio||1,3),n=Math.round(t.width*e),r=Math.round(t.height*e);return s.width!==n&&(s.width=n),s.height!==r&&(s.height=r),{width:t.width,height:t.height,dpr:e}}function Y(s,t){if(!s?.length||t<=0)return[];if(s.length===t)return s;let e=new Array(t),n=s.length/t;for(let r=0;r<t;r++){let o=Math.floor(r*n),i=Math.max(o+1,Math.floor((r+1)*n)),a=0;for(let l=o;l<i&&l<s.length;l++)s[l]>a&&(a=s[l]);e[r]=a}return e}function Jt(s,t,e,n){let r=n.barWidth+n.barGap,o=Y(s,Math.max(1,Math.floor((t+n.barGap)/r))),i=o.reduce((l,d)=>d>l?d:l,0),a=i>0?1/i:1;return o.map((l,d)=>{let p=Math.max(l*a,.04);if(n.style==="bars"){let I=Math.max(1,p*e);return{x:d*r,y:e-I,w:n.barWidth,h:I}}let f=Math.max(1,p*(e-2));return{x:d*r,y:e/2-f/2,w:n.barWidth,h:f}})}function dt(s,t,e,n){let r=Yt(s),o=r&&s.getContext&&s.getContext("2d");if(!o)return;let{width:i,height:a,dpr:l}=r;if(o.setTransform(l,0,0,l,0,0),o.clearRect(0,0,i,a),!t?.length){o.fillStyle=n.color,o.fillRect(0,Math.floor(a/2),i,1);return}let d=new Path2D;for(let f of Jt(t,i,a,n))d.rect(f.x,f.y,f.w,f.h);o.fillStyle=n.color,o.fill(d);let p=Math.min(Math.max(e,0),1)*i;p>0&&(o.save(),o.beginPath(),o.rect(0,0,p,a),o.clip(),o.fillStyle=n.progressColor,o.fill(d),o.restore())}var Qt=["onLoad","onPlay","onPause","onEnd","onTimeUpdate","onError"];function ht(s,t,e){let n=s||{},r=t==="strip",o={height:r?48:32,waveformStyle:r?"mirror":"bars",preload:"metadata",singlePlay:!0,...n,audioMode:"self"};for(let i of Qt)o[i]=(...a)=>{e[i]?.(...a),typeof n[i]=="function"&&n[i](...a)};return o}function J(s,t){return t==="strip"&&s.waveform||s.peaks||null}function Xt(s,t){let e=S(String(t??"")).trim();return!e||S(String(s??"")).includes(e)}function ft(s,t,e){return Math.max(0,Math.min(e-1,s+t))}function v(s){return{button:s.querySelector("[data-ws-menu-btn]"),pop:s.querySelector("[data-ws-menu-pop]"),search:s.querySelector("[data-ws-menu-search]"),list:s.querySelector("[data-ws-menu-list]"),none:s.querySelector("[data-ws-menu-none]"),value:s.querySelector("[data-ws-menu-value]")}}var Q=s=>s.search||s.list||s.pop.querySelector("input")||s.pop.querySelector("button"),X=(s,t=!1)=>[...s.list.querySelectorAll('[role="option"]')].filter(e=>!t||!e.hidden),U=class{constructor(t,{onPick:e,signal:n}){this.container=t,this.onPick=e,this.menus=Object.fromEntries([...t.querySelectorAll("[data-ws-menu]")].map(r=>[r.dataset.wsMenu,r])),this.openMenu=null,this._bind(n)}_bind(t){let e={signal:t};for(let[n,r]of Object.entries(this.menus)){let o=v(r);if(o.button.addEventListener("click",()=>this.openMenu===r?this.close(!0):this.open(r),e),o.button.addEventListener("keydown",i=>{(i.key==="ArrowDown"||i.key==="ArrowUp")&&(i.preventDefault(),this.open(r))},e),!o.list){o.pop.addEventListener("keydown",i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),this.close(!0))},e);continue}o.list.addEventListener("click",i=>{let a=i.target.closest('[role="option"]');a&&this._pick(n,a.dataset.value)},e),o.list.addEventListener("mousedown",i=>i.preventDefault(),e),o.search?.addEventListener("input",()=>this._filter(r,o.search.value),e),Q(o).addEventListener("keydown",i=>this._onKey(i,n,r),e)}document.addEventListener("pointerdown",n=>{this.openMenu&&!this.openMenu.contains(n.target)&&this.close(!1)},e),this.container.addEventListener("focusout",n=>{this.openMenu&&!this.openMenu.contains(n.relatedTarget)&&this.close(!1)},e)}open(t){this.openMenu&&this.openMenu!==t&&this.close(!1);let e=v(t);e.button.setAttribute("aria-expanded","true"),e.pop.hidden=!1,this.openMenu=t,e.search&&(e.search.value="",this._filter(t,"")),t.classList.remove("ws-menu--end"),e.pop.getBoundingClientRect().right>this.container.getBoundingClientRect().right+1&&t.classList.add("ws-menu--end"),e.list&&this._activate(t,e.list.querySelector('[role="option"][aria-selected="true"]')),Q(e)?.focus()}close(t){let e=this.openMenu;if(!e)return;this.openMenu=null;let n=v(e);n.pop.hidden=!0,n.button.setAttribute("aria-expanded","false"),t&&n.button.focus()}setValue(t,e){let n=this.menus[t];if(!n)return;let r=v(n);if(!r.list)return;let o=null;for(let i of X(r)){let a=i.dataset.value===String(e??"");i.setAttribute("aria-selected",String(a)),a&&(o=i.querySelector(".ws-menu-text")?.textContent??"")}o!==null&&(r.value.textContent=o)}_filter(t,e){let n=v(t),r=null;for(let o of X(n))o.hidden=!Xt(o.textContent,e),o.hidden||(r??=o);n.none.hidden=r!==null,this._activate(t,r)}_activate(t,e){let n=v(t);for(let o of n.list.querySelectorAll(".is-active"))o.classList.remove("is-active");let r=Q(n);if(!e||e.hidden){r.removeAttribute("aria-activedescendant");return}e.classList.add("is-active"),r.setAttribute("aria-activedescendant",e.id),e.scrollIntoView?.({block:"nearest"})}_onKey(t,e,n){let r=v(n),o=X(r,!0),i=o.indexOf(r.list.querySelector(".is-active")),a=d=>{t.preventDefault(),this._activate(n,o[d])},l=t.target.matches("input");switch(t.key){case"ArrowDown":return a(ft(i,1,o.length));case"ArrowUp":return a(ft(i,-1,o.length));case"Home":return l?void 0:a(0);case"End":return l?void 0:a(o.length-1);case"Enter":t.preventDefault(),i>=0&&this._pick(e,o[i].dataset.value);return;case"Escape":return t.preventDefault(),t.stopPropagation(),this.close(!0);case"Tab":return this.close(!1);default:return}}_pick(t,e){this.close(!0),this.onPick(t,e)}};var b="[WaveformSounds]";function Z(s,t=0,e=1){return Math.min(Math.max(s,t),e)}function mt(s,t){return t&&t.width?Z((s-t.left)/t.width):0}function yt(s){return!!s&&(s.isContentEditable||/^(INPUT|SELECT|TEXTAREA)$/.test(s.tagName))}function wt(s,t,e){let n=new CustomEvent(`waveformsounds:${t}`,{bubbles:!0,detail:e});return s.dispatchEvent(n),n}function gt(s){let t=5381;for(let e of s)t=t*33+e.codePointAt(0)>>>0;return t}var bt=.1;function xt(s,t,e){if(!e)return null;switch(s){case"ArrowDown":return t+1<e?t+1:null;case"ArrowUp":return t>0?t-1:"search";case"Home":return 0;case"End":return e-1;default:return null}}function St(s,t){return t!=="ArrowRight"&&t!=="ArrowLeft"?null:Z(s+(t==="ArrowRight"?bt:-bt),0,.999)}function _t(s,t){let e=new Set(s.slice(0,t));return{visible:e,remaining:s.length-e.size}}function vt(s,t){return t>=s?t+1:s}function Mt(s,t,e){let n=Math.min(s,t),r=Math.max(s,t);return{bpmMin:n>e.min?String(n):"",bpmMax:r<e.max?String(r):""}}function k(s,t){let e=(o,i)=>{let a=Number(o);return o===""||o==null||!Number.isFinite(a)?i:Math.min(Math.max(a,t.min),t.max)},n=e(s.bpmMin,t.min),r=e(s.bpmMax,t.max);return n<=r?{lo:n,hi:r}:{lo:r,hi:n}}function tt(s,t){let e=t.max-t.min;return e>0?Math.min(Math.max((s-t.min)/e,0),1):0}function Et(s){return s.bpmMin!=null&&s.bpmMin!==""||s.bpmMax!=null&&s.bpmMax!==""}var g={search:"Search sounds",searchPlaceholder:"Search sounds\u2026",all:"All",types:"Type",key:"Key",anyKey:"Any key",allTypes:"All types",findType:"Find a type\u2026",findKey:"Find a key\u2026",noMatches:"No matches",bpm:"BPM",bpmMin:"Min BPM",bpmMax:"Max BPM",anyBpm:"Any BPM",bpmRange:"{min}\u2013{max} BPM",sort:"Sort",sortBy:"Sort by",sortDefault:"Default",sortTitle:"Name",sortBpm:"BPM",sortKey:"Key",sortDuration:"Length",loop:"Loop",loopFilter:"Loops or one-shots",loops:"Loops",oneShots:"One-shots",isLoop:"Loop",play:"Play {title}",pause:"Pause {title}",seek:"Seek {title}",download:"Download {title}",count:"{count} sounds",countOne:"1 sound",countFiltered:"{count} of {total} sounds",showMore:"Show {count} more",empty:"No sounds match.",clear:"Clear filters",nowPlaying:"Playing {title}"},Lt={default:"sortDefault",title:"sortTitle",bpm:"sortBpm",key:"sortKey",duration:"sortDuration"};function h(s,t={}){return String(s).replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e)}function K(s,t,e=g){if(!Et(s))return e.anyBpm;let{lo:n,hi:r}=k(s,t);return h(e.bpmRange,{min:n,max:r})}function H(s,t,e=g){return s!==t?h(e.countFiltered,{count:s,total:t}):t===1?e.countOne:h(e.count,{count:t})}var Tt=["type","key","bpm","loop"],kt=["type","bpm","key","duration"],m={player:"inline",search:!0,filters:[...Tt],sorts:[...A],loopToggle:!0,showCount:!0,menuSearch:8,pageSize:50,columns:[...kt],maxTypeChips:10};function At(s){let t={};for(let e in s??{})s[e]!==void 0&&(t[e]=s[e]);return t}function et(s,t,e){return Array.isArray(s)?s.filter(n=>t.includes(n)):e}function st(s,t){let e=Number(s);return Number.isFinite(e)&&e>=0?Math.floor(e):t}function R(s={}){let t={...m,...At(s)};return{...t,player:t.player==="strip"?"strip":"inline",filters:et(t.filters,Tt,m.filters),sorts:et(t.sorts,A,m.sorts),columns:et(t.columns,kt,m.columns),menuSearch:st(t.menuSearch,m.menuSearch),maxTypeChips:st(t.maxTypeChips,m.maxTypeChips),pageSize:st(t.pageSize,m.pageSize),strings:{...g,...At(s.strings)}}}var j={...m,sounds:null,manifest:null,waveformStyle:"mirror",waveformColor:null,progressColor:null,barWidth:2,barGap:1,loop:null,autoAdvance:!1,arrowAudition:!0,idPrefix:null,urlState:!1,playerOptions:null,playerClass:null,strings:null,onReady:null,onPlay:null,onPause:null,onEnd:null,onFilter:null,onError:null};function M(s){if(s===""||s==="true")return!0;if(s==="false")return!1}function nt(s){if(s!=null)return s.split(",").map(t=>t.trim()).filter(Boolean)}function C(s){return s===void 0||s===""?void 0:Number(s)}function Zt(s){if(s===void 0)return;let t=M(s);return t===void 0?s:t}function Rt(s,t){if(s)try{return JSON.parse(s)}catch{console.warn(`${b} Ignoring invalid JSON in data-${t}`);return}}function Ct(s){let t=s.dataset||{},e={player:t.player||void 0,manifest:t.manifest||void 0,search:M(t.search),filters:nt(t.filters),sorts:nt(t.sorts),showCount:M(t.showCount),menuSearch:C(t.menuSearch),idPrefix:t.idPrefix||void 0,urlState:Zt(t.urlState),loopToggle:M(t.loopToggle),pageSize:C(t.pageSize),maxTypeChips:C(t.maxTypeChips),columns:nt(t.columns),waveformStyle:t.waveformStyle||void 0,waveformColor:t.waveformColor||void 0,progressColor:t.progressColor||void 0,barWidth:C(t.barWidth),barGap:C(t.barGap),loop:M(t.loop),autoAdvance:M(t.autoAdvance),arrowAudition:M(t.arrowAudition),strings:Rt(t.strings,"strings"),playerOptions:Rt(t.playerOptions,"player-options")};for(let n of Object.keys(e))e[n]===void 0&&delete e[n];return e}function Ft(...s){let t={};for(let e of s)if(e)for(let n in e)e[n]!==null&&e[n]!==void 0&&(t[n]=e[n]);return t}var te=new Set(["input","br","img"]);function c(s){return P(s??"")}function ee(s={}){let t="";for(let[e,n]of Object.entries(s))n===!0?t+=` ${e}`:n!==!1&&n!=null&&(t+=` ${e}="${P(n)}"`);return t}function u(s,t={},...e){let n=`<${s}${ee(t)}>`;return te.has(s)?n:n+e.flat(1/0).filter(r=>r!=null&&r!==!1&&r!=="").join("")+`</${s}>`}function E(s,t=""){return`<svg class="${t?`ws-icon ${t}`:"ws-icon"}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${s}"/></svg>`}var y={play:E("M8 5.5v13l11-6.5z","ws-icon-play"),pause:E("M7 5h3.5v14H7zM13.5 5H17v14h-3.5z","ws-icon-pause"),search:E("M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z"),chevron:E("M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z","ws-menu-chevron"),check:E("M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z","ws-menu-check"),download:E("M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z"),loop:E("M17 4l3 3-3 3V8H8a3 3 0 0 0-3 3v1H3v-1a5 5 0 0 1 5-5h9V4zM7 20l-3-3 3-3v2h9a3 3 0 0 0 3-3v-1h2v1a5 5 0 0 1-5 5H7v2z")};function se(s){let t=[s.length,...s.map(e=>e.url)].join("|");return`ws${gt(t).toString(36)}`}function ne(s,t){let e=t.filters.includes("type")&&s.types.length>1,n=q(t.sorts,s);return{types:e?s.types.length>t.maxTypeChips?"menu":"chips":null,key:t.filters.includes("key")&&s.keys.length>1,bpm:t.filters.includes("bpm")&&s.bpm!==null&&s.bpm.max>s.bpm.min,loops:t.filters.includes("loop")&&s.loops>0&&s.oneShots>0,sorts:n.length>1?n:[],search:!!t.search,loop:!!t.loopToggle,count:!!t.showCount}}function rt(s,t){return s==null?t.loops>0:!!s}function re(s){return u("label",{class:"ws-search"},y.search,u("span",{class:"ws-sr"},c(s.search)),u("input",{type:"search",class:"ws-search-input","data-ws-search":!0,placeholder:s.searchPlaceholder,autocomplete:"off",spellcheck:"false"}))}function oe(s,t){let e=`${t.id}-${s}-list`,n=t.options.find(l=>l.value===t.value)??t.options[0],r=t.placeholder&&t.options.length>t.searchFrom,o=u("button",{type:"button",class:"ws-menu-btn","data-ws-menu-btn":!0,"aria-haspopup":"listbox","aria-expanded":"false","aria-controls":e},t.prefix?u("span",{class:"ws-menu-prefix"},c(t.prefix)):u("span",{class:"ws-sr"},c(`${t.label}: `)),u("span",{class:"ws-menu-value","data-ws-menu-value":!0},c(n.label)),y.chevron),i=r&&u("input",{type:"search",class:"ws-menu-search","data-ws-menu-search":!0,role:"combobox","aria-expanded":"true","aria-controls":e,"aria-autocomplete":"list","aria-label":t.placeholder,placeholder:t.placeholder,autocomplete:"off",spellcheck:"false"}),a=t.options.map((l,d)=>u("li",{role:"option",id:`${t.id}-${s}-${d}`,class:"ws-menu-option","data-value":l.value,"aria-selected":String(l===n)},y.check,u("span",{class:"ws-menu-text"},c(l.label)),l.count!=null&&u("span",{class:"ws-menu-count"},c(l.count))));return u("div",{class:"ws-menu","data-ws-menu":s},o,u("div",{class:"ws-menu-pop","data-ws-menu-pop":!0,hidden:!0},i,u("ul",{class:"ws-menu-list",role:"listbox",id:e,"aria-label":t.label,tabindex:"-1","data-ws-menu-list":!0},a),u("p",{class:"ws-menu-none","data-ws-menu-none":!0,hidden:!0},c(t.noMatches))))}function ie({id:s,s:t,range:e}){let n=`${s}-bpm-pop`,r=(o,i,a)=>u("input",{type:"range",class:"ws-range-input",[o]:!0,"aria-label":i,min:e.min,max:e.max,step:"1",value:a});return u("div",{class:"ws-menu ws-menu--bpm","data-ws-menu":"bpm"},u("button",{type:"button",class:"ws-menu-btn","data-ws-menu-btn":!0,"aria-haspopup":"dialog","aria-expanded":"false","aria-controls":n},u("span",{class:"ws-sr"},c(`${t.bpm}: `)),u("span",{class:"ws-menu-value","data-ws-menu-value":!0},c(K({},e,t))),y.chevron),u("div",{class:"ws-menu-pop ws-bpm-pop",id:n,role:"dialog","aria-label":t.bpm,"data-ws-menu-pop":!0,hidden:!0},u("div",{class:"ws-bpm-head"},u("span",{class:"ws-bpm-readout","data-ws-bpm-readout":!0,"aria-live":"polite"},c(h(t.bpmRange,e))),u("button",{type:"button",class:"ws-bpm-clear","data-ws-bpm-clear":!0},c(t.anyBpm))),u("div",{class:"ws-range","data-ws-bpm-range":!0},r("data-ws-bpm-min",t.bpmMin,e.min),r("data-ws-bpm-max",t.bpmMax,e.max)),u("div",{class:"ws-range-ends","aria-hidden":"true"},u("span",{},c(e.min)),u("span",{},c(e.max)))))}function ae(s){let t=(e,n)=>u("button",{type:"button",class:"ws-seg-btn","data-ws-loop-filter":e,"aria-pressed":String(e==="")},u("span",{},c(n)));return u("div",{class:"ws-seg",role:"group","aria-label":s.loopFilter},t("",s.all),t("loop",s.loops),t("one-shot",s.oneShots))}function le(s,t){return u("button",{type:"button",class:"ws-loop","data-ws-loop":!0,"aria-pressed":String(t)},y.loop,u("span",{},c(s.loop)))}function It(s,t,e,n){return u("button",{type:"button",class:"ws-chip","data-ws-type":s,"aria-pressed":String(n)},u("span",{class:"ws-chip-label"},c(t))," ",u("span",{class:"ws-chip-count"},c(e)))}function ue(s,{o:t,s:e,f:n,total:r,id:o}){let i=(p,f)=>oe(p,{id:o,searchFrom:t.menuSearch,noMatches:e.noMatches,...f}),a=[s.types==="menu"&&i("type",{label:e.types,value:"",placeholder:e.findType,options:[{value:"",label:e.allTypes,count:r},...n.types.map(p=>({value:p.name,label:p.name,count:p.count}))]}),s.key&&i("key",{label:e.key,value:"",placeholder:e.findKey,options:[{value:"",label:e.anyKey},...n.keys.map(p=>({value:p,label:p}))]}),s.bpm&&ie({id:o,s:e,range:n.bpm}),s.loops&&ae(e),s.sorts.length>0&&i("sort",{label:e.sort,prefix:e.sortBy,value:s.sorts[0],options:s.sorts.map(p=>({value:p,label:e[Lt[p]]}))}),s.loop&&le(e,rt(t.loop,n))].filter(Boolean),l=s.types==="chips"&&u("div",{class:"ws-types",role:"group","aria-label":e.types},It("",e.all,r,!0),n.types.map(p=>It(p.name,p.name,p.count,!1))),d=s.count&&u("p",{class:"ws-count","data-ws-count":!0,"aria-live":"polite"},c(H(r,r,e)));return u("div",{class:"ws-toolbar"},s.search&&re(e),a.length>0&&u("div",{class:"ws-controls"},a),(l||d)&&u("div",{class:"ws-meta"},l,d))}var ce={type:s=>c(s.type),bpm:s=>c(s.bpm??""),key:s=>c(s.key),duration:s=>c(D(s.duration))};function pe(s,t,e,n=!1){let r=e.strings,o={title:s.title},i=e.columns.map(a=>u("span",{class:`ws-cell ws-${a}`},ce[a](s)));return u("li",{class:"ws-row","data-ws-index":t,"data-ws-id":s.id,"data-url":s.url,"data-title":s.title,"data-type":s.type||null,"data-bpm":s.bpm,"data-key":s.key||null,"data-duration":s.duration,"data-tags":s.tags?.length?s.tags.join(","):null,"data-peaks":s.peaks?O(s.peaks):null,"data-waveform":s.waveform,"data-download":s.download,"data-loop":s.loop?"true":null,hidden:n},u("button",{type:"button",class:"ws-play","aria-pressed":"false","aria-label":h(r.play,o)},y.play,y.pause),u("span",{class:"ws-cell ws-title"},u("span",{class:"ws-title-text"},c(s.title)),s.loop&&u("span",{class:"ws-loop-mark",title:r.isLoop},y.loop,u("span",{class:"ws-sr"},c(r.isLoop)))),i.length>0&&u("span",{class:"ws-cells"},i),e.player==="inline"&&u("span",{class:"ws-wave",role:"slider","aria-label":h(r.seek,o),"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":"0",tabindex:"-1"},u("canvas",{class:"ws-canvas","aria-hidden":"true"})),s.download&&u("a",{class:"ws-download",href:s.download,download:!0,"aria-label":h(r.download,o)},y.download))}function de({o:s,s:t,total:e}){let n=s.pageSize>0?s.pageSize:e,r=Math.max(0,e-n),o=s.player==="strip";return[u("p",{class:"ws-empty","data-ws-empty":!0,hidden:!0},c(t.empty)," ",u("button",{type:"button",class:"ws-clear","data-ws-clear":!0},c(t.clear))),u("button",{type:"button",class:"ws-more","data-ws-more":!0,hidden:r===0},c(h(t.showMore,{count:Math.min(r,n)}))),u("div",{class:o?"ws-engine ws-engine--strip":"ws-engine","data-ws-engine":!0,hidden:!o}),u("p",{class:"ws-sr","data-ws-status":!0,"aria-live":"polite"})].join("")}function F(s,t={}){let e=R(t),n=_(s),r={o:e,s:e.strings,f:w(n),total:n.length,id:e.idPrefix||se(n)},o=e.pageSize>0?e.pageSize:1/0;return ue(ne(r.f,e),r)+u("ul",{class:`ws-list ws-list--${e.player}`,role:"list","data-ws-list":!0},n.map((i,a)=>pe(i,a,e,a>=o)))+de(r)}function he(s,t={},e=""){let n=R(t),r=["waveform-sounds",`waveform-sounds--${n.player}`,e].filter(Boolean).join(" ");return u("div",{class:r,"data-waveform-sounds":!0,"data-player":n.player},F(s,t))}var ot=":scope > [data-ws-index]";function $t(s){let t=[...s.querySelectorAll(ot)].sort((n,r)=>Number(n.dataset.wsIndex)-Number(r.dataset.wsIndex)),e=[];for(let n of t){let r=n.dataset,o=V({id:r.wsId,url:r.url,title:r.title,type:r.type,bpm:r.bpm,key:r.key,duration:r.duration,tags:r.tags,peaks:r.peaks,waveform:r.waveform,download:r.download,loop:r.loop},e.length);if(!o){n.remove();continue}n.dataset.wsIndex=String(e.length),e.push(o)}return e}function Pt(s){let t=[];return s.querySelectorAll(ot).forEach(e=>{t[Number(e.dataset.wsIndex)]=e}),t}function it(s){return[...s.querySelectorAll(ot)].filter(t=>!t.hidden)}function Nt(s,t){let e=document.createDocumentFragment();for(let n of t)n&&e.appendChild(n);s.appendChild(e)}function fe(s){let t=String(s??"").trim();if(!t||t==="transparent")return 0;let e=t.match(/\/\s*([\d.]+)(%?)\s*\)$/);if(e)return Number(e[1])/(e[2]?100:1);let n=t.match(/^rgba\(\s*[^,]+,[^,]+,[^,]+,\s*([\d.]+)\s*\)$/);return n?Number(n[1]):1}function Ot(s,t=.95){for(let e=s;e&&e.nodeType===1;e=e.parentElement||e.getRootNode?.().host){let n=getComputedStyle(e).backgroundColor;if(fe(n)>t)return n}return"#fff"}function at(s,t){let e=document.createElement("span");e.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden",e.style.color=t,s.appendChild(e);let n=getComputedStyle(e).color;return e.remove(),n}function lt(s){if(!s)return null;let t=typeof s=="string"?`${s}-`:"";return{q:`${t}q`,type:`${t}type`,key:`${t}key`,bpm:`${t}bpm`,loop:`${t}loop`,sort:`${t}sort`}}function me(s){let t=String(s??"").match(/^(\d*)-(\d*)$/);return t&&(t[1]||t[2])?{bpmMin:t[1],bpmMax:t[2]}:null}function ye(s,t){let e=s??"",n=t??"";return e!==""||n!==""?`${e}-${n}`:""}function Dt(s,t,e,n){let r={filter:{},sort:null};if(!t)return r;let o=new URLSearchParams(s),i=o.get(t.q);i&&(r.filter.query=i);let a=o.get(t.type);a&&e.types.some(I=>I.name===a)&&(r.filter.type=a);let l=L(o.get(t.key));l&&e.keys.includes(l)&&(r.filter.key=l);let d=me(o.get(t.bpm));d&&Object.assign(r.filter,d);let p=o.get(t.loop);pt.includes(p)&&e.loops>0&&e.oneShots>0&&(r.filter.loop=p);let f=o.get(t.sort);return f&&n.includes(f)&&(r.sort=f),r}function Bt(s,t,e,n,r){if(!t)return s;let o=new URL(s),i=(a,l)=>l?o.searchParams.set(a,l):o.searchParams.delete(a);return i(t.q,String(e.query??"").trim()),i(t.type,e.type),i(t.key,e.key),i(t.bpm,ye(e.bpmMin,e.bpmMax)),i(t.loop,e.loop),i(t.sort,n!==r?n:""),o.href}var zt=Object.freeze({query:"",type:"",key:"",bpmMin:"",bpmMax:"",loop:""}),we=120,ge=200,be=250,x=class s{static instances=new Map;constructor(t,e={}){let n=typeof t=="string"?document.querySelector(t):t;if(!n)throw new Error(`${b} Container not found: ${t}`);this.container=n,this.options=Ft(j,e,Ct(n)),this.options.waveformStyle=this.options.waveformStyle==="bars"?"bars":"mirror",this.strings={...g,...this.options.strings||{}},this.render={...R(this.options),strings:this.strings},this.sounds=[],this.rows=[],this.filter={...zt},this.sortBy="default",this.limit=this._pageSize(),this.currentIndex=null,this.playing=!1,this.progress=0,this.loop=!!this.options.loop,this.engine=null,this.menus=null,this.destroyed=!1,this._ctl=new AbortController,this._originalHTML=null,this._pendingSeek=null,this._raf=0,s.instances.set(n,this),n.dataset.wsInitialized="true",this.ready=Promise.resolve().then(()=>this._init()).catch(r=>{console.error(`${b} Failed to initialise:`,r),this._emit("error",{error:r}),this.options.onError?.(r,this)})}async _init(){let t=this.container,e=t.querySelector("[data-ws-list]");if(e)this.sounds=$t(e);else{if(this._originalHTML=t.innerHTML,this.sounds=await this._loadSounds(),this.destroyed)return;t.innerHTML=F(this.sounds,{...this.render,idPrefix:this.options.idPrefix||t.id||void 0})}this.destroyed||(this._addedClasses=["waveform-sounds",`waveform-sounds--${this.render.player}`].filter(n=>!t.classList.contains(n)),t.classList.add(...this._addedClasses),this._cacheRefs(),this._bind(),this._observe(),this._resolveColors(),this._loopSet||(this.loop=rt(this.options.loop,w(this.sounds))),this._setLoop(this.loop),this._bpmExtent=w(this.sounds).bpm,this._sorts=q(this.render.sorts,w(this.sounds)),this._sortSet||(this.sortBy=this._sorts[0]||"default"),this._readUrl(),this._syncControls(),this._apply({resort:this.sortBy!=="default"}),this._playerClass()&&this._ensureEngine(),this.render.player==="strip"&&this.engine&&this.currentIndex==null&&this._cueFirst(),this._emit("ready",{sounds:this.sounds.length}),this.options.onReady?.(this))}async _loadSounds(){if(this.options.sounds||!this.options.manifest)return _(this.options.sounds||[]);let t=await fetch(this.options.manifest);if(!t.ok)throw new Error(`${b} Manifest ${this.options.manifest}: HTTP ${t.status}`);return B(await t.json())}_cacheRefs(){let t=e=>this.container.querySelector(e);this.$={list:t("[data-ws-list]"),search:t("[data-ws-search]"),bpmMin:t("[data-ws-bpm-min]"),bpmMax:t("[data-ws-bpm-max]"),bpmRange:t("[data-ws-bpm-range]"),bpmReadout:t("[data-ws-bpm-readout]"),bpmClear:t("[data-ws-bpm-clear]"),bpmLabel:t('[data-ws-menu="bpm"] [data-ws-menu-value]'),loop:t("[data-ws-loop]"),count:t("[data-ws-count]"),empty:t("[data-ws-empty]"),more:t("[data-ws-more]"),engine:t("[data-ws-engine]"),status:t("[data-ws-status]"),chips:[...this.container.querySelectorAll("[data-ws-type]")],loopFilter:[...this.container.querySelectorAll("[data-ws-loop-filter]")]},this.rows=Pt(this.$.list)}_bind(){let t={signal:this._ctl.signal},e=this.$,n=this.container;n.addEventListener("click",a=>this._onClick(a),t),n.addEventListener("pointerdown",a=>this._onPointerDown(a),t),n.addEventListener("keydown",a=>this._onKey(a),t);let r=0,o=0;e.search?.addEventListener("input",()=>{clearTimeout(r),r=setTimeout(()=>this.setFilter({query:e.search.value}),we)},t),e.search?.addEventListener("keydown",a=>{a.key==="ArrowDown"&&(a.preventDefault(),this._focusRow(it(e.list)[0])),a.key==="Escape"&&e.search.value&&(a.preventDefault(),e.search.value="",this.setFilter({query:""}))},t);let i=a=>{let l=Number(e.bpmMin.value),d=Number(e.bpmMax.value);l>d&&(a.value=String(a===e.bpmMin?d:l));let p=Mt(Number(e.bpmMin.value),Number(e.bpmMax.value),this._bpmExtent);this._showBpm(p),clearTimeout(o),o=setTimeout(()=>this.setFilter(p),ge)};e.bpmMin?.addEventListener("input",()=>i(e.bpmMin),t),e.bpmMax?.addEventListener("input",()=>i(e.bpmMax),t),e.bpmClear?.addEventListener("click",()=>{clearTimeout(o),this.setFilter({bpmMin:"",bpmMax:""})},t),this.menus=new U(n,{signal:this._ctl.signal,onPick:(a,l)=>a==="sort"?this.setSort(l):this.setFilter({[a]:l})}),document.addEventListener("waveformplayer:play",a=>{let l=a.detail?.player;l&&l!==this.engine&&this.playing&&this.pause()},t)}_onClick(t){let e=t.target,n=e.closest("[data-ws-type]");if(n){this.setFilter({type:n.dataset.wsType});return}let r=e.closest("[data-ws-loop-filter]");if(r){this.setFilter({loop:r.dataset.wsLoopFilter});return}if(e.closest("[data-ws-more]")){this.showMore();return}if(e.closest("[data-ws-clear]")){this.clearFilters();return}if(e.closest("[data-ws-loop]")){this.setLoop(!this.loop);return}let o=e.closest(".ws-wave");if(o){this._lastPointer==="touch"&&this._seekAt(o,t.clientX);return}let i=e.closest("[data-ws-index]");!i||e.closest(".ws-download")||(this.toggle(Number(i.dataset.wsIndex)),this._focusRowQuietly(i))}_onPointerDown(t){this._lastPointer=t.pointerType;let e=t.target.closest(".ws-wave");!e||t.button!==0||t.pointerType==="touch"||(t.preventDefault(),this._seekAt(e,t.clientX))}_seekAt(t,e){let n=t.closest("[data-ws-index]");this._seekRow(Number(n.dataset.wsIndex),mt(e,t.getBoundingClientRect())),this._focusRowQuietly(n)}_onKey(t){if(t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey)return;if(t.key==="/"&&!yt(t.target)&&this.$.search){t.preventDefault(),this.$.search.focus();return}let e=t.target.closest?.("[data-ws-index]");if(!e)return;let n=Number(e.dataset.wsIndex),r=St(this.progress,t.key);if(r!==null){if(n!==this.currentIndex||!this.engine)return;t.preventDefault(),this._seekRow(n,r);return}let o=it(this.$.list),i=xt(t.key,o.indexOf(e),o.length);if(i!==null){if(t.preventDefault(),i==="search"){this.$.search?.focus();return}this._focusRow(o[i]),this.options.arrowAudition&&this.playing&&this.play(Number(o[i].dataset.wsIndex))}}_focusRow(t){t?.querySelector(".ws-play")?.focus()}_focusRowQuietly(t){let e=t?.querySelector(".ws-play");e&&document.activeElement!==e&&e.focus({preventScroll:!0})}_observe(){if(this.render.player!=="inline"||typeof window>"u")return;if(this._drawn=new Set,"IntersectionObserver"in window?(this._io=new IntersectionObserver(n=>{for(let r of n){if(!r.isIntersecting)continue;let o=Number(r.target.dataset.wsIndex);this._drawn.add(o),this._drawRow(o)}},{rootMargin:"200px 0px"}),this.rows.forEach(n=>n&&this._io.observe(n))):this.rows.forEach((n,r)=>n&&this._drawn.add(r)),"ResizeObserver"in window){let n=0;this._ro=new ResizeObserver(([r])=>{let o=Math.round(r.contentRect.width);o!==n&&(n=o,this._redrawAll())}),this._ro.observe(this.$.list)}let t=()=>requestAnimationFrame(()=>{this._resolveColors(),this._redrawAll()});this._mo=new MutationObserver(t);let e={attributes:!0,attributeFilter:["class","data-theme","data-color-scheme","style"]};this._mo.observe(document.documentElement,e),document.body&&this._mo.observe(document.body,e);try{window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",t,{signal:this._ctl.signal})}catch{}}_resolveColors(){(this._autoSurface||!getComputedStyle(this.container).getPropertyValue("--ws-surface").trim())&&(this._autoSurface=!0,this.container.style.removeProperty("--ws-surface"),this.container.style.setProperty("--ws-surface",Ot(this.container))),this.colors={wave:this.options.waveformColor||at(this.container,"var(--ws-wave-color)")||"rgba(128,128,128,.5)",progress:this.options.progressColor||at(this.container,"var(--ws-progress-color)")||"currentColor"}}_drawRow(t){if(this.render.player!=="inline"||t==null||!this._drawn?.has(t))return;let e=this.rows[t],n=e?.querySelector("canvas");if(!n||e.hidden)return;let r=Number(this.options.barGap);dt(n,this.sounds[t].peaks,t===this.currentIndex?this.progress:0,{style:this.options.waveformStyle,color:this.colors?.wave||"rgba(128,128,128,.5)",progressColor:this.colors?.progress||"currentColor",barWidth:Math.max(1,Number(this.options.barWidth)||2),barGap:Number.isFinite(r)?Math.max(0,r):1})}_redrawAll(){this._drawn?.forEach(t=>this._drawRow(t))}_readUrl(){let t=lt(this.options.urlState);if(!t||typeof location>"u")return;let{filter:e,sort:n}=Dt(location.search,t,w(this.sounds),this._sorts);this.filter={...this.filter,...e},n&&(this.sortBy=n,this._sortSet=!0)}_queueUrl(){let t=lt(this.options.urlState);!t||typeof location>"u"||(clearTimeout(this._urlTimer),this._urlTimer=setTimeout(()=>{if(this.destroyed)return;let e=Bt(location.href,t,this.filter,this.sortBy,this._sorts?.[0]||"default");e!==location.href&&history.replaceState(history.state,"",e)},be))}get visible(){return T(this.sounds.filter(t=>z(t,this.filter)),this.sortBy)}setFilter(t={}){this.filter={...this.filter,...t},this.limit=this._pageSize(),this._syncControls(),this._apply({resort:!1})}clearFilters(){this.setFilter(zt)}setSort(t){this._sortSet=!0,this.sortBy=A.includes(t)?t:"default",this.menus?.setValue("sort",this.sortBy),this._apply({resort:!0})}showMore(){this.limit!==1/0&&(this.limit+=this.render.pageSize,this._apply({resort:!1}))}_pageSize(){return this.render.pageSize>0?this.render.pageSize:1/0}_syncControls(){let t=this.$,e=this.filter;if(t){if(t.search&&t.search.value!==e.query&&(t.search.value=e.query),this.menus?.setValue("type",e.type||""),this.menus?.setValue("key",e.key||""),this.menus?.setValue("sort",this.sortBy),t.bpmMin&&t.bpmMax&&this._bpmExtent){let{lo:n,hi:r}=k(e,this._bpmExtent);t.bpmMin.value=String(n),t.bpmMax.value=String(r),this._showBpm(e)}t.chips.forEach(n=>n.setAttribute("aria-pressed",String(n.dataset.wsType===(e.type||"")))),t.loopFilter.forEach(n=>n.setAttribute("aria-pressed",String(n.dataset.wsLoopFilter===(e.loop||""))))}}_showBpm(t){let e=this.$,n=this._bpmExtent;if(!e?.bpmRange||!n)return;let{lo:r,hi:o}=k(t,n);e.bpmLabel&&(e.bpmLabel.textContent=K(t,n,this.strings)),e.bpmReadout&&(e.bpmReadout.textContent=h(this.strings.bpmRange,{min:r,max:o})),e.bpmRange.style.setProperty("--ws-lo",String(tt(r,n))),e.bpmRange.style.setProperty("--ws-hi",String(tt(o,n))),e.bpmRange.classList.toggle("is-min-top",r>=o&&r>n.min),e.bpmRange.classList.toggle("is-active",r>n.min||o<n.max)}_apply({resort:t}){let e=this.$;if(!e)return;(t||this.sortBy!==this._lastSort)&&(Nt(e.list,T(this.sounds,this.sortBy).map(i=>this.rows[this.sounds.indexOf(i)])),this._lastSort=this.sortBy);let n=this.visible,{visible:r,remaining:o}=_t(n,this.limit);this.sounds.forEach((i,a)=>{this.rows[a]&&(this.rows[a].hidden=!r.has(i))}),e.more&&(e.more.hidden=o<=0,e.more.textContent=h(this.strings.showMore,{count:Math.min(o,this.render.pageSize||o)})),e.empty&&(e.empty.hidden=n.length>0),e.count&&(e.count.textContent=H(n.length,this.sounds.length,this.strings)),this._cued&&!this.playing&&this._cueFirst(),this._queueUrl(),this._emit("filter",{visible:n.length,total:this.sounds.length,filter:{...this.filter},sort:this.sortBy}),this.options.onFilter?.(n,this)}_indexOf(t){if(t==null)return this.currentIndex??(this.visible[0]?this.sounds.indexOf(this.visible[0]):null);if(typeof t=="number")return this.sounds[t]?t:null;let e=typeof t=="object"?this.sounds.indexOf(t):this.sounds.findIndex(n=>n.id===String(t));return e>=0?e:null}_playerClass(){return this.options.playerClass||(typeof window<"u"?window.WaveformPlayer:null)||null}_engineMount(){let t=this.$.engine,e=t.querySelector(":scope > [data-ws-engine-mount]");return e||(e=document.createElement("div"),e.setAttribute("data-ws-engine-mount",""),t.appendChild(e)),e}_ensureEngine(){if(this.engine)return this.engine;let t=this._playerClass();return t?(this.engine=new t(this._engineMount(),ht(this.options.playerOptions,this.render.player,{onLoad:()=>this._onEngineLoad(),onPlay:()=>this._setPlaying(!0),onPause:()=>this._setPlaying(!1),onEnd:()=>this._onEnd(),onTimeUpdate:(e,n)=>this._onTime(e,n),onError:e=>this._onEngineError(e)})),this.engine):(console.error(`${b} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`),null)}play(t,e={}){if(!this.$){this.ready.then(()=>{this.destroyed||this.play(t,e)});return}let n=this._indexOf(t);if(n==null)return;this._cued=!1;let r=this._ensureEngine();if(!r)return;if(n===this.currentIndex&&r.audio?.src){e.at!=null&&this._seekRow(n,e.at),this.playing||r.play();return}let o=this.currentIndex;this.currentIndex=n,this.progress=0,this._pendingSeek=e.at??null,o!=null&&this._paintRow(o),this._paintRow(n);let i=this.sounds[n];r.loadTrack(i.url,i.title,i.type||null,{waveform:J(i,this.render.player),autoplay:!0})}_cueFirst(){let t=this.engine,e=this.visible[0];if(!t||!e)return;let n=this.sounds.indexOf(e);n!==this.currentIndex&&(this.currentIndex=n,this.progress=0,this._cued=!0,t.loadTrack(e.url,e.title,e.type||null,{waveform:J(e,"strip"),autoplay:!1}))}pause(){this.engine&&this.playing&&this.engine.pause()}toggle(t){let e=this._indexOf(t);e!=null&&(e===this.currentIndex&&this.playing?this.pause():this.play(e))}next(){this._step(1)}previous(){this._step(-1)}_step(t){let e=this.visible,n=this.currentIndex==null||this._cued?-1:e.indexOf(this.sounds[this.currentIndex]),r=e[n+t];if(!r)return!1;let o=vt(this.limit,n+t);return o!==this.limit&&(this.limit=o,this._apply({resort:!1})),this.play(this.sounds.indexOf(r)),!0}setLoop(t){this._loopSet=!0,this.loop=!!t,this._setLoop(this.loop)}_setLoop(t){this.$?.loop?.setAttribute("aria-pressed",String(t)),this.engine?.audio&&(this.engine.audio.loop=this._repeats())}_repeats(){return this.loop?!this.sounds.some(e=>e.loop)||!!this.sounds[this.currentIndex]?.loop:!1}_seekRow(t,e){if(t!==this.currentIndex||!this.engine){this.play(t,{at:e});return}let n=this.engine.audio?.duration;if(!Number.isFinite(n)||n<=0){this._pendingSeek=e;return}this.engine.seekTo(e*n),this.progress=e,this._paintRow(t),this.playing||this.engine.play()}_onEngineLoad(){this.engine?.audio&&(this.engine.audio.loop=this._repeats());let t=this.sounds[this.currentIndex];t&&!t.peaks&&this.engine?.waveformData?.length&&(t.peaks=Y(this.engine.waveformData,96),this._drawRow(this.currentIndex));let e=this.engine?.audio?.duration;this._pendingSeek!=null&&Number.isFinite(e)&&e>0&&(this.engine.seekTo(this._pendingSeek*e),this.progress=this._pendingSeek,this._pendingSeek=null)}_onTime(t,e){if(!(this.currentIndex==null||!e)){if(this._pendingSeek!=null){let n=this._pendingSeek;this._pendingSeek=null,this.engine.seekTo(n*e);return}this.progress=Math.min(Math.max(t/e,0),1),!this._raf&&(this._raf=requestAnimationFrame(()=>{this._raf=0,this._drawRow(this.currentIndex),this.rows[this.currentIndex]?.querySelector(".ws-wave")?.setAttribute("aria-valuenow",String(Math.round(this.progress*100)))}))}}_onEnd(){let t=this.sounds[this.currentIndex];this._emit("end",{sound:t,index:this.currentIndex}),this.options.onEnd?.(t,this),!(this.options.autoAdvance&&this._step(1))&&(this.progress=0,this._setPlaying(!1))}_onEngineError(t){this.rows[this.currentIndex]?.classList.add("is-error"),this._emit("error",{error:t,sound:this.sounds[this.currentIndex],index:this.currentIndex}),this.options.onError?.(t,this)}_setPlaying(t){let e=this.playing!==t;this.playing=t,t&&(this._cued=!1);let n=this.currentIndex;if(n==null||(this._paintRow(n),!e))return;let r=this.sounds[n];t&&this.$.status&&(this.$.status.textContent=h(this.strings.nowPlaying,{title:r.title})),this._emit(t?"play":"pause",{sound:r,index:n}),(t?this.options.onPlay:this.options.onPause)?.(r,this)}_paintRow(t){let e=this.rows[t];if(!e)return;let n=t===this.currentIndex,r=n&&this.playing;e.classList.toggle("is-current",n),e.classList.toggle("is-playing",r);let o=e.querySelector(".ws-play");o&&(o.setAttribute("aria-pressed",String(r)),o.setAttribute("aria-label",h(r?this.strings.pause:this.strings.play,{title:this.sounds[t].title})));let i=e.querySelector(".ws-wave");i&&(i.tabIndex=n?0:-1,n||i.setAttribute("aria-valuenow","0")),this._drawRow(t)}_emit(t,e={}){wt(this.container,t,{...e,instance:this})}get current(){return this.currentIndex==null||this._cued?null:this.sounds[this.currentIndex]}destroy(){if(!this.destroyed){this.destroyed=!0,this._ctl.abort(),this._io?.disconnect(),this._ro?.disconnect(),this._mo?.disconnect(),this._raf&&cancelAnimationFrame(this._raf),clearTimeout(this._urlTimer);try{this.engine?.destroy()}catch{}this.engine=null,this.$?.engine?.querySelector(":scope > [data-ws-engine-mount]")?.remove(),this._originalHTML!=null&&(this.container.innerHTML=this._originalHTML),this._addedClasses?.length&&this.container.classList.remove(...this._addedClasses),this._autoSurface&&this.container.style.removeProperty("--ws-surface"),delete this.container.dataset.wsInitialized,s.instances.delete(this.container)}}static init(t=document){if(typeof document>"u")return[];let e=t||document,n=[...e.matches?.("[data-waveform-sounds]")?[e]:[],...e.querySelectorAll("[data-waveform-sounds]")],r=[];for(let o of n)if(!(o.dataset.wsInitialized==="true"||s.instances.has(o)))try{r.push(new s(o))}catch(i){console.error(`${b} Failed to initialise:`,i,o)}return r}static getInstance(t){let e=typeof t=="string"?document.querySelector(t):t;return e&&s.instances.get(e)||null}static prune(){for(let[t,e]of s.instances)t.isConnected||e.destroy()}};x.utils={encodePeaks:O,decodePeaks:W,normalizeKey:L,normalizeSounds:_,parseManifest:B,facets:w,matches:z,sortSounds:T,formatDuration:D,renderSounds:F};x.DEFAULT_OPTIONS=j;x.DEFAULT_STRINGS=g;typeof window<"u"&&(window.WaveformSounds=x);var G=x;var Ss=G;typeof document<"u"&&document.documentElement?.dataset?.waveformAutoinit!=="false"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>G.init(),{once:!0}):G.init());})();
2
2
  /**
3
3
  * @arraypress/waveform-sounds
4
4
  * A searchable, filterable list of sounds for WaveformPlayer.
package/index.d.ts CHANGED
@@ -104,6 +104,10 @@ export interface WaveformSoundsStrings {
104
104
  bpm: string;
105
105
  bpmMin: string;
106
106
  bpmMax: string;
107
+ /** The BPM menu with no limit set. */
108
+ anyBpm: string;
109
+ /** The BPM menu's range: `{min}`, `{max}`. */
110
+ bpmRange: string;
107
111
  sort: string;
108
112
  sortBy: string;
109
113
  sortDefault: string;
@@ -187,8 +191,9 @@ export interface WaveformSoundsOptions {
187
191
  barWidth?: number;
188
192
  /** Gap between row bars in CSS px. Default 1. */
189
193
  barGap?: number;
190
- /** Start with Loop on. Default false. */
191
- loop?: boolean;
194
+ /** Start with Loop on or off. Unset (default): on when any sound is
195
+ * marked `loop: true` (then only loops repeat), off otherwise. */
196
+ loop?: boolean | null;
192
197
  /** Play the next visible sound when one ends. Default false. */
193
198
  autoAdvance?: boolean;
194
199
  /** While a sound plays, ↑/↓ move to the next row AND play it (the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arraypress/waveform-sounds",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Searchable, filterable sound list for WaveformPlayer: audition hundreds of sample previews with inline waveforms, keyboard navigation and one shared audio engine.",
5
5
  "type": "module",
6
6
  "main": "dist/waveform-sounds.cjs",
@@ -104,16 +104,6 @@
104
104
  }
105
105
 
106
106
  .ws-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
107
- .ws-bpm-range input {
108
- height: 2.75rem;
109
- border: 1px solid var(--ws-border);
110
- border-radius: var(--ws-control-radius);
111
- background: var(--ws-field);
112
- color: inherit;
113
- font: inherit;
114
- font-size: 0.9em;
115
- }
116
-
117
107
  /* ── Dropdowns (type / key / sort) ──────────────────────────────────── */
118
108
  .ws-menu { position: relative; }
119
109
  .ws-menu-btn {
@@ -185,9 +175,105 @@
185
175
  .ws-menu-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
186
176
  .ws-menu-count { font-family: var(--ws-mono); font-size: 0.85em; color: var(--ws-muted); }
187
177
  .ws-menu-none { margin: 0; padding: 0.6rem; color: var(--ws-muted); font-size: 0.9em; }
188
- .ws-bpm-range { display: inline-flex; align-items: center; gap: 0.35rem; color: var(--ws-muted); font-size: 0.9em; }
189
- .ws-bpm-range input { width: 5rem; padding: 0 0.85rem; -moz-appearance: textfield; }
190
- .ws-bpm-range input::-webkit-inner-spin-button { display: none; }
178
+
179
+ /* ── The BPM menu: a panel with a two-handle range ───────────────────── */
180
+ .ws-bpm-pop { width: 17rem; padding: 0.85rem 1rem 0.7rem; }
181
+ .ws-bpm-head { display: flex; align-items: baseline; justify-content: space-between; gap: 0.75rem; margin-bottom: 0.6rem; }
182
+ .ws-bpm-readout { font-weight: 600; font-variant-numeric: tabular-nums; }
183
+ .ws-bpm-clear {
184
+ padding: 0;
185
+ border: 0;
186
+ background: none;
187
+ color: var(--ws-muted);
188
+ font: inherit;
189
+ font-size: 0.85em;
190
+ cursor: pointer;
191
+ }
192
+ .ws-bpm-clear:hover { color: inherit; text-decoration: underline; }
193
+
194
+ /* Two native range inputs stacked on one track. The track and the filled
195
+ * span are drawn by the wrapper (--ws-lo / --ws-hi are the handles' 0..1
196
+ * positions, set by the runtime); the inputs contribute only their thumbs.
197
+ * A thumb's centre runs from half a thumb in from each end, hence the
198
+ * calc() on the fill. */
199
+ .ws-range {
200
+ --ws-thumb: 18px;
201
+ --ws-lo: 0;
202
+ --ws-hi: 1;
203
+ position: relative;
204
+ height: 1.75rem;
205
+ }
206
+ .ws-range::before,
207
+ .ws-range::after {
208
+ content: '';
209
+ position: absolute;
210
+ top: 50%;
211
+ height: 4px;
212
+ border-radius: 2px;
213
+ transform: translateY(-50%);
214
+ }
215
+ .ws-range::before { left: 0; right: 0; background: var(--ws-border); }
216
+ .ws-range::after {
217
+ left: calc(var(--ws-thumb) / 2 + var(--ws-lo) * (100% - var(--ws-thumb)));
218
+ right: calc(var(--ws-thumb) / 2 + (1 - var(--ws-hi)) * (100% - var(--ws-thumb)));
219
+ background: var(--ws-accent);
220
+ opacity: 0.35;
221
+ }
222
+ .ws-range.is-active::after { opacity: 1; }
223
+ .ws-range-input {
224
+ position: absolute;
225
+ inset: 0;
226
+ z-index: 1;
227
+ width: 100%;
228
+ height: 100%;
229
+ margin: 0;
230
+ background: none;
231
+ pointer-events: none;
232
+ -webkit-appearance: none;
233
+ appearance: none;
234
+ }
235
+ /* When the handles meet, the lower one goes on top (it's the one that can
236
+ * still move: left). */
237
+ .ws-range.is-min-top [data-ws-bpm-min] { z-index: 2; }
238
+ .ws-range-input::-webkit-slider-runnable-track { height: 100%; background: none; }
239
+ .ws-range-input::-moz-range-track { background: none; }
240
+ .ws-range-input::-webkit-slider-thumb {
241
+ width: var(--ws-thumb);
242
+ height: var(--ws-thumb);
243
+ margin-top: calc((1.75rem - var(--ws-thumb)) / 2);
244
+ border: 2px solid var(--ws-surface, Canvas);
245
+ border-radius: 50%;
246
+ background: var(--ws-accent);
247
+ box-shadow: 0 0 0 1px var(--ws-border);
248
+ cursor: grab;
249
+ pointer-events: auto;
250
+ -webkit-appearance: none;
251
+ appearance: none;
252
+ }
253
+ .ws-range-input::-moz-range-thumb {
254
+ width: var(--ws-thumb);
255
+ height: var(--ws-thumb);
256
+ box-sizing: border-box;
257
+ border: 2px solid var(--ws-surface, Canvas);
258
+ border-radius: 50%;
259
+ background: var(--ws-accent);
260
+ box-shadow: 0 0 0 1px var(--ws-border);
261
+ cursor: grab;
262
+ pointer-events: auto;
263
+ }
264
+ .ws-range-input:active::-webkit-slider-thumb { cursor: grabbing; }
265
+ .ws-range-input:focus-visible { outline: none; }
266
+ .ws-range-input:focus-visible::-webkit-slider-thumb { box-shadow: 0 0 0 3px var(--ws-accent); }
267
+ .ws-range-input:focus-visible::-moz-range-thumb { box-shadow: 0 0 0 3px var(--ws-accent); }
268
+ .ws-range-ends {
269
+ display: flex;
270
+ justify-content: space-between;
271
+ margin-top: 0.15rem;
272
+ color: var(--ws-muted);
273
+ font-family: var(--ws-mono);
274
+ font-size: 0.75em;
275
+ font-variant-numeric: tabular-nums;
276
+ }
191
277
  .ws-loop {
192
278
  display: inline-flex;
193
279
  align-items: center;
@@ -388,9 +474,11 @@
388
474
  .ws-more { display: block; margin: 1.25rem auto 0; padding: 0.7rem 1.4rem; font-size: 0.92em; }
389
475
  .ws-more:hover, .ws-clear:hover { background: var(--ws-hover); }
390
476
 
391
- /* The strip layout: the engine is a full player docked under the list. */
477
+ /* The strip layout: the engine is a full player docked under the list.
478
+ * It stays in place by default; set --ws-strip-position: sticky to keep it
479
+ * at the bottom of the viewport while a long list scrolls past. */
392
480
  .ws-engine--strip {
393
- position: sticky;
481
+ position: var(--ws-strip-position, static);
394
482
  bottom: 0;
395
483
  margin-top: 1rem;
396
484
  padding: 0.75rem;
@@ -406,7 +494,9 @@
406
494
  @media (pointer: coarse) {
407
495
  .ws-play, .ws-download { width: 2.75rem; height: 2.75rem; }
408
496
  .ws-chip { height: 2.5rem; }
409
- .ws-search-input, .ws-menu-search, .ws-bpm-range input { font-size: 16px; }
497
+ .ws-search-input, .ws-menu-search { font-size: 16px; }
498
+ .ws-range { --ws-thumb: 24px; height: 2.25rem; }
499
+ .ws-range-input::-webkit-slider-thumb { margin-top: calc((2.25rem - var(--ws-thumb)) / 2); }
410
500
  .ws-menu-option { padding: 0.75rem 0.6rem; }
411
501
  }
412
502
 
@@ -33,9 +33,10 @@ import {Menus} from '../dom/menus.js';
33
33
  import {limitToReveal, pageWindow, rowTarget, seekTarget} from '../data/navigation.js';
34
34
  import {DEFAULT_OPTIONS, mergeOptions, readDataOptions} from './options.js';
35
35
  import {resolveRenderOptions} from '../render/options.js';
36
- import {renderSounds} from '../render/markup.js';
36
+ import {loopsByDefault, renderSounds} from '../render/markup.js';
37
37
  import {indexRows, orderRows, readRows, visibleRows} from '../dom/rows.js';
38
- import {countText, DEFAULT_STRINGS, fill} from '../render/strings.js';
38
+ import {bpmLabel, countText, DEFAULT_STRINGS, fill} from '../render/strings.js';
39
+ import {bpmFilterFromRange, bpmFraction, bpmRangeFromFilter} from '../data/bpm.js';
39
40
  import {pageSurface, resolveCssColor} from '../dom/colors.js';
40
41
  import {readUrlState, urlKeys, writeUrlState} from '../data/url-state.js';
41
42
  import {emit, isTyping, LOG, pointerFraction} from '../shared/utils.js';
@@ -131,7 +132,11 @@ export class WaveformSounds {
131
132
  this._bind();
132
133
  this._observe();
133
134
  this._resolveColors();
135
+ // Unless set (option or an early setLoop()), Loop starts on exactly
136
+ // when the list marks loops — only those repeat.
137
+ if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, facets(this.sounds));
134
138
  this._setLoop(this.loop);
139
+ this._bpmExtent = facets(this.sounds).bpm;
135
140
 
136
141
  // The starting order is the first one offered, unless setSort()
137
142
  // already chose one; then the address may override both.
@@ -148,6 +153,9 @@ export class WaveformSounds {
148
153
  // BEFORE the first play — built on first play, that sound went
149
154
  // untracked.
150
155
  if (this._playerClass()) this._ensureEngine();
156
+ // Strip: the docked player starts with the first sound cued — its
157
+ // title and waveform, ready to play — rather than an empty frame.
158
+ if (this.render.player === 'strip' && this.engine && this.currentIndex == null) this._cueFirst();
151
159
 
152
160
  this._emit('ready', {sounds: this.sounds.length});
153
161
  this.options.onReady?.(this);
@@ -176,6 +184,10 @@ export class WaveformSounds {
176
184
  search: q('[data-ws-search]'),
177
185
  bpmMin: q('[data-ws-bpm-min]'),
178
186
  bpmMax: q('[data-ws-bpm-max]'),
187
+ bpmRange: q('[data-ws-bpm-range]'),
188
+ bpmReadout: q('[data-ws-bpm-readout]'),
189
+ bpmClear: q('[data-ws-bpm-clear]'),
190
+ bpmLabel: q('[data-ws-menu="bpm"] [data-ws-menu-value]'),
179
191
  loop: q('[data-ws-loop]'),
180
192
  count: q('[data-ws-count]'),
181
193
  empty: q('[data-ws-empty]'),
@@ -211,12 +223,22 @@ export class WaveformSounds {
211
223
  if (e.key === 'ArrowDown') { e.preventDefault(); this._focusRow(visibleRows($.list)[0]); }
212
224
  if (e.key === 'Escape' && $.search.value) { e.preventDefault(); $.search.value = ''; this.setFilter({query: ''}); }
213
225
  }, sig);
214
- const onBpm = () => {
226
+ // The BPM handles: the label and the track follow the drag at once;
227
+ // the list re-filters once it settles. A handle can't pass the other.
228
+ const onBpm = (moved) => {
229
+ const lo = Number($.bpmMin.value), hi = Number($.bpmMax.value);
230
+ if (lo > hi) moved.value = String(moved === $.bpmMin ? hi : lo);
231
+ const f = bpmFilterFromRange(Number($.bpmMin.value), Number($.bpmMax.value), this._bpmExtent);
232
+ this._showBpm(f);
215
233
  clearTimeout(bpmTimer);
216
- bpmTimer = setTimeout(() => this.setFilter({bpmMin: $.bpmMin?.value ?? '', bpmMax: $.bpmMax?.value ?? ''}), BPM_DELAY);
234
+ bpmTimer = setTimeout(() => this.setFilter(f), BPM_DELAY);
217
235
  };
218
- $.bpmMin?.addEventListener('input', onBpm, sig);
219
- $.bpmMax?.addEventListener('input', onBpm, sig);
236
+ $.bpmMin?.addEventListener('input', () => onBpm($.bpmMin), sig);
237
+ $.bpmMax?.addEventListener('input', () => onBpm($.bpmMax), sig);
238
+ $.bpmClear?.addEventListener('click', () => {
239
+ clearTimeout(bpmTimer);
240
+ this.setFilter({bpmMin: '', bpmMax: ''});
241
+ }, sig);
220
242
 
221
243
  this.menus = new Menus(root, {
222
244
  signal: this._ctl.signal,
@@ -516,12 +538,35 @@ export class WaveformSounds {
516
538
  this.menus?.setValue('type', f.type || '');
517
539
  this.menus?.setValue('key', f.key || '');
518
540
  this.menus?.setValue('sort', this.sortBy);
519
- if ($.bpmMin && $.bpmMin.value !== String(f.bpmMin)) $.bpmMin.value = f.bpmMin;
520
- if ($.bpmMax && $.bpmMax.value !== String(f.bpmMax)) $.bpmMax.value = f.bpmMax;
541
+ if ($.bpmMin && $.bpmMax && this._bpmExtent) {
542
+ const {lo, hi} = bpmRangeFromFilter(f, this._bpmExtent);
543
+ $.bpmMin.value = String(lo);
544
+ $.bpmMax.value = String(hi);
545
+ this._showBpm(f);
546
+ }
521
547
  $.chips.forEach((c) => c.setAttribute('aria-pressed', String(c.dataset.wsType === (f.type || ''))));
522
548
  $.loopFilter.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.wsLoopFilter === (f.loop || ''))));
523
549
  }
524
550
 
551
+ /**
552
+ * Show a BPM filter in its menu: the button label, the panel's readout,
553
+ * the filled part of the track, and which handle sits on top (the one
554
+ * that can still move, when they meet).
555
+ * @private
556
+ */
557
+ _showBpm(f) {
558
+ const $ = this.$, extent = this._bpmExtent;
559
+ if (!$?.bpmRange || !extent) return;
560
+ const {lo, hi} = bpmRangeFromFilter(f, extent);
561
+ if ($.bpmLabel) $.bpmLabel.textContent = bpmLabel(f, extent, this.strings);
562
+ if ($.bpmReadout) $.bpmReadout.textContent = fill(this.strings.bpmRange, {min: lo, max: hi});
563
+ // CSSOM, not a style attribute: works under a strict CSP.
564
+ $.bpmRange.style.setProperty('--ws-lo', String(bpmFraction(lo, extent)));
565
+ $.bpmRange.style.setProperty('--ws-hi', String(bpmFraction(hi, extent)));
566
+ $.bpmRange.classList.toggle('is-min-top', lo >= hi && lo > extent.min);
567
+ $.bpmRange.classList.toggle('is-active', lo > extent.min || hi < extent.max);
568
+ }
569
+
525
570
  /**
526
571
  * Lay the rows out for the current filter, sort and page: order, hide,
527
572
  * "Show more", the empty state and the count. Then report it.
@@ -546,6 +591,8 @@ export class WaveformSounds {
546
591
  }
547
592
  if ($.empty) $.empty.hidden = shown.length > 0;
548
593
  if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
594
+ // Nothing played yet: keep the cued sound one the list still shows.
595
+ if (this._cued && !this.playing) this._cueFirst();
549
596
  this._queueUrl();
550
597
  this._emit('filter', {visible: shown.length, total: this.sounds.length, filter: {...this.filter}, sort: this.sortBy});
551
598
  this.options.onFilter?.(shown, this);
@@ -631,6 +678,7 @@ export class WaveformSounds {
631
678
  if (!this.$) { this.ready.then(() => { if (!this.destroyed) this.play(target, opts); }); return; }
632
679
  const index = this._indexOf(target);
633
680
  if (index == null) return;
681
+ this._cued = false;
634
682
  const engine = this._ensureEngine();
635
683
  if (!engine) return;
636
684
  if (index === this.currentIndex && engine.audio?.src) {
@@ -648,6 +696,26 @@ export class WaveformSounds {
648
696
  engine.loadTrack(sound.url, sound.title, sound.type || null, {waveform: enginePeaks(sound, this.render.player), autoplay: true});
649
697
  }
650
698
 
699
+ /**
700
+ * Strip layout: load the first sound the list shows into the docked
701
+ * player WITHOUT playing it, so the player shows a title and waveform
702
+ * (and its play button plays that sound) instead of an empty frame.
703
+ * Only metadata is fetched — the browser default for any `<audio>`.
704
+ * The row isn't marked current until it plays.
705
+ * @private
706
+ */
707
+ _cueFirst() {
708
+ const engine = this.engine;
709
+ const first = this.visible[0];
710
+ if (!engine || !first) return;
711
+ const index = this.sounds.indexOf(first);
712
+ if (index === this.currentIndex) return;
713
+ this.currentIndex = index;
714
+ this.progress = 0;
715
+ this._cued = true;
716
+ engine.loadTrack(first.url, first.title, first.type || null, {waveform: enginePeaks(first, 'strip'), autoplay: false});
717
+ }
718
+
651
719
  /** Pause the current sound. */
652
720
  pause() {
653
721
  if (this.engine && this.playing) this.engine.pause();
@@ -680,7 +748,8 @@ export class WaveformSounds {
680
748
  */
681
749
  _step(dir) {
682
750
  const shown = this.visible;
683
- const at = this.currentIndex == null ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
751
+ // A cued sound counts as nothing played: next() starts with it.
752
+ const at = this.currentIndex == null || this._cued ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
684
753
  const target = shown[at + dir];
685
754
  if (!target) return false;
686
755
  const limit = limitToReveal(this.limit, at + dir);
@@ -696,6 +765,7 @@ export class WaveformSounds {
696
765
  * @param {boolean} on
697
766
  */
698
767
  setLoop(on) {
768
+ this._loopSet = true;
699
769
  this.loop = !!on;
700
770
  this._setLoop(this.loop);
701
771
  }
@@ -808,6 +878,7 @@ export class WaveformSounds {
808
878
  _setPlaying(on) {
809
879
  const changed = this.playing !== on;
810
880
  this.playing = on;
881
+ if (on) this._cued = false; // the strip's own button played the cued sound
811
882
  const index = this.currentIndex;
812
883
  if (index == null) return;
813
884
  this._paintRow(index);
@@ -856,7 +927,8 @@ export class WaveformSounds {
856
927
 
857
928
  /** The sound playing (or paused) now, or null. */
858
929
  get current() {
859
- return this.currentIndex == null ? null : this.sounds[this.currentIndex];
930
+ // A cued sound (strip, nothing played yet) isn't "current".
931
+ return this.currentIndex == null || this._cued ? null : this.sounds[this.currentIndex];
860
932
  }
861
933
 
862
934
  /**
@@ -25,7 +25,7 @@ export const DEFAULT_OPTIONS = {
25
25
  progressColor: null,
26
26
  barWidth: 2,
27
27
  barGap: 1,
28
- loop: false,
28
+ loop: null,
29
29
  autoAdvance: false,
30
30
  arrowAudition: true,
31
31
  idPrefix: null,