1import{a as ja,c as qa}from"./chunk-5TBO732O.js";var Mr=ja((Tr,ji)=>{(function(t,e){"use strict";var i,n,s,r=null,o=null,a=null,l=function(p,u,v){p.addEventListener?p.addEventListener(u,v,!1):p.attachEvent?p.attachEvent("on"+u,v):p["on"+u]=v},h={autoRun:!0,barThickness:3,barColors:{0:"rgba(26, 188, 156, .9)",".25":"rgba(52, 152, 219, .9)",".50":"rgba(241, 196, 15, .9)",".75":"rgba(230, 126, 34, .9)","1.0":"rgba(211, 84, 0, .9)"},shadowBlur:10,shadowColor:"rgba(0, 0, 0, .6)",className:null},c=function(){i.width=t.innerWidth,i.height=h.barThickness*5;var p=i.getContext("2d");p.shadowBlur=h.shadowBlur,p.shadowColor=h.shadowColor;var u=p.createLinearGradient(0,0,i.width,0);for(var v in h.barColors)u.addColorStop(v,h.barColors[v]);p.lineWidth=h.barThickness,p.beginPath(),p.moveTo(0,h.barThickness/2),p.lineTo(Math.ceil(n*i.width),h.barThickness/2),p.strokeStyle=u,p.stroke()},d=function(){i=e.createElement("canvas");var p=i.style;p.position="fixed",p.top=p.left=p.right=p.margin=p.padding=0,p.zIndex=100001,p.display="none",h.className&&i.classList.add(h.className),l(t,"resize",c)},m={config:function(p){for(var u in p)h.hasOwnProperty(u)&&(h[u]=p[u])},show:function(p){if(!s)if(p){if(a)return;a=setTimeout(()=>m.show(),p)}else s=!0,o!==null&&t.cancelAnimationFrame(o),i||d(),i.parentElement||e.body.appendChild(i),i.style.opacity=1,i.style.display="block",m.progress(0),h.autoRun&&function u(){r=t.requestAnimationFrame(u),m.progress("+"+.05*Math.pow(1-Math.sqrt(n),2))}()},progress:function(p){return typeof p>"u"||(typeof p=="string"&&(p=(p.indexOf("+")>=0||p.indexOf("-")>=0?n:0)+parseFloat(p)),n=p>1?1:p,c()),n},hide:function(){clearTimeout(a),a=null,s&&(s=!1,r!=null&&(t.cancelAnimationFrame(r),r=null),function p(){if(m.progress("+.1")>=1&&(i.style.opacity-=.05,i.style.opacity<=.05)){i.style.display="none",o=null;return}o=t.requestAnimationFrame(p)}())}};typeof ji=="object"&&typeof ji.exports=="object"?ji.exports=m:typeof define=="function"&&define.amd?define(function(){return m}):this.topbar=m}).call(Tr,window,document)});(function(){var t=e();function e(){if(typeof window.CustomEvent=="function")return window.CustomEvent;function s(r,o){o=o||{bubbles:!1,cancelable:!1,detail:void 0};var a=document.createEvent("CustomEvent");return a.initCustomEvent(r,o.bubbles,o.cancelable,o.detail),a}return s.prototype=window.Event.prototype,s}function i(s,r){var o=document.createElement("input");return o.type="hidden",o.name=s,o.value=r,o}function n(s,r){var o=s.getAttribute("data-to"),a=i("_method",s.getAttribute("data-method")),l=i("_csrf_token",s.getAttribute("data-csrf")),h=document.createElement("form"),c=document.createElement("input"),d=s.getAttribute("target");h.method=s.getAttribute("data-method")==="get"?"get":"post",h.action=o,h.style.display="none",d?h.target=d:r&&(h.target="_blank"),h.appendChild(l),h.appendChild(a),document.body.appendChild(h),c.type="submit",h.appendChild(c),c.click()}window.addEventListener("click",function(s){var r=s.target;if(!s.defaultPrevented)for(;r&&r.getAttribute;){var o=new t("phoenix.link.click",{bubbles:!0,cancelable:!0});if(!r.dispatchEvent(o))return s.preventDefault(),s.stopImmediatePropagation(),!1;if(r.getAttribute("data-method")&&r.getAttribute("data-to"))return n(r,s.metaKey||s.shiftKey),s.preventDefault(),!1;r=r.parentNode}},!1),window.addEventListener("phoenix.link.click",function(s){var r=s.target.getAttribute("data-confirm");r&&!window.confirm(r)&&s.preventDefault()},!1)})();var Te=t=>typeof t=="function"?t:function(){return t},za=typeof self<"u"?self:null,At=typeof window<"u"?window:null,Rt=za||At||globalThis,Va="2.0.0",Ot={connecting:0,open:1,closing:2,closed:3},Wa=100,Ka=1e4,Xa=1e3,mt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},qt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},En={longpoll:"longpoll",websocket:"websocket"},Ga={complete:4},Sn="base64url.bearer.phx.",_i=class{constructor(t,e,i,n){this.channel=t,this.event=e,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHo
vendor: 6,648 bytes, line 1
1oks=[],this.sent=!1}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:t,response:e,_ref:i}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.cancelRefEvent(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Fs=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Ja=class{constructor(t,e,i){this.state=mt.closed,this.topic=t,this.params=Te(e||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new _i(this,qt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Fs(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=mt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=mt.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=mt.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=mt.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new _i(this,qt.leave,Te({}),this.timeout).send(),this.state=mt.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(qt.reply,(n,s)=>{this.trigger(this.replyEventName(s),n)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(t){this.on(qt.close,t)}onError(t){return this.on(qt.error,e=>t(e))}on(t,e){let i=this.bindingRef++;return this.bindings.push({event:t,ref:i,callback:e}),i}off(t,e){this.bindings=this.bindings.filter(i=>!(i.event===t&&(typeof e>"u"||e===i.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,i=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new _i(this,t,function(){return e},i);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=mt.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(qt.close,"leave")},i=new _i(this,qt.leave,Te({}),t);return i.receive("ok",()=>e()).receive("timeout",()=>e()),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(t,e,i){return e}isMember(t,e,i,n){return this.topic!==t?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:i,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=mt.joining,this.joinPush.resend(t))}trigger(t,e,i,n){let s=this.onMessage(t,e,i,n);if(e&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(o=>o.event===t);for(let o=0;o<r.length;o++)r[o].callback(s,i,n||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===mt.closed}isErrored(){return this.state===mt.errored}isJoined(){return this.state===mt.joined}isJoining(){return this.state===mt.joining}isLeaving(){return this.state===mt.leaving}},xi=class{static request(t,e,i,n,s,r,o){if(Rt.XDomainRequest){let a=new Rt.XDomainRequest;return this.xdomainRequest(a,t,e,n,s,r,o)}else if(Rt.XMLHttpRequest){let a=new Rt.XMLHttpRequest;return this.xhrRequest(a,t,e,i,n,s,r,o)}else{if(Rt.fetch&&Rt.AbortController)return this.fetchRequest(t,e,i,n,s,r,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,i,n,s,r,o){let a={method:t,headers:i,body:n},l=null,h=null;return s&&(l=new AbortController,h=setTimeout(()=>l.abort(),s),a.signal=l.signal),Rt.fetch(e,a).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>{h&&clearTimeout(h),o&&o(c)}).catch(c=>{h&&clearTimeout(h),c.name==="AbortError"&&r?r():o&&o(null)}),l}static xdomainRequest(t,e,i,n,s,r,o){return t.timeout=s,t.open(e,i),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a)},r&&(t.ontimeout=r),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,i,n,s,r,o,a){t.open(e,i,!0),t.timeout=r;for(let[l,h]of Object.entries(n))t.setRequestHeader(l,h);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Ga.complete&&a){let l=this.parseJSON(t.responseText);a(l)}},o&&(t.ontimeout=o),t.send(s),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let i=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=e?`${e}[${n}]`:n,r=t[n];
vendor: 1,797 bytes, line 1
1typeof r=="object"?i.push(this.serialize(r,s)):i.push(encodeURIComponent(s)+"="+encodeURIComponent(r))}return i.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let i=t.match(/\?/)?"&":"?";return`${t}${i}${this.serialize(e)}`}},Ya=t=>{let e="",i=new Uint8Array(t),n=i.byteLength;for(let s=0;s<n;s++)e+=String.fromCharCode(i[s]);return btoa(e)},Qt=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Sn)&&(this.authToken=atob(e[1].slice(Sn.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Ot.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+En.websocket),"$1/"+En.longpoll)}endpointURL(){return xi.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,i){this.close(t,e,i),this.readyState=Ot.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Ot.open||this.readyState===Ot.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:i,token:n,messages:s}=e;if(i===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=n}else i=0;switch(i){case 200:s.forEach(r=>{setTimeout(()=>this.onmessage({data:r}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Ot.open,this.onopen({}),this.poll();break;
vendor: 11,383 bytes, lines 1-2
1case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${i}`)}})}send(t){typeof t!="string"&&(t=Ya(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t,e=0){this.awaitingBatchAck=!0;let i=e+Wa,n=t.slice(e,i);this.ajax("POST",{"Content-Type":"application/x-ndjson"},n.join(` 2`),()=>this.ontimeout(),s=>{!s||s.status!==200?(this.awaitingBatchAck=!1,this.onerror(s&&s.status),this.closeAndRetry(1011,"internal server error",!1)):i<t.length?this.batchSend(t,i):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(t,e,i){for(let s of this.reqs)s.abort();this.readyState=Ot.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:i});this.batchBuffer=[],this.awaitingBatchAck=!1,clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(t,e,i,n,s){let r,o=()=>{this.reqs.delete(r),n()};r=xi.request(t,this.endpointURL(),e,i,this.timeout,o,a=>{this.reqs.delete(r),this.isActive()&&s(a)}),this.reqs.add(r)}};var Ai={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let i=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(i))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[i,n,s,r,o]=JSON.parse(t);return e({join_ref:i,ref:n,topic:s,event:r,payload:o})}},binaryEncode(t){let{join_ref:e,ref:i,event:n,topic:s,payload:r}=t,o=new TextEncoder,a=o.encode(e),l=o.encode(i),h=o.encode(s),c=o.encode(n);this.assertFieldSize(a.byteLength,"join_ref"),this.assertFieldSize(l.byteLength,"ref"),this.assertFieldSize(h.byteLength,"topic"),this.assertFieldSize(c.byteLength,"event");let d=this.META_LENGTH+a.byteLength+l.byteLength+h.byteLength+c.byteLength,m=new ArrayBuffer(this.HEADER_LENGTH+d),p=new Uint8Array(m),u=new DataView(m),v=0;u.setUint8(v++,this.KINDS.push),u.setUint8(v++,a.byteLength),u.setUint8(v++,l.byteLength),u.setUint8(v++,h.byteLength),u.setUint8(v++,c.byteLength),p.set(a,v),v+=a.byteLength,p.set(l,v),v+=l.byteLength,p.set(h,v),v+=h.byteLength,p.set(c,v),v+=c.byteLength;var y=new Uint8Array(m.byteLength+r.byteLength);return y.set(p,0),y.set(new Uint8Array(r),m.byteLength),y.buffer},assertFieldSize(t,e){if(t>255)throw new Error(`unable to convert ${e} to binary: must be less than or equal to 255 bytes, but is ${t} bytes`)},binaryDecode(t){let e=new DataView(t),i=e.getUint8(0),n=new TextDecoder;switch(i){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,i){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=i.decode(t.slice(o,o+n));o=o+n;let l=i.decode(t.slice(o,o+s));o=o+s;let h=i.decode(t.slice(o,o+r));o=o+r;let c=t.slice(o,t.byteLength);return{join_ref:a,ref:null,topic:l,event:h,payload:c}},decodeReply(t,e,i){let n=e.getUint8(1),s=e.getUint8(2),r=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=i.decode(t.slice(a,a+n));a=a+n;let h=i.decode(t.slice(a,a+s));a=a+s;let c=i.decode(t.slice(a,a+r));a=a+r;let d=i.decode(t.slice(a,a+o));a=a+o;let m=t.slice(a,t.byteLength),p={status:d,response:m};return{join_ref:l,ref:h,topic:c,event:qt.reply,payload:p}},decodeBroadcast(t,e,i){let n=e.getUint8(1),s=e.getUint8(2),r=this.HEADER_LENGTH+2,o=i.decode(t.slice(r,r+n));r=r+n;let a=i.decode(t.slice(r,r+s));r=r+s;let l=t.slice(r,t.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:l}}},Ns=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Ka,this.transport=e.transport||Rt.WebSocket||Qt,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Rt&&Rt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Ai.encode.bind(Ai),this.defaultDecoder=Ai.decode.bind(Ai),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.transport!==Qt?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;At&&At.addEventListener&&(At.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),i=this.connectClock)}),At.addEventListener("pageshow",n=>{i===this.connectClock&&(i=null,this.connect())}),At.addEventListener("visibilitychange",()=>{this.handleVisibilityChange()}),At.document&&At.document.addEventListener("resume",()=>{this.handleVisibilityChange()})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,s,r)=>{console.log(`${n}: ${s}`,r)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Te(e.params||{}),this.endPoint=`${t}/${En.websocket}`,this.vsn=e.vsn||Va,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Fs(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(()=>this.connect())},this.reconnectAfterMs),this.authToken=e.authToken&&Te(e.authToken)}get pageHidden(){return At&&At.document?At.document.visibilityState==="hidden":!1}handleVisibilityChange(){this.pageHidden||!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect())}getLongPollTransport(){return Qt}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=xi.appendParams(xi.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,i){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,i)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Te(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Qt?this.connectWithFallback(Qt,this.longPollFallbackMs):this.transportConnect())}log(t,e,i){this.logger&&this.logger(t,e,i)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(s=>{s.ref===e&&(this.off([n]),t(Date.now()-i))});return!0}transportName(t){switch(t){case Qt:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Sn}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let i=!1,n=!0,s,r,o=this.transportName(t),a=l=>{this.log("transport",`falling back to ${o}...`,l),this.off([s,r]),n=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),r=this.onError(l=>{this.log("transport","error",l),n&&!i&&(clearTimeout(this.fallbackTimer),a(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!n){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transportName(this.transport)} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,t])=>t())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError("heartbeat_timeout"),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Xa,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,i){if(!this.conn)return t&&t();let n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,i||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,i=1){if(i===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,i+1)},150*i)}waitForSocketClosed(t,e,i=1){if(i===5||t.readyState===Ot.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,i+1)},150*i)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{});let e=t&&t.code;this.hasLogger()&&this.log("transport","close",t),this.triggerChanError("connection_closed"),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,i])=>i(t))}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,i=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,n])=>{n(t,e,i)}),(e===this.transport||i>0)&&this.triggerChanError("connection_error")}
2triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(qt.error,{source:"transport",reason:t})})}connectionState(){switch(this.conn&&this.conn.readyState){case Ot.connecting:return"connecting";case Ot.open:return"open";case Ot.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([i])=>t.indexOf(i)===-1)}channel(t,e={}){let i=new Ja(t,e,this);return this.channels.push(i),i}push(t){if(this.hasLogger()){let{topic:e,event:i,payload:n,ref:s,join_ref:r}=t;this.log("push",`${e} ${i} (${r}, ${s})`,n)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:i,event:n,payload:s,ref:r,join_ref:o}=e;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${s.status||""} ${i} ${n} ${r&&"("+r+")"||""}`,s);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(i,n,s,o)&&l.trigger(n,s,r,o)}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,l]=this.stateChangeCallbacks.message[a];l(e)}})}leaveOpenTopic(t){let e=this.channels.find(i=>i.topic===t&&(i.isJoined()||i.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var fr="consecutive-reloads",Za=10,Qa=5e3,tl=1e4,el=3e4,pr=["phx-click-loading","phx-change-loading","phx-submit-loading","phx-keydown-loading","phx-keyup-loading","phx-blur-loading","phx-focus-loading","phx-hook-loading"],Cn="phx-drop-target-active",xt="data-phx-component",Le="data-phx-view",kn="data-phx-link",il="track-static",Us="data-phx-link-state",Re="data-phx-ref-loading",Et="data-phx-ref-src",q="data-phx-ref-lock",Bs="phx-pending-refs",mr="track-uploads",Vt="data-phx-upload-ref",$n="data-phx-preflighted-refs",nl="data-phx-done-refs",gr="data-phx-error-refs",Ti="drop-target",Dn="data-phx-active-refs",Ri="phx:live-file:updated",vr="data-phx-skip",Ln="data-phx-id",$s="data-phx-prune",js="phx-connected",le="phx-loading",Me="phx-error",qs="phx-client-error",Xe="phx-server-error",me="data-phx-parent-id",jn="data-phx-main",zt="data-phx-root-id",Rn="viewport-top",On="viewport-bottom",sl="viewport-overrun-target",rl="trigger-action",Ni="phx-has-focused",ol=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"],br=["checkbox","radio"],ii="phx-has-submitted",Ut="data-phx-session",ni=`[${Ut}]`,Hn="data-phx-sticky",pe="data-phx-static",Fn="data-phx-readonly",Ie="data-phx-disabled",zs="disable-with",Ui="data-phx-disable-with-restore",he="hook",al="debounce",ll="throttle",Bi="update",hl="patch-focused",Oi="stream",Ge="data-phx-stream",qn="data-phx-portal",ge="data-phx-teleported",ne="data-phx-teleported-src",Hi="data-phx-runtime-hook",cl="data-phx-pid",dl="key",Ht="phxPrivate",Vs="auto-recover",Ws="no-unused-field",Mi="phx:live-socket:debug",_n="phx:live-socket:profiling",An="phx:live-socket:latency-sim",Pi="phx:nav-history-position",ul="progress",Ks="mounted",Xs="__phoenix_reload_status__",fl=1,xn=3,pl=200,ml=500,gl="phx-",vl=3e4,Je="debounce-trigger",Ye="throttled",Gs="debounce-prev-key",bl={debounce:300,throttle:300},Js=[Re,Et,q],gt="s",Tn="r",Q="c",B="k",Ft="kc",Ys="km",Zs="e",Qs="r",tr="t",te="p",Pe="stream",yl="phx:live-view:diagnostic",wl=1,El=class{constructor(t,e,i){let{chunk_size:n,chunk_timeout:s}
2=e;this.liveSocket=i,this.entry=t,this.offset=0,this.chunkSize=n,this.chunkTimeout=s,this.chunkTimer=null,this.errored=!1,this.uploadChannel=i.channel(`lvu:${t.ref}`,{token:t.metadata()})}error(t){this.errored||(this.entry.view.cancelSubmit(this.entry.fileEl.form),this.uploadChannel.leave(),this.errored=!0,this.chunkTimer!=null&&clearTimeout(this.chunkTimer),t!=="writer_error"&&this.entry.error(t))}upload(){this.uploadChannel.onError(t=>this.error(t)),this.uploadChannel.join().receive("ok",t=>this.readNextChunk()).receive("error",({reason:t})=>this.error(t))}isDone(){return this.offset>=this.entry.file.size}readNextChunk(){let t=new window.FileReader,e=this.entry.file.slice(this.offset,this.chunkSize+this.offset);t.onload=i=>{if(i.target?.error===null)this.offset+=i.target.result.byteLength,this.pushChunk(i.target.result);else return this.entry.view.logError("upload.read-failed","Read error: "+i.target?.error,{entry:this.entry,offset:this.offset})},t.readAsArrayBuffer(e)}pushChunk(t){this.uploadChannel.isJoined()&&this.uploadChannel.push("chunk",t,this.chunkTimeout).receive("ok",()=>{this.entry.progress(this.offset/this.entry.file.size*100),this.isDone()||(this.chunkTimer=setTimeout(()=>this.readNextChunk(),this.liveSocket.getLatencySim()||0))}).receive("error",({reason:e})=>this.error(e))}},yr=t=>{window.dispatchEvent(new CustomEvent(yl,{detail:{version:wl,...t}}))},Nt=(t,e,i,n)=>{console.error&&console.error(e,i),yr({level:"error",code:t,message:e,metadata:i,...n})},er=(t,e)=>{let i;try{i=new URL(t,window.location.href)}catch{throw new Error(`expected ${e} destination to be a valid URL, got: ${t}`)}if(i.origin!==window.location.origin)throw new Error(`cannot ${e} to "${t}" because its origin does not match the current origin "${window.location.origin}". Use window.location directly for cross-origin navigation.`)},ie=t=>{let e=typeof t;return e==="number"||e==="string"&&/^(0|[1-9]\d*)$/.test(t)};function Sl(t=Nt){let e=new Map,i=document.querySelectorAll("*[id]");for(let n=0,s=i.length;n<s;n++){let r=i[n].id,o=e.get(r);o?t("dom.duplicate-id",`Multiple IDs detected: ${r}. Ensure unique element ids.`,{id:r,elements:[o,i[n]]},{attribution:"app"}):e.set(r,i[n])}}function Cl(t,e=Nt){let i=new Set;Object.keys(t).forEach(n=>{let s=document.getElementById(n);s&&s.parentElement&&s.parentElement.getAttribute("phx-update")!=="stream"&&i.add(s.parentElement)}),i.forEach(n=>{let s=n.id;e("dom.invalid-stream-container",`The stream container with id "${s}" is missing the phx-update="stream" attribute. Ensure it is set for streams to work properly.`,{id:s,container:n},{attribution:"app"})})}var kl=(t,e,i,n)=>{t.liveSocket.isDebugEnabled()&&console.log(`${t.id} ${e}: ${i} - `,n)},Ze=t=>typeof t=="function"?t:function(){return t},Fi=t=>JSON.parse(JSON.stringify(t)),wr=t=>"structuredClone"in window?structuredClone(t):JSON.parse(JSON.stringify(t)),fe=(t,e,i)=>{let n=t;do{if(n.matches(`[${e}]`)&&!("disabled"in n&&n.disabled))return n;n=n.parentElement}while(n!==null&&n.nodeType===1&&!(i&&i.isSameNode(n)||n.matches(ni)));return null},ce=t=>t!==null&&typeof t=="object"&&!(t instanceof Array),_l=(t,e)=>JSON.stringify(t)===JSON.stringify(e),ir=t=>{for(let e in t)return!1;return!0},De=(t,e)=>t&&e(t),Al=function(t,e,i,n){t.forEach(s=>{new El(s,i.config,n).upload()})},xl=t=>{if(t.dataTransfer.types){for(let e=0;e<t.dataTransfer.types.length;e++)if(t.dataTransfer.types[e]==="Files")return!0}return!1},Tl={canPushState(){return typeof history.pushState<"u"},dropLocal(t,e,i){return t.removeItem(this.localKey(e,i))},updateLocal(t,e,i,n,s){let r=this.getLocal(t,e,i),o=this.localKey(e,i),a=r===null?n:s(r);return t.setItem(o,JSON.stringify(a)),a},getLocal(t,e,i){return JSON.parse(t.getItem(this.localKey(e,i)))},updateCurrentState(t){this.canPushState()&&history.replaceState(t(history.state||{}),"",window.location.href)},pushState(t,e,i){if(this.canPushState()){if(i!==window.location.href){if(e.type=="redirect"&&e.scroll){let n=history.state||{};n.scroll=e.scroll,history.replaceState(n,"",window.location.href)}delete e.scroll,history[t+"State"](e,"",i||null),window.requestAnimationFrame(()=>{let n=this.getHashTargetEl(window.location.hash);n?n.scrollIntoView():e.type==="redirect"&&window.scroll(0,0)})}}else i&&this.redirect(i)}
2,setCookie(t,e,i){let n=typeof i=="number"?` max-age=${i};`:"";document.cookie=`${t}=${e};${n} path=/`},getCookie(t){return document.cookie.replace(new RegExp(`(?:(?:^|.*;s*)${t}s*=s*([^;]*).*$)|^.*$`),"$1")},deleteCookie(t){document.cookie=`${t}=; max-age=-1; path=/`},redirect(t,e=null,i=n=>{window.location.href=n}){e&&this.setCookie("__phoenix_flash__",e,60),i(t)},localKey(t,e){return`${t}-${e}`},getHashTargetEl(t){let e=t.toString().substring(1);if(e!=="")return document.getElementById(e)||document.querySelector(`a[name="${e}"]`)}},dt=Tl,ue={byId(t){return document.getElementById(t)||Nt("dom.element-not-found",`no id found for ${t}`,{id:t},{attribution:"internal"})},elementFromTarget(t){return t instanceof Node?t.nodeType===Node.ELEMENT_NODE?t:t.parentElement:null},removeClass(t,e){t.classList.remove(e),t.classList.length===0&&t.removeAttribute("class")},all(t,e,i){if(!t)return[];let n=Array.from(t.querySelectorAll(e));return i&&n.forEach(i),n},childNodeLength(t){let e=document.createElement("template");return e.innerHTML=t,e.content.childElementCount},isUploadInput(t){return t.type==="file"&&t.getAttribute(Vt)!==null},isAutoUpload(t){return t.hasAttribute("data-phx-auto-upload")},findUploadInputs(t){let e=t.id,i=this.all(document,`input[type="file"][${Vt}][form="${e}"]`);return this.all(t,`input[type="file"][${Vt}]`).concat(i)},findComponent(t,e,i=document){return i.querySelector(`[${Le}="${t}"][${xt}="${e}"]`)},getComponent(t,e,i=document){let n=this.findComponent(t,e,i);if(!n)throw new Error(`no component found matching viewId ${t} and cid ${e}`);return n},isPhxDestroyed(t){return!!(t.id&&ue.private(t,"destroyed"))},wantsNewTab(t){let e=t.ctrlKey||t.shiftKey||t.metaKey||t.button&&t.button===1,i=t.target instanceof HTMLAnchorElement&&t.target.hasAttribute("download"),n=t.target.hasAttribute("target")&&t.target.getAttribute("target").toLowerCase()==="_blank",s=t.target.hasAttribute("target")&&!t.target.getAttribute("target").startsWith("_");return e||n||i||s},isUnloadableFormSubmit(t){return t.target&&t.target.getAttribute("method")==="dialog"||t.submitter&&t.submitter.getAttribute("formmethod")==="dialog"?!1:!t.defaultPrevented&&!this.wantsNewTab(t)},isNewPageClick(t,e){let i=t.target instanceof HTMLAnchorElement?t.target.getAttribute("href"):null,n;if(t.defaultPrevented||i===null||this.wantsNewTab(t)||i.startsWith("mailto:")||i.startsWith("tel:")||t.target.isContentEditable)return!1;try{n=new URL(i)}catch{try{n=new URL(i,e)}catch{return!0}}return n.host===e.host&&n.protocol===e.protocol&&n.pathname===e.pathname&&n.search===e.search?n.hash===""&&!n.href.endsWith("#"):n.protocol.startsWith("http")},markPhxChildDestroyed(t){this.isPhxChild(t)&&t.setAttribute(Ut,""),this.putPrivate(t,"de
2stroyed",!0)},findPhxChildrenInFragment(t,e){let i=document.createElement("template");return i.innerHTML=t,this.findPhxChildren(i.content,e)},isIgnored(t,e){return(t.getAttribute(e)||t.getAttribute("data-phx-update"))==="ignore"},isPhxUpdate(t,e,i){return t.getAttribute&&i.indexOf(t.getAttribute(e))>=0},findPhxSticky(t){return this.all(t,`[${Hn}]`)},findPhxChildren(t,e){return this.all(t,`${ni}[${me}="${e}"]`)},findExistingParentCIDs(t,e){let i=new Set,n=new Set;return e.forEach(s=>{this.all(document,`[${Le}="${t}"][${xt}="${s}"]`).forEach(r=>{i.add(s),this.all(r,`[${Le}="${t}"][${xt}]`).map(o=>parseInt(o.getAttribute(xt))).forEach(o=>n.add(o))})}),n.forEach(s=>i.delete(s)),i},private(t,e){return t[Ht]&&t[Ht][e]},deletePrivate(t,e){t[Ht]&&delete t[Ht][e]},putPrivate(t,e,i){t[Ht]||(t[Ht]={}),t[Ht][e]=i},updatePrivate(t,e,i,n){let s=this.private(t,e);s===void 0?this.putPrivate(t,e,n(i)):this.putPrivate(t,e,n(s))},syncPendingAttrs(t,e){t.hasAttribute(Et)&&(pr.forEach(i=>{t.classList.contains(i)&&e.classList.add(i)}),Js.filter(i=>t.hasAttribute(i)).forEach(i=>{e.setAttribute(i,t.getAttribute(i))}))},copyPrivates(t,e){e[Ht]&&(t[Ht]=e[Ht])},putTitle(t){let e=document.querySelector("title");if(e){let{prefix:i,suffix:n,default:s}=e.dataset,r=typeof t!="string"||t.trim()==="";if(r&&typeof s!="string")return;let o=r?s:t;document.title=`${i||""}${o||""}${n||""}`}else document.title=t},debounce(t,e,i,n,s,r,o,a){let l=t.getAttribute(i),h=t.getAttribute(s);l===""&&(l=n),h===""&&(h=r);let c=l||h;switch(c){case null:return a();case"blur":this.incCycle(t,"debounce-blur-cycle",()=>{o()&&a()}),this.once(t,"debounce-blur")&&t.addEventListener("blur",()=>this.triggerCycle(t,"debounce-blur-cycle"));return;default:let d=parseInt(c),m=()=>h?this.deletePrivate(t,Ye):a(),p=this.incCycle(t,Je,m);if(isNaN(d))return Nt("dom.invalid-debounce",`invalid throttle/debounce value: ${c}`,{el:t,value:c},{attribution:"app"});if(h){let v=!1;if(e.type==="keydown"){let y=this.private(t,Gs);this.putPrivate(t,Gs,e.key),v=y!==e.key}if(!v&&this.private(t,Ye))return!1;{a();let y=setTimeout(()=>{o()&&this.triggerCycle(t,Je)},d);this.putPrivate(t,Ye,y)}}else setTimeout(()=>{o()&&this.triggerCycle(t,Je,p)},d);let u=t.form;u&&this.once(u,"bind-debounce")&&u.addEventListener("submit",()=>{Array.from(new FormData(u).entries(),([v])=>{let y=u.elements.namedItem(v),M=y instanceof RadioNodeList?y[0]:y;M&&(this.incCycle(M,Je),this.deletePrivate(M,Ye))})}),this.once(t,"bind-debounce")&&t.addEventListener("blur",()=>{clearTimeout(this.private(t,Ye)),o()&&this.triggerCycle(t,Je)})}},triggerCycle(t,e,i){let[n,s]=this.private(t,e);i||(i=n),i===n&&(this.incCycle(t,e),s())},once(t,e){return this.private(t,e)===!0?!1:(this.putPrivate(t,e,!0),!0)},incCycle(t,e,i=function(){}){let[n]=this.private(t,e)||[0,i];return n++,this.putPrivate(t,e,[n,i]),n},maintainPrivateHooks(t,e,i,n){t.hasAttribute&&t.hasAttribute("data-phx-hook")&&!e.hasAttribute("data-phx-hook")&&e.setAttribute("data-phx-hook",t.getAttribute("data-phx-hook")),e.hasAttribute&&(e.hasAttribute(i)||e.hasAttribute(n))&&e.setAttribute("data-phx-hook","Phoenix.InfiniteScroll")},putCustomElHook(t,e){t.isConnected?t.setAttribute("data-phx-hook",""):Nt("hook.non-connected-element",` 3 hook attached to non-connected DOM element 4 ensure you are calling createHook within your connectedCallback. ${t.outerHTML} 5 `,{el:t},{attribution:"app"}),this.putPrivate(t,"custom-el-hook",e)},getCustomElHook(t){return this.private(t,"custom-el-hook")},isUsedInput(t){return t.nodeType===Node.ELEMENT_NODE&&(this.private(t,Ni)||this.private(t,ii))},resetForm(t){Array.from(t.elements).forEach(e=>{this.deletePrivate(e,Ni),this.deletePrivate(e,ii)})},isPhxChild(t){return t.getAttribute&&t.getAttribute(me)},isPhxSticky(t){return t.getAttribute&&t.getAttribute(Hn)!==null},isChildOfAny(t,e){return!!e.find(i=>i.contains(t))},firstPhxChild(t){return this.isPhxChild(t)?t:this.all(t,`[${me}]`)[0]},isPortalTemplate(t){return t.tagName==="TEMPLATE"&&t.hasAttribute(qn)},closestViewEl(t){let e=t.closest(`[${ge}],${ni}`);return e?e.hasAttribute(ge)?this.byId(e.getAttribute(ge)):e.hasAttribute(Ut)?e:null:null},dispatchEvent(t,e,i={}){let n=!0;t.nodeName==="INPUT"&&t.type==="file"&&e==="click"&&(n=!1);let o={bubbles:i.bubbles===void 0?n:!!i.bubbles,cancelable:!0,detail:i.detail||{}},a=e==="click"?new MouseEvent("click",o):new CustomEvent(e,o);return t.dispatchEvent(a)},cloneNode(t,e){if(typeof e>"u")return t.cloneNode(!0);{let i=t.cloneNode(!1);return i.innerHTML=e,i}},mergeAttrs(t,e,i={}){let n=new Set(i.exclude||[]),s=i.isIgnored,r=e.attributes;for(let a=r.length-1;a>=0;a--){let l=r[a].name;if(n.has(l)){if(l==="value"){let h=e.value??e.getAttribute(l);t.value===h&&t.setAttribute("value",e.getAttribute(l))}}else{let h=e.getAttribute(l);t.getAttribute(l)!==h&&(!s||s&&l.startsWith("data-"))&&t.setAttribute(l,h)}}let o=t.attributes;for(let a=o.length-1;a>=0;a--){let l=o[a].name;s?l.startsWith("data-")&&!e.hasAttribute(l)&&!Js.includes(l)&&t.removeAttribute(l):e.hasAttribute(l)||t.removeAttribute(l)}},mergeFocusedInput(t,e){t instanceof HTMLSelectElement||ue.mergeAttrs(t,e,{exclude:["value"]}),e.readOnly?t.setAttribute("readonly",!0):t.removeAttribute("readonly")},hasSelectionRange(t){return t.setSelectionRange&&(t.type==="text"||t.type==="textarea")},restoreFocus(t,e,i){if(t instanceof HTMLSelectElement&&t.focus(),!ue.isTextualInput(t))return;
5t.matches(":focus")||t.focus(),this.hasSelectionRange(t)&&t.setSelectionRange(e,i)},isEditableInput(t){return this.isFormAssociated(t)&&!(t instanceof HTMLButtonElement)&&!(t instanceof HTMLInputElement&&t.type==="button")},isFormAssociated(t){if(!(t instanceof HTMLElement))return!1;if(t.localName){let e=customElements.get(t.localName);if(e)return e.formAssociated===!0}return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLButtonElement},syncAttrsToProps(t){t instanceof HTMLInputElement&&br.indexOf(t.type.toLocaleLowerCase())>=0&&(t.checked=t.getAttribute("checked")!==null)},isTextualInput(t){return ol.indexOf(t.type)>=0},isNowTriggerFormExternal(t,e){return t.getAttribute&&t.getAttribute(e)!==null&&document.body.contains(t)},cleanChildNodes(t,e,i=Nt){if(ue.isPhxUpdate(t,e,["append","prepend",Oi])){let n=[];t.childNodes.forEach(s=>{(!("id"in s)||!s.id)&&(!(s.nodeType===Node.TEXT_NODE&&s.nodeValue&&s.nodeValue.trim()==="")&&s.nodeType!==Node.COMMENT_NODE&&i("dom.invalid-phx-update-child",`only HTML element tags with an id are allowed inside containers with phx-update. 6 7removing illegal node: "${("outerHTML"in s&&s.outerHTML||s.nodeValue||"").trim()}" 8 9`,{container:t,childNode:s,phxUpdate:e},{attribution:"app"}),n.push(s))}),n.forEach(s=>s.remove())}},replaceRootContainer(t,e,i){let n=new Set(["id",Ut,pe,jn,zt]);if(t.tagName.toLowerCase()===e.toLowerCase())return Array.from(t.attributes).filter(s=>!n.has(s.name.toLowerCase())).forEach(s=>t.removeAttribute(s.name)),Object.keys(i).filter(s=>!n.has(s.toLowerCase())).forEach(s=>t.setAttribute(s,i[s])),t;{let s=document.createElement(e);
9return Object.keys(i).forEach(r=>s.setAttribute(r,i[r])),n.forEach(r=>{let o=t.getAttribute(r);o!==null&&s.setAttribute(r,o)}),s.innerHTML=t.innerHTML,t.replaceWith(s),s}},getSticky(t,e,i){let n=(ue.private(t,"sticky")||[]).find(([s])=>e===s);if(n){let[s,r,o]=n;return o}else return typeof i=="function"?i():i},deleteSticky(t,e){this.updatePrivate(t,"sticky",[],i=>i.filter(([n,s])=>n!==e))},putSticky(t,e,i){let n=i(t);this.updatePrivate(t,"sticky",[],s=>{let r=s.findIndex(([o])=>e===o);return r>=0?s[r]=[e,i,n]:s.push([e,i,n]),s})},applyStickyOperations(t){let e=ue.private(t,"sticky");e&&e.forEach(([i,n,s])=>this.putSticky(t,i,n))},isLocked(t){return t.hasAttribute&&t.hasAttribute(q)},attributeIgnored(t,e){return e.some(i=>t.name==i||i==="*"||i.includes("*")&&t.name.match(i)!=null)}},f=ue,Qe=class{static isActive(t,e){let i=e._phxRef,n=i===void 0,s=t.getAttribute(Dn).split(","),r=!n&&s.indexOf(i)>=0;return e.size>0&&(n||r)}static isPreflighted(t,e){return t.getAttribute($n).split(",").indexOf(Z.genFileRef(e))>=0&&this.isActive(t,e)}static isPreflightInProgress(t){return t._preflightInProgress===!0}static markPreflightInProgress(t){t._preflightInProgress=!0}constructor(t,e,i,n){this.ref=Z.genFileRef(e),this.fileEl=t,this.file=e,this.view=i,this.meta=null,this._isCancelled=!1,this._isDone=!1,this._progress=0,this._lastProgressSent=-1,this._onCancel=function(){},this._onDone=function(){},this._onElUpdated=this.onElUpdated.bind(this),this.fileEl.addEventListener(Ri,this._onElUpdated),this.autoUpload=n}metadata(){return this.meta}progress(t){this._progress=Math.floor(t),this._progress>this._lastProgressSent&&(this._progress>=100?(this._progress=100,this._lastProgressSent=100,this._isDone=!0,this.view.pushFileProgress(this.fileEl,this.ref,100,()=>{Z.untrackFile(this.fileEl,this.file),this._onDone()})):(this._lastProgressSent=this._progress,this.view.pushFileProgress(this.fileEl,this.ref,this._progress)))}isCancelled(){return this._isCancelled}cancel(){this.file._preflightInProgress=!1,this._isCancelled=!0,this._isDone=!0;try{this._onCancel()}finally{this._onDone()}}isDone(){return this._isDone}error(t="failed"){this.fileEl.removeEventListener(Ri,this._onElUpdated),this.view.pushFileProgress(this.fileEl,this.ref,{error:t}),this.isAutoUpload()||Z.clearFiles(this.fileEl)}isAutoUpload(){return this.autoUpload}onCancel(t){this.isCancelled()?t():this._onCancel=t}onDone(t){this._onDone=()=>{this.fileEl.removeEventListener(Ri,this._onElUpdated),t()}}onElUpdated(){this.fileEl.getAttribute(Dn).split(",").indexOf(this.ref)===-1&&(Z.untrackFile(this.fileEl,this.file),this.cancel())}toPreflightPayload(){return{last_modified:this.file.lastModified,name:this.file.name,relative_path:this.file.webkitRelativePath,size:this.file.size,type:this.file.type,ref:this.ref,meta:typeof this.file.meta=="function"?this.file.meta():void 0}}uploader(t){if(this.meta.uploader){let e=t[this.meta.uploader]||this.view.logError("upload.missing-uploader",`no uploader configured for ${this.meta.uploader}`,{uploader:this.meta.uploader,uploaders:t});return{name:this.meta.uploader,callback:e}}else return{name:"channel",callback:Al}}zipPostFlight(t){this.meta=t.entries[this.ref],this.meta||this.view.logError("upload.missing-preflight-response",`no preflight upload response returned with ref ${this.ref}`,{ref:this.ref,input:this.fileEl,response:t},{attribution:"internal"})}},Ml=0,Z=class Nn{static genFileRef(e){let i=e._phxRef;return i!==void 0?i:(e._phxRef=(Ml++).toString(),e._phxRef)}static getEntryDataURL(e,i){let n=this.activeFiles(e).find(s=>this.genFileRef(s)===i);return n?URL.createObjectURL(n):null}static hasUploadsInProgress(e){let i=0;return f.findUploadInputs(e).forEach(n=>{n.getAttribute($n)!==n.getAttribute(nl)&&i++}),i>0}static hasUploadErrors(e){return f.findUploadInputs(e).some(i=>(i.getAttribute(gr)||"")!=="")}static serializeUploads(e){let i=this.activeFiles(e),n={};return i.forEach(s=>{let r={path:e.name},o=e.getAttribute(Vt);n[o]=n[o]||[],r.ref=this.genFileRef(s),r.last_modified=s.lastModified,r.name=s.name||r.ref,r.relative_path=s.webkitRelativePath,r.type=s.type,r.size=s.size,typeof s.meta=="function"&&(r.meta=s.meta()),n[o].push(r)}),n}static clearFiles(e){e.value=null,e.removeAttribute(Vt),f.putPrivate(e,"files",[])}static untrackFile(e,i){f.putPrivate(e,"files",f.private(e,"files").filter(n=>!Object.is(n,i)))}static trackFiles(e,i,n){if(e.getAttribute("multiple")!==null){let s=i.filter(r=>!this.activeFiles(e).find(o=>Object.is(o,r)));f.updatePrivate(e,"files",[],r=>r.concat(s)),e.value=""}else n&&n.files.length>0&&(e.files=n.files),f.putPrivate(e,"files",i)}
9static activeFileInputs(e){let i=f.findUploadInputs(e);return Array.from(i).filter(n=>n.files&&this.activeFiles(n).length>0)}static activeFiles(e){return(f.private(e,"files")||[]).filter(i=>Qe.isActive(e,i))}static inputsAwaitingPreflight(e){let i=f.findUploadInputs(e);return Array.from(i).filter(n=>this.filesAwaitingPreflight(n).length>0)}static filesAwaitingPreflight(e){return this.activeFiles(e).filter(i=>!Qe.isPreflighted(e,i)&&!Qe.isPreflightInProgress(i))}static markPreflightInProgress(e){e.forEach(i=>Qe.markPreflightInProgress(i.file))}constructor(e,i,n){this.autoUpload=f.isAutoUpload(e),this.view=i,this.onComplete=n,this._entries=Array.from(Nn.filesAwaitingPreflight(e)||[]).map(s=>new Qe(e,s,i,this.autoUpload)),Nn.markPreflightInProgress(this._entries),this.numEntriesInProgress=this._entries.length}isAutoUpload(){return this.autoUpload}entries(){return this._entries}cancel(){this._entries.filter(e=>!e.isDone()).forEach(e=>e.cancel())}initAdapterUpload(e,i,n){this._entries=this._entries.map(r=>(r.isCancelled()?(this.numEntriesInProgress--,this.numEntriesInProgress===0&&this.onComplete()):(r.zipPostFlight(e),r.onDone(()=>{this.numEntriesInProgress--,this.numEntriesInProgress===0&&this.onComplete()})),r));let s=this._entries.reduce((r,o)=>{if(!o.meta)return r;let{name:a,callback:l}=o.uploader(n.uploaders);return r[a]=r[a]||{callback:l,entries:[]},r[a].entries.push(o),r},{});for(let r in s){let{callback:o,entries:a}=s[r];o(a,i,e,n)}}},Pl={anyOf(t,e){return e.some(i=>t instanceof i)},isFocusable(t,e=!1){return t instanceof HTMLAnchorElement&&t.rel!=="ignore"||t instanceof HTMLAreaElement&&t.href!==void 0||!("disabled"in t&&t.disabled)&&this.anyOf(t,[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement,HTMLButtonElement])||t instanceof HTMLIFrameElement||t instanceof HTMLElement&&t.tabIndex>=0&&t.getAttribute("aria-hidden")!=="true"||!e&&t.getAttribute("tabindex")!==null&&t.getAttribute("aria-hidden")!=="true"},attemptFocus(t,e=!1){if(this.isFocusable(t,e))try{t.focus()}catch{}return!!document.activeElement&&document.activeElement.isSameNode(t)},focusFirstInteractive(t){let e=t.firstElementChild;for(;e;){if(this.attemptFocus(e,!0)||this.focusFirstInteractive(e))return!0;e=e.nextElementSibling}return!1},focusFirst(t){let e=t.firstElementChild;for(;e;){if(this.attemptFocus(e)||this.focusFirst(e))return!0;e=e.nextElementSibling}return!1},focusLast(t){let e=t.lastElementChild;for(;e;){if(this.attemptFocus(e)||this.focusLast(e))return!0;e=e.previousElementSibling}return!1}},vt=Pl,Er=t=>["HTML","BODY"].indexOf(t.nodeName.toUpperCase())>=0?null:["scroll","auto"].indexOf(getComputedStyle(t).overflowY)>=0?t:Er(t.parentElement),nr=t=>t?t.scrollTop:document.documentElement.scrollTop||document.body.scrollTop,zn=t=>t?t.getBoundingClientRect().bottom:window.innerHeight||document.documentElement.clientHeight,Vn=t=>t?t.getBoundingClientRect().top:0,Il=(t,e)=>{let i=t.getBoundingClientRect();return Math.ceil(i.top)>=Vn(e)&&Math.floor(i.top)<=zn(e)},Dl=(t,e)=>{let i=t.getBoundingClientRect();return Math.ceil(i.bottom)>=Vn(e)&&Math.floor(i.bottom)<=zn(e)},sr=(t,e)=>{let i=t.getBoundingClientRect();return Math.ceil(i.top)>=Vn(e)&&Math.floor(i.top)<=zn(e)},Ll={mounted(){this.scrollContainer=Er(this.el);let t=nr(this.scrollContainer),e=!1,i=500,n=null,s=this.throttle(i,(a,l)=>{n=()=>!0,this.liveSocket.js().push(this.el,a,{value:{id:l.id,_overran:!0},callback:()=>{n=null}})}),r=this.throttle(i,(a,l)=>{n=()=>l.scrollIntoView({block:"start"}),this.liveSocket.js().push(this.el,a,{value:{id:l.id},callback:()=>{n=null,window.requestAnimationFrame(()=>{sr(l,this.scrollContainer)||l.scrollIntoView({block:"start"})})}})}),o=this.throttle(i,(a,l)=>{n=()=>l.scrollIntoView({block:"end"}),this.liveSocket.js().push(this.el,a,{value:{id:l.id},callback:()=>{n=null,window.requestAnimationFrame(()=>{sr(l,this.scrollContainer)||l.scrollIntoView({block:"end"})})}})});this.throttles=[s,r,o],this.onScroll=a=>{let l=nr(this.scrollContainer);if(n)return t=l,n();let h=this.findOverrunTarget(),c=this.el.getAttribute(this.liveSocket.binding("viewport-top")),d=this.el.getAttribute(this.liveSocket.b
9inding("viewport-bottom")),m=this.el.lastElementChild,p=this.el.firstElementChild,u=l<t,v=l>t;u&&c&&!e&&h.top>=0?(e=!0,s(c,p)):v&&e&&h.top<=0&&(e=!1),c&&u&&p&&Il(p,this.scrollContainer)?r(c,p):d&&v&&m&&Dl(m,this.scrollContainer)&&o(d,m),t=l},this.scrollContainer?this.scrollContainer.addEventListener("scroll",this.onScroll):window.addEventListener("scroll",this.onScroll)},updated(){this.scrollContainer&&!this.scrollContainer.isConnected&&(this.destroyed(),this.mounted())},destroyed(){this.throttles?.forEach(t=>t.cancel()),this.throttles=null,this.scrollContainer?this.scrollContainer.removeEventListener("scroll",this.onScroll):window.removeEventListener("scroll",this.onScroll)},throttle(t,e){let i=0,n=null,s=(...r)=>{let o=Date.now(),a=t-(o-i);a<=0||a>t?(n!==null&&(clearTimeout(n),n=null),i=o,e(...r)):n===null&&(n=setTimeout(()=>{i=Date.now(),n=null,e(...r)},a))};return s.cancel=()=>{n!==null&&(clearTimeout(n),n=null)},s},findOverrunTarget(){let t,e=this.el.getAttribute(this.liveSocket.binding(sl));if(e){let i=document.getElementById(e);if(i)t=i.getBoundingClientRect();else throw new Error("did not find element with id "+e)}else t=this.el.getBoundingClientRect();return t}},Rl={activeRefs(){return this.el.getAttribute(Dn)},preflightedRefs(){return this.el.getAttribute($n)},errorRefs(){return this.el.getAttribute(gr)||""},hasSelectedFiles(){return(this.el.files?.length||0)>0||Z.activeFiles(this.el).length>0||this.activeRefs()!==""||this.errorRefs()!==""},maybeRemoveRequired(){this.hasSelectedFiles()&&this.el.removeAttribute("required")},mounted(){this.js().ignoreAttributes(this.el,["value"]),this.preflightedWas=this.preflightedRefs(),this.errorRefsWas=this.errorRefs(),this.el.addEventListener("input",()=>this.maybeRemoveRequired()),this.maybeRemoveRequired()},updated(){let t=this.preflightedRefs(),e=this.errorRefs();this.errorRefsWas!==e&&(this.errorRefsWas=e,e!==""&&this.__view().cancelSubmit(this.el.form)),this.preflightedWas!==t&&(this.preflightedWas=t,t===""&&this.__view().cancelSubmit(this.el.form)),this.activeRefs()===""&&(this.el.value=""),this.maybeRemoveRequired(),this.el.dispatchEvent(new CustomEvent(Ri))}},Ol={mounted(){this.ref=this.el.getAttribute("data-phx-entry-ref"),this.inputEl=document.getElementById(this.el.getAttribute(Vt)),this.url=Z.getEntryDataURL(this.inputEl,this.ref),this.el.src=this.url},destroyed(){URL.revokeObjectURL(this.url)}},Hl={LiveFileUpload:Rl,LiveImgPreview:Ol,FocusWrap:{mounted(){this.focusStart=this.el.firstElementChild,this.focusEnd=this.el.lastElementChild,this.focusStart.addEventListener("focus",t=>{if(!t.relatedTarget||!this.el.contains(t.relatedTarget)){let e=t.target.nextElementSibling;vt.attemptFocus(e)||vt.focusFirst(e)}else vt.focusLast(this.el)}),this.focusEnd.addEventListener("focus",t=>{if(!t.relatedTarget||!this.el.contains(t.relatedTarget)){let e=t.target.previousElementSibling;vt.attemptFocus(e)||vt.focusLast(e)}else vt.focusFirst(this.el)}),this.el.contains(document.activeElement)||(this.el.addEventListener("phx:show-end",()=>this.el.focus()),window.getComputedStyle(this.el).display!=="none"&&vt.focusFirst(this.el))}},InfiniteScroll:Ll},Fl=Hl,Un=class{static onUnlock(t,e){if(!f.isLocked(t)&&!t.closest(`[${q}]`))return e();let i=t.closest(`[${q}]`),n=i.closest(`[${q}]`).getAttribute(q);i.addEventListener(`phx:undo-lock:${n}`,()=>{e()},{once:!0})}constructor(t){this.el=t,this.loadingRef=t.hasAttribute(Re)?parseInt(t.getAttribute(Re),10):null,this.lockRef=t.hasAttribute(q)?parseInt(t.getAttribute(q),10):null}maybeUndo(t,e,i){if(!this.isWithin(t)){f.updatePrivate(this.el,Bs,[],n=>(n.push(t),n));return}this.undoLocks(t,e,i),this.undoLoading(t,e),f.updatePrivate(this.el,Bs,[],n=>n.filter(s=>{let r={detail:{ref:s,event:e},bubbles:!0,cancelable:!1};return this.loadingRef&&this.loadingRef>s&&this.el.dispatchEvent(new CustomEvent(`phx:undo-loading:${s}`,r)),this.lockRef&&this.lockRef>s&&this.el.dispatchEvent(new CustomEvent(`phx:undo-lock:${s}`,r)),s>t})),this.isFullyResolvedBy(t)&&this.el.removeAttribute(Et)}isWithin(t){return!(this.loadingRef!==null&&this.loadingRef>t&&this.lockRef!==null&&this.lockRef>t)}undoLocks(t,e,i){if(!this.isLockUndoneBy(t))return;let n=f.private(this.el,q);
9n&&(i(n),f.deletePrivate(this.el,q)),this.el.removeAttribute(q);let s={detail:{ref:t,event:e},bubbles:!0,cancelable:!1};this.el.dispatchEvent(new CustomEvent(`phx:undo-lock:${this.lockRef}`,s))}undoLoading(t,e){if(!this.isLoadingUndoneBy(t)){this.canUndoLoading(t)&&this.el.classList.contains("phx-submit-loading")&&this.el.classList.remove("phx-change-loading");return}if(this.canUndoLoading(t)){this.el.removeAttribute(Re);let i=this.el.getAttribute(Ie),n=this.el.getAttribute(Fn);n!==null&&"readOnly"in this.el&&(this.el.readOnly=n==="true",this.el.removeAttribute(Fn)),i!==null&&"disabled"in this.el&&(this.el.disabled=i==="true",this.el.removeAttribute(Ie));let s=this.el.getAttribute(Ui);s!==null&&(this.el.textContent=s,this.el.removeAttribute(Ui));let r={detail:{ref:t,event:e},bubbles:!0,cancelable:!1};this.el.dispatchEvent(new CustomEvent(`phx:undo-loading:${this.loadingRef}`,r))}pr.forEach(i=>{(i!=="phx-submit-loading"||this.canUndoLoading(t))&&f.removeClass(this.el,i)})}isLoadingUndoneBy(t){return this.loadingRef===null?!1:this.loadingRef<=t}isLockUndoneBy(t){return this.lockRef===null?!1:this.lockRef<=t}isFullyResolvedBy(t){return(this.loadingRef===null||this.loadingRef<=t)&&(this.lockRef===null||this.lockRef<=t)}canUndoLoading(t){return this.lockRef===null||this.lockRef<=t}},Nl=class{constructor(t,e,i){let n=new Set,s=new Set([...e.children].map(o=>o.id)),r=[];Array.from(t.children).forEach(o=>{if(o.id&&(n.add(o.id),s.has(o.id))){let a=o.previousElementSibling&&o.previousElementSibling.id;r.push({elementId:o.id,previousElementId:a})}}),this.containerId=e.id,this.updateType=i,this.elementsToModify=r,this.elementIdsToAdd=[...s].filter(o=>!n.has(o))}perform(){let t=f.byId(this.containerId);t&&(this.elementsToModify.forEach(e=>{e.previousElementId?De(document.getElementById(e.previousElementId),i=>{De(document.getElementById(e.elementId),n=>{n.previousElementSibling&&n.previousElementSibling.id==i.id||i.insertAdjacentElement("afterend",n)})}):De(document.getElementById(e.elementId),i=>{i.previousElementSibling==null||t.insertAdjacentElement("afterbegin",i)})}),this.updateType=="prepend"&&this.elementIdsToAdd.reverse().forEach(e=>{De(document.getElementById(e),i=>t.insertAdjacentElement("afterbegin",i))}))}},rr=11;function Ul(t,e){var i=e.attributes,n,s,r,o,a;if(!(e.nodeType===rr||t.nodeType===rr)){for(var l=i.length-1;l>=0;l--)n=i[l],s=n.name,r=n.namespaceURI,o=n.value,r?(s=n.localName||s,a=t.getAttributeNS(r,s),a!==o&&(n.prefix==="xmlns"&&(s=n.name),t.setAttributeNS(r,s,o))):(a=t.getAttribute(s),a!==o&&t.setAttribute(s,o));for(var h=t.attributes,c=h.length-1;c>=0;c--)n=h[c],s=n.name,r=n.namespaceURI,r?(s=n.localName||s,e.hasAttributeNS(r,s)||t.removeAttributeNS(r,s)):e.hasAttribute(s)||t.removeAttribute(s)}}var Ii,Bl="http://www.w3.org/1999/xhtml",et=typeof document>"u"?void 0:document,$l=!!et&&"content"in et.createElement("template"),jl=!!et&&et.createRange&&"createContextualFragment"in et.createRange();function ql(t){var e=et.createElement("template");return e.innerHTML=t,e.content.childNodes[0]}function zl(t){Ii||(Ii=et.createRange(),Ii.selectNode(et.body));var e=Ii.createContextualFragment(t);return e.childNodes[0]}function Vl(t){var e=et.createElement("body");return e.innerHTML=t,e.childNodes[0]}function Wl(t){return t=t.trim(),$l?ql(t):jl?zl(t):Vl(t)}function Di(t,e){var i=t.nodeName,n=e.nodeName,s,r;return i===n?!0:(s=i.charCodeAt(0),r=n.charCodeAt(0),s<=90&&r>=97?i===n.toUpperCase():r<=90&&s>=97?n===i.toUpperCase():!1)}function Kl(t,e){return!e||e===Bl?et.createElement(t):et.createElementNS(e,t)}function Xl(t,e){for(var i=t.firstChild;i;){var n=i.nextSibling;e.appendChild(i),i=n}return e}function Mn(t,e,i){t[i]!==e[i]&&(t[i]=e[i],t[i]?t.setAttribute(i,""):t.removeAttribute(i))}var or={OPTION:function(t,e){var i=t.parentNode;if(i){var n=i.nodeName.toUpperCase();n==="OPTGROUP"&&(i=i.parentNode,n=i&&i.nodeName.toUpperCase()),n==="SELECT"&&!i.hasAttribute("multiple")&&(t.hasAttribute("selected")&&!e.selected&&(t.setAttribute("selected","selected"),t.removeAttribute("selected")),i.selectedIndex=-1)}Mn(t,e,"selected")},INPUT:function(t,e){Mn(t,e,"checked"),Mn(t,e,"disabled"),t.value!==e.value&&(t.value=e.value),e.hasAttribute("value")||t.removeAttribute("value")},TEXTAREA:function(t,e){var i=e.value;t.value!==i&&(t.value=i);var n=t.firstChild;if(n){var s=n.nodeValue;if(s==i||!i&&s==t.placeholder)return;n.nodeValue=i}},SELECT:function(t,e){if(!e.hasAttribute("multiple")){for(var i=-1,n=0,s=t.firstChild,r,o;s;
9)if(o=s.nodeName&&s.nodeName.toUpperCase(),o==="OPTGROUP")r=s,s=r.firstChild,s||(s=r.nextSibling,r=null);else{if(o==="OPTION"){if(s.hasAttribute("selected")){i=n;break}n++}s=s.nextSibling,!s&&r&&(s=r.nextSibling,r=null)}t.selectedIndex=i}}},ti=1,ar=11,lr=3,hr=8;function ee(){}function Gl(t){if(t)return t.getAttribute&&t.getAttribute("id")||t.id}function Jl(t){return function(i,n,s){if(s||(s={}),typeof n=="string")if(i.nodeName==="#document"||i.nodeName==="HTML"){var r=n;n=et.createElement("html"),n.innerHTML=r}else if(i.nodeName==="BODY"){var o=n;n=et.createElement("html"),n.innerHTML=o;var a=n.querySelector("body");a&&(n=a)}else n=Wl(n);else n.nodeType===ar&&(n=n.firstElementChild);var l=s.getNodeKey||Gl,h=s.onBeforeNodeAdded||ee,c=s.onNodeAdded||ee,d=s.onBeforeElUpdated||ee,m=s.onElUpdated||ee,p=s.onBeforeNodeDiscarded||ee,u=s.onNodeDiscarded||ee,v=s.onBeforeElChildrenUpdated||ee,y=s.skipFromChildren||ee,M=s.addChild||function(_,A){return _.appendChild(A)},L=s.childrenOnly===!0,H=s.keyedRoot===!0,R=Object.create(null),E=[];function S(_){E.push(_)}function T(_,A){if(_.nodeType===ti)for(var F=_.firstChild;F;){var O=void 0;A&&(O=l(F))?S(O):(u(F),F.firstChild&&T(F,A)),F=F.nextSibling}}function X(_,A,F){p(_)!==!1&&(A&&A.removeChild(_),u(_),T(_,F))}function g(_){if(_.nodeType===ti||_.nodeType===ar)for(var A=_.firstChild;A;){var F=l(A);F&&(R[F]=A),g(A),A=A.nextSibling}}g(i);function w(_){c(_);for(var A=_.firstChild;A;){var F=A.nextSibling,O=l(A);if(O){var N=R[O];N&&Di(A,N)?(A.parentNode.replaceChild(N,A),G(N,A)):w(A)}else w(A);A=F}}function j(_,A,F){for(;A;){var O=A.nextSibling;(F=l(A))?S(F):X(A,_,!0),A=O}}function G(_,A,F){var O=l(A);if(O&&delete R[O],!F){var N=d(_,A);if(N===!1||(N instanceof HTMLElement&&(_=N,g(_)),t(_,A),m(_),v(_,A)===!1))return}_.nodeName!=="TEXTAREA"?U(_,A):or.TEXTAREA(_,A)}function U(_,A){var F=y(_,A),O=A.firstChild,N=_.firstChild,Ae,jt,xe,Ci,Yt;t:for(;O;){for(Ci=O.nextSibling,Ae=l(O);!F&&N;){if(xe=N.nextSibling,O.isSameNode&&O.isSameNode(N)){O=Ci,N=xe;continue t}jt=l(N);var ki=N.nodeType,Zt=void 0;if(ki===O.nodeType&&(ki===ti?(Ae?Ae!==jt&&((Yt=R[Ae])?xe===Yt?Zt=!1:(_.insertBefore(Yt,N),jt?S(jt):X(N,_,!0),N=Yt,jt=l(N)):Zt=!1):jt&&(Zt=!1),Zt=Zt!==!1&&Di(N,O),Zt&&G(N,O)):(ki===lr||ki==hr)&&(Zt=!0,N.nodeValue!==O.nodeValue&&(N.nodeValue=O.nodeValue))),Zt){O=Ci,N=xe;continue t}jt?S(jt):X(N,_,!0),N=xe}if(Ae&&(Yt=R[Ae])&&Di(Yt,O))F||M(_,Yt),G(Yt,O);else{var wn=h(O);wn!==!1&&(wn&&(O=wn),O.actualize&&(O=O.actualize(_.ownerDocument||et)),M(_,O),w(O))}O=Ci,N=xe}j(_,N,jt);var Hs=or[_.nodeName];Hs&&Hs(_,A)}function ht(){for(var _=0,A=E.length;_<A;_++){var F=R[E[_]];F&&X(F,F.parentNode,!1)}}if(H&&!L){var ct=l(i),_t=l(n);if((ct||_t)&&ct!==_t)return n.actualize&&(n=n.actualize(i.ownerDocument||et)),u(i),i.parentNode&&i.parentNode.replaceChild(n,i),w(n),T(i,!1),ht(),n}var W=i,Lt=W.nodeType,Si=n.nodeType;if(!L){if(Lt===ti)Si===ti?Di(i,n)||(u(i),W=Xl(i,Kl(n.nodeName,n.namespaceURI))):W=n;else if(Lt===lr||Lt===hr){if(Si===Lt)return W.nodeValue!==n.nodeValue&&(W.nodeValue=n.nodeValue),W;W=n}}if(W===n)u(i);else{if(n.isSameNode&&n.isSameNode(W))return;G(W,n,L),ht()}return!L&&W!==i&&i.parentNode&&(W.actualize&&(W=W.actualize(i.ownerDocument||et)),i.parentNode.replaceChild(W,i)),W}}var Yl=Jl(Ul),Bn=Yl,Li=class{constructor(t,e,i,n,s,r={}){this.view=t,this.liveSocket=t.liveSocket,this.container=e,this.rootID=t.root.id,this.html=i,this.streams=n,this.streamInserts={},this.streamComponentRestore={},this.targetCID=s,this.pendingRemoves=[],this.phxRemove=this.liveSocket.binding("remove"),this.targetContainer=s?f.getComponent(this.view.id,s):e,this.beforeUpdatedCallbacks=[],this.afterAddedCallbacks=[],this.afterUpdatedCallbacks=[],this.afterPhxChildAddedCallbacks=[],this.afterDiscardedCallbacks=[],this.afterTransitionsDiscardedCallbacks=[],this.withChildren=r.withChildren||r.undoRef!==void 0||!1,this.undoRef=r.undoRef??null}beforeUpdated(t){this.beforeUpdatedCallbacks.push(t)}afterAdded(t){this.afterAddedCallbacks.push(t)}afterUpdated(t){this.afterUpdatedCallbacks.push(t)}afterPhxChildAdded(t){this.afterPhxChildAddedCallbacks.push(t)}afterDiscarded(t){this.afterDiscardedCallbacks.push(t)}afterTransitionsDiscarded(t){this.afterTransitionsDiscardedCallbacks.push(t)}
9markPrunableContentForRemoval(){let t=this.liveSocket.binding(Bi);f.all(this.container,`[${t}=append] > *, [${t}=prepend] > *`,e=>{e.setAttribute($s,"")})}perform(t){let{view:e,liveSocket:i,html:n,container:s}=this,r=(E,S,T,X)=>e.logError(E,S,T,X),o=this.targetContainer;if(this.targetCID){let E=o.closest(`[${q}]`);if(E&&!E.isSameNode(o)){let S=f.private(E,q);if(S&&(o=S.querySelector(`[data-phx-component="${this.targetCID}"]`),!o))return}}let a=i.getActiveElement(),{selectionStart:l,selectionEnd:h}=a&&f.hasSelectionRange(a)?a:{},c=i.binding(Bi),d=i.binding(Rn),m=i.binding(On),p=i.binding(rl),u=i.binding(hl),v=[],y=[],M=[],L=[],H=null,R=(E,S,T=this.withChildren)=>{let X={childrenOnly:E.getAttribute(xt)===null&&!T,keyedRoot:E.getAttribute(xt)!=null,getNodeKey:g=>!(g instanceof Element)||f.isPhxDestroyed(g)?null:t?g.id:f.private(g,"clientsideIdAttribute")?g.getAttribute(Ln):g.id||g.getAttribute(Ln),skipFromChildren:g=>g.getAttribute(c)===Oi,addChild:(g,w)=>{let{ref:j,streamAt:G}=this.getStreamInsert(w);if(j===void 0)return g.appendChild(w);if(this.setStreamRef(w,j),G===0)g.insertAdjacentElement("afterbegin",w);else if(G===-1){let U=g.lastElementChild;if(U&&!U.hasAttribute(Ge)){let ht=Array.from(g.children).find(ct=>!ct.hasAttribute(Ge));g.insertBefore(w,ht??null)}else g.appendChild(w)}else if(G>0){let U=Array.from(g.children)[G];g.insertBefore(w,U)}},onBeforeNodeAdded:g=>{if(!(g instanceof Element))return g;if(this.getStreamInsert(g)?.updateOnly&&!this.streamComponentRestore[g.id])return!1;f.maintainPrivateHooks(g,g,d,m);let w=g;return this.streamComponentRestore[g.id]&&(w=this.streamComponentRestore[g.id],delete this.streamComponentRestore[g.id],R(w,g,!0)),w},onNodeAdded:g=>{if(!(g instanceof Element)){v.push(g);return}this.maybeReOrderStream(g,!0),f.isPortalTemplate(g)&&L.push(()=>this.teleport(g,R)),g instanceof HTMLImageElement&&g.srcset?g.srcset=g.srcset:g instanceof HTMLVideoElement&&g.autoplay&&g.play(),f.isNowTriggerFormExternal(g,p)&&(H=g),(f.isPhxChild(g)&&e.ownsElement(g)||f.isPhxSticky(g)&&e.ownsElement(g.parentNode))&&this.trackAfterPhxChildAdded(g),g.nodeName==="SCRIPT"&&g.hasAttribute(Hi)&&(g=this.handleRuntimeHook(g,S)),v.push(g)},onNodeDiscarded:g=>this.onNodeDiscarded(g),onBeforeNodeDiscarded:g=>{if(!(g instanceof Element)||g.getAttribute($s)!==null)return!0;if(g.parentElement!==null&&g.id&&f.isPhxUpdate(g.parentElement,c,[Oi,"append","prepend"])||g.getAttribute(ge)||this.maybePendingRemove(g)||this.skipCIDSibling(g))return!1;if(f.isPortalTemplate(g)){let w=document.getElementById(g.content.firstElementChild?.id||"");w&&(w.remove(),X.onNodeDiscarded(w),this.view.dropPortalElementId(w.id))}return!0},onElUpdated:g=>{f.isNowTriggerFormExternal(g,p)&&(H=g),y.push(g),this.maybeReOrderStream(g,!1)},onBeforeElUpdated:(g,w)=>{f.syncPendingAttrs(g,w),f.maintainPrivateHooks(g,w,d,m),f.cleanChildNodes(w,c,r);let j=a&&g.isSameNode(a)&&f.isEditableInput(g),G=j&&this.isChangedSelect(g,w);if(this.skipCIDSibling(w))return this.maybeCloneLockedElement(g,j),this.copyNestedPrivateLock(g,w),this.maybeReOrderStream(g),!1;if(f.isPhxSticky(g))return[Ut,pe,zt].map(U=>[U,g.getAttribute(U),w.getAttribute(U)]).forEach(([U,ht,ct])=>{ct&&ht!==ct&&g.setAttribute(U,ct)}),!1;if(f.isIgnored(g,c)||g.form&&g.form.isSameNode(H))return this.trackBeforeUpdated(g,w),f.mergeAttrs(g,w,{isIgnored:f.isIgnored(g,c)}),y.push(g),f.applyStickyOperations(g),!1;if(g.type==="number"&&g.validity&&g.validity.badInput)return!1;if(g=this.maybeCloneLockedElement(g,j),f.isPhxChild(w)){let U=g.getAttribute(Ut);return f.mergeAttrs(g,w,{exclude:[pe]}),U!==""&&g.setAttribute(Ut,U),g.setAttribute(zt,this.rootID),f.applyStickyOperations(g),!1}return this.copyNestedPrivateLock(g,w),f.copyPrivates(w,g),f.isPortalTemplate(w)?(L.push(()=>this.teleport(w,R)),g.content.replaceChildren(w.content.cloneNode(!0)),!1):j&&g.type!=="hidden"&&!G&&!w.hasAttribute(u)?(this.trackBeforeUpdated(g,w),f.mergeFocusedInput(g,w),f.syncAttrsToProps(g),y.push(g),f.applyStickyOperations(g),!1):(G&&g.blur(),f.isPhxUpdate(w,c,["append","prepend"])&&M.push(new Nl(g,w,w.getAttribute(c))),f.syncAttrsToProps(w),f.applyStickyOperations(w),this.trackBeforeUpdated(g,w),g)}};
9Bn(E,S,X)};if(this.trackBeforeUpdated(s,s),i.time("morphdom",()=>{this.streams.forEach(([S,T,X,g])=>{T.forEach(([w,j,G,U])=>{this.streamInserts[w]={ref:S,streamAt:j,limit:G,reset:g,updateOnly:U}}),g!==void 0&&f.all(document,`[${Ge}="${S}"]`,w=>{this.removeStreamChildElement(w)}),X.forEach(w=>{let j=document.getElementById(w);j&&this.removeStreamChildElement(j)})}),t&&f.all(this.container,`[${c}=${Oi}]`).filter(S=>this.view.ownsElement(S)).forEach(S=>{Array.from(S.children).forEach(T=>{this.removeStreamChildElement(T,!0)})}),R(o,n);let E=0;for(;L.length>0&&E<5;){let S=L.slice();L=[],S.forEach(T=>T()),E++}this.view.portalElementIds.forEach(S=>{let T=document.getElementById(S);if(T){let X=T.getAttribute(ne);X&&(document.getElementById(X)||(T.remove(),this.onNodeDiscarded(T),this.view.dropPortalElementId(S)))}})}),i.isDebugEnabled()&&(Sl(r),Cl(this.streamInserts,r),Array.from(document.querySelectorAll("input[name=id]")).forEach(E=>{E instanceof HTMLInputElement&&E.form&&r("dom.form-input-name-id",`Detected an input with name="id" inside a form! This will cause problems when patching the DOM. 10`,{el:E},{attribution:"app"})})),M.length>0&&i.time("post-morph append/prepend restoration",()=>{M.forEach(E=>E.perform())}),i.silenceEvents(()=>f.restoreFocus(a,l,h)),f.dispatchEvent(document,"phx:update"),v.forEach(E=>this.trackAfterAdded(E)),y.forEach(E=>this.trackAfterUpdated(E)),this.transitionPendingRemoves(),H){i.unload();let E=f.private(H,"submitter");if(E&&E.name&&o.contains(E)){let S=document.createElement("input");S.type="hidden";let T=E.getAttribute("form");T&&S.setAttribute("form",T),S.name=E.name,S.value=E.value,E.parentElement.insertBefore(S,E)}Object.getPrototypeOf(H).submit.call(H)}return!0}trackBeforeUpdated(t,e){this.beforeUpdatedCallbacks.forEach(i=>i(t,e))}trackAfterAdded(t){this.afterAddedCallbacks.forEach(e=>e(t))}trackAfterUpdated(t){this.afterUpdatedCallbacks.forEach(e=>e(t))}trackAfterPhxChildAdded(t){this.afterPhxChildAddedCallbacks.forEach(e=>e(t))}trackAfterDiscarded(t){this.afterDiscardedCallbacks.forEach(e=>e(t))}trackAfterTransitionsDiscarded(t){this.afterTransitionsDiscardedCallbacks.forEach(e=>e(t))}onNodeDiscarded(t){(f.isPhxChild(t)||f.isPhxSticky(t))&&this.liveSocket.destroyViewByEl(t),this.trackAfterDiscarded(t)}maybePendingRemove(t){return t.getAttribute&&t.getAttribute(this.phxRemove)!==null?(this.pendingRemoves.push(t),!0):!1}removeStreamChildElement(t,e=!1){!e&&!this.view.ownsElement(t)||(this.streamInserts[t.id]?(this.streamComponentRestore[t.id]=t,t.remove()):this.maybePendingRemove(t)||(t.remove(),this.onNodeDiscarded(t)))}getStreamInsert(t){return(t.id?this.streamInserts[t.id]:{})||{}}setStreamRef(t,e){f.putSticky(t,Ge,i=>i.setAttribute(Ge,e))}maybeReOrderStream(t,e=!1){let{ref:i,streamAt:n,reset:s}=this.getStreamInsert(t);if(n!==void 0&&(this.setStreamRef(t,i),!(!s&&!e)&&t.parentElement)){if(n===0)this.moveOrInsertBefore(t.parentElement,t,t.parentElement.firstElementChild);else if(n>0){let r=Array.from(t.parentElement.children),o=r.indexOf(t);if(n>=r.length-1)this.moveOrInsertBefore(t.parentElement,t,null);else{let a=r[n];o>n?this.moveOrInsertBefore(t.parentElement,t,a):this.moveOrInsertBefore(t.parentElement,t,a.nextElementSibling)}}this.maybeLimitStream(t)}}moveOrInsertBefore(t,e,i){if(typeof t.moveBefore=="function")try{t.moveBefore(e,i);return}catch{}t.insertBefore(e,i)}maybeLimitStream(t){let{limit:e}=this.getStreamInsert(t);if(e!==null){let i=Array.from(t.parentElement.children);e<0&&i.length>e*-1?i.slice(0,i.length+e).forEach(n=>this.removeStreamChildElement(n)):e>=0&&i.length>e&&i.slice(e).forEach(n=>this.removeStreamChildElement(n))}}transitionPendingRemoves(){let{pendingRemoves:t,liveSocket:e}=this;t.length>0&&e.transitionRemoves(t,this.view,()=>{t.forEach(i=>{let n=f.firstPhxChild(i);n&&e.destroyViewByEl(n),i.remove()}),this.trackAfterTransitionsDiscarded(t)})}isChangedSelect(t,e){return!(t instanceof HTMLSelectElement)||t.multiple?!1:t.options.length!==e.options.length?!0:(e.value=t.value,!t.isEqualNode(e))}skipCIDSibling(t){return t.nodeType===Node.ELEMENT_NODE&&t.hasAttribute(vr)}maybeCloneLockedElement(t,e){if(!t.hasAttribute(Et))return t;let i=new Un(t);if(!t.hasAttribute(q)||this.undoRef!==null&&i.isLockUndoneBy(this.undoRef))return t;f.applyStickyOperations(t);let n=t.hasAttribute(q)?f.private(t,q)||t.cloneNode(!0):null;return n?(f.putPrivate(t,q,n),e?t:n):t}copyNestedPrivateLock(t,e){this.undoRef===null||!f.private(e,q)||f.putPrivate(t,q,f.private(e,q))}indexOf(t,e){return Array.from(t.children).indexOf(e)}teleport(t,e){let i=t.getAttribute(qn),n=document.querySelector(i);if(!n)throw new Error("portal target with selector "+i+" not found");let s=t.content.firstElementChild;if(this.skipCIDSibling(s))return;if(!s?.id)throw new Error("phx-portal template must have a single root element with ID!");let r=document.getElementById(s.id),o;r?(n.contains(r)||n.appendChild(r),o=r):(o=document.createElement(s.tagName),n.appendChild(o)),s.setAttribute(ge,this.view.id),s.setAttribute(ne,t.id),e(o,s,!0),s.removeAttribute(ge),s.removeAttribute(ne),this.view.pushPortalElementId(s.id)}handleRuntimeHook(t,e){let i=t.getAttribute(Hi),n=t.hasAttribute("nonce")?t.getAttribute("nonce"):null;if(t.hasAttribute("nonce")){let r=document.createElement("template");r.innerHTML=e,n=r.content.querySelector(`script[${Hi}="${CSS.escape(i)}"]`)?.getAttribute("nonce")??null}let s=document.createElement("script");return s.textContent=t.textContent,f.mergeAttrs(s,t,{isIgnored:!1}),n&&(s.nonce=n),t.replaceWith(s),s}},Zl=new Set(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),Ql=new Set(["'",'"']),Sr=(t,e,i)=>{let n,s,r,o,a,l,h,c,d=t.match(/^(\s*(?:<!--.*?-->\s*)*)<([^\s\/>]+)/);if(d===null)throw new Error(`malformed html ${t}`);for(n=d[0].length,r=d[1],a=d[2],l=n,n;n<t.length&&t.charAt(n)!==">";n++)if(t.charAt(n)==="="){let u=t.slice(n-3,n)===" id";n++;let v=t.charAt(n);if(Ql.has(v)){let y=n;for(n++,n;n<t.length&&t.charAt(n)!==v;n++);if(u){h=t.slice(y+1,n);break}}}let m=t.length-1;for(s=!1;m>=r.length+a.length;){let u=t.charAt(m);
10if(s)u==="-"&&t.slice(m-3,m)==="<!-"?(s=!1,m-=4):m-=1;else if(u===">"&&t.slice(m-2,m)==="--")s=!0,m-=3;else{if(u===">")break;m-=1}}o=t.slice(m+1,t.length);let p=Object.keys(e).map(u=>e[u]===!0?u:`${u}="${e[u]}"`).join(" ");if(i){let u=h?` id="${h}"`:"";Zl.has(a)?c=`<${a}${u}${p===""?"":" "}${p}/>`:c=`<${a}${u}${p===""?"":" "}${p}></${a}>`}else{let u=t.slice(l,m+1);c=`<${a}${p===""?"":" "}${p}${u}`}return[c,r,o]},$i=class{constructor(t,e){this.html="",this.pending=[]}get length(){let t=this.html.length;for(let e=0;e<this.pending.length;e++)t+=this.pending[e].length;return t}write(t){this.html+=t}toString(){return this.html}beginRoot(){this.pending.push(this.html),this.html=""}endRoot(t,e){let[i,n,s]=Sr(this.html,t,e);this.html=this.pending.pop()+n+i+s}enter(t,e,i){}exit(){}beginKeyedEntry(t){}endKeyedEntry(){}},Pn=Symbol("all changed"),th=class extends $i{constructor(t,e){super(t,e),this.frames=[],this.cursors=[],this.diff=this.cursorFor(t,e)}static preMerge(t){return wr(t)}cursorFor(t,e){if(t)return e===null?t:t[Q]&&t[Q][e]}onEnter(t){}onExit(t){}currentDiff(){return this.cursors.length>0?this.cursors[this.cursors.length-1]:this.diff}enter(t,e,i){let n=this.diffFor(this.currentDiff(),e),s={node:t,index:e,statics:i,changed:n!==void 0};this.cursors.push(n),this.frames.push(s),this.onEnter(s)}exit(){this.cursors.pop(),this.onExit(this.frames.pop())}beginKeyedEntry(t){this.cursors.push(this.keyedEntry(this.currentDiff(),t))}endKeyedEntry(){this.cursors.pop()}keyedEntry(t,e){let i=this.diffFor(t,B);if(i===Pn||i===void 0)return i;let n=i[e];return Array.isArray(n)?n[1]:typeof n=="number"?void 0:n}diffFor(t,e){if(t!=null)return t===Pn||t[gt]!==void 0?Pn:t[e]}},cr=class{static extract(t){let{[Qs]:e,[Zs]:i,[tr]:n}=t;return delete t[Qs],delete t[Zs],delete t[tr],{diff:t,title:n,reply:e||null,events:i||[]}}constructor(t,e,i=()=>$i){this.viewId=t,this.rendered={},this.magicId=0,this.bufferClass=i,this.initialMerge=!0,this.mergeDiff(e),this.initialMerge=!1}parentViewId(){return this.viewId}toString(t){let{buffer:e,streams:i}=this.recursiveToString(this.rendered,this.rendered[Q],t,!0,{},null);return{buffer:e,streams:i}}recursiveToString(t,e=t[Q],i,n,s,r){i=i?new Set(i):null;let o=this.bufferClass(),[a,l]=this.bufferPreMerge,h=new o(a===o?l:void 0,r),c={buffer:h,components:e,onlyCids:i,streams:new Set};return this.toOutputBuffer(t,null,c,n,s),{buffer:h.toString(),streams:c.streams}}componentCIDs(t){return Object.keys(t[Q]||{}).map(e=>parseInt(e))}isComponentOnlyDiff(t){return t[Q]?Object.keys(t).length===1:!1}getComponent(t,e){return t[Q][e]}resetRender(t){this.rendered[Q][t]&&(this.rendered[Q][t].reset=!0)}mergeDiff(t){let e=this.bufferClass();this.bufferPreMerge=[e,!this.initialMerge&&e.preMerge?e.preMerge(t):void 0];let i=t[Q],n={};if(delete t[Q],this.rendered=this.mutableMerge(this.rendered,t),this.rendered[Q]=this.rendered[Q]||{},i){let s=this.rendered[Q];for(let r in i)i[r]=this.cachedFindComponent(r,i[r],s,i,n);for(let r in i)s[r]=i[r];t[Q]=i}}cachedFindComponent(t,e,i,n,s){if(s[t])return s[t];{let r,o,a=e[gt];if(ie(a)){let l;a>0?l=this.cachedFindComponent(a,n[a],i,n,s):l=i[-a],o=l[gt],r=this.cloneMerge(l,e,!0),r[gt]=o}else r=e[gt]!==void 0||i[t]===void 0?e:this.cloneMerge(i[t],e,!1);return s[t]=r,r}}mutableMerge(t,e){return e[gt]!==void 0?e:(this.doMutableMerge(t,e),t)}doMutableMerge(t,e){if(e[B])this.mergeKeyed(t,e);else for(let i in e){let n=e[i],s=t[i];ce(n)&&n[gt]===void 0&&ce(s)?this.doMutableMerge(s,n):t[i]=n}t[Tn]&&(t.newRender=!0)}clone(t){return wr(t)}mergeKeyed(t,e){let i=e[B][Ys]&&this.clone(t);if(Object.entries(e[B]).forEach(([n,s])=>{if(!(n===Ft||n===Ys))if(Array.isArray(s)){let[r,o]=s;t[B][n]=i[B][r],this.doMutableMerge(t[B][n],o)}else if(typeof s=="number"){let r=s;t[B][n]=i[B][r]}else typeof s=="object"&&(t[B][n]||(t[B][n]={}),this.doMutableMerge(t[B][n],s))}),e[B][Ft]<t[B][Ft])for(let n=e[B][Ft];n<t[B][Ft];n++)delete t[B][n];t[B][Ft]=e[B][Ft],e[Pe]&&(t[Pe]=e[Pe]),e[te]&&(t[te]=e[te])}cloneMerge(t,e,i){let n;if(e[B])n=this.clone(t),this.mergeKeyed(n,e),i&&this.pruneInternalIds(n);else{n={...t,...e};
10for(let s in n){let r=e[s],o=t[s];ce(r)&&r[gt]===void 0&&ce(o)?n[s]=this.cloneMerge(o,r,i):r===void 0&&ce(o)&&(n[s]=this.cloneMerge(o,{},i))}}return i?this.deleteInternalIds(n):t[Tn]&&(n.newRender=!0),n}pruneInternalIds(t){for(let e in t)ce(t[e])&&this.pruneInternalIds(t[e]);this.deleteInternalIds(t)}deleteInternalIds(t){delete t.magicId,delete t.newRender}componentToString(t){let{buffer:e,streams:i}=this.recursiveCIDToString(this.rendered[Q],t,null),[n,s,r]=Sr(e,{});return{buffer:n,streams:i}}pruneCIDs(t){t.forEach(e=>delete this.rendered[Q][e])}get(){return this.rendered}isNewFingerprint(t={}){return!!t[gt]}templateStatic(t,e){return typeof t=="number"?e[t]:t}nextMagicID(){return this.magicId++,`m${this.magicId}-${this.parentViewId()}`}toOutputBuffer(t,e,i,n,s={}){if(t[B])return this.comprehensionToBuffer(t,e,i,n);t[te]&&(e=t[te],delete t[te]);let{[gt]:r}=t;r=this.templateStatic(r,e),t[gt]=r;let o=t[Tn];if(o&&i.buffer.beginRoot(),n&&o&&!t.magicId&&(t.newRender=!0,t.magicId=this.nextMagicID()),this.dynamicsToBuffer(t,r,e,i,n),o){let a=!1,l;n||t.magicId?(a=n&&!t.newRender,l={[Ln]:t.magicId,...s}):l=s,a&&(l[vr]=!0),i.buffer.endRoot(l,a),t.newRender=!1}}dynamicsToBuffer(t,e,i,n,s){let r=n.buffer;for(let o=0;o<e.length-1;o++)r.write(e[o]),r.enter(t,o,e),this.dynamicToBuffer(t[o],i,n,s),r.exit();r.write(e[e.length-1])}comprehensionToBuffer(t,e,i,n){let s=e||t[te],r=this.templateStatic(t[gt],e);t[gt]=r,delete t[te];for(let o=0;o<t[B][Ft];o++)i.buffer.beginKeyedEntry(o),this.dynamicsToBuffer(t[B][o],r,s,i,n),i.buffer.endKeyedEntry();if(t[Pe]){let o=t[Pe],[a,l,h,c]=o||[null,{},[],null];o!==void 0&&(t[B][Ft]>0||h.length>0||c)&&(delete t[Pe],t[B]={[Ft]:0},i.streams.add(o))}}dynamicToBuffer(t,e,i,n){if(typeof t=="number"){let{buffer:s,streams:r}=this.recursiveCIDToString(i.components,t,i.onlyCids);i.buffer.write(s),i.streams=new Set([...i.streams,...r])}else ce(t)?this.toOutputBuffer(t,e,i,n,{}):i.buffer.write(t)}recursiveCIDToString(t,e,i){if(t[e]){let n=t[e],s={[xt]:e,[Le]:this.viewId},r=i&&!i.has(e);n.newRender=!r,n.magicId=`c${e}-${this.parentViewId()}`;let o=!n.reset,{buffer:a,streams:l}=this.recursiveToString(n,t,i,o,s,e);return delete n.reset,{buffer:a,streams:l}}else throw Nt("render.missing-component",`no component for CID ${e}`,{cid:e,components:t},{viewId:this.viewId,attribution:"internal"}),new Error("Cannot continue render due to missing component: "+e)}},ei=[],dr=200,eh={exec(t,e,i,n,s,r){let[o,a]=r||[null,{callback:r&&r.callback}];(Array.isArray(i)?i:typeof i=="string"&&i.startsWith("[")?JSON.parse(i):[[o,a]]).forEach(([h,c])=>{h===o&&(c={...a,...c},c.callback=c.callback||a.callback),this.filterToEls(n.liveSocket,s,c).forEach(d=>{this[`exec_${h}`](t,e,i,n,s,d,c)})})},isVisible(t){return!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length>0)},isInViewport(t){let e=t.getBoundingClientRect(),i=window.innerHeight||document.documentElement.clientHeight,n=window.innerWidth||document.documentElement.clientWidth;return e.right>0&&e.bottom>0&&e.left<n&&e.top<i},exec_exec(t,e,i,n,s,r,{attr:o,to:a}){let l=r.getAttribute(o);if(!l)throw new Error(`expected ${o} to contain JS command on "${a}"`);n.liveSocket.execJS(r,l,e)},exec_dispatch(t,e,i,n,s,r,{event:o,detail:a,bubbles:l,blocking:h}){if(a=a||{},a.dispatcher=s,h){let c=new Promise((d,m)=>{a.done=d});n.liveSocket.asyncTransition(c)}f.dispatchEvent(r,o,{detail:a,bubbles:l})},exec_push(t,e,i,n,s,r,o){let{event:a,data:l,target:h,page_loading:c,loading:d,value:m,dispatcher:p,callback:u}=o,v={loading:d,value:m,target:h,page_loading:!!c,originalEvent:t},y=e==="change"&&p?p:s,M=h||y.getAttribute(n.binding("target"))||y,L=(H,R)=>{if(H.isConnected())if(e==="change"){let{newCid:E,_target:S}=o;S=S||(f.isFormAssociated(s)?s.name:void 0),S&&(v._target=S),H.pushInput(s,R,E,a||i,v,u)}else if(e==="submit"){let{submitter:E}=o;H.submitForm(s,R,a||i,E,v,u)}else H.pushEvent(e,s,R,a||i,l,v,u)};o.targetView&&o.targetCtx?L(o.targetView,o.targetCtx):n.withinTargets(M,L)},exec_navigate(t,e,i,n,s,r,{href:o,replace:a}){n.liveSocket.historyRedirect(t,o,a?"replace":"push",null,s)},exec_patch(t,e,i,n,s,r,{href:o,replace:a}){n.liveSocket.pushHistoryPatch(t,o,a?"replace":"push",s)},exec_focus(t,e,i,n,s,r){vt.attemptFocus(r),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>vt.attemptFocus(r))})}
10,exec_focus_first(t,e,i,n,s,r){vt.focusFirstInteractive(r)||vt.focusFirst(r),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>vt.focusFirstInteractive(r)||vt.focusFirst(r))})},exec_push_focus(t,e,i,n,s,r){n.isDestroyed()||ei.push({el:r||s,view:n})},exec_pop_focus(t,e,i,n,s,r){if(n.isDestroyed())return;let o=ei.pop();if(o){let{el:a}=o;a.focus(),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>a.focus())})}},dropFocus(t){let e=0;for(let i=ei.length-1;i>=0;i--)ei[i].view===t&&(ei.splice(i,1),e++);return e},exec_add_class(t,e,i,n,s,r,{names:o,transition:a,time:l,blocking:h}){this.addOrRemoveClasses(r,o,[],a,l,n,h)},exec_remove_class(t,e,i,n,s,r,{names:o,transition:a,time:l,blocking:h}){this.addOrRemoveClasses(r,[],o,a,l,n,h)},exec_toggle_class(t,e,i,n,s,r,{names:o,transition:a,time:l,blocking:h}){this.toggleClasses(r,o,a,l,n,h)},exec_toggle_attr(t,e,i,n,s,r,{attr:[o,a,l]}){this.toggleAttr(r,o,a,l)},exec_ignore_attrs(t,e,i,n,s,r,{attrs:o}){this.ignoreAttrs(r,o)},exec_transition(t,e,i,n,s,r,{time:o,transition:a,blocking:l}){this.addOrRemoveClasses(r,[],[],a,o,n,l)},exec_toggle(t,e,i,n,s,r,{display:o,ins:a,outs:l,time:h,blocking:c}){this.toggle(e,n,r,o,a,l,h,c)},exec_show(t,e,i,n,s,r,{display:o,transition:a,time:l,blocking:h}){this.show(e,n,r,o,a,l,h)},exec_hide(t,e,i,n,s,r,{display:o,transition:a,time:l,blocking:h}){this.hide(e,n,r,o,a,l,h)},exec_set_attr(t,e,i,n,s,r,{attr:[o,a]}){this.setOrRemoveAttrs(r,[[o,a]],[])},exec_remove_attr(t,e,i,n,s,r,{attr:o}){this.setOrRemoveAttrs(r,[],[o])},ignoreAttrs(t,e){f.putPrivate(t,"JS:ignore_attrs",{apply:(i,n)=>{let s=Array.from(i.attributes),r=s.map(o=>o.name);Array.from(n.attributes).filter(o=>!r.includes(o.name)).forEach(o=>{f.attributeIgnored(o,e)&&n.removeAttribute(o.name)}),s.forEach(o=>{f.attributeIgnored(o,e)&&n.setAttribute(o.name,o.value)})}})},onBeforeElUpdated(t,e){let i=f.private(t,"JS:ignore_attrs");i&&i.apply(t,e)},show(t,e,i,n,s,r,o){this.isVisible(i)||this.toggle(t,e,i,n,s,null,r,o)},hide(t,e,i,n,s,r,o){this.isVisible(i)&&this.toggle(t,e,i,n,null,s,r,o)},toggle(t,e,i,n,s,r,o,a){o=o??dr;let[l,h,c]=s||[[],[],[]],[d,m,p]=r||[[],[],[]];if(l.length>0||d.length>0)if(this.isVisible(i)){let u=()=>{this.addOrRemoveClasses(i,m,l.concat(h).concat(c)),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(i,d,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(i,p,m))})},v=()=>{this.addOrRemoveClasses(i,[],d.concat(p)),f.putSticky(i,"toggle",y=>y.style.display="none"),i.dispatchEvent(new Event("phx:hide-end"))};i.dispatchEvent(new Event("phx:hide-start")),a===!1?(u(),setTimeout(v,o)):e.transition(o,u,v)}else{if(t==="remove")return;let u=()=>{this.addOrRemoveClasses(i,h,d.concat(m).concat(p));let y=n||this.defaultDisplay(i);window.requestAnimationFrame(()=>{this.addOrRemoveClasses(i,l,[]),window.requestAnimationFrame(()=>{f.putSticky(i,"toggle",M=>M.style.display=y),this.addOrRemoveClasses(i,c,h)})})},v=()=>{this.addOrRemoveClasses(i,[],l.concat(c)),i.dispatchEvent(new Event("phx:show-end"))};i.dispatchEvent(new Event("phx:show-start")),a===!1?(u(),setTimeout(v,o)):e.transition(o,u,v)}else this.isVisible(i)?window.requestAnimationFrame(()=>{i.dispatchEvent(new Event("phx:hide-start")),f.putSticky(i,"toggle",u=>u.style.display="none"),i.dispatchEvent(new Event("phx:hide-end"))}):window.requestAnimationFrame(()=>{i.dispatchEvent(new Event("phx:show-start"));let u=n||this.defaultDisplay(i);f.putSticky(i,"toggle",v=>v.style.display=u),i.dispatchEvent(new Event("phx:show-end"))})},toggleClasses(t,e,i,n,s,r){window.requestAnimationFrame(()=>{let[o,a]=f.getSticky(t,"classes",[[],[]]),l=e.filter(c=>o.indexOf(c)<0&&!t.classList.contains(c)),h=e.filter(c=>a.indexOf(c)<0&&t.classList.contains(c));this.addOrRemoveClasses(t,l,h,i,n,s,r)})},toggleAttr(t,e,i,n){t.hasAttribute(e)?n!==void 0?t.getAttribute(e)===i?this.setOrRemoveAttrs(t,[[e,n]],[]):this.setOrRemoveAttrs(t,[[e,i]],[]):this.setOrRemoveAttrs(t,[],[e]):this.setOrRemoveAttrs(t,[[e,i]],[])},addOrRemoveClasses(t,e,i,n,s,r,o){s=s??dr;let[a,l,h]=n||[[],[],[]];if(a.length>0){let c=()=>{this.addOrRemoveClasses(t,l,[].concat(a).concat(h)),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(t,a,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(t,h,l))})},d=()=>this.addOrRemoveClasses(t,e.concat(h),i.concat(a).concat(l));o===!1?(c(),setTimeout(d,s)):r.transition(s,c,d);return}window.requestAnimationFrame(()=>{let[c,d]=f.getSticky(t,"classes",[[],[]]),m=e.filter(y=>c.indexOf(y)<0&&!t.classList.contains(y)),p=i.filter(y=>d.indexOf(y)<0&&t.classList.contains(y)),u=c.filter(y=>i.indexOf(y)<0).concat(m),v=d.filter(y=>e.indexOf(y)<0).concat(p);f.putSticky(t,"classes",y=>(y.classList.remove(...v),y.classList.add(...u),[u,v]))})}
10,setOrRemoveAttrs(t,e,i){let[n,s]=f.getSticky(t,"attrs",[[],[]]),r=e.map(([l,h])=>l).concat(i),o=n.filter(([l,h])=>!r.includes(l)).concat(e),a=s.filter(l=>!r.includes(l)).concat(i);e.some(([l,h])=>l==="id"&&t.getAttribute("id")!==h)&&f.putPrivate(t,"clientsideIdAttribute",!0),f.putSticky(t,"attrs",l=>(a.forEach(h=>l.removeAttribute(h)),o.forEach(([h,c])=>l.setAttribute(h,c)),[o,a]))},hasAllClasses(t,e){return e.every(i=>t.classList.contains(i))},isToggledOut(t,e){return!this.isVisible(t)||this.hasAllClasses(t,e)},filterToEls(t,e,{to:i}){let n=()=>{if(typeof i=="string")return document.querySelectorAll(i);if(i.closest){let s=e.closest(i.closest);return s?[s]:[]}else if(i.inner)return e.querySelectorAll(i.inner)};return i?t.jsQuerySelectorAll(e,i,n):[e]},defaultDisplay(t){return{tr:"table-row",td:"table-cell"}[t.tagName.toLowerCase()]||"block"},transitionClasses(t){if(!t)return null;let[e,i,n]=Array.isArray(t)?t:[t.split(" "),[],[]];return e=Array.isArray(e)?e:e.split(" "),i=Array.isArray(i)?i:i.split(" "),n=Array.isArray(n)?n:n.split(" "),[e,i,n]}},I=eh,Cr=(t,e)=>({exec(i,n){t.execJS(i,n,e)},show(i,n={}){let s=t.owner(i);I.show(e,s,i,n.display,I.transitionClasses(n.transition),n.time,n.blocking)},hide(i,n={}){let s=t.owner(i);I.hide(e,s,i,null,I.transitionClasses(n.transition),n.time,n.blocking)},toggle(i,n={}){let s=t.owner(i),r=I.transitionClasses(n.in),o=I.transitionClasses(n.out);I.toggle(e,s,i,n.display,r,o,n.time,n.blocking)},addClass(i,n,s={}){let r=Array.isArray(n)?n:n.split(" "),o=t.owner(i);I.addOrRemoveClasses(i,r,[],I.transitionClasses(s.transition),s.time,o,s.blocking)},removeClass(i,n,s={}){let r=Array.isArray(n)?n:n.split(" "),o=t.owner(i);I.addOrRemoveClasses(i,[],r,I.transitionClasses(s.transition),s.time,o,s.blocking)},toggleClass(i,n,s={}){let r=Array.isArray(n)?n:n.split(" "),o=t.owner(i);I.toggleClasses(i,r,I.transitionClasses(s.transition),s.time,o,s.blocking)},transition(i,n,s={}){let r=t.owner(i);I.addOrRemoveClasses(i,[],[],I.transitionClasses(n),s.time,r,s.blocking)},setAttribute(i,n,s){I.setOrRemoveAttrs(i,[[n,s]],[])},removeAttribute(i,n){I.setOrRemoveAttrs(i,[],[n])},toggleAttribute(i,n,s,r){I.toggleAttr(i,n,s,r)},push(i,n,s={}){t.withinOwners(i,r=>{let o=s.value||{};delete s.value;let a=new CustomEvent("phx:exec",{detail:{sourceElement:i}});I.exec(a,e,n,r,i,["push",{data:o,...s}])})},navigate(i,n={}){er(i,"navigate");let s=new CustomEvent("phx:exec");t.historyRedirect(s,i,n.replace?"replace":"push",null,null)},patch(i,n={}){er(i,"patch");let s=new CustomEvent("phx:exec");t.pushHistoryPatch(s,i,n.replace?"replace":"push",null)},ignoreAttributes(i,n){I.ignoreAttrs(i,Array.isArray(n)?n:[n])}}),In="hookId",ur="deadHook",ih=1,de=class kr{get liveSocket(){return this.__liveSocket()}static makeID(){return ih++}static elementID(e){return f.private(e,In)}static deadHook(e){return f.private(e,ur)===!0}constructor(e,i,n){if(this.el=i,this.__attachView(e),this.__listeners=new Set,this.__isDisconnected=!1,f.putPrivate(this.el,In,kr.makeID()),e&&e.isDead&&f.putPrivate(this.el,ur,!0),n){let s=new Set(["el","liveSocket","__view","__listeners","__isDisconnected","constructor","js","pushEvent","pushEventTo","handleEvent","removeHandleEvent","upload","uploadTo","__mounted","__updated","__beforeUpdate","__destroyed","__reconnected","__disconnected","__cleanup__"]);for(let o in n)Object.prototype.hasOwnProperty.call(n,o)&&(this[o]=n[o],s.has(o)&&console.warn(`Hook object for element #${i.id} overwrites core property '${o}'!`));["mounted","beforeUpdate","updated","destroyed","disconnected","reconnected"].forEach(o=>{n[o]&&typeof n[o]=="function"&&(this[o]=n[o])})}}__attachView(e){e?(this.__view=()=>e,this.__liveSocket=()=>e.liveSocket):(this.__view=()=>{throw new Error(`hook not yet attached to a live view: ${this.el.outerHTML}`)},this.__liveSocket=()=>{throw new Error(`hook not yet attached to a live view: ${this.el.outerHTML}`)})}mounted(){}beforeUpdate(e){}updated(){}destroyed(){}disconnected(){}reconnected(){}__mounted(){this.mounted()}__updated(){this.updated()}__beforeUpdate(e){this.beforeUpdate(e)}__destroyed(){this.destroyed(),f.deletePrivate(this.el,In)}__reconnected(){this.__isDisconnected&&(this.__isDisconnected=!1,this.reconnected())}__disconnected(){this.__isDisconnected=!0,this.disconnected()}js(){return{...Cr(this.__view().liveSocket,"hook"),exec:e=>{this.__view().liveSocket.execJS(this.el,e,"hook")}}}pushEvent(e,i,n){let s=this.__view().pushHookEvent(this.el,null,e,i||{});if(n===void 0)return s.then(({reply:r})=>r);s.then(({reply:r,ref:o})=>n(r,o),()=>{})}pushEventTo(e,i,n,s){if(s===void 0){let r=[];this.__view().withinTargets(e,(a,l)=>{r.push({view:a,targetCtx:l})});let o=r.map(({view:a,targetCtx:l})=>a.pushHookEvent(this.el,l,i,n||{}));return Promise.allSettled(o)}this.__view().withinTargets(e,(r,o)=>{r.pushHookEvent(this.el,o,i,n||{}).then(({reply:a,ref:l})=>s(a,l),()=>{})})}handleEvent(e,i){let n={event:e,callback:s=>i(s.detail)};return window.addEventListener(`phx:${e}`,n.callback),this.__listeners.add(n),n}removeHandleEvent(e){window.removeEventListener(`phx:${e.event}`,e.callback),this.__listeners.delete(e)}upload(e,i){return this.__view().dispatchUploads(null,e,i)}uploadTo(e,i,n){return this.__view().withinTargets(e,(s,r)=>{s.dispatchUploads(r,i,n)})}
10__cleanup__(){this.__listeners.forEach(e=>this.removeHandleEvent(e))}},nh=(t,e)=>{let i=t.endsWith("[]"),n=i?t.slice(0,-2):t;return n=n.replace(/([^\[\]]+)(\]?$)/,`${e}$1$2`),i&&(n+="[]"),n},sh=class _r{static closestView(e){let i=e.closest(ni);return i?f.private(i,"view"):null}constructor(e,i,n,s=null,r=null){this.rendered=null,this.isDead=!1,this.liveSocket=i,this.flash=s,this.parent=n,this.root=n?n.root:this,this.el=e;let o=f.private(this.el,"view");if(o!==void 0&&o.isDead!==!0)throw this.logError("view.duplicate-binding",`The DOM element for this view has already been bound to a view. 11 12 An element can only ever be associated with a single view! 13 Please ensure that you are not trying to initialize multiple LiveSockets on the same page. 14 This could happen if you're accidentally trying to render your root layout more than once. 15 Ensure that the template set on the LiveView is different than the root layout. 16 `,{view:o},{attribution:"app"}),new Error("Cannot bind multiple views to the same DOM element.");f.putPrivate(this.el,"view",this),this.id=this.el.id,this.el.setAttribute(zt,this.root.id),this.ref=0,this.lastAckRef=null,this.childJoins=0,this.loaderTimer=null,this.disconnectedTimer=null,this.pendingDiffs=[],this.pendingForms=new Set,this.activeUploaders=new Set,this.redirect=!1,this.href=null,this.joinCount=this.parent?this.parent.joinCount-1:0,this.joinAttempts=0,this.joinPending=!0,this.destroyed=!1,this.joinCallback=function(a){a&&a()},this.stopCallback=function(){},this.pendingJoinOps=[],this.viewHooks={},this.formSubmits=[],this.children=this.parent?null:{},this.root.children[this.id]={},this.formsForRecovery={},this.channel=this.liveSocket.channel(`lv:${this.id}`,()=>{let a=this.href&&this.expandURL(this.href);return{redirect:this.redirect?a:void 0,url:this.redirect?void 0:a||void 0,params:this.connectParams(r),session:this.getSession(),static:this.getStatic(),flash:this.flash??void 0,sticky:this.el.hasAttribute(Hn)}}),this.portalElementIds=new Set}setHref(e){this.href=e}setRedirect(e){this.redirect=!0,this.href=e}isMain(){return this.el.hasAttribute(jn)}connectParams(e){let i=this.liveSocket.params(this.el),n=f.all(document,`[${this.binding(il)}]`).map(s=>"src"in s&&s.src||"href"in s&&s.href).filter(s=>typeof s=="string");return n.length>0&&(i._track_static=n),i._mounts=this.joinCount,i._mount_attempts=this.joinAttempts,i._live_referer=e??void 0,this.joinAttempts++,i}isConnected(){return this.channel.canPush()}getSession(){return this.el.getAttribute(Ut)}getStatic(){let e=this.el.getAttribute(pe);return e===""?null:e}destroy(e=function(){}){I.dropFocus(this),this.destroyAllChildren(),this.destroyPortalElements(),this.destroyed=!0,this.activeUploaders.forEach(n=>n.cancel()),this.activeUploaders.clear(),f.deletePrivate(this.el,"view"),delete this.root.children[this.id],this.parent&&delete this.root.children[this.parent.id][this.id],this.loaderTimer!=null&&clearTimeout(this.loaderTimer);let i=()=>{e();for(let n in this.viewHooks)this.destroyHook(this.viewHooks[n])};f.markPhxChildDestroyed(this.el),this.log("destroyed",()=>["the child has been removed from the parent"],{code:"view.child-destroyed"}),this.channel.leave().receive("ok",i).receive("error",i).receive("timeout",i)}setContainerClasses(...e){this.el.classList.remove(js,le,Me,qs,Xe),this.el.classList.add(...e)}showLoader(e){if(this.loaderTimer!=null&&clearTimeout(this.loaderTimer),e)this.loaderTimer=setTimeout(()=>this.showLoader(),e);else{for(let i in this.viewHooks)this.viewHooks[i].__disconnected();this.setContainerClasses(le)}}execAll(e){f.all(this.el,`[${e}]`,i=>this.liveSocket.execJS(i,i.getAttribute(e)))}hideLoader(){this.loaderTimer!=null&&clearTimeout(this.loaderTimer),this.disconnectedTimer!=null&&clearTimeout(this.disconnectedTimer),this.setContainerClasses(js),this.execAll(this.binding("connected"))}triggerReconnected(){for(let e in this.viewHooks)this.viewHooks[e].__reconnected()}log(e,i,n){this.liveSocket.log(this,e,i,n)}logError(e,i,n,s={attribution:"unknown"}){Nt(e,i,n,{viewId:this.id??this.el.id,...s})}transition(e,i,n=function(){}){this.liveSocket.transition(e,i,n)}withinTargets(e,i,n=document){if(e instanceof HTMLElement||e instanceof SVGElement)return this.liveSocket.owner(e,s=>i(s,e));if(ie(e))f.findComponent(this.id,e,n)?i(this,typeof e=="number"?e:parseInt(e)):this.logError("event.missing-component-target",`no component found matching phx-target of ${e}`,{target:e});else{let s=Array.from(n.querySelectorAll(e));s.length===0&&this.logError("event.missing-selector-target",`nothing found matching the phx-target selector "${e}"`,{target:e},{attribution:"app"}
16),s.forEach(r=>this.liveSocket.owner(r,o=>i(o,r)))}}applyDiff(e,i,n){let s=Fi(i);this.log(e,()=>["received diff",s],{code:`view.diff-${e}`,metadata:()=>({diff:s})});let{diff:r,reply:o,events:a,title:l}=cr.extract(i),h=a.reduce((d,m)=>(m.length===3&&m[2]==!0?d.pre.push(m.slice(0,-1)):d.post.push(m),d),{pre:[],post:[]});this.liveSocket.dispatchEvents(h.pre);let c=()=>{n({diff:r,reply:o,events:h.post}),(typeof l=="string"||e=="mount"&&this.isMain())&&window.requestAnimationFrame(()=>f.putTitle(l))};"onDocumentPatch"in this.liveSocket.domCallbacks?this.liveSocket.triggerDOM("onDocumentPatch",[c]):c()}onJoin(e){let{rendered:i,container:n,liveview_version:s,pid:r}=e;if(n){let[o,a]=n;this.el=f.replaceRootContainer(this.el,o,a),f.putPrivate(this.el,"view",this)}this.childJoins=0,this.joinPending=!0,this.flash=null,this.root===this&&(this.formsForRecovery=this.getFormsForRecovery()),this.isMain()&&window.history.state===null&&dt.pushState("replace",{type:"patch",id:this.id,position:this.liveSocket.currentHistoryPosition}),s!==this.liveSocket.version()&&console.warn(`LiveView asset version mismatch. JavaScript version ${this.liveSocket.version()} vs. server ${s}. To avoid issues, please ensure that your assets use the same version as the server.`),r&&this.el.setAttribute(cl,r),dt.dropLocal(this.liveSocket.localStorage,window.location.pathname,fr),this.applyDiff("mount",i,({diff:o,events:a})=>{this.rendered=new cr(this.id,o,()=>this.liveSocket.RenderingBuffer);let[l,h]=this.renderContainer(null,"join");this.dropPendingRefs(),this.joinCount++,this.joinAttempts=0,this.maybeRecoverForms(l,()=>{this.onJoinComplete(e,l,h,a)})})}dropPendingRefs(){f.all(document,`[${Et}="${this.refSrc()}"]`,e=>{e.removeAttribute(Re),e.removeAttribute(Et),e.removeAttribute(q)})}onJoinComplete({live_patch:e},i,n,s){if(this.joinCount>1||this.parent&&!this.parent.isJoinPending())return this.applyJoinPatch(e,i,n,s);f.findPhxChildrenInFragment(i,this.id).filter(o=>{let a=o.id&&this.el.querySelector(`[id="${o.id}"]`),l=a&&a.getAttribute(pe);return l&&o.setAttribute(pe,l),a&&a.setAttribute(zt,this.root.id),this.joinChild(o)}).length===0?this.parent?(this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(e,i,n,s)]),this.parent.ackJoin(this)):(this.onAllChildJoinsComplete(),this.applyJoinPatch(e,i,n,s)):this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(e,i,n,s)])}attachTrueDocEl(){let e=f.byId(this.id);if(!e)throw new Error("unable to find root element for view");this.el=e,f.putPrivate(this.el,"view",this),this.el.setAttribute(zt,this.root.id)}execNewMounted(e=document){let i=this.binding(Rn),n=this.binding(On);this.all(e,`[${i}], [${n}]`,s=>{f.maintainPrivateHooks(s,s,i,n),this.maybeAddNewHook(s)}),this.all(e,`[${this.binding(he)}], [data-phx-${he}]`,s=>{this.maybeAddNewHook(s)}),this.all(e,`[${this.binding(Ks)}]`,s=>{this.maybeMounted(s)})}all(e,i,n){f.all(e,i,s=>{this.ownsElement(s)&&n(s)})}applyJoinPatch(e,i,n,s){this.joinCount>1&&this.pendingJoinOps.length&&(this.pendingJoinOps.forEach(o=>typeof o=="function"&&o()),this.pendingJoinOps=[]),this.attachTrueDocEl();let r=new Li(this,this.el,i,n,null);if(r.markPrunableContentForRemoval(),this.performPatch(r,!1,!0),this.joinNewChildren(),this.execNewMounted(),this.joinPending=!1,this.liveSocket.dispatchEvents(s),this.applyPendingUpdates(),e){let{kind:o,to:a}=e;this.liveSocket.historyPatch(a,o)}this.hideLoader(),this.joinCount>1&&this.triggerReconnected(),this.stopCallback()}triggerBeforeUpdateHook(e,i){this.liveSocket.triggerDOM("onBeforeElUpdated",[e,i]);let n=this.getHook(e),s=n&&f.isIgnored(e,this.binding(Bi));if(n&&!e.isEqualNode(i)&&!(s&&_l(e.dataset,i.dataset)))return n.__beforeUpdate(i),n}maybeMounted(e){let i=e.getAttribute(this.binding(Ks)),n=i&&f.private(e,"mounted");i&&!n&&(this.liveSocket.execJS(e,i),f.putPrivate(e,"mounted",!0))}maybeAddNewHook(e){let i=this.addHook(e);i&&i.__mounted()}performPatch(e,i,n=!1){let s=[],r=!1,o=new Set,a=new Set;this.liveSocket.triggerDOM("onPatchStart",[e.targetContainer]),e.afterAdded(c=>{this.liveSocket.triggerDOM("onNodeAdded",[c]);let d=this.binding(Rn),m=this.binding(On);f.maintainPrivateHooks(c,c,d,m),this.maybeAddNewHook(c),c.getAttribute&&this.maybeMounted(c)}),e.afterPhxChildAdded(c=>{f.isPhxSticky(c)?this.liveSocket.joinRootViews():r=!0});
16let l=this.binding(he),h=`data-phx-${he}`;return e.beforeUpdated((c,d)=>{let m=this.triggerBeforeUpdateHook(c,d);m?c.hasAttribute(l)&&c.getAttribute(l)!==d.getAttribute(l)?(this.destroyHook(m),d.getAttribute(l)&&a.add(d.id)):o.add(c.id):d.id&&d.getAttribute&&!this.getHook(c)&&(d.getAttribute(l)||d.getAttribute(h))&&a.add(d.id),I.onBeforeElUpdated(c,d)}),e.afterUpdated(c=>{if(o.has(c.id)){let d=this.getHook(c);d&&d.__updated()}else a.has(c.id)&&this.maybeAddNewHook(c)}),e.afterDiscarded(c=>{c.nodeType===Node.ELEMENT_NODE&&s.push(c)}),e.afterTransitionsDiscarded(c=>this.afterElementsRemoved(c,i)),e.perform(n),this.afterElementsRemoved(s,i),this.liveSocket.triggerDOM("onPatchEnd",[e.targetContainer]),r}afterElementsRemoved(e,i){let n=[];e.forEach(s=>{let r=f.all(s,`[${Le}="${this.id}"][${xt}]`),o=f.all(s,`[${this.binding(he)}], [data-phx-hook]`);r.concat(s).forEach(a=>{let l=this.componentID(a);ie(l)&&n.indexOf(l)===-1&&a.getAttribute(Le)===this.id&&n.push(l)}),o.concat(s).forEach(a=>{let l=this.getHook(a);l&&this.destroyHook(l)})}),i&&this.maybePushComponentsDestroyed(n)}joinNewChildren(){f.findPhxChildren(document,this.id).forEach(e=>this.joinChild(e))}maybeRecoverForms(e,i){let n=this.binding("change"),s=this.root.formsForRecovery,r=document.createElement("template");if(r.innerHTML=e,!r.content.firstElementChild)return i();f.all(r.content,`[${qn}]`).forEach(l=>{l instanceof HTMLTemplateElement&&r.content.firstElementChild?.appendChild(l.content.firstElementChild)});let o=r.content.firstElementChild;o.id=this.id,o.setAttribute(zt,this.root.id),o.setAttribute(Ut,this.getSession()),o.setAttribute(pe,this.getStatic()??""),this.parent&&o.setAttribute(me,this.parent.id),f.putPrivate(o,"view",this);let a=f.all(r.content,"form").filter(l=>l.id&&s[l.id]).filter(l=>!this.pendingForms.has(l.id)).filter(l=>s[l.id].getAttribute(n)===l.getAttribute(n)).map(l=>[s[l.id],l]);if(a.length===0)return i();a.forEach(([l,h],c)=>{this.pendingForms.add(h.id),this.pushFormRecovery(l,h,r.content.firstElementChild,()=>{this.pendingForms.delete(h.id),c===a.length-1&&i()})})}getChildById(e){return this.root.children[this.id][e]}
16getDescendentByEl(e){return e.id===this.id?this:this.children&&this.children[e.getAttribute(me)]?.[e.id]}destroyDescendent(e){for(let i in this.root.children)for(let n in this.root.children[i])if(n===e)return this.root.children[i][n].destroy()}joinChild(e){if(!this.getChildById(e.id)){let n=new _r(e,this.liveSocket,this);return this.root.children[this.id][n.id]=n,n.join(),this.childJoins++,!0}}isJoinPending(){return this.joinPending}ackJoin(e){this.childJoins--,this.childJoins===0&&(this.parent?this.parent.ackJoin(this):this.onAllChildJoinsComplete())}onAllChildJoinsComplete(){this.pendingForms.clear(),this.formsForRecovery={},this.joinCallback(()=>{this.pendingJoinOps.forEach(([e,i])=>{e.isDestroyed()||i()}),this.pendingJoinOps=[]})}update(e,i,n=!1){if(this.isJoinPending()||this.liveSocket.hasPendingLink()&&this.root.isMain())return n||this.pendingDiffs.push({diff:e,events:i,joinCount:this.joinCount}),!1;this.rendered.mergeDiff(e);let s=!1;return this.rendered.isComponentOnlyDiff(e)?this.liveSocket.time("component patch complete",()=>{f.findExistingParentCIDs(this.id,this.rendered.componentCIDs(e)).forEach(o=>{this.componentPatch(this.rendered.getComponent(e,o),o)&&(s=!0)})}):ir(e)||this.liveSocket.time("full patch complete",()=>{let[r,o]=this.renderContainer(e,"update"),a=new Li(this,this.el,r,o,null);s=this.performPatch(a,!0)}),this.liveSocket.dispatchEvents(i),s&&this.joinNewChildren(),!0}renderContainer(e,i){return this.liveSocket.time(`toString diff (${i})`,()=>{let n=this.el.tagName,s=e?this.rendered.componentCIDs(e):null,{buffer:r,streams:o}=this.rendered.toString(s);return[`<${n}>${r}</${n}>`,o]})}componentPatch(e,i){if(ir(e))return!1;let{buffer:n,streams:s}=this.rendered.componentToString(i),r=new Li(this,this.el,n,s,i);return this.performPatch(r,!0)}getHook(e){return this.viewHooks[de.elementID(e)]}addHook(e){let i=de.elementID(e);if(!(e.getAttribute&&!this.ownsElement(e)))if(i&&!this.viewHooks[i]){if(de.deadHook(e))return;let n=f.getCustomElHook(e)||this.logError("hook.custom-element-missing-hook",`no hook found for custom element: ${e.id}`,{el:e},{attribution:"app"});return this.viewHooks[i]=n,n.__attachView(this),n}else{if(i||!e.getAttribute)return;{let n=e.getAttribute(`data-phx-${he}`)||e.getAttribute(this.binding(he));if(!n)return;let s=this.liveSocket.getHookDefinition(n);if(s){if(!e.id){this.logError("hook.missing-id",`no DOM ID for hook "${n}". Hooks require a unique ID on each element.`,{el:e,hookName:n},{attribution:"app"});return}let r;try{if(typeof s=="function"&&s.prototype instanceof de)r=new s(this,e);else if(typeof s=="object"&&s!==null)r=new de(this,e,s);else{this.logError("hook.invalid-definition",`Invalid hook definition for "${n}". Expected a class extending ViewHook or an object definition.`,{el:e,hookName:n},{attribution:"app"});return}}catch(o){let a=o instanceof Error?o.message:String(o);this.logError("hook.creation-failed",`Failed to create hook "${n}": ${a}`,{el:e,hookName:n,error:o},{attribution:"app"});return}return this.viewHooks[de.elementID(r.el)]=r,r}
16else n!==null&&this.logError("hook.unknown",`unknown hook found for "${n}"`,{el:e,hookName:n},{attribution:"app"})}}}destroyHook(e){let i=de.elementID(e.el);e.__destroyed(),e.__cleanup__(),delete this.viewHooks[i]}applyPendingUpdates(){this.pendingDiffs=this.pendingDiffs.filter(({diff:e,events:i,joinCount:n})=>n!==this.joinCount?(this.log("update",()=>["discarded diff from previous join",e],{code:"view.stale-diff-discarded",metadata:()=>({joinCount:n,currentJoinCount:this.joinCount})}),!1):!this.update(e,i,!0)),this.eachChild(e=>e.applyPendingUpdates())}eachChild(e){let i=this.root.children[this.id]||{};for(let n in i)e(this.getChildById(n))}onChannel(e,i){this.liveSocket.onChannel(this.channel,e,n=>{this.isJoinPending()&&!["redirect","live_redirect"].includes(e)?this.joinCount>1?this.pendingJoinOps.push(()=>i(n)):this.root.pendingJoinOps.push([this,()=>i(n)]):this.liveSocket.requestDOMUpdate(()=>i(n))})}bindChannel(){this.liveSocket.onChannel(this.channel,"diff",e=>{this.liveSocket.requestDOMUpdate(()=>{this.applyDiff("update",e,({diff:i,events:n})=>this.update(i,n))})}),this.onChannel("redirect",({to:e,flash:i})=>this.onRedirect({to:e,flash:i})),this.onChannel("live_patch",e=>this.onLivePatch(e)),this.onChannel("live_redirect",e=>this.onLiveRedirect(e)),this.channel.onError(e=>this.onError(e)),this.channel.onClose(e=>this.onClose(e))}destroyAllChildren(){this.eachChild(e=>e.destroy())}onLiveRedirect(e){let{to:i,kind:n,flash:s}=e,r=this.expandURL(i),o=new CustomEvent("phx:server-navigate",{detail:{to:i,kind:n,flash:s}});this.liveSocket.historyRedirect(o,r,n,s)}onLivePatch(e){let{to:i,kind:n}=e;this.href=this.expandURL(i),this.liveSocket.historyPatch(i,n)}expandURL(e){return e.startsWith("/")?`${window.location.protocol}//${window.location.host}${e}`:e}onRedirect({to:e,flash:i,reloadToken:n}){this.liveSocket.redirect(e,i??null,n??null)}isDestroyed(){return this.destroyed}joinDead(){this.isDead=!0}join(e){this.showLoader(this.liveSocket.loaderTimeout),this.bindChannel(),this.isMain()&&(this.stopCallback=this.liveSocket.withPageLoading({to:this.href,kind:"initial"})),this.joinCallback=i=>{i=i||function(){},e?e(this.joinCount,i):i()},this.wrapPush(()=>this.channel.join(),{ok:i=>this.liveSocket.requestDOMUpdate(()=>this.onJoin(i)),error:i=>this.onJoinError(i),timeout:()=>this.onJoinError({reason:"timeout"})})}onJoinError(e){if(e.events&&this.liveSocket.dispatchEvents(e.events),e.reason==="reload"){this.log("error",()=>[`failed mount with ${e.status}. Falling back to page reload`,e],{code:"view.mount-reload",level:"error",metadata:()=>({status:e.status}),context:{attribution:"app"}}),this.onRedirect({to:this.liveSocket.main.href,reloadToken:e.token});return}else if(e.reason==="unauthorized"||e.reason==="stale"){this.log("error",()=>["unauthorized live_redirect. Falling back to page request",e],{code:"view.unauthorized-live-redirect",level:"error",metadata:()=>({reason:e.reason}),context:{attribution:"app"}}),this.onRedirect({to:this.liveSocket.main.href,flash:this.flash});return}if((e.redirect||e.live_redirect)&&(this.joinPending=!1,this.channel.leave()),e.redirect)return this.onRedirect(e.redirect);if(e.live_redirect)return this.onLiveRedirect(e.live_redirect);let i=e.reason==="timeout",n=i||e.source==="transport"?"network":"app";if(this.log("error",()=>[i?"join timed out":"unable to join",e],{code:i?"view.join-timeout":"view.join-failed",level:"error",metadata:()=>i?{error:e}:{response:e},context:{attribution:n}}),this.isMain())this.displayError([le,Me,Xe],{unstructuredError:e,errorKind:"server"}),this.liveSocket.isConnected()&&this.liveSocket.reloadWithJitter(this);else{if(this.joinAttempts>=xn){this.root.displayError([le,Me,Xe],{unstructuredError:e,errorKind:"server"}),this.log("error",()=>[`giving up trying to mount after ${xn} tries`,e],{code:"view.mount-attempts-exhausted",level:"error",metadata:()=>({attempts:xn,response:e})}),this.destroy();return}let s=f.byId(this.el.id);s?(f.mergeAttrs(s,this.el),this.displayError([le,Me,Xe],{unstructuredError:e,errorKind:"server"}),this.el=s):this.destroy()}}onClose(e){if(!this.isDestroyed()){if(this.isMain()&&this.liveSocket.hasPendingLink()&&e!=="leave")return this.liveSocket.reloadWithJitter(this);this.destroyAllChildren(),this.liveSocket.dropActiveElement(this),this.liveSocket.isUnloaded()&&this.showLoader(pl)}}onError(e){this.onClose(e),this.liveSocket.isConnected()&&this.log("error",()=>["view crashed",e],{code:"view.crashed",level:"error",metadata:()=>({reason:e}),context:{attribution:"app"}}),this.liveSocket.isUnloaded()||(this.liveSocket.isConnected()?this.displayError([le,Me,Xe],{unstructuredError:e,errorKind:"server"}):this.displayError([le,Me,qs],{unstructuredError:e,errorKind:"client"}))}displayError(e,i={}){this.isMain()&&f.dispatchEvent(window,"phx:page-loading-start",{detail:{to:this.href,kind:"error",...i}}),this.showLoader(),this.setContainerClasses(...e),this.delayedDisconnected()}delayedDisconnected(){this.disconnectedTimer=setTimeout(()=>{this.execAll(this.binding("disconnected"))},this.liveSocket.disconnectedTimeout)}wrapPush(e,i){let n=this.liveSocket.getLatencySim(),s=n?r=>setTimeout(()=>!this.isDestroyed()&&r(),n):r=>!this.isDestroyed()&&r();s(()=>{e().receive("ok",r=>s(()=>i.ok&&i.ok(r))).receive("error",r=>s(()=>i.error&&i.error(r))).receive("timeout",()=>s(()=>i.timeout&&i.timeout()))})}pushWithReply(e,i,n){if(!this.isConnected())return Promise.resolve({type:"error",error:"no connection",context:{attribution:"network"}});let[s,[r],o]=e?e({payload:n}):[null,[],{}],a=this.joinCount,l=function(){};return o.page_loading&&(l=this.liveSocket.withPageLoading({kind:"element",target:r})),typeof n.cid!="number"&&delete n.cid,new Promise(h=>{this.wrapPush(()=>this.channel.push(i,n,vl),{ok:c=>{s!==null&&(this.lastAckRef=s);let d=m=>{c.redirect&&this.onRedirect(c.redirect),c.live_patch&&this.onLivePatch(c.live_patch),c.live_redirect&&this.onLiveRedirect(c.live_redirect),l(),h({type:"ok",resp:c,reply:m,ref:s})};c.diff?this.liveSocket.requestDOMUpdate(()=>{this.applyDiff("update",c.diff,({diff:m,reply:p,events:u})=>{s!==null&&this.undoRefs(s,n.event),this.update(m,u),d(p)})}):(s!==null&&this.undoRefs(s,n.event),d(null))},error:c=>{l(),h({type:"error",error:`failed with reason: ${JSON.stringify(c)}`,context:{attribution:"app"}})},timeout:()=>{l(),h({type:"error",error:"push timeout",context:{attribution:"network"}}),this.joinCount===a&&this.liveSocket.reloadWithJitter(this,()=>{this.log("timeout",()=>["received timeout while communicating with server. Falling back to hard refresh for recovery"],{code:"view.push-timeout-recovery",level:"error",context:{attribution:"network"}})})}})})}undoRefs(e,i,n){if(!this.isConnected())return;let s=`[${Et}="${this.refSrc()}"]`;n?(n=new Set(n),f.all(document,s,r=>{n&&!n.has(r)||(f.all(r,s,o=>this.undoElRef(o,e,i)),this.undoElRef(r,e,i))}
16)):f.all(document,s,r=>this.undoElRef(r,e,i))}undoElRef(e,i,n){new Un(e).maybeUndo(i,n,r=>{let o=new Li(this,e,r,new Set,null,{undoRef:i}),a=this.performPatch(o,!0);f.all(e,`[${Et}="${this.refSrc()}"]`,l=>this.undoElRef(l,i,n)),a&&this.joinNewChildren()})}refSrc(){return this.el.id}putRef(e,i,n,s={}){let r=this.ref++,o=this.binding(zs);if(s.loading){let a=f.all(document,s.loading).map(l=>({el:l,lock:!0,loading:!0}));e=e.concat(a)}for(let{el:a,lock:l,loading:h}of e){if(!l&&!h)throw new Error("putRef requires lock or loading");if(a.setAttribute(Et,this.refSrc()),h&&a.setAttribute(Re,r.toString()),l&&a.setAttribute(q,r.toString()),!h||s.submitter&&!(a===s.submitter||a===s.form))continue;let c=new Promise(u=>{a.addEventListener(`phx:undo-lock:${r}`,()=>u(p),{once:!0})}),d=new Promise(u=>{a.addEventListener(`phx:undo-loading:${r}`,()=>u(p),{once:!0})});a.classList.add(`phx-${n}-loading`);let m=a.getAttribute(o);m!==null&&(a.getAttribute(Ui)||a.setAttribute(Ui,a.textContent||""),m!==""&&(a.textContent=m),a.setAttribute(Ie,a.getAttribute(Ie)||("disabled"in a?String(a.disabled):"")),a.setAttribute("disabled",""));let p={event:i,eventType:n,ref:r,isLoading:h,isLocked:l,lockElements:e.filter(({lock:u})=>u).map(({el:u})=>u),loadingElements:e.filter(({loading:u})=>u).map(({el:u})=>u),unlock:u=>{u=Array.isArray(u)?u:[u],this.undoRefs(r,i,u)},lockComplete:c,loadingComplete:d,lock:u=>new Promise(v=>{if(this.isAcked(r))return v(p);u.setAttribute(q,r),u.setAttribute(Et,this.refSrc()),u.addEventListener(`phx:undo-lock:${r}`,()=>v(p),{once:!0})})};s.payload&&(p.payload=s.payload),s.target&&(p.target=s.target),s.originalEvent&&(p.originalEvent=s.originalEvent),a.dispatchEvent(new CustomEvent("phx:push",{detail:p,bubbles:!0,cancelable:!1})),i&&a.dispatchEvent(new CustomEvent(`phx:push:${i}`,{detail:p,bubbles:!0,cancelable:!1}))}return[r,e.map(({el:a})=>a),s]}isAcked(e){return this.lastAckRef!==null&&this.lastAckRef>=e}componentID(e){let i=e.getAttribute&&e.getAttribute(xt);return i?parseInt(i):null}targetComponentID(e,i,n={}){if(ie(i))return i;let s=n.target||e.getAttribute(this.binding("target"));return ie(s)?typeof s=="number"?s:parseInt(s):i&&(s!==null||n.target)?this.closestComponentID(i):null}closestComponentID(e){return ie(e)?e:e?De(e.closest(`[${xt}],[${ne}]`),i=>{if(i.hasAttribute(xt))return this.ownsElement(i)&&this.componentID(i);if(i.hasAttribute(ne)){let n=f.byId(i.getAttribute(ne));return this.closestComponentID(n)}}):null}pushHookEvent(e,i,n,s){if(!this.isConnected())return this.log("hook",()=>["unable to push hook event. LiveView not connected",{event:n,payload:s}],{code:"hook.push-disconnected",metadata:()=>({event:n,payload:s}),context:{attribution:"network"}}),Promise.reject(new Error("unable to push hook event. LiveView not connected"));let r=()=>this.putRef([{el:e,loading:!0,lock:!0}],n,"hook",{payload:s,target:i});return this.pushWithReply(r,"event",{type:"hook",event:n,value:s,cid:this.closestComponentID(i)}).then(o=>{if(o.type==="error")throw new Error("Failed to push hook event: "+o.error);return{reply:o.reply,ref:o.ref}})}extractMeta(e,i,n){let s=this.binding("value-");for(let r=0;r<e.attributes.length;r++){i||(i={});let o=e.attributes[r].name;o.startsWith(s)&&(i[o.replace(s,"")]=e.getAttribute(o))}if(e.value!==void 0&&!(e instanceof HTMLFormElement)&&(i||(i={}),i.value=e.value,e.tagName==="INPUT"&&br.indexOf(e.type)>=0&&!e.checked&&delete i.value),n){i||(i={});for(let r in n)i[r]=n[r]}return i}serializeForm(e,i={},n=[]){let{submitter:s}=i,r;if(s&&s.name){let m=document.createElement("input");m.type="hidden";let p=s.getAttribute("form");p&&m.setAttribute("form",p),m.name=s.name,m.value=s.value,s.parentElement.insertBefore(m,s),r=m}let o=new FormData(e),a=[];o.forEach((m,p,u)=>{m instanceof File&&a.push(p)}),a.forEach(m=>o.delete(m));let l=new URLSearchParams,{inputsUnused:h,onlyHiddenInputs:c}=Array.from(e.elements).reduce((m,p)=>{if(!f.isFormAssociated(p))return m;let{inputsUnused:u,onlyHiddenInputs:v}=m,y=p.name;if(!y)return m;u[y]===void 0&&(u[y]=!0),v[y]===void 0&&(v[y]=!0);let M=p.hasAttribute(this.binding(Ws)),L=f.private(p,Ni)||f.private(p,ii)||M,H=p.type==="hidden";return u[y]=u[y]&&!L,v[y]=v[y]&&H,m},{inputsUnused:{}
16,onlyHiddenInputs:{}}),d=e.hasAttribute(this.binding(Ws));for(let[m,p]of o.entries())if(n.length===0||n.indexOf(m)>=0){let u=h[m],v=c[m];!d&&u&&!(s&&s.name==m)&&!v&&l.append(nh(m,"_unused_"),""),typeof p=="string"&&l.append(m,p)}return s&&r&&s.parentElement.removeChild(r),l.toString()}pushEvent(e,i,n,s,r,o={},a){this.pushWithReply(l=>this.putRef([{el:i,loading:!0,lock:!0}],s,e,{...o,payload:l?.payload}),"event",{type:e,event:s,value:this.extractMeta(i,r,o.value),cid:this.targetComponentID(i,n,o)}).then(l=>{l.type==="ok"?a&&a(l.reply):this.logError("event.push-failed","Failed to push event",{error:l.error,type:e,phxEvent:s,el:i},l.context)})}pushFileProgress(e,i,n,s=function(){}){this.liveSocket.withinOwners(e.form,(r,o)=>{r.pushWithReply(null,"progress",{event:e.getAttribute(r.binding(ul)),ref:e.getAttribute(Vt),entry_ref:i,progress:n,cid:r.targetComponentID(e.form,o)}).then(a=>{a.type==="ok"?s():r.logError("upload.progress-push-failed","Failed to push file progress",{error:a.error,fileEl:e,entryRef:i,progress:n},a.context)})})}pushInput(e,i,n,s,r,o){if(!e.form)throw new Error("form events require the input to be inside a form");let a,l=ie(n)?n:this.targetComponentID(e.form,i,r),h=u=>this.putRef([{el:e,loading:!0,lock:!0},{el:e.form,loading:!0,lock:!0}],s,"change",{...r,payload:u?.payload}),c,d=this.extractMeta(e.form,{},r.value),m={};e instanceof HTMLButtonElement&&(m.submitter=e),e.getAttribute(this.binding("change"))?c=this.serializeForm(e.form,m,[e.name]):c=this.serializeForm(e.form,m),f.isUploadInput(e)&&e.files&&e.files.length>0&&Z.trackFiles(e,Array.from(e.files)),a=Z.serializeUploads(e);let p={type:"form",event:s,value:c,meta:{_target:r._target||"undefined",...d},uploads:a,cid:l};this.pushWithReply(h,"event",p).then(u=>{u.type==="ok"?f.isUploadInput(e)&&f.isAutoUpload(e)?Un.onUnlock(e,()=>{if(Z.filesAwaitingPreflight(e).length>0){let[v,y]=h();this.undoRefs(v,s,[e.form]),this.uploadFiles(e.form,s,i,v,l,M=>{o&&o(u.resp),this.triggerAwaitingSubmit(e.form,s),this.undoRefs(v,s)})}}):o&&o(u.resp):this.logError("event.input-push-failed","Failed to push input event",{error:u.error,inputEl:e,phxEvent:s},u.context)})}triggerAwaitingSubmit(e,i){let n=this.getScheduledSubmit(e);if(n){let[s,r,o,a]=n;this.cancelSubmit(e,i),a()}}getScheduledSubmit(e){return this.formSubmits.find(([i,n,s,r])=>i.isSameNode(e))}scheduleSubmit(e,i,n,s){if(this.getScheduledSubmit(e))return!0;this.formSubmits.push([e,i,n,s])}cancelSubmit(e,i){this.formSubmits=this.formSubmits.filter(([n,s,r,o])=>n.isSameNode(e)?(this.undoRefs(s,i),!1):!0)}disableForm(e,i,n={}){let s=u=>!(fe(u,`${this.binding(Bi)}=ignore`,u.form)||fe(u,"data-phx-update=ignore",u.form)),r=u=>u.hasAttribute(this.binding(zs)),o=u=>u.tagName=="BUTTON",a=u=>["INPUT","TEXTAREA"].includes(u.tagName),l=Array.from(e.elements),h=l.filter(r),c=l.filter(o).filter(s),d=l.filter(a).filter(s);c.forEach(u=>{u.setAttribute(Ie,u.disabled.toString()),u.disabled=!0}),d.forEach(u=>{u.setAttribute(Fn,u.readOnly.toString()),u.readOnly=!0,u instanceof HTMLInputElement&&u.files&&(u.setAttribute(Ie,u.disabled.toString()),u.disabled=!0)});let m=h.concat(c).concat(d).map(u=>({el:u,loading:!0,lock:!0})),p=[{el:e,loading:!0,lock:!1},...m].reverse();return this.putRef(p,i,"submit",n)}pushFormSubmit(e,i,n,s,r,o){let a=h=>this.disableForm(e,n,{...r,form:e,payload:h?.payload,submitter:s});f.putPrivate(e,"submitter",s);let l=this.targetComponentID(e,i);if(Z.hasUploadErrors(e))return this.cancelSubmit(e,n);if(Z.hasUploadsInProgress(e)){let[h,c]=a(),d=()=>this.pushFormSubmit(e,i,n,s,r,o);return this.scheduleSubmit(e,h,r,d)}else if(Z.inputsAwaitingPreflight(e).length>0){let[h,c]=a(),d=()=>[h,c,r];this.uploadFiles(e,n,i,h,l,m=>{if(Z.inputsAwaitingPreflight(e).length>0)return this.undoRefs(h,n);let p=this.extractMeta(e,{},r.value),u=this.serializeForm(e,{submitter:s});this.pushWithReply(d,"event",{type:"form",event:n,value:u,meta:p,cid:l}).then(v=>{v.type==="ok"?o(v.resp):this.logError("event.submit-push-failed","Failed to push form submit",{error:v.error,phxEvent:n,formEl:e},v.context)})})}else if(!(e.hasAttribute(Et)&&e.classList.contains("phx-submit-loading"))){let h=this.extractMeta(e,{},r.value),c=this.serializeForm(e,{submitter:s}
16);this.pushWithReply(a,"event",{type:"form",event:n,value:c,meta:h,cid:l}).then(d=>{d.type==="ok"?o(d.resp):this.logError("event.submit-push-failed","Failed to push form submit",{error:d.error,phxEvent:n,formEl:e},d.context)})}}uploadFiles(e,i,n,s,r,o){let a=this.joinCount,l=Z.activeFileInputs(e),h=l.length;l.forEach(c=>{let d=new Z(c,this,()=>{this.activeUploaders.delete(d),h--,h===0&&o()});this.activeUploaders.add(d);let m=d.entries().map(u=>u.toPreflightPayload());if(m.length===0){this.activeUploaders.delete(d),h--;return}let p={ref:c.getAttribute(Vt),entries:m,cid:this.targetComponentID(c.form,n)};this.log("upload",()=>["sending preflight request",p],{code:"upload.preflight-request",metadata:()=>({payload:p})}),this.pushWithReply(null,"allow_upload",p).then(u=>{if(u.type==="ok")if(this.log("upload",()=>["got preflight response",u.resp],{code:"upload.preflight-response",metadata:()=>({response:u.resp})}),d.entries().forEach(v=>{u.resp.entries&&!u.resp.entries[v.ref]&&this.handleFailedEntryPreflight(v.ref,"failed preflight",d)}),u.resp.error||Object.keys(u.resp.entries).length===0)this.undoRefs(s,i),(u.resp.error||[]).map(([y,M])=>{this.handleFailedEntryPreflight(y,M,d)}),this.activeUploaders.delete(d);else{let v=y=>{this.channel.onError(()=>{this.joinCount===a&&y()})};d.initAdapterUpload(u.resp,v,this.liveSocket)}else this.activeUploaders.delete(d),this.logError("upload.push-failed","Failed to push upload",{error:u.error,phxEvent:i,formEl:e},u.context)})})}handleFailedEntryPreflight(e,i,n){if(n.isAutoUpload()){let s=n.entries().find(r=>r.ref===e.toString());s&&s.cancel()}else n.entries().map(s=>s.cancel());this.log("upload",()=>[`error for entry ${e}`,i],{code:"upload.preflight-rejected",metadata:()=>({uploadRef:e,reason:i})})}dispatchUploads(e,i,n){let s=this.targetCtxElement(e)||this.el,r=f.findUploadInputs(s).filter(o=>o.name===i);r.length===0?this.logError("upload.input-not-found",`no live file inputs found matching the name "${i}"`,{name:i},{attribution:"app"}):r.length>1?this.logError("upload.duplicate-input",`duplicate live file inputs found matching the name "${i}"`,{name:i,inputs:r},{attribution:"app"}):f.dispatchEvent(r[0],mr,{detail:{files:n}})}targetCtxElement(e){return ie(e)?f.findComponent(this.id,e):e||null}pushFormRecovery(e,i,n,s){let r=this.binding("change"),o=i.getAttribute(this.binding("target"))||i,a=i.getAttribute(this.binding(Vs))||i.getAttribute(this.binding("change")),l=Array.from(e.elements).filter(d=>f.isFormAssociated(d)&&d.name&&!d.hasAttribute(r));if(l.length===0){s();return}l.forEach(d=>d.hasAttribute(Vt)&&Z.clearFiles(d));let h=l.find(d=>d.type!=="hidden")||l[0],c=0;this.withinTargets(o,(d,m)=>{let p=this.targetComponentID(i,m);c++;let u=new CustomEvent("phx:form-recovery",{detail:{sourceElement:e}});I.exec(u,"change",a,this,h,["push",{_target:h.name,targetView:d,targetCtx:m,newCid:p,callback:()=>{c--,c===0&&s()}}])},n)}pushLinkPatch(e,i,n,s){let r=this.liveSocket.setPendingLink(i),o=e.isTrusted&&e.type!=="popstate",a=n?()=>this.putRef([{el:n,loading:o,lock:!0}],null,"click"):null,l=()=>this.liveSocket.redirect(window.location.href,null,null),h=i.startsWith("/")?`${location.protocol}//${location.host}${i}`:i;this.pushWithReply(a,"live_patch",{url:h}).then(c=>{c.type==="ok"?this.liveSocket.requestDOMUpdate(()=>{if(c.resp.link_redirect)this.liveSocket.replaceMain(i,null,s,r);else{if(c.resp.redirect)return;this.liveSocket.commitPendingLink(r)&&(this.href=i),this.applyPendingUpdates(),s&&s(r)}}):l()})}getFormsForRecovery(){if(this.joinCount===0)return{};let e=this.binding("change");return f.all(document,`#${CSS.escape(this.id)} form[${e}], [${ge}="${CSS.escape(this.id)}"] form[${e}]`).filter(i=>i instanceof HTMLFormElement).filter(i=>i.id).filter(i=>i.elements.length>0).filter(i=>i.getAttribute(this.binding(Vs))!=="ignore").map(i=>{let n=i.cloneNode(!0);Bn(n,i,{onBeforeElUpdated:(r,o)=>(f.copyPrivates(r,o),r.getAttribute("form")===i.id&&r.parentNode?(r.parentNode.removeChild(r),!1):!0)});let s=document.querySelectorAll(`[form="${CSS.escape(i.id)}"]`);return Array.from(s).forEach(r=>{let o=r.cloneNode(!0);Bn(o,r),f.copyPrivates(o,r),o.removeAttribute("form"),n.appendChild(o)}),n}).reduce((i,n)=>(i[n.id]=n,i),{})}
16maybePushComponentsDestroyed(e){let i=e.filter(s=>f.findComponent(this.id,s)===null),n=(s,r)=>{this.isDestroyed()||this.logError("component.destroy-push-failed","Failed to push components destroyed",{error:s.error,cids:r},s.context)};i.length>0&&(i.forEach(s=>this.rendered.resetRender(s)),this.pushWithReply(null,"cids_will_destroy",{cids:i}).then(s=>{s.type==="ok"?this.liveSocket.requestDOMUpdate(()=>{let r=i.filter(o=>f.findComponent(this.id,o)===null);r.length>0&&this.pushWithReply(null,"cids_destroyed",{cids:r}).then(o=>{o.type==="ok"?this.rendered.pruneCIDs(o.resp.cids):n(o,r)})}):n(s,i)}))}ownsElement(e){let i=f.closestViewEl(e);return e.getAttribute(me)===this.id||i&&i.id===this.id||!i&&this.isDead}submitForm(e,i,n,s,r={}){f.putPrivate(e,ii,!0),Array.from(e.elements).forEach(a=>f.putPrivate(a,ii,!0)),this.liveSocket.blurActiveElement(),this.pushFormSubmit(e,i,n,s,r,()=>{this.liveSocket.restorePreviouslyActiveFocus()})}binding(e){return this.liveSocket.binding(e)}pushPortalElementId(e){this.portalElementIds.add(e)}dropPortalElementId(e){this.portalElementIds.delete(e)}destroyPortalElements(){this.liveSocket.unloaded||this.portalElementIds.forEach(e=>{let i=document.getElementById(e);i&&i.remove()})}},rh=Object.freeze({RenderingBuffer:$i,ReportingBuffer:th});var Ar=class{constructor(t,e,i={}){if(this.unloaded=!1,this.buffers=rh,!e||e.constructor.name==="Object")throw new Error(` 17 a phoenix Socket must be provided as the second argument to the LiveSocket constructor. For example: 18 19 import {Socket} from "phoenix" 20 import {LiveSocket} from "phoenix_live_view" 21 let liveSocket = new LiveSocket("/live", Socket, {...}) 22 `);this.socket=new e(t,i),this.bindingPrefix=i.bindingPrefix||gl,this.params=Ze(i.params||{}),this.viewLogger=i.viewLogger,this.metadataCallbacks=i.metadata||{},this.defaults=Object.assign(Fi(bl),i.defaults||{}),this.prevActive=null,this.silenced=!1,this.main=null,this.outgoingMainEl=null,this.clickStartedAtTarget=null,this.linkRef=1,this.roots={},this.href=window.location.href,this.pendingLink=null,this.currentLocation=Fi(window.location),this.hooks=i.hooks||{},this.uploaders=i.uploaders||{},this.RenderingBuffer=$i,this.loaderTimeout=i.loaderTimeout||fl,this.disconnectedTimeout=i.disconnectedTimeout||ml,this.reloadWithJitterTimer=null,this.maxReloads=i.maxReloads||Za,this.reloadJitterMin=i.reloadJitterMin||Qa,this.reloadJitterMax=i.reloadJitterMax||tl,this.failsafeJitter=i.failsafeJitter||el,this.localStorage=i.localStorage||window.localStorage,this.sessionStorage=i.sessionStorage||window.sessionStorage,this.boundTopLevelEvents=!1,this.boundEventNames=new Set,this.blockPhxChangeWhileComposing=i.blockPhxChangeWhileComposing||!1,this.cascadePhxRemoveOnNavigation=i.cascadePhxRemoveOnNavigation??!0,this.serverCloseRef=null,this.domCallbacks=Object.assign({jsQuerySelectorAll:null,onPatchStart:Ze(),onPatchEnd:Ze(),onNodeAdded:Ze(),onBeforeElUpdated:Ze()},i.dom||{}),this.transitions=new oh,this.currentHistoryPosition=parseInt(this.sessionStorage.getItem(Pi)||"0")||0,window.addEventListener("pagehide",n=>{this.unloaded=!0}),this.socket.onOpen(()=>{this.isUnloaded()&&window.location.reload()})}version(){return"1.2.11"}isProfileEnabled(){return this.sessionStorage.getItem(_n)==="true"}attachDebugBuffer(t){let e=this.RenderingBuffer;return this.RenderingBuffer=t,e}isDebugEnabled(){return this.sessionStorage.getItem(Mi)==="true"}isDebugDisabled(){return this.sessionStorage.getItem(Mi)==="false"}enableDebug(){this.sessionStorage.setItem(Mi,"true")}enableProfiling(){this.sessionStorage.setItem(_n,"true")}disableDebug(){this.sessionStorage.setItem(Mi,"false")}disableProfiling(){this.sessionStorage.removeItem(_n)}enableLatencySim(t){this.enableDebug(),console.log("latency simulator enabled for the duration of this browser session. Call disableLatencySim() to disable"),this.sessionStorage.setItem(An,t.toString())}disableLatencySim(){this.sessionStorage.removeItem(An)}getLatencySim(){let t=this.sessionStorage.getItem(An);return t?parseInt(t):null}getSocket(){return this.socket}connect(){let t=window.location.hostname.toLowerCase();(t==="localhost"||t.endsWith(".localhost"))&&!this.isDebugDisabled()&&this.enableDebug();let e=()=>{this.resetReloadStatus(),this.joinRootViews()?(this.bindTopLevelEvents(),this.socket.connect()):this.main?this.socket.connect():this.bindTopLevelEvents({dead:!0}),this.joinDeadView()};["complete","loaded","interactive"].indexOf(document.readyState)>=0?e():document.addEventListener("DOMContentLoaded",()=>e())}disconnect(t){this.reloadWithJitterTimer!=null&&clearTimeout(this.reloadWithJitterTimer),this.serverCloseRef&&(this.socket.off([this.serverCloseRef]),this.serverCloseRef=null),this.socket.disconnect(t)}replaceTransport(t){this.reloadWithJitterTimer!=null&&clearTimeout(this.reloadWithJitterTimer),this.socket.replaceTransport(t),this.connect()}execJS(t,e,i=null){let n=new CustomEvent("phx:exec",{detail:{sourceElement:t}});this.owner(t,s=>I.exec(n,i,e,s,t))}js(){return Cr(this,"js")}unload(){this.unloaded||(this.main&&this.isConnected()&&this.log(this.main,"socket",()=>["disconnect for page nav"],{code:"socket.page-navigation-disconnect"}),this.unloaded=!0,this.destroyAllViews(),this.disconnect())}triggerDOM(t,e){this.domCallbacks[t](...e)}time(t,e){if(!this.isProfileEnabled()||!console.time)return e();console.time(t);let i=e();return console.timeEnd(t),i}log(t,e,i,n){let s=this.isDebugEnabled(),r=n?.level??"debug",o=!!n&&(r!=="debug"||s);if(!this.viewLogger&&!s&&!o)return;let[a,l]=i();this.viewLogger?this.viewLogger(t,e,a,l):s&&kl(t,e,a,l),o&&n&&yr({level:r,code:n.code,message:a,viewId:t.id,metadata:n.metadata?.(),...n.context||{attribution:"unknown"}})}requestDOMUpdate(t){this.transitions.after(t)}asyncTransition(t){this.transitions.addAsyncTransition(t)}
22transition(t,e,i=function(){}){this.transitions.addTransition(t,e,i)}onChannel(t,e,i){t.on(e,n=>{let s=this.getLatencySim();s?setTimeout(()=>i(n),s):i(n)})}reloadWithJitter(t,e){this.reloadWithJitterTimer!=null&&clearTimeout(this.reloadWithJitterTimer),this.disconnect();let i=this.reloadJitterMin,n=this.reloadJitterMax,s=Math.floor(Math.random()*(n-i+1))+i,r=dt.updateLocal(this.localStorage,window.location.pathname,fr,0,o=>o+1);r>=this.maxReloads&&(s=this.failsafeJitter),this.reloadWithJitterTimer=setTimeout(()=>{t.isDestroyed()||t.isConnected()||(t.destroy(),e?e():this.log(t,"join",()=>[`encountered ${r} consecutive reloads`],{code:"view.reload-attempts",metadata:()=>({tries:r})}),r>=this.maxReloads&&this.log(t,"join",()=>[`exceeded ${this.maxReloads} consecutive reloads. Entering failsafe mode`],{code:"view.reload-failsafe",level:"error",metadata:()=>({tries:r,maxReloads:this.maxReloads})}),this.pendingLink!==null?window.location.href=this.pendingLink:window.location.reload())},s)}getHookDefinition(t){if(t)return this.maybeInternalHook(t)||this.hooks[t]||this.maybeRuntimeHook(t)}maybeInternalHook(t){return t&&t.startsWith("Phoenix.")&&Fl[t.split(".")[1]]}maybeRuntimeHook(t){let e=document.querySelector(`script[${Hi}="${CSS.escape(t)}"]`);if(!e)return;let i=window[`phx_hook_${t}`];if(!i||typeof i!="function"){Nt("hook.runtime-not-function","a runtime hook must be a function",{runtimeHook:e,name:t},{attribution:"app"});return}let n=i();if(n&&(typeof n=="object"||typeof n=="function"))return n;Nt("hook.runtime-invalid-return","runtime hook must return an object with hook callbacks or an instance of ViewHook",{runtimeHook:e,name:t},{attribution:"app"})}isUnloaded(){return this.unloaded}isConnected(){return this.socket.isConnected()}getBindingPrefix(){return this.bindingPrefix}binding(t){return`${this.getBindingPrefix()}${t}`}channel(t,e){return this.socket.channel(t,e)}joinDeadView(){let t=document.body;if(t&&!this.isPhxView(t)&&!this.isPhxView(document.firstElementChild)){let e=this.newRootView(t);e.setHref(this.getHref()),e.joinDead(),this.main||(this.main=e),window.requestAnimationFrame(()=>{e.execNewMounted(),this.maybeScroll(history.state?.scroll)})}}joinRootViews(){let t=!1;return f.all(document,`${ni}:not([${me}])`,e=>{if(!this.getRootById(e.id)){let i=this.newRootView(e);f.isPhxSticky(e)||i.setHref(this.getHref()),i.join(),e.hasAttribute(jn)&&(this.main=i)}t=!0}),t}redirect(t,e,i){i&&dt.setCookie(Xs,i,60),this.unload(),dt.redirect(t,e)}replaceMain(t,e,i=null,n=this.setPendingLink(t)){if(!this.main)return;let s=this.currentLocation.href;this.outgoingMainEl=this.outgoingMainEl||this.main.el;let r=f.findPhxSticky(document)||[],o=this.phxRemoveElementsForNavigation(this.outgoingMainEl,r),a=f.cloneNode(this.outgoingMainEl,""),l=this.main;l.showLoader(this.loaderTimeout),l.destroy(),this.main=this.newRootView(a,e,s),this.main.setRedirect(t),this.transitionRemoves(o,l),this.main.join((h,c)=>{h===1&&this.commitPendingLink(n)&&this.requestDOMUpdate(()=>{o.forEach(d=>{d.isSameNode(this.outgoingMainEl)||d.remove()}),r.forEach(d=>a.appendChild(d)),this.outgoingMainEl.replaceWith(a),this.outgoingMainEl=null,i&&i(n),c()})})}phxRemoveElementsForNavigation(t,e=f.findPhxSticky(document)||[]){let i=`[${this.binding("remove")}]`;return(this.cascadePhxRemoveOnNavigation?[t,...f.all(t,i)]:[t]).filter(s=>s.matches(i)&&!f.isChildOfAny(s,e))}transitionRemoves(t,e,i){let n=this.binding("remove"),s=r=>{r.preventDefault(),r.stopImmediatePropagation()};t.forEach(r=>{for(let a of this.boundEventNames)r.addEventListener(a,s,!0);let o=new CustomEvent("phx:exec",{detail:{sourceElement:r}});I.exec(o,"remove",r.getAttribute(n),e,r)}),this.requestDOMUpdate(()=>{t.forEach(r=>{for(let o of this.boundEventNames)r.removeEventListener(o,s,!0)}),i&&i()})}isPhxView(t){return t.getAttribute&&t.getAttribute(Ut)!==null}newRootView(t,e,i){let n=new sh(t,this,null,e,i);return this.roots[n.id]=n,n}owner(t,e){let i,n=f.closestViewEl(t);if(n)i=f.private(n,"view");else{if(!t.isConnected)return null;i=this.main}return i&&e?e(i):i}withinOwners(t,e){this.owner(t,i=>e(i,t))}getViewByEl(t){let e=t.getAttribute(zt);return De(this.getRootById(e),i=>i.getDescendentByEl(t))}getRootById(t){return this.roots[t]}destroyAllViews(){for(let t in this.roots)this.roots[t].destroy(),delete this.roots[t];this.main=null}destroyViewByEl(t){let e=this.getRootById(t.getAttribute(zt));e&&e.id===t.id?(e.destroy(),delete this.roots[e.id]):e&&e.destroyDescendent(t.id)}getActiveElement(){return document.activeElement}dropActiveElement(t){this.prevActive&&t.ownsElement(this.prevActive)&&(this.prevActive=null)}restorePreviouslyActiveFocus(){this.prevActive&&this.prevActive!==document.body&&this.prevActive instanceof HTMLElement&&this.prevActive.focus()}blurActiveElement(){this.prevActive=this.getActiveElement(),this.prevActive!==document.body&&this.prevActive instanceof HTMLElement&&this.prevActive.blur()}bindTopLevelEvents({dead:t}={}){if(this.serverCloseRef===null&&(this.serverCloseRef=this.socket.onClose(i=>{if(i&&i.code===1e3&&this.main)return this.reloadWithJitter(this.main)})),this.boundTopLevelEvents)return;this.boundTopLevelEvents=!0,document.body.addEventListener("click",function(){}),window.addEventListener("pageshow",i=>{i.persisted&&(this.getSocket().disconnect(),this.withPageLoading({to:window.location.href,kind:"redirect"}),window.location.reload())},!0),t||this.bindNav(),this.bindClicks(),t||this.bindForms(),this.bind({keyup:"keyup",keydown:"keydown"},(i,n,s,r,o,a)=>{let l=r.getAttribute(this.binding(dl)),h=i.key&&i.key.toLowerCase();if(l&&l.toLowerCase()!==h)return;let c={key:i.key,...this.eventMeta(n,i,r)};I.exec(i,n,o,s,r,["push",{data:c}])}
22),this.bind({blur:"focusout",focus:"focusin"},(i,n,s,r,o,a)=>{if(!a){let l={...this.eventMeta(n,i,r)};I.exec(i,n,o,s,r,["push",{data:l}])}}),this.bind({blur:"blur",focus:"focus"},(i,n,s,r,o,a)=>{if(a==="window"){let l=this.eventMeta(n,i,r);I.exec(i,n,o,s,r,["push",{data:l}])}}),this.on("dragover",i=>i.preventDefault());let e=new WeakMap;this.on("dragenter",i=>{let n=i.target&&f.elementFromTarget(i.target);if(!n)return;let s=fe(n,this.binding(Ti));if(!(!s||!(s instanceof HTMLElement))&&xl(i)){let r=(e.get(s)||0)+1;e.set(s,r),r===1&&this.js().addClass(s,Cn)}}),this.on("dragleave",i=>{let n=i.target&&f.elementFromTarget(i.target);if(!n)return;let s=fe(n,this.binding(Ti));if(!s||!(s instanceof HTMLElement))return;let r=e.get(s);r!==void 0&&(r>1?e.set(s,r-1):(e.delete(s),this.js().removeClass(s,Cn)))}),this.on("drop",i=>{let n=i.target&&f.elementFromTarget(i.target);if(!n)return;i.preventDefault();let s=fe(n,this.binding(Ti));if(!s||!(s instanceof HTMLElement)||(e.delete(s),this.js().removeClass(s,Cn),!i.dataTransfer))return;let r=s.getAttribute(this.binding(Ti)),o=r&&document.getElementById(r),a=Array.from(i.dataTransfer.files||[]);!o||!(o instanceof HTMLInputElement)||o.disabled||a.length===0||!(o.files instanceof FileList)||(Z.trackFiles(o,a,i.dataTransfer),o.dispatchEvent(new Event("input",{bubbles:!0})))}),this.on(mr,i=>{let n=i.target&&f.elementFromTarget(i.target);if(!f.isUploadInput(n))return;let s=Array.from(i.detail.files||[]).filter(r=>r instanceof File||r instanceof Blob);Z.trackFiles(n,s),n.dispatchEvent(new Event("input",{bubbles:!0}))})}eventMeta(t,e,i){let n=this.metadataCallbacks[t];return n?n(e,i):{}}setPendingLink(t){return this.linkRef++,this.pendingLink=t,this.resetReloadStatus(),this.linkRef}resetReloadStatus(){dt.deleteCookie(Xs)}commitPendingLink(t){return this.linkRef!==t?!1:(this.pendingLink!==null&&(this.href=this.pendingLink,this.pendingLink=null),!0)}getHref(){return this.href}hasPendingLink(){return!!this.pendingLink}bind(t,e){for(let i in t){let n=t[i];this.on(n,s=>{let r=this.binding(i),o=this.binding(`window-${i}`),a=s.target instanceof Element&&s.target.getAttribute(r);s.target instanceof Element&&(a?this.debounce(s.target,s,n,()=>{this.withinOwners(s.target,l=>{e(s,i,l,s.target,a,null)})}):f.all(document,`[${o}]`,l=>{let h=l.getAttribute(o);this.debounce(l,s,n,()=>{this.withinOwners(l,c=>{e(s,i,c,l,h,"window")})})}))})}}bindClicks(){this.on("mousedown",t=>this.clickStartedAtTarget=t.target),this.bindClick()}bindClick(){let t=this.binding("click");window.addEventListener("click",e=>{let i=e.target&&f.elementFromTarget(e.target);if(!i)return;e.detail===0&&(this.clickStartedAtTarget=i);let n=this.clickStartedAtTarget||i;if(i=fe(i,t),this.dispatchClickAway(e,n),this.clickStartedAtTarget=null,!i)return;let s=i.getAttribute(t);if(!s){f.isNewPageClick(e,window.location)&&this.unload();return}i.getAttribute("href")==="#"&&e.preventDefault(),!i.hasAttribute(Et)&&this.debounce(i,e,"click",()=>{this.withinOwners(i,r=>{I.exec(e,"click",s,r,i,["push",{data:this.eventMeta("click",e,i)}])})})},!1)}dispatchClickAway(t,e){let i=this.binding("click-away"),n=e.closest(`[${ne}]`),s=n&&f.byId(n.getAttribute(ne));f.all(document,`[${i}]`,r=>{let o=e;n&&!n.contains(r)&&(o=s),r.isSameNode(o)||r.contains(o)||!I.isVisible(e)||this.withinOwners(r,a=>{let l=r.getAttribute(i);I.isVisible(r)&&I.isInViewport(r)&&I.exec(t,"click",l,a,r,["push",{data:this.eventMeta("click",t,t.target)}])})})}bindNav(){if(!dt.canPushState())return;history.scrollRestoration&&(history.scrollRestoration="manual");let t=null;window.addEventListener("scroll",e=>{t!=null&&clearTimeout(t),t=setTimeout(()=>{dt.updateCurrentState(i=>Object.assign(i,{scroll:window.scrollY}))},100)}),window.addEventListener("popstate",e=>{if(!this.isNewLocation(window.location))return;let{type:i,backType:n,id:s,scroll:r,position:o}=e.state||{},a=window.location.href,l=o>this.currentHistoryPosition,h=l?i:n||i,d={href:a,patch:h==="patch",pop:!0,direction:l?"forward":"backward"};if(!this.dispatchBeforeNavigate(d)){l?history.back():history.forward();return}this.registerNewLocation(window.location),this.currentHistoryPosition=o||0,this.sessionStorage.setItem(Pi,this.currentHistoryPosition.toString()),f.dispatchEvent(window,"phx:navigate",{detail:d}),this.requestDOMUpdate(()=>{let m=()=>{this.maybeScroll(r)};this.main&&this.main.isConnected()&&h==="patch"&&s===this.main.id?this.main.pushLinkPatch(e,a,null,m):this.replaceMain(a,null,m)})},!1),window.addEventListener("click",e=>{let i=e.target&&f.elementFromTarget(e.target);if(!i)return;let n=fe(i,kn),s=n&&n.getAttribute(kn);if(!s||!this.isConnected()||!this.main||f.wantsNewTab(e))return;let r=n.href instanceof SVGAnimatedString?n.href.baseVal:n.href,o=n.getAttribute(Us);if(o!=="replace"&&o!=="push")throw new Error(`expected ${Us} to be "replace" or "push", got: ${o}`);if(s!=="patch"&&s!=="redirect")throw new Error(`expected ${kn} to be "patch" or "redirect", got: ${s}`);if(e.preventDefault(),e.stopImmediatePropagation(),this.pendingLink===r)return;let a={href:r,patch:s==="patch",pop:!1,direction:"forward"},l=n.getAttribute(this.binding("click")),h=()=>{l&&this.requestDOMUpdate(()=>this.execJS(n,l,"click"))};if(!this.dispatchBeforeNavigate(a)){h();return}this.requestDOMUpdate(()=>{s==="patch"?this.pushHistoryPatch(e,r,o,n):this.historyRedirect(e,r,o,null,n),h()})},!1)}maybeScroll(t){typeof t=="number"&&requestAnimationFrame(()=>{window.scrollTo(0,t)})}dispatchEvent(t,e={}){f.dispatchEvent(window,`phx:${t}`,{detail:e})}dispatchEvents(t){t.forEach(([e,i])=>this.dispatchEvent(e,i))}withPageLoading(t,e){f.dispatchEvent(window,"phx:page-loading-start",{detail:t});let i=()=>f.dispatchEvent(window,"phx:page-loading-stop",{detail:t});return e?e(i):i}
22dispatchBeforeNavigate(t){return f.dispatchEvent(window,"phx:before-navigate",{detail:t})}pushHistoryPatch(t,e,i,n){if(!this.isConnected()||!(this.main&&this.main.isMain()))return dt.redirect(e);this.withPageLoading({to:e,kind:"patch"},s=>{this.main.pushLinkPatch(t,e,n,r=>{this.historyPatch(e,i,r),s()})})}historyPatch(t,e,i=this.setPendingLink(t)){this.commitPendingLink(i)&&(this.currentHistoryPosition++,this.sessionStorage.setItem(Pi,this.currentHistoryPosition.toString()),dt.updateCurrentState(n=>({...n,backType:"patch"})),dt.pushState(e,{type:"patch",id:this.main.id,position:this.currentHistoryPosition},t),f.dispatchEvent(window,"phx:navigate",{detail:{patch:!0,href:t,pop:!1,direction:"forward"}}),this.registerNewLocation(window.location))}historyRedirect(t,e,i,n,s){let r=s&&t.isTrusted&&t.type!=="popstate";if(r&&s.classList.add("phx-click-loading"),!this.isConnected()||!(this.main&&this.main.isMain()))return dt.redirect(e,n);if(/^\/$|^\/[^\/]+.*$/.test(e)){let{protocol:a,host:l}=window.location;e=`${a}//${l}${e}`}let o=window.scrollY;this.withPageLoading({to:e,kind:"redirect"},a=>{this.replaceMain(e,n,l=>{l===this.linkRef&&(this.currentHistoryPosition++,this.sessionStorage.setItem(Pi,this.currentHistoryPosition.toString()),dt.updateCurrentState(h=>({...h,backType:"redirect"})),dt.pushState(i,{type:"redirect",id:this.main.id,scroll:o,position:this.currentHistoryPosition},e),f.dispatchEvent(window,"phx:navigate",{detail:{href:e,patch:!1,pop:!1,direction:"forward"}}),this.registerNewLocation(window.location)),r&&s.classList.remove("phx-click-loading"),a()})})}registerNewLocation(t){return this.isNewLocation(t)?(this.currentLocation=Fi(t),!0):!1}isNewLocation(t){let{pathname:e,search:i}=this.currentLocation;return e+i!==t.pathname+t.search}bindForms(){let t=0,e=!1;this.on("submit",i=>{if(!(i.target instanceof HTMLFormElement))return;let n=i.target.getAttribute(this.binding("submit")),s=i.target.getAttribute(this.binding("change"));!e&&s&&!n&&(e=!0,i.preventDefault(),this.withinOwners(i.target,r=>{r.disableForm(i.target,s),window.requestAnimationFrame(()=>{f.isUnloadableFormSubmit(i)&&this.unload(),i.target.submit()})}))}),this.on("submit",i=>{if(!(i.target instanceof HTMLFormElement))return;let n=i.target.getAttribute(this.binding("submit"));if(!n){f.isUnloadableFormSubmit(i)&&this.unload();return}i.preventDefault(),this.withinOwners(i.target,s=>{I.exec(i,"submit",n,s,i.target,["push",{submitter:i.submitter}])})});for(let i of["change","input"])this.on(i,n=>{if(!f.isFormAssociated(n.target))return;if(n instanceof CustomEvent&&n.target.form===void 0){if(n.detail&&n.detail.dispatcher)throw new Error(`dispatching a custom ${i} event is only supported on input elements inside a form`);return}let s=n.target,r=this.binding("change");if(this.blockPhxChangeWhileComposing&&n instanceof InputEvent&&n.isComposing){let p=`composition-listener-${i}`;f.private(s,p)||(f.putPrivate(s,p,!0),s.addEventListener("compositionend",()=>{s.dispatchEvent(new Event(i,{bubbles:!0})),f.deletePrivate(s,p)},{once:!0}));return}let o=s.getAttribute(r),a=s.form&&s.form.getAttribute(r),l=o||a;if(!l||s.type==="number"&&s.validity&&s.validity.badInput)return;let h=o?s:s.form,c=t;t++;let{at:d,type:m}=f.private(s,"prev-iteration")||{};d===c-1&&i==="change"&&m==="input"||(f.putPrivate(s,"prev-iteration",{at:c,type:i}),this.debounce(s,n,i,()=>{this.withinOwners(h,p=>{f.putPrivate(s,Ni,!0),I.exec(n,"change",l,p,s,["push",{_target:s.name,dispatcher:h}])})}))});this.on("reset",i=>{let n=i.target;f.resetForm(n);let s=Array.from(n.elements).find(r=>"type"in r&&r.type==="reset");s&&window.requestAnimationFrame(()=>{s.dispatchEvent(new Event("input",{bubbles:!0,cancelable:!1}))})})}debounce(t,e,i,n){if(i==="blur"||i==="focusout")return n();let s=this.binding(al),r=this.binding(ll),o=this.defaults.debounce.toString(),a=this.defaults.throttle.toString();this.withinOwners(t,l=>{let h=()=>!l.isDestroyed()&&document.body.contains(t);f.debounce(t,e,s,o,r,a,h,()=>{n()})})}silenceEvents(t){this.silenced=!0,t(),this.silenced=!1}on(t,e){this.boundEventNames.add(t),window.addEventListener(t,i=>{this.silenced||e(i)})}jsQuerySelectorAll(t,e,i){let n=this.domCallbacks.jsQuerySelectorAll;return n?n(t,e,i):i()}},oh=class{constructor(){this.transitions=new Set,this.promises=new Set,this.pendingOps=[]}reset(){this.transitions.forEach(t=>{clearTimeout(t),this.transitions.delete(t)}),this.promises.clear(),this.flushPendingOps()}after(t){this.size()===0?t():this.pushPendingOp(t)}
22addTransition(t,e,i){e();let n=setTimeout(()=>{this.transitions.delete(n),i(),this.flushPendingOps()},t);this.transitions.add(n)}addAsyncTransition(t){this.promises.add(t),t.then(()=>{this.promises.delete(t),this.flushPendingOps()})}pushPendingOp(t){this.pendingOps.push(t)}size(){return this.transitions.size+this.promises.size}flushPendingOps(){if(this.size()>0)return;let t=this.pendingOps.shift();t&&(t(),this.flushPendingOps())}};var xr={};function ve(t,e,i){return n=>{(t.el.dataset.events||"").split(",").indexOf(e)>-1&&t.pushEventTo(t.el,`turnstile:${i||e}`,n)}}var si={mounted(){turnstile.render(this.el,{callback:ve(this,"success"),"error-callback":ve(this,"error"),"expired-callback":ve(this,"expired"),"before-interactive-callback":ve(this,"beforeInteractive","before-interactive"),"after-interactive-callback":ve(this,"afterInteractive","after-interactive"),"unsupported-callback":ve(this,"unsupported"),"timeout-callback":ve(this,"timeout")}),this.handleEvent("turnstile:refresh",t=>{(!t.id||t.id===this.el.id)&&turnstile.reset(this.el)}),this.handleEvent("turnstile:remove",t=>{(!t.id||t.id===this.el.id)&&turnstile.remove(this.el)})}};var yn=qa(Mr());var ah={TIT2:"title",TPE1:"artist",TALB:"album"};function Wn(t,e){return(t[e]&127)<<21|(t[e+1]&127)<<14|(t[e+2]&127)<<7|t[e+3]&127}function lh(t){if(t.length===0)return"";let e=t[0],i=t.subarray(1);return e===0||e===3?new TextDecoder(e===3?"utf-8":"iso-8859-1").decode(i).replace(/\0+$/,""):e===1||e===2?new TextDecoder(e===1?"utf-16":"utf-16be").decode(i).replace(/\0+$/,""):""}function Pr(t){if(!t||t.length<10||t[0]!==73||t[1]!==68||t[2]!==51)return null;let e=t[3],i=t[5],n=Wn(t,6),s={},r=10;i&64&&(r+=Wn(t,r));let o=Math.min(10+n,t.length);for(;r+10<=o;){let a=String.fromCharCode(t[r],t[r+1],t[r+2],t[r+3]);if(a==="\0\0\0\0")break;let l=e===4?Wn(t,r+4):t[r+4]<<24|t[r+5]<<16|t[r+6]<<8|t[r+7];if(r+=10,l<=0||r+l>o)break;let h=ah[a];h&&(s[h]=lh(t.subarray(r,r+l))),r+=l}return Object.keys(s).length>0?s:null}var hh={enableWorker:!0,lowLatencyMode:!1,startLevel:1,testBandwidth:!1,initialLiveManifestSize:3,liveSyncDurationCount:3,abrEwmaDefaultEstimate:2e5,fragLoadPolicy:{default:{maxTimeToFirstByteMs:4e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}}},Ir=hh;var qi=null,ch=8e3,Kn=new WeakMap,dh={TIT2:"title",TPE1:"artist",TALB:"album"};function zi(t){return t==="autodj"}async function Xn(){return qi||(qi=import("./hls-UBS7LC7M.js").then(t=>t.default||t).catch(t=>{throw qi=null,t})),qi}function uh(t){if(!t)return null;let e=t.value;if(e&&typeof e=="object"&&typeof e.key=="string"){let i=dh[e.key];return i&&typeof e.data=="string"&&e.data!==""?{[i]:e.data}:null}return t.data instanceof ArrayBuffer?Pr(new Uint8Array(t.data)):null}function fh(t){let e=t?Array.from(t):[];if(e.length===0)return null;let i={};for(let n of e){let s=uh(n);if(s)for(let r of["title","artist","album"])typeof s[r]=="string"&&s[r]!==""&&(i[r]=s[r])}return Object.keys(i).length>0?i:null}function Dr(t,e){if(!t||typeof e!="function")return;Lr(t);let i={trackListeners:new Map,onAddTrack:null},n=r=>{if(!r||r.kind!=="metadata"||i.trackListeners.has(r))return;r.mode="hidden";let o=()=>{let a=fh(r.activeCues);a&&e(a)};r.addEventListener("cuechange",o),i.trackListeners.set(r,o)};for(let r of Array.from(t.textTracks||[]))n(r);let s=r=>n(r.track);t.textTracks.addEventListener("addtrack",s),i.onAddTrack=s,Kn.set(t,i)}function Lr(t){let e=t&&Kn.get(t);if(e){e.onAddTrack&&t.textTracks&&t.textTracks.removeEventListener("addtrack",e.onAddTrack);for(let[i,n]of e.trackListeners)i.removeEventListener("cuechange",n);e.trackListeners.clear(),Kn.delete(t)}}async function Rr(t,e,i,n={}){Vi(t,i,{resetAudio:!1});let s=await Xn();if(!s.isSupported())return t.src=e,t.load(),Dr(t,n.onMetadata),null;let r=new s(Ir);return Dr(t,n.onMetadata),await new Promise((o,a)=>{let l=null,h=!1,c=()=>r.loadSource(e),d=()=>u(()=>o(r)),m=(v,y)=>{y?.fatal&&u(()=>{r.destroy(),a(new Error(y.details||"Fatal HLS playback error"))})},p=()=>
22{l&&(clearTimeout(l),l=null),r.off(s.Events.MEDIA_ATTACHED,c),r.off(s.Events.MANIFEST_PARSED,d),r.off(s.Events.ERROR,m)},u=v=>{h||(h=!0,p(),v())};r.on(s.Events.MEDIA_ATTACHED,c),r.on(s.Events.MANIFEST_PARSED,d),r.on(s.Events.ERROR,m),r.attachMedia(t),l=window.setTimeout(()=>{u(()=>{r.destroy(),a(new Error("Timed out while attaching HLS stream"))})},ch)})}function Vi(t,e,i={}){t&&Lr(t),e&&e.destroy(),t&&i.resetAudio!=!1&&(t.removeAttribute("src"),t.load())}var Gn=null;function Fr(){if(Gn===null){let t=document.createElement("audio");t.volume=.5,Gn=t.volume===.5}return Gn}var Or=[1e3,2e3,5e3,1e4,15e3,3e4],ph=10,mh=5e3,Jn="cloudradio_volume";function gh(t){try{return localStorage.getItem(t)}catch{return null}}function Hr(t,e){try{localStorage.setItem(t,e)}catch{}}var be=class{constructor({onStateChange:e,onMetadata:i,persistVolume:n=!0}={}){this.onStateChange=typeof e=="function"?e:()=>{},this.onMetadata=typeof i=="function"?i:()=>{},this.persistVolume=n,this.audio=null,this.audioTapped=!1,this.hls=null,this.audioContext=null,this.desiredState="stopped",this.reconnectAttempts=0,this.isReconnecting=!1,this.reconnectTimer=null,this.stallCheckTimer=null,this.lastStallCheckTime=0,this.hasStreamSrc=!1,this.playRequestId=0,this.volume=80,this.isMuted=!1,this.streamUrl="",this.streamType="external",this.stationTitle="Live Radio",this.trackTitle="",this.trackArtist="",this.coverArtUrl="",this.defaultCoverUrl="",this.coverPending=!1}init({volume:e}={}){if(typeof e=="number"&&!Number.isNaN(e)&&(this.volume=e),this.persistVolume){let i=gh(Jn);if(i!==null){let n=parseInt(i,10);Number.isNaN(n)||(this.volume=n)}}this.audio=this.createAudio(),this.setupMediaSession()}createAudio(){let e=new Audio;return e.preload="none",e.volume=this.volume/100,e.muted=this.isMuted,e.addEventListener("playing",()=>this.audio===e&&this.onPlaying()),e.addEventListener("pause",()=>this.audio===e&&this.onPause()),e.addEventListener("waiting",()=>this.audio===e&&this.onBuffering()),e.addEventListener("stalled",()=>this.audio===e&&this.onStalled()),e.addEventListener("error",i=>this.audio===e&&this.onError(i)),e.addEventListener("ended",()=>this.audio===e&&this.onEnded()),e.addEventListener("canplay",()=>this.audio===e&&this.emitState()),e.addEventListener("volumechange",()=>this.audio===e&&this.onVolumeChange()),this.audioTapped=!1,e}setSource(e,i){let n=e||"",s=i||"external",r=n!==this.streamUrl||s!==this.streamType;this.streamUrl=n,this.streamType=s,r&&this.desiredState==="playing"&&(this.resetStreamSource(),this.play())}setNowPlaying({stationTitle:e,title:i,artist:n,coverArtUrl:s,defaultCoverUrl:r,coverPending:o}={}){typeof e=="string"&&e&&(this.stationTitle=e),typeof i=="string"&&(this.trackTitle=i),typeof n=="string"&&(this.trackArtist=n),typeof s=="string"&&(this.coverArtUrl=s),typeof r=="string"&&r&&(this.defaultCoverUrl=r),typeof o=="boolean"&&(this.coverPending=o),this.syncMediaSessionMetadata()}computeState(){return this.audio&&this.desiredState==="playing"?this.audio.readyState>=3&&!this.audio.paused?"playing":this.isReconnecting||this.audio.readyState<3?"buffering":"playing":"stopped"}emitState(e){let i=e||this.computeState();"mediaSession"in navigator&&(navigator.mediaSession.playbackState=i==="playing"?"playing":"paused"),this.onStateChange(i)}toggle(){this.desiredState==="playing"?this.stop():this.play()}async play(){let e=++this.playRequestId;if(!(!this.audio||!this.streamUrl)){if(this.desiredState="playing",this.emitState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),!this.hasStreamSrc)try{if(await this.attachStreamSource(e),this.isStalePlayRequest(e)){this.resetStreamSource();return}}catch(i){if(this.isStalePlayRequest(e))return;console.error("[PlaybackEngine] Failed to attach stream source:",i),this.desiredState="stopped",this.emitState("error");return}this.unlockAudioContext();try{if(await this.audio.play(),this.isStalePlayRequest(e)){this.stop();return}this.reconnectAttempts=0,this.emitState()}catch(i){if(this.isStalePlayRequest(e))return;console.warn("[PlaybackEngine] Play failed:",i),this.desiredState="stopped",this.stop()}}}stop(){this.audio&&(this.playRequestId+=1,this.desiredState="stopped",this.isReconnecting=!1,this.reconnectAttempts=0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stallCheckTimer&&(clearTimeout(this.stallCheckTimer),this.stallCheckTimer=null),this.audio.pause(),this.resetStreamSource(),this.emitState("stopped"))}setVolume(e){this.volume=Math.max(0,Math.min(100,e)),this.audio&&(this.audio.volume=this.volume/100),this.persistVolume&&Hr(Jn,this.volume.toString()),this.isMuted&&this.volume>0&&(this.isMuted=!1,this.audio&&(this.audio.muted=!1))}toggleMute(){if(this.audio)return this.isMuted=!this.isMuted,this.audio.muted=this.isMuted,this.isMuted}onPlaying(){this.desiredState==="playing"&&(this.isReconnecting=!1,this.reconnectAttempts=0,this.emitState())}onPause(){this.emitState()}onBuffering(){this.desiredState==="playing"&&this.emitState()}onStalled(){this.desiredState!=="playing"||this.stallCheckTimer||(this.stallCheckTimer=setTimeout(()=>{if(this.stallCheckTimer=null,this.desiredState!=="playing"||!this.audio)return;let e=this.audio.currentTime;e===this.lastStallCheckTime&&!this.audio.paused&&(console.warn("[PlaybackEngine] Stream stalled, attempting to re
22cover..."),this.attemptReconnect()),this.lastStallCheckTime=e},mh))}onError(e){if(this.desiredState!=="playing")return;let i=e.target?.error;if(console.error("[PlaybackEngine] Audio error:",i),i?.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED){this.desiredState="stopped",this.emitState("error");return}this.attemptReconnect()}onEnded(){this.desiredState==="playing"&&this.attemptReconnect()}onVolumeChange(){this.audio&&!this.isMuted&&(this.volume=Math.round(this.audio.volume*100),this.persistVolume&&Hr(Jn,this.volume.toString()))}attemptReconnect(){if(this.isReconnecting||this.desiredState!=="playing")return;if(this.reconnectAttempts>=ph){console.error("[PlaybackEngine] Max reconnect attempts reached"),this.desiredState="stopped",this.emitState("error");return}this.isReconnecting=!0,this.emitState("buffering");let e=Or[Math.min(this.reconnectAttempts,Or.length-1)];console.debug(`[PlaybackEngine] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts+1})`),this.reconnectTimer=setTimeout(()=>{this.reconnectAttempts+=1,this.isReconnecting=!1,!(this.desiredState!=="playing"||!this.audio)&&(this.resetStreamSource(),this.play())},e)}async attachStreamSource(e){if(zi(this.streamType)){let i=await Rr(this.audio,this.streamUrl,this.hls,{onMetadata:n=>this.onMetadata(n)});if(this.isStalePlayRequest(e)){Vi(this.audio,i);return}this.hls=i}else this.audioTapped&&(this.audio.pause(),this.audio=this.createAudio()),this.audio.src=this.streamUrl,this.audio.load();this.hasStreamSrc=!0}isStalePlayRequest(e){return e!==this.playRequestId||this.desiredState!=="playing"}resetStreamSource(){Vi(this.audio,this.hls),this.hls=null,this.hasStreamSrc=!1}setupMediaSession(){"mediaSession"in navigator&&(this.syncMediaSessionMetadata(),navigator.mediaSession.setActionHandler("play",()=>{this.play()}),navigator.mediaSession.setActionHandler("pause",()=>this.stop()),navigator.mediaSession.setActionHandler("stop",()=>this.stop()))}buildArtwork(e){return e?[{src:e}]:[]}syncMediaSessionMetadata(e={}){if(!("mediaSession"in navigator))return;let i=e.title||this.trackTitle||this.stationTitle,n=e.artist||this.trackArtist||"Live Radio",s=this.coverPending?"":this.defaultCoverUrl,r=e.artworkUrl||this.coverArtUrl||s,o=this.stationTitle,a=this.lastMediaSessionMetadata;a&&a.title===i&&a.artist===n&&a.album===o&&a.artworkUrl===r||(this.lastMediaSessionMetadata={title:i,artist:n,album:o,artworkUrl:r},navigator.mediaSession.metadata=new MediaMetadata({title:i,artist:n,album:o,artwork:this.buildArtwork(r)}))}unlockAudioContext(){if(!this.audioContext)try{let e=window.AudioContext||window.webkitAudioContext;e&&(this.audioContext=new e,this.audioContext.state==="suspended"&&this.audioContext.resume())}catch(e){console.warn("[PlaybackEngine] Could not create AudioContext:",e)}}destroy(){this.lastMediaSessionMetadata=null,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stallCheckTimer&&(clearTimeout(this.stallCheckTimer),this.stallCheckTimer=null),this.audio&&(this.audio.pause(),this.resetStreamSource(),this.audio=null,this.desiredState="stopped"),this.audioContext&&(this.audioContext.close(),this.audioContext=null)}};var vh="id:",bh="song|";function Yn(){return{fallback_ms:2e4,gate:{enabled:!1},holds:{default:500,library:500,live:500}}}function Zn(t){let e=Yn();if(!t||typeof t!="object")return e;let i=t.gate&&typeof t.gate=="object"?t.gate:{},n=t.holds&&typeof t.holds=="object"?t.holds:{};return{...e,...t,gate:{...e.gate,...i},holds:{...e.holds,...n}}}function Qn(t){if(typeof t!="string"||t.trim()==="")return Yn();try{return Zn(JSON.parse(t))}catch{return Yn()}}function Nr(t){return yh(t)===!0}function yh(t){return Zn(t).gate.enabled===!0}function Ur(t,e){let i=Zn(e).holds;return typeof t=="string"&&t.startsWith(vh)?i.library:typeof t=="string"&&t.startsWith(bh)?i.live:i.default}function Wi(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase().replace(/\s+/g," ");return e.length>0?e:null}function wh(t){if(typeof t!="string")return null;let e=t.split("|")[0];return e&&e.length>0?e:null}function Eh(t){if(!t||typeof t!="object")return null;let e=Wi(t.title),i=Wi(t.artist),n=Wi(t.album);return!e&&!i&&!n?null:[e||"",i||"",n||""].join("|")}var ye=class{constructor({onReveal:e}={}){this.onReveal=typeof e=="function"?e:()=>{},this.config=Qn(null),this.gateEnabled=!1,this.pendingKey=null,this.pendingCueTitle=null,this.pendingMatchedCue=!1,this.cueSequence=0,this.baselineSequence=0,this.currentCueSignature=null,this.baselineCueSignature=null,this.revealTimer=null,this.revealTimerKey=null,this.lastRevealedKey=null}setConfig(e){this.config=Qn(e),this.gateEnabled=Nr(this.config)}setPending(e,i){let n=e||null;if(n!==this.pendingKey&&(this.cancel(),this.pendingMatchedCue=!1,this.baselineSequence=this.cueSequence,this.baselineCueSignature=this.currentCueSignature),this.pendingKey=n,this.pendingCueTitle=Wi(i),this.lastRevealedKey&&this.lastRevealedKey!==this.pendingKey&&(this.lastRevealedKey=null),this.pendingKey&&this.lastRevealedKey===this.pendingKey){this.onReveal(this.pendingKey);return}this.maybeReveal()}feedCue(e){if(!this.gateEnabled)return;let i=Eh(e);!i||i===this.currentCueSignature||(this.currentCueSignature=i,this.cueSequence+=1,this.maybeReveal())}maybeReveal(){if(!(!this.gateEnabled||!this.pendingKey)&&this.lastRevealedKey!==this.pendingKey){if(this.matchesPendingCue()){this.schedule(this.pendingKey),this.pendingMatchedCue=!0;return}this.cueSequence<=this.baselineSequence||this.currentCueSignature!==this.baselineCueSignature&&this.schedule(this.pendingKey)}}matchesPendingCue(){return this.pendingCueTitle?wh(this.currentCueSignature)===this.pendingCueTitle:!1}schedule(e){e&&(this.revealTimer&&this.revealTimerKey===e||(this.cancel(),this.revealTimerKey=e,this.revealTimer=window.setTimeout(()=>{this.revealTimer=null,this.revealTimerKey=null,this.pendingKey===e&&this.lastRevealedKey!==e&&(!(this.pendingMatchedCue&&this.matchesPendingCue())&&(this.cueSequence<=this.baselineSequence||this.currentCueSignature===this.baselineCueSignature)||(this.lastRevealedKey=e,this.onReveal(e)))},Ur(e,this.config))))}cancel(){this.revealTimer&&window.clearTimeout(this.revealTimer),this.revealTimer=null,this.revealTimerKey=null,this.pendingMatchedCue=!1}resetCues(){this.cancel(),this.currentCueSignature=null,this.pendingMatchedCue=!1}};var Br="autodj:player:configure",$r="autodj:player:request-state",jr="autodj:player:toggle",Sh="autodj:player:state",Ch="autodj:player:reveal",kh="global-autodj-player",ts=class{constructor(e){this.el=e,this.engine=new be({persistVolume:!0,onStateChange:i=>this.emitState(i),onMetadata:i=>this.reveal.feedCue(i)}),this.reveal=new ye({onReveal:i=>this.dispatchReveal(i)}),this.engine.defaultCoverUrl=this.el.dataset.defaultCoverUrl||""}init(){this.engine.init(),this.engine.setNowPlaying({defaultCoverUrl:this.el.dataset.defaultCoverUrl||""}),this._configureHandler=e=>this.configure(e.detail||{}),this._toggleHandler=()=>
22this.engine.toggle(),this._requestStateHandler=()=>this.emitState(),window.addEventListener(Br,this._configureHandler),window.addEventListener(jr,this._toggleHandler),window.addEventListener($r,this._requestStateHandler),this.emitState()}configure(e){this.engine.setNowPlaying({stationTitle:e.title,title:e.currentTrack||"",artist:e.currentArtist||"",coverArtUrl:e.coverArtUrl||"",coverPending:e.coverPending===!0,defaultCoverUrl:e.defaultCoverUrl}),this.reveal.setConfig(e.metadataSync),this.reveal.setPending(e.pendingKey||null,e.pendingCueTitle||null),this.engine.setSource(e.streamUrl||"",e.streamType||"external"),this.emitState()}emitState(e){let i=e||this.engine.computeState();window.dispatchEvent(new CustomEvent(Sh,{detail:{state:i,streamUrl:this.engine.streamUrl,currentTrack:this.engine.trackTitle,currentArtist:this.engine.trackArtist,coverArtUrl:this.engine.coverArtUrl||this.engine.defaultCoverUrl}}))}dispatchReveal(e){window.dispatchEvent(new CustomEvent(Ch,{detail:{key:e}}))}cleanup(){window.removeEventListener(Br,this._configureHandler),window.removeEventListener(jr,this._toggleHandler),window.removeEventListener($r,this._requestStateHandler),this.reveal.cancel(),this.engine.destroy()}};function qr(){if(window.__globalAutoDJPlayer)return;let t=document.getElementById(kh);if(!t)return;let e=new ts(t);e.init(),window.__globalAutoDJPlayer=e}function _h(t,e="play-button-icon",i=""){switch(t){case"stop":return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="${e}"><path fill-rule="evenodd" d="M4.5 7.5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-9a3 3 0 0 1-3-3v-9Z" clip-rule="evenodd" /></svg>`;case"buffering":return`<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="${e} animate-spin"><path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" /></svg>`;default:return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="${e}${i}"><path fill-rule="evenodd" d="M4.5 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.573 0 3.286L7.28 19.99c-1.25.687-2.779-.217-2.779-1.643V5.653Z" clip-rule="evenodd" /></svg>`}}function Vr(t,e){let i=t.dataset.iconClass||"play-button-icon",n=t.dataset.iconClass?" ml-0.5":"";return _h(e,i,n)}var zr=new WeakMap;function Wr(t,e){let i=zr.get(t);i&&i.node===t.firstElementChild&&i.html===e||(t.innerHTML=e,zr.set(t,{node:t.firstElementChild,html:e}))}var we=class{constructor({root:e,onToggle:i}){this.root=e,this.onToggle=i,this.playButton=null,this._playButtonHandler=null}bind(e=this.root){this.root=e,this.playButton=e.querySelector('[data-player-control="play"]'),this.playButton&&(this._playButtonHandler=i=>{i.preventDefault(),this.onToggle()},this.playButton.addEventListener("click",this._playButtonHandler))}unbind(){this.playButton&&this._playButtonHandler&&this.playButton.removeEventListener("click",this._playButtonHandler),this._playButtonHandler=null}render(e){if(!this.playButton)return;let i,n,s;e==="playing"?(s="playing",i="stop",n="Stop"):e==="buffering"?(s="buffering",i="buffering",n="Loading..."):(s="stopped",i="play",n="Play"),this.playButton.dataset.state=s,this.playButton.setAttribute("aria-label",n);let r=this.playButton.querySelector("[data-player-icon]");r&&Wr(r,Vr(this.root,i))}};function Ah({engine:t,context:e,reducedMotion:i,optedIn:n}){return i?"reduced_motion":n?t?.audio?t.hls?e?e.state!=="running"?"context_suspended":null:"no_context":"not_mse":"no_audio":"not_opted_in"}function xh(t,e=2048,i=32){let n=t/e,s=e/2,r=[],o=Math.max(1,Math.floor(50/n));for(let a=0;a<i;a++){let l=50*Math.pow(280,(a+1)/i),h=Math.min(s,Math.max(o+1,Math.round(l/n)));r.push([o,h]),o=Math.min(s-1,h)}return r}var ri=class{constructor({engine:e,container:i,root:n=document.documentElement,win:s=window}){this.engine=e,this.container=i,this.root=n,this.win=s,this.bands=new Float32Array(32),this.raw=new Float32Array(32),this.live=!1,this.playing=!1,this.failed=!1,this.tappedAudio=null,this.analyser=null,this.bins=null,this.ranges=null,this.peaks=new Float32Array(32),this.floors=new Float32Array(32),this.silentSince=null,this.frame=null,this.reducedMotion=s.matchMedia?.("(prefers-reduced-motion: reduce)")||null,this._onReducedMotion=()=>this.sync(),this.reducedMotion?.addEventListener?.("change",this._onReducedMotion),this._onVisibility=()=>this.sync(),s.document.addEventListener("visibilitychange",this._onVisibility),this._onContextState=()=>this.sync(),this.watchedContext=null}update(e){this.playing=e==="playing",this.sync()}sync(){this.playing&&!this.reducedMotion?.matches&&this.tap(),this.playing&&this.tappedAudio&&this.watchedContext?.state==="suspended"&&this.watchedContext.resume?.()?.catch?.(()=>{}),this.shouldRun()?this.start():this.stop()}shouldRun(){return this.playing&&this.analyser!==null&&this.tappedAudio===this.engine.audio&&!this.reducedMotion?.matches&&this.win.document.visibilityState!=="hidden"}tap(){if(this.failed)return;let e=this.engine.audio;if(this.analyser&&this.tappedAudio===e)return;let i=this.engine.audioContext;if(this.watchContext(i),!Ah({engine:this.engine,context:i,reducedMotion:!!this.reducedMotion?.matches,optedIn:this.optedIn()}))try{let s=i.createMediaElementSource(e);s.connect(i.destination),this.engine.audioTapped=!0,this.tappedAudio=e;let r=i.createAnalyser();r.fftSize=2048,r.smoothingTimeConstant=.5,r.minDecibels=-85,r.maxDecibels=-20,s.connect(r),this.analyser=r,this.bins=new Uint8Array(r.frequencyBinCount),this.ranges=xh(i.sampleRate,2048)}catch(s){console.warn("[AudioLevels] Analyser unavailable, keeping decorative bars:",s),this.failed=!0,this.analyser=null}}optedIn(){return!!this.container?.querySelector?.("[data-levels]")}watchContext(e){!e||e===this.watchedContext||(this.watchedContext?.removeEventListener?.("statechange",this._onContextState),e.addEventListener?.("statechange",this._onContextState),this.watchedContext=e)}start(){this.frame===null&&(this.silentSince=null,this.frame=this.win.requestAnimationFrame(e=>this.tick(e)))}stop(){this.frame!==null&&(this.win.cancelAnimationFrame(this.frame),this.frame=null),this.bands.fill(0),this.setLive(!1)}tick(e){this.frame=null,this.sample(e),this.write(),this.shouldRun()?this.frame=this.win.requestAnimationFrame(i=>this.tick(i)):this.stop()}sample(e){this.analyser.getByteFrequencyData(this.bins);let i=0,n=this.raw;
22this.ranges.forEach(([s,r],o)=>{let a=0;for(let l=s;l<r;l++)a+=this.bins[l];n[o]=a/(r-s)/255,i=Math.max(i,n[o])}),i===0?(this.silentSince??=e,e-this.silentSince>=1500&&this.setLive(!1)):(this.silentSince=null,this.setLive(!0));for(let s=0;s<32;s++){let r=n[s];this.peaks[s]=Math.max(r,this.peaks[s]-.004),this.floors[s]=r<this.floors[s]?r:this.floors[s]+(r-this.floors[s])*.01;let o=Math.max(.12,this.peaks[s]-this.floors[s]),a=Math.min(1,(r-this.floors[s])/o)*(1-.3*s/31),l=a>this.bands[s]?.55:.18;this.bands[s]+=(a-this.bands[s])*l}}write(){if(!this.live)return;let e=this.root.style;for(let i=0;i<32;i++)e.setProperty(`--lv-${i}`,this.bands[i].toFixed(3))}setLive(e){if(this.live!==e)if(this.live=e,e)this.root.dataset.audioLevels="live";else{delete this.root.dataset.audioLevels;for(let i=0;i<32;i++)this.root.style.removeProperty(`--lv-${i}`)}}destroy(){this.playing=!1,this.stop(),this.reducedMotion?.removeEventListener?.("change",this._onReducedMotion),this.win.document.removeEventListener("visibilitychange",this._onVisibility),this.watchedContext?.removeEventListener?.("statechange",this._onContextState),this.watchedContext=null}};function Kr(t){return t?.closest?.("#player-container")?._playerBootstrap?.levels||null}var Ki=class{constructor(e){this.el=e,this.previewMode=e.dataset.previewMode==="true",this.autoplay=e.dataset.autoplay==="true",this.pushEvent=null,this.pendingRevealKey=null,this.engine=new be({persistVolume:!this.previewMode,onStateChange:i=>this.handleStateChange(i),onMetadata:i=>this.reveal.feedCue(i)}),this.reveal=new ye({onReveal:i=>this.handleReveal(i)}),this.controls=new we({root:e,onToggle:()=>this.engine.toggle()}),this.datasetVolume=parseInt(e.dataset.volume,10),this.engine.init({volume:Number.isNaN(this.datasetVolume)?80:this.datasetVolume}),this.levels=new ri({engine:this.engine,container:e}),this.refreshFromDataset(),this.bindUIElements(),this.renderControls(),this.renderMuteControl(),this.warmHlsChunk(),this.autoplay&&this.engine.streamUrl&&this.engine.play()}warmHlsChunk(){if(!zi(this.el.dataset.streamType))return;let e=()=>{Xn().catch(()=>{})};typeof requestIdleCallback=="function"?requestIdleCallback(e):setTimeout(e,2e3)}adopt(e){this.pushEvent=e;let i=this.pendingRevealKey;this.pendingRevealKey=null,this.refreshFromDataset(),this.unbindUIElements(),this.bindUIElements(),this.renderControls(),this.renderMuteControl(),this.pushEvent("player_state_changed",{state:this.engine.computeState()}),this.pendingRevealKey?this.pendingRevealKey=null:i&&this.pushEvent("stream_metadata_revealed",{key:i})}detach(){this.pushEvent=null}updated(){this.refreshFromDataset(),this.applyPreviewVolume(),this.unbindUIElements(),this.bindUIElements(),this.renderControls(),this.renderMuteControl()}destroy(){this.unbindUIElements(),this.levels.destroy(),this.reveal.cancel(),this.engine.destroy()}refreshFromDataset(){this.engine.setNowPlaying({stationTitle:this.el.dataset.title||"Live Radio",title:this.el.dataset.currentTrack||"",artist:this.el.dataset.currentArtist||"",coverArtUrl:this.el.dataset.coverArtUrl||"",defaultCoverUrl:this.el.dataset.defaultCoverUrl||"",coverPending:this.el.dataset.coverPending==="true"}),this.reveal.setConfig(this.el.dataset.metadataSync||""),this.reveal.setPending(this.el.dataset.pendingKey||null,this.el.dataset.pendingCueTitle||null),this.engine.setSource(this.el.dataset.streamUrl,this.el.dataset.streamType||"external")}applyPreviewVolume(){if(!this.previewMode)return;let e=parseInt(this.el.dataset.volume,10);Number.isNaN(e)||e===this.datasetVolume||(this.datasetVolume=e,this.engine.setVolume(e))}handleStateChange(e){this.renderControls(e),this.levels.update(e),this.pushEvent&&this.pushEvent("player_state_changed",{state:e})}handleReveal(e){this.pendingRevealKey=e,this.pushEvent&&this.pushEvent("stream_metadata_revealed",{key:e})}renderControls(e){this.controls.render(e||this.engine.computeState())}renderMuteControl(){if(!this.muteButton)return;let e=this.engine.isMuted,i=this.muteButton.querySelector('[data-mute-icon="off"]'),n=this.muteButton.querySelector('[data-mute-icon="on"]');i&&(i.hidden=e),n&&(n.hidden=!e),this.muteButton.setAttribute("aria-pressed",e),this.muteButton.setAttribute("aria-label",e?"Unmute":"Mute")}get playButton(){return this.controls.playButton}bindUIElements(){this.controls.bind(this.el),this.volumeSlider=this.el.querySelector('[data-player-control="volume"]'),this.volumeSlider&&!Fr()&&(this.volumeSlider.hidden=!0,this.volumeSlider=null),this.volumeSlider&&(this.volumeSlider.value=this.engine.volume,this._volumeSliderHandler=e=>{this.engine.setVolume(parseInt(e.target.value,10)),this.renderMuteControl()},this.volumeSlider.addEventListener("input",this._volumeSliderHandler)),this.muteButton=this.el.querySelector('[data-player-control="mute"]'),this.muteButton&&(this._muteButtonHandler=()=>{this.engine.toggleMute(),this.renderMuteControl()},this.muteButton.addEventListener("click",this._muteButtonHandler))}unbindUIElements(){this.controls.unbind(),this.volumeSlider&&this._volumeSliderHandler&&this.volumeSlider.removeEventListener("input",this._volumeSliderHandler),this.muteButton&&this._muteButtonHandler&&this.muteButton.removeEventListener("click",this._muteButtonHandler)}};function es(t){if(t._playerBootstrap)return t._playerBootstrap;let e=new Ki(t);return t._playerBootstrap=e,e}function Xr(t=document){t.querySelectorAll('#player-container[phx-hook="PlayerHook"]').forEach(e
22=>{try{es(e)}catch(i){console.error("[bootstrapPlayers] Failed to boot player:",i)}})}var Th="autodj:player:configure",Mh="autodj:player:request-state",Ph="autodj:player:toggle",Gr="autodj:player:state",Jr="autodj:player:reveal",Ih={mounted(){this.controls=new we({root:this.el,onToggle:()=>window.dispatchEvent(new CustomEvent(Ph))}),this.bindUIElements(),this._stateHandler=t=>this.applyState(t.detail||{}),this._revealHandler=t=>this.handleReveal(t.detail||{}),window.addEventListener(Gr,this._stateHandler),window.addEventListener(Jr,this._revealHandler),this.syncPlayerConfig(),this.requestPlayerState()},updated(){this.unbindUIElements(),this.bindUIElements(),this.syncPlayerConfig(),this.requestPlayerState()},destroyed(){this.unbindUIElements(),this._stateHandler&&(window.removeEventListener(Gr,this._stateHandler),this._stateHandler=null),this._revealHandler&&(window.removeEventListener(Jr,this._revealHandler),this._revealHandler=null)},bindUIElements(){this.controls.bind(this.el),this.playButton=this.controls.playButton},unbindUIElements(){this.controls.unbind()},syncPlayerConfig(){window.dispatchEvent(new CustomEvent(Th,{detail:{streamUrl:this.el.dataset.streamUrl||"",streamType:this.el.dataset.streamType||"external",title:this.el.dataset.title||"Station",currentTrack:this.el.dataset.currentTrack||"",currentArtist:this.el.dataset.currentArtist||"",coverArtUrl:this.el.dataset.coverArtUrl||"",coverPending:this.el.dataset.coverPending==="true",defaultCoverUrl:this.el.dataset.defaultCoverUrl||"",metadataSync:this.el.dataset.metadataSync||"",pendingKey:this.el.dataset.pendingKey||null,pendingCueTitle:this.el.dataset.pendingCueTitle||null}}))},requestPlayerState(){window.dispatchEvent(new CustomEvent(Mh))},applyState(t){if(!this.playButton)return;let e=t.state||"stopped";this.controls.render(e),this.lastPushedState!==e&&(this.lastPushedState=e,this.pushEvent("autodj_mini_player_state_changed",{state:e}))},handleReveal({key:t}){typeof t=="string"&&t!==""&&this.pushEvent("autodj_mini_player_metadata_revealed",{key:t})}},Yr=Ih;var Dh={animationClasses:["transition-opacity","duration-300","ease-out"],mounted(){this.el.dataset.isStatic!=="true"&&this.setup()},updated(){let{el:t}=this,e=t.querySelector(".progress");if(t.classList.remove("hidden"),e){let i=t.dataset.timerLength,n=i-this.time-100;e.style.transitionDuration="0ms",e.style.width=`${this.time/i*100}%`,e.style.transitionDuration=`${n}ms`,setTimeout(()=>{e.style.width="100%"},100)}},destroyed(){this.stop()},setup(){let{el:t}=this,e=t.querySelector(".progress"),{timerLength:i}=t.dataset,n=t.dataset.clearServerOnTimeout==="true";this.handleClick=this.handleClick.bind(this),this.handleClearFlash=this.handleClearFlash.bind(this),this.stop=this.stop.bind(this),t.addEventListener("click",this.handleClick),t.addEventListener("clear-flash",this.handleClearFlash),e&&(setTimeout(()=>{e.style.width="100%",e.style.transitionDuration=`${i}ms`},100),this.timer=setTimeout(()=>this.stop({clearServer:n}),i),this.time=0,this.interval=setInterval(()=>{this.time+=100,this.time>=i&&clearInterval(this.interval)},100))},handleClick(){this.stop()},handleClearFlash(){this.stop()},stop({clearServer:t=!1}={}){if(this.stopped)return;this.stopped=!0;let{el:e}=this,i=e.dataset.type;e.removeEventListener("click",this.handleClick),e.removeEventListener("clear-flash",this.handleClearFlash),clearTimeout(this.timer),clearInterval(this.interval),t&&i&&this.pushEvent("lv:clear-flash",{key:i}),e.classList.add(...this.animationClasses),e.classList.add("opacity-0"),setTimeout(()=>{e.remove()},300)}},Zr=Dh;var Lh={mounted(){this.el.addEventListener("click",t=>{t.preventDefault();let e=this.el.dataset.content;if(!e){console.log("[Clipboard] No content to copy");return}(async()=>{try{await navigator.clipboard.writeText(e);let n=this.el.querySelector('span[class*="hero-"]');if(n){let s=n.className;n.className=n.className.replace(/hero-[^\s]+/,"hero-check"),n.classList.add("text-green-500"),setTimeout(()=>{n.className=s},2e3)}this.el.dataset.notify&&this.pushEvent("clipboard_copy",{})}catch{console.warn("[Clipboard] Modern API failed, trying fallback");let s=document.createElement("textarea");s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select();try{document.execCommand("copy"),document.body.removeChild(s);let r=this.el.querySelector('span[class*="hero-"]');if(r){let o=r.className;r.className=r.className.replace(/hero-[^\s]+/,"hero-check"),r.classList.add("text-green-500"),setTimeout(()=>{r.className=o},2e3)}this.el.dataset.notify&&this.pushEvent("clipboard_copy",{})}catch(r){console.error("[Clipboard] All copy methods failed:",r),document.body.removeChild(s)}}})()})}},Qr=Lh;var Rh={reviveJsFunction(t,e){let i=t?.[e];i&&typeof i=="object"&&i.__type==="js_function"&&(t[e]=new Function("return "+i.value)())},parseConfig(t){let e=JSON.parse(t);return this.reviveJsFunction(e.tooltip,"formatter"),this.reviveJsFunction(e.tooltip,"valueFormatter"),this.reviveJsFunction(e.xAxis?.axisLabel,"formatter"),e},mounted(){this.isDestroyed=!1,this.ready=import("./echarts_setup-2TH2QSQZ.js").then(({default:t})=>{this.isDestroyed||(this.chart=t.init(this.el),this.chart.setOption(this.parseConfig(this.el.dataset.config)),this.resizeObserver=new ResizeObserver(()=>{this.chart.resize()}),this.resizeObserver.observe(this.el))}).catch(t=>{console.error("[ECharts] chart chunk failed to load;
22 leaving chart empty",t)}),this.handleEvent("update-chart",({config:t,id:e})=>{e&&e!==this.el.id||this.ready.then(()=>{this.chart&&this.chart.setOption(this.parseConfig(t),{notMerge:!0})})})},updated(){this.ready?.then(()=>{this.chart&&this.chart.setOption(this.parseConfig(this.el.dataset.config),{notMerge:!0})})},destroyed(){this.isDestroyed=!0,this.ready?.then(()=>{this.resizeObserver&&this.resizeObserver.disconnect(),this.chart&&this.chart.dispose()})}},to=Rh;var eo=!1;async function Oh(){let[{default:t},{default:e}]=await Promise.all([import("./echarts_setup-2TH2QSQZ.js"),import("./world-5IDVMJHU.js")]);return eo||(t.registerMap("world",e),eo=!0),t}var Hh=Math.log(1001),Fh=400;function io(t,e=8,i=50){if(t<=0)return e;let n=Math.log(t+1),s=Math.min(n/Hh,1);return e+s*(i-e)}function Nh(t){if(t<=0)return[];let e=Math.min(t,1e3),i=t>1e3,n=[];return e>=1&&n.push({value:1,label:"1"}),e>=10&&n.push({value:10,label:"10"}),e>=100&&n.push({value:100,label:"100"}),e>=1e3&&n.push({value:1e3,label:i?"1000+":"1.0k"}),n}var Uh={mounted(){this.isDestroyed=!1,this.ready=Oh().then(t=>{this.isDestroyed||(this.chart=t.init(this.el),this.chart.setOption({backgroundColor:"transparent",animation:!0,animationDuration:300,geo:{map:"world",roam:"move",zoom:1.2,center:[0,20],scaleLimit:{min:1,max:8},itemStyle:{areaColor:"#e7e8ea",borderColor:"#d1d5db"},emphasis:{itemStyle:{areaColor:"#d1d5db"}}},series:[{type:"scatter",coordinateSystem:"geo",data:[],symbolSize:function(e){return io(e[2])},itemStyle:{color:"rgba(59, 130, 246, 0.7)",borderColor:"#3b82f6",borderWidth:1},emphasis:{itemStyle:{color:"rgba(59, 130, 246, 0.9)"}},zlevel:1}],tooltip:{trigger:"item",formatter:e=>{let i=e.data;if(!i)return"";let n=i.value[2];return`<div class="font-medium">${i.country||"Unknown"}</div> 23 <div class="text-blue-600">${n} listener${n!==1?"s":""}</div>`},backgroundColor:"rgba(255, 255, 255, 0.95)",borderColor:"#e5e7eb",borderWidth:1,textStyle:{color:"#374151",fontSize:12},padding:[8,12]},graphic:[]}),this.resizeObserver=new ResizeObserver(()=>{if(!(this.isDestroyed||!this.chart||this.chart.isDisposed())&&(this.chart.resize(),this.lastMaxCount!==void 0)){let e=this.generateLegendGraphics(this.lastMaxCount);this.chart.setOption({graphic:e})}}),this.resizeObserver.observe(this.el))}).catch(t=>{console.error("[ListenerMap] map chunk failed to load; leaving map empty",t)}),this.handleEvent("update_listeners",({bubbles:t})=>{this.ready.then(()=>{if(!this.chart)return;if(!t||!Array.isArray(t)){this.chart.setOption({series:[{data:[]}]});return}let e=t.filter(s=>s.lat!=null&&s.lon!=null&&s.count>0).map(s=>({name:s.country_code,value:[s.lon,s.lat,s.count],country:s.country,countryCode:s.country_code})),i=e.reduce((s,r)=>Math.max(s,r.value[2]),0);this.lastMaxCount=i;let n=this.generateLegendGraphics(i);this.chart.setOption({series:[{data:e}],graphic:n})})})},generateLegendGraphics(t){if(t<=0)return[];if(this.el.offsetWidth<Fh)return[];let i=Nh(t);if(i.length===0)return[];let n=[],s=20,r=20,o=45;return n.push({type:"text",left:s,bottom:r+i.length*o+10,style:{text:"Listeners",font:"11px sans-serif",fill:"#6b7280"}}),i.forEach((a,l)=>{let h=io(a.value),c=r+(i.length-1-l)*o;n.push({type:"circle",left:s+15,bottom:c+8,shape:{r:h/2},style:{fill:"rgba(59, 130, 246, 0.5)",stroke:"#3b82f6",lineWidth:1}}),n.push({type:"text",left:s+35,bottom:c+4,style:{text:a.label,font:"11px sans-serif",fill:"#374151"}})}),n},destroyed(){this.isDestroyed=!0,this.resizeObserver&&this.resizeObserver.disconnect(),this.ready?.then(()=>{this.chart&&this.chart.dispose()})}},no=Uh;var Bh="fill-zinc-300 dark:fill-zinc-700",$h="fill-green-600 dark:fill-green-500",jh={mounted(){this.render()},updated(){this.render()},async render(){let{default:t}=await import("./world_dots-6SYABRNT.js");if(!this.el.isConnected)return;let e=new Set;for(let s of JSON.parse(this.el.dataset.countries||"[]"))for(let r of t.countries[s]||[])e.add(r);let i="http://www.w3.org/2000/svg",n=document.createElementNS(i,"svg");n.setAttribute("viewBox",`0 0 ${t.cols} ${t.rows}`),n.setAttribute("preserveAspectRatio","xMidYMid meet"),n.setAttribute("aria-hidden","true"),n.setAttribute("class","h-full w-full"),t.dots.forEac
23h(([s,r],o)=>{let a=document.createElementNS(i,"circle");a.setAttribute("cx",s+.5),a.setAttribute("cy",r+.5),a.setAttribute("r",e.has(o)?.48:.3),a.setAttribute("class",e.has(o)?$h:Bh),n.appendChild(a)}),this.el.replaceChildren(n)}},so=jh;var qh={mounted(){this.formatTime(),this.el.dataset.format==="relative"&&(this.interval=setInterval(()=>this.formatTime(),6e4))},updated(){this.formatTime()},destroyed(){this.interval&&clearInterval(this.interval)},formatTime(){let t=parseInt(this.el.dataset.timestamp,10);if(isNaN(t))return;let e=this.el.dataset.format||"short",i=new Date(t*1e3);this.el.textContent=this.formatDate(i,e),this.el.title=i.toLocaleString("en-US",{hourCycle:"h23"})},formatDate(t,e){let i="en-US";switch(e){case"short":return new Intl.DateTimeFormat(i,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(t);case"long":return new Intl.DateTimeFormat(i,{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(t);case"time":return new Intl.DateTimeFormat(i,{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(t);case"date":return new Intl.DateTimeFormat(i,{year:"numeric",month:"short",day:"numeric"}).format(t);case"relative":return this.formatRelative(t);default:return t.toLocaleString(i,{hourCycle:"h23"})}},formatRelative(t){let i=Math.floor((new Date-t)/1e3);if(i<60)return"just now";if(i<3600){let n=Math.floor(i/60);return`${n} minute${n===1?"":"s"} ago`}else if(i<86400){let n=Math.floor(i/3600);return`${n} hour${n===1?"":"s"} ago`}else{let n=Math.floor(i/86400);return`${n} day${n===1?"":"s"} ago`}}},ro=qh;var zh={SCROLL_SPEED:30,MIN_DURATION:6,MAX_DURATION:40,MIN_OVERFLOW:24,mounted(){if(this.track=this.el.querySelector(".marquee-title-track"),this.firstText=this.el.querySelector(".marquee-title-text"),!this.track||!this.firstText){console.warn("[MarqueeHook] Missing required elements");return}requestAnimationFrame(()=>{this.checkOverflow()}),this.resizeObserver=new ResizeObserver(()=>{this.checkOverflow()}),this.resizeObserver.observe(this.el),this.mutationObserver=new MutationObserver(()=>{requestAnimationFrame(()=>this.checkOverflow())}),this.mutationObserver.observe(this.firstText,{characterData:!0,childList:!0,subtree:!0}),setTimeout(()=>this.checkOverflow(),500)},updated(){requestAnimationFrame(()=>this.checkOverflow())},destroyed(){this.resizeObserver&&this.resizeObserver.disconnect(),this.mutationObserver&&this.mutationObserver.disconnect()},checkOverflow(){if(!this.track||!this.firstText)return;this.el.dataset.marquee==="on"&&(this.el.removeAttribute("data-marquee"),this.el.style.removeProperty("--marquee-distance"),this.el.style.removeProperty("--marquee-duration"),this.el.offsetWidth);let e=this.el.clientWidth,i=this.firstText.scrollWidth,n=parseFloat(getComputedStyle(this.el).getPropertyValue("--marquee-gap"))||0;if(i-e>this.MIN_OVERFLOW){let o=i+n,a=o/this.SCROLL_SPEED;a=Math.max(this.MIN_DURATION,Math.min(this.MAX_DURATION,a)),this.el.style.setProperty("--marquee-distance",`-${o}px`),this.el.style.setProperty("--marquee-duration",`${a}s`),this.el.setAttribute("data-marquee","on")}else this.el.removeAttribute("data-marquee"),this.el.style.removeProperty("--marquee-distance"),this.el.style.removeProperty("--marquee-duration")}},oo=zh;var Vh={mounted(){this.trackKey=this.el.dataset.trackKey,this.reducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)"),this.announcing=!1,this.hovered=!1;let t=this.el.querySelector(".isl")||this.el;t.addEventListener("pointerenter",e=>{e.pointerType==="mouse"&&(this.hovered=!0,this.sync())}),t.addEventListener("pointerleave",()=>{this.hovered=!1,this.sync()}),this.announce()},updated(){this.el.dataset.trackKey!==this.trackKey&&(this.trackKey=this.el.dataset.trackKey,this.announce())},destroyed(){clearTimeout(this.closeTimer)},announce(){this.reducedMotion.matches||(clearTimeout(this.closeTimer),this.announcing=!0,this.sync(),this.closeTimer=setTimeout(()=>{this.announcing=!1,this.sync()},4500))},sync(){this.announcing||this.hovered?this.js().setAttribute(this.el,"data-open",""):this.js().removeAttribute(this.el,"data-open")}},ao=Vh;var oi=18,lo=9,Wh=13,ho=14,Kh=1.6,Xh=1.4,is=8,ai=[1,3,6,10,15,21,28],co="rgba(255,255,255,.055)",Gh={A:[14,17,17,31,17,17,17],B:[30,17,17,30,17,17,30],C:[14,17,16,16,16,17,14],D:[28,18,17,17,17,18,28],E:[31,16,16,30,16,16,31],F:[31,16,16,30,16,16,16],G:[
2314,17,16,23,17,17,15],H:[17,17,17,31,17,17,17],I:[14,4,4,4,4,4,14],J:[7,2,2,2,2,18,12],K:[17,18,20,24,20,18,17],L:[16,16,16,16,16,16,31],M:[17,27,21,21,17,17,17],N:[17,17,25,21,19,17,17],O:[14,17,17,17,17,17,14],P:[30,17,17,30,16,16,16],Q:[14,17,17,17,21,18,13],R:[30,17,17,30,20,18,17],S:[15,16,16,14,1,1,30],T:[31,4,4,4,4,4,4],U:[17,17,17,17,17,17,14],V:[17,17,17,17,17,10,4],W:[17,17,17,21,21,21,10],X:[17,17,10,4,10,17,17],Y:[17,17,17,10,4,4,4],Z:[31,1,2,4,8,16,31],0:[14,17,19,21,25,17,14],1:[4,12,4,4,4,4,14],2:[14,17,1,2,4,8,31],3:[31,2,4,2,1,17,14],4:[2,6,10,18,31,2,2],5:[31,16,30,1,1,17,14],6:[6,8,16,30,17,17,14],7:[31,1,2,4,8,8,8],8:[14,17,17,14,17,17,14],9:[14,17,17,15,1,2,12],".":[0,0,0,0,0,12,12],",":[0,0,0,0,12,4,8],"'":[12,4,8,0,0,0,0],"!":[4,4,4,4,4,0,4],"?":[14,17,1,2,4,0,4],"-":[0,0,0,31,0,0,0],"&":[12,18,20,8,21,18,13],"(":[2,4,8,8,8,4,2],")":[8,4,2,2,2,4,8],"[":[14,8,8,8,8,8,14],"]":[14,2,2,2,2,2,14],"/":[0,1,2,4,8,16,0],":":[0,12,12,0,12,12,0],"\xB7":[0,0,0,12,12,0,0],"+":[0,4,4,31,4,4,0],"#":[10,10,31,10,31,10,10],'"':[10,10,0,0,0,0,0]},Wt=null,ns=new Map;function Jh(t){if(ns.has(t))return ns.get(t);Wt||=document.createElement("canvas").getContext("2d",{willReadFrequently:!0}),Wt.canvas.width=16,Wt.canvas.height=8,Wt.font="bold 8px sans-serif",Wt.textBaseline="bottom";let e=Math.max(1,Math.min(8,Math.ceil(Wt.measureText(t).width)));Wt.clearRect(0,0,16,8),Wt.fillText(t,0,8);let i=Wt.getImageData(0,0,e,8).data,n=[];for(let s=0;s<e;s++){let r=0;for(let o=0;o<7;o++)i[((o+1)*e+s)*4+3]>110&&(r|=1<<o);n.push(r)}return ns.set(t,n),n}function Yh(t){let e=[],i=t.normalize("NFD").replace(/[Ì-ͯ]/g,"").toUpperCase();for(let n of i){if(/\s/.test(n)){e.push(0,0,0);continue}let s=Gh[n];if(s)for(let r=0;r<5;r++){let o=0;for(let a=0;a<7;a++)s[a]&16>>r&&(o|=1<<a);e.push(o)}else e.push(...Jh(n));e.push(0)}return e}function Zh(t,e,i){let n=Math.exp(-(t%.5/.5)*6);ai.forEach((s,r)=>{let o=s/31,a=.5+.5*Math.sin(t*(2.1+s*.53)+s*1.7)*Math.sin(t*(1.3+s*.21)+s*.9),l=(.75*Math.pow(1-o,.8)+.15)*(.35+.45*a)+(s<8?n*.45*(1-o*3):n*.1);l=Math.min(1,Math.max(0,l));let h=l>e[r]?.5:.12;e[r]+=(l-e[r])*Math.min(1,h*i*60)})}function uo(t){let e=window.devicePixelRatio||1,i=t.clientWidth,n=t.clientHeight;return(t._w!==i||t._h!==n||t._dpr!==e)&&(t.width=Math.max(1,Math.round(i*e)),t.height=Math.max(1,Math.round(n*e)),t._w=i,t._h=n,t._dpr=e,t.getContext("2d").setTransform(e,0,0,e,0,0)),t.getContext("2d")}function Xi(t,e,i,n){t.moveTo(e+n,i),t.arc(e,i,n,0,Math.PI*2)}var Qh={mounted(){this.screen=this.makeCanvas(".dm-screen"),this.meter=this.makeCanvas(".dm-meter"),this.reducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)"),this.lines=[],this.cols=0,this.noise=null,this.dissolve=null,this.levels=new Float32Array(ai.length),this.peaks=new Float32Array(ai.length),this.gain=0,this.clock=0,this.visible=!0,this.readColor(),this.setLines(!1),this.resize=new ResizeObserver(()=>this.redraw()),this.resize.observe(this.el),this.onScreen=new IntersectionObserver(([t])=>{this.visible=t.isIntersecting,this.redraw()}),this.onScreen.observe(this.el),this.redraw()},updated(){this.readColor(),this.texts().join(` 24`)!==this.lines.map(e=>e.text).join(` 25`)&&this.setLines(!0),this.redraw()},destroyed(){cancelAnimationFrame(this.frame),this.frame=null,this.resize?.disconnect(),this.onScreen?.disconnect()},makeCanvas(t){let e=this.el.querySelector(t),i=document.createElement("canvas");return e.replaceChildren(i),i},texts(){return[this.el.dataset.line1||"",this.el.dataset.line2||""]},readColor(){this.led=getComputedStyle(this.el).getPropertyValue("--dm-led").trim()||"#FFB020"},animated(){return!this.reducedMotion.matches},setLines(t){let e=null;if(t&&this.animated()&&this.cols){e=new Uint8Array(oi*this.cols);for(let i=0;i<oi;i++)for(let n=0;n<this.cols;n++)e[i*this.cols+n]=this.lit(i,n)}this.lines=this.texts().map(i=>({text:i,cols:Yh(i),offset:0,hold:Kh})),this.dissolve=e?{t:0,snapshot:e,cols:this.cols}:null},lit(t,e){let i=this.lines[t<lo?0:1];if(!i)return 0;let n=t%lo-1;if(n<0||n>6)return 0;let s=i.cols.length,r=s<=this.cols-2?e-1:Math.floor(e+i.offset)%(s+ho);return r>=0&&r<s?i.cols[r]>>n&1:0},redraw(){this.animated()&&this.visible?this.frame||(this.last=performance.now(),this.frame=requestAnimationFrame(t=>this.tick(t))):(cancelAnimationFrame(this.frame),this.frame=null,this.draw(0))},tick(t){let e=Math.min(.1,(t-this.last)/1e3);this.last=t,this.draw(e),this.frame=this.animated()&&this.visible?requestAnimationFrame(i=>this.tick(i)):null},draw(t){this.clock+=t,this.drawScreen(t),this.drawMeter(t)},drawScreen(t){let e=this.screen,i=uo(e),n=e._h/oi,s=Math.max(1,Math.floor(e._w/n));s!==this.cols&&(this.cols=s,this.noise=Float32Array.from({length:oi*s},()=>Math.random()));let r=1;if(this.dissolve&&(this.dissolve.t+=t,r=this.dissolve.t/Xh,r>=1&&(this.dissolve=null)),!this.dissolve&&this.animated())for(let m of this.lines)m.cols.length<=this.cols-2||(m.hold>0?m.hold-=t:m.offset=(m.offset+Wh*t)%(m.cols.length+ho));let o=(e._w-s*n)/2,a=n*.36,l=new Path2D,h=new Path2D,c=new Path2D,d=this.dissolve;for(let m=0;m<oi;m++)for(let p=0;p<s;p++){let u=m*s+p,v;d?v=r<.5?d.cols===s&&d.snapshot[u]&&this.noise[u]>r*2:this.lit(m,p)&&this.noise[u]<(r-.5)*2:v=this.lit(m,p);let y=o+p*n+n/2,M=m*n+n/2;v?(Xi(h,y,M,a*1.7),Xi(c,y,M,a)):Xi(l,y,M,a)}i.clearRect(0,0,e._w,e._h),i.fillStyle=co,i.fill(l),i.fillStyle=this.led,i.globalAlpha=.2,i.fill(h),i.globalAlpha=1,i.fill(c)},drawMeter(t){let e=this.meter,i=uo(e),n=this.el.dataset.state==="playing"&&this.animated();this.gain+=((n?1:0)-this.gain)*Math.min(1,t*5);let s=Kr(this.el);s?.live?ai.forEach((c,d)=>this.levels[d]=s.bands[c]):Zh(this.clock,this.levels,t);let r=e._h/is,o=r*.36,a=new Path2D,l=new Path2D,h=new Path2D;ai.forEach((c,d)=>{let m=Math.round(this.levels[d]*this.gain*is);this.peaks[d]=Math.max(this.peaks[d]-t*4,m);let p=Math.round(this.peaks[d]);for(let u=0;u<is;u++){let v=u<m?l:u===p-1&&p>m?h:a;Xi(v,d*r+r/2,e._h-(u*r+r/2),o)}}),i.clearRect(0,0,e._w,e._h),i.fillStyle=co,i.fill(a),i.fillStyle=this.led,i.fill(l),i.globalAlpha=.6,i.fill(h),i.globalAlpha=1}},fo=Qh;var tc={mounted(){this.previewMode=this.el.dataset.previewMode==="true",this.studioOrigin=this.el.dataset.studioOrigin||null,this.ownsBootstrap=!this.el._playerBootstrap,this.bootstrap=es(this.el),this.bootstrap.adopt((t,e)=>this.pushEvent(t,e)),this.previewMode&&(this.setupPreviewMessageListener(),this.announcePreviewReady())},updated(){this.bootstrap.updated()},disconnected(){console.debug("[PlayerHook] LiveView disconnected; audio continues, reconnecting")},reconnected(){this.bootstrap.renderControls(),this.bootstrap.renderMuteControl(),this.pushEvent("player_state_changed",{state:this.bootstrap.engine.computeState()}),this.previewMode&&this.announcePreviewReady()},destroyed(){this.cleanupPreviewMessageListener(),this.bootstrap.detach(),(this.ownsBootstrap||!this.el.
25isConnected)&&(this.bootstrap.destroy(),this.el._playerBootstrap=null)},setupPreviewMessageListener(){this.previewMode&&(this._previewMessageHandler=t=>this.handlePreviewMessage(t),window.addEventListener("message",this._previewMessageHandler))},cleanupPreviewMessageListener(){this._previewMessageHandler&&(window.removeEventListener("message",this._previewMessageHandler),this._previewMessageHandler=null)},announcePreviewReady(){!this.studioOrigin||!window.parent||window.parent===window||window.parent.postMessage({type:"preview_ready"},this.studioOrigin)},handlePreviewMessage(t){if(!this.studioOrigin||t.origin!==this.studioOrigin){console.warn("[PlayerHook] Rejected message: missing or mismatched origin",t.origin);return}let e=t.data;!e||e.type!=="preview_settings"||this.pushEvent("apply_preview_settings",e.settings)}},po=tc;var ec={iframe:null,embedOrigin:null,mounted(){if(this.embedOrigin=this.el.dataset.embedOrigin,!this.embedOrigin){console.warn("[PreviewSenderHook] Missing data-embed-origin attribute");return}this.acquireIframe(),this.handleEvent("preview_update",t=>{this.sendPreviewSettings(t)}),this._readyHandler=t=>this.handlePreviewReady(t),window.addEventListener("message",this._readyHandler),console.debug("[PreviewSenderHook] Mounted, target origin:",this.embedOrigin)},updated(){this.acquireIframe()},destroyed(){this._readyHandler&&(window.removeEventListener("message",this._readyHandler),this._readyHandler=null),this.iframe=null},handlePreviewReady(t){t.origin!==this.embedOrigin||t.source!==this.iframe?.contentWindow||t.data?.type==="preview_ready"&&this.pushEvent("preview_ready",{})},acquireIframe(){this.iframe=this.el.querySelector("#player-preview-iframe"),this.iframe||console.warn("[PreviewSenderHook] Could not find #player-preview-iframe")},sendPreviewSettings(t){if(!this.iframe||!this.iframe.contentWindow){console.warn("[PreviewSenderHook] No iframe available");return}if(!this.embedOrigin){console.warn("[PreviewSenderHook] No embed origin configured");return}let e={type:"preview_settings",settings:t};try{this.iframe.contentWindow.postMessage(e,this.embedOrigin)}catch(i){console.error("[PreviewSenderHook] Failed to post message:",i)}}},mo=ec;var ic={mounted(){this.handleEvent("print-invoice",()=>{window.print()})}},go=ic;var nc={mounted(){this.onClick=t=>{t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation?.();let e=t.shiftKey?"range":(t.metaKey||t.ctrlKey,"toggle");this.pushEvent("toggle_event_selection",{id:this.el.dataset.eventId,mode:e})},this.el.addEventListener("click",this.onClick,!0)},destroyed(){this.el.removeEventListener("click",this.onClick,!0)}},vo=nc;var bo="[data-grid-nav='true']";var sc=t=>t?!!t.closest("input, textarea, select, [contenteditable='true']"):!1,it=t=>{let e=Number.parseInt(t,10);return Number.isNaN(e)?null:e},wo=t=>t instanceof HTMLSelectElement,rc=t=>t instanceof HTMLInputElement&&["text","search","url","tel","password","email"].includes(t.type)||t instanceof HTMLTextAreaElement,yo=(t,e)=>{if(wo(t))return!1;if(!rc(t))return!0;let{selectionStart:i,selectionEnd:n,value:s}=t;return typeof i!="number"||typeof n!="number"||i!==n?!1:e==="ArrowLeft"?i===0:e==="ArrowRight"?n===s.length:!1},ss=t=>{t instanceof HTMLInputElement&&typeof t.select=="function"&&!["date","time"].includes(t.type)&&t.select(),t instanceof HTMLTextAreaElement&&typeof t.select=="function"&&t.select()},oc={mounted(){this.pendingFocus=null,this.dirtyForms=new Set,this.onInput=t=>{let e=t.target.closest("form[data-grid-autosave='true']");e&&this.el.contains(e)&&this.dirtyForms.add(e.id)},this.onFocusOut=t=>{let e=t.target.closest("form[data-grid-autosave='true']");!e||!this.el.contains(e)||t.relatedTarget&&e.contains(t.relatedTarget)||this.dirtyForms.has(e.id)&&(this.dirtyForms.delete(e.id),e.requestSubmit())},this.onPaste=t=>{if(sc(t.target))return;let e=t.clipboardData?.getData("text/plain")?.trim();if(!e)return;t.preventDefault();let i=e.split(/\r\n|\r|\n/).filter(n=>n.trim()!=="").length;if(i>201){window.alert(`Paste up to 200 rows at a time. You pasted about ${i}. Split the import into smaller batches.`);return}this.pushEvent("schedule_grid_paste",{text:e})},this.onKeyDown=t=>{let e=t.target.closest(bo);if(!(!e||!this.el.contains(e)||t.defaultPrevented||t.isComposing)&&!(t.metaKey||t.ctrlKey||t.altKey)&&!(wo(e)&&(t.key==="ArrowUp"||t.key==="ArrowDown")))switch(t.key){case"Enter":this.handleEnter(t,e);break;case"Tab":this.handleTab(t,e);break;case"ArrowUp":this.handleArrowMove(t,e,-1,0);break;case"ArrowDown":this.handleArrowMove(t,e,1,0);break;case"ArrowLeft":yo(e,t.key)&&this.handleArrowMove(t,e,0,-1);break;case"ArrowRight":yo(e,t.key)&&this.handleArrowMove(t,e,0,1);break;default:break}},this.el.addEventListener("paste",this.onPaste),this.el.addEventListener("keydown",this.onKeyDown),this.el.addEventListener("input",this.onInput),this.el.addEventListener("focusout",this.onFocusOut)},updated(){this.restorePendingFocus()},destroyed(){this.el.removeEventListener("paste",this.onPaste),this.el.removeEventListener("keydown",this.onKeyDown),this.el.removeEventListener("input",this.onInput),this.el.removeEventListener("focusout",this.onFocusOut)},handleEnter(t,e){t.preventDefault();
25let i=it(e.dataset.gridRowIndex),n=it(e.dataset.gridCol);this.pendingFocus={rowIndex:(i??0)+(t.shiftKey?-1:1),colIndex:n},e.form&&this.dirtyForms?.delete(e.form.id),e.form?.requestSubmit()},handleTab(t,e){let i=it(e.dataset.gridRowIndex),n=this.rowFields(i);if(n.length===0||(t.shiftKey?n[0]:n[n.length-1])!==e)return;if(t.preventDefault(),!t.shiftKey&&this.isLastRow(i)){this.commitDirty(e.form),this.pendingFocus={rowIndex:(i??0)+1,colIndex:0,createIfMissing:!0},this.pushEvent("add_grid_row",{});return}let r=(i??0)+(t.shiftKey?-1:1),o=it((t.shiftKey?n[n.length-1]:n[0]).dataset.gridCol);this.pendingFocus={rowIndex:r,colIndex:o,rowDirection:t.shiftKey?-1:1},e.form&&this.dirtyForms?.delete(e.form.id),e.form?.requestSubmit()},isLastRow(t){let e=this.fields().map(i=>it(i.dataset.gridRowIndex)).filter(i=>i!==null);return e.length>0&&t===Math.max(...e)},commitDirty(t){t&&this.dirtyForms?.has(t.id)&&(this.dirtyForms.delete(t.id),t.requestSubmit())},handleArrowMove(t,e,i,n){t.preventDefault();let s=it(e.dataset.gridRowIndex),r=it(e.dataset.gridCol),o=i===0?this.resolveHorizontalTarget(s??0,r??0,n):this.resolveTarget({rowIndex:(s??0)+i,colIndex:r??0,rowDirection:i});o&&(o.focus(),ss(o))},fields(){return Array.from(this.el.querySelectorAll(bo)).filter(t=>!t.disabled)},rowFields(t){return this.fields().filter(e=>
25it(e.dataset.gridRowIndex)===t).sort((e,i)=>it(e.dataset.gridCol)-it(i.dataset.gridCol))},resolveHorizontalTarget(t,e,i){let n=this.rowFields(t),s=n.findIndex(o=>it(o.dataset.gridCol)===e),r=n[s+i];return r||this.resolveTarget({rowIndex:t+(i>0?1:-1),colIndex:i>0?0:Number.MAX_SAFE_INTEGER,rowDirection:i>0?1:-1})},resolveTarget({rowIndex:t,colIndex:e,rowDirection:i=1}){let n=this.fields().find(a=>it(a.dataset.gridRowIndex)===t&&it(a.dataset.gridCol)===e);if(n)return n;let s=[...new Set(this.fields().map(a=>it(a.dataset.gridRowIndex)).filter(a=>a!==null))].sort((a,l)=>a-l);if(s.length===0)return null;let r=i>=0?s:[...s].reverse();for(let a of r){if(i>=0&&a<t||i<0&&a>t)continue;let l=this.rowFields(a),h=l.find(c=>it(c.dataset.gridCol)===e);if(h)return h;if(l.length>0)return i>=0?l[0]:l[l.length-1]}let o=i>=0?[...s].reverse():s;for(let a of o){let l=this.rowFields(a);if(l.length>0)return i>=0?l[l.length-1]:l[0]}return null},restorePendingFocus(){if(!this.pendingFocus)return;let t=this.pendingFocus;requestAnimationFrame(()=>{if(t.createIfMissing){let i=this.rowFields(t.rowIndex);if(i.length===0)return;let n=i.find(s=>it(s.dataset.gridCol)===t.colIndex)||i[0];n.focus(),ss(n),this.pendingFocus=null;return}let e=this.resolveTarget(t);e&&(e.focus(),ss(e)),this.pendingFocus=null})}},Eo=oc;var ac=t=>{let e=t.slice(0,8),i=e.slice(0,4);return e.length>4&&(i+="-"+e.slice(4,6)),e.length>6&&(i+="-"+e.slice(6,8)),i},lc={mounted(){this.onInput=()=>{let t=this.el.value.replace(/\D/g,""),e=ac(t);e!==this.el.value&&(this.el.value=e,this.el.setSelectionRange(e.length,e.length))},this.el.addEventListener("input",this.onInput)},destroyed(){this.el.removeEventListener("input",this.onInput)}},So=lc;var hc={mounted(){this.handleScroll=this.handleScroll.bind(this),this.handleClick=this.handleClick.bind(this),window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.el.addEventListener("click",this.handleClick)},destroyed(){window.removeEventListener("scroll",this.handleScroll)},handleScroll(){window.scrollY>24&&this.dismiss()},handleClick(){document.querySelector(".listen-content")?.scrollIntoView({behavior:"smooth"}),this.dismiss()},dismiss(){window.removeEventListener("scroll",this.handleScroll),this.el.classList.add("listen-scroll-hint-hidden")}},Co=hc;var cc={mounted(){this.update=()=>{let t=this.el,e=t.parentElement,i=t.scrollHeight-t.clientHeight,n=i>0?Math.min(1,t.scrollTop/24):0,s=i>0?Math.min(1,(i-t.scrollTop)/24):0;e.style.setProperty("--scroll-shadow-top-opacity",n.toFixed(3)),e.style.setProperty("--scroll-shadow-bottom-opacity",s.toFixed(3))},this.el.addEventListener("scroll",this.update,{passive:!0}),this.resizeObserver=new ResizeObserver(this.update),this.resizeObserver.observe(this.el),this.update()},updated(){this.update()},destroyed(){this.resizeObserver?.disconnect()}},ko=cc;var dc={mounted(){this.onResize=()=>this.align(),window.addEventListener("resize",this.onResize),this.align()},updated(){this.align()},destroyed(){window.removeEventListener("resize",this.onResize)},align(){let t=this.el.offsetParent,e=[...document.querySelectorAll(this.el.dataset.anchor)].find(o=>o.offsetParent!==null),i=Number(this.el.dataset.anchorMinWidth||0);if(!t||!e||window.innerWidth<i){this.el.style.left="";return}let n=t.getBoundingClientRect(),s=e.getBoundingClientRect().left-n.left,r=n.width-this.el.offsetWidth-8;this.el.style.left=`${Math.round(Math.max(0,Math.min(s,r)))}px`}},_o=dc;var uc={mounted(){this.handleEvent("selection-changed",({selected_ids:t})=>{let e=new Set(t),i=document.querySelector(this.el.dataset.target);if(!i)return;let n=this.el.dataset.selector||"input[type=checkbox][phx-value-id]",s=i.querySelectorAll(n),r=s.length>0;s.forEach(o=>{let a=o.getAttribute("phx-value-id"),l=e.has(a);o.checked=l;let h=o.closest("tr");h&&h.toggleAttribute("data-selected",l),l||(r=!1)}),this.el.checked=r})}},Ao=uc;function fc(){return new Promise((t,e)=>{if(window.Stripe){t(window.Stripe);return}let i=document.createElement("script");i.src="https://js.stripe.com/v3/",i.async=!0,i.onload=()=>t(window.Stripe),i.onerror=()=>e(new Error("Failed to load Stripe.js")),document.head.appendChild(i)})}var pc={async mounted(){if(this.publishableKey=this.el.dataset.publishableKey,this.stripe=null,this.cardElement=null,this.clientSecret=null,!this.publishableKey){console.error("StripeElementsHook: Missing data-publishable-key attribute on mount"),this.pushEvent("stripe_payment_failed",{error:"Stripe configuration error"});return}try{let e=await fc();this.stripe=e(this.publishableKey)}catch(e){console.error("Failed to load Stripe.js:",e);return}let t=this.stripe.elements();
25this.cardElement=t.create("card",{style:{base:{fontSize:"16px",color:"#18181b",fontFamily:"ui-sans-serif, system-ui, sans-serif","::placeholder":{color:"#a1a1aa"}},invalid:{color:"#dc2626",iconColor:"#dc2626"}}}),this.cardElement.mount(this.el),this.cardElement.on("change",e=>{let i=document.getElementById("card-errors");i&&(i.textContent=e.error?e.error.message:"")}),this.handleEvent("confirm_stripe_payment",({client_secret:e,payment_method_id:i})=>{this.clientSecret=e,i?this.confirmPaymentWithSavedCard(e,i):this.confirmPaymentWithNewCard(e)})},async confirmPaymentWithSavedCard(t,e){try{let{paymentIntent:i,error:n}=await this.stripe.confirmCardPayment(t,{payment_method:e});n?this.pushEvent("stripe_payment_failed",{error:n.message}):i.status==="succeeded"?this.pushEvent("stripe_payment_confirmed",{intent_id:i.id}):this.pushEvent("stripe_payment_failed",{error:`Payment status: ${i.status}`})}catch(i){this.pushEvent("stripe_payment_failed",{error:i.message})}},async confirmPaymentWithNewCard(t){try{let{paymentIntent:e,error:i}=await this.stripe.confirmCardPayment(t,{payment_method:{card:this.cardElement}});i?this.pushEvent("stripe_payment_failed",{error:i.message}):e.status==="succeeded"?this.pushEvent("stripe_payment_confirmed",{intent_id:e.id}):this.pushEvent("stripe_payment_failed",{error:`Payment status: ${e.status}`})}catch(e){this.pushEvent("stripe_payment_failed",{error:e.message})}},destroyed(){this.cardElement&&(this.cardElement.unmount(),this.cardElement.destroy())}},xo=pc;function mc(){return new Promise((t,e)=>{if(window.Stripe){t(window.Stripe);return}let i=document.createElement("script");i.src="https://js.stripe.com/v3/",i.async=!0,i.onload=()=>t(window.Stripe),i.onerror=()=>e(new Error("Failed to load Stripe.js")),document.head.appendChild(i)})}var gc={async mounted(){if(this.publishableKey=this.el.dataset.publishableKey,this.stripe=null,this.cardElement=null,!this.publishableKey){console.error("StripeSetupHook: Missing data-publishable-key attribute on mount"),this.pushEvent("setup_intent_failed",{error:"Stripe configuration error"});return}try{let e=await mc();this.stripe=e(this.publishableKey)}catch(e){console.error("Failed to load Stripe.js:",e);return}let t=this.stripe.elements();this.cardElement=t.create("card",{style:{base:{fontSize:"16px",color:"#18181b",fontFamily:"ui-sans-serif, system-ui, sans-serif","::placeholder":{color:"#a1a1aa"}},invalid:{color:"#dc2626",iconColor:"#dc2626"}}}),this.cardElement.mount(this.el),this.cardElement.on("change",e=>{let i=document.getElementById("setup-card-errors");i&&(i.textContent=e.error?e.error.message:"")}),this.handleEvent("confirm_setup_intent",({client_secret:e})=>{this.confirmSetup(e)})},async confirmSetup(t){try{let{setupIntent:e,error:i}=await this.stripe.confirmCardSetup(t,{payment_method:{card:this.cardElement}});i?this.pushEvent("setup_intent_failed",{error:i.message}):e.status==="succeeded"?this.pushEvent("setup_intent_confirmed",{setup_intent_id:e.id}):this.pushEvent("setup_intent_failed",{error:`Setup status: ${e.status}`})}catch(e){this.pushEvent("setup_intent_failed",{error:e.message})}},destroyed(){this.cardElement&&(this.cardElement.unmount(),this.cardElement.destroy())}},To=gc;var vc={mounted(){this.defaultTab=this.el.dataset.defaultTab,this.urlParam=this.el.dataset.urlParam||null,this.activeTab=this.tabFromUrl()||this.el.dataset.activeTab||this.defaultTab,this.bindTabButtons(),this.activateTab(this.activeTab,{updateUrl:!1}),this.revealActiveButton()},revealActiveButton(){let t=this.el.querySelector(`.tabs-button[data-tab-id="${CSS.escape(this.activeTab||"")}"]`),e=t&&t.parentElement;if(!e||e.scrollWidth<=e.clientWidth)return;let i=e.getBoundingClientRect(),n=t.getBoundingClientRect();e.scrollLeft+=n.left-i.left-(i.width-n.width)/2},updated(){this.defaultTab=this.el.dataset.defaultTab,this.urlParam=this.el.dataset.urlParam||null,this.bindTabButtons(),this.activateTab(this.activeTab||this.defaultTab,{updateUrl:!1})},bindTabButtons(){this.el.querySelectorAll(".tabs-button").forEach(t=>{t._tabsBound||(t._tabsBound=!0,t.addEventListener("click",e=>{this.activateTab(e.currentTarget.dataset.tabId,{updateUrl:!0})}
25))})},tabFromUrl(){if(!this.urlParam)return null;let t=new URLSearchParams(window.location.search).get(this.urlParam);return t&&this.el.querySelector(`.tabs-button[data-tab-id="${CSS.escape(t)}"]`)?t:null},syncUrl(t){if(!this.urlParam)return;let e=new URL(window.location.href);e.searchParams.set(this.urlParam,t),window.history.replaceState(window.history.state,"",e)},activateTab(t,{updateUrl:e}={updateUrl:!1}){this.activeTab=t,this.el.dataset.activeTab=t,this.el.querySelectorAll(".tabs-button").forEach(i=>{let n=i.dataset.tabId===t;i.dataset.active=n}),this.el.querySelectorAll(".tabs-panel").forEach(i=>{let n=i.dataset.tabPanel===t;i.dataset.active=n}),e&&this.syncUrl(t)}},Mo=vc;var bc={mounted(){this.onKeydown=t=>{t.key==="Enter"&&t.preventDefault()},this.el.addEventListener("keydown",this.onKeydown)},updated(){let t=this.el.getAttribute("aria-activedescendant");if(!t)return;let e=document.getElementById(t);e&&e.scrollIntoView({block:"nearest"})},destroyed(){this.el.removeEventListener("keydown",this.onKeydown)}},Po=bc;var yc={mounted(){this.activeId=this.el.querySelector("[role=option][data-current]")?.id||null,this.navigating=!1,this.onKeydown=t=>this.keydown(t),this.onInput=()=>{this.navigating=!1},this.el.addEventListener("keydown",this.onKeydown),this.el.addEventListener("input",this.onInput),this.apply(),this.input()?.focus()},updated(){this.apply()},destroyed(){this.el.removeEventListener("keydown",this.onKeydown),this.el.removeEventListener("input",this.onInput)},input(){return this.el.querySelector("[data-role=chooser-search]")},options(){return Array.from(this.el.querySelectorAll("[role=option]"))},apply(){let t=this.options();this.activeId&&!t.some(i=>i.id===this.activeId)&&(this.activeId=null),t.forEach(i=>i.setAttribute("aria-selected",i.id===this.activeId?"true":"false"));let e=this.input();e&&(this.activeId?e.setAttribute("aria-activedescendant",this.activeId):e.removeAttribute("aria-activedescendant"))},move(t){let e=this.options();if(e.length===0)return;let i=e.findIndex(s=>s.id===this.activeId),n=i===-1?t>0?0:e.length-1:Math.min(Math.max(i+t,0),e.length-1);this.activeId=e[n].id,this.apply(),e[n].scrollIntoView({block:"nearest"})},returnFocus(){document.getElementById(this.el.dataset.returnFocus)?.focus()},keydown(t){if(t.isComposing||t.keyCode===229)return;if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.pushEventTo(this.el,"close_chooser",{}),this.returnFocus();return}if(t.target!==this.input())return;let e=this.activeId&&document.getElementById(this.activeId);switch(t.key){case"ArrowDown":case"ArrowUp":t.preventDefault(),this.navigating=!0,this.move(t.key==="ArrowDown"?1:-1);break;case"Enter":t.preventDefault(),e&&e.querySelector("[data-role=chooser-pick]")?.click();break;case" ":e&&(this.navigating||t.target.value==="")&&(t.preventDefault(),e.querySelector("[data-role=chooser-play]")?.click());break}}},Io=yc;var wc={mounted(){this.addTimezoneToHref()},updated(){this.addTimezoneToHref()},addTimezoneToHref(){let t=this.el.getAttribute("href");if(!t)return;let e=Intl.DateTimeFormat().resolvedOptions().timeZone,i=new URL(t,window.location.origin);i.searchParams.set("tz",e),this.el.setAttribute("href",i.pathname+i.search)}},Do=wc;var Ec={mounted(){this.startCounter()},updated(){this.stopCounter(),this.startCounter()},destroyed(){this.stopCounter()},startCounter(){let t=this.el.dataset.startedAt;if(!t||t==="null"||t===""){this.el.textContent="\u2014";return}let e=new Date(t);if(isNaN(e.getTime())){this.el.textContent="\u2014";return}this.updateDisplay(e),this.interval=setInterval(()=>{this.updateDisplay(e)},1e3)},stopCounter(){this.interval&&(clearInterval(this.interval),this.interval=null)},updateDisplay(t){let e=Date.now(),i=Math.floor((e-t.getTime())/1e3);if(i<0){this.el.textContent="\u2014";return}let n=Math.floor(i/86400),s=Math.floor(i%86400/3600),r=Math.floor(i%3600/60),o=i%60,a=[];n>0&&a.push(`${n}d`),(s>0||n>0)&&a.push(`${s}h`),(r>0||s>0||n>0)&&a.push(`${r}m`),a.push(`${o}s`),this.el.textContent=a.join(" ")}},Lo=Ec;var Ro=[1,2,4,8,16],Sc=100,Cc=1e3,kc=2e3,_c=15e3,Ac=6e3,xc=50,as=6e4,rs=1,Tc=15e3,Mc=50,Pc=350,Ic=6e4,Dc=1e3,Lc=8192,Rc=64,Oc={mounted(){this.peaks=null,this.zoomIndex=0,this.hoverMs=null,this.playing=!1,this.previewStopMs=null,this.rafId=null,this.dragging=null,this.cacheElements(),this.readDataset(),this.bindEvents(),this.observeResize(),this.clampFades(),this.syncAll(),this.loadPeaks()},updated(){let t=this.audioUrl;this.readDataset(),t!==this.audioUrl&&this.teardownAudio(),this.clearHover(),this.clampFades(),this.syncAll(),this.loadPeaks()},destroyed(){this.teardownAudio(),this.rafId&&cancelAnimationFrame(this.rafId),this.resizeObserver&&this.resizeObserver.disconnect()},cacheElements(){let t=e=>this.el.querySelector(e);this.viewport=t("[data-waveform-viewport]"),this.trackEl=t("[data-waveform-track]"),this.canvas=t("[data-waveform-canvas]"),this.axis=t("[data-time-axis]"),this.playhead=t("[data-playhead]"),this.hoverCurs
25or=t("[data-hover-cursor]"),this.hoverLabel=t("[data-hover-label]"),this.timeDisplay=t("[data-time-display]"),this.zoomLabel=t("[data-zoom-level]"),this.errorEl=t("[data-cue-error]"),this.resetLinks={cueIn:t('[data-action="reset-cue-in"]'),cueOut:t('[data-action="reset-cue-out"]'),fadeIn:t('[data-action="reset-fade-in"]'),fadeOut:t('[data-action="reset-fade-out"]'),all:t('[data-action="reset-all"]')},this.regions={trimStart:t('[data-region="trim-start"]'),trimEnd:t('[data-region="trim-end"]'),fadeIn:t('[data-region="fade-in"]'),fadeOut:t('[data-region="fade-out"]'),overlap:t('[data-region="overlap"]'),mixPoint:t('[data-region="mix-point"]'),break:t('[data-region="break"]')},this.handles={in:t('[data-handle="in"]'),out:t('[data-handle="out"]')},this.fadeHandles={in:t('[data-fade-handle="in"]'),out:t('[data-fade-handle="out"]')},this.timeInputs={in:t('[data-time-input="in"]'),out:t('[data-time-input="out"]')},this.fadeInputs={in:t('[data-fade-input="in"]'),out:t('[data-fade-input="out"]')},this.pills={in:t('[data-cue-state="in"]'),out:t('[data-cue-state="out"]')},this.hints={in:t('[data-cue-hint="in"]'),out:t('[data-cue-hint="out"]')},this.fadeHints={in:t('[data-fade-hint="in"]'),out:t('[data-fade-hint="out"]')},this.fadeWarnings={in:t('[data-fade-warning="in"]'),out:t('[data-fade-warning="out"]')},this.hidden={cueIn:t('[data-cue-field="cue_in_ms"]'),cueOut:t('[data-cue-field="cue_out_ms"]'),fadeIn:t('[data-cue-field="fade_in_ms"]'),fadeOut:t('[data-cue-field="fade_out_ms"]')}},readDataset(){let t=this.el.dataset;this.peaksUrl=t.peaksUrl||null,this.audioUrl=t.audioUrl||null,this.durationMs=bt(t.durationMs)||0,this.suggestedIn=bt(t.suggestedCueInMs),this.suggestedOut=bt(t.suggestedCueOutMs),this.mixPointMs=bt(t.mixPointMs),this.manual={in:t.manualCueIn==="true",out:t.manualCueOut==="true"},this.cue={in:bt(t.cueInMs)||0,out:bt(t.cueOutMs)},this.fade={in:bt(t.fadeInMs)||0,out:bt(t.fadeOutMs)||0},this.crossfadeMs=Math.max(0,bt(t.crossfadeMs)||0),this.maxFadeMs=bt(t.maxFadeMs)||_c,this.fadeWarningMs=bt(t.fadeWarningMs)||Ac,this.cutFadeMs=bt(t.cutFadeMs)||xc,this.shortFileMs=bt(t.shortFileMs)||as,this.cue.out===null&&(this.cue.out=this.durationMs||null)},bindEvents(){this.el.addEventListener("click",t=>{let e=t.target.closest("[data-action]");!e||!this.el.contains(e)||(t.preventDefault(),this.runAction(e.dataset.action,e))});for(let t of["in","out"])this.bindHandle(this.handles[t],t,"cue"),this.bindHandle(this.fadeHandles[t],t,"fade"),this.timeInputs[t].addEventListener("change",()=>{let e=jc(this.timeInputs[t].value);if(e===null)return this.syncAll();this.setCue(t,e,{manual:!0})}),this.fadeInputs[t].addEventListener("change",()=>{this.setFade(t,this.parseFadeInput(t,this.fadeInputs[t].value))});this.trackEl.addEventListener("pointerdown",t=>{t.target.closest("[data-handle], [data-fade-handle]")||this.seekTo(this.msFromClientX(t.clientX))}),this.viewport.addEventListener("wheel",t=>{!t.ctrlKey&&!t.metaKey||(t.preventDefault(),this.setZoom(this.zoomIndex+(t.deltaY<0?1:-1),t.clientX))},{passive:!1}),this.bindHover()},bindHandle(t,e,i){t.addEventListener("pointerdown",s=>{s.preventDefault(),t.focus(),t.setPointerCapture(s.pointerId),t.dataset.dragging="true",this.dragging={handle:t,side:e,kind:i,pointerId:s.pointerId}}),t.addEventListener("pointermove",s=>{!this.dragging||this.dragging.pointerId!==s.pointerId||this.applyDrag(s.clientX)});let n=s=>{!this.dragging||this.dragging.pointerId!==s.pointerId||(delete t.dataset.dragging,this.dragging=null)};t.addEventListener("pointerup",n),t.addEventListener("pointercancel",n),t.addEventListener("keydown",s=>this.handleKey(s,e,i))},observeResize(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>this.render()),this.resizeObserver.observe(this.viewport))},async loadPeaks(){if(!(!this.peaksUrl||this.loadedPeaksUrl===this.peaksUrl)){this.loadedPeaksUrl=this.peaksUrl;try{let t=await fetch(this.peaksUrl,{credentials:"same-origin"});if(!t.ok)throw new Error(`peaks request failed: ${t.status}`);this.peaks=qc(await t.json()),this.clearError()}catch{this.peaks=null,this.showError("The waveform could not be loaded, so the timeline below is a plain seek bar.")}this.render()}},setCue(t,e,{manual:i=!0}={}){let n=St(Math.round(e),0,this.maxMs());t==="in"?this.cue.in=Math.max(0,Math.min(n,(this.cue.out??this.maxMs())-this.minWindow())):this.cue.out=Math.max(n,this.cue.in+this.minWindow(),rs+1),this.manual[t]=i,this.clampFades(),this.syncAll()},setFade(t,e){let i=Math.round(e),n=t==="in"&&i>0&&i<this.cutFadeMs?this.cutFadeMs:i;this.fade[t]=St(n,0,this.maxFade()),this.clampFades(),this.syncAll()},parseFadeInput(t,e){let i=parseFloat(e);return Number.isFinite(i)?t==="in"&&i<=0?this.cutFadeMs:Math.round(i*1e3):0},fadeInState(){return this.fade.in===0?"default":this.fade.in===this.cutFadeMs?"none":"set"},fadeInDefault(){return Kc(this.cueWindow(),this.crossfadeMs,this.shortFileMs)},clampFades(){let t=this.cueWindow();
25this.fade.in=St(this.fade.in,0,Math.min(this.maxFadeMs,t)),this.fade.out=St(this.fade.out,0,Math.min(this.maxFadeMs,t))},resetCue(t){this.manual[t]=!1,t==="in"?this.cue.in=this.suggestedIn??0:this.cue.out=this.suggestedOut??this.durationMs??null,this.clampFades(),this.syncAll()},resetToDetected(){this.resetCue("in"),this.resetCue("out"),this.setFade("in",0),this.setFade("out",0)},runAction(t,e=null){this.pressed=e;let i=this.cue.out??this.maxMs();switch(t){case"reset-cue-in":return this.resetCue("in");case"reset-cue-out":return this.resetCue("out");case"reset-fade-in":return this.setFade("in",0);case"reset-fade-out":return this.setFade("out",0);case"reset-all":return this.resetToDetected();case"zoom-in":return this.setZoom(this.zoomIndex+1);case"zoom-out":return this.setZoom(this.zoomIndex-1);case"preview-fade-in":return this.preview(this.cue.in);case"preview-fade-out":return this.preview(Math.max(this.cue.in,i-this.effectiveFade("out")-kc));case"stop":return this.stop()}},setZoom(t,e=null){let i=St(t,0,Ro.length-1);if(i===this.zoomIndex)return;let n=this.viewport.getBoundingClientRect(),s=e===null?this.anchorOffsetFromPlayhead(n.width):St(e-n.left,0,n.width),r=this.msFromClientX(n.left+s);this.zoomIndex=i,this.render(),this.view&&(this.viewport.scrollLeft=Ee(r,this.view)-s)},anchorOffsetFromPlayhead(t){let i=(parseFloat(this.playhead.style.left)||0)-this.viewport.scrollLeft;return!this.playhead.classList.contains("hidden")&&i>=0&&i<=t?i:t/2},handleKey(t,e,i){let n=t.shiftKey?Cc:Sc,s=0;if(t.key==="ArrowLeft"||t.key==="ArrowDown")s=-n;else if(t.key==="ArrowRight"||t.key==="ArrowUp")s=n;else if(t.key==="Home")s=-this.maxMs();else if(t.key==="End")s=this.maxMs();else return;t.preventDefault(),i==="cue"?this.setCue(e,(e==="in"?this.cue.in:this.cue.out??this.maxMs())+s):this.setFadeFromHandle(e,this.fade[e]+s)},setFadeFromHandle(t,e){this.setFade(t,t==="in"?Math.max(e,this.cutFadeMs):e)},applyDrag(t){let{side:e,kind:i}=this.dragging,n=this.msFromClientX(t);if(i==="cue")return this.setCue(e,n);let s=this.cue.out??this.maxMs();this.setFadeFromHandle(e,e==="in"?n-this.cue.in:s-n)},effectiveFade(t){let e=t==="out"?this.resolvedFadeOut():this.fade.in;return Math.min(e,this.cueWindow())},syncAll(){this.syncInputs(),this.syncPills(),this.syncFadeHints(),this.syncHidden(),this.syncResetAll(),this.render()},syncResetAll(){this.resetLinks.all&&(this.resetLinks.all.disabled=!(this.manual.in||this.manual.out||this.fade.in>0||this.fade.out>0))},syncInputs(){for(let t of["in","out"]){let e=t==="in"?this.cue.in:this.cue.out;document.activeElement!==this.timeInputs[t]&&(this.timeInputs[t].value=e===null?"":t==="in"?Oo(e):li(e)),document.activeElement!==this.fadeInputs[t]&&(this.fadeInputs[t].value=this.fadeInputValue(t))}},fadeInputValue(t){return t==="in"&&this.fadeInState()==="none"?"0":this.fade[t]>0?(this.fade[t]/1e3).toFixed(1):""},syncPills(){for(let t of["in","out"]){let e=this.manual[t];this.pills[t].dataset.manual=String(e),this.pills[t].textContent=e?"Manual":"Auto-detected";let i=t==="in"?this.suggestedIn:this.suggestedOut;this.hints[t].textContent=i===null?"Nothing detected at import.":`Detected at ${li(i)}.`}Tt(this.resetLinks.cueIn,this.manual.in),Tt(this.resetLinks.cueOut,this.manual.out)},syncFadeHints(){let t=this.fadeOutSource(),e=this.fadeInState(),i=this.fadeInDefault(),n={in:Xc(e,i,this.shortFileMs),out:this.fade.out>0?"":Wc(t,this.crossfadeMs,this.resolvedFadeOut())};for(let s of["in","out"])this.fadeHints[s]&&(this.fadeHints[s].textContent=n[s]);this.fadeInputs.in.placeholder=Gc(i),this.resetLinks.fadeIn.textContent=Jc(i),Tt(this.resetLinks.fadeIn,Yc(e,i)),Tt(this.resetLinks.fadeOut,this.fade.out>0);for(let s of["in","out"])this.fadeWarnings[s]&&Tt(this.fadeWarnings[s],this.fade[s]>this.fadeWarningMs);for(let s of["in","out"]){let r=String(s==="out"&&t==="station"),o=this.handleLabel(s),a=this.fadeHandles[s],l=s==="in"?this.regions.fadeIn:this.regions.fadeOut;a.dataset.station=r,l.dataset.station=r,a.setAttribute("aria-valuetext",o);let h=a.querySelector("[data-handle-value]");h&&(h.textContent=o)}this.regions.overlap.setAttribute("aria-label",td(Ho(this.resolvedFadeOut(),this.crossfadeMs)))},handleLabel(t){return t==="in"?Zc(this.fadeInState(),this.fadeInDefault(),this.fade.in):Qc(this.fadeOutSource(),this.resolvedFadeOut())}
25,fadeOutSource(){if(this.fade.out>0)return"manual";if(this.crossfadeMs<=0)return"none";let t=this.cue.out??this.maxMs();return this.mixPointMs===t?"cut":this.mixPointMs===null||this.mixPointMs>t?"station":"detected"},resolvedFadeOut(){let t=this.cue.out??this.maxMs();switch(this.fadeOutSource()){case"manual":return this.fade.out;case"none":return 0;case"cut":return this.durationMs>0&&this.durationMs<Ic?Pc:Mc;case"detected":return Math.min(t-this.mixPointMs,this.crossfadeMs<=Dc?this.crossfadeMs:1/0,this.maxFadeMs,this.cueWindow());default:return Math.min(this.crossfadeMs,this.maxFadeMs,this.cueWindow())}},syncHidden(){this.hidden.cueIn.value=this.manual.in?String(Math.max(this.cue.in,rs)):"0",this.hidden.cueOut.value=this.manual.out&&this.cue.out!==null?String(this.cue.out):"",this.hidden.fadeIn.value=String(this.fade.in),this.hidden.fadeOut.value=String(this.fade.out)},currentView(){return Fc({totalMs:this.maxMs(),viewportWidth:this.viewport.clientWidth,zoom:Ro[this.zoomIndex]})},render(){let t=this.currentView();t.width!==0&&(this.view=t,this.trackEl.style.width=`${t.width}px`,this.axis.style.width=`${t.width}px`,this.zoomLabel.textContent=Uc(t),this.drawWaveform(t),this.drawAxis(t),this.positionOverlays(t),this.renderHover())},drawWaveform(t){let e=t.width,i=this.trackEl.clientHeight||160,n=Math.min(window.devicePixelRatio||1,Lc/Math.max(1,e));this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(i*n);let s=this.canvas.getContext("2d");s.setTransform(n,0,0,n,0,0),s.clearRect(0,0,e,i),s.fillStyle=id(this.el);let r=i/2;if(!this.peaks){for(let h of os(t))s.fillRect(h.left,r-2,h.right-h.left,4);return}let{mins:o,maxs:a}=this.peaks,l=o.length;for(let h of os(t)){let c=h.toMs-h.fromMs,d=h.right-h.left;if(c<=0||d<=0)continue;let m=h.fromMs/t.totalMs*l,p=h.toMs/t.totalMs*l;for(let u=Math.floor(h.left);u<h.right;u++){let v=(u-h.left)/d,y=(u+1-h.left)/d,M=Math.floor(m+v*(p-m)),L=Math.max(M+1,Math.floor(m+y*(p-m))),H=0,R=0;for(let T=M;T<L&&T<l;T++)o[T]<H&&(H=o[T]),a[T]>R&&(R=a[T]);let E=r-R*r,S=r-H*r;s.fillRect(u,E,1,Math.max(1,S-E))}}},drawAxis(t){let e=t.totalMs;if(e<=0)return;let i=e,n=Math.max(2,Math.round(t.width/120)),s=ed(i/n);this.axis.replaceChildren();for(let r=0;r<=e;r+=s){let o=document.createElement("span");o.className="absolute top-0 border-l border-zinc-300 pl-1 text-xs tabular-nums text-zinc-600 dark:border-white/10 dark:text-zinc-400",o.style.left=`${Ee(r,t)}px`,o.textContent=$c(r),this.axis.appendChild(o)}},positionOverlays(t){let e=t.totalMs;if(e<=0)return;let i=l=>Ee(l,t),n=this.cue.out??e;this.placeSpan(this.regions.trimStart,0,this.cue.in,t,this.cue.in>0),this.placeSpan(this.regions.trimEnd,n,e,t,n<e);let s=this.effectiveFade("in"),r=this.effectiveFade("out");this.placeSpan(this.regions.fadeIn,this.cue.in,this.cue.in+s,t,s>0),this.placeSpan(this.regions.fadeOut,n-r,n,t,r>0);let o=Ho(this.resolvedFadeOut(),this.crossfadeMs),a=Math.max(this.cue.in,n-o);if(this.placeSpan(this.regions.overlap,a,n,t,o>0&&n>a),this.regions.mixPoint){let l=this.mixPointMs,h=l!==null&&l>this.cue.in&&l<n;Tt(this.regions.mixPoint,h),this.regions.mixPoint.style.left=`${i(l||0)}px`}this.placeHandle(this.handles.in,i(this.cue.in),this.cue.in,Oo(this.cue.in),e),this.placeHandle(this.handles.out,i(n),n,li(n),e);for(let l of["in","out"]){let h=l==="in"?s:r;this.placeHandle(this.fadeHandles[l],i(l==="in"?this.cue.in+h:n-h),this.fade[l],this.handleLabel(l),this.cueWindow())}},placeSpan(t,e,i,n,s){let r=s?Nc(e,i,n):null;Tt(t,r!==null),r&&(t.style.left=`${r.left}px`,t.style.width=`${r.right-r.left}px`)},placeHandle(t,e,i,n,s){Tt(t,!0),t.style.left=`${e}px`,t.setAttribute("aria-valuenow",String(i)),t.setAttribute("aria-valuemax",String(s)),t.setAttribute("aria-valuetext",n);let r=t.querySelector("[data-handle-value]");r&&(r.textContent=n)},preview(t,e=null){if(!this.audioUrl)return;let i=this.ensureAudio();this.previewStopMs=e??this.cue.out??this.maxMs(),this.previewFromMs=t,this.pending={fromMs:t,stopMs:e},this.audioContext&&this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.movePlayhead(t),this.setLoading(!0);let n=()=>{i.currentTime=t/1e3,this.applyFadeGain(t),i.play().then(()=>{this.pending=null,this.playing=!0,this.trackPosition()}).catch(()=>{this.setLoading(!1),this.showError("Unable to play this track in the browser.")})};i.readyState>=1?n():i.addEventListener("loadedmetadata",n,{once:!0})},stop(){this.audio&&this.audio.pause(),this.playing=!1,this.pending=null,this.setLoading(!1),this.rafId&&cancelAnimationFrame(this.rafId),this.rafId=null},setLoading(t){this.loading=t;for(let e of this.el.querySelectorAll('[data-action^="preview-"]'))t&&e===this.pressed?e.dataset.loading="true":delete e.dataset.loading;t&&(this.timeDisplay.textContent="Loading")},seekTo(t){this.movePlayhead(t),this.audio&&this.playing&&(this.audio.currentTime=t/1e3)},ensureAudio(){if(this.audio)return this.audio;let t=new Audio;return t.preload="metadata",t.crossOrigin="anonymous",t.src=this.audioUrl,this.bindAudioEvents(t),t.addEventListener("error",()=>this.downgradeToPlainAudio()),this.audio=t,this.setupGain(t),t},bindAudioEvents(t){t.addEventListener("ended",()=>this.stop()),t.addEventListener("waiting",()=>this.playing&&this.setLoading(!0)),t.addEventListener("playing",()=>this.setLoading(!1))},setupGain(t){let e=window.AudioContext||window.webkitAudioContext;if(e)try{this.audioContext=new e,this.gainNode=this.audioContext.createGain(),this.audioContext.createMediaElementSource(t).connect(this.gainNode),this.gainNode.connect(this.audioContext.destination)}catch{this.audioContext=null,this.gainNode=null}},downgradeToPlainAudio(){if(this.downgraded||!this.audio)return;let t=this.playing?{fromMs:this.previewFromMs??this.cue.in,stopMs:this.previewStopMs}:this.pending;this.teardownAudio(),this.downgraded=!0;let e=new Audio;e.preload="metadata",e.src=this.audioUrl,this.bindAudioEvents(e),this.audio=e,t&&this.preview(t.fromMs,t.stopMs)},teardownAudio(){this.stop(),this.downgraded=!1,this.audio&&(this.audio.removeAttribute("src"),this.audio.load(),this.audio=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null,this.gainNode=null)},trackPosition(){let t=()=>{if(!this.playing||!this.audio)return;let e=this.audio.currentTime*1e3;if(this.movePlayhead(e),this.applyFadeGain(e),this.previewStopMs!==null&&e>=this.previewStopMs)return this.stop();this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)},applyFadeGain(t){let e=this.cue.out??this.maxMs(),i=this.effectiveFade("in"),n=this.effectiveFade("out"),s=1;i>0&&t<this.cue.in+i&&(s=Fo((t-this.cue.in)/i)),n>0&&t>e-n&&(s=Math.min(s,Fo((e-t)/n))),this.gainNode?this.gainNode.gain.value=s:this.audio&&(this.audio.volume=St(s,0,1))},movePlayhead(t){let e=this.view||this.currentView();e.totalMs<=0||e.width<=0||(Tt(this.playhead,!0),this.playhead.style.left=`${Ee(t,e)}px`,this.timeDisplay.textContent=li(t))},showError(t){this.errorEl.textContent=t,this.errorEl.classList.remove("hidden")},clearError(){this.errorEl.textContent="",this.errorEl.classList.add("hidden")},maxMs(){return this.durationMs||this.cue.out||0},cueWindow(){return Math.max(0,(this.cue.out??this.maxMs())-this.cue.in)},minWindow(){return Math.max(1,Math.min(Tc,Math.floor(this.maxMs()/2)))},maxFade(){return Math.min(this.maxFadeMs,this.cueWindow())},msFromClientX(t){let e=this.view||this.currentView(),i=this.trackEl.getBoundingClientRect(),n=i.width>0?e.width/i.width:1;return Hc((t-i.left)*n,e)}
25,bindHover(){this.hoverCursor&&(this.trackEl.addEventListener("pointermove",t=>{if(t.pointerType==="touch")return this.clearHover();if(t.target.closest("[data-fade-handle]"))return this.clearHover();let e=t.target.closest('[data-handle], [data-region="mix-point"]');this.hoverMs=e?this.markerMs(e):this.msFromClientX(t.clientX),this.renderHover()}),this.trackEl.addEventListener("pointerleave",()=>this.clearHover()),this.trackEl.addEventListener("pointercancel",()=>this.clearHover()))},markerMs(t){return t.dataset.region==="mix-point"?this.mixPointMs??0:t.dataset.handle==="in"?this.cue.in:this.cue.out??this.maxMs()},clearHover(){this.hoverMs=null,this.renderHover()},renderHover(){if(!this.hoverCursor)return;let t=this.view||this.currentView();if(this.hoverMs===null||t.totalMs<=0||t.width<=0)return Tt(this.hoverCursor,!1);let e=Ee(this.hoverMs,t);if(Tt(this.hoverCursor,!0),this.hoverCursor.style.left=`${e}px`,this.hoverLabel){this.hoverLabel.textContent=Bc(this.hoverMs);let i=e-this.viewport.scrollLeft>this.viewport.clientWidth-Rc;this.hoverLabel.dataset.flip=String(i)}}};function St(t,e,i){return Math.min(Math.max(t,e),i)}function Ee(t,e){let i=Math.max(0,e.totalMs);return i<=0?0:St(t,0,i)/i*e.width}function Hc(t,e){let i=Math.max(0,e.totalMs);if(i<=0||e.width<=0)return 0;let n=St(t,0,e.width);return Math.round(n/e.width*i)}function Fc({totalMs:t=0,viewportWidth:e=0,zoom:i=1}={}){let n=Math.max(0,t),s=Math.max(0,e);return{zoom:i,totalMs:n,width:Math.round(s*i)}}function os(t){return[{fromMs:0,toMs:t.totalMs,left:0,right:t.width}]}function Nc(t,e,i){let n=os(i).find(o=>t<o.toMs)||null;if(!n)return null;let s=Math.max(t,n.fromMs),r=Math.min(e,n.toMs);return r<=s?null:{fromMs:s,toMs:r,left:Ee(s,i),right:Ee(r,i)}}function Uc(t){return`${t.zoom}x`}function li(t){let e=Math.max(0,Math.round(t)),i=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),s=e%1e3;return`${i}:${String(n).padStart(2,"0")}.${String(s).padStart(3,"0")}`}function Oo(t){return li(t<=rs?0:t)}function Bc(t){let e=Math.max(0,Math.round(t)),i=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),s=Math.floor(e%1e3/10);return`${i}:${String(n).padStart(2,"0")}.${String(s).padStart(2,"0")}`}function $c(t){let e=Math.max(0,Math.round(t)),i=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${i}:${String(n).padStart(2,"0")}`}function jc(t){let e=(t||"").trim();if(e==="")return null;let i=e.match(/^(?:(\d+):)?(\d+(?:\.\d+)?)$/);if(!i)return null;let n=i[1]?parseInt(i[1],10):0,s=parseFloat(i[2]);return Number.isFinite(s)?Math.round((n*60+s)*1e3):null}function qc(t){if(!t||!Array.isArray(t.data)||t.data.length===0)return null;let e=t.channels||1,i=e*2,n=t.bits===8?128:32768,s=Math.floor(t.data.length/i),r=new Float32Array(s),o=new Float32Array(s);for(let a=0;a<s;a++){let l=0,h=0;for(let c=0;c<e;c++){let d=a*i+c*2;l=Math.min(l,t.data[d]),h=Math.max(h,t.data[d+1])}r[a]=St(l/n,-1,1),o[a]=St(h/n,-1,1)}return{mins:r,maxs:o}}function Ho(t,e){return e<=0?0:zc(t,e)}function zc(t,e){return t>0?t:Math.max(0,e)}function Fo(t){let e=St(t,0,1);return(1+Math.sin((e-.5)*Math.PI))/2}var No=1e3;function Oe(t){let e=Math.max(0,t)/1e3;return Number.isInteger(e)?String(e):e.toFixed(1)}function Vc(t){return t<=0?"No overlap: the next track starts at the cue out.":t<=No?`No overlap: a short ${Oe(t)} s fade at the cue out.`:"Smart crossfade: fades over the detected ending."}function Wc(t,e,i){switch(t){case"none":return"No overlap: the next track starts at the cue out.";case"cut":return"This track ends cold: the next one cuts in at the cue out.";case"detected":return`Detected fade (${Oe(i)} s).`;default:return Vc(e)}}function Kc(t,e,i=as){return t<i?"short":e>No?"auto":"none"}function Xc(t,e,i=as){return t==="set"?"":t==="default"&&e==="auto"?"Auto: smart crossfade sizes the fade in per pair, up to 3 s on a loud intro.":t==="default"&&e==="short"?`No fade in: under ${i/1e3} s, a jingle or ID always enters at full level.`:"No fade in: the track starts at full level."}function Gc(t){return t==="auto"?"Auto":"0"}function Jc(t){return t==="auto"?"Use auto":"Remove the fade in"}function Yc(t,e){return t==="set"||t==="none"&&e==="auto"}
25function Zc(t,e,i){return t==="set"?`Fade in ${Oe(i)} s`:t==="default"&&e==="auto"?"Fade in auto":"No fade in"}function Qc(t,e){switch(t){case"cut":return"Cuts";case"none":return"No fade out";case"station":return`Fade out ${Oe(e)} s (station)`;default:return`Fade out ${Oe(e)} s`}}function td(t){return`Next track starts ${Oe(t)} s before the cue out`}function ed(t){return[100,250,500,1e3,2e3,5e3,1e4,15e3,3e4,6e4,12e4,3e5].find(i=>i>=t)||6e5}function bt(t){if(t==null||t==="")return null;let e=parseInt(t,10);return Number.isFinite(e)?e:null}function Tt(t,e){t.classList.toggle("hidden",!e)}function id(t){return getComputedStyle(t).getPropertyValue("--waveform-color").trim()||"#71717a"}var Uo=Oc;var Pt={},Ji=null,He=null;Pt.setDuplicateHandler=function(t){Ji=t};Pt.setCompletionHandler=function(t){He=t,hi()};Pt.clearCompletionHandler=function(t){He===t&&(He=null)};var nd=100*1024*1024;async function sd(t){try{if(!Ji||!window.crypto||!window.crypto.subtle||t.file.size>nd)return!1;let e=await t.file.arrayBuffer(),i=await crypto.subtle.digest("SHA-256",e),n=Array.from(new Uint8Array(i)).map(s=>s.toString(16).padStart(2,"0")).join("");return await Ji.isDuplicate(n)}catch{return!1}}var rd=2,od=3,ad=2e3,ld=250,hd=12e4,Gi=0,Mt=[],Se=new Set,rt=new Set,Yi=new Set,Fe=null;function Zi(t){return t.view&&typeof t.view.isConnected=="function"&&t.view.isConnected()}function cd(t){return t.view&&typeof t.view.isDestroyed=="function"&&t.view.isDestroyed()}function st(t){return t.cancelled.value||t.entry.isCancelled()&&!t.channelErrored}function dd(){Fe!=null&&(clearTimeout(Fe),Fe=null)}function hi(){Fe!=null||rt.size===0||(Fe=setTimeout(()=>{Fe=null,fd()},ld))}function ls(t,e){t.pendingTerminalNotification=e,rt.add(t),hi()}function ud(t){let{entry:e}=t;!He||typeof He.complete!="function"||!e.meta||(t.terminalPushInFlight=!0,He.complete({track_id:e.meta.track_id,ingest_key:e.meta.key}).then(i=>{t.terminalPushInFlight=!1,i&&i.ok===!0?(t.pendingTerminalNotification=null,rt.delete(t)):(console.warn("[app] interrupted upload completion was not accepted:",i),t.pendingTerminalNotification=null,rt.delete(t))}).catch(()=>{t.terminalPushInFlight=!1}).finally(()=>{hi()}))}function fd(){rt.forEach(t=>{let{entry:e}=t;if(st(t)){t.pendingTerminalNotification=null,rt.delete(t);return}let i=t.pendingTerminalNotification;if(!t.terminalPushInFlight){if(i.type==="interrupted_complete"){ud(t);return}if(cd(e)){t.pendingTerminalNotification=null,rt.delete(t);return}Zi(e)&&(t.pendingTerminalNotification=null,rt.delete(t),i.type==="complete"?e.progress(100):i.type==="error"&&$o(e,i.message))}}),hi()}function pd(t){let{entry:e}=t;if(!st(t)){if(t.channelErrored){ls(t,{type:"interrupted_complete"});return}Zi(e)?e.progress(100):ls(t,{type:"complete"})}}function md(t,e){let{entry:i}=t;if(!st(t)){if(t.channelErrored){console.warn("[app] upload failed after LiveView reconnect boundary:",e),Yi.add(t);return}Zi(i)?$o(i,e):ls(t,{type:"error",message:e})}}function Ne(t){t.cancelled.value=!0,t.pendingTerminalNotification=null,t.terminalPushInFlight=!1,rt.delete(t),t.xhr&&t.xhr.abort()}function gd(){Mt.forEach(Ne),Mt=[],Se.forEach(Ne),Array.from(rt).forEach(Ne),rt.clear(),Yi.clear(),dd()}function Bo(){for(;Gi<rd&&Mt.length>0;){let t=Mt.shift();st(t)||bd(t)}}function vd(t){return t===408||t===429||t>=500}function $o(t,e){let i=t.fileEl,n=i&&i.getAttribute("data-phx-upload-ref");t.error(e),i&&n&&!i.hasAttribute("data-phx-upload-ref")&&i.setAttribute("data-phx-upload-ref",n)}function bd(t){let{entry:e}=t;if(st(t))return;Gi++,Se.add(t);let i=!1,n=()=>{i||(i=!0,Gi=Math.max(0,Gi-1),Se.delete(t),t.xhr=null,Bo())},s=o=>{if(st(t)){n();return}let a=new XMLHttpRequest;t.xhr=a;let l=!1,h=null,c=()=>{h&&(clearTimeout(h),h=null)},d=()=>{c(),h=setTimeout(()=>{l=!0,a.abort()},hd)},m=(p,u)=>{if(c(),st(t)){n();return}u&&o<od?(t.xhr=null,setTimeout(()=>s(o+1),ad*o)):(md(t,p),n())};a.onload=()=>{c(),a.status===200||a.status===204?(st(t)||pd(t),n()):m(`Upload failed with status ${a.status}`,vd(a.status))},a.onerror=()=>{m("Network error during upload",!0)},a.onabort=()=>{l?m("Upload stalled",!0):(c(),n())},a.upload.addEventListener("progress",p=>{if(st(t)){c(),a.abort();return}if(d(),p.lengthComputable){let u=Math.round(p.loaded/p.total*100);t.progress=u,u<100&&!t.channelErrored&&Zi(e)&&e.progress(u)}}),a.open("PUT",e.meta.url,!0),e.file.type&&a.setRequestHeader("Content-Type",e.file.type),d(),a.send(e.file)};(t.channelErrored?Promise.resolve(!1):sd(e)).then(o=>{if(o&&!st(t))try{t.channelErrored||Ji.skip(e)}finally{n()}else s(1)})}Pt.S3=function(t,e){t.forEach(i=>
25{let s={entry:i,cancelled:{value:!1},xhr:null,pendingTerminalNotification:null,terminalPushInFlight:!1,channelErrored:!1,progress:0};e(()=>{s.channelErrored=!0,hi()}),Mt.push(s)}),Bo()};Pt.hasPending=function(){return Mt.some(t=>!st(t))||Array.from(Se).some(t=>!st(t))||Array.from(rt).some(t=>!st(t))};Pt.uploadsInProgress=function(){return Pt.hasPending()?!0:typeof document<"u"&&document.querySelector('[data-uploading="true"]')!==null};function yd(t){return rt.has(t)?"finalizing":Yi.has(t)?"failed":Se.has(t)?"uploading":"queued"}function wd(t,e){return e==="finalizing"?100:e==="queued"?0:t.progress||0}Pt.orphanSnapshot=function(){let t=new Set;Se.forEach(n=>t.add(n)),rt.forEach(n=>t.add(n)),Yi.forEach(n=>t.add(n));let e=[];t.forEach(n=>{if(!n.channelErrored||st(n))return;let{entry:s}=n,r=yd(n);e.push({track_id:s.meta&&s.meta.track_id,filename:s.file&&s.file.name,size_bytes:s.file&&s.file.size,progress:wd(n,r),state:r})});let i=0;return Mt.forEach(n=>{n.channelErrored&&!st(n)&&(i+=1)}),{uploads:e,queued_count:i}};Pt.cancelAll=function(){gd(),Mt=[]};Pt.cancel=function(t){let e=i=>i.entry&&i.entry.ref===t;Mt.forEach(i=>e(i)&&Ne(i)),Mt=Mt.filter(i=>!e(i)),Se.forEach(i=>e(i)&&Ne(i)),Array.from(rt).forEach(i=>e(i)&&Ne(i))};var ot=Pt;var Ed={mounted(){this._navigating=!1,this._confirmDialog=null,ot.setDuplicateHandler({isDuplicate:e=>new Promise(i=>{let n=!1,s=o=>{n||(n=!0,i(o))},r=setTimeout(()=>s(!1),1e4);try{this.pushEvent("check_content_hash",{hash:e},o=>{clearTimeout(r),s(o!=null&&o.duplicate===!0)})}catch{clearTimeout(r),s(!1)}}),skip:e=>{this.pushEvent("skip_duplicate_upload",{ref:e.ref,upload:e.fileEl&&e.fileEl.name})}}),this._completionHandler={complete:e=>this.pushEvent("complete_interrupted_upload",e)},ot.setCompletionHandler(this._completionHandler),this._pushOrphanUploads=e=>{let i=JSON.stringify(e);if(i!==this._lastOrphanPayload){this._lastOrphanPayload=i;try{this.pushEvent("orphan_uploads",e,()=>{})}catch{}}},this._startOrphanPushing=()=>{if(this._orphanInterval)return;let e=ot.orphanSnapshot();e.uploads.length===0&&e.queued_count===0||(this._lastOrphanPayload=null,this._pushOrphanUploads(e),this._orphanInterval=setInterval(()=>{let i=ot.orphanSnapshot(),n=i.uploads.some(s=>s.state==="uploading"||s.state==="finalizing");this._pushOrphanUploads(i),!n&&i.queued_count===0&&(clearInterval(this._orphanInterval),this._orphanInterval=null)},1e3))},this._startOrphanPushing(),this._uploadsInProgress=()=>this.el.dataset.uploading==="true"||ot.hasPending(),this._beforeUnload=e=>{this._uploadsInProgress()&&(e.preventDefault(),e.returnValue="")},this._showLeaveDialog=({title:e="Uploads in progress",body:i="Leaving now will cancel all ongoing uploads.",confirmLabel:n="Cancel Upload",cancelLabel:s="Stay on this page"}={})=>this._confirmDialog?Promise.resolve(!1):new Promise(r=>{let o=document.createElement("div");o.className="fixed inset-0 z-[1000] flex items-center justify-center bg-zinc-950/50 p-4",o.innerHTML=` 26 <div class="w-full max-w-md rounded-xl bg-white p-5 shadow-2xl ring-1 ring-zinc-200"> 27 <h3 class="text-base font-semibold text-zinc-900">${e}</h3> 28 <p class="mt-2 text-sm text-zinc-600"> 29 ${i} 30 </p> 31 <div class="mt-5 flex flex-col gap-2 sm:flex-row sm:justify-end"> 32 <button 33 type="button" 34 data-upload-guard-action="leave" 35 class="inline-flex justify-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white hover:bg-red-500" 36 > 37 ${n} 38 </button> 39 <button 40 type="button" 41 data-upload-guard-action="stay" 42 class="inline-flex justify-center rounded-md bg-emerald-600 px-3 py-2 text-sm font-semibold text-white hover:bg-emerald-500" 43 > 44 ${s} 45 </button> 46 </div> 47 </div> 48 `;let a=c=>{o.removeEventListener("click",l),document.removeEventListener("keydown",h),o.remove(),this._confirmDialog=null,r(c)},l=c=>{let d=c.target.closest("[data-upload-guard-action]");d&&a(d.dataset.uploadGuardAction==="leave")},h=c=>{c.key==="Escape"&&a(!1)};o.addEventListener("click",l),document.addEventListener("keydown",h),document.body.appendChild(o),this._confirmDialog=o}),this._blockNav=async e=>{if(this._navigating||!this._uploadsInProgress()||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;let n=e.target.closest("a[data-phx-link]");if(n&&n.target!=="_blank"&&(e.preventDefault(),e.stopImmediatePropagation(),await this._showLeaveDialog())){this._navigating=!0,ot.cancelAll();let s=!1,r=()=>{s||(s=!0,n.click())},o=setTimeout(r,150);this.pushEvent("cancel-all-uploads",{},()=>{clearTimeout(o),r()})}},window.addEventListener("beforeunload",this._beforeUnload),window.addEventListener("click",this._blockNav,!0),this._overlay=this.el.querySelector("[data-upload-drop-overlay]"),this._dragDepth=0,this._lastDragOver=0,this._dragWatchdog=null;let t=e=>e.dataTransfer&&Array.prototype.includes.call(e.dataTransfer.types||[],"Files");this._setOverlay=e=>{this._overlay&&(this._overlay.classList.toggle("hidden",!e),this._overlay.classList.toggle("flex",e),this._overlay.classList.toggle("pointer-events-auto",e),this._overlay.classList.toggle("pointer-events-none",!e),e?this._startDragWatchdog():this._stopDragWatchdog())},this._startDragWatchdog=()=>{this._dragWatchdog||(this._lastDragOver=Date.now(),this._dragWatchdog=setInterval(()=>{Date.now()-this._lastDragOver>600&&(this._dragDepth=0,this._setOverlay(!1))},400))},this._stopDragWatchdog=()=>{this._dragWatchdog&&(clearInterval(this._dragWatchdog),this._dragWatchdog=null)},this._dragEnter=e=>{t(e)&&(this._dragDepth++,this._setOverlay(!0))},this._dragLeave=e=>{t(e)&&(this._dragDepth=Math.max(0,this._dragDepth-1),this._dragDepth===0&&this._setOverlay(!1))},this._dragOver=e=>{t(e)&&(this._lastDragOver=Date.now(),e.preventDefault())},this._dragReset=e=>{this._dragDepth=0,this._setOverlay(!1),e.type==="drop"&&t(e)&&e.preventDefault()},window.addEventListener("dragenter",this._dragEnter),window.addEventListener("dragleave",this._dragLeave),window.addEventListener("dragover",this._dragOver),window.addEventListener("drop",this._dragReset),window.addEventListener("dragend",this._dragReset),this._cancelUploadClicks=e=>{let i=e.target.closest('[phx-click="cancel_upload"]');if(i){let n=i.getAttribute("phx-value-ref");n&&ot.cancel(n)}},this.el.addEventListener("click",this._cancelUploadClicks),this._confirmCancelAll=e=>{e.target.closest("[data-cancel-all-uploads]")&&(e.preventDefault(),e.stopImmediatePropagation(),this._showLeaveDialog({title:"Cancel all uploads?",body:"This will stop every upload currently in progress or queued.",confirmLabel:"Cancel all uploads",cancelLabel:"Keep uploading"}).then(n=>
48{n&&(ot.cancelAll(),this.pushEvent("cancel-all-uploads",{}))}))},this.el.addEventListener("click",this._confirmCancelAll,!0)},reconnected(){this._lastOrphanPayload=null,this._startOrphanPushing&&this._startOrphanPushing()},destroyed(){ot.setDuplicateHandler(null),ot.clearCompletionHandler(this._completionHandler),this._orphanInterval&&(clearInterval(this._orphanInterval),this._orphanInterval=null),this._dragWatchdog&&(clearInterval(this._dragWatchdog),this._dragWatchdog=null),window.removeEventListener("beforeunload",this._beforeUnload),window.removeEventListener("click",this._blockNav,!0),window.removeEventListener("dragenter",this._dragEnter),window.removeEventListener("dragleave",this._dragLeave),window.removeEventListener("dragover",this._dragOver),window.removeEventListener("drop",this._dragReset),window.removeEventListener("dragend",this._dragReset),this._cancelUploadClicks&&this.el.removeEventListener("click",this._cancelUploadClicks),this._confirmCancelAll&&this.el.removeEventListener("click",this._confirmCancelAll,!0),this._confirmDialog&&(this._confirmDialog.remove(),this._confirmDialog=null)}},jo=Ed;var Sd={mounted(){this.pendingSubmit=!1,this.createModal();let t=this.el.querySelector("button");t&&t.addEventListener("click",()=>this.showModal()),window.addEventListener("feedback:open",()=>this.showModal()),this.handleEvent("feedback:close_modal",()=>{this.pendingSubmit=!1,this.hideModal();let e=document.getElementById("feedback-form"),i=document.getElementById("feedback-submit-btn");e&&e.reset(),i&&(i.disabled=!1,i.textContent="Send Feedback")}),this.handleEvent("feedback:error",()=>{this.pendingSubmit=!1;let e=document.getElementById("feedback-submit-btn");e&&(e.disabled=!1,e.textContent="Send Feedback")})},createModal(){if(document.getElementById("feedback-modal-backdrop"))return;document.body.insertAdjacentHTML("beforeend",` 49 <div id="feedback-modal-backdrop" class="hidden fixed inset-0 z-50 overflow-y-auto" role="dialog" aria-modal="true"> 50 <div class="flex min-h-screen items-center justify-center p-4"> 51 <div id="feedback-backdrop-overlay" class="fixed inset-0 bg-zinc-900/50 transition-opacity"></div> 52 <div class="relative w-full max-w-md transform rounded-xl bg-white shadow-xl transition-all dark:bg-zinc-900"> 53 <div class="p-6"> 54 <h3 class="text-lg font-semibold text-zinc-900 dark:text-white mb-1">Send Feedback</h3> 55 <p class="text-sm text-zinc-600 dark:text-zinc-400 mb-4">Help us improve CloudRadio with your suggestions</p> 56 57 <div class="rounded-xl border border-blue-200 bg-blue-50 p-4 mb-6 dark:bg-blue-900/20 dark:border-blue-800"> 58 <div class="flex items-start gap-3"> 59 <div class="flex-shrink-0"> 60 <svg class="h-5 w-5 text-blue-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"> 61 <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clip-rule="evenodd" /> 62 </svg> 63 </div> 64 <div class="text-sm text-blue-700 dark:text-blue-300"> 65 Need help? For support requests, please use our 66 <a href="https://www.cloudrad.io/contact" target="_blank" rel="noopener noreferrer" class="font-medium underline hover:text-blue-800 dark:hover:text-blue-200">contact form</a>. 67 </div> 68 </div> 69 </div> 70 71 <form id="feedback-form"> 72 <input type="hidden" name="source_url" id="feedback-source-url" value="" /> 73 <div class="mb-4"> 74 <label for="feedback-subject" class="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Subject</label> 75 <input type="text" id="feedback-subject" name="subject" required maxlength="200" placeholder="Brief summary of your feedback" class="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm shadow-sm focus:border-brand-500 focus:ring-1 focus:ring-brand-500 dark:bg-zinc-800 dark:border-zinc-700 dark:text-white" /> 76 </div> 77 <div class="mb-6"> 78 <label for="feedback-message" class="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Message</label> 79 <textarea id="feedback-message" name="message" required maxlength="5000" rows="5" placeholder="Describe your idea or suggestion..." class="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm shadow-sm focus:border-brand-500 focus:ring-1 focus:ring-brand-500 dark:bg-zinc-800 dark:border-zinc-700 dark:text-white"></textarea> 80 <p class="mt-1 text-xs text-zinc-500 dark:text-zinc-400">Minimum 10 characters</p> 81 </div> 82 <div class="flex justify-end gap-3"> 83 <button type="button" id="feedback-cancel-btn" class="rounded-lg border border-zinc-300 px-4 py-2 text-sm font-medium text-zinc-700 hover:bg-zinc-50 dark:border-zinc-600 dark:text-zinc-300 dark:hover:bg-zinc-800">Cancel</button> 84 <button type="submit" id="feedback-submit-btn" class="rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2">Send Feedback</button> 85 </div> 86 </form> 87 </div> 88 </div> 89 </div> 90 </div> 91 `);let e=document.getElementById("feedback-backdrop-overlay"),i=document.getElementById("feedback-cancel-btn"),n=document.getElementById("feedback-form");e&&e.addEventListener("click",()=>this.hideModal()),i&&i.addEventListener("click",()=>this.hideModal()),n&&n.addEventListener("submit",s=>this.handleSubmit(s))},showModal(){let t=document.getElementById("feedback-modal-backdrop"),e=d
91ocument.getElementById("feedback-source-url");e&&(e.value=window.location.pathname),t&&t.classList.remove("hidden")},hideModal(){let t=document.getElementById("feedback-modal-backdrop");t&&t.classList.add("hidden")},handleSubmit(t){if(t.preventDefault(),this.pendingSubmit)return;let e=t.target,i=document.getElementById("feedback-submit-btn"),n=new FormData(e),s={subject:n.get("subject"),message:n.get("message"),source_url:n.get("source_url")};this.pendingSubmit=!0,i&&(i.disabled=!0,i.textContent="Submitting..."),this.pushEvent("submit_feedback",s)},destroyed(){let t=document.getElementById("feedback-modal-backdrop");t&&t.remove()}},qo=Sd;function Cd(t,e,i){return(e=xd(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Xt(){return Xt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)({}).hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},Xt.apply(null,arguments)}function zo(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),i.push.apply(i,n)}return i}function $t(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?zo(Object(i),!0).forEach(function(n){Cd(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):zo(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}function kd(t,e){if(t==null)return{};var i,n,s=_d(t,e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(n=0;n<r.length;n++)i=r[n],e.indexOf(i)===-1&&{}.propertyIsEnumerable.call(t,i)&&(s[i]=t[i])}return s}function _d(t,e){if(t==null)return{};var i={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(e.indexOf(n)!==-1)continue;i[n]=t[n]}return i}function Ad(t,e){if(typeof t!="object"||!t)return t;var i=t[Symbol.toPrimitive];if(i!==void 0){var n=i.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xd(t){var e=Ad(t,"string");return typeof e=="symbol"?e:e+""}function bs(t){"@babel/helpers - typeof";return bs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bs(t)}var Td="1.15.7";function Kt(t){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(t)}var Gt=Kt(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),bi=Kt(/Edge/i),Vo=Kt(/firefox/i),fi=Kt(/safari/i)&&!Kt(/chrome/i)&&!Kt(/android/i),Cs=Kt(/iP(ad|od|hone)/i),Qo=Kt(/chrome/i)&&Kt(/android/i),ta={capture:!1,passive:!1};function D(t,e,i){t.addEventListener(e,i,!Gt&&ta)}function P(t,e,i){t.removeEventListener(e,i,!Gt&&ta)}function ln(t,e){if(e){if(e[0]===">"&&(e=e.substring(1)),t)try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch{return!1}return!1}}function ea(t){return t.host&&t!==document&&t.host.nodeType&&t.host!==t?t.host:t.parentNode}function Dt(t,e,i,n){if(t){i=i||document;do{if(e!=null&&(e[0]===">"?t.parentNode===i&&ln(t,e):ln(t,e))||n&&t===i)return t;if(t===i)break}while(t=ea(t))}return null}var Wo=/\s+/g;function yt(t,e,i){if(t&&e)if(t.classList)t.classList[i?"add":"remove"](e);else{var n=(" "+t.className+" ").replace(Wo," ").replace(" "+e+" "," ");t.className=(n+(i?" "+e:"")).replace(Wo," ")}}function C(t,e,i){var n=t&&t.style;if(n){if(i===void 0)return document.defaultView&&document.defaultView.getComputedStyle?i=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(i=t.currentStyle),e===void 0?i:i[e];!(e in n)&&e.indexOf("webkit")===-1&&(e="-webkit-"+e),n[e]=i+(typeof i=="string"?"":"px")}}function qe(t,e){var i="";if(typeof t=="string")i=t;else do{var n=C(t,"transform");n&&n!=="none"&&(i=n+" "+i)}while(!e&&(t=t.parentNode));var s=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return s&&new s(i)}function ia(t,e,i){if(t){var n=t.getElementsByTagName(e),s=0,r=n.length;if(i)for(;s<r;s++)i(n[s],s);return n}return[]}function Bt(){var t=document.scrollingElement;return t||document.documentElement}function Y(t,e,i,n,s){if(!(!t.getBoundingClientRect&&t!==window)){var r,o,a,l,h,c,d;
vendor: 4,907 bytes, line 91
91if(t!==window&&t.parentNode&&t!==Bt()?(r=t.getBoundingClientRect(),o=r.top,a=r.left,l=r.bottom,h=r.right,c=r.height,d=r.width):(o=0,a=0,l=window.innerHeight,h=window.innerWidth,c=window.innerHeight,d=window.innerWidth),(e||i)&&t!==window&&(s=s||t.parentNode,!Gt))do if(s&&s.getBoundingClientRect&&(C(s,"transform")!=="none"||i&&C(s,"position")!=="static")){var m=s.getBoundingClientRect();o-=m.top+parseInt(C(s,"border-top-width")),a-=m.left+parseInt(C(s,"border-left-width")),l=o+r.height,h=a+r.width;break}while(s=s.parentNode);if(n&&t!==window){var p=qe(s||t),u=p&&p.a,v=p&&p.d;p&&(o/=v,a/=u,d/=u,c/=v,l=o+c,h=a+d)}return{top:o,left:a,bottom:l,right:h,width:d,height:c}}}function Ko(t,e,i){for(var n=oe(t,!0),s=Y(t)[e];n;){var r=Y(n)[i],o=void 0;if(i==="top"||i==="left"?o=s>=r:o=s<=r,!o)return n;if(n===Bt())break;n=oe(n,!1)}return!1}function ze(t,e,i,n){for(var s=0,r=0,o=t.children;r<o.length;){if(o[r].style.display!=="none"&&o[r]!==k.ghost&&(n||o[r]!==k.dragged)&&Dt(o[r],i.draggable,t,!1)){if(s===e)return o[r];s++}r++}return null}function ks(t,e){for(var i=t.lastElementChild;i&&(i===k.ghost||C(i,"display")==="none"||e&&!ln(i,e));)i=i.previousElementSibling;return i||null}function Ct(t,e){var i=0;if(!t||!t.parentNode)return-1;for(;t=t.previousElementSibling;)t.nodeName.toUpperCase()!=="TEMPLATE"&&t!==k.clone&&(!e||ln(t,e))&&i++;return i}function Xo(t){var e=0,i=0,n=Bt();if(t)do{var s=qe(t),r=s.a,o=s.d;e+=t.scrollLeft*r,i+=t.scrollTop*o}while(t!==n&&(t=t.parentNode));return[e,i]}function Md(t,e){for(var i in t)if(t.hasOwnProperty(i)){for(var n in e)if(e.hasOwnProperty(n)&&e[n]===t[i][n])return Number(i)}return-1}function oe(t,e){if(!t||!t.getBoundingClientRect)return Bt();var i=t,n=!1;do if(i.clientWidth<i.scrollWidth||i.clientHeight<i.scrollHeight){var s=C(i);if(i.clientWidth<i.scrollWidth&&(s.overflowX=="auto"||s.overflowX=="scroll")||i.clientHeight<i.scrollHeight&&(s.overflowY=="auto"||s.overflowY=="scroll")){if(!i.getBoundingClientRect||i===document.body)return Bt();if(n||e)return i;n=!0}}while(i=i.parentNode);return Bt()}function Pd(t,e){if(t&&e)for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}function hs(t,e){return Math.round(t.top)===Math.round(e.top)&&Math.round(t.left)===Math.round(e.left)&&Math.round(t.height)===Math.round(e.height)&&Math.round(t.width)===Math.round(e.width)}var pi;function na(t,e){return function(){if(!pi){var i=arguments,n=this;i.length===1?t.call(n,i[0]):t.apply(n,i),pi=setTimeout(function(){pi=void 0},e)}}}function Id(){clearTimeout(pi),pi=void 0}function sa(t,e,i){t.scrollLeft+=e,t.scrollTop+=i}function ra(t){var e=window.Polymer,i=window.jQuery||window.Zepto;return e&&e.dom?e.dom(t).cloneNode(!0):i?i(t).clone(!0)[0]:t.cloneNode(!0)}function oa(t,e,i){var n={};return Array.from(t.children).forEach(function(s){var r,o,a,l;if(!(!Dt(s,e.draggable,t,!1)||s.animated||s===i)){var h=Y(s);n.left=Math.min((r=n.left)!==null&&r!==void 0?r:1/0,h.left),n.top=Math.min((o=n.top)!==null&&o!==void 0?o:1/0,h.top),n.right=Math.max((a=n.right)!==null&&a!==void 0?a:-1/0,h.right),n.bottom=Math.max((l=n.bottom)!==null&&l!==void 0?l:-1/0,h.bottom)}}),n.width=n.right-n.left,n.height=n.bottom-n.top,n.x=n.left,n.y=n.top,n}var ft="Sortable"+new Date().getTime();function Dd(){var t=[],e;return{captureAnimationState:function(){if(t=[],!!this.options.animation){var n=[].slice.call(this.el.children);n.forEach(function(s){if(!(C(s,"display")==="none"||s===k.ghost)){t.push({target:s,rect:Y(s)});var r=$t({},t[t.length-1].rect);if(s.thisAnimationDuration){var o=qe(s,!0);o&&(r.top-=o.f,r.left-=o.e)}s.fromRect=r}})}},addAnimationState:function(n){t.push(n)},removeAnimationState:function(n){t.splice(Md(t,{target:n}),1)},animateAll:function(n){var s=this;if(!this.options.animation){clearTimeout(e),typeof n=="function"&&n();return}var r=!1,o=0;t.forEach(function(a){var l=0,h=a.target,c=h.fromRect,d=Y(h),m=h.prevFromRect,p=h.prevToRect,u=a.rect,v=qe(h,!0);v&&(d.top-=v.f,d.left-=v.e),h.toRect=d,h.thisAnimationDuration&&hs(m,d)&&!hs(c,d)&&(u.top-d.top)/(u.left-d.left)===(c.top-d.top)/(c.left-d.left)&&(l=Rd(u,m,p,s.options)),hs(d,c)||(h.prevFromRect=c,h.prevToRect=d,l||(l=s.options.animation),s.animate(h,u,d,l)),l&&(r=!0,o=Math.max(o,l),clearTimeout(h.animationResetTimer),h.animationResetTimer=setTimeout(function(){h.animationTime=0,h.prevFromRect=null,h.fromRect=null,h.prevToRect=null,h.thisAnimationDuration=null},l),h.thisAnimationDuration=l)}),clearTimeout(e),r?e=setTimeout(function(){typeof n=="function"&&n()},o):typeof n=="function"&&n(),t=[]},animate:function(n,s,r,o){if(o){C(n,"transition",""),C(n,"transform","");var a=qe(this.el),l=a&&a.a,h=a&&a.d,c=(s.left-r.left)/(l||1),d=(s.top-r.top)/(h||1);n.animatingX=!!c,n.animatingY=!!d,C(n,"transform","translate3d("+c+"px,"+d+"px,0)"),this.forRepaintDummy=Ld(n),C(n,"transition","transform "+o+"ms"+(this.options.easing?" "+this.options.easing:"")),C(n,"transform","translate3d(0,
910,0)"),typeof n.animated=="number"&&clearTimeout(n.animated),n.animated=setTimeout(function(){C(n,"transition",""),C(n,"transform",""),n.animated=!1,n.animatingX=!1,n.animatingY=!1},o)}}}}function Ld(t){return t.offsetWidth}function Rd(t,e,i,n){return Math.sqrt(Math.pow(e.top-t.top,2)+Math.pow(e.left-t.left,2))/Math.sqrt(Math.pow(e.top-i.top,2)+Math.pow(e.left-i.left,2))*n.animation}var Ue=[],cs={initializeByDefault:!0},yi={mount:function(e){for(var i in cs)cs.hasOwnProperty(i)&&!(i in e)&&(e[i]=cs[i]);Ue.forEach(function(n){if(n.pluginName===e.pluginName)throw"Sortable: Cannot mount plugin ".concat(e.pluginName," more than once")}),Ue.push(e)},pluginEvent:function(e,i,n){var s=this;this.eventCanceled=!1,n.cancel=function(){s.eventCanceled=!0};var r=e+"Global";Ue.forEach(function(o){i[o.pluginName]&&(i[o.pluginName][r]&&i[o.pluginName][r]($t({sortable:i},n)),i.options[o.pluginName]&&i[o.pluginName][e]&&i[o.pluginName][e]($t({sortable:i},n)))})},initializePlugins:function(e,i,n,s){Ue.forEach(function(a){var l=a.pluginName;if(!(!e.options[l]&&!a.initializeByDefault)){var h=new a(e,i,e.options);h.sortable=e,h.options=e.options,e[l]=h,Xt(n,h.defaults)}});for(var r in e.options)if(e.options.hasOwnProperty(r)){var o=this.modifyOption(e,r,e.options[r]);typeof o<"u"&&(e.options[r]=o)}},getEventProperties:function(e,i){var n={};return Ue.forEach(function(s){typeof s.eventProperties=="function"&&Xt(n,s.eventProperties.call(i[s.pluginName],e))}),n},modifyOption:function(e,i,n){var s;return Ue.forEach(function(r){e[r.pluginName]&&r.optionListeners&&typeof r.optionListeners[i]=="function"&&(s=r.optionListeners[i].call(e[r.pluginName],n))}),s}};function Od(t){var e=t.sortable,i=t.rootEl,n=t.name,s=t.targetEl,r=t.cloneEl,o=t.toEl,a=t.from
vendor: 1,718 bytes, line 91
91El,l=t.oldIndex,h=t.newIndex,c=t.oldDraggableIndex,d=t.newDraggableIndex,m=t.originalEvent,p=t.putSortable,u=t.extraEventProperties;if(e=e||i&&i[ft],!!e){var v,y=e.options,M="on"+n.charAt(0).toUpperCase()+n.substr(1);window.CustomEvent&&!Gt&&!bi?v=new CustomEvent(n,{bubbles:!0,cancelable:!0}):(v=document.createEvent("Event"),v.initEvent(n,!0,!0)),v.to=o||i,v.from=a||i,v.item=s||i,v.clone=r,v.oldIndex=l,v.newIndex=h,v.oldDraggableIndex=c,v.newDraggableIndex=d,v.originalEvent=m,v.pullMode=p?p.lastPutMode:void 0;var L=$t($t({},u),yi.getEventProperties(n,e));for(var H in L)v[H]=L[H];i&&i.dispatchEvent(v),y[M]&&y[M].call(e,v)}}var Hd=["evt"],ut=function(e,i){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=n.evt,r=kd(n,Hd);yi.pluginEvent.bind(k)(e,i,$t({dragEl:b,parentEl:V,ghostEl:x,rootEl:$,nextEl:_e,lastDownEl:sn,cloneEl:z,cloneHidden:re,dragStarted:ci,putSortable:tt,activeSortable:k.active,originalEvent:s,oldIndex:je,oldDraggableIndex:mi,newIndex:wt,newDraggableIndex:se,hideGhostForTarget:ca,unhideGhostForTarget:da,cloneNowHidden:function(){re=!0},cloneNowShown:function(){re=!1},dispatchSortableEvent:function(a){at({sortable:i,name:a,originalEvent:s})}},r))};function at(t){Od($t({putSortable:tt,cloneEl:z,targetEl:b,rootEl:$,oldIndex:je,oldDraggableIndex:mi,newIndex:wt,newDraggableIndex:se},t))}var b,V,x,$,_e,sn,z,re,je,wt,mi,se,Qi,tt,$e=!1,hn=!1,cn=[],Ce,It,ds,us,Go,Jo,ci,Be,gi,vi=!1,tn=!1,rn,nt,fs=[],ys=!1,dn=[],fn=typeof document<"u",en=Cs,Yo=bi||Gt?"cssFloat":"float",Fd=fn&&!Qo&&!Cs&&"draggable"in document.createElement("div"),aa=function(){if(fn){if(Gt)return!1;var t=document.createElement("x");return t.style.cssText="pointer-events:auto",t.style.pointerEvents==="auto"}}
vendor: 18,995 bytes, line 91
91(),la=function(e,i){var n=C(e),s=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),r=ze(e,0,i),o=ze(e,1,i),a=r&&C(r),l=o&&C(o),h=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+Y(r).width,c=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+Y(o).width;if(n.display==="flex")return n.flexDirection==="column"||n.flexDirection==="column-reverse"?"vertical":"horizontal";if(n.display==="grid")return n.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(r&&a.float&&a.float!=="none"){var d=a.float==="left"?"left":"right";return o&&(l.clear==="both"||l.clear===d)?"vertical":"horizontal"}return r&&(a.display==="block"||a.display==="flex"||a.display==="table"||a.display==="grid"||h>=s&&n[Yo]==="none"||o&&n[Yo]==="none"&&h+c>s)?"vertical":"horizontal"},Nd=function(e,i,n){var s=n?e.left:e.top,r=n?e.right:e.bottom,o=n?e.width:e.height,a=n?i.left:i.top,l=n?i.right:i.bottom,h=n?i.width:i.height;return s===a||r===l||s+o/2===a+h/2},Ud=function(e,i){var n;return cn.some(function(s){var r=s[ft].options.emptyInsertThreshold;if(!(!r||ks(s))){var o=Y(s),a=e>=o.left-r&&e<=o.right+r,l=i>=o.top-r&&i<=o.bottom+r;if(a&&l)return n=s}}),n},ha=function(e){function i(r,o){return function(a,l,h,c){var d=a.options.group.name&&l.options.group.name&&a.options.group.name===l.options.group.name;if(r==null&&(o||d))return!0;if(r==null||r===!1)return!1;if(o&&r==="clone")return r;if(typeof r=="function")return i(r(a,l,h,c),o)(a,l,h,c);var m=(o?a:l).options.group.name;return r===!0||typeof r=="string"&&r===m||r.join&&r.indexOf(m)>-1}}var n={},s=e.group;(!s||bs(s)!="object")&&(s={name:s}),n.name=s.name,n.checkPull=i(s.pull,!0),n.checkPut=i(s.put),n.revertClone=s.revertClone,e.group=n},ca=function(){!aa&&x&&C(x,"display","none")},da=function(){!aa&&x&&C(x,"display","")};fn&&!Qo&&document.addEventListener("click",function(t){if(hn)return t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),hn=!1,!1},!0);var ke=function(e){if(b){e=e.touches?e.touches[0]:e;var i=Ud(e.clientX,e.clientY);if(i){var n={};for(var s in e)e.hasOwnProperty(s)&&(n[s]=e[s]);n.target=n.rootEl=i,n.preventDefault=void 0,n.stopPropagation=void 0,i[ft]._onDragOver(n)}}},Bd=function(e){b&&b.parentNode[ft]._isOutsideThisEl(e.target)};function k(t,e){if(!(t&&t.nodeType&&t.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=Xt({},e),t[ft]=this;var i={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return la(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(o,a){o.setData("Text",a.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:k.supportPointer!==!1&&"PointerEvent"in window&&(!fi||Cs),emptyInsertThreshold:5};yi.initializePlugins(this,t,i);for(var n in i)!(n in e)&&(e[n]=i[n]);ha(e);for(var s in this)s.charAt(0)==="_"&&typeof this[s]=="function"&&(this[s]=this[s].bind(this));this.nativeDraggable=e.forceFallback?!1:Fd,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?D(t,"pointerdown",this._onTapStart):(D(t,"mousedown",this._onTapStart),D(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(D(t,"dragover",this),D(t,"dragenter",this)),cn.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),Xt(this,Dd())}k.prototype={constructor:k,_isOutsideThisEl:function(e){!this.el.contains(e)&&e!==this.el&&(Be=null)},_getDirection:function(e,i){return typeof this.options.direction=="function"?this.options.direction.call(this,e,i,b):this.options.direction},_onTapStart:function(e){if(e.cancelable){var i=this,n=this.el,s=this.options,r=s.preventOnFilter,o=e.type,a=e.touches&&e.touches[0]||e.pointerType&&e.pointerType==="touch"&&e,l=(a||e).target,h=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=s.filter;if(Xd(n),!b&&!(/mousedown|pointerdown/.test(o)&&e.button!==0||s.disabled)&&!h.isContentEditable&&!(!this.nativeDraggable&&fi&&l&&l.tagName.toUpperCase()==="SELECT")&&(l=Dt(l,s.draggable,n,!1),!(l&&l.animated)&&sn!==l)){if(je=Ct(l),mi=Ct(l,s.draggable),typeof c=="function"){if(c.call(this,e,l,this)){at({sortable:i,rootEl:h,name:"filter",targetEl:l,toEl:n,fromEl:n}),ut("filter",i,{evt:e}),r&&e.preventDefault();return}}else if(c&&(c=c.split(",").some(function(d){if(d=Dt(h,d.trim(),n,!1),d)return at({sortable:i,rootEl:d,name:"filter",targetEl:l,fromEl:n,toEl:n}),ut("filter",i,{evt:e}),!0}),c)){r&&e.preventDefault();return}s.handle&&!Dt(h,s.handle,n,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(e,i,n){var s=this,r=s.el,o=s.options,a=r.ownerDocument,l;if(n&&!b&&n.parentNode===r){var h=Y(n);if($=r,b=n,V=b.parentNode,_e=b.nextSibling,sn=n,Qi=o.group,k.dragged=b,Ce={target:b,clientX:(i||e).clientX,clientY:(i||e).clientY},Go=Ce.clientX-h.left,Jo=Ce.clientY-h.top,this._lastX=(i||e).clientX,this._lastY=(i||e).clientY,b.style["will-change"]="all",l=function(){if(ut("delayEnded",s,{evt:e}),k.eventCanceled){s._onDrop();return}s._disableDelayedDragEvents(),!Vo&&s.nativeDraggable&&(b.draggable=!0),s._triggerDragStart(e,i),at({sortable:s,name:"choose",originalEvent:e}),yt(b,o.chosenClass,!0)},o.ignore.split(",").forEach(function(c){ia(b,c.trim(),ps)}),D(a,"dragover",ke),D(a,"mousemove",ke),D(a,"touchmove",ke),o.supportPointer?(D(a,"pointerup",s._onDrop),!this.nativeDraggable&&D(a,"pointercancel",s._onDrop)):(D(a,"mouseup",s._onDrop),D(a,"touchend",s._onDrop),D(a,"touchcancel",s._onDrop)),Vo&&this.nativeDraggable&&(this.options.touchStartThreshold=4,b.draggable=!0),ut("delayStart",this,{evt:e}),o.delay&&(!o.delayOnTouchOnly||i)&&(!this.nativeDraggable||!(bi||Gt))){if(k.eventCanceled){this._onDrop();return}o.supportPointer?(D(a,"pointerup",s._disableDelayedDrag),D(a,"pointercancel",s._disableDelayedDrag)):(D(a,"mouseup",s._disableDelayedDrag),D(a,"touchend",s._disableDelayedDrag),D(a,"touchcancel",s._disableDelayedDrag)),D(a,"mousemove",s._delayedDragTouchMoveHandler),D(a,"touchmove",s._delayedDragTouchMoveHandler),o.supportPointer&&D(a,"pointermove",s._delayedDragTouchMoveHandler),s._dragStartTimer=setTimeout(l,o.delay)}else l()}},_delayedDragTouchMoveHandler:function(e){var i=e.touches?e.touches[0]:e;Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){b&&ps(b),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var e=this.el.ownerDocument;P(e,"mouseup",this._disableDelayedDrag),P(e,"touchend",this._disableDelayedDrag),P(e,"touchcancel",this._disableDelayedDrag),P(e,"pointerup",this._disableDelayedDrag),P(e,"pointercancel",this._disableDelayedDrag),P(e,"mousemove",this._delayedDragTouchMoveHandler),P(e,"touchmove",this._delayedDragTouchMoveHandler),P(e,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(e,i){i=i||e.pointerType=="touch"&&e,!this.nativeDraggable||i?this.options.supportPointer?D(document,"pointermove",this._onTouchMove):i?D(document,"touchmove",this._onTouchMove):D(document,"mousemove",this._onTouchMove):(D(b,"dragend",this),D($,"dragstart",this._onDragStart));try{document.selection?on(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(e,i){if($e=!1,$&&b){ut("dragStarted",this,{evt:i}),this.nativeDraggable&&D(document,"dragover",Bd);var n=this.options;!e&&yt(b,n.dragClass,!1),yt(b,n.ghostClass,!0),k.active=this,e&&this._appendGhost(),at({sortable:this,name:"start",originalEvent:i})}else this._nulling()},_emulateDragOver:function(){if(It){this._lastX=It.clientX,this._lastY=It.clientY,ca();for(var e=document.elementFromPoint(It.clientX,It.clientY),i=e;e&&e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(It.clientX,It.clientY),e!==i);)i=e;if(b.parentNode[ft]._isOutsideThisEl(e),i)do{if(i[ft]){var n=void 0;if(n=i[ft]._onDragOver({clientX:It.clientX,clientY:It.clientY,target:e,rootEl:i}),n&&!this.options.dragoverBubble)break}e=i}while(i=ea(i));da()}},_onTouchMove:function(e){if(Ce){var i=this.options,n=i.fallbackTolerance,s=i.fallbackOffset,r=e.touches?e.touches[0]:e,o=x&&qe(x,!0),a=x&&o&&o.a,l=x&&o&&o.d,h=en&&nt&&Xo(nt),c=(r.clientX-Ce.clientX+s.x)/(a||1)+(h?h[0]-fs[0]:0)/(a||1),d=(r.clientY-Ce.clientY+s.y)/(l||1)+(h?h[1]-fs[1]:0)/(l||1);if(!k.active&&!$e){if(n&&Math.max(Math.abs(r.clientX-this._lastX),Math.abs(r.clientY-this._lastY))<n)return;this._onDragStart(e,!0)}if(x){o?(o.e+=c-(ds||0),o.f+=d-(us||0)):o={a:1,b:0,c:0,d:1,e:c,f:d};var m="matrix(".concat(o.a,",").concat(o.b,",").concat(o.c,",").concat(o.d,",").concat(o.e,",").concat(o.f,")");C(x,"webkitTransform",m),C(x,"mozTransform",m),C(x,"msTransform",m),C(x,"transform",m),ds=c,us=d,It=r}e.cancelable&&e.preventDefault()}},_appendGhost:function(){if(!x){var e=this.options.fallbackOnBody?document.body:$,i=Y(b,!0,en,!0,e),n=this.options;if(en){for(nt=e;C(nt,"position")==="static"&&C(nt,"transform")==="none"&&nt!==document;)nt=nt.parentNode;nt!==document.body&&nt!==document.documentElement?(nt===document&&(nt=Bt()),i.top+=nt.scrollTop,i.left+=nt.scrollLeft):nt=Bt(),fs=Xo(nt)}x=b.cloneNode(!0),yt(x,n.ghostClass,!1),yt(x,n.fallbackClass,!0),yt(x,n.dragClass,!0),C(x,"transition",""),C(x,"transform",""),C(x,"box-sizing","border-box"),C(x,"margin",0),C(x,"top",i.top),C(x,"left",i.left),C(x,"width",i.width),C(x,"height",i.height),C(x,"opacity","0.8"),C(x,"position",en?"absolute":"fixed"),C(x,"zIndex","100000"),C(x,"pointerEvents","none"),k.ghost=x,e.appendChild(x),C(x,"transform-origin",Go/parseInt(x.style.width)*100+"% "+Jo/parseInt(x.style.height)*100+"%")}},_onDragStart:function(e,i){var n=this,s=e.dataTransfer,r=n.options;if(ut("dragStart",this,{evt:e}),k.eventCanceled){this._onDrop();return}ut("setupClone",this),k.eventCanceled||(z=ra(b),z.removeAttribute("id"),z.draggable=!1,z.style["will-change"]="",this._hideClone(),yt(z,this.options.chosenClass,!1),k.clone=z),n.cloneId=on(function(){ut("clone",n),!k.eventCanceled&&(n.options.removeCloneOnHide||$.insertBefore(z,b),n._hideClone(),at({sortable:n,name:"clone"}))}),!i&&yt(b,r.dragClass,!0),i?(hn=!0,n._loopId=setInterval(n._emulateDragOver,50)):(P(document,"mouseup",n._onDrop),P(document,"touchend",n._onDrop),P(document,"touchcancel",n._onDrop),s&&(s.effectAllowed="move",r.setData&&r.setData.call(n,s,b)),D(document,"drop",n),C(b,"transform","translateZ(0)")),$e=!0,n._dragStartId=on(n._dragStarted.bind(n,i,e)),D(document,"selectstart",n),ci=!0,window.getSelection().removeAllRanges(),fi&&C(document.body,"user-select","none")},_onDragOver:function(e){var i=this.el,n=e.target,s,r,o,a=this.options,l=a.group,h=k.active,c=Qi===l,d=a.sort,m=tt||h,p,u=this,v=!1;if(ys)return;function y(Lt,Si){ut(Lt,u,$t({evt:e,isOwner:c,axis:p?"vertical":"horizontal",revert:o,dragRect:s,targetRect:r,canSort:d,fromSortable:m,target:n,completed:L,onMove:function(A,F){return nn($,i,b,s,A,Y(A),e,F)},changed:H},Si))}function M(){y("dragOverAnimationCapture"),u.captureAnimationState(),u!==m&&m.captureAnimationState()}function L(Lt){return y("dragOverCompleted",{insertion:Lt}),Lt&&(c?h._hideClone():h._showClone(u),u!==m&&(yt(b,tt?tt.options.ghostClass:h.options.ghostClass,!1),yt(b,a.ghostClass,!0)),tt!==u&&u!==k.active?tt=u:u===k.active&&tt&&(tt=null),m===u&&(u._ignoreWhileAnimating=n),u.animateAll(function(){y("dragOverAnimationComplete"),u._ignoreWhileAnimating=null}),u!==m&&(m.animateAll(),m._ignoreWhileAnimating=null)),(n===b&&!b.animated||n===i&&!n.animated)&&(Be=null),!a.dragoverBubble&&!e.rootEl&&n!==document&&(b.parentNode[ft]._isOutsideThisEl(e.target),!Lt&&ke(e)),!a.dragoverBubble&&e.stopPropagation&&e.stopPropagation(),v=!0}function H(){wt=Ct(b),se=Ct(b,a.draggable),at({sortable:u,name:"change",toEl:i,newIndex:wt,newDraggableIndex:se,originalEvent:e})}if(e.preventDefault!==void 0&&e.cancelable&&e.preventDefault(),n=Dt(n,a.draggable,i,!0),y("dragOver"),k.eventCanceled)return v;if(b.contains(e.target)||n.animated&&n.animatingX&&n.animatingY||u._ignoreWhileAnimating===n)return L(!1);if(hn=!1,h&&!a.disabled&&(c?d||(o=V!==$):tt===this||(this.lastPutMode=Qi.checkPull(this,h,b,e))&&l.checkPut(this,h,b,e))){if(p=this._getDirection(e,n)==="vertical",s=Y(b),y("dragOverValid"),k.eventCanceled)return v;if(o)return V=$,M(),this._hideClone(),y("revert"),k.eventCanceled||(_e?$.insertBefore(b,_e):$.appendChild(b)),L(!0);var R=ks(i,a.draggable);if(!R||zd(e,p,this)&&!R.animated){if(R===b)return L(!1);if(R&&i===e.target&&(n=R),n&&(r=Y(n)),nn($,i,b,s,n,r,e,!!n)!==!1)return M(),R&&R.nextSibling?i.insertBefore(b,R.nextSibling):i.appendChild(b),V=i,H(),L(!0)}else if(R&&qd(e,p,this)){var E=ze(i,0,a,!0);if(E===b)return L(!1);if(n=E,r=Y(n),nn($,i,b,s,n,r,e,!1)!==!1)return M(),i.insertBefore(b,E),V=i,H(),L(!0)}else if(n.parentNode===i){r=Y(n);var S=0,T,X=b.parentNode!==i,g=!Nd(b.animated&&b.toRect||s,n.animated&&n.toRect||r,p),w=p?"top":"left",j=Ko(n,"top","top")||Ko(b,"top","top"),G=j?j.scrollTop:void 0;Be!==n&&(T=r[w],vi=!1,tn=!g&&a.invertSwap||X),S=Vd(e,n,r,p,g?1:a.swapThreshold,a.invertedSwapThreshold==null?a.swapThreshold:a.invertedSwapThreshold,tn,Be===n);var U;if(S!==0){var ht=Ct(b);do ht-=S,U=V.children[ht];while(U&&(C(U,"display")==="none"||U===x))}if(S===0||U===n)return L(!1);Be=n,gi=S;var ct=n.nextElementSibling,_t=!1;_t=S===1;var W=nn($,i,b,s,n,r,e,_t);if(W!==!1)return(W===1||W===-1)&&(_t=W===1),ys=!0,setTimeout(jd,30),M(),_t&&!ct?i.appendChild(b):n.parentNode.insertBefore(b,_t?ct:n),j&&sa(j,0,G-j.scrollTop),V=b.parentNode,T!==void 0&&!tn&&(rn=Math.abs(T-Y(n)[w])),H(),L(!0)}if(i.contains(b))return L(!1)}return!1},_ignoreWhileAnimating:null,_offMoveEvents:function(){P(document,"mousemove",this._onTouchMove),P(document,"touchmove",this._onTouchMove),P(document,"pointermove",this._onTouchMove),P(document,"dragover",ke),P(document,"mousemove",ke),P(document,"touchmove",ke)},_offUpEvents:function(){var e=this.el.ownerDocument;P(e,"mouseup",this._onDrop),P(e,"touchend",this._onDrop),P(e,"pointerup",this._onDrop),P(e,"pointercancel",this._onDrop),P(e,"touchcancel",this._onDrop),P(document,"selectstart",this)},_onDrop:function(e){var i=this.el,n=this.options;if(wt=Ct(b),se=Ct(b,n.draggable),ut("drop",this,{evt:e}),V=b&&b.parentNode,wt=Ct(b),se=Ct(b,n.draggable),k.eventCanceled){this._nulling();return}$e=!1,tn=!1,vi=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),ws(this.cloneId),ws(this._dragStartId),this.nativeDraggable&&(P(document,"drop",this),P(i,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),fi&&C(document.body,"user-select",""),C(b,"transform",""),e&&(ci&&(e.cancelable&&e.preventDefault(),!n.dropBubble&&e.stopPropagation()),x&&x.parentNode&&x.parentNode.removeChild(x),($===V||tt&&tt.lastPutMode!=="clone")&&z&&z.parentNode&&z.parentNode.removeChild(z),b&&(this.nativeDraggable&&P(b,"dragend",this),ps(b),b.style["will-change"]="",ci&&!$e&&yt(b,tt?tt.options.ghostClass:this.options.ghostClass,!1),yt(b,this.options.chosenClass,!1),at({sortable:this,name:"unchoose",toEl:V,newIndex:null,newDraggableIndex:null,originalEvent:e}),$!==V?(wt>=0&&(at({rootEl:V,name:"add",toEl:V,fromEl:$,originalEvent:e}),at({sortable:this,name:"remove",toEl:V,originalEvent:e}),at({rootEl:V,name:"sort",toEl:V,fromEl:$,originalEvent:e}),at({sortable:this,name:"sort",toEl:V,originalEvent:e})),tt&&tt.save()):wt!==je&&wt>=0&&(at({sortable:this,name:"update",toEl:V,originalEvent:e}),at({sortable:this,name:"sort",toEl:V,originalEvent:e})),k.active&&((wt==null||wt===-1)&&(wt=je,se=mi),at({sortable:this,name:"end",toEl:V,originalEvent:e}),this.save()))),this._nulling()},_nulling:function(){ut("nulling",this),$=b=V=x=_e=z=sn=re=Ce=It=ci=wt=se=je=mi=Be=gi=tt=Qi=k.dragged=k.ghost=k.clone=k.active=null;var e=this.el;dn.forEach(function(i){e.contains(i)&&(i.checked=!0)}),dn.length=ds=us=0},handleEvent:function(e){switch(e.type){case"drop":case"dragend":this._onDrop(e);break;case"dragenter":case"dragover":b&&(this._onDragOver(e),$d(e));break;case"selectstart":e.preventDefault();break}},toArray:function(){for(var e=[],i,n=this.el.children,s=0,r=n.length,o=this.options;s<r;s++)i=n[s],Dt(i,o.draggable,this.el,!1)&&e.push(i.getAttribute(o.dataIdAttr)||Kd(i));return e},sort:function(e,i){var n={},s=this.el;this.toArray().forEach(function(r,o){var a=s.children[o];Dt(a,this.options.draggable,s,!1)&&(n[r]=a)},this),i&&this.captureAnimationState(),e.forEach(function(r){n[r]&&(s.removeChild(n[r]),s.appendChild(n[r]))}),i&&this.animateAll()},save:function(){var e=this.options.store;e&&e.set&&e.set(this)},closest:function(e,i){return Dt(e,i||this.options.draggable,this.el,!1)},option:function(e,i){var n=this.options;if(i===void 0)return n[e];var s=yi.modifyOption(this,e,i);typeof s<"u"?n[e]=s:n[e]=i,e==="group"&&ha(n)},destroy:function(){ut("destroy",this);var e=this.el;e[ft]=null,P(e,"mousedown",this._onTapStart),P(e,"touchstart",this._onTapStart),P(e,"pointerdown",this._onTapStart),this.nativeDraggable&&(P(e,"dragover",this),P(e,"dragenter",this)),Array.prototype.forEach.call(e.querySelectorAll("[draggable]"),function(i){i.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),cn.splice(cn.indexOf(this.el),1),this.el=e=null},_hideClone:function(){if(!re){if(ut("hideClone",this),k.eventCanceled)return;C(z,"display","none"),this.options.removeCloneOnHide&&z.parentNode&&z.parentNode.removeChild(z),re=!0}},_showClone:function(e){if(e.lastPutMode!=="clone"){this._hideClone();return}if(re){if(ut("showClone",this),k.eventCanceled)return;b.parentNode==$&&!this.options.group.revertClone?$.insertBefore(z,b):_e?$.insertBefore(z,_e):$.appendChild(z),this.options.group.revertClone&&this.animate(b,z),C(z,"display",""),re=!1}}};function $d(t){t.dataTransfer&&(t.dataTransfer.dropEffect="move"),t.cancelable&&t.preventDefault()}function nn(t,e,i,n,s,r,o,a){var l,h=t[ft],c=h.options.onMove,d;return window.CustomEvent&&!Gt&&!bi?l=new CustomEvent("move",{bubbles:!0,cancelable:!0}):(l=document.createEvent("Event"),l.initEvent("move",!0,!0)),l.to=e,l.from=t,l.dragged=i,l.draggedRect=n,l.related=s||e,l.relatedRect=r||Y(e),l.willInsertAfter=a,l.originalEvent=o,t.dispatchEvent(l),c&&(d=c.call(h,l,o)),d}function ps(t){t.draggable=!1}function jd(){ys=!1}function qd(t,e,i){var n=Y(ze(i.el,0,i.options,!0)),s=oa(i.el,i.options,x),r=10;return e?t.clientX<s.left-r||t.clientY<n.top&&t.clientX<n.right:t.clientY<s.top-r||t.clientY
91<n.bottom&&t.clientX<n.left}function zd(t,e,i){var n=Y(ks(i.el,i.options.draggable)),s=oa(i.el,i.options,x),r=10;return e?t.clientX>s.right+r||t.clientY>n.bottom&&t.clientX>n.left:t.clientY>s.bottom+r||t.clientX>n.right&&t.clientY>n.top}function Vd(t,e,i,n,s,r,o,a){var l=n?t.clientY:t.clientX,h=n?i.height:i.width,c=n?i.top:i.left,d=n?i.bottom:i.right,m=!1;if(!o){if(a&&rn<h*s){if(!vi&&(gi===1?l>c+h*r/2:l<d-h*r/2)&&(vi=!0),vi)m=!0;else if(gi===1?l<c+rn:l>d-rn)return-gi}else if(l>c+h*(1-s)/2&&l<d-h*(1-s)/2)return Wd(e)}return m=m||o,m&&(l<c+h*r/2||l>d-h*r/2)?l>c+h/2?1:-1:0}function Wd(t){return Ct(b)<Ct(t)?1:-1}function Kd(t){for(var e=t.tagName+t.className+t.src+t.href+t.textContent,i=e.length,n=0;i--;)n+=e.charCodeAt(i);return n.toString(36)}function Xd(t){dn.length=0;for(var e=t.getElementsByTagName("input"),i=e.length;i--;){var n=e[i];n.checked&&dn.push(n)}}function on(t){return setTimeout(t,0)}function ws(t){return clearTimeout(t)}fn&&D(document,"touchmove",function(t){(k.active||$e)&&t.cancelable&&t.preventDefault()});k.utils={on:D,off:P,css:C,find:ia,is:function(e,i){return!!Dt(e,i,e,!1)},extend:Pd,throttle:na,closest:Dt,toggleClass:yt,clone:ra,index:Ct,nextTick:on,cancelNextTick:ws,detectDirection:la,getChild:ze,expando:ft};k.get=function(t){return t[ft]};k.mount=function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];e[0].constructor===Array&&(e=e[0]),e.forEach(function(n){if(!n.prototype||!n.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(n));n.utils&&(k.utils=$t($t({},k.utils),n.utils)),yi.mount(n)})};k.create=function(t,e){return new k(t,e)};k.version=Td;var J=[],di,Es,Ss=!1,ms,gs,un,ui;function Gd(){function t(){this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0};for(var e in this)e.charAt(0)==="_"&&typeof this[e]=="function"&&(this[e]=this[e].bind(this))}return t.prototype={dragStarted:function(i){var n=i.originalEvent;this.sortable.nativeDraggable?D(document,"dragover",this._handleAutoScroll):this.options.supportPointer?D(document,"pointermove",this._handleFallbackAutoScroll):n.touches?D(document,"touchmove",this._handleFallbackAutoScroll):D(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(i){var n=i.originalEvent;!this.options.dragOverBubble&&!n.rootEl&&this._handleAutoScroll(n)},drop:function(){this.sortable.nativeDraggable?P(document,"dragover",this._handleAutoScroll):(P(document,"pointermove",this._handleFallbackAutoScroll),P(document,"touchmove",this._handleFallbackAutoScroll),P(document,"mousemove",this._handleFallbackAutoScroll)),Zo(),an(),Id()},nulling:function(){un=Es=di=Ss=ui=ms=gs=null,J.length=0},_handleFallbackAutoScroll:function(i){this._handleAutoScroll(i,!0)},_handleAutoScroll:function(i,n){var s=this,r=(i.touches?i.touches[0]:i).clientX,o=(i.touches?i.touches[0]:i).clientY,a=document.elementFromPoint(r,o);if(un=i,n||this.options.forceAutoScrollFallback||bi||Gt||fi){vs(i,this.options,a,n);var l=oe(a,!0);Ss&&(!ui||r!==ms||o!==gs)&&(ui&&Zo(),ui=setInterval(function(){var h=oe(document.elementFromPoint(r,o),!0);h!==l&&(l=h,an()),vs(i,s.options,h,n)},10),ms=r,gs=o)}else{if(!this.options.bubbleScroll||oe(a,!0)===Bt()){an();return}vs(i,this.options,oe(a,!1),!1)}}},Xt(t,{pluginName:"scroll",initializeByDefault:!0})}function an(){J.forEach(function(t){clearInterval(t.pid)}),J=[]}function Zo(){clearInterval(ui)}var vs=na(function(t,e,i,n){if(e.scroll){var s=(t.touches?t.touches[0]:t).clientX,r=(t.touches?t.touches[0]:t).clientY,o=e.scrollSensitivity,a=e.scrollSpeed,l=Bt(),h=!1,c;Es!==i&&(Es=i,an(),di=e.scroll,c=e.scrollFn,di===!0&&(di=oe(i,!0)));var d=0,m=di;do{var p=m,u=Y(p),v=u.top,y=u.bottom,M=u.left,L=u.right,H=u.width,R=u.height,E=void 0,S=void 0,T=p.scrollWidth,X=p.scrollHeight,g=C(p),w=p.scrollLeft,j=p.scrollTop;p===l?(E=H<T&&(g.overflowX==="auto"||g.overflowX==="scroll"||g.overflowX==="visible"),S=R<X&&(g.overflowY==="auto"||g.overflowY==="scroll"||g.overflowY==="visible")):(E=H<T&&(g.overflowX==="auto"||g.overflowX==="scroll"),S=R<X&&(g.overflowY==="auto"||g.overflowY==="scroll"));var G=E&&(Math.abs(L-s)<=o&&w+H<T)-(Math.abs(M-s)<=o&&!!w),U=S&&(Math.abs(y-r)<=o&&j+R<X)-(Math.abs(v-r)<=o&&!!j);if(!J[d])for(var ht=0;ht<=d;ht++)J[ht]||(J[ht]={});(J[d].vx!=G||J[d].vy!=U||J[d].el!==p)&&(J[d].el=p,J[d].vx=G,J[d].vy=U,clearInterval(J[d].pid),(G!=0||U!=0)&&(h=!0,J[d].pid=setInterval(function(){n&&this.layer===0&&k.active._onTouchMove(un);var ct=J[this.layer].vy?J[this.layer].vy*a:0,_t=J[this.layer].vx?J[this.layer].vx*a:0;typeof c=="function"&&c.call(k.dragged.parentNode[ft],_t,ct,t,un,J[this.layer].el)!=="continue"||sa(J[this.layer].el,_t,ct)}.bind({layer:d}),24))),d++}while(e.bubbleScroll&&m!==l&&(m=oe(m,!1)));Ss=h}},30),ua=function(e){var i=e.originalEvent,n=e.putSortable,s=e.dragEl,r=e.activeSortable,o=e.dispatchSortableEvent,a=e.hideGhostForTarget,l=e.unhideGhostForTarget;if(i){var h=n||r;a();var c=i.changedTouches&&i.changedTouches.length?i.changedTouches[0]:i,d=document.elementFromPoint(c.clientX,c.clientY);l(),h&&!h.el.contains(d)&&(o("spill"),this.onSpill({dragEl:s,putSortable:n}))}};function _s(){}_s.prototype={startIndex:null,dragStart:function(e){var i=e.oldDraggableIndex;this.startIndex=i},onSpill:function(e){var i=e.dragEl,n=e.putSortable;this.sortable.captureAnimationState(),n&&n.captureAnimationState();var s=ze(this.sortable.el,this.startIndex,this.options);s?this.sortable.el.insertBefore(i,s):this.sortable.el.appendChild(i),this.sortable.animateAll(),n&&n.animateAll()},drop:ua};Xt(_s,{pluginName:"revertOnSpill"});function As(){}As.prototype={onSpill:function(e){var i=e.dragEl,n=e.putSortable,s=n||this.sortable;s.captureAnimationState(),i.parentNode&&i.parentNode.removeChild(i),s.animateAll()},drop:ua};Xt(As,{pluginName:"removeOnSpill"});k.mount(new Gd);k.mount(As,_s);var xs=k;var fa="playlist-items",pa={delay:150,delayOnTouchOnly:!0,touchStartThreshold:5},ma={mounted(){this.sorter=new xs(this.el,{group:{name:fa,pull:!1,put:!0},animation:150,handle:"[data-drag-handle]",draggable:"[data-sortable-id]",ghostClass:"opacity-50",...pa,onEnd:t=>{if(t.from!==t.to||t.oldIndex===t.newIndex)return;let e=[...this.el.querySelectorAll("[data-sortable-id]")].map(i=>i.dataset.sortableId);this.pushEvent("reorder_items",{ids:e})},onAdd:t=>{let{trackId:e,tagId:i}=t.item.dataset,n=t.newIndex;t.item.remove(),e?this.pushEvent("add_track_at",{id:e,index:n}):i&&this.pushEvent("add_tag_at",{id:i,index:n})}})},destroyed(){this.sorter?.destroy()}},ga={mounted(){this.sorter=new xs(this.el,{group:{name:fa,pull:"clone",put:!1},sort:!1,animation:150,draggable:"[data-track-id], [data-tag-id]",ghostClass:"opacity-50",filter:"[data-no-drag]",preventOnFilter:!1,...pa})},destroyed(){this.sorter?.destroy()}};var Jd={mounted(){this.sync=()=>{let t=document.documentElement.getAttribute("data-theme-pref")||"system";
91this.el.querySelectorAll("[data-phx-theme]").forEach(e=>{e.setAttribute("aria-pressed",String(e.dataset.phxTheme===t))})},this.observer=new MutationObserver(this.sync),this.observer.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme-pref"]}),this.sync()},destroyed(){this.observer.disconnect()}},va=Jd;var Yd={...si,mounted(){this.el.dataset.theme=document.documentElement.getAttribute("data-theme")==="dark"?"dark":"light",si.mounted.call(this)}},ba=Yd;var Ve=t=>{window.__panelAnchor={rect:t,ts:Date.now()}},Zd={mounted(){let t=window.__panelAnchor;!t||Date.now()-t.ts>1500||(window.__panelAnchor=null,this.anchorRect=t.rect,this.applyPosition())},updated(){this.applyPosition()},applyPosition(){if(!this.anchorRect)return;let t=this.anchorRect,e=this.el,i=e.offsetWidth,n=e.offsetHeight,s=window.innerWidth,r=window.innerHeight,o=t.right+12;o+i>s-8&&(o=t.left-i-12),o<8&&(o=Math.max(8,(s-i)/2));let a=Math.max(8,Math.min(t.top,r-n-8));e.style.position="fixed",e.style.left=`${Math.round(o)}px`,e.style.top=`${Math.round(a)}px`,e.style.margin="0",e.style.maxHeight=`${r-16}px`,e.style.overflowY="auto"}},ya=Zd;var ae=15,Qd=60,gn=15,tu=8,eu=9,wi=350,K=1440,_a=864e5,Ms=(t,e,i)=>Math.max(e,Math.min(i,t)),Ps=t=>Math.round(t/ae)*ae,pn=t=>Ms(Ps(t),0,1440-ae),mn=(t,e)=>{let i=Number.parseInt(t,10);return Number.isNaN(i)?e:i},Jt=t=>{let[e,i,n]=t.split("-").map(Number);return Math.floor(Date.UTC(e,i-1,n)/_a)},Is=t=>new Date(t*_a).toISOString().slice(0,10),iu=({columnDate:t,pointerMinutes:e,grabOffsetMinutes:i,firstDate:n,lastDate:s})=>{let r=Ps(e-i),o=Math.floor(r/K),a=Jt(n),l=Jt(s),h=Jt(t)+o;return h<a?{date:n,startMinutes:0}:h>l?{date:s,startMinutes:K-ae}:{date:Is(h),startMinutes:(r%K+K)%K}},nu=t=>{let e=mn(t.dataset.startMinutes,0),i=mn(t.dataset.durationMinutes,gn);return{eventId:t.dataset.eventId,displayDate:t.dataset.date,displayStartMinutes:e,displayDurationMinutes:i,occurrenceDate:t.dataset.occurrenceDate||t.dataset.date,occurrenceStartMinutes:mn(t.dataset.occurrenceStartMinutes,e),occurrenceDurationMinutes:mn(t.dataset.occurrenceDurationMinutes,i)}},wa=t=>{let i=(Jt(t.toDate)-Jt(t.displayDate))*K+t.newStartMinutes-t.startMinutes,n=t.occurrenceStartMinutes+i,s=Math.floor(n/K),r=(n%K+K)%K;return{id:t.eventId,from_date:t.occurrenceDate,to_date:Is(Jt(t.occurrenceDate)+s),start_minutes:r}},su=t=>({id:t.eventId,date:t.occurrenceDate,duration_minutes:t.newDurationMinutes}),Ea=t=>({id:t.dataset.eventId,date:t.dataset.occurrenceDate||t.dataset.date}),Ts=t=>Ms(t,0,K-ae),ru=(t,e)=>{let i=e.filter(s=>s>t).reduce((s,r)=>Math.min(s,r),1/0),n=Math.min(Qd,i-t);return Math.max(gn,n)},ou=({anchorMinutes:t,snappedEndMinutes:e,travelMinutes:i})=>{if(Math.abs(i)<ae)return{kind:"click",startMinutes:Ts(t)};let n=Math.min(t,e),s=Math.max(t,e);return{kind:"drag",startMinutes:n,durationMinutes:Math.max(ae,s-n)}},vn=t=>{let e=(t%K+K)%K;return`${String(Math.floor(e/60)).padStart(2,"0")}:${String(e%60).padStart(2,"0")}`},Sa=(t,e)=>`${vn(t)} - ${vn(t+e)}`,Ca=t=>{let e=/rgba?\(([^)]+)\)/.exec(t??"");if(!e)return null;let[i,n,s,r]=e[1].split(",").map(o=>Number.parseFloat(o));return{r:i,g:n,b:s,a:Number.isFinite(r)?r:1}},au=(t,e)=>{let i=Ca(t),n=Ca(e)??{r:255,g:255,b:255};if(!i)return"rgb(255, 255, 255)";let s=(r,o)=>Math.round(r*i.a+o*(1-i.a));return`rgb(${s(i.r,n.r)}, ${s(i.g,n.g)}, ${s(i.b,n.b)})`},lu=({date:t,startMinutes:e,durationMinutes:i,firstDate:n,lastDate:s})=>{let r=Jt(n),o=Jt(s),a=[],l=Jt(t),h=e,c=i;for(;c>0&&l<=o;){let d=Math.min(c,K-h);l>=r&&a.push({date:Is(l),top:h,height:d}),c-=d,l+=1,h=0}return a},We=(t,e)=>{let i=t.getBoundingClientRect(),n=Ms(e-i.top,0,i.height),s=i.height===0?0:n/i.height;return Math.round(s*1440)},hu=(t,e)=>{let i=t.getBoundingClientRect(),n=i.height===0?0:(e-i.top)/i.height;return Math.round(n*K)},ka=t=>!!t.closest("[data-calendar-interactive='true']"),cu={mounted(){this.pointerId=null,this.gesture=null,this.suppressClickUntil=0,this.dragPreview=null,this.moveGhosts=[],this.hoverCursorChip=null,this.hoverHint=null,this.ensurePreview=()=>{if(this.dragPreview?.isConnected)return;let t=document.createElement("div");t.className="absolute left-1 right-1 z-30 rounded-md border border-brand-500/70 bg-brand-500/15 pointer-events-none",t.style.display="none",this.el.appendChild(t),this.dragPreview=t},this.updatePreview=(t,e)=>{this.ensurePreview();let i=Math.min(t,e),n=Math.max(t,e),s=Math.max(ae,n-i);this.dragPreview.style.display="block",this.dragPreview.style.top=`${i}px`,this.dragPreview.style.height=`${s}px`},this.clearPreview=()=>{this.dragPreview&&(this.dragPreview.style.display="none",this.dragPreview.style.top="0px",this.dragPreview.style.height="0px")},this.ensureHoverHint=()=>{if(this.hoverHint?.isConnected)return;let t=document.createElement("div");t.className="pointer-events-none absolute left-1 right-1 z-[15] rounded-md border border-dashed border-zinc-300 px-2 py-1 text-[11px] font-medium tabular-nums text-zinc-400",t.style.display="none",this.el.appendChild(t),this.hoverHint=t},this.updateHoverHint=t=>{if(t.pointerType!=="mouse")return;if(t.target.closest("[data-event-id]")||ka(t.target)){this.hideHoverHint();return}this.ensureHoverHint();let e=Ts(pn(We(this.el,t.clientY))),i=this.defaultCreateDuration(e);this.hoverHint.textContent=vn(e),this.hoverHint.style.display="block",this.hoverHint.style.top=`${e}px`,this.hoverHint.style.height=`${Math.min(i,K-e)}px`},this.defaultCreateDuration=t=>{let e=Array.from(this.el.querySelectorAll("[data-event-id]")).map(i=>Number.parseInt(i.dataset.startMinutes,10)).filter(Number.isFinite);return ru(t,e)},this.pushCreateSelection=t=>{let e=t.kind==="click"?this.defaultCreateDuration(t.startMinutes):t.durationMinutes;this.anchorPanelToSlot(t.startMinutes,e),this.pushEvent(t.kind==="click"?"new_event":"drag_create",{date:this.el.dataset.date,start_minutes:t.startMinutes,duration_minutes:e}),this.suppressClickUntil=Date.now()+wi},this.hideHoverHint=()=>{this.hoverHint&&(this.hoverHint.style.display="none")},this.updateRailBadge=t=>{let e=document.querySelector("[data-role='calendar-time-rail']");if(!e)return;let i=document.getElementById("calendar-drag-time-badge");i||(i=document.createElement("div"),i.id="calendar-drag-time-badge",i.className="pointer-events-none absolute left-1 right-1 z-50 -translate-y-1/2 roun
91ded bg-zinc-900 px-1 py-0.5 text-center text-[10px] font-semibold tabular-nums text-white shadow",e.appendChild(i)),i.style.display="block",i.style.top=`${t/K*100}%`,i.textContent=vn(t)},this.hideRailBadge=()=>{let t=document.getElementById("calendar-drag-time-badge");t&&t.remove()},this.buildMoveGhost=t=>{let e=t.cloneNode(!0);e.removeAttribute("id");for(let{name:i}of[...e.attributes])i.startsWith("phx-")&&e.removeAttribute(i);return e.removeAttribute("data-event-id"),e.classList.add("pointer-events-none"),e.classList.remove("cursor-grab","cursor-grabbing","transition"),e.style.transform="",e.style.left="4px",e.style.right="4px",e.style.width="auto",e.style.opacity="",e.style.zIndex="35",e.style.boxShadow="0 8px 24px rgba(24, 24, 27, 0.25)",e.style.backgroundColor=au(getComputedStyle(t).backgroundColor,this.surfaceColor(t)),e},this.surfaceColor=t=>{for(let e=t.parentElement;e;e=e.parentElement){let i=getComputedStyle(e).backgroundColor;if(i&&i!=="transparent"&&!i.startsWith("rgba(0, 0, 0, 0)"))return i}return"rgb(255, 255, 255)"},this.updateMoveGhosts=t=>{let e=wa(t),i=lu({date:e.to_date,startMinutes:e.start_minutes,durationMinutes:t.durationMinutes,firstDate:t.columns[0].date,lastDate:t.columns[t.columns.length-1].date}),n=Sa(e.start_minutes,t.durationMinutes);i.forEach((s,r)=>{let o=this.moveGhosts[r];o?.isConnected||(o=this.buildMoveGhost(t.chip),this.moveGhosts[r]=o);let a=t.columns.find(({date:h})=>h===s.date);a&&o.parentElement!==a.element&&a.element.appendChild(o),o.style.top=`${s.top}px`,o.style.height=`${s.height}px`;let l=o.querySelector("[data-role='calendar-event-time-range']");l&&(l.textContent=n)});for(let s of this.moveGhosts.splice(i.length))s.remove()},this.clearMoveGhosts=()=>{for(let t of this.moveGhosts.splice(0))t.remove()},this.withinResizeZone=(t,e)=>t.getBoundingClientRect().bottom-e.clientY<=eu,this.updateHoverCursor=t=>{let e=t.target.closest("[data-event-id]");this.hoverCursorChip&&this.hoverCursorChip!==e&&this.clearHoverCursor(),!(!e||!e.querySelector("[data-resize-handle]"))&&(e.style.cursor=this.withinResizeZone(e,t)?"ns-resize":"",this.hoverCursorChip=e)},this.clearHoverCursor=()=>{this.hoverCursorChip&&(this.hoverCursorChip.style.cursor="",this.hoverCursorChip=null)},this.occurrenceChips=t=>Array.from(document.querySelectorAll(`[data-event-id="${CSS.escape(t.eventId)}"]`)).filter(e=>(e.dataset.occurrenceDate||e.dataset.date)===t.occurrenceDate),this.captureColumns=()=>Array.from(document.querySelectorAll("[id^='calendar-day-'][data-date]")).map(t=>({date:t.dataset.date,rect:t.getBoundingClientRect(),element:t})),this.columnAt=t=>{let e=this.gesture.columns,i=e.find(({rect:r})=>t>=r.left&&t<r.right);if(i)return i;let n=e[0],s=1/0;for(let r of e){let o=(r.rect.left+r.rect.right)/2,a=Math.abs(t-o);a<s&&(n=r,s=a)}return n},this.restoreChip=()=>{let t=this.gesture;if(t?.chip)for(let[e,i]of t.occurrenceChipStyles??[[t.chip,t.originalStyle]]){let n=e===t.chip?t.originalTimeLabel:void 0;this.restoreChipStyle(e,i,n)}},this.finishGesture=()=>{this.clearPreview(),this.clearMoveGhosts(),this.hideRailBadge(),document.body.style.userSelect="",window.removeEventListener("keydown",this.onKeyDown,!0),this.pointerId=null,this.gesture=null},this.cancelGesture=()=>{this.gesture&&(this.gesture.moved&&(this.suppressClickUntil=Date.now()+wi),this.restoreChip(),this.finishGesture())},this.onKeyDown=t=>{t.key==="Escape"&&this.gesture&&(t.preventDefault(),t.stopPropagation(),this.cancelGesture())},this.onPointerDown=t=>{if(t.button!==0||this.gesture)return;this.hideHoverHint();let e=t.target.closest("[data-event-id]"),i=t.target.closest("[data-resize-handle]")||e&&this.withinResizeZone(e,t)&&e.querySelector("[data-resize-handle]")||null;if(e){this.clearHoverCursor();let n=nu(e),s={chip:e,columns:this.captureColumns(),originalStyle:e.getAttribute("style"),occurrenceChipStyles:this.occurrenceChips(n).map(r=>[r,r.getAttribute("style")]),eventId:n.eventId,displayDate:n.displayDate,occurrenceDate:n.occurrenceDate,occurrenceStartMinutes:n.occurrenceStartMinutes,startMinutes:n.displayStartMinutes,displayDurationMinutes:n.displayDurationMinutes,durationMinutes:n.occurrenceDurationMinutes,startX:t.clientX,startY:t.clientY,moved:!1};if(i)this.gesture={...s,type:"resize",newDurationMinutes:s.durationMinutes};else{let r=We(this.el,t.clientY)-s.startMinutes;this.gesture={...s,type:"move",grabOffsetMinutes:r,toDate:s.displayDate,newStartMinutes:s.startMinutes}}}else{if(ka(t.target))return;this.gesture={type:"create",startMinutes:pn(We(this.el,t.clientY)),rawStartMinutes:We(this.el,t.clientY),startX:t.clientX,startY:t.clientY,moved:!1},this.clearPreview()}if(this.pointerId=t.pointerId,window.addEventListener("keydown",this.onKeyDown,!0),this.el.setPointerCapture)try{this.el.setPointerCapture(t.pointerId)}catch{}},this.onPointerMove=t=>
91{if(!this.gesture){this.updateHoverCursor(t),this.updateHoverHint(t);return}if(this.pointerId!==null&&t.pointerId!==this.pointerId)return;let e=Math.hypot(t.clientX-this.gesture.startX,t.clientY-this.gesture.startY);if(!(!this.gesture.moved&&e<tu))switch(this.gesture.moved||(this.gesture.moved=!0,document.body.style.userSelect="none",this.gesture.chip&&this.gesture.chip.classList.add("cursor-grabbing")),this.gesture.type){case"create":this.updatePreview(this.gesture.startMinutes,pn(We(this.el,t.clientY)));break;case"move":this.trackMove(t);break;case"resize":this.trackResize(t);break}},this.trackMove=t=>{let e=this.gesture,i=this.columnAt(t.clientX);if(!i)return;let n=iu({columnDate:i.date,pointerMinutes:hu(i.element,t.clientY),grabOffsetMinutes:e.grabOffsetMinutes,firstDate:e.columns[0].date,lastDate:e.columns[e.columns.length-1].date});if(e.columns.find(({date:r})=>r===n.date)){e.toDate=n.date,e.newStartMinutes=n.startMinutes;for(let[r]of e.occurrenceChipStyles)r.style.opacity="0.5";this.updateMoveGhosts(e),this.updateRailBadge(n.startMinutes)}},this.trackResize=t=>{let e=this.gesture,i=Math.round(t.clientY-e.startY);e.newDurationMinutes=Math.max(Ps(e.durationMinutes+i),gn);let n=e.displayDurationMinutes+(e.newDurationMinutes-e.durationMinutes);e.chip.style.height=`${Math.max(n,gn)/1440*100}%`,e.chip.style.zIndex="35";let s=e.chip.querySelector("[data-role='calendar-event-time-range']");s&&(e.originalTimeLabel===void 0&&(e.originalTimeLabel=s.textContent),s.textContent=Sa(e.occurrenceStartMinutes,e.newDurationMinutes))},this.onPointerUp=t=>{if(!this.gesture||this.pointerId!==null&&t.pointerId!==this.pointerId)return;let e=this.gesture;if(!e.moved){e.type==="create"?this.pushCreateSelection({kind:"click",startMinutes:Ts(e.startMinutes)}):this.openChipEditor(e.chip),this.finishGesture();return}switch(t.preventDefault(),t.stopPropagation(),e.type){case"create":{let i=We(this.el,t.clientY);this.pushCreateSelection(ou({anchorMinutes:e.startMinutes,snappedEndMinutes:pn(i),travelMinutes:i-e.rawStartMinutes}));break}case"move":{if(e.toDate!==e.displayDate||e.newStartMinutes!==e.startMinutes){let n=e.occurrenceChipStyles,s=this.moveGhosts;this.moveGhosts=[];let r=wa(e);this.anchorPanelToPendingChange(r.to_date,r.start_minutes,e.durationMinutes),this.pushEvent("move_event",r,o=>{for(let a of s)a.remove();for(let[a,l]of n)this.settleChip(a,l,o)}),this.suppressClickUntil=Date.now()+wi}else this.restoreChip(),this.openChipEditor(e.chip);break}case"resize":{if(e.newDurationMinutes!==e.durationMinutes){let i=e.chip,n=e.originalStyle,s=e.originalTimeLabel;Ve(i.getBoundingClientRect()),this.pushEvent("resize_event",su(e),r=>this.settleChip(i,n,r,s))}else this.restoreChip();this.suppressClickUntil=Date.now()+wi;break}}if(this.el.releasePointerCapture)try{this.el.releasePointerCapture(t.pointerId)}catch{}this.finishGesture()},this.openChipEditor=t=>{Ve(t.getBoundingClientRect()),this.pushEvent("edit_event",Ea(t)),this.suppressClickUntil=Date.now()+wi},this.anchorPanelToPendingChange=(t,e,i)=>{let n=this.gesture.columns.find(({date:a})=>a===t);if(!n)return;let s=n.element.getBoundingClientRect(),r=s.top+e/K*s.height,o=Math.min(i,K-e);Ve({left:s.left,right:s.right,top:r,bottom:r+o/K*s.height})},this.anchorPanelToSlot=(t,e)=>{let i=this.el.getBoundingClientRect();Ve({left:i.left,right:i.right,top:i.top+t,bottom:i.top+t+e})},this.restoreChipStyle=(t,e,i)=>{if(t.isConnected){if(e===null?t.removeAttribute("style"):t.setAttribute("style",e),i!==void 0){let n=t.querySelector("[data-role='calendar-event-time-range']");n&&(n.textContent=i)}t.classList.remove("cursor-grabbing")}},this.settleChip=(t,e,i,n)=>{if(i&&i.status==="applied"){if(!t.isConnected)return;t.style.transform="",t.style.zIndex="",t.style.opacity="",t.style.boxShadow="",t.classList.remove("cursor-grabbing")}else this.restoreChipStyle(t,e,n)},this.onPointerCancel=t=>{this.cancelGesture()},this.onPointerLeave=t=>{this.gesture||(this.clearHoverCursor(),this.hideHoverHint())},this.onContextMenu=t=>{let e=t.target.closest("[data-event-id]");!e||this.gesture||(t.preventDefault(),Ve({left:t.clientX,right:t.clientX,top:t.clientY,bottom:t.clientY}),this.pushEvent("calendar_context_menu",Ea(e)))},this.onClickCapture=t=>{Date.now()<=this.suppressClickUntil&&(t.preventDefault(),t.stopPropagation())},this.el.addEventListener("pointerdown",this.onPointerDown),this.el.addEventListener("pointermove",this.onPointerMove),this.el.addEventListener("pointerup",this.onPointerUp),this.el.addEventListener("pointercancel",this.onPointerCancel),this.el.addEventListener("pointerleave",this.onPointerLeave),this.el.addEventListener("contextmenu",this.onContextMenu),this.el.addEventListener("click",this.onClickCapture,!0)},destroyed(){this.el.removeEventListener("pointerdown",this.onPointerDown),this.el.removeEventListener("pointermove",this.onPointerMove),this.el.removeEventListener("pointerup",this.onPointerUp),this.el.removeEventListener("pointercancel",this.onPointerCancel),this.el.removeEventListener("pointerleave",this.onPointerLeave),this.el.removeEventListener("contextmenu",this.onContextMenu),this.el.removeEventListener("click",this.onClickCapture,!0),window.removeEventListener("keydown",this.onKeyDown,!0),document.body.style.userSelect="",this.dragPreview&&(this.dragPreview.remove(),this.dragPreview=null),this.hoverHint&&(this.hoverHint.remove(),this.hoverHint=null),this.hideRailBadge?.();for(let t of this.moveGhosts.splice(0))t.remove()}},Aa=cu;var du="input, textarea, select, button, label, a[href], [role='menu']",uu={mounted(){this.openMenu=null,this.dismissing=!1,this.closeOpenMenu=()=>{this.openMenu&&(this.openMenu.classList.add("hidden"),this.openMenu.style.removeProperty("left"),this.openMenu.style.removeProperty("top"),this.openMenu.style.removeProperty("display"),this.openMenu.classList.remove("fixed"),this.openMenu.classList.add("absolute"),this.openMenu=null)},this.onContextMenu=t=>{let e=t.target.closest("tr[data-context-row]");if(!e)return;let i=e.querySelector("[role='menu']");if(!i||t.target.closest("input, textarea, a[href]"))return;t.preventDefault(),this.closeOpenMenu(),i.style.removeProperty("display"),i.classList.remove("hidden","absolute"),i.classList.add("fixed");let{width:n,height:s}=i.getBoundingClientRect(),r=Math.min(t.clientX,window.innerWidth-n-8),o=Math.min(t.clientY,window.innerHeight-s-8);i.style.left=`${Math.max(8,r)}px`,i.style.top=`${Math.max(8,o)}px`,this.openMenu=i},this.onPointerDown=t=>{!this.openMenu||this.openMenu.contains(t.target)||(this.dismissing=!0,this.closeOpenMenu())},this.editItem=t=>[...t.querySelectorAll("[role='menu'] button")].find(e=>e.textContent.trim()==="Edit"),this.activateRow=t=>{let e=t.target.closest("tr[data-context-row]");if(!e||t.target.closest(du)||!window.getSelection().isCollapsed)return;let i=this.editItem(e);i&&i.click()},this.onClick=t=>{if(this.openMenu&&this.openMenu.contains(t.target))return this.closeOpenMenu();if(!this.openMenu){if(this.dismissing){this.dismissing=!1;return}this.activateRow(t)}},this.onRowKeyDown=t=>{t.key==="Enter"&&t.target.matches("tr[data-context-row]")&&(t.preventDefault(),this.activateRow(t))},this.onKeyDown=t=>{t.key==="Escape"&&this.closeOpenMenu()},this.el.addEventListener("contextmenu",this.onContextMenu),this.el.addEventListener("click",this.onClick),this.el.addEventListener("keydown",this.onRowKeyDown),window.addEventListener("pointerdown",this.onPointerDown,!0),window.addEventListener("keydown",this.onKeyDown,!0)},destroyed(){this.el.removeEventListener("contextmenu",this.onContextMenu),this.el.removeEventListener("click",this.onClick),this.el.removeEventListener("keydown",this.onRowKeyDown),window.removeEventListener("pointerdown",this.onPointerDown,!0),window.removeEventListener("keydown",this.onKeyDown,!0)}},xa=uu;var fu={mounted(){this.formatter=new Intl.DateTimeFormat("en-US",{timeZone:this.el.dataset.timezone||"UTC",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}),this.text=this.el.querySelector("[data-clock-text]")||this.el,this.tick(),this.interval=setInterval(()=>this.tick(),1e3)},destroyed(){clearInterval(this.interval)},tick(){this.text.textContent=this.formatter.format(new Date)}},Ta=fu;var pu={mounted(){this.targetMs=Number(this.el.dataset.startsAtMs),this.text=this.el.querySelector("[data-countdown-text]")||this.el,this.tick(),this.interval=setInterval(()=>this.tick(),1e3)},destroyed(){clearInterval(this.interval)},tick(){let t=Math.round((this.targetMs-Date.now())/1e3);if(t<=0){this.text.textContent="starting now",this.stop();return}this.text.textContent=`in ${mu(t)}`},stop(){clearInterval(this.interval),this.interval=null}};function Ds(t){return String(t).padStart(2,"0")}function mu(t){let e=Math.floor(t/86400),i=Math.floor(t%86400/3600),n=Math.floor(t%3600/60),s=t%60;return e>0?`${e}d ${i}h`:i>0?`${i}h ${Ds(n)}m`:`${Ds(n)}:${Ds(s)}`}var Ma=pu;var gu={mounted(){let{targetMs:t,fromMs:e}=this.el.dataset;this.targetMs=Number(t),this.fromMs=e?Number(e):null,this.days=this.el.querySelector("[data-countdown-days]"),this.progress=this.el.querySelector("[data-countdown-progress]"),this.tick(),this.interval=setInterval(()=>this.tick(),1e3)},destroyed(){clearInterval(this.interval)},tick(){let t=Date.now(),e=bu(Math.floor((this.targetMs-t)/1e3));for(let[i,n]of Object.entries(e)){let s=this.el.querySelector(`[data-countdown-unit="${i}"]`);s&&(s.textContent=i==="days"?String(n):vu(n))}if(this.days&&(this.days.hidden=e.days===0),this.progress&&this.fromMs!==null){let i=this.targetMs-this.fromMs,n=i>0?(t-this.fromMs)/i:1;this.progress.style.width=`${Math.min(100,Math.max(0,n*100))}%`}t>=this.targetMs&&(clearInterval(this.interval),this.interval=null)}};function vu(t){return String(t).padStart(2,"0")}function bu(t){let e=Math.max(0,t);return{days:Math.floor(e/86400),hours:Math.floor(e%86400/3600),minutes:Math.floor(e%3600/60),seconds:e%60}}var Pa=gu;var yu={mounted(){this.header=this.el.querySelector("[data-role='calendar-header-scroll']"),this.body=this.el.querySelector("[data-role='calendar-body-scroll']"),this.syncHeader=()=>{this.header&&this.body&&(this.header.scrollLeft=this.body.scrollLeft)},this.body?.addEventListener("scroll",this.syncHeader,{passive:!0});let t=this.el.querySelector("[data-role='calendar-now-line']");if(!t)return;let e=t.getBoundingClientRect().top+window.pageYOffset;window.scrollTo({top:Math.max(0,e-window.innerHeight/3)});let i=t.closest("[data-date]");if(!i||!this.body)return;let n=i.getBoundingClientRect().left-this.body.getBoundingClientRect().left+this.body.scrollLeft;this.body.scrollLeft=Math.max(0,n-70),this.syncHeader()},destroyed(){this.body?.removeEventListener("scroll",this.syncHeader)}},Ia=yu;var wu={mounted(){this.pushVisibilityEvent=()=>{document.hidden?this.pushEvent("page_hidden",{}):this.pushEvent("page_visible",{})},this.handleVisibilityChange=()=>{this.pushVisibilityEvent()},this.handleNavigation=t=>{t.detail&&t.detail.kind==="redirect"&&this.pushEvent("page_hidden",{})},document.hidden&&this.pushEvent("page_hidden",{}),document.addEventListener("visibilitychange",this.handleVisibilityChange),window.addEventListener("phx:page-loading-start",this.handleNavigation)},destroyed(){document.removeEventListener("visibilitychange",this.handleVisibilityChange),window.removeEventListener("phx:page-loading-start",this.handleNavigation)}},Da=wu;var La=t=>`cloudradio-paypal-${t}`,Ra={mounted(){this.popup=null,this.starting=!1,this.flowId=this.el.dataset.flowId,this.channel=new BroadcastChannel(La(this.flowId)),this.onMessage=({data:t})=>{this.clearPopupWatch(),this.starting=!1,this.popup=null,t?.status==="completed"?this.pushEvent("paypal_payment_completed",{}):t?.status==="cancelled"?this.pushEvent("paypal_payment_cancelled",{}):t?.status==="failed"&&this.pushEvent("paypal_payment_failed",{})},this.channel.addEventListener("message",this.onMessage),this.onClick=()=>
91{if(!this.starting){if(this.popup=window.open("","_blank","popup,width=520,height=720"),!this.popup){this.pushEvent("paypal_popup_blocked",{});return}this.starting=!0,this.popup.document.title="Opening PayPal",this.popup.document.body.textContent="Opening PayPal...",this.watchPopup(),this.pushEvent(this.el.dataset.submitEvent||"submit_paypal",{})}},this.el.addEventListener("click",this.onClick),this.handleEvent("open_paypal_setup",({url:t})=>{if(!this.popup||this.popup.closed){this.starting=!1,this.pushEvent("paypal_popup_blocked",{});return}this.popup.opener=null,this.popup.location.replace(t)}),this.handleEvent("paypal_setup_error",()=>{this.clearPopupWatch(),this.starting=!1,this.popup?.close(),this.popup=null})},destroyed(){this.clearPopupWatch(),this.el.removeEventListener("click",this.onClick),this.channel.removeEventListener("message",this.onMessage),this.channel.close()},watchPopup(){this.clearPopupWatch(),this.popupWatch=window.setInterval(()=>{this.popup?.closed&&(this.clearPopupWatch(),this.starting=!1,this.popup=null,this.pushEvent("paypal_payment_cancelled",{}))},500)},clearPopupWatch(){this.popupWatch&&(window.clearInterval(this.popupWatch),this.popupWatch=null)}},Oa={mounted(){let t=new BroadcastChannel(La(this.el.dataset.flowId));t.postMessage({status:this.el.dataset.status}),window.setTimeout(()=>{t.close(),window.close()},250)}};var Ha="schedule-ai-placeholder-index",Eu={mounted(){this.index=this.nextIndex(),this.apply()},updated(){this.apply()},apply(){let t=this.examples();t.length!==0&&(this.el.placeholder=t[this.index%t.length])},nextIndex(){let t=0;try{t=parseInt(localStorage.getItem(Ha),10)||0,localStorage.setItem(Ha,`${t+1}`)}catch{}return t},examples(){try{return JSON.parse(this.el.dataset.placeholders||"[]")}catch{return[]}}},Fa=Eu;var Su=30*24*60*60*1e3;function Cu(t){if(t==null)return!1;if(t==="1")return!0;let e=Number(t);return Number.isFinite(e)?Date.now()-e<Su:!1}var Rs=!1,Ua=!1;try{Rs=window.sessionStorage.getItem("phx:fallback:LongPoll")!==null,Rs&&Cu(window.localStorage.getItem("phx:ws-ok"))&&(window.sessionStorage.removeItem("phx:fallback:LongPoll"),Ua=!0)}catch{}var ku=document.querySelector("meta[name='csrf-token']").getAttribute("content"),Na=document.querySelector("meta[name='live-socket-path']"),Ba=Na?Na.getAttribute("content"):"/live",bn=new Map,Ke=new Map,Os=(t,e)=>{if(!t)return;let i=t.id,n=Ke.get(i);n&&(clearTimeout(n),Ke.delete(i));let s=t.querySelector("[data-sidebar-backdrop]"),r=t.querySelector(".mobile-sidebar-panel");if(e)t.classList.remove("hidden"),t.style.display="block",requestAnimationFrame(()=>{s?.classList.add("opacity-100"),s?.classList.remove("opacity-0"),r?.classList.add("open")});else{s?.classList.add("opacity-0"),s?.classList.remove("opacity-100"),r?.classList.remove("open");let o=setTimeout(()=>{bn.get(i)||(t.style.display="none",t.classList.add("hidden"),Ke.delete(i))},300);Ke.set(i,o)}},_u={mounted(){Os(this.el,bn.get(this.el.id)===!0),this.onLinkClick=t=>{t.target.closest("a")&&window.toggleSidebar(this.el.id,!1)},this.el.addEventListener("click",this.onLinkClick)},updated(){Os(this.el,bn.get(this.el.id)===!0)},destroyed(){this.el.removeEventListener("click",this.onLinkClick);let t=Ke.get(this.el.id);t&&(clearTimeout(t),Ke.delete(this.el.id))}},$a={params:{_csrf_token:ku,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},hooks:{...xr,AutoDJMiniPlayer:Yr,AnchoredPanel:ya,AnchorUnder:_o,CalendarDragCreate:Aa,CalendarViewport:Ia,ComponentChooser:Io,DotMatrixHook:fo,PageVisibility:Da,PayPalReturn:Oa,PayPalSetup:Ra,MobileSidebar:_u,Turnstile:si,ClearFlashHook:Zr,Clipboard:Qr,ECharts:to,FeedbackButton:qo,IslandHook:ao,ListenerMap:no,ReachMap:so,LocalTime:ro,MarqueeHook:oo,PlayerHook:po,PreviewSender:mo,PrintInvoice:go,RotatingPlaceholder:Fa,ScheduleGrid:Eo,ScheduleDateMask:So,ScheduleSelection:vo,ScrollHint:Co,ScrollShadows:ko,SelectAll:Ao,ShowCountdown:Pa,SortableList:ma,SortableSource:ga,StationClock:Ta,StripeElements:xo,StripeSetup:To,Tabs:Mo,ThemeToggle:va,ThemedTurnstile:ba,TagPickerEmbeddedKeys:Po,TrackRowContextMenu:xa,TransitionCountdown:Ma,TimezoneExport:Do,UploadGuard:jo,UptimeCounter:Lo,WaveformEditor:Uo},uploaders:ot};$a.longPollFallbackMs=2500;var pt=new Ar(Ba,Ns,$a);yn.default.config({barColors:{0:"#29d"},shadowColor:"rgba(0, 0, 0, .3)"});window.addEventListener("phx:page-loading-start",t=>yn.default.show(300));window.addEventListener("phx:page-loading-stop",t=>yn.default.hide());window.addEventListener("phx:copy",t=>{let e=t.target,i=e.textContent||e.innerText;navigator.clipboard.writeText(i.trim()).then(()=>{let n=t.detail?.dispatcher;if(n){let s=n.title;n.title="Copied!",setTimeout(()=>{n.title=s},2e3)}}).catch(n=>{console.error("Failed to copy:",n)})});var lt=null,kt=null,Au=t=>{let e=document.querySelector("[data-phx-main]"),i=e&&pt.getViewByEl(e)||pt.main;i&&i.pushEvent("audio_ended",{track_id:t})},Ei=(t,e)=>{if(!t)return;let i=document.querySelector(`button[phx-click="toggle_play"][phx-value-id="${t}"]`);if(!i)return;i.classList.toggle("bg-purple-100",e),i.classList.toggle("border-purple-500",e),i.classList.toggle("text-purple-600",e),i.classList.toggle("text-zinc-500",!e),i.classList.toggle("hover:text-purple-600",!e);let n=(i.getAttribute("aria-label")||"").replace(/^(Play|Pause)/,"");i.setAttribute("aria-label",(e?"Pause":"Play")+n),i.innerHTML=e?'<span class="hero-pause-solid h-4 w-4"></span>':'<span class="hero-play-solid h-4 w-4 ml-0.5"></span>'},xu=()=>{kt&&Ei(kt,!0)};window.addEventListener("phx:audio_play",t=>{let{url:e,track_id:i}=t.detail;kt&&kt!==i&&Ei(kt,!1),lt&&(lt.pause(),lt.src=""),lt=new Audio(e);let n=lt,s=!1,r=()=>{s||(s=!0,Ei(i,!1),kt===i&&(kt=null),Au(i),lt===n&&(lt=null))};n.onended=()=>{r()},n.onpause=()=>{n.ended&&r()},n.onerror=()=>{console.error("Audio playback failed"),r()},n.play().catch(o=>{console.error("Audio play error:",o),r()}),kt=i,Ei(i,!0)});window.addEventListener("phx:audio_stop",()=>{kt&&(Ei(kt,!1),kt=null),lt&&(lt.pause(),lt.src="",lt=null)});window.addEventListener("phx:page-loading-stop",()=>{xu()});window.addEventListener("phx:page-loading-start",t=>{t.detail.kind==="redirect"&<&&(lt.pause(),lt.src="",lt=null,kt=null)});window.addEventListener("phx:download_file",t=>{let{url:e}=t.detail,i=document.createElement("a");i.href=e,i.download="",document.body.appendChild(i),i.click(),document.body.removeChild(i)});window.addEventListener("phx:scroll-to",t=>{let{id:e}=t.detail||{};e&&requestAnimationFrame(()=>{let i=document.getElementById(e);i&&i.scrollIntoView({behavior:"smooth",block:"start"})})});window.addEventListener("phx:lock-body-scroll",()=>{document.body.style.overflow="hidden"});window.addEventListener("phx:unlock-body-scroll",()=>{document.body.style.overflow=""});window.toggleSidebar=function(t,e){let i=document.getElementById(t);i&&(bn.set(t,e),Os(i,e))};{let t=Ba==="/embed/live",e=5e3,i=1e4,n=3,s=1e4,r=pt.reloadWithJitter.bind(pt),o=null,a=null,l=0,h=c=>{if(o!=null)return;if(a!=null&&(clearTimeout(a),a=null),l>
91=n){if(l=0,t){console.warn("[app] embed socket keeps closing (code 1000) after multiple reconnect attempts; staying disconnected instead of reloading so the listener's audio keeps playing");return}if(ot.uploadsInProgress())console.warn("[app] socket keeps closing (code 1000), but uploads are still finishing; deferring the crash-loop reload until they complete and reconnecting instead");else{console.warn("[app] socket keeps closing (code 1000) after multiple reconnect attempts; falling back to the original reload as a crash-loop failsafe"),r(c);return}}let d=Math.floor(Math.random()*(i-e+1))+e;l+=1,console.debug(`[app] socket closed gracefully (code 1000); reconnecting in ${d}ms instead of reloading (cycle ${l}/${n})`),o=setTimeout(()=>{o=null,!(c&&(c.isDestroyed()||c.isConnected()))&&(console.debug("[app] socket reconnecting now"),pt.connect())},d),pt.disconnect()};pt.socket.onOpen(()=>{a!=null&&clearTimeout(a),a=setTimeout(()=>{a=null,l=0},s)}),pt.reloadWithJitter=function(c){h(c)},pt.socket.onClose(c=>{c&&c.code===1e3&&pt.main&&h(pt.main)})}pt.connect();Xr();qr();var Ls=pt.getSocket();Ls.onOpen(()=>{if(Ls.transport===Qt)console.warn(Rs&&!Ua?"[CloudRadio] LiveView connected over LongPoll (memorized fallback from a previous failed WebSocket attempt; close the tab to retry WebSocket). Expect remounts and slower realtime updates.":"[CloudRadio] LiveView connected over LongPoll (WebSocket upgrade failed). Expect remounts and slower realtime updates. Check the edge proxy /live/websocket Upgrade/Connection headers.");else{Ls.longPollFallbackMs=null;try{window.localStorage.setItem("phx:ws-ok",String(Date.now()))}catch{}}});window.liveSocket=pt;window.Uploaders=ot; 92/** 93 * @license MIT 94 * topbar 3.0.0 95 * http://buunguyen.github.io/topbar 96 * Copyright (c) 2024 Buu Nguyen 97 */ 98/*! Bundled license information: 99 100sortablejs/modular/sortable.esm.js: 101 (**! 102 * Sortable 1.15.7 103 * @author RubaXa <[email protected]> 104 * @author owenm <[email protected]> 105 * @license MIT 106 *) 107*/
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.