@digitalmeadow/control-panel 1.0.2 → 1.0.4

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 +1,282 @@
1
- (function(d,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(d=typeof globalThis<"u"?globalThis:d||self,o(d.ControlPanel={}))})(this,(function(d){"use strict";function o(n,t={},e=[]){const i=document.createElement(n);for(const[s,a]of Object.entries(t))s==="className"?i.className=String(a):s==="style"&&typeof a=="object"?Object.assign(i.style,a):s==="open"&&typeof a=="boolean"?a?i.setAttribute("open",""):i.removeAttribute("open"):typeof a!="object"&&i.setAttribute(s,String(a));for(const s of e)typeof s=="string"?i.appendChild(document.createTextNode(s)):i.appendChild(s);return i}function D(n){const t=o("button",{className:"cp-button cp-button-delete"},["×"]);return t.addEventListener("click",n),t}function K(n){return n.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}function O(n,t,e){return Math.min(Math.max(n,t),e)}function Q(n,t,e){if(t.length!==e.length)throw new Error("Input and output ranges must have the same length");if(t.length<2)throw new Error("Input and output ranges must have at least two values");let i=0;for(;i<t.length-1&&n>t[i+1];)i++;if(i===t.length-1)return e[e.length-1];if(i===0&&n<t[0])return e[0];const s=t[i],a=t[i+1],r=e[i],h=e[i+1];return(n-s)/(a-s)*(h-r)+r}class B{constructor(){this.source=null,this.stream=null,this.fftSize=2048,this.smoothingTimeConstant=.92,this.spectrumBoost=2,this.levels={bass:0,mids:0,highs:0,volume:0},this.peaks={bass:0,mids:0,highs:0,volume:0},this._isAnalyzing=!1,this.loop=()=>{this._isAnalyzing&&(requestAnimationFrame(this.loop),this.update())};const t=window.AudioContext||window.webkitAudioContext;this.ctx=new t,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.waveformArray=new Uint8Array(this.analyser.frequencyBinCount)}setFFTSize(t){this.fftSize=t,this.analyser.fftSize=t,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.waveformArray=new Uint8Array(this.analyser.frequencyBinCount)}async setInput(t){try{let e;t==="browser"?e=navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0}):e=navigator.mediaDevices.getUserMedia({audio:!0});const i=await e;this.ctx.state==="suspended"&&this.ctx.resume(),this.source&&this.source.disconnect(),this.stream&&this.stream.getTracks().forEach(s=>s.stop()),this.stream=i,this.source=this.ctx.createMediaStreamSource(this.stream),this.source.connect(this.analyser),this._isAnalyzing=!0,this.loop()}catch(e){console.error("Error accessing audio input:",e),this._isAnalyzing=!1}}update(){if(this.analyser.getByteFrequencyData(this.dataArray),this.analyser.getByteTimeDomainData(this.waveformArray),this.spectrumBoost!==1){const p=this.dataArray.length;for(let c=0;c<p;c++){const f=1+c/p*(this.spectrumBoost-1);this.dataArray[c]=Math.min(255,this.dataArray[c]*f)}}const t=[2,10],e=[10,150],i=[150,600],s=this.getAverage(t[0],t[1]),a=this.getAverage(e[0],e[1]),r=this.getAverage(i[0],i[1]),h=this.getAverage(0,i[1]);this.processLevel("bass",s),this.processLevel("mids",a),this.processLevel("highs",r),this.processLevel("volume",h)}processLevel(t,e){this.peaks[t]-=5e-4,this.peaks[t]=O(this.peaks[t],.1,1),e>this.peaks[t]&&(this.peaks[t]=e),this.levels[t]=O(Q(e,[0,this.peaks[t]],[0,1]),0,1)}getAverage(t,e){let i=0;const s=e-t;if(s<=0)return 0;for(let a=t;a<e;a++)i+=this.dataArray[a];return i/s/255}getSignal(t){return()=>this.levels[t]}}const x=new B;class F{constructor(){this.midiAccess=null,this.values=new Map,this.isListening=!1,this.resolveListen=null,this.listeningCallback=null,this.init()}async init(){if(typeof navigator<"u"&&navigator.requestMIDIAccess)try{this.midiAccess=await navigator.requestMIDIAccess(),this.setupInputs(),this.midiAccess.onstatechange=t=>{t.port.type==="input"&&t.port.state==="connected"&&this.setupInputs()}}catch(t){console.warn("MIDI Access failed",t)}}setupInputs(){if(!this.midiAccess)return;const t=this.midiAccess.inputs.values();for(const e of t)e.onmidimessage=this.handleMessage.bind(this)}handleMessage(t){const e=t.data,[i]=e;if((i&240)>=240)return;const a=this.getIdFromMessage(t),r=this.normalizeValue(e);this.values.set(a,r),this.isListening&&this.resolveListen&&r>0&&(this.resolveListen(a),this.isListening=!1,this.resolveListen=null,this.listeningCallback&&this.listeningCallback())}getIdFromMessage(t){const e=t.data,[i,s]=e,a=i&240,r=t.currentTarget.name||"unknown",h=a===144||a===128?"note":"ctrl",p=r.replace(/[^a-zA-Z0-9]/g,"");return`${s}_${h}_${p}`}normalizeValue(t){const[e,i,s]=t,a=e&240;return a===144?s>0?1:0:a===128?0:a===176?s/127:0}listen(){return this.isListening=!0,new Promise(t=>{this.resolveListen=t})}cancelListen(){this.isListening=!1,this.resolveListen=null}getSignal(t){return()=>this.values.get(t)??0}}const P=new F,M=class M{constructor(t,e,i={}){this.changeFns=new Set,this.object=t,this.property=e,this.key=i.id??e,this.initialValue=this.object[this.property],this.domElement=o("div",{className:"cp-controller"});const s=i.label??K(e),a=o("label",{className:"cp-label"},[String(s)]);a.setAttribute("title",String(s)),this.domElement.appendChild(a),i.disabled&&this.domElement.setAttribute("data-disabled","true")}get value(){return this.object[this.property]}setValue(t,e=!0){this.object[this.property]=t,e&&this.emitChange(t),this.updateDisplay()}save(){return this.value}load(t){this.setValue(t)}reset(){this.setValue(this.initialValue)}onChange(t){return this.changeFns.add(t),this}emitChange(t){for(const e of this.changeFns)e(t)}appendWidget(t){this.domElement.appendChild(t)}};M.audio=x,M.midi=P;let m=M;const k={linear:n=>n,quadIn:n=>n*n,quadOut:n=>n*(2-n),quadInOut:n=>n<.5?2*n*n:-1+(4-2*n)*n,cubicIn:n=>n*n*n,cubicOut:n=>--n*n*n+1,cubicInOut:n=>n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1,expoIn:n=>n===0?0:Math.pow(2,10*(n-1)),expoOut:n=>n===1?1:-Math.pow(2,-10*n)+1,expoInOut:n=>n===0||n===1?n:(n*=2)<1?.5*Math.pow(2,10*(n-1)):.5*(-Math.pow(2,-10*--n)+2),sineIn:n=>1-Math.cos(n*Math.PI/2),sineOut:n=>Math.sin(n*Math.PI/2),sineInOut:n=>-(Math.cos(Math.PI*n)-1)/2};class R{constructor(t){this.rafId=null,this.currentSignalType=null,this.currentMidiId=null,this.currentEase="linear",this.currentBehaviour="forward",this.loop=()=>{if(this.currentSignalType){let e=0;this.currentSignalType==="midi"?this.currentMidiId&&(e=m.midi.getSignal(this.currentMidiId)()):e=m.audio.getSignal(this.currentSignalType)();const i=k[this.currentEase](e);this.onChange(i,this.currentBehaviour),this.rafId=requestAnimationFrame(this.loop)}},this.onChange=t.onChange,this.setupControllers(t.container)}setupControllers(t){const e=this.createSettingSelect("signal",["none","bass","mids","highs","volume","midi"],r=>this.setSignalType(r));this.signalSelect=e.select,t.appendChild(e.row),this.midiRow=o("div",{className:"cp-setting-row",style:"display: none;"});const i=o("label",{className:"cp-setting-label"},["Midi"]);this.midiBtn=o("button",{className:"cp-button cp-input-small"},["Learn"]),this.midiBtn.addEventListener("click",async()=>{if(this.midiBtn.textContent==="Listening..."){m.midi.cancelListen(),this.setMidiId(null);return}this.midiBtn.textContent="Listening...";const r=await m.midi.listen();this.setMidiId(r)}),this.midiRow.appendChild(i),this.midiRow.appendChild(this.midiBtn),t.appendChild(this.midiRow);const s=this.createSettingSelect("behaviour",["forward","backward","loopForward","loopBackward","pingpong"],r=>this.setBehaviour(r));this.behaviourRow=s.row,this.behaviourSelect=s.select,this.behaviourRow.style.display="none",this.behaviourSelect.value=this.currentBehaviour,t.appendChild(this.behaviourRow);const a=this.createSettingSelect("ease",Object.keys(k),r=>this.setEase(r));this.easeRow=a.row,this.easeSelect=a.select,this.easeRow.style.display="none",this.easeSelect.value=this.currentEase,t.appendChild(this.easeRow)}createSettingSelect(t,e,i){const s=o("div",{className:"cp-setting-row"}),a=o("label",{className:"cp-setting-label"},[t]),r=o("select",{className:"cp-select cp-input-small"});return e.forEach(h=>{const p=o("option",{value:h},[h]);r.appendChild(p)}),r.addEventListener("change",()=>i(r.value)),s.appendChild(a),s.appendChild(r),{row:s,select:r}}setSignalType(t){if(!t||t==="none")this.currentSignalType=null,this.currentMidiId=null,this.midiRow.style.display="none",this.easeRow.style.display="none",this.behaviourRow.style.display="none",this.stop(),this.signalSelect.value!=="none"&&(this.signalSelect.value="none");else{this.currentSignalType=t;const e=t==="midi";this.midiRow.style.display=e?"flex":"none",this.easeRow.style.display="flex",this.behaviourRow.style.display="flex",e||(this.currentMidiId=null,m.audio.ctx.state==="suspended"&&m.audio.setInput("microphone")),this.start(),this.signalSelect.value!==t&&(this.signalSelect.value=t)}}setMidiId(t){this.currentMidiId=t,this.midiBtn.textContent=t??"Learn"}setEase(t){this.currentEase=t,this.easeSelect.value!==t&&(this.easeSelect.value=t)}setBehaviour(t){this.currentBehaviour=t,this.behaviourSelect.value!==t&&(this.behaviourSelect.value=t)}start(){!this.rafId&&this.currentSignalType&&this.loop()}stop(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}save(){return{type:this.currentSignalType,midiId:this.currentMidiId,ease:this.currentEase,behaviour:this.currentBehaviour}}load(t){t&&(this.setSignalType(t.type),this.setMidiId(t.midiId||null),this.setEase(t.ease||"linear"),this.setBehaviour(t.behaviour||"forward"))}reset(){this.setSignalType("none"),this.setEase("linear"),this.setBehaviour("forward"),this.setMidiId(null)}}class j extends m{constructor(t,e,i={}){super(t,e,i),this.pingPongDirection=1,this.min=0,this.max=100,this.initialOptions=i,this.min=i.min??0,this.max=i.max??100;const s=o("details",{className:"cp-controller-details"}),a=o("summary",{className:"cp-controller-summary"});this.input=o("input",{type:"range",className:"cp-input-range",step:i.step??"any"}),i.min!==void 0&&(this.input.min=String(i.min)),i.max!==void 0&&(this.input.max=String(i.max)),this.input.value=String(this.value),this.display=o("span",{className:"cp-value-display"},[String(this.value.toFixed(1))]),this.input.addEventListener("input",()=>{const l=parseFloat(this.input.value);isNaN(l)||(this.setValue(l),this.display.textContent=String(l.toFixed(1)))}),this.input.addEventListener("click",l=>{l.stopPropagation()});const r=o("div",{className:"cp-controller-summary-content"});r.appendChild(this.input),r.appendChild(this.display),a.appendChild(r),s.appendChild(a);const h=o("div",{className:"cp-number-settings"}),p=this.createSetting("min",i.min,l=>this.setMin(l));this.minInput=p.input,h.appendChild(p.row);const c=this.createSetting("max",i.max,l=>this.setMax(l));this.maxInput=c.input,h.appendChild(c.row);const v=this.createSetting("step",i.step,l=>this.setStep(l));this.stepInput=v.input,h.appendChild(v.row);const f=o("hr",{className:"cp-separator"});h.appendChild(f),this.signalHandler=new R({container:h,onChange:(l,u)=>this.applySignal(l,u)}),s.appendChild(h),this.appendWidget(s)}setMin(t){typeof t=="number"&&(t=String(t)),t===""||isNaN(parseFloat(t))?this.input.removeAttribute("min"):(this.input.min=t,this.min=parseFloat(t)),this.minInput&&this.minInput.value!==t&&(this.minInput.value=t)}setMax(t){typeof t=="number"&&(t=String(t)),t===""||isNaN(parseFloat(t))?this.input.removeAttribute("max"):(this.input.max=t,this.max=parseFloat(t)),this.maxInput&&this.maxInput.value!==t&&(this.maxInput.value=t)}setStep(t){t===void 0&&(t=""),typeof t=="number"&&(t=String(t)),t===""||t==="any"||isNaN(parseFloat(t))?this.input.step="any":this.input.step=t,this.stepInput&&(t==="any"||t===""?this.stepInput.value="":this.stepInput.value!==t&&(this.stepInput.value=t))}applySignal(t,e){const i=this.max-this.min;let s;if(e==="forward")s=this.min+t*i;else if(e==="backward")s=this.max-t*i;else{const a=t*(i*.01);s=this.value,e==="loopForward"?(s+=a,s>this.max&&(s=this.min+(s-this.min)%i)):e==="loopBackward"?(s-=a,s<this.min&&(s=this.max-(this.max-s)%i)):e==="pingpong"&&(s+=a*this.pingPongDirection,s>=this.max?(s=this.max,this.pingPongDirection=-1):s<=this.min&&(s=this.min,this.pingPongDirection=1))}s=this.roundToStep(s),this.setValue(s),this.input.value=String(s),this.display.textContent=String(s.toFixed(1))}roundToStep(t){const e=this.input.step;if(e==="any"||e===""||isNaN(parseFloat(e)))return t;const i=parseFloat(e),s=this.min;return s+Math.round((t-s)/i)*i}createSetting(t,e,i){const s=o("div",{className:"cp-setting-row"}),a=o("label",{className:"cp-setting-label"},[t]),r=o("input",{type:"number",className:"cp-input-number cp-input-small",step:"any"});return e!==void 0&&(r.value=String(e)),r.addEventListener("input",()=>i(r.value)),s.appendChild(a),s.appendChild(r),{row:s,input:r}}updateDisplay(){this.input.value=String(this.value),this.display.textContent=String(this.value.toFixed(1))}save(){return{value:this.value,settings:{min:this.min,max:this.max,step:this.input.step,signal:this.signalHandler.save()}}}load(t){if(typeof t=="number")this.setValue(t),this.resetSettings();else if(typeof t=="object"&&t!==null&&"value"in t){const e=t.settings||{};e.min!==void 0?this.setMin(e.min):this.setMin(this.initialOptions.min!==void 0?this.initialOptions.min:""),e.max!==void 0?this.setMax(e.max):this.setMax(this.initialOptions.max!==void 0?this.initialOptions.max:""),e.step!==void 0?this.setStep(e.step):this.setStep(this.initialOptions.step);let i=t.value;!isNaN(this.min)&&i<this.min&&(i=this.min),!isNaN(this.max)&&i>this.max&&(i=this.max),this.setValue(i),this.signalHandler?.load(e.signal)}}reset(){this.setValue(this.initialValue),this.resetSettings()}resetSettings(){this.setMin(this.initialOptions.min!==void 0?this.initialOptions.min:""),this.setMax(this.initialOptions.max!==void 0?this.initialOptions.max:""),this.setStep(this.initialOptions.step),this.signalHandler?.reset()}}class z extends m{constructor(t,e,i){super(t,e,i),this.optionValues=[],this.select=o("select",{className:"cp-select"}),this.optionValues=i.options||[],this.optionValues.forEach((s,a)=>{const r=o("option",{value:String(a)},[String(s)]);this.select.appendChild(r)}),this.updateDisplay(),this.select.addEventListener("change",()=>{const s=parseInt(this.select.value),a=this.optionValues[s];this.setValue(a)}),this.appendWidget(this.select)}setOptions(t){this.select.innerHTML="",this.optionValues=t,this.optionValues.forEach((e,i)=>{const s=o("option",{value:String(i)},[String(e)]);this.select.appendChild(s)}),this.updateDisplay(),this.select.value===""&&this.optionValues.length>0&&this.setValue(this.optionValues[0])}updateDisplay(){const t=this.optionValues.indexOf(this.value);t!==-1&&(this.select.value=String(t))}}class $ extends m{constructor(t,e,i={}){const s={action:e};super(s,"action",i);const a=i.label??t;this.button=o("button",{className:"cp-button"},[String(a)]),this.button.addEventListener("click",()=>{const r=this.value;typeof r=="function"&&r(),this.emitChange(r)}),this.appendWidget(this.button)}updateDisplay(){}}class q extends m{constructor(t,e,i={}){super(t,e,i),this.input=o("input",{type:"checkbox",className:"cp-checkbox"}),this.input.checked=this.value,this.input.addEventListener("change",()=>{this.setValue(this.input.checked)}),this.appendWidget(this.input)}updateDisplay(){this.input.checked=this.value}}class H extends m{constructor(t,e,i){super(t,e,i),this.buttons=[],this.optionValues=[],this.container=o("div",{className:"cp-radios"}),this.optionValues=i.options||[],this.optionValues.forEach(s=>{const a=o("button",{className:"cp-button cp-radio"},[String(s)]);a.addEventListener("click",()=>{this.setValue(s)}),this.container.appendChild(a),this.buttons.push(a)}),this.updateDisplay(),this.appendWidget(this.container)}updateDisplay(){const t=this.value;this.buttons.forEach((e,i)=>{this.optionValues[i]===t?e.setAttribute("data-active","true"):e.removeAttribute("data-active")})}}class U extends m{constructor(t,e,i={}){super(t,e,i),this.input=o("input",{type:"color",className:"cp-input-color",value:this.value||"#000000"}),this.appendWidget(this.input),this.input.addEventListener("input",s=>{const a=s.target;this.setValue(a.value)}),this.updateDisplay()}updateDisplay(){this.input.value=this.value}}function _(n){const t=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;n=n.replace(t,(i,s,a,r)=>s+s+a+a+r+r);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(n);return e?[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]:[0,0,0]}function X(n,t,e){return"#"+((1<<24)+(Math.round(n)<<16)+(Math.round(t)<<8)+Math.round(e)).toString(16).slice(1)}function I(n){const t=n/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function A(n){return n<=.0031308?n*12.92*255:(1.055*Math.pow(n,1/2.4)-.055)*255}function Y(n,t,e){const[i,s,a]=_(n),[r,h,p]=_(t),c=I(i),v=I(s),f=I(a),l=I(r),u=I(h),g=I(p),S=c+e*(l-c),N=v+e*(u-v),C=f+e*(g-f),b=A(S),y=A(N),w=A(C);return X(b,y,w)}class W extends m{constructor(t,e,i={}){super(t,e,i),this.stops=[],this.pingPongDirection=1,this.animationT=0,this.manualPosition=0,this.initialOptions=i,this.stops=i.stops||[{color:"#000000",position:0},{color:"#ffffff",position:1}],this.sortStops();const s=o("details",{className:"cp-controller-details"}),a=o("summary",{className:"cp-controller-summary"}),r=o("div",{className:"cp-controller-summary-content"});this.displayColor=o("div",{className:"cp-color-swatch",style:`background-color: ${this.value}`}),this.displayText=o("span",{className:"cp-value-display"},[String(this.value)]),r.appendChild(this.displayColor),r.appendChild(this.displayText),a.appendChild(r),s.appendChild(a);const h=o("div",{className:"cp-number-settings"});this.stopsContainer=o("div",{className:"cp-stops-container"}),this.renderStops(),h.appendChild(this.stopsContainer);const p=o("button",{className:"cp-button"},["+ Add Stop"]);p.addEventListener("click",()=>{this.stops.push({color:"#ffffff",position:.5}),this.sortStops(),this.renderStops(),this.updateOutput()}),h.appendChild(p);const c=o("hr",{className:"cp-separator"});h.appendChild(c),this.signalHandler=new R({container:h,onChange:(v,f)=>this.applySignal(v,f)}),s.appendChild(h),this.appendWidget(s),this.updateOutput(0)}sortStops(){this.stops.sort((t,e)=>t.position-e.position)}renderStops(){this.stopsContainer.innerHTML="",this.stops.forEach((t,e)=>{const i=o("div",{className:"cp-setting-row"}),s=o("input",{type:"color",className:"cp-input-color",value:t.color});s.addEventListener("input",h=>{t.color=h.target.value,this.updateOutput()});const a=o("input",{type:"number",className:"cp-input-number cp-input-small",min:"0",max:"1",step:"0.01",value:String(t.position)});a.addEventListener("change",h=>{let p=parseFloat(h.target.value);isNaN(p)&&(p=0),t.position=Math.max(0,Math.min(1,p)),this.sortStops(),this.renderStops(),this.updateOutput()});const r=D(()=>{this.stops.splice(e,1),this.renderStops(),this.updateOutput()});i.appendChild(s),i.appendChild(a),i.appendChild(r),this.stopsContainer.appendChild(i)})}updateOutput(t=this.manualPosition){if(this.stops.length===0)return;if(this.stops.length===1){this.setValue(this.stops[0].color),this.updateDisplay();return}let e="#000000";if(t=Math.max(0,Math.min(1,t)),t<=this.stops[0].position)e=this.stops[0].color;else if(t>=this.stops[this.stops.length-1].position)e=this.stops[this.stops.length-1].color;else for(let i=0;i<this.stops.length-1;i++){const s=this.stops[i],a=this.stops[i+1];if(t>=s.position&&t<=a.position){const r=a.position-s.position,h=r===0?0:(t-s.position)/r;e=Y(s.color,a.color,h);break}}this.setValue(e),this.updateDisplay()}updateDisplay(){this.displayColor&&(this.displayColor.style.backgroundColor=this.value),this.displayText&&(this.displayText.textContent=this.value)}applySignal(t,e){let i=t;if(e==="forward")i=t;else if(e==="backward")i=1-t;else{const s=t*.05;e==="loopForward"?(this.animationT=(this.animationT+s)%1,i=this.animationT):e==="loopBackward"?(this.animationT=(this.animationT-s+1)%1,i=this.animationT):e==="pingpong"&&(this.animationT+=s*this.pingPongDirection,this.animationT>=1?(this.animationT=1,this.pingPongDirection=-1):this.animationT<=0&&(this.animationT=0,this.pingPongDirection=1),i=this.animationT)}this.updateOutput(i),this.manualPosition=i}save(){return{stops:this.stops,settings:{signal:this.signalHandler.save()}}}load(t){t&&t.stops&&(this.stops=t.stops,this.sortStops(),this.renderStops()),t&&t.settings&&this.signalHandler?.load(t.settings.signal)}reset(){this.stops=this.initialOptions.stops||[{color:"#000000",position:0},{color:"#ffffff",position:1}],this.sortStops(),this.renderStops(),this.signalHandler?.reset(),this.updateOutput(0)}}class J extends m{constructor(t,e,i={}){super(t,e,i),this.items=[],this.initialOptions=i,this.itemType=i.itemType||"string",this.items=this.parseValue(this.value);const s=o("details",{className:"cp-controller-details"}),a=o("summary",{className:"cp-controller-summary"}),r=o("div",{className:"cp-controller-summary-content"}),h=o("span",{className:"cp-value-display"},[`${this.items.length} items`]);r.appendChild(h),a.appendChild(r),s.appendChild(a);const p=o("div",{className:"cp-number-settings"});this.itemsContainer=o("div",{className:"cp-stops-container"}),this.renderItems(),p.appendChild(this.itemsContainer);const c=o("button",{className:"cp-button cp-input-small",style:"margin-top: 8px; width: 100%;"},["+ Add Item"]);c.addEventListener("click",()=>{this.addItem()}),p.appendChild(c),s.appendChild(p),this.appendWidget(s)}parseValue(t){return!t||t.trim()===""?[]:t.split(",").map(e=>e.trim())}serializeValue(){return this.items.join(",")}getDefaultItemValue(){switch(this.itemType){case"color":return"#ffffff";case"number":return"0";default:return""}}addItem(t){const e=t!==void 0?t:this.getDefaultItemValue();this.items.push(e),this.renderItems(),this.updateValue()}updateValue(){const t=this.serializeValue();this.setValue(t),this.updateSummary()}updateSummary(){const t=this.domElement.querySelector(".cp-value-display");t&&(t.textContent=`${this.items.length} items`)}renderItems(){this.itemsContainer.innerHTML="",this.items.forEach((t,e)=>{const i=o("div",{className:"cp-setting-row"});let s;this.itemType==="color"?s=o("input",{type:"color",className:"cp-input-color",value:t}):this.itemType==="number"?s=o("input",{type:"number",className:"cp-input-number cp-input-small",step:"any",value:t}):s=o("input",{type:"text",className:"cp-input-number cp-input-small",value:t}),s.addEventListener("input",r=>{this.items[e]=r.target.value,this.updateValue()});const a=D(()=>{this.items.splice(e,1),this.renderItems(),this.updateValue()});i.appendChild(s),i.appendChild(a),this.itemsContainer.appendChild(i)})}updateDisplay(){}save(){return[...this.items]}load(t){Array.isArray(t)?this.items=[...t]:typeof t=="string"&&(this.items=this.parseValue(t)),this.renderItems(),this.updateValue()}reset(){const t=this.initialValue||"";this.items=this.parseValue(t),this.renderItems(),this.updateValue()}}class tt{constructor(){this.frames=0,this.pollingInterval=1e3,this.prevTime=performance.now(),this.render=()=>{this.frames++;const t=performance.now();if(t>=this.prevTime+this.pollingInterval){const e=Math.round(this.frames*1e3/(t-this.prevTime));let i="";const s=performance.memory;s&&(i=` / ${Math.round(s.usedJSHeapSize/1048576)}MB`),this.domElement.textContent=`${e} FPS${i}`,this.prevTime=t,this.frames=0}this.rafId=requestAnimationFrame(this.render)},this.domElement=o("span",{className:"cp-stats"}),this.rafId=requestAnimationFrame(this.render)}destroy(){cancelAnimationFrame(this.rafId)}}class G{constructor(){this.controllers=[],this.folders=[]}addNumber(t,e,i={}){const s=new j(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addSelect(t,e,i={}){const s=new z(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addBoolean(t,e,i={}){const s=new q(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addButton(t,e,i={}){const s=new $(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addRadio(t,e,i={}){const s=new H(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addColor(t,e,i={}){const s=new U(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addGradient(t,e,i={}){const s=new W(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addArray(t,e,i={}){const s=new J(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addFolder(t){const e=new et(t);return this.contentElement.appendChild(e.domElement),this.folders.push(e),e}save(){const t={controllers:{},folders:{}};for(const e of this.controllers)typeof e.value!="function"&&(t.controllers[e.key]=e.save());for(const e of this.folders)t.folders[e.title]=e.save();return t}load(t){if(!t){this.reset();return}for(const e of this.controllers)if(typeof e.value!="function")if(t.controllers&&e.key in t.controllers){const i=t.controllers[e.key];i!==void 0&&e.load(i)}else e.reset();for(const e of this.folders){const i=t.folders?t.folders[e.title]:void 0;e.load(i)}}reset(){for(const t of this.controllers)typeof t.value!="function"&&t.reset();for(const t of this.folders)t.reset()}}class et extends G{constructor(t){super(),this.title=t,this.domElement=o("details",{className:"cp-folder",open:!0}),this.summaryElement=o("summary",{className:"cp-summary"},[t]),this.domElement.appendChild(this.summaryElement),this.contentElement=o("div",{className:"cp-content cp-folder-content"}),this.domElement.appendChild(this.contentElement),this.domElement.appendChild(o("hr",{className:"cp-separator"}))}}class st extends G{constructor(t,e={}){super(),this.domElement=o("details",{className:"cp-root",open:!0}),this.summaryElement=o("summary",{className:"cp-summary cp-summary-root"}),this.domElement.appendChild(this.summaryElement);const i=o("span",{},[e.title||"ControlPanel"]);this.summaryElement.appendChild(i),this.stats=new tt,this.summaryElement.appendChild(this.stats.domElement),this.contentElement=o("div",{className:"cp-content"}),this.domElement.appendChild(this.contentElement);const s=this.addFolder("_Signals"),a={audioInput:null,fftSize:2048};s.addRadio(a,"audioInput",{label:"Audio Signal",options:["microphone","browser"]}).onChange(l=>{x.setInput(l)}),s.addSelect(a,"fftSize",{label:"FFT Size",options:[256,512,1024,2048]}).onChange(l=>{x.setFFTSize(l)}),s.addNumber(x,"smoothingTimeConstant",{min:0,max:.99,step:.01,label:"Smoothing"}).onChange(l=>{x.analyser.smoothingTimeConstant=l}),s.addNumber(x,"spectrumBoost",{min:1,max:5,step:.1,label:"Compression"}),t?t.appendChild(this.domElement):document.body.appendChild(this.domElement);const r=e.title||"ControlPanel";this.presetStoragePrefix=`cp-presets-${r}-`;const h=this.addFolder("_User Presets"),p=()=>{const l=["Default"];if(typeof localStorage>"u")return l;for(let u=0;u<localStorage.length;u++){const g=localStorage.key(u);if(g&&g.startsWith(this.presetStoragePrefix)){const S=g.substring(this.presetStoragePrefix.length);S!=="Default"&&!l.includes(S)&&l.push(S)}}return l.sort()},c={selected:"Default",save:()=>{const l=prompt("Preset Name:",c.selected);if(l){if(l==="Default"){alert("Cannot overwrite Default preset");return}const u=this.presetStoragePrefix+l;this.saveToLocalStorage(u);const g=p();f.setOptions(g),c.selected=l,f.setValue(l)}},load:()=>{const l=c.selected,u=this.presetStoragePrefix+l;this.loadFromLocalStorage(u),c.selected=l,f.setValue(l)},delete:()=>{if(c.selected==="Default"){alert("Cannot delete Default preset");return}if(confirm(`Delete preset "${c.selected}"?`)){const l=this.presetStoragePrefix+c.selected;localStorage.removeItem(l);const u=p();f.setOptions(u),c.selected="Default",f.setValue("Default"),this.reset()}},export:()=>{const l=this.save(),u=L=>{const E={controllers:{},folders:{}};for(const[T,V]of Object.entries(L.controllers))T.startsWith("_")||(E.controllers[T]=V);for(const[T,V]of Object.entries(L.folders))T.startsWith("_")||(E.folders[T]=u(V));return E},g=u(l),S={_presetName:c.selected||"CustomPreset",_exportDate:new Date().toISOString(),_instructions:"To add as factory preset: Copy 'controllers' and 'folders' fields into the presets.json file",...g},N=JSON.stringify(S,null,2),C=new Blob([N],{type:"application/json"}),b=URL.createObjectURL(C),y=document.createElement("a");y.href=b;const w=new Date().toISOString().split("T")[0],Z=c.selected.replace(/[^a-z0-9]/gi,"-").toLowerCase();y.download=`${r.toLowerCase()}-preset-${Z}-${w}.json`,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(b)},import:()=>{const l=document.createElement("input");l.type="file",l.accept=".json",l.onchange=u=>{const g=u.target.files?.[0];if(!g)return;const S=new FileReader;S.onload=N=>{try{const C=N.target?.result,b=JSON.parse(C),y={controllers:b.controllers||{},folders:b.folders||{}};if(!y.controllers||!y.folders){alert("Invalid preset file: missing 'controllers' or 'folders'");return}this.load(y);const w=b._presetName||"ImportedPreset";if(confirm(`Preset loaded! Save as "${w}" to User Presets?`)){const L=this.presetStoragePrefix+w;this.saveToLocalStorage(L);const E=p();f.setOptions(E),c.selected=w,f.setValue(w)}}catch(C){alert(`Failed to import preset: ${C instanceof Error?C.message:"Invalid JSON"}`),console.error("Import error:",C)}},S.readAsText(g)},l.click()}},v=p(),f=h.addSelect(c,"selected",{label:"Preset",options:v});h.addButton("Load",()=>c.load()),h.addButton("Save / New",()=>c.save()),h.addButton("Delete",()=>c.delete()),h.addButton("Export JSON",()=>c.export()),h.addButton("Import JSON",()=>c.import())}saveToLocalStorage(t){const e=this.save();try{localStorage.setItem(t,JSON.stringify(e))}catch(i){console.warn("ControlPanel: Failed to save to localStorage",i)}}loadFromLocalStorage(t){try{const e=localStorage.getItem(t);if(e){const i=JSON.parse(e);this.load(i)}}catch(e){console.warn("ControlPanel: Failed to load from localStorage",e)}}saveDefaultPreset(){const t=this.presetStoragePrefix+"Default";this.save(),this.saveToLocalStorage(t)}destroy(){this.stats.destroy(),this.domElement.remove(),this.controllers=[],this.folders=[]}}d.ArrayController=J,d.AudioSignals=B,d.BooleanController=q,d.ButtonController=$,d.ColorController=U,d.ControlPanel=st,d.Controller=m,d.GradientController=W,d.MidiSignals=F,d.NumberController=j,d.RadioController=H,d.SelectController=z,d.audioSignals=x,d.midiSignals=P,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(d,N){typeof exports=="object"&&typeof module<"u"?N(exports):typeof define=="function"&&define.amd?define(["exports"],N):(d=typeof globalThis<"u"?globalThis:d||self,N(d.ControlPanel={}))})(this,(function(d){"use strict";const N=`
2
+ .cp-root {
3
+ position: fixed;
4
+ top: 10px;
5
+ right: 10px;
6
+ width: 280px;
7
+ max-height: 90vh;
8
+ overflow: auto;
9
+ background: transparent;
10
+ color: #fff;
11
+ mix-blend-mode: exclusion;
12
+ font-family:
13
+ -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial,
14
+ sans-serif;
15
+ font-size: 10px;
16
+ line-height: 1.2;
17
+ padding: 8px;
18
+ z-index: 100;
19
+ }
20
+
21
+ .cp-root::-webkit-scrollbar {
22
+ width: 1px;
23
+ }
24
+ .cp-root::-webkit-scrollbar-track {
25
+ background: transparent;
26
+ }
27
+ .cp-root::-webkit-scrollbar-thumb {
28
+ background: rgba(255, 255, 255, 0.5);
29
+ }
30
+
31
+ .cp-summary {
32
+ cursor: pointer;
33
+ user-select: none;
34
+ font-weight: bold;
35
+ outline: none;
36
+ }
37
+
38
+ .cp-summary-root {
39
+ position: sticky;
40
+ top: 0;
41
+ }
42
+
43
+ .cp-stats {
44
+ float: right;
45
+ font-weight: normal;
46
+ opacity: 0.6;
47
+ font-size: 0.9em;
48
+ font-variant-numeric: tabular-nums;
49
+ }
50
+
51
+ .cp-content {
52
+ margin-top: 4px;
53
+ display: flex;
54
+ flex-direction: column;
55
+ gap: 6px;
56
+ }
57
+
58
+ .cp-folder {
59
+ width: 100%;
60
+ }
61
+
62
+ .cp-folder-content {
63
+ margin: 0 0 6px 0;
64
+ padding: 4px 0 0 9px;
65
+ }
66
+
67
+ .cp-controller {
68
+ display: flex;
69
+ }
70
+
71
+ .cp-label {
72
+ margin: auto 0;
73
+ width: 50%;
74
+ flex-shrink: 0;
75
+ overflow: hidden;
76
+ text-overflow: ellipsis;
77
+ white-space: nowrap;
78
+ user-select: none;
79
+ padding-right: 8px;
80
+ opacity: 0.8;
81
+ }
82
+
83
+ .cp-input-number {
84
+ width: 50%;
85
+ background: transparent;
86
+ border: 1px solid #fff;
87
+ color: inherit;
88
+ padding: 2px 4px;
89
+ border-radius: 2px;
90
+ font-family: inherit;
91
+ font-size: inherit;
92
+ }
93
+
94
+ .cp-input-number:focus {
95
+ outline: none;
96
+ border-color: #fff;
97
+ background: transparent;
98
+ }
99
+
100
+ .cp-select {
101
+ width: 50%;
102
+ background: rgba(255, 255, 255, 0.3);
103
+ border: none;
104
+ padding: 2px 4px;
105
+ border-radius: 2px;
106
+ font-family: inherit;
107
+ font-size: inherit;
108
+ }
109
+
110
+ .cp-checkbox {
111
+ margin: auto 0;
112
+ }
113
+
114
+ .cp-button {
115
+ width: 100%;
116
+ background: rgba(255, 255, 255, 0.3);
117
+ border: none;
118
+ padding: 4px 2px;
119
+ border-radius: 2px;
120
+ cursor: pointer;
121
+ text-align: center;
122
+ font-family: inherit;
123
+ font-size: inherit;
124
+ transition: background 0.1s;
125
+ }
126
+
127
+ .cp-button:hover {
128
+ background: rgba(255, 255, 255, 0.4);
129
+ }
130
+
131
+ .cp-button:active {
132
+ background: rgba(255, 255, 255, 0.2);
133
+ transform: translateY(1px);
134
+ }
135
+
136
+ .cp-controller[data-disabled="true"] {
137
+ opacity: 0.5;
138
+ pointer-events: none;
139
+ cursor: not-allowed;
140
+ }
141
+
142
+ .cp-controller-details {
143
+ width: 50%;
144
+ }
145
+
146
+ .cp-controller-summary {
147
+ cursor: pointer;
148
+ outline: none;
149
+ }
150
+
151
+ .cp-controller-summary-content {
152
+ display: inline-flex;
153
+ align-items: center;
154
+ gap: 6px;
155
+ width: calc(100% - 16px);
156
+ vertical-align: middle;
157
+ }
158
+
159
+ .cp-input-range {
160
+ -webkit-appearance: none;
161
+ flex: 1;
162
+ min-width: 0;
163
+ height: 2px;
164
+ background: rgba(255, 255, 255, 0.3);
165
+ margin: 0;
166
+ vertical-align: middle;
167
+ cursor: grab;
168
+ }
169
+ .cp-input-range::-webkit-slider-thumb {
170
+ -webkit-appearance: none;
171
+ width: 4px;
172
+ height: 8px;
173
+ border-radius: 1px;
174
+ background: #fff;
175
+ cursor: grab;
176
+ }
177
+ .cp-input-range::-moz-range-thumb {
178
+ width: 4px;
179
+ height: 16px;
180
+ background: #fff;
181
+ cursor: grab;
182
+ }
183
+
184
+ .cp-input-range:active {
185
+ cursor: grabbing;
186
+ }
187
+
188
+ .cp-value-display {
189
+ min-width: 24px;
190
+ text-align: right;
191
+ font-variant-numeric: tabular-nums;
192
+ font-size: 0.9em;
193
+ opacity: 0.8;
194
+ user-select: none;
195
+ }
196
+
197
+ .cp-number-settings {
198
+ margin-top: 4px;
199
+ background: transparent;
200
+ border: 1px solid rgba(255, 255, 255, 0.2);
201
+ padding: 4px;
202
+ border-radius: 4px;
203
+ display: flex;
204
+ flex-direction: column;
205
+ gap: 4px;
206
+ }
207
+
208
+ .cp-separator {
209
+ border: none;
210
+ border-top: 1px solid rgba(255, 255, 255, 0.3);
211
+ margin: 4px 0;
212
+ width: 100%;
213
+ }
214
+
215
+ .cp-setting-row {
216
+ display: flex;
217
+ align-items: center;
218
+ gap: 4px;
219
+ }
220
+
221
+ .cp-setting-label {
222
+ width: 50%;
223
+ font-size: 0.9em;
224
+ opacity: 0.7;
225
+ }
226
+
227
+ .cp-input-small {
228
+ width: 50%;
229
+ }
230
+
231
+ .cp-radios {
232
+ width: 50%;
233
+ display: flex;
234
+ gap: 2px;
235
+ }
236
+
237
+ .cp-radio {
238
+ flex: 1;
239
+ font-size: 0.9em;
240
+ padding: 4px 2px;
241
+ height: 100%;
242
+ }
243
+
244
+ .cp-radio[data-active="true"] {
245
+ background: rgba(255, 255, 255, 0.2);
246
+ border-color: #fff;
247
+ font-weight: bold;
248
+ }
249
+
250
+ .cp-button-delete {
251
+ width: 24px;
252
+ padding: 0;
253
+ display: flex;
254
+ align-items: center;
255
+ justify-content: center;
256
+ line-height: 1;
257
+ }
258
+
259
+ .cp-input-color {
260
+ padding: 0;
261
+ margin: 0;
262
+ border: none;
263
+ background: none;
264
+ outline: none;
265
+
266
+ isolation: isolate;
267
+ mix-blend-mode: normal;
268
+ cursor: pointer;
269
+ }
270
+
271
+ .cp-color-swatch {
272
+ width: 10px;
273
+ height: 10px;
274
+ margin-right: 8px;
275
+ }
276
+
277
+ .cp-stops-container {
278
+ display: flex;
279
+ flex-direction: column;
280
+ gap: 4px;
281
+ }
282
+ `;let O=!1;function X(){if(O)return;const n=document.createElement("style");n.id="control-panel-styles",n.textContent=N,document.head.appendChild(n),O=!0}function r(n,t={},e=[]){const i=document.createElement(n);for(const[s,a]of Object.entries(t))s==="className"?i.className=String(a):s==="style"&&typeof a=="object"?Object.assign(i.style,a):s==="open"&&typeof a=="boolean"?a?i.setAttribute("open",""):i.removeAttribute("open"):typeof a!="object"&&i.setAttribute(s,String(a));for(const s of e)typeof s=="string"?i.appendChild(document.createTextNode(s)):i.appendChild(s);return i}function F(n){const t=r("button",{className:"cp-button cp-button-delete"},["×"]);return t.addEventListener("click",n),t}function tt(n){return n.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}function B(n,t,e){return Math.min(Math.max(n,t),e)}function et(n,t,e){if(t.length!==e.length)throw new Error("Input and output ranges must have the same length");if(t.length<2)throw new Error("Input and output ranges must have at least two values");let i=0;for(;i<t.length-1&&n>t[i+1];)i++;if(i===t.length-1)return e[e.length-1];if(i===0&&n<t[0])return e[0];const s=t[i],a=t[i+1],o=e[i],c=e[i+1];return(n-s)/(a-s)*(c-o)+o}class P{constructor(){this.source=null,this.stream=null,this.fftSize=2048,this.smoothingTimeConstant=.92,this.spectrumBoost=2,this.levels={bass:0,mids:0,highs:0,volume:0},this.peaks={bass:0,mids:0,highs:0,volume:0},this._isAnalyzing=!1,this.loop=()=>{this._isAnalyzing&&(requestAnimationFrame(this.loop),this.update())};const t=window.AudioContext||window.webkitAudioContext;this.ctx=new t,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.waveformArray=new Uint8Array(this.analyser.frequencyBinCount)}setFFTSize(t){this.fftSize=t,this.analyser.fftSize=t,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.waveformArray=new Uint8Array(this.analyser.frequencyBinCount)}async setInput(t){try{let e;t==="browser"?e=navigator.mediaDevices.getDisplayMedia({audio:!0,video:!0}):e=navigator.mediaDevices.getUserMedia({audio:!0});const i=await e;this.ctx.state==="suspended"&&this.ctx.resume(),this.source&&this.source.disconnect(),this.stream&&this.stream.getTracks().forEach(s=>s.stop()),this.stream=i,this.source=this.ctx.createMediaStreamSource(this.stream),this.source.connect(this.analyser),this._isAnalyzing=!0,this.loop()}catch(e){console.error("Error accessing audio input:",e),this._isAnalyzing=!1}}update(){if(this.analyser.getByteFrequencyData(this.dataArray),this.analyser.getByteTimeDomainData(this.waveformArray),this.spectrumBoost!==1){const h=this.dataArray.length;for(let p=0;p<h;p++){const f=1+p/h*(this.spectrumBoost-1);this.dataArray[p]=Math.min(255,this.dataArray[p]*f)}}const t=[2,10],e=[10,150],i=[150,600],s=this.getAverage(t[0],t[1]),a=this.getAverage(e[0],e[1]),o=this.getAverage(i[0],i[1]),c=this.getAverage(0,i[1]);this.processLevel("bass",s),this.processLevel("mids",a),this.processLevel("highs",o),this.processLevel("volume",c)}processLevel(t,e){this.peaks[t]-=5e-4,this.peaks[t]=B(this.peaks[t],.1,1),e>this.peaks[t]&&(this.peaks[t]=e),this.levels[t]=B(et(e,[0,this.peaks[t]],[0,1]),0,1)}getAverage(t,e){let i=0;const s=e-t;if(s<=0)return 0;for(let a=t;a<e;a++)i+=this.dataArray[a];return i/s/255}getSignal(t){return()=>this.levels[t]}}const w=new P;class z{constructor(){this.midiAccess=null,this.values=new Map,this.isListening=!1,this.resolveListen=null,this.listeningCallback=null,this.init()}async init(){if(typeof navigator<"u"&&navigator.requestMIDIAccess)try{this.midiAccess=await navigator.requestMIDIAccess(),this.setupInputs(),this.midiAccess.onstatechange=t=>{t.port.type==="input"&&t.port.state==="connected"&&this.setupInputs()}}catch(t){console.warn("MIDI Access failed",t)}}setupInputs(){if(!this.midiAccess)return;const t=this.midiAccess.inputs.values();for(const e of t)e.onmidimessage=this.handleMessage.bind(this)}handleMessage(t){const e=t.data,[i]=e;if((i&240)>=240)return;const a=this.getIdFromMessage(t),o=this.normalizeValue(e);this.values.set(a,o),this.isListening&&this.resolveListen&&o>0&&(this.resolveListen(a),this.isListening=!1,this.resolveListen=null,this.listeningCallback&&this.listeningCallback())}getIdFromMessage(t){const e=t.data,[i,s]=e,a=i&240,o=t.currentTarget.name||"unknown",c=a===144||a===128?"note":"ctrl",h=o.replace(/[^a-zA-Z0-9]/g,"");return`${s}_${c}_${h}`}normalizeValue(t){const[e,i,s]=t,a=e&240;return a===144?s>0?1:0:a===128?0:a===176?s/127:0}listen(){return this.isListening=!0,new Promise(t=>{this.resolveListen=t})}cancelListen(){this.isListening=!1,this.resolveListen=null}getSignal(t){return()=>this.values.get(t)??0}}const j=new z,k=class k{constructor(t,e,i={}){this.changeFns=new Set,this.object=t,this.property=e,this.key=i.id??e,this.initialValue=this.object[this.property],this.domElement=r("div",{className:"cp-controller"});const s=i.label??tt(e),a=r("label",{className:"cp-label"},[String(s)]);a.setAttribute("title",String(s)),this.domElement.appendChild(a),i.disabled&&this.domElement.setAttribute("data-disabled","true")}get value(){return this.object[this.property]}setValue(t,e=!0){this.object[this.property]=t,e&&this.emitChange(t),this.updateDisplay()}save(){return this.value}load(t){this.setValue(t)}reset(){this.setValue(this.initialValue)}onChange(t){return this.changeFns.add(t),this}emitChange(t){for(const e of this.changeFns)e(t)}appendWidget(t){this.domElement.appendChild(t)}};k.audio=w,k.midi=j;let m=k;const R={linear:n=>n,quadIn:n=>n*n,quadOut:n=>n*(2-n),quadInOut:n=>n<.5?2*n*n:-1+(4-2*n)*n,cubicIn:n=>n*n*n,cubicOut:n=>--n*n*n+1,cubicInOut:n=>n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1,expoIn:n=>n===0?0:Math.pow(2,10*(n-1)),expoOut:n=>n===1?1:-Math.pow(2,-10*n)+1,expoInOut:n=>n===0||n===1?n:(n*=2)<1?.5*Math.pow(2,10*(n-1)):.5*(-Math.pow(2,-10*--n)+2),sineIn:n=>1-Math.cos(n*Math.PI/2),sineOut:n=>Math.sin(n*Math.PI/2),sineInOut:n=>-(Math.cos(Math.PI*n)-1)/2};class ${constructor(t){this.rafId=null,this.currentSignalType=null,this.currentMidiId=null,this.currentEase="linear",this.currentBehaviour="forward",this.loop=()=>{if(this.currentSignalType){let e=0;this.currentSignalType==="midi"?this.currentMidiId&&(e=m.midi.getSignal(this.currentMidiId)()):e=m.audio.getSignal(this.currentSignalType)();const i=R[this.currentEase](e);this.onChange(i,this.currentBehaviour),this.rafId=requestAnimationFrame(this.loop)}},this.onChange=t.onChange,this.setupControllers(t.container)}setupControllers(t){const e=this.createSettingSelect("signal",["none","bass","mids","highs","volume","midi"],o=>this.setSignalType(o));this.signalSelect=e.select,t.appendChild(e.row),this.midiRow=r("div",{className:"cp-setting-row",style:"display: none;"});const i=r("label",{className:"cp-setting-label"},["Midi"]);this.midiBtn=r("button",{className:"cp-button cp-input-small"},["Learn"]),this.midiBtn.addEventListener("click",async()=>{if(this.midiBtn.textContent==="Listening..."){m.midi.cancelListen(),this.setMidiId(null);return}this.midiBtn.textContent="Listening...";const o=await m.midi.listen();this.setMidiId(o)}),this.midiRow.appendChild(i),this.midiRow.appendChild(this.midiBtn),t.appendChild(this.midiRow);const s=this.createSettingSelect("behaviour",["forward","backward","loopForward","loopBackward","pingpong"],o=>this.setBehaviour(o));this.behaviourRow=s.row,this.behaviourSelect=s.select,this.behaviourRow.style.display="none",this.behaviourSelect.value=this.currentBehaviour,t.appendChild(this.behaviourRow);const a=this.createSettingSelect("ease",Object.keys(R),o=>this.setEase(o));this.easeRow=a.row,this.easeSelect=a.select,this.easeRow.style.display="none",this.easeSelect.value=this.currentEase,t.appendChild(this.easeRow)}createSettingSelect(t,e,i){const s=r("div",{className:"cp-setting-row"}),a=r("label",{className:"cp-setting-label"},[t]),o=r("select",{className:"cp-select cp-input-small"});return e.forEach(c=>{const h=r("option",{value:c},[c]);o.appendChild(h)}),o.addEventListener("change",()=>i(o.value)),s.appendChild(a),s.appendChild(o),{row:s,select:o}}setSignalType(t){if(!t||t==="none")this.currentSignalType=null,this.currentMidiId=null,this.midiRow.style.display="none",this.easeRow.style.display="none",this.behaviourRow.style.display="none",this.stop(),this.signalSelect.value!=="none"&&(this.signalSelect.value="none");else{this.currentSignalType=t;const e=t==="midi";this.midiRow.style.display=e?"flex":"none",this.easeRow.style.display="flex",this.behaviourRow.style.display="flex",e||(this.currentMidiId=null,m.audio.ctx.state==="suspended"&&m.audio.setInput("microphone")),this.start(),this.signalSelect.value!==t&&(this.signalSelect.value=t)}}setMidiId(t){this.currentMidiId=t,this.midiBtn.textContent=t??"Learn"}setEase(t){this.currentEase=t,this.easeSelect.value!==t&&(this.easeSelect.value=t)}setBehaviour(t){this.currentBehaviour=t,this.behaviourSelect.value!==t&&(this.behaviourSelect.value=t)}start(){!this.rafId&&this.currentSignalType&&this.loop()}stop(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}save(){return{type:this.currentSignalType,midiId:this.currentMidiId,ease:this.currentEase,behaviour:this.currentBehaviour}}load(t){t&&(this.setSignalType(t.type),this.setMidiId(t.midiId||null),this.setEase(t.ease||"linear"),this.setBehaviour(t.behaviour||"forward"))}reset(){this.setSignalType("none"),this.setEase("linear"),this.setBehaviour("forward"),this.setMidiId(null)}}class q extends m{constructor(t,e,i={}){super(t,e,i),this.pingPongDirection=1,this.min=0,this.max=100,this.initialOptions=i,this.min=i.min??0,this.max=i.max??100;const s=r("details",{className:"cp-controller-details"}),a=r("summary",{className:"cp-controller-summary"});this.input=r("input",{type:"range",className:"cp-input-range",step:i.step??"any"}),i.min!==void 0&&(this.input.min=String(i.min)),i.max!==void 0&&(this.input.max=String(i.max)),this.input.value=String(this.value),this.display=r("span",{className:"cp-value-display"},[String(this.value.toFixed(1))]),this.input.addEventListener("input",()=>{const l=parseFloat(this.input.value);isNaN(l)||(this.setValue(l),this.display.textContent=String(l.toFixed(1)))}),this.input.addEventListener("click",l=>{l.stopPropagation()});const o=r("div",{className:"cp-controller-summary-content"});o.appendChild(this.input),o.appendChild(this.display),a.appendChild(o),s.appendChild(a);const c=r("div",{className:"cp-number-settings"}),h=this.createSetting("min",i.min,l=>this.setMin(l));this.minInput=h.input,c.appendChild(h.row);const p=this.createSetting("max",i.max,l=>this.setMax(l));this.maxInput=p.input,c.appendChild(p.row);const b=this.createSetting("step",i.step,l=>this.setStep(l));this.stepInput=b.input,c.appendChild(b.row);const f=r("hr",{className:"cp-separator"});c.appendChild(f),this.signalHandler=new $({container:c,onChange:(l,u)=>this.applySignal(l,u)}),s.appendChild(c),this.appendWidget(s)}setMin(t){typeof t=="number"&&(t=String(t)),t===""||isNaN(parseFloat(t))?this.input.removeAttribute("min"):(this.input.min=t,this.min=parseFloat(t)),this.minInput&&this.minInput.value!==t&&(this.minInput.value=t)}setMax(t){typeof t=="number"&&(t=String(t)),t===""||isNaN(parseFloat(t))?this.input.removeAttribute("max"):(this.input.max=t,this.max=parseFloat(t)),this.maxInput&&this.maxInput.value!==t&&(this.maxInput.value=t)}setStep(t){t===void 0&&(t=""),typeof t=="number"&&(t=String(t)),t===""||t==="any"||isNaN(parseFloat(t))?this.input.step="any":this.input.step=t,this.stepInput&&(t==="any"||t===""?this.stepInput.value="":this.stepInput.value!==t&&(this.stepInput.value=t))}applySignal(t,e){const i=this.max-this.min;let s;if(e==="forward")s=this.min+t*i;else if(e==="backward")s=this.max-t*i;else{const a=t*(i*.01);s=this.value,e==="loopForward"?(s+=a,s>this.max&&(s=this.min+(s-this.min)%i)):e==="loopBackward"?(s-=a,s<this.min&&(s=this.max-(this.max-s)%i)):e==="pingpong"&&(s+=a*this.pingPongDirection,s>=this.max?(s=this.max,this.pingPongDirection=-1):s<=this.min&&(s=this.min,this.pingPongDirection=1))}s=this.roundToStep(s),this.setValue(s),this.input.value=String(s),this.display.textContent=String(s.toFixed(1))}roundToStep(t){const e=this.input.step;if(e==="any"||e===""||isNaN(parseFloat(e)))return t;const i=parseFloat(e),s=this.min;return s+Math.round((t-s)/i)*i}createSetting(t,e,i){const s=r("div",{className:"cp-setting-row"}),a=r("label",{className:"cp-setting-label"},[t]),o=r("input",{type:"number",className:"cp-input-number cp-input-small",step:"any"});return e!==void 0&&(o.value=String(e)),o.addEventListener("input",()=>i(o.value)),s.appendChild(a),s.appendChild(o),{row:s,input:o}}updateDisplay(){this.input.value=String(this.value),this.display.textContent=String(this.value.toFixed(1))}save(){return{value:this.value,settings:{min:this.min,max:this.max,step:this.input.step,signal:this.signalHandler.save()}}}load(t){if(typeof t=="number")this.setValue(t),this.resetSettings();else if(typeof t=="object"&&t!==null&&"value"in t){const e=t.settings||{};e.min!==void 0?this.setMin(e.min):this.setMin(this.initialOptions.min!==void 0?this.initialOptions.min:""),e.max!==void 0?this.setMax(e.max):this.setMax(this.initialOptions.max!==void 0?this.initialOptions.max:""),e.step!==void 0?this.setStep(e.step):this.setStep(this.initialOptions.step);let i=t.value;!isNaN(this.min)&&i<this.min&&(i=this.min),!isNaN(this.max)&&i>this.max&&(i=this.max),this.setValue(i),this.signalHandler?.load(e.signal)}}reset(){this.setValue(this.initialValue),this.resetSettings()}resetSettings(){this.setMin(this.initialOptions.min!==void 0?this.initialOptions.min:""),this.setMax(this.initialOptions.max!==void 0?this.initialOptions.max:""),this.setStep(this.initialOptions.step),this.signalHandler?.reset()}}class H extends m{constructor(t,e,i){super(t,e,i),this.optionValues=[],this.select=r("select",{className:"cp-select"}),this.optionValues=i.options||[],this.optionValues.forEach((s,a)=>{const o=r("option",{value:String(a)},[String(s)]);this.select.appendChild(o)}),this.updateDisplay(),this.select.addEventListener("change",()=>{const s=parseInt(this.select.value),a=this.optionValues[s];this.setValue(a)}),this.appendWidget(this.select)}setOptions(t){this.select.innerHTML="",this.optionValues=t,this.optionValues.forEach((e,i)=>{const s=r("option",{value:String(i)},[String(e)]);this.select.appendChild(s)}),this.updateDisplay(),this.select.value===""&&this.optionValues.length>0&&this.setValue(this.optionValues[0])}updateDisplay(){const t=this.optionValues.indexOf(this.value);t!==-1&&(this.select.value=String(t))}}class U extends m{constructor(t,e,i={}){const s={action:e};super(s,"action",i);const a=i.label??t;this.button=r("button",{className:"cp-button"},[String(a)]),this.button.addEventListener("click",()=>{const o=this.value;typeof o=="function"&&o(),this.emitChange(o)}),this.appendWidget(this.button)}updateDisplay(){}}class _ extends m{constructor(t,e,i={}){super(t,e,i),this.input=r("input",{type:"checkbox",className:"cp-checkbox"}),this.input.checked=this.value,this.input.addEventListener("change",()=>{this.setValue(this.input.checked)}),this.appendWidget(this.input)}updateDisplay(){this.input.checked=this.value}}class W extends m{constructor(t,e,i){super(t,e,i),this.buttons=[],this.optionValues=[],this.container=r("div",{className:"cp-radios"}),this.optionValues=i.options||[],this.optionValues.forEach(s=>{const a=r("button",{className:"cp-button cp-radio"},[String(s)]);a.addEventListener("click",()=>{this.setValue(s)}),this.container.appendChild(a),this.buttons.push(a)}),this.updateDisplay(),this.appendWidget(this.container)}updateDisplay(){const t=this.value;this.buttons.forEach((e,i)=>{this.optionValues[i]===t?e.setAttribute("data-active","true"):e.removeAttribute("data-active")})}}class J extends m{constructor(t,e,i={}){super(t,e,i),this.input=r("input",{type:"color",className:"cp-input-color",value:this.value||"#000000"}),this.appendWidget(this.input),this.input.addEventListener("input",s=>{const a=s.target;this.setValue(a.value)}),this.updateDisplay()}updateDisplay(){this.input.value=this.value}}function G(n){const t=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;n=n.replace(t,(i,s,a,o)=>s+s+a+a+o+o);const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(n);return e?[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]:[0,0,0]}function st(n,t,e){return"#"+((1<<24)+(Math.round(n)<<16)+(Math.round(t)<<8)+Math.round(e)).toString(16).slice(1)}function I(n){const t=n/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function A(n){return n<=.0031308?n*12.92*255:(1.055*Math.pow(n,1/2.4)-.055)*255}function it(n,t,e){const[i,s,a]=G(n),[o,c,h]=G(t),p=I(i),b=I(s),f=I(a),l=I(o),u=I(c),g=I(h),v=p+e*(l-p),E=b+e*(u-b),S=f+e*(g-f),x=A(v),y=A(E),C=A(S);return st(x,y,C)}class Z extends m{constructor(t,e,i={}){super(t,e,i),this.stops=[],this.pingPongDirection=1,this.animationT=0,this.manualPosition=0,this.initialOptions=i,this.stops=i.stops||[{color:"#000000",position:0},{color:"#ffffff",position:1}],this.sortStops();const s=r("details",{className:"cp-controller-details"}),a=r("summary",{className:"cp-controller-summary"}),o=r("div",{className:"cp-controller-summary-content"});this.displayColor=r("div",{className:"cp-color-swatch",style:`background-color: ${this.value}`}),this.displayText=r("span",{className:"cp-value-display"},[String(this.value)]),o.appendChild(this.displayColor),o.appendChild(this.displayText),a.appendChild(o),s.appendChild(a);const c=r("div",{className:"cp-number-settings"});this.stopsContainer=r("div",{className:"cp-stops-container"}),this.renderStops(),c.appendChild(this.stopsContainer);const h=r("button",{className:"cp-button"},["+ Add Stop"]);h.addEventListener("click",()=>{this.stops.push({color:"#ffffff",position:.5}),this.sortStops(),this.renderStops(),this.updateOutput()}),c.appendChild(h);const p=r("hr",{className:"cp-separator"});c.appendChild(p),this.signalHandler=new $({container:c,onChange:(b,f)=>this.applySignal(b,f)}),s.appendChild(c),this.appendWidget(s),this.updateOutput(0)}sortStops(){this.stops.sort((t,e)=>t.position-e.position)}renderStops(){this.stopsContainer.innerHTML="",this.stops.forEach((t,e)=>{const i=r("div",{className:"cp-setting-row"}),s=r("input",{type:"color",className:"cp-input-color",value:t.color});s.addEventListener("input",c=>{t.color=c.target.value,this.updateOutput()});const a=r("input",{type:"number",className:"cp-input-number cp-input-small",min:"0",max:"1",step:"0.01",value:String(t.position)});a.addEventListener("change",c=>{let h=parseFloat(c.target.value);isNaN(h)&&(h=0),t.position=Math.max(0,Math.min(1,h)),this.sortStops(),this.renderStops(),this.updateOutput()});const o=F(()=>{this.stops.splice(e,1),this.renderStops(),this.updateOutput()});i.appendChild(s),i.appendChild(a),i.appendChild(o),this.stopsContainer.appendChild(i)})}updateOutput(t=this.manualPosition){if(this.stops.length===0)return;if(this.stops.length===1){this.setValue(this.stops[0].color),this.updateDisplay();return}let e="#000000";if(t=Math.max(0,Math.min(1,t)),t<=this.stops[0].position)e=this.stops[0].color;else if(t>=this.stops[this.stops.length-1].position)e=this.stops[this.stops.length-1].color;else for(let i=0;i<this.stops.length-1;i++){const s=this.stops[i],a=this.stops[i+1];if(t>=s.position&&t<=a.position){const o=a.position-s.position,c=o===0?0:(t-s.position)/o;e=it(s.color,a.color,c);break}}this.setValue(e),this.updateDisplay()}updateDisplay(){this.displayColor&&(this.displayColor.style.backgroundColor=this.value),this.displayText&&(this.displayText.textContent=this.value)}applySignal(t,e){let i=t;if(e==="forward")i=t;else if(e==="backward")i=1-t;else{const s=t*.05;e==="loopForward"?(this.animationT=(this.animationT+s)%1,i=this.animationT):e==="loopBackward"?(this.animationT=(this.animationT-s+1)%1,i=this.animationT):e==="pingpong"&&(this.animationT+=s*this.pingPongDirection,this.animationT>=1?(this.animationT=1,this.pingPongDirection=-1):this.animationT<=0&&(this.animationT=0,this.pingPongDirection=1),i=this.animationT)}this.updateOutput(i),this.manualPosition=i}save(){return{stops:this.stops,settings:{signal:this.signalHandler.save()}}}load(t){t&&t.stops&&(this.stops=t.stops,this.sortStops(),this.renderStops()),t&&t.settings&&this.signalHandler?.load(t.settings.signal)}reset(){this.stops=this.initialOptions.stops||[{color:"#000000",position:0},{color:"#ffffff",position:1}],this.sortStops(),this.renderStops(),this.signalHandler?.reset(),this.updateOutput(0)}}class K extends m{constructor(t,e,i={}){super(t,e,i),this.items=[],this.initialOptions=i,this.itemType=i.itemType||"string",this.items=this.parseValue(this.value);const s=r("details",{className:"cp-controller-details"}),a=r("summary",{className:"cp-controller-summary"}),o=r("div",{className:"cp-controller-summary-content"}),c=r("span",{className:"cp-value-display"},[`${this.items.length} items`]);o.appendChild(c),a.appendChild(o),s.appendChild(a);const h=r("div",{className:"cp-number-settings"});this.itemsContainer=r("div",{className:"cp-stops-container"}),this.renderItems(),h.appendChild(this.itemsContainer);const p=r("button",{className:"cp-button cp-input-small",style:"margin-top: 8px; width: 100%;"},["+ Add Item"]);p.addEventListener("click",()=>{this.addItem()}),h.appendChild(p),s.appendChild(h),this.appendWidget(s)}parseValue(t){return!t||t.trim()===""?[]:t.split(",").map(e=>e.trim())}serializeValue(){return this.items.join(",")}getDefaultItemValue(){switch(this.itemType){case"color":return"#ffffff";case"number":return"0";default:return""}}addItem(t){const e=t!==void 0?t:this.getDefaultItemValue();this.items.push(e),this.renderItems(),this.updateValue()}updateValue(){const t=this.serializeValue();this.setValue(t),this.updateSummary()}updateSummary(){const t=this.domElement.querySelector(".cp-value-display");t&&(t.textContent=`${this.items.length} items`)}renderItems(){this.itemsContainer.innerHTML="",this.items.forEach((t,e)=>{const i=r("div",{className:"cp-setting-row"});let s;this.itemType==="color"?s=r("input",{type:"color",className:"cp-input-color",value:t}):this.itemType==="number"?s=r("input",{type:"number",className:"cp-input-number cp-input-small",step:"any",value:t}):s=r("input",{type:"text",className:"cp-input-number cp-input-small",value:t}),s.addEventListener("input",o=>{this.items[e]=o.target.value,this.updateValue()});const a=F(()=>{this.items.splice(e,1),this.renderItems(),this.updateValue()});i.appendChild(s),i.appendChild(a),this.itemsContainer.appendChild(i)})}updateDisplay(){}save(){return[...this.items]}load(t){Array.isArray(t)?this.items=[...t]:typeof t=="string"&&(this.items=this.parseValue(t)),this.renderItems(),this.updateValue()}reset(){const t=this.initialValue||"";this.items=this.parseValue(t),this.renderItems(),this.updateValue()}}class nt{constructor(){this.frames=0,this.pollingInterval=1e3,this.prevTime=performance.now(),this.render=()=>{this.frames++;const t=performance.now();if(t>=this.prevTime+this.pollingInterval){const e=Math.round(this.frames*1e3/(t-this.prevTime));let i="";const s=performance.memory;s&&(i=` / ${Math.round(s.usedJSHeapSize/1048576)}MB`),this.domElement.textContent=`${e} FPS${i}`,this.prevTime=t,this.frames=0}this.rafId=requestAnimationFrame(this.render)},this.domElement=r("span",{className:"cp-stats"}),this.rafId=requestAnimationFrame(this.render)}destroy(){cancelAnimationFrame(this.rafId)}}class V{constructor(){this.controllers=[],this.folders=[]}addNumber(t,e,i={}){const s=new q(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addSelect(t,e,i={}){const s=new H(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addBoolean(t,e,i={}){const s=new _(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addButton(t,e,i={}){const s=new U(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addRadio(t,e,i={}){const s=new W(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addColor(t,e,i={}){const s=new J(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addGradient(t,e,i={}){const s=new Z(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addArray(t,e,i={}){const s=new K(t,e,i);return this.contentElement.appendChild(s.domElement),this.controllers.push(s),s}addFolder(t){const e=new Y(t);return this.contentElement.appendChild(e.domElement),this.folders.push(e),e}save(){const t={controllers:{},folders:{}};for(const e of this.controllers)typeof e.value!="function"&&(t.controllers[e.key]=e.save());for(const e of this.folders)t.folders[e.title]=e.save();return t}load(t){if(!t){this.reset();return}for(const e of this.controllers)if(typeof e.value!="function")if(t.controllers&&e.key in t.controllers){const i=t.controllers[e.key];i!==void 0&&e.load(i)}else e.reset();for(const e of this.folders){const i=t.folders?t.folders[e.title]:void 0;e.load(i)}}reset(){for(const t of this.controllers)typeof t.value!="function"&&t.reset();for(const t of this.folders)t.reset()}}class Y extends V{constructor(t){super(),this.title=t,this.domElement=r("details",{className:"cp-folder",open:!0}),this.summaryElement=r("summary",{className:"cp-summary"},[t]),this.domElement.appendChild(this.summaryElement),this.contentElement=r("div",{className:"cp-content cp-folder-content"}),this.domElement.appendChild(this.contentElement),this.domElement.appendChild(r("hr",{className:"cp-separator"}))}}class at extends V{constructor(t,e={}){super(),X(),this.domElement=r("details",{className:"cp-root",open:!0}),this.summaryElement=r("summary",{className:"cp-summary cp-summary-root"}),this.domElement.appendChild(this.summaryElement);const i=r("span",{},[e.title||"ControlPanel"]);this.summaryElement.appendChild(i),this.stats=new nt,this.summaryElement.appendChild(this.stats.domElement),this.contentElement=r("div",{className:"cp-content"}),this.domElement.appendChild(this.contentElement);const s=this.addFolder("_Signals"),a={audioInput:null,fftSize:2048};s.addRadio(a,"audioInput",{label:"Audio Signal",options:["microphone","browser"]}).onChange(l=>{w.setInput(l)}),s.addSelect(a,"fftSize",{label:"FFT Size",options:[256,512,1024,2048]}).onChange(l=>{w.setFFTSize(l)}),s.addNumber(w,"smoothingTimeConstant",{min:0,max:.99,step:.01,label:"Smoothing"}).onChange(l=>{w.analyser.smoothingTimeConstant=l}),s.addNumber(w,"spectrumBoost",{min:1,max:5,step:.1,label:"Compression"}),t?t.appendChild(this.domElement):document.body.appendChild(this.domElement);const o=e.title||"ControlPanel";this.presetStoragePrefix=`cp-presets-${o}-`;const c=this.addFolder("_User Presets"),h=()=>{const l=["Default"];if(typeof localStorage>"u")return l;for(let u=0;u<localStorage.length;u++){const g=localStorage.key(u);if(g&&g.startsWith(this.presetStoragePrefix)){const v=g.substring(this.presetStoragePrefix.length);v!=="Default"&&!l.includes(v)&&l.push(v)}}return l.sort()},p={selected:"Default",save:()=>{const l=prompt("Preset Name:",p.selected);if(l){if(l==="Default"){alert("Cannot overwrite Default preset");return}const u=this.presetStoragePrefix+l;this.saveToLocalStorage(u);const g=h();f.setOptions(g),p.selected=l,f.setValue(l)}},load:()=>{const l=p.selected,u=this.presetStoragePrefix+l;this.loadFromLocalStorage(u),p.selected=l,f.setValue(l)},delete:()=>{if(p.selected==="Default"){alert("Cannot delete Default preset");return}if(confirm(`Delete preset "${p.selected}"?`)){const l=this.presetStoragePrefix+p.selected;localStorage.removeItem(l);const u=h();f.setOptions(u),p.selected="Default",f.setValue("Default"),this.reset()}},export:()=>{const l=this.save(),u=L=>{const T={controllers:{},folders:{}};for(const[M,D]of Object.entries(L.controllers))M.startsWith("_")||(T.controllers[M]=D);for(const[M,D]of Object.entries(L.folders))M.startsWith("_")||(T.folders[M]=u(D));return T},g=u(l),v={_presetName:p.selected||"CustomPreset",_exportDate:new Date().toISOString(),_instructions:"To add as factory preset: Copy 'controllers' and 'folders' fields into the presets.json file",...g},E=JSON.stringify(v,null,2),S=new Blob([E],{type:"application/json"}),x=URL.createObjectURL(S),y=document.createElement("a");y.href=x;const C=new Date().toISOString().split("T")[0],Q=p.selected.replace(/[^a-z0-9]/gi,"-").toLowerCase();y.download=`${o.toLowerCase()}-preset-${Q}-${C}.json`,document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(x)},import:()=>{const l=document.createElement("input");l.type="file",l.accept=".json",l.onchange=u=>{const g=u.target.files?.[0];if(!g)return;const v=new FileReader;v.onload=E=>{try{const S=E.target?.result,x=JSON.parse(S),y={controllers:x.controllers||{},folders:x.folders||{}};if(!y.controllers||!y.folders){alert("Invalid preset file: missing 'controllers' or 'folders'");return}this.load(y);const C=x._presetName||"ImportedPreset";if(confirm(`Preset loaded! Save as "${C}" to User Presets?`)){const L=this.presetStoragePrefix+C;this.saveToLocalStorage(L);const T=h();f.setOptions(T),p.selected=C,f.setValue(C)}}catch(S){alert(`Failed to import preset: ${S instanceof Error?S.message:"Invalid JSON"}`),console.error("Import error:",S)}},v.readAsText(g)},l.click()}},b=h(),f=c.addSelect(p,"selected",{label:"Preset",options:b});c.addButton("Load",()=>p.load()),c.addButton("Save / New",()=>p.save()),c.addButton("Delete",()=>p.delete()),c.addButton("Export JSON",()=>p.export()),c.addButton("Import JSON",()=>p.import())}saveToLocalStorage(t){const e=this.save();try{localStorage.setItem(t,JSON.stringify(e))}catch(i){console.warn("ControlPanel: Failed to save to localStorage",i)}}loadFromLocalStorage(t){try{const e=localStorage.getItem(t);if(e){const i=JSON.parse(e);this.load(i)}}catch(e){console.warn("ControlPanel: Failed to load from localStorage",e)}}saveDefaultPreset(){const t=this.presetStoragePrefix+"Default";this.save(),this.saveToLocalStorage(t)}destroy(){this.stats.destroy(),this.domElement.remove(),this.controllers=[],this.folders=[]}}d.ArrayController=K,d.AudioSignals=P,d.BooleanController=_,d.ButtonController=U,d.ColorController=J,d.ControlPanel=at,d.ControlPanelContainer=V,d.Controller=m,d.Folder=Y,d.GradientController=Z,d.MidiSignals=z,d.NumberController=q,d.RadioController=W,d.SelectController=H,d.audioSignals=w,d.midiSignals=j,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,2 @@
1
+ export declare function injectStyles(): void;
2
+ //# sourceMappingURL=styles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"styles.d.ts","sourceRoot":"","sources":["../src/styles.ts"],"names":[],"mappings":"AA6RA,wBAAgB,YAAY,SAS3B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digitalmeadow/control-panel",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "type": "module",
5
5
  "description": "A minimalist, framework-agnostic control panel GUI",
6
6
  "author": "Digital Meadow <inbox@digitalmeadow.studio> (https://digitalmeadow.studio)",
package/dist/index.css DELETED
@@ -1 +0,0 @@
1
- .cp-root{position:fixed;top:10px;right:10px;width:280px;max-height:90vh;overflow:auto;background:transparent;color:#fff;mix-blend-mode:exclusion;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:10px;line-height:1.2;padding:8px;z-index:100}.cp-root::-webkit-scrollbar{width:1px}.cp-root::-webkit-scrollbar-track{background:transparent}.cp-root::-webkit-scrollbar-thumb{background:#ffffff80}.cp-summary{cursor:pointer;-webkit-user-select:none;user-select:none;font-weight:700;outline:none}.cp-summary-root{position:sticky;top:0}.cp-stats{float:right;font-weight:400;opacity:.6;font-size:.9em;font-variant-numeric:tabular-nums}.cp-content{margin-top:4px;display:flex;flex-direction:column;gap:6px}.cp-folder{width:100%}.cp-folder-content{margin:0 0 6px;padding:4px 0 0 9px}.cp-controller{display:flex}.cp-label{margin:auto 0;width:50%;flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;-webkit-user-select:none;user-select:none;padding-right:8px;opacity:.8}.cp-input-number{width:50%;background:transparent;border:1px solid #fff;color:inherit;padding:2px 4px;border-radius:2px;font-family:inherit;font-size:inherit}.cp-input-number:focus{outline:none;border-color:#fff;background:transparent}.cp-select{width:50%;background:#ffffff4d;border:none;padding:2px 4px;border-radius:2px;font-family:inherit;font-size:inherit}.cp-checkbox{margin:auto 0}.cp-button{width:100%;background:#ffffff4d;border:none;padding:4px 2px;border-radius:2px;cursor:pointer;text-align:center;font-family:inherit;font-size:inherit;transition:background .1s}.cp-button:hover{background:#fff6}.cp-button:active{background:#fff3;transform:translateY(1px)}.cp-controller[data-disabled=true]{opacity:.5;pointer-events:none;cursor:not-allowed}.cp-controller-details{width:50%}.cp-controller-summary{cursor:pointer;outline:none}.cp-controller-summary-content{display:inline-flex;align-items:center;gap:6px;width:calc(100% - 16px);vertical-align:middle}.cp-input-range{-webkit-appearance:none;flex:1;min-width:0;height:2px;background:#ffffff4d;margin:0;vertical-align:middle;cursor:grab}.cp-input-range::-webkit-slider-thumb{-webkit-appearance:none;width:4px;height:8px;border-radius:1px;background:#fff;cursor:grab}.cp-input-range::-moz-range-thumb{width:4px;height:16px;background:#fff;cursor:grab}.cp-input-range:active{cursor:grabbing}.cp-value-display{min-width:24px;text-align:right;font-variant-numeric:tabular-nums;font-size:.9em;opacity:.8;-webkit-user-select:none;user-select:none}.cp-number-settings{margin-top:4px;background:transparent;border:1px solid rgba(255,255,255,.2);padding:4px;border-radius:4px;display:flex;flex-direction:column;gap:4px}.cp-separator{border:none;border-top:1px solid rgba(255,255,255,.3);margin:4px 0;width:100%}.cp-setting-row{display:flex;align-items:center;gap:4px}.cp-setting-label{width:50%;font-size:.9em;opacity:.7}.cp-input-small{width:50%}.cp-radios{width:50%;display:flex;gap:2px}.cp-radio{flex:1;font-size:.9em;padding:4px 2px;height:100%}.cp-radio[data-active=true]{background:#fff3;border-color:#fff;font-weight:700}.cp-button-delete{width:24px;padding:0;display:flex;align-items:center;justify-content:center;line-height:1}.cp-input-color{padding:0;margin:0;border:none;background:none;outline:none;isolation:isolate;mix-blend-mode:normal;cursor:pointer}.cp-color-swatch{width:10px;height:10px;margin-right:8px}.cp-stops-container{display:flex;flex-direction:column;gap:4px}