Files
bDS2/priv/static/assets/app.js

27 lines
158 KiB
JavaScript

(()=>{var Me=e=>typeof e=="function"?e:function(){return e},ps=typeof self<"u"?self:null,Te=typeof window<"u"?window:null,K=ps||Te||globalThis,ms="2.0.0",z={connecting:0,open:1,closing:2,closed:3},gs=1e4,vs=1e3,B={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},se={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},St={longpoll:"longpoll",websocket:"websocket"},bs={complete:4},kt="base64url.bearer.phx.",Ge=class{constructor(e,t,i,s){this.channel=e,this.event=t,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,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(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:i}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},ei=class{constructor(e,t){this.callback=e,this.timerCalc=t,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))}},ws=class{constructor(e,t,i){this.state=B.closed,this.topic=e,this.params=Me(t||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Ge(this,se.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ei(()=>{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=B.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=B.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=B.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=B.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 Ge(this,se.leave,Me({}),this.timeout).send(),this.state=B.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(se.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(e=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=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on(se.close,e)}onError(e){return this.on(se.error,t=>e(t))}on(e,t){let i=this.bindingRef++;return this.bindings.push({event:e,ref:i,callback:t}),i}off(e,t){this.bindings=this.bindings.filter(i=>!(i.event===e&&(typeof t>"u"||t===i.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,i=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new Ge(this,e,function(){return t},i);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=B.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(se.close,"leave")},i=new Ge(this,se.leave,Me({}),e);return i.receive("ok",()=>t()).receive("timeout",()=>t()),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(e,t,i){return t}isMember(e,t,i,s){return this.topic!==e?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:i,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=B.joining,this.joinPush.resend(e))}trigger(e,t,i,s){let n=this.onMessage(e,t,i,s);if(t&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(o=>o.event===e);for(let o=0;o<r.length;o++)r[o].callback(n,i,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===B.closed}isErrored(){return this.state===B.errored}isJoined(){return this.state===B.joined}isJoining(){return this.state===B.joining}isLeaving(){return this.state===B.leaving}},Ze=class{static request(e,t,i,s,n,r,o){if(K.XDomainRequest){let a=new K.XDomainRequest;return this.xdomainRequest(a,e,t,s,n,r,o)}else if(K.XMLHttpRequest){let a=new K.XMLHttpRequest;return this.xhrRequest(a,e,t,i,s,n,r,o)}else{if(K.fetch&&K.AbortController)return this.fetchRequest(e,t,i,s,n,r,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(e,t,i,s,n,r,o){let a={method:e,headers:i,body:s},h=null;if(n){h=new AbortController;let l=setTimeout(()=>h.abort(),n);a.signal=h.signal}return K.fetch(t,a).then(l=>l.text()).then(l=>this.parseJSON(l)).then(l=>o&&o(l)).catch(l=>{l.name==="AbortError"&&r?r():o&&o(null)}),h}static xdomainRequest(e,t,i,s,n,r,o){return e.timeout=n,e.open(t,i),e.onload=()=>{let a=this.parseJSON(e.responseText);o&&o(a)},r&&(e.ontimeout=r),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,i,s,n,r,o,a){e.open(t,i,!0),e.timeout=r;for(let[h,l]of Object.entries(s))e.setRequestHeader(h,l);return e.onerror=()=>a&&a(null),e.onreadystatechange=()=>{if(e.readyState===bs.complete&&a){let h=this.parseJSON(e.responseText);a(h)}},o&&(e.ontimeout=o),e.send(n),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let i=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let n=t?`${t}[${s}]`:s,r=e[s];typeof r=="object"?i.push(this.serialize(r,n)):i.push(encodeURIComponent(n)+"="+encodeURIComponent(r))}return i.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let i=e.match(/\?/)?"&":"?";return`${e}${i}${this.serialize(t)}`}},ys=e=>{let t="",i=new Uint8Array(e),s=i.byteLength;for(let n=0;n<s;n++)t+=String.fromCharCode(i[n]);return btoa(t)},Ce=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(kt)&&(this.authToken=atob(t[1].slice(kt.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(e),this.readyState=z.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+St.websocket),"$1/"+St.longpoll)}endpointURL(){return Ze.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,i){this.close(e,t,i),this.readyState=z.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===z.open||this.readyState===z.connecting}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),t=>{if(t){var{status:i,token:s,messages:n}=t;if(i===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else i=0;switch(i){case 200:n.forEach(r=>{setTimeout(()=>this.onmessage({data:r}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=z.open,this.onopen({}),this.poll();break;case 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(e){typeof e!="string"&&(e=ys(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(`
`),()=>this.onerror("timeout"),t=>{this.awaitingBatchAck=!1,!t||t.status!==200?(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(e,t,i){for(let n of this.reqs)n.abort();this.readyState=z.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:i});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,i,s,n){let r,o=()=>{this.reqs.delete(r),s()};r=Ze.request(e,this.endpointURL(),t,i,this.timeout,o,a=>{this.reqs.delete(r),this.isActive()&&n(a)}),this.reqs.add(r)}};var Ye={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let i=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(i))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[i,s,n,r,o]=JSON.parse(e);return t({join_ref:i,ref:s,topic:n,event:r,payload:o})}},binaryEncode(e){let{join_ref:t,ref:i,event:s,topic:n,payload:r}=e,o=this.META_LENGTH+t.length+i.length+n.length+s.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),h=new DataView(a),l=0;h.setUint8(l++,this.KINDS.push),h.setUint8(l++,t.length),h.setUint8(l++,i.length),h.setUint8(l++,n.length),h.setUint8(l++,s.length),Array.from(t,p=>h.setUint8(l++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(l++,p.charCodeAt(0))),Array.from(n,p=>h.setUint8(l++,p.charCodeAt(0))),Array.from(s,p=>h.setUint8(l++,p.charCodeAt(0)));var d=new Uint8Array(a.byteLength+r.byteLength);return d.set(new Uint8Array(a),0),d.set(new Uint8Array(r),a.byteLength),d.buffer},binaryDecode(e){let t=new DataView(e),i=t.getUint8(0),s=new TextDecoder;switch(i){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=i.decode(e.slice(o,o+s));o=o+s;let h=i.decode(e.slice(o,o+n));o=o+n;let l=i.decode(e.slice(o,o+r));o=o+r;let d=e.slice(o,e.byteLength);return{join_ref:a,ref:null,topic:h,event:l,payload:d}},decodeReply(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=t.getUint8(3),o=t.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,h=i.decode(e.slice(a,a+s));a=a+s;let l=i.decode(e.slice(a,a+n));a=a+n;let d=i.decode(e.slice(a,a+r));a=a+r;let p=i.decode(e.slice(a,a+o));a=a+o;let m=e.slice(a,e.byteLength),g={status:p,response:m};return{join_ref:h,ref:l,topic:d,event:se.reply,payload:g}},decodeBroadcast(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=this.HEADER_LENGTH+2,o=i.decode(e.slice(r,r+s));r=r+s;let a=i.decode(e.slice(r,r+n));r=r+n;let h=e.slice(r,e.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:h}}},ti=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||gs,this.transport=t.transport||K.WebSocket||Ce,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||K&&K.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Ye.encode.bind(Ye),this.defaultDecoder=Ye.decode.bind(Ye),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.transport!==Ce?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;Te&&Te.addEventListener&&(Te.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),i=this.connectClock)}),Te.addEventListener("pageshow",s=>{i===this.connectClock&&(i=null,this.connect())}),Te.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=s=>t.rejoinAfterMs?t.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>t.reconnectAfterMs?t.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(s,n,r)=>{console.log(`${s}: ${n}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=Me(t.params||{}),this.endPoint=`${e}/${St.websocket}`,this.vsn=t.vsn||ms,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ei(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(()=>this.connect())},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return Ce}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Ze.appendParams(Ze.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,i){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,i)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Me(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ce?this.connectWithFallback(Ce,this.longPollFallbackMs):this.transportConnect())}log(e,t,i){this.logger&&this.logger(e,t,i)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(n=>{n.ref===t&&(this.off([s]),e(Date.now()-i))});return!0}transportName(e){switch(e){case Ce:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["phoenix",`${kt}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let i=!1,s=!0,n,r,o=this.transportName(e),a=h=>{this.log("transport",`falling back to ${o}...`,h),this.off([n,r]),s=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,t),r=this.onError(h=>{this.log("transport","error",h),s&&!i&&(clearTimeout(this.fallbackTimer),a(h))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!s){let h=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${h}`,"true"),this.log("transport",`established ${h} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,t),this.ping(h=>{this.log("transport","connected to primary after",h),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(([,e])=>e())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),vs,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,i){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,i||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,i=1){if(i===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,i+1)},150*i)}waitForSocketClosed(e,t,i=1){if(i===5||e.readyState===z.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,i+1)},150*i)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{});let t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&t!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,i])=>i(e))}onConnError(e){this.hasLogger()&&this.log("transport",e);let t=this.transport,i=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,s])=>{s(e,t,i)}),(t===this.transport||i>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(se.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case z.connecting:return"connecting";case z.open:return"open";case z.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([i])=>e.indexOf(i)===-1)}channel(e,t={}){let i=new ws(e,t,this);return this.channels.push(i),i}push(e){if(this.hasLogger()){let{topic:t,event:i,payload:s,ref:n,join_ref:r}=e;this.log("push",`${t} ${i} (${r}, ${n})`,s)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,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(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:i,event:s,payload:n,ref:r,join_ref:o}=t;r&&r===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${n.status||""} ${i} ${s} ${r&&"("+r+")"||""}`,n);for(let a=0;a<this.channels.length;a++){let h=this.channels[a];h.isMember(i,s,n,o)&&h.trigger(s,n,r,o)}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,h]=this.stateChangeCallbacks.message[a];h(t)}})}leaveOpenTopic(e){let t=this.channels.find(i=>i.topic===e&&(i.isJoined()||i.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};var xi="consecutive-reloads",Es=10,Ss=5e3,ks=1e4,As=3e4,Ri=["phx-click-loading","phx-change-loading","phx-submit-loading","phx-keydown-loading","phx-keyup-loading","phx-blur-loading","phx-focus-loading","phx-hook-loading"],At="phx-drop-target-active",Z="data-phx-component",Le="data-phx-view",Ct="data-phx-link",Cs="track-static",Ts="data-phx-link-state",De="data-phx-ref-loading",W="data-phx-ref-src",D="data-phx-ref-lock",ii="phx-pending-refs",Ii="track-uploads",oe="data-phx-upload-ref",Ft="data-phx-preflighted-refs",_s="data-phx-done-refs",Qe="drop-target",It="data-phx-active-refs",ot="phx:live-file:updated",Li="data-phx-skip",Di="data-phx-id",si="data-phx-prune",ni="phx-connected",me="phx-loading",_e="phx-error",ri="phx-client-error",He="phx-server-error",ye="data-phx-parent-id",Ut="data-phx-main",re="data-phx-root-id",Lt="viewport-top",Dt="viewport-bottom",Ps="viewport-overrun-target",xs="trigger-action",ct="phx-has-focused",Rs=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"],Oi=["checkbox","radio"],We="phx-has-submitted",Q="data-phx-session",qe=`[${Q}]`,Ot="data-phx-sticky",we="data-phx-static",Mt="data-phx-readonly",Re="data-phx-disabled",oi="disable-with",dt="data-phx-disable-with-restore",Ne="hook",Is="debounce",Ls="throttle",ut="update",at="stream",$e="data-phx-stream",Bt="data-phx-portal",Ee="data-phx-teleported",fe="data-phx-teleported-src",ht="data-phx-runtime-hook",Ds="data-phx-pid",Os="key",G="phxPrivate",ai="auto-recover",et="phx:live-socket:debug",Tt="phx:live-socket:profiling",_t="phx:live-socket:latency-sim",tt="phx:nav-history-position",Ms="progress",hi="mounted",li="__phoenix_reload_status__",Hs=1,ci=3,Ns=200,$s=500,Fs="phx-",Us=3e4,Fe="debounce-trigger",Ue="throttled",di="debounce-prev-key",Bs={debounce:300,throttle:300},ui=[De,W,D],V="s",Pt="r",$="c",I="k",Y="kc",fi="e",pi="r",mi="t",de="p",Pe="stream",js=class{constructor(e,t,i){let{chunk_size:s,chunk_timeout:n}=t;this.liveSocket=i,this.entry=e,this.offset=0,this.chunkSize=s,this.chunkTimeout=n,this.chunkTimer=null,this.errored=!1,this.uploadChannel=i.channel(`lvu:${e.ref}`,{token:e.metadata()})}error(e){this.errored||(this.uploadChannel.leave(),this.errored=!0,clearTimeout(this.chunkTimer),this.entry.error(e))}upload(){this.uploadChannel.onError(e=>this.error(e)),this.uploadChannel.join().receive("ok",e=>this.readNextChunk()).receive("error",e=>this.error(e))}isDone(){return this.offset>=this.entry.file.size}readNextChunk(){let e=new window.FileReader,t=this.entry.file.slice(this.offset,this.chunkSize+this.offset);e.onload=i=>{if(i.target.error===null)this.offset+=i.target.result.byteLength,this.pushChunk(i.target.result);else return P("Read error: "+i.target.error)},e.readAsArrayBuffer(t)}pushChunk(e){this.uploadChannel.isJoined()&&this.uploadChannel.push("chunk",e,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:t})=>this.error(t))}},P=(e,t)=>console.error&&console.error(e,t),ne=e=>{let t=typeof e;return t==="number"||t==="string"&&/^(0|[1-9]\d*)$/.test(e)};function Vs(){let e=new Set,t=document.querySelectorAll("*[id]");for(let i=0,s=t.length;i<s;i++)e.has(t[i].id)?console.error(`Multiple IDs detected: ${t[i].id}. Ensure unique element ids.`):e.add(t[i].id)}function Ws(e){let t=new Set;Object.keys(e).forEach(i=>{let s=document.getElementById(i);s&&s.parentElement&&s.parentElement.getAttribute("phx-update")!=="stream"&&t.add(`The stream container with id "${s.parentElement.id}" is missing the phx-update="stream" attribute. Ensure it is set for streams to work properly.`)}),t.forEach(i=>console.error(i))}var qs=(e,t,i,s)=>{e.liveSocket.isDebugEnabled()&&console.log(`${e.id} ${t}: ${i} - `,s)},Be=e=>typeof e=="function"?e:function(){return e},lt=e=>JSON.parse(JSON.stringify(e)),be=(e,t,i)=>{do{if(e.matches(`[${t}]`)&&!e.disabled)return e;e=e.parentElement||e.parentNode}while(e!==null&&e.nodeType===1&&!(i&&i.isSameNode(e)||e.matches(qe)));return null},xe=e=>e!==null&&typeof e=="object"&&!(e instanceof Array),Js=(e,t)=>JSON.stringify(e)===JSON.stringify(t),gi=e=>{for(let t in e)return!1;return!0},Ie=(e,t)=>e&&t(e),Xs=function(e,t,i,s){e.forEach(n=>{new js(n,i.config,s).upload()})},Ks=e=>{if(e.dataTransfer.types){for(let t=0;t<e.dataTransfer.types.length;t++)if(e.dataTransfer.types[t]==="Files")return!0}return!1},zs={canPushState(){return typeof history.pushState<"u"},dropLocal(e,t,i){return e.removeItem(this.localKey(t,i))},updateLocal(e,t,i,s,n){let r=this.getLocal(e,t,i),o=this.localKey(t,i),a=r===null?s:n(r);return e.setItem(o,JSON.stringify(a)),a},getLocal(e,t,i){return JSON.parse(e.getItem(this.localKey(t,i)))},updateCurrentState(e){this.canPushState()&&history.replaceState(e(history.state||{}),"",window.location.href)},pushState(e,t,i){if(this.canPushState()){if(i!==window.location.href){if(t.type=="redirect"&&t.scroll){let s=history.state||{};s.scroll=t.scroll,history.replaceState(s,"",window.location.href)}delete t.scroll,history[e+"State"](t,"",i||null),window.requestAnimationFrame(()=>{let s=this.getHashTargetEl(window.location.hash);s?s.scrollIntoView():t.type==="redirect"&&window.scroll(0,0)})}}else this.redirect(i)},setCookie(e,t,i){let s=typeof i=="number"?` max-age=${i};`:"";document.cookie=`${e}=${t};${s} path=/`},getCookie(e){return document.cookie.replace(new RegExp(`(?:(?:^|.*;s*)${e}s*=s*([^;]*).*$)|^.*$`),"$1")},deleteCookie(e){document.cookie=`${e}=; max-age=-1; path=/`},redirect(e,t,i=s=>{window.location.href=s}){t&&this.setCookie("__phoenix_flash__",t,60),i(e)},localKey(e,t){return`${e}-${t}`},getHashTargetEl(e){let t=e.toString().substring(1);if(t!=="")return document.getElementById(t)||document.querySelector(`a[name="${t}"]`)}},U=zs,ve={byId(e){return document.getElementById(e)||P(`no id found for ${e}`)},removeClass(e,t){e.classList.remove(t),e.classList.length===0&&e.removeAttribute("class")},all(e,t,i){if(!e)return[];let s=Array.from(e.querySelectorAll(t));return i&&s.forEach(i),s},childNodeLength(e){let t=document.createElement("template");return t.innerHTML=e,t.content.childElementCount},isUploadInput(e){return e.type==="file"&&e.getAttribute(oe)!==null},isAutoUpload(e){return e.hasAttribute("data-phx-auto-upload")},findUploadInputs(e){let t=e.id,i=this.all(document,`input[type="file"][${oe}][form="${t}"]`);return this.all(e,`input[type="file"][${oe}]`).concat(i)},findComponentNodeList(e,t,i=document){return this.all(i,`[${Le}="${e}"][${Z}="${t}"]`)},isPhxDestroyed(e){return!!(e.id&&ve.private(e,"destroyed"))},wantsNewTab(e){let t=e.ctrlKey||e.shiftKey||e.metaKey||e.button&&e.button===1,i=e.target instanceof HTMLAnchorElement&&e.target.hasAttribute("download"),s=e.target.hasAttribute("target")&&e.target.getAttribute("target").toLowerCase()==="_blank",n=e.target.hasAttribute("target")&&!e.target.getAttribute("target").startsWith("_");return t||s||i||n},isUnloadableFormSubmit(e){return e.target&&e.target.getAttribute("method")==="dialog"||e.submitter&&e.submitter.getAttribute("formmethod")==="dialog"?!1:!e.defaultPrevented&&!this.wantsNewTab(e)},isNewPageClick(e,t){let i=e.target instanceof HTMLAnchorElement?e.target.getAttribute("href"):null,s;if(e.defaultPrevented||i===null||this.wantsNewTab(e)||i.startsWith("mailto:")||i.startsWith("tel:")||e.target.isContentEditable)return!1;try{s=new URL(i)}catch{try{s=new URL(i,t)}catch{return!0}}return s.host===t.host&&s.protocol===t.protocol&&s.pathname===t.pathname&&s.search===t.search?s.hash===""&&!s.href.endsWith("#"):s.protocol.startsWith("http")},markPhxChildDestroyed(e){this.isPhxChild(e)&&e.setAttribute(Q,""),this.putPrivate(e,"destroyed",!0)},findPhxChildrenInFragment(e,t){let i=document.createElement("template");return i.innerHTML=e,this.findPhxChildren(i.content,t)},isIgnored(e,t){return(e.getAttribute(t)||e.getAttribute("data-phx-update"))==="ignore"},isPhxUpdate(e,t,i){return e.getAttribute&&i.indexOf(e.getAttribute(t))>=0},findPhxSticky(e){return this.all(e,`[${Ot}]`)},findPhxChildren(e,t){return this.all(e,`${qe}[${ye}="${t}"]`)},findExistingParentCIDs(e,t){let i=new Set,s=new Set;return t.forEach(n=>{this.all(document,`[${Le}="${e}"][${Z}="${n}"]`).forEach(r=>{i.add(n),this.all(r,`[${Le}="${e}"][${Z}]`).map(o=>parseInt(o.getAttribute(Z))).forEach(o=>s.add(o))})}),s.forEach(n=>i.delete(n)),i},private(e,t){return e[G]&&e[G][t]},deletePrivate(e,t){e[G]&&delete e[G][t]},putPrivate(e,t,i){e[G]||(e[G]={}),e[G][t]=i},updatePrivate(e,t,i,s){let n=this.private(e,t);n===void 0?this.putPrivate(e,t,s(i)):this.putPrivate(e,t,s(n))},syncPendingAttrs(e,t){e.hasAttribute(W)&&(Ri.forEach(i=>{e.classList.contains(i)&&t.classList.add(i)}),ui.filter(i=>e.hasAttribute(i)).forEach(i=>{t.setAttribute(i,e.getAttribute(i))}))},copyPrivates(e,t){t[G]&&(e[G]=t[G])},putTitle(e){let t=document.querySelector("title");if(t){let{prefix:i,suffix:s,default:n}=t.dataset,r=typeof e!="string"||e.trim()==="";if(r&&typeof n!="string")return;let o=r?n:e;document.title=`${i||""}${o||""}${s||""}`}else document.title=e},debounce(e,t,i,s,n,r,o,a){let h=e.getAttribute(i),l=e.getAttribute(n);h===""&&(h=s),l===""&&(l=r);let d=h||l;switch(d){case null:return a();case"blur":this.incCycle(e,"debounce-blur-cycle",()=>{o()&&a()}),this.once(e,"debounce-blur")&&e.addEventListener("blur",()=>this.triggerCycle(e,"debounce-blur-cycle"));return;default:let p=parseInt(d),m=()=>l?this.deletePrivate(e,Ue):a(),g=this.incCycle(e,Fe,m);if(isNaN(p))return P(`invalid throttle/debounce value: ${d}`);if(l){let v=!1;if(t.type==="keydown"){let w=this.private(e,di);this.putPrivate(e,di,t.key),v=w!==t.key}if(!v&&this.private(e,Ue))return!1;{a();let w=setTimeout(()=>{o()&&this.triggerCycle(e,Fe)},p);this.putPrivate(e,Ue,w)}}else setTimeout(()=>{o()&&this.triggerCycle(e,Fe,g)},p);let u=e.form;u&&this.once(u,"bind-debounce")&&u.addEventListener("submit",()=>{Array.from(new FormData(u).entries(),([v])=>{let w=u.elements.namedItem(v),O=w instanceof RadioNodeList?w[0]:w;O&&(this.incCycle(O,Fe),this.deletePrivate(O,Ue))})}),this.once(e,"bind-debounce")&&e.addEventListener("blur",()=>{clearTimeout(this.private(e,Ue)),this.triggerCycle(e,Fe)})}},triggerCycle(e,t,i){let[s,n]=this.private(e,t);i||(i=s),i===s&&(this.incCycle(e,t),n())},once(e,t){return this.private(e,t)===!0?!1:(this.putPrivate(e,t,!0),!0)},incCycle(e,t,i=function(){}){let[s]=this.private(e,t)||[0,i];return s++,this.putPrivate(e,t,[s,i]),s},maintainPrivateHooks(e,t,i,s){e.hasAttribute&&e.hasAttribute("data-phx-hook")&&!t.hasAttribute("data-phx-hook")&&t.setAttribute("data-phx-hook",e.getAttribute("data-phx-hook")),t.hasAttribute&&(t.hasAttribute(i)||t.hasAttribute(s))&&t.setAttribute("data-phx-hook","Phoenix.InfiniteScroll")},putCustomElHook(e,t){e.isConnected?e.setAttribute("data-phx-hook",""):console.error(`
hook attached to non-connected DOM element
ensure you are calling createHook within your connectedCallback. ${e.outerHTML}
`),this.putPrivate(e,"custom-el-hook",t)},getCustomElHook(e){return this.private(e,"custom-el-hook")},isUsedInput(e){return e.nodeType===Node.ELEMENT_NODE&&(this.private(e,ct)||this.private(e,We))},resetForm(e){Array.from(e.elements).forEach(t=>{this.deletePrivate(t,ct),this.deletePrivate(t,We)})},isPhxChild(e){return e.getAttribute&&e.getAttribute(ye)},isPhxSticky(e){return e.getAttribute&&e.getAttribute(Ot)!==null},isChildOfAny(e,t){return!!t.find(i=>i.contains(e))},firstPhxChild(e){return this.isPhxChild(e)?e:this.all(e,`[${ye}]`)[0]},isPortalTemplate(e){return e.tagName==="TEMPLATE"&&e.hasAttribute(Bt)},closestViewEl(e){let t=e.closest(`[${Ee}],${qe}`);return t?t.hasAttribute(Ee)?this.byId(t.getAttribute(Ee)):t.hasAttribute(Q)?t:null:null},dispatchEvent(e,t,i={}){let s=!0;e.nodeName==="INPUT"&&e.type==="file"&&t==="click"&&(s=!1);let o={bubbles:i.bubbles===void 0?s:!!i.bubbles,cancelable:!0,detail:i.detail||{}},a=t==="click"?new MouseEvent("click",o):new CustomEvent(t,o);e.dispatchEvent(a)},cloneNode(e,t){if(typeof t>"u")return e.cloneNode(!0);{let i=e.cloneNode(!1);return i.innerHTML=t,i}},mergeAttrs(e,t,i={}){let s=new Set(i.exclude||[]),n=i.isIgnored,r=t.attributes;for(let a=r.length-1;a>=0;a--){let h=r[a].name;if(s.has(h)){if(h==="value"){let l=t.value??t.getAttribute(h);e.value===l&&e.setAttribute("value",t.getAttribute(h))}}else{let l=t.getAttribute(h);e.getAttribute(h)!==l&&(!n||n&&h.startsWith("data-"))&&e.setAttribute(h,l)}}let o=e.attributes;for(let a=o.length-1;a>=0;a--){let h=o[a].name;n?h.startsWith("data-")&&!t.hasAttribute(h)&&!ui.includes(h)&&e.removeAttribute(h):t.hasAttribute(h)||e.removeAttribute(h)}},mergeFocusedInput(e,t){e instanceof HTMLSelectElement||ve.mergeAttrs(e,t,{exclude:["value"]}),t.readOnly?e.setAttribute("readonly",!0):e.removeAttribute("readonly")},hasSelectionRange(e){return e.setSelectionRange&&(e.type==="text"||e.type==="textarea")},restoreFocus(e,t,i){if(e instanceof HTMLSelectElement&&e.focus(),!ve.isTextualInput(e))return;e.matches(":focus")||e.focus(),this.hasSelectionRange(e)&&e.setSelectionRange(t,i)},isFormInput(e){return e.localName&&customElements.get(e.localName)?customElements.get(e.localName).formAssociated:/^(?:input|select|textarea)$/i.test(e.tagName)&&e.type!=="button"},syncAttrsToProps(e){e instanceof HTMLInputElement&&Oi.indexOf(e.type.toLocaleLowerCase())>=0&&(e.checked=e.getAttribute("checked")!==null)},isTextualInput(e){return Rs.indexOf(e.type)>=0},isNowTriggerFormExternal(e,t){return e.getAttribute&&e.getAttribute(t)!==null&&document.body.contains(e)},cleanChildNodes(e,t){if(ve.isPhxUpdate(e,t,["append","prepend",at])){let i=[];e.childNodes.forEach(s=>{s.id||(!(s.nodeType===Node.TEXT_NODE&&s.nodeValue.trim()==="")&&s.nodeType!==Node.COMMENT_NODE&&P(`only HTML element tags with an id are allowed inside containers with phx-update.
removing illegal node: "${(s.outerHTML||s.nodeValue).trim()}"
`),i.push(s))}),i.forEach(s=>s.remove())}},replaceRootContainer(e,t,i){let s=new Set(["id",Q,we,Ut,re]);if(e.tagName.toLowerCase()===t.toLowerCase())return Array.from(e.attributes).filter(n=>!s.has(n.name.toLowerCase())).forEach(n=>e.removeAttribute(n.name)),Object.keys(i).filter(n=>!s.has(n.toLowerCase())).forEach(n=>e.setAttribute(n,i[n])),e;{let n=document.createElement(t);return Object.keys(i).forEach(r=>n.setAttribute(r,i[r])),s.forEach(r=>n.setAttribute(r,e.getAttribute(r))),n.innerHTML=e.innerHTML,e.replaceWith(n),n}},getSticky(e,t,i){let s=(ve.private(e,"sticky")||[]).find(([n])=>t===n);if(s){let[n,r,o]=s;return o}else return typeof i=="function"?i():i},deleteSticky(e,t){this.updatePrivate(e,"sticky",[],i=>i.filter(([s,n])=>s!==t))},putSticky(e,t,i){let s=i(e);this.updatePrivate(e,"sticky",[],n=>{let r=n.findIndex(([o])=>t===o);return r>=0?n[r]=[t,i,s]:n.push([t,i,s]),n})},applyStickyOperations(e){let t=ve.private(e,"sticky");t&&t.forEach(([i,s,n])=>this.putSticky(e,i,s))},isLocked(e){return e.hasAttribute&&e.hasAttribute(D)},attributeIgnored(e,t){return t.some(i=>e.name==i||i==="*"||i.includes("*")&&e.name.match(i)!=null)}},c=ve,je=class{static isActive(e,t){let i=t._phxRef===void 0,n=e.getAttribute(It).split(",").indexOf(M.genFileRef(t))>=0;return t.size>0&&(i||n)}static isPreflighted(e,t){return e.getAttribute(Ft).split(",").indexOf(M.genFileRef(t))>=0&&this.isActive(e,t)}static isPreflightInProgress(e){return e._preflightInProgress===!0}static markPreflightInProgress(e){e._preflightInProgress=!0}constructor(e,t,i,s){this.ref=M.genFileRef(t),this.fileEl=e,this.file=t,this.view=i,this.meta=null,this._isCancelled=!1,this._isDone=!1,this._progress=0,this._lastProgressSent=-1,this._onDone=function(){},this._onElUpdated=this.onElUpdated.bind(this),this.fileEl.addEventListener(ot,this._onElUpdated),this.autoUpload=s}metadata(){return this.meta}progress(e){this._progress=Math.floor(e),this._progress>this._lastProgressSent&&(this._progress>=100?(this._progress=100,this._lastProgressSent=100,this._isDone=!0,this.view.pushFileProgress(this.fileEl,this.ref,100,()=>{M.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,this._onDone()}isDone(){return this._isDone}error(e="failed"){this.fileEl.removeEventListener(ot,this._onElUpdated),this.view.pushFileProgress(this.fileEl,this.ref,{error:e}),this.isAutoUpload()||M.clearFiles(this.fileEl)}isAutoUpload(){return this.autoUpload}onDone(e){this._onDone=()=>{this.fileEl.removeEventListener(ot,this._onElUpdated),e()}}onElUpdated(){this.fileEl.getAttribute(It).split(",").indexOf(this.ref)===-1&&(M.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(e){if(this.meta.uploader){let t=e[this.meta.uploader]||P(`no uploader configured for ${this.meta.uploader}`);return{name:this.meta.uploader,callback:t}}else return{name:"channel",callback:Xs}}zipPostFlight(e){this.meta=e.entries[this.ref],this.meta||P(`no preflight upload response returned with ref ${this.ref}`,{input:this.fileEl,response:e})}},Gs=0,M=class Ht{static genFileRef(t){let i=t._phxRef;return i!==void 0?i:(t._phxRef=(Gs++).toString(),t._phxRef)}static getEntryDataURL(t,i,s){let n=this.activeFiles(t).find(r=>this.genFileRef(r)===i);s(URL.createObjectURL(n))}static hasUploadsInProgress(t){let i=0;return c.findUploadInputs(t).forEach(s=>{s.getAttribute(Ft)!==s.getAttribute(_s)&&i++}),i>0}static serializeUploads(t){let i=this.activeFiles(t),s={};return i.forEach(n=>{let r={path:t.name},o=t.getAttribute(oe);s[o]=s[o]||[],r.ref=this.genFileRef(n),r.last_modified=n.lastModified,r.name=n.name||r.ref,r.relative_path=n.webkitRelativePath,r.type=n.type,r.size=n.size,typeof n.meta=="function"&&(r.meta=n.meta()),s[o].push(r)}),s}static clearFiles(t){t.value=null,t.removeAttribute(oe),c.putPrivate(t,"files",[])}static untrackFile(t,i){c.putPrivate(t,"files",c.private(t,"files").filter(s=>!Object.is(s,i)))}static trackFiles(t,i,s){if(t.getAttribute("multiple")!==null){let n=i.filter(r=>!this.activeFiles(t).find(o=>Object.is(o,r)));c.updatePrivate(t,"files",[],r=>r.concat(n)),t.value=null}else s&&s.files.length>0&&(t.files=s.files),c.putPrivate(t,"files",i)}static activeFileInputs(t){let i=c.findUploadInputs(t);return Array.from(i).filter(s=>s.files&&this.activeFiles(s).length>0)}static activeFiles(t){return(c.private(t,"files")||[]).filter(i=>je.isActive(t,i))}static inputsAwaitingPreflight(t){let i=c.findUploadInputs(t);return Array.from(i).filter(s=>this.filesAwaitingPreflight(s).length>0)}static filesAwaitingPreflight(t){return this.activeFiles(t).filter(i=>!je.isPreflighted(t,i)&&!je.isPreflightInProgress(i))}static markPreflightInProgress(t){t.forEach(i=>je.markPreflightInProgress(i.file))}constructor(t,i,s){this.autoUpload=c.isAutoUpload(t),this.view=i,this.onComplete=s,this._entries=Array.from(Ht.filesAwaitingPreflight(t)||[]).map(n=>new je(t,n,i,this.autoUpload)),Ht.markPreflightInProgress(this._entries),this.numEntriesInProgress=this._entries.length}isAutoUpload(){return this.autoUpload}entries(){return this._entries}initAdapterUpload(t,i,s){this._entries=this._entries.map(r=>(r.isCancelled()?(this.numEntriesInProgress--,this.numEntriesInProgress===0&&this.onComplete()):(r.zipPostFlight(t),r.onDone(()=>{this.numEntriesInProgress--,this.numEntriesInProgress===0&&this.onComplete()})),r));let n=this._entries.reduce((r,o)=>{if(!o.meta)return r;let{name:a,callback:h}=o.uploader(s.uploaders);return r[a]=r[a]||{callback:h,entries:[]},r[a].entries.push(o),r},{});for(let r in n){let{callback:o,entries:a}=n[r];o(a,i,t,s)}}},Ys={anyOf(e,t){return t.find(i=>e instanceof i)},isFocusable(e,t){return e instanceof HTMLAnchorElement&&e.rel!=="ignore"||e instanceof HTMLAreaElement&&e.href!==void 0||!e.disabled&&this.anyOf(e,[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement,HTMLButtonElement])||e instanceof HTMLIFrameElement||e.tabIndex>=0&&e.getAttribute("aria-hidden")!=="true"||!t&&e.getAttribute("tabindex")!==null&&e.getAttribute("aria-hidden")!=="true"},attemptFocus(e,t){if(this.isFocusable(e,t))try{e.focus()}catch{}return!!document.activeElement&&document.activeElement.isSameNode(e)},focusFirstInteractive(e){let t=e.firstElementChild;for(;t;){if(this.attemptFocus(t,!0)||this.focusFirstInteractive(t))return!0;t=t.nextElementSibling}},focusFirst(e){let t=e.firstElementChild;for(;t;){if(this.attemptFocus(t)||this.focusFirst(t))return!0;t=t.nextElementSibling}},focusLast(e){let t=e.lastElementChild;for(;t;){if(this.attemptFocus(t)||this.focusLast(t))return!0;t=t.previousElementSibling}}},j=Ys,Mi={LiveFileUpload:{activeRefs(){return this.el.getAttribute(It)},preflightedRefs(){return this.el.getAttribute(Ft)},mounted(){this.js().ignoreAttributes(this.el,["value"]),this.preflightedWas=this.preflightedRefs()},updated(){let e=this.preflightedRefs();this.preflightedWas!==e&&(this.preflightedWas=e,e===""&&this.__view().cancelSubmit(this.el.form)),this.activeRefs()===""&&(this.el.value=null),this.el.dispatchEvent(new CustomEvent(ot))}},LiveImgPreview:{mounted(){this.ref=this.el.getAttribute("data-phx-entry-ref"),this.inputEl=document.getElementById(this.el.getAttribute(oe)),M.getEntryDataURL(this.inputEl,this.ref,e=>{this.url=e,this.el.src=e})},destroyed(){URL.revokeObjectURL(this.url)}},FocusWrap:{mounted(){this.focusStart=this.el.firstElementChild,this.focusEnd=this.el.lastElementChild,this.focusStart.addEventListener("focus",e=>{if(!e.relatedTarget||!this.el.contains(e.relatedTarget)){let t=e.target.nextElementSibling;j.attemptFocus(t)||j.focusFirst(t)}else j.focusLast(this.el)}),this.focusEnd.addEventListener("focus",e=>{if(!e.relatedTarget||!this.el.contains(e.relatedTarget)){let t=e.target.previousElementSibling;j.attemptFocus(t)||j.focusLast(t)}else j.focusFirst(this.el)}),this.el.contains(document.activeElement)||(this.el.addEventListener("phx:show-end",()=>this.el.focus()),window.getComputedStyle(this.el).display!=="none"&&j.focusFirst(this.el))}}},Hi=e=>["HTML","BODY"].indexOf(e.nodeName.toUpperCase())>=0?null:["scroll","auto"].indexOf(getComputedStyle(e).overflowY)>=0?e:Hi(e.parentElement),vi=e=>e?e.scrollTop:document.documentElement.scrollTop||document.body.scrollTop,jt=e=>e?e.getBoundingClientRect().bottom:window.innerHeight||document.documentElement.clientHeight,Vt=e=>e?e.getBoundingClientRect().top:0,Zs=(e,t)=>{let i=e.getBoundingClientRect();return Math.ceil(i.top)>=Vt(t)&&Math.ceil(i.left)>=0&&Math.floor(i.top)<=jt(t)},Qs=(e,t)=>{let i=e.getBoundingClientRect();return Math.ceil(i.bottom)>=Vt(t)&&Math.ceil(i.left)>=0&&Math.floor(i.bottom)<=jt(t)},bi=(e,t)=>{let i=e.getBoundingClientRect();return Math.ceil(i.top)>=Vt(t)&&Math.ceil(i.left)>=0&&Math.floor(i.top)<=jt(t)};Mi.InfiniteScroll={mounted(){this.scrollContainer=Hi(this.el);let e=vi(this.scrollContainer),t=!1,i=500,s=null,n=this.throttle(i,(a,h)=>{s=()=>!0,this.liveSocket.js().push(this.el,a,{value:{id:h.id,_overran:!0},callback:()=>{s=null}})}),r=this.throttle(i,(a,h)=>{s=()=>h.scrollIntoView({block:"start"}),this.liveSocket.js().push(this.el,a,{value:{id:h.id},callback:()=>{s=null,window.requestAnimationFrame(()=>{bi(h,this.scrollContainer)||h.scrollIntoView({block:"start"})})}})}),o=this.throttle(i,(a,h)=>{s=()=>h.scrollIntoView({block:"end"}),this.liveSocket.js().push(this.el,a,{value:{id:h.id},callback:()=>{s=null,window.requestAnimationFrame(()=>{bi(h,this.scrollContainer)||h.scrollIntoView({block:"end"})})}})});this.onScroll=a=>{let h=vi(this.scrollContainer);if(s)return e=h,s();let l=this.findOverrunTarget(),d=this.el.getAttribute(this.liveSocket.binding("viewport-top")),p=this.el.getAttribute(this.liveSocket.binding("viewport-bottom")),m=this.el.lastElementChild,g=this.el.firstElementChild,u=h<e,v=h>e;u&&d&&!t&&l.top>=0?(t=!0,n(d,g)):v&&t&&l.top<=0&&(t=!1),d&&u&&Zs(g,this.scrollContainer)?r(d,g):p&&v&&Qs(m,this.scrollContainer)&&o(p,m),e=h},this.scrollContainer?this.scrollContainer.addEventListener("scroll",this.onScroll):window.addEventListener("scroll",this.onScroll)},destroyed(){this.scrollContainer?this.scrollContainer.removeEventListener("scroll",this.onScroll):window.removeEventListener("scroll",this.onScroll)},throttle(e,t){let i=0,s;return(...n)=>{let r=Date.now(),o=e-(r-i);o<=0||o>e?(s&&(clearTimeout(s),s=null),i=r,t(...n)):s||(s=setTimeout(()=>{i=Date.now(),s=null,t(...n)},o))}},findOverrunTarget(){let e,t=this.el.getAttribute(this.liveSocket.binding(Ps));if(t){let i=document.getElementById(t);if(i)e=i.getBoundingClientRect();else throw new Error("did not find element with id "+t)}else e=this.el.getBoundingClientRect();return e}};var en=Mi,Nt=class{static onUnlock(e,t){if(!c.isLocked(e)&&!e.closest(`[${D}]`))return t();let i=e.closest(`[${D}]`),s=i.closest(`[${D}]`).getAttribute(D);i.addEventListener(`phx:undo-lock:${s}`,()=>{t()},{once:!0})}constructor(e){this.el=e,this.loadingRef=e.hasAttribute(De)?parseInt(e.getAttribute(De),10):null,this.lockRef=e.hasAttribute(D)?parseInt(e.getAttribute(D),10):null}maybeUndo(e,t,i){if(!this.isWithin(e)){c.updatePrivate(this.el,ii,[],s=>(s.push(e),s));return}this.undoLocks(e,t,i),this.undoLoading(e,t),c.updatePrivate(this.el,ii,[],s=>s.filter(n=>{let r={detail:{ref:n,event:t},bubbles:!0,cancelable:!1};return this.loadingRef&&this.loadingRef>n&&this.el.dispatchEvent(new CustomEvent(`phx:undo-loading:${n}`,r)),this.lockRef&&this.lockRef>n&&this.el.dispatchEvent(new CustomEvent(`phx:undo-lock:${n}`,r)),n>e})),this.isFullyResolvedBy(e)&&this.el.removeAttribute(W)}isWithin(e){return!(this.loadingRef!==null&&this.loadingRef>e&&this.lockRef!==null&&this.lockRef>e)}undoLocks(e,t,i){if(!this.isLockUndoneBy(e))return;let s=c.private(this.el,D);s&&(i(s),c.deletePrivate(this.el,D)),this.el.removeAttribute(D);let n={detail:{ref:e,event:t},bubbles:!0,cancelable:!1};this.el.dispatchEvent(new CustomEvent(`phx:undo-lock:${this.lockRef}`,n))}undoLoading(e,t){if(!this.isLoadingUndoneBy(e)){this.canUndoLoading(e)&&this.el.classList.contains("phx-submit-loading")&&this.el.classList.remove("phx-change-loading");return}if(this.canUndoLoading(e)){this.el.removeAttribute(De);let i=this.el.getAttribute(Re),s=this.el.getAttribute(Mt);s!==null&&(this.el.readOnly=s==="true",this.el.removeAttribute(Mt)),i!==null&&(this.el.disabled=i==="true",this.el.removeAttribute(Re));let n=this.el.getAttribute(dt);n!==null&&(this.el.textContent=n,this.el.removeAttribute(dt));let r={detail:{ref:e,event:t},bubbles:!0,cancelable:!1};this.el.dispatchEvent(new CustomEvent(`phx:undo-loading:${this.loadingRef}`,r))}Ri.forEach(i=>{(i!=="phx-submit-loading"||this.canUndoLoading(e))&&c.removeClass(this.el,i)})}isLoadingUndoneBy(e){return this.loadingRef===null?!1:this.loadingRef<=e}isLockUndoneBy(e){return this.lockRef===null?!1:this.lockRef<=e}isFullyResolvedBy(e){return(this.loadingRef===null||this.loadingRef<=e)&&(this.lockRef===null||this.lockRef<=e)}canUndoLoading(e){return this.lockRef===null||this.lockRef<=e}},tn=class{constructor(e,t,i){let s=new Set,n=new Set([...t.children].map(o=>o.id)),r=[];Array.from(e.children).forEach(o=>{if(o.id&&(s.add(o.id),n.has(o.id))){let a=o.previousElementSibling&&o.previousElementSibling.id;r.push({elementId:o.id,previousElementId:a})}}),this.containerId=t.id,this.updateType=i,this.elementsToModify=r,this.elementIdsToAdd=[...n].filter(o=>!s.has(o))}perform(){let e=c.byId(this.containerId);e&&(this.elementsToModify.forEach(t=>{t.previousElementId?Ie(document.getElementById(t.previousElementId),i=>{Ie(document.getElementById(t.elementId),s=>{s.previousElementSibling&&s.previousElementSibling.id==i.id||i.insertAdjacentElement("afterend",s)})}):Ie(document.getElementById(t.elementId),i=>{i.previousElementSibling==null||e.insertAdjacentElement("afterbegin",i)})}),this.updateType=="prepend"&&this.elementIdsToAdd.reverse().forEach(t=>{Ie(document.getElementById(t),i=>e.insertAdjacentElement("afterbegin",i))}))}},wi=11;function sn(e,t){var i=t.attributes,s,n,r,o,a;if(!(t.nodeType===wi||e.nodeType===wi)){for(var h=i.length-1;h>=0;h--)s=i[h],n=s.name,r=s.namespaceURI,o=s.value,r?(n=s.localName||n,a=e.getAttributeNS(r,n),a!==o&&(s.prefix==="xmlns"&&(n=s.name),e.setAttributeNS(r,n,o))):(a=e.getAttribute(n),a!==o&&e.setAttribute(n,o));for(var l=e.attributes,d=l.length-1;d>=0;d--)s=l[d],n=s.name,r=s.namespaceURI,r?(n=s.localName||n,t.hasAttributeNS(r,n)||e.removeAttributeNS(r,n)):t.hasAttribute(n)||e.removeAttribute(n)}}var it,nn="http://www.w3.org/1999/xhtml",F=typeof document>"u"?void 0:document,rn=!!F&&"content"in F.createElement("template"),on=!!F&&F.createRange&&"createContextualFragment"in F.createRange();function an(e){var t=F.createElement("template");return t.innerHTML=e,t.content.childNodes[0]}function hn(e){it||(it=F.createRange(),it.selectNode(F.body));var t=it.createContextualFragment(e);return t.childNodes[0]}function ln(e){var t=F.createElement("body");return t.innerHTML=e,t.childNodes[0]}function cn(e){return e=e.trim(),rn?an(e):on?hn(e):ln(e)}function st(e,t){var i=e.nodeName,s=t.nodeName,n,r;return i===s?!0:(n=i.charCodeAt(0),r=s.charCodeAt(0),n<=90&&r>=97?i===s.toUpperCase():r<=90&&n>=97?s===i.toUpperCase():!1)}function dn(e,t){return!t||t===nn?F.createElement(e):F.createElementNS(t,e)}function un(e,t){for(var i=e.firstChild;i;){var s=i.nextSibling;t.appendChild(i),i=s}return t}function xt(e,t,i){e[i]!==t[i]&&(e[i]=t[i],e[i]?e.setAttribute(i,""):e.removeAttribute(i))}var yi={OPTION:function(e,t){var i=e.parentNode;if(i){var s=i.nodeName.toUpperCase();s==="OPTGROUP"&&(i=i.parentNode,s=i&&i.nodeName.toUpperCase()),s==="SELECT"&&!i.hasAttribute("multiple")&&(e.hasAttribute("selected")&&!t.selected&&(e.setAttribute("selected","selected"),e.removeAttribute("selected")),i.selectedIndex=-1)}xt(e,t,"selected")},INPUT:function(e,t){xt(e,t,"checked"),xt(e,t,"disabled"),e.value!==t.value&&(e.value=t.value),t.hasAttribute("value")||e.removeAttribute("value")},TEXTAREA:function(e,t){var i=t.value;e.value!==i&&(e.value=i);var s=e.firstChild;if(s){var n=s.nodeValue;if(n==i||!i&&n==e.placeholder)return;s.nodeValue=i}},SELECT:function(e,t){if(!t.hasAttribute("multiple")){for(var i=-1,s=0,n=e.firstChild,r,o;n;)if(o=n.nodeName&&n.nodeName.toUpperCase(),o==="OPTGROUP")r=n,n=r.firstChild,n||(n=r.nextSibling,r=null);else{if(o==="OPTION"){if(n.hasAttribute("selected")){i=s;break}s++}n=n.nextSibling,!n&&r&&(n=r.nextSibling,r=null)}e.selectedIndex=i}}},Ve=1,Ei=11,Si=3,ki=8;function ue(){}function fn(e){if(e)return e.getAttribute&&e.getAttribute("id")||e.id}function pn(e){return function(i,s,n){if(n||(n={}),typeof s=="string")if(i.nodeName==="#document"||i.nodeName==="HTML"){var r=s;s=F.createElement("html"),s.innerHTML=r}else if(i.nodeName==="BODY"){var o=s;s=F.createElement("html"),s.innerHTML=o;var a=s.querySelector("body");a&&(s=a)}else s=cn(s);else s.nodeType===Ei&&(s=s.firstElementChild);var h=n.getNodeKey||fn,l=n.onBeforeNodeAdded||ue,d=n.onNodeAdded||ue,p=n.onBeforeElUpdated||ue,m=n.onElUpdated||ue,g=n.onBeforeNodeDiscarded||ue,u=n.onNodeDiscarded||ue,v=n.onBeforeElChildrenUpdated||ue,w=n.skipFromChildren||ue,O=n.addChild||function(y,E){return y.appendChild(E)},q=n.childrenOnly===!0,S=Object.create(null),C=[];function x(y){C.push(y)}function H(y,E){if(y.nodeType===Ve)for(var L=y.firstChild;L;){var k=void 0;E&&(k=h(L))?x(k):(u(L),L.firstChild&&H(L,E)),L=L.nextSibling}}function f(y,E,L){g(y)!==!1&&(E&&E.removeChild(y),u(y),H(y,L))}function b(y){if(y.nodeType===Ve||y.nodeType===Ei)for(var E=y.firstChild;E;){var L=h(E);L&&(S[L]=E),b(E),E=E.nextSibling}}b(i);function N(y){d(y);for(var E=y.firstChild;E;){var L=E.nextSibling,k=h(E);if(k){var T=S[k];T&&st(E,T)?(E.parentNode.replaceChild(T,E),R(T,E)):N(E)}else N(E);E=L}}function J(y,E,L){for(;E;){var k=E.nextSibling;(L=h(E))?x(L):f(E,y,!0),E=k}}function R(y,E,L){var k=h(E);if(k&&delete S[k],!L){var T=p(y,E);if(T===!1||(T instanceof HTMLElement&&(y=T,b(y)),e(y,E),m(y),v(y,E)===!1))return}y.nodeName!=="TEXTAREA"?Se(y,E):yi.TEXTAREA(y,E)}function Se(y,E){var L=w(y,E),k=E.firstChild,T=y.firstChild,ke,ie,Ae,Ke,le;e:for(;k;){for(Ke=k.nextSibling,ke=h(k);!L&&T;){if(Ae=T.nextSibling,k.isSameNode&&k.isSameNode(T)){k=Ke,T=Ae;continue e}ie=h(T);var ze=T.nodeType,ce=void 0;if(ze===k.nodeType&&(ze===Ve?(ke?ke!==ie&&((le=S[ke])?Ae===le?ce=!1:(y.insertBefore(le,T),ie?x(ie):f(T,y,!0),T=le,ie=h(T)):ce=!1):ie&&(ce=!1),ce=ce!==!1&&st(T,k),ce&&R(T,k)):(ze===Si||ze==ki)&&(ce=!0,T.nodeValue!==k.nodeValue&&(T.nodeValue=k.nodeValue))),ce){k=Ke,T=Ae;continue e}ie?x(ie):f(T,y,!0),T=Ae}if(ke&&(le=S[ke])&&st(le,k))L||O(y,le),R(le,k);else{var Et=l(k);Et!==!1&&(Et&&(k=Et),k.actualize&&(k=k.actualize(y.ownerDocument||F)),O(y,k),N(k))}k=Ke,T=Ae}J(y,T,ie);var Qt=yi[y.nodeName];Qt&&Qt(y,E)}var _=i,Xe=_.nodeType,Zt=s.nodeType;if(!q){if(Xe===Ve)Zt===Ve?st(i,s)||(u(i),_=un(i,dn(s.nodeName,s.namespaceURI))):_=s;else if(Xe===Si||Xe===ki){if(Zt===Xe)return _.nodeValue!==s.nodeValue&&(_.nodeValue=s.nodeValue),_;_=s}}if(_===s)u(i);else{if(s.isSameNode&&s.isSameNode(_))return;if(R(_,s,q),C)for(var wt=0,fs=C.length;wt<fs;wt++){var yt=S[C[wt]];yt&&f(yt,yt.parentNode,!1)}}return!q&&_!==i&&i.parentNode&&(_.actualize&&(_=_.actualize(i.ownerDocument||F)),i.parentNode.replaceChild(_,i)),_}}var mn=pn(sn),$t=mn,nt=class{constructor(e,t,i,s,n,r,o={}){this.view=e,this.liveSocket=e.liveSocket,this.container=t,this.id=i,this.rootID=e.root.id,this.html=s,this.streams=n,this.streamInserts={},this.streamComponentRestore={},this.targetCID=r,this.cidPatch=ne(this.targetCID),this.pendingRemoves=[],this.phxRemove=this.liveSocket.binding("remove"),this.targetContainer=this.isCIDPatch()?this.targetCIDContainer(s):t,this.callbacks={beforeadded:[],beforeupdated:[],beforephxChildAdded:[],afteradded:[],afterupdated:[],afterdiscarded:[],afterphxChildAdded:[],aftertransitionsDiscarded:[]},this.withChildren=o.withChildren||o.undoRef||!1,this.undoRef=o.undoRef}before(e,t){this.callbacks[`before${e}`].push(t)}after(e,t){this.callbacks[`after${e}`].push(t)}trackBefore(e,...t){this.callbacks[`before${e}`].forEach(i=>i(...t))}trackAfter(e,...t){this.callbacks[`after${e}`].forEach(i=>i(...t))}markPrunableContentForRemoval(){let e=this.liveSocket.binding(ut);c.all(this.container,`[${e}=append] > *, [${e}=prepend] > *`,t=>{t.setAttribute(si,"")})}perform(e){let{view:t,liveSocket:i,html:s,container:n}=this,r=this.targetContainer;if(this.isCIDPatch()&&!this.targetContainer)return;if(this.isCIDPatch()){let S=r.closest(`[${D}]`);if(S&&!S.isSameNode(r)){let C=c.private(S,D);C&&(r=C.querySelector(`[data-phx-component="${this.targetCID}"]`))}}let o=i.getActiveElement(),{selectionStart:a,selectionEnd:h}=o&&c.hasSelectionRange(o)?o:{},l=i.binding(ut),d=i.binding(Lt),p=i.binding(Dt),m=i.binding(xs),g=[],u=[],v=[],w=[],O=null,q=(S,C,x=this.withChildren)=>{let H={childrenOnly:S.getAttribute(Z)===null&&!x,getNodeKey:f=>c.isPhxDestroyed(f)?null:e?f.id:f.id||f.getAttribute&&f.getAttribute(Di),skipFromChildren:f=>f.getAttribute(l)===at,addChild:(f,b)=>{let{ref:N,streamAt:J}=this.getStreamInsert(b);if(N===void 0)return f.appendChild(b);if(this.setStreamRef(b,N),J===0)f.insertAdjacentElement("afterbegin",b);else if(J===-1){let R=f.lastElementChild;if(R&&!R.hasAttribute($e)){let Se=Array.from(f.children).find(_=>!_.hasAttribute($e));f.insertBefore(b,Se)}else f.appendChild(b)}else if(J>0){let R=Array.from(f.children)[J];f.insertBefore(b,R)}},onBeforeNodeAdded:f=>{if(this.getStreamInsert(f)?.updateOnly&&!this.streamComponentRestore[f.id])return!1;c.maintainPrivateHooks(f,f,d,p),this.trackBefore("added",f);let b=f;return this.streamComponentRestore[f.id]&&(b=this.streamComponentRestore[f.id],delete this.streamComponentRestore[f.id],q(b,f,!0)),b},onNodeAdded:f=>{f.getAttribute&&this.maybeReOrderStream(f,!0),c.isPortalTemplate(f)&&w.push(()=>this.teleport(f,q)),f instanceof HTMLImageElement&&f.srcset?f.srcset=f.srcset:f instanceof HTMLVideoElement&&f.autoplay&&f.play(),c.isNowTriggerFormExternal(f,m)&&(O=f),(c.isPhxChild(f)&&t.ownsElement(f)||c.isPhxSticky(f)&&t.ownsElement(f.parentNode))&&this.trackAfter("phxChildAdded",f),f.nodeName==="SCRIPT"&&f.hasAttribute(ht)&&this.handleRuntimeHook(f,C),g.push(f)},onNodeDiscarded:f=>this.onNodeDiscarded(f),onBeforeNodeDiscarded:f=>{if(f.getAttribute&&f.getAttribute(si)!==null)return!0;if(f.parentElement!==null&&f.id&&c.isPhxUpdate(f.parentElement,l,[at,"append","prepend"])||f.getAttribute&&f.getAttribute(Ee)||this.maybePendingRemove(f)||this.skipCIDSibling(f))return!1;if(c.isPortalTemplate(f)){let b=document.getElementById(f.content.firstElementChild.id);b&&(b.remove(),H.onNodeDiscarded(b),this.view.dropPortalElementId(b.id))}return!0},onElUpdated:f=>{c.isNowTriggerFormExternal(f,m)&&(O=f),u.push(f),this.maybeReOrderStream(f,!1)},onBeforeElUpdated:(f,b)=>{if(f.id&&f.isSameNode(S)&&f.id!==b.id)return H.onNodeDiscarded(f),f.replaceWith(b),H.onNodeAdded(b);if(c.syncPendingAttrs(f,b),c.maintainPrivateHooks(f,b,d,p),c.cleanChildNodes(b,l),this.skipCIDSibling(b))return this.maybeReOrderStream(f),!1;if(c.isPhxSticky(f))return[Q,we,re].map(R=>[R,f.getAttribute(R),b.getAttribute(R)]).forEach(([R,Se,_])=>{_&&Se!==_&&f.setAttribute(R,_)}),!1;if(c.isIgnored(f,l)||f.form&&f.form.isSameNode(O))return this.trackBefore("updated",f,b),c.mergeAttrs(f,b,{isIgnored:c.isIgnored(f,l)}),u.push(f),c.applyStickyOperations(f),!1;if(f.type==="number"&&f.validity&&f.validity.badInput)return!1;let N=o&&f.isSameNode(o)&&c.isFormInput(f),J=N&&this.isChangedSelect(f,b);if(f.hasAttribute(W)){let R=new Nt(f);if(R.lockRef&&(!this.undoRef||!R.isLockUndoneBy(this.undoRef))){c.applyStickyOperations(f);let _=f.hasAttribute(D)?c.private(f,D)||f.cloneNode(!0):null;_&&(c.putPrivate(f,D,_),N||(f=_))}}if(c.isPhxChild(b)){let R=f.getAttribute(Q);return c.mergeAttrs(f,b,{exclude:[we]}),R!==""&&f.setAttribute(Q,R),f.setAttribute(re,this.rootID),c.applyStickyOperations(f),!1}return this.undoRef&&c.private(b,D)&&c.putPrivate(f,D,c.private(b,D)),c.copyPrivates(b,f),c.isPortalTemplate(b)?(w.push(()=>this.teleport(b,q)),f.content.replaceChildren(b.content.cloneNode(!0)),!1):N&&f.type!=="hidden"&&!J?(this.trackBefore("updated",f,b),c.mergeFocusedInput(f,b),c.syncAttrsToProps(f),u.push(f),c.applyStickyOperations(f),!1):(J&&f.blur(),c.isPhxUpdate(b,l,["append","prepend"])&&v.push(new tn(f,b,b.getAttribute(l))),c.syncAttrsToProps(b),c.applyStickyOperations(b),this.trackBefore("updated",f,b),f)}};$t(S,C,H)};if(this.trackBefore("added",n),this.trackBefore("updated",n,n),i.time("morphdom",()=>{this.streams.forEach(([C,x,H,f])=>{x.forEach(([b,N,J,R])=>{this.streamInserts[b]={ref:C,streamAt:N,limit:J,reset:f,updateOnly:R}}),f!==void 0&&c.all(document,`[${$e}="${C}"]`,b=>{this.removeStreamChildElement(b)}),H.forEach(b=>{let N=document.getElementById(b);N&&this.removeStreamChildElement(N)})}),e&&c.all(this.container,`[${l}=${at}]`).filter(C=>this.view.ownsElement(C)).forEach(C=>{Array.from(C.children).forEach(x=>{this.removeStreamChildElement(x,!0)})}),q(r,s);let S=0;for(;w.length>0&&S<5;){let C=w.slice();w=[],C.forEach(x=>x()),S++}this.view.portalElementIds.forEach(C=>{let x=document.getElementById(C);x&&(document.getElementById(x.getAttribute(fe))||(x.remove(),this.onNodeDiscarded(x),this.view.dropPortalElementId(C)))})}),i.isDebugEnabled()&&(Vs(),Ws(this.streamInserts),Array.from(document.querySelectorAll("input[name=id]")).forEach(S=>{S instanceof HTMLInputElement&&S.form&&console.error(`Detected an input with name="id" inside a form! This will cause problems when patching the DOM.
`,S)})),v.length>0&&i.time("post-morph append/prepend restoration",()=>{v.forEach(S=>S.perform())}),i.silenceEvents(()=>c.restoreFocus(o,a,h)),c.dispatchEvent(document,"phx:update"),g.forEach(S=>this.trackAfter("added",S)),u.forEach(S=>this.trackAfter("updated",S)),this.transitionPendingRemoves(),O){i.unload();let S=c.private(O,"submitter");if(S&&S.name&&r.contains(S)){let C=document.createElement("input");C.type="hidden";let x=S.getAttribute("form");x&&C.setAttribute("form",x),C.name=S.name,C.value=S.value,S.parentElement.insertBefore(C,S)}Object.getPrototypeOf(O).submit.call(O)}return!0}onNodeDiscarded(e){(c.isPhxChild(e)||c.isPhxSticky(e))&&this.liveSocket.destroyViewByEl(e),this.trackAfter("discarded",e)}maybePendingRemove(e){return e.getAttribute&&e.getAttribute(this.phxRemove)!==null?(this.pendingRemoves.push(e),!0):!1}removeStreamChildElement(e,t=!1){!t&&!this.view.ownsElement(e)||(this.streamInserts[e.id]?(this.streamComponentRestore[e.id]=e,e.remove()):this.maybePendingRemove(e)||(e.remove(),this.onNodeDiscarded(e)))}getStreamInsert(e){return(e.id?this.streamInserts[e.id]:{})||{}}setStreamRef(e,t){c.putSticky(e,$e,i=>i.setAttribute($e,t))}maybeReOrderStream(e,t){let{ref:i,streamAt:s,reset:n}=this.getStreamInsert(e);if(s!==void 0&&(this.setStreamRef(e,i),!(!n&&!t)&&e.parentElement)){if(s===0)e.parentElement.insertBefore(e,e.parentElement.firstElementChild);else if(s>0){let r=Array.from(e.parentElement.children),o=r.indexOf(e);if(s>=r.length-1)e.parentElement.appendChild(e);else{let a=r[s];o>s?e.parentElement.insertBefore(e,a):e.parentElement.insertBefore(e,a.nextElementSibling)}}this.maybeLimitStream(e)}}maybeLimitStream(e){let{limit:t}=this.getStreamInsert(e),i=t!==null&&Array.from(e.parentElement.children);t&&t<0&&i.length>t*-1?i.slice(0,i.length+t).forEach(s=>this.removeStreamChildElement(s)):t&&t>=0&&i.length>t&&i.slice(t).forEach(s=>this.removeStreamChildElement(s))}transitionPendingRemoves(){let{pendingRemoves:e,liveSocket:t}=this;e.length>0&&t.transitionRemoves(e,()=>{e.forEach(i=>{let s=c.firstPhxChild(i);s&&t.destroyViewByEl(s),i.remove()}),this.trackAfter("transitionsDiscarded",e)})}isChangedSelect(e,t){return!(e instanceof HTMLSelectElement)||e.multiple?!1:e.options.length!==t.options.length?!0:(t.value=e.value,!e.isEqualNode(t))}isCIDPatch(){return this.cidPatch}skipCIDSibling(e){return e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute(Li)}targetCIDContainer(e){if(!this.isCIDPatch())return;let[t,...i]=c.findComponentNodeList(this.view.id,this.targetCID);return i.length===0&&c.childNodeLength(e)===1?t:t&&t.parentNode}indexOf(e,t){return Array.from(e.children).indexOf(t)}teleport(e,t){let i=e.getAttribute(Bt),s=document.querySelector(i);if(!s)throw new Error("portal target with selector "+i+" not found");let n=e.content.firstElementChild;if(this.skipCIDSibling(n))return;if(!n?.id)throw new Error("phx-portal template must have a single root element with ID!");let r=document.getElementById(n.id),o;r?(s.contains(r)||s.appendChild(r),o=r):(o=document.createElement(n.tagName),s.appendChild(o)),n.setAttribute(Ee,this.view.id),n.setAttribute(fe,e.id),t(o,n,!0),n.removeAttribute(Ee),n.removeAttribute(fe),this.view.pushPortalElementId(n.id)}handleRuntimeHook(e,t){let i=e.getAttribute(ht),s=e.hasAttribute("nonce")?e.getAttribute("nonce"):null;if(e.hasAttribute("nonce")){let r=document.createElement("template");r.innerHTML=t,s=r.content.querySelector(`script[${ht}="${CSS.escape(i)}"]`).getAttribute("nonce")}let n=document.createElement("script");n.textContent=e.textContent,c.mergeAttrs(n,e,{isIgnored:!1}),s&&(n.nonce=s),e.replaceWith(n),e=n}},gn=new Set(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]),vn=new Set(["'",'"']),Ai=(e,t,i)=>{let s=0,n=!1,r,o,a,h,l,d,p=e.match(/^(\s*(?:<!--.*?-->\s*)*)<([^\s\/>]+)/);if(p===null)throw new Error(`malformed html ${e}`);for(s=p[0].length,r=p[1],a=p[2],h=s,s;s<e.length&&e.charAt(s)!==">";s++)if(e.charAt(s)==="="){let u=e.slice(s-3,s)===" id";s++;let v=e.charAt(s);if(vn.has(v)){let w=s;for(s++,s;s<e.length&&e.charAt(s)!==v;s++);if(u){l=e.slice(w+1,s);break}}}let m=e.length-1;for(n=!1;m>=r.length+a.length;){let u=e.charAt(m);if(n)u==="-"&&e.slice(m-3,m)==="<!-"?(n=!1,m-=4):m-=1;else if(u===">"&&e.slice(m-2,m)==="--")n=!0,m-=3;else{if(u===">")break;m-=1}}o=e.slice(m+1,e.length);let g=Object.keys(t).map(u=>t[u]===!0?u:`${u}="${t[u]}"`).join(" ");if(i){let u=l?` id="${l}"`:"";gn.has(a)?d=`<${a}${u}${g===""?"":" "}${g}/>`:d=`<${a}${u}${g===""?"":" "}${g}></${a}>`}else{let u=e.slice(h,m+1);d=`<${a}${g===""?"":" "}${g}${u}`}return[d,r,o]},Ci=class{static extract(e){let{[pi]:t,[fi]:i,[mi]:s}=e;return delete e[pi],delete e[fi],delete e[mi],{diff:e,title:s,reply:t||null,events:i||[]}}constructor(e,t){this.viewId=e,this.rendered={},this.magicId=0,this.mergeDiff(t)}parentViewId(){return this.viewId}toString(e){let{buffer:t,streams:i}=this.recursiveToString(this.rendered,this.rendered[$],e,!0,{});return{buffer:t,streams:i}}recursiveToString(e,t=e[$],i,s,n){i=i?new Set(i):null;let r={buffer:"",components:t,onlyCids:i,streams:new Set};return this.toOutputBuffer(e,null,r,s,n),{buffer:r.buffer,streams:r.streams}}componentCIDs(e){return Object.keys(e[$]||{}).map(t=>parseInt(t))}isComponentOnlyDiff(e){return e[$]?Object.keys(e).length===1:!1}getComponent(e,t){return e[$][t]}resetRender(e){this.rendered[$][e]&&(this.rendered[$][e].reset=!0)}mergeDiff(e){let t=e[$],i={};if(delete e[$],this.rendered=this.mutableMerge(this.rendered,e),this.rendered[$]=this.rendered[$]||{},t){let s=this.rendered[$];for(let n in t)t[n]=this.cachedFindComponent(n,t[n],s,t,i);for(let n in t)s[n]=t[n];e[$]=t}}cachedFindComponent(e,t,i,s,n){if(n[e])return n[e];{let r,o,a=t[V];if(ne(a)){let h;a>0?h=this.cachedFindComponent(a,s[a],i,s,n):h=i[-a],o=h[V],r=this.cloneMerge(h,t,!0),r[V]=o}else r=t[V]!==void 0||i[e]===void 0?t:this.cloneMerge(i[e],t,!1);return n[e]=r,r}}mutableMerge(e,t){return t[V]!==void 0?t:(this.doMutableMerge(e,t),e)}doMutableMerge(e,t){if(t[I])this.mergeKeyed(e,t);else for(let i in t){let s=t[i],n=e[i];xe(s)&&s[V]===void 0&&xe(n)?this.doMutableMerge(n,s):e[i]=s}e[Pt]&&(e.newRender=!0)}clone(e){return"structuredClone"in window?structuredClone(e):JSON.parse(JSON.stringify(e))}mergeKeyed(e,t){let i=this.clone(e);if(Object.entries(t[I]).forEach(([s,n])=>{if(s!==Y)if(Array.isArray(n)){let[r,o]=n;e[I][s]=i[I][r],this.doMutableMerge(e[I][s],o)}else if(typeof n=="number"){let r=n;e[I][s]=i[I][r]}else typeof n=="object"&&(e[I][s]||(e[I][s]={}),this.doMutableMerge(e[I][s],n))}),t[I][Y]<e[I][Y])for(let s=t[I][Y];s<e[I][Y];s++)delete e[I][s];e[I][Y]=t[I][Y],t[Pe]&&(e[Pe]=t[Pe]),t[de]&&(e[de]=t[de])}cloneMerge(e,t,i){let s;if(t[I])s=this.clone(e),this.mergeKeyed(s,t);else{s={...e,...t};for(let n in s){let r=t[n],o=e[n];xe(r)&&r[V]===void 0&&xe(o)?s[n]=this.cloneMerge(o,r,i):r===void 0&&xe(o)&&(s[n]=this.cloneMerge(o,{},i))}}return i?(delete s.magicId,delete s.newRender):e[Pt]&&(s.newRender=!0),s}componentToString(e){let{buffer:t,streams:i}=this.recursiveCIDToString(this.rendered[$],e,null),[s,n,r]=Ai(t,{});return{buffer:s,streams:i}}pruneCIDs(e){e.forEach(t=>delete this.rendered[$][t])}get(){return this.rendered}isNewFingerprint(e={}){return!!e[V]}templateStatic(e,t){return typeof e=="number"?t[e]:e}nextMagicID(){return this.magicId++,`m${this.magicId}-${this.parentViewId()}`}toOutputBuffer(e,t,i,s,n={}){if(e[I])return this.comprehensionToBuffer(e,t,i,s);e[de]&&(t=e[de],delete e[de]);let{[V]:r}=e;r=this.templateStatic(r,t),e[V]=r;let o=e[Pt],a=i.buffer;o&&(i.buffer=""),s&&o&&!e.magicId&&(e.newRender=!0,e.magicId=this.nextMagicID()),i.buffer+=r[0];for(let h=1;h<r.length;h++)this.dynamicToBuffer(e[h-1],t,i,s),i.buffer+=r[h];if(o){let h=!1,l;s||e.magicId?(h=s&&!e.newRender,l={[Di]:e.magicId,...n}):l=n,h&&(l[Li]=!0);let[d,p,m]=Ai(i.buffer,l,h);e.newRender=!1,i.buffer=a+p+d+m}}comprehensionToBuffer(e,t,i,s){let n=t||e[de],r=this.templateStatic(e[V],t);e[V]=r,delete e[de];for(let o=0;o<e[I][Y];o++){i.buffer+=r[0];for(let a=1;a<r.length;a++)this.dynamicToBuffer(e[I][o][a-1],n,i,s),i.buffer+=r[a]}if(e[Pe]){let o=e[Pe],[a,h,l,d]=o||[null,{},[],null];o!==void 0&&(e[I][Y]>0||l.length>0||d)&&(delete e[Pe],e[I]={[Y]:0},i.streams.add(o))}}dynamicToBuffer(e,t,i,s){if(typeof e=="number"){let{buffer:n,streams:r}=this.recursiveCIDToString(i.components,e,i.onlyCids);i.buffer+=n,i.streams=new Set([...i.streams,...r])}else xe(e)?this.toOutputBuffer(e,t,i,s,{}):i.buffer+=e}recursiveCIDToString(e,t,i){let s=e[t]||P(`no component for CID ${t}`,e),n={[Z]:t,[Le]:this.viewId},r=i&&!i.has(t);s.newRender=!r,s.magicId=`c${t}-${this.parentViewId()}`;let o=!s.reset,{buffer:a,streams:h}=this.recursiveToString(s,e,i,o,n);return delete s.reset,{buffer:a,streams:h}}},Ti=[],_i=200,bn={exec(e,t,i,s,n,r){let[o,a]=r||[null,{callback:r&&r.callback}];(i.charAt(0)==="["?JSON.parse(i):[[o,a]]).forEach(([l,d])=>{l===o&&(d={...a,...d},d.callback=d.callback||a.callback),this.filterToEls(s.liveSocket,n,d).forEach(p=>{this[`exec_${l}`](e,t,i,s,n,p,d)})})},isVisible(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length>0)},isInViewport(e){let t=e.getBoundingClientRect(),i=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth;return t.right>0&&t.bottom>0&&t.left<s&&t.top<i},exec_exec(e,t,i,s,n,r,{attr:o,to:a}){let h=r.getAttribute(o);if(!h)throw new Error(`expected ${o} to contain JS command on "${a}"`);s.liveSocket.execJS(r,h,t)},exec_dispatch(e,t,i,s,n,r,{event:o,detail:a,bubbles:h,blocking:l}){if(a=a||{},a.dispatcher=n,l){let d=new Promise((p,m)=>{a.done=p});s.liveSocket.asyncTransition(d)}c.dispatchEvent(r,o,{detail:a,bubbles:h})},exec_push(e,t,i,s,n,r,o){let{event:a,data:h,target:l,page_loading:d,loading:p,value:m,dispatcher:g,callback:u}=o,v={loading:p,value:m,target:l,page_loading:!!d,originalEvent:e},w=t==="change"&&g?g:n,O=l||w.getAttribute(s.binding("target"))||w,q=(S,C)=>{if(S.isConnected())if(t==="change"){let{newCid:x,_target:H}=o;H=H||(c.isFormInput(n)?n.name:void 0),H&&(v._target=H),S.pushInput(n,C,x,a||i,v,u)}else if(t==="submit"){let{submitter:x}=o;S.submitForm(n,C,a||i,x,v,u)}else S.pushEvent(t,n,C,a||i,h,v,u)};o.targetView&&o.targetCtx?q(o.targetView,o.targetCtx):s.withinTargets(O,q)},exec_navigate(e,t,i,s,n,r,{href:o,replace:a}){s.liveSocket.historyRedirect(e,o,a?"replace":"push",null,n)},exec_patch(e,t,i,s,n,r,{href:o,replace:a}){s.liveSocket.pushHistoryPatch(e,o,a?"replace":"push",n)},exec_focus(e,t,i,s,n,r){j.attemptFocus(r),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>j.attemptFocus(r))})},exec_focus_first(e,t,i,s,n,r){j.focusFirstInteractive(r)||j.focusFirst(r),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>j.focusFirstInteractive(r)||j.focusFirst(r))})},exec_push_focus(e,t,i,s,n,r){Ti.push(r||n)},exec_pop_focus(e,t,i,s,n,r){let o=Ti.pop();o&&(o.focus(),window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>o.focus())}))},exec_add_class(e,t,i,s,n,r,{names:o,transition:a,time:h,blocking:l}){this.addOrRemoveClasses(r,o,[],a,h,s,l)},exec_remove_class(e,t,i,s,n,r,{names:o,transition:a,time:h,blocking:l}){this.addOrRemoveClasses(r,[],o,a,h,s,l)},exec_toggle_class(e,t,i,s,n,r,{names:o,transition:a,time:h,blocking:l}){this.toggleClasses(r,o,a,h,s,l)},exec_toggle_attr(e,t,i,s,n,r,{attr:[o,a,h]}){this.toggleAttr(r,o,a,h)},exec_ignore_attrs(e,t,i,s,n,r,{attrs:o}){this.ignoreAttrs(r,o)},exec_transition(e,t,i,s,n,r,{time:o,transition:a,blocking:h}){this.addOrRemoveClasses(r,[],[],a,o,s,h)},exec_toggle(e,t,i,s,n,r,{display:o,ins:a,outs:h,time:l,blocking:d}){this.toggle(t,s,r,o,a,h,l,d)},exec_show(e,t,i,s,n,r,{display:o,transition:a,time:h,blocking:l}){this.show(t,s,r,o,a,h,l)},exec_hide(e,t,i,s,n,r,{display:o,transition:a,time:h,blocking:l}){this.hide(t,s,r,o,a,h,l)},exec_set_attr(e,t,i,s,n,r,{attr:[o,a]}){this.setOrRemoveAttrs(r,[[o,a]],[])},exec_remove_attr(e,t,i,s,n,r,{attr:o}){this.setOrRemoveAttrs(r,[],[o])},ignoreAttrs(e,t){c.putPrivate(e,"JS:ignore_attrs",{apply:(i,s)=>{let n=Array.from(i.attributes),r=n.map(o=>o.name);Array.from(s.attributes).filter(o=>!r.includes(o.name)).forEach(o=>{c.attributeIgnored(o,t)&&s.removeAttribute(o.name)}),n.forEach(o=>{c.attributeIgnored(o,t)&&s.setAttribute(o.name,o.value)})}})},onBeforeElUpdated(e,t){let i=c.private(e,"JS:ignore_attrs");i&&i.apply(e,t)},show(e,t,i,s,n,r,o){this.isVisible(i)||this.toggle(e,t,i,s,n,null,r,o)},hide(e,t,i,s,n,r,o){this.isVisible(i)&&this.toggle(e,t,i,s,null,n,r,o)},toggle(e,t,i,s,n,r,o,a){o=o||_i;let[h,l,d]=n||[[],[],[]],[p,m,g]=r||[[],[],[]];if(h.length>0||p.length>0)if(this.isVisible(i)){let u=()=>{this.addOrRemoveClasses(i,m,h.concat(l).concat(d)),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(i,p,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(i,g,m))})},v=()=>{this.addOrRemoveClasses(i,[],p.concat(g)),c.putSticky(i,"toggle",w=>w.style.display="none"),i.dispatchEvent(new Event("phx:hide-end"))};i.dispatchEvent(new Event("phx:hide-start")),a===!1?(u(),setTimeout(v,o)):t.transition(o,u,v)}else{if(e==="remove")return;let u=()=>{this.addOrRemoveClasses(i,l,p.concat(m).concat(g));let w=s||this.defaultDisplay(i);window.requestAnimationFrame(()=>{this.addOrRemoveClasses(i,h,[]),window.requestAnimationFrame(()=>{c.putSticky(i,"toggle",O=>O.style.display=w),this.addOrRemoveClasses(i,d,l)})})},v=()=>{this.addOrRemoveClasses(i,[],h.concat(d)),i.dispatchEvent(new Event("phx:show-end"))};i.dispatchEvent(new Event("phx:show-start")),a===!1?(u(),setTimeout(v,o)):t.transition(o,u,v)}else this.isVisible(i)?window.requestAnimationFrame(()=>{i.dispatchEvent(new Event("phx:hide-start")),c.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=s||this.defaultDisplay(i);c.putSticky(i,"toggle",v=>v.style.display=u),i.dispatchEvent(new Event("phx:show-end"))})},toggleClasses(e,t,i,s,n,r){window.requestAnimationFrame(()=>{let[o,a]=c.getSticky(e,"classes",[[],[]]),h=t.filter(d=>o.indexOf(d)<0&&!e.classList.contains(d)),l=t.filter(d=>a.indexOf(d)<0&&e.classList.contains(d));this.addOrRemoveClasses(e,h,l,i,s,n,r)})},toggleAttr(e,t,i,s){e.hasAttribute(t)?s!==void 0?e.getAttribute(t)===i?this.setOrRemoveAttrs(e,[[t,s]],[]):this.setOrRemoveAttrs(e,[[t,i]],[]):this.setOrRemoveAttrs(e,[],[t]):this.setOrRemoveAttrs(e,[[t,i]],[])},addOrRemoveClasses(e,t,i,s,n,r,o){n=n||_i;let[a,h,l]=s||[[],[],[]];if(a.length>0){let d=()=>{this.addOrRemoveClasses(e,h,[].concat(a).concat(l)),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(e,a,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(e,l,h))})},p=()=>this.addOrRemoveClasses(e,t.concat(l),i.concat(a).concat(h));o===!1?(d(),setTimeout(p,n)):r.transition(n,d,p);return}window.requestAnimationFrame(()=>{let[d,p]=c.getSticky(e,"classes",[[],[]]),m=t.filter(w=>d.indexOf(w)<0&&!e.classList.contains(w)),g=i.filter(w=>p.indexOf(w)<0&&e.classList.contains(w)),u=d.filter(w=>i.indexOf(w)<0).concat(m),v=p.filter(w=>t.indexOf(w)<0).concat(g);c.putSticky(e,"classes",w=>(w.classList.remove(...v),w.classList.add(...u),[u,v]))})},setOrRemoveAttrs(e,t,i){let[s,n]=c.getSticky(e,"attrs",[[],[]]),r=t.map(([h,l])=>h).concat(i),o=s.filter(([h,l])=>!r.includes(h)).concat(t),a=n.filter(h=>!r.includes(h)).concat(i);c.putSticky(e,"attrs",h=>(a.forEach(l=>h.removeAttribute(l)),o.forEach(([l,d])=>h.setAttribute(l,d)),[o,a]))},hasAllClasses(e,t){return t.every(i=>e.classList.contains(i))},isToggledOut(e,t){return!this.isVisible(e)||this.hasAllClasses(e,t)},filterToEls(e,t,{to:i}){let s=()=>{if(typeof i=="string")return document.querySelectorAll(i);if(i.closest){let n=t.closest(i.closest);return n?[n]:[]}else if(i.inner)return t.querySelectorAll(i.inner)};return i?e.jsQuerySelectorAll(t,i,s):[t]},defaultDisplay(e){return{tr:"table-row",td:"table-cell"}[e.tagName.toLowerCase()]||"block"},transitionClasses(e){if(!e)return null;let[t,i,s]=Array.isArray(e)?e:[e.split(" "),[],[]];return t=Array.isArray(t)?t:t.split(" "),i=Array.isArray(i)?i:i.split(" "),s=Array.isArray(s)?s:s.split(" "),[t,i,s]}},A=bn,Ni=(e,t)=>({exec(i,s){e.execJS(i,s,t)},show(i,s={}){let n=e.owner(i);A.show(t,n,i,s.display,A.transitionClasses(s.transition),s.time,s.blocking)},hide(i,s={}){let n=e.owner(i);A.hide(t,n,i,null,A.transitionClasses(s.transition),s.time,s.blocking)},toggle(i,s={}){let n=e.owner(i),r=A.transitionClasses(s.in),o=A.transitionClasses(s.out);A.toggle(t,n,i,s.display,r,o,s.time,s.blocking)},addClass(i,s,n={}){let r=Array.isArray(s)?s:s.split(" "),o=e.owner(i);A.addOrRemoveClasses(i,r,[],A.transitionClasses(n.transition),n.time,o,n.blocking)},removeClass(i,s,n={}){let r=Array.isArray(s)?s:s.split(" "),o=e.owner(i);A.addOrRemoveClasses(i,[],r,A.transitionClasses(n.transition),n.time,o,n.blocking)},toggleClass(i,s,n={}){let r=Array.isArray(s)?s:s.split(" "),o=e.owner(i);A.toggleClasses(i,r,A.transitionClasses(n.transition),n.time,o,n.blocking)},transition(i,s,n={}){let r=e.owner(i);A.addOrRemoveClasses(i,[],[],A.transitionClasses(s),n.time,r,n.blocking)},setAttribute(i,s,n){A.setOrRemoveAttrs(i,[[s,n]],[])},removeAttribute(i,s){A.setOrRemoveAttrs(i,[],[s])},toggleAttribute(i,s,n,r){A.toggleAttr(i,s,n,r)},push(i,s,n={}){e.withinOwners(i,r=>{let o=n.value||{};delete n.value;let a=new CustomEvent("phx:exec",{detail:{sourceElement:i}});A.exec(a,t,s,r,i,["push",{data:o,...n}])})},navigate(i,s={}){let n=new CustomEvent("phx:exec");e.historyRedirect(n,i,s.replace?"replace":"push",null,null)},patch(i,s={}){let n=new CustomEvent("phx:exec");e.pushHistoryPatch(n,i,s.replace?"replace":"push",null)},ignoreAttributes(i,s){A.ignoreAttrs(i,Array.isArray(s)?s:[s])}}),Rt="hookId",Pi="deadHook",wn=1,ge=class $i{get liveSocket(){return this.__liveSocket()}static makeID(){return wn++}static elementID(t){return c.private(t,Rt)}static deadHook(t){return c.private(t,Pi)===!0}constructor(t,i,s){if(this.el=i,this.__attachView(t),this.__listeners=new Set,this.__isDisconnected=!1,c.putPrivate(this.el,Rt,$i.makeID()),t&&t.isDead&&c.putPrivate(this.el,Pi,!0),s){let n=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 s)Object.prototype.hasOwnProperty.call(s,o)&&(this[o]=s[o],n.has(o)&&console.warn(`Hook object for element #${i.id} overwrites core property '${o}'!`));["mounted","beforeUpdate","updated","destroyed","disconnected","reconnected"].forEach(o=>{s[o]&&typeof s[o]=="function"&&(this[o]=s[o])})}}__attachView(t){t?(this.__view=()=>t,this.__liveSocket=()=>t.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(){}updated(){}destroyed(){}disconnected(){}reconnected(){}__mounted(){this.mounted()}__updated(){this.updated()}__beforeUpdate(){this.beforeUpdate()}__destroyed(){this.destroyed(),c.deletePrivate(this.el,Rt)}__reconnected(){this.__isDisconnected&&(this.__isDisconnected=!1,this.reconnected())}__disconnected(){this.__isDisconnected=!0,this.disconnected()}js(){return{...Ni(this.__view().liveSocket,"hook"),exec:t=>{this.__view().liveSocket.execJS(this.el,t,"hook")}}}pushEvent(t,i,s){let n=this.__view().pushHookEvent(this.el,null,t,i||{});if(s===void 0)return n.then(({reply:r})=>r);n.then(({reply:r,ref:o})=>s(r,o)).catch(()=>{})}pushEventTo(t,i,s,n){if(n===void 0){let r=[];this.__view().withinTargets(t,(a,h)=>{r.push({view:a,targetCtx:h})});let o=r.map(({view:a,targetCtx:h})=>a.pushHookEvent(this.el,h,i,s||{}));return Promise.allSettled(o)}this.__view().withinTargets(t,(r,o)=>{r.pushHookEvent(this.el,o,i,s||{}).then(({reply:a,ref:h})=>n(a,h)).catch(()=>{})})}handleEvent(t,i){let s={event:t,callback:n=>i(n.detail)};return window.addEventListener(`phx:${t}`,s.callback),this.__listeners.add(s),s}removeHandleEvent(t){window.removeEventListener(`phx:${t.event}`,t.callback),this.__listeners.delete(t)}upload(t,i){return this.__view().dispatchUploads(null,t,i)}uploadTo(t,i,s){return this.__view().withinTargets(t,(n,r)=>{n.dispatchUploads(r,i,s)})}__cleanup__(){this.__listeners.forEach(t=>this.removeHandleEvent(t))}},yn=(e,t)=>{let i=e.endsWith("[]"),s=i?e.slice(0,-2):e;return s=s.replace(/([^\[\]]+)(\]?$)/,`${t}$1$2`),i&&(s+="[]"),s},rt=(e,t,i=[])=>{let{submitter:s}=t,n;if(s&&s.name){let d=document.createElement("input");d.type="hidden";let p=s.getAttribute("form");p&&d.setAttribute("form",p),d.name=s.name,d.value=s.value,s.parentElement.insertBefore(d,s),n=d}let r=new FormData(e),o=[];r.forEach((d,p,m)=>{d instanceof File&&o.push(p)}),o.forEach(d=>r.delete(d));let a=new URLSearchParams,{inputsUnused:h,onlyHiddenInputs:l}=Array.from(e.elements).reduce((d,p)=>{let{inputsUnused:m,onlyHiddenInputs:g}=d,u=p.name;if(!u)return d;m[u]===void 0&&(m[u]=!0),g[u]===void 0&&(g[u]=!0);let v=c.private(p,ct)||c.private(p,We),w=p.type==="hidden";return m[u]=m[u]&&!v,g[u]=g[u]&&w,d},{inputsUnused:{},onlyHiddenInputs:{}});for(let[d,p]of r.entries())if(i.length===0||i.indexOf(d)>=0){let m=h[d],g=l[d];m&&!(s&&s.name==d)&&!g&&a.append(yn(d,"_unused_"),""),typeof p=="string"&&a.append(d,p)}return s&&n&&s.parentElement.removeChild(n),a.toString()},En=class Fi{static closestView(t){let i=t.closest(qe);return i?c.private(i,"view"):null}constructor(t,i,s,n,r){this.isDead=!1,this.liveSocket=i,this.flash=n,this.parent=s,this.root=s?s.root:this,this.el=t;let o=c.private(this.el,"view");if(o!==void 0&&o.isDead!==!0)throw P(`The DOM element for this view has already been bound to a view.
An element can only ever be associated with a single view!
Please ensure that you are not trying to initialize multiple LiveSockets on the same page.
This could happen if you're accidentally trying to render your root layout more than once.
Ensure that the template set on the LiveView is different than the root layout.
`,{view:o}),new Error("Cannot bind multiple views to the same DOM element.");c.putPrivate(this.el,"view",this),this.id=this.el.id,this.el.setAttribute(re,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.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,sticky:this.el.hasAttribute(Ot)}}),this.portalElementIds=new Set}setHref(t){this.href=t}setRedirect(t){this.redirect=!0,this.href=t}isMain(){return this.el.hasAttribute(Ut)}connectParams(t){let i=this.liveSocket.params(this.el),s=c.all(document,`[${this.binding(Cs)}]`).map(n=>n.src||n.href).filter(n=>typeof n=="string");return s.length>0&&(i._track_static=s),i._mounts=this.joinCount,i._mount_attempts=this.joinAttempts,i._live_referer=t,this.joinAttempts++,i}isConnected(){return this.channel.canPush()}getSession(){return this.el.getAttribute(Q)}getStatic(){let t=this.el.getAttribute(we);return t===""?null:t}destroy(t=function(){}){this.destroyAllChildren(),this.destroyPortalElements(),this.destroyed=!0,c.deletePrivate(this.el,"view"),delete this.root.children[this.id],this.parent&&delete this.root.children[this.parent.id][this.id],clearTimeout(this.loaderTimer);let i=()=>{t();for(let s in this.viewHooks)this.destroyHook(this.viewHooks[s])};c.markPhxChildDestroyed(this.el),this.log("destroyed",()=>["the child has been removed from the parent"]),this.channel.leave().receive("ok",i).receive("error",i).receive("timeout",i)}setContainerClasses(...t){this.el.classList.remove(ni,me,_e,ri,He),this.el.classList.add(...t)}showLoader(t){if(clearTimeout(this.loaderTimer),t)this.loaderTimer=setTimeout(()=>this.showLoader(),t);else{for(let i in this.viewHooks)this.viewHooks[i].__disconnected();this.setContainerClasses(me)}}execAll(t){c.all(this.el,`[${t}]`,i=>this.liveSocket.execJS(i,i.getAttribute(t)))}hideLoader(){clearTimeout(this.loaderTimer),clearTimeout(this.disconnectedTimer),this.setContainerClasses(ni),this.execAll(this.binding("connected"))}triggerReconnected(){for(let t in this.viewHooks)this.viewHooks[t].__reconnected()}log(t,i){this.liveSocket.log(this,t,i)}transition(t,i,s=function(){}){this.liveSocket.transition(t,i,s)}withinTargets(t,i,s=document){if(t instanceof HTMLElement||t instanceof SVGElement)return this.liveSocket.owner(t,n=>i(n,t));if(ne(t))c.findComponentNodeList(this.id,t,s).length===0?P(`no component found matching phx-target of ${t}`):i(this,parseInt(t));else{let n=Array.from(s.querySelectorAll(t));n.length===0&&P(`nothing found matching the phx-target selector "${t}"`),n.forEach(r=>this.liveSocket.owner(r,o=>i(o,r)))}}applyDiff(t,i,s){this.log(t,()=>["",lt(i)]);let{diff:n,reply:r,events:o,title:a}=Ci.extract(i),h=o.reduce((d,p)=>(p.length===3&&p[2]==!0?d.pre.push(p.slice(0,-1)):d.post.push(p),d),{pre:[],post:[]});this.liveSocket.dispatchEvents(h.pre);let l=()=>{s({diff:n,reply:r,events:h.post}),(typeof a=="string"||t=="mount"&&this.isMain())&&window.requestAnimationFrame(()=>c.putTitle(a))};"onDocumentPatch"in this.liveSocket.domCallbacks?this.liveSocket.triggerDOM("onDocumentPatch",[l]):l()}onJoin(t){let{rendered:i,container:s,liveview_version:n,pid:r}=t;if(s){let[o,a]=s;this.el=c.replaceRootContainer(this.el,o,a)}this.childJoins=0,this.joinPending=!0,this.flash=null,this.root===this&&(this.formsForRecovery=this.getFormsForRecovery()),this.isMain()&&window.history.state===null&&U.pushState("replace",{type:"patch",id:this.id,position:this.liveSocket.currentHistoryPosition}),n!==this.liveSocket.version()&&console.warn(`LiveView asset version mismatch. JavaScript version ${this.liveSocket.version()} vs. server ${n}. To avoid issues, please ensure that your assets use the same version as the server.`),r&&this.el.setAttribute(Ds,r),U.dropLocal(this.liveSocket.localStorage,window.location.pathname,xi),this.applyDiff("mount",i,({diff:o,events:a})=>{this.rendered=new Ci(this.id,o);let[h,l]=this.renderContainer(null,"join");this.dropPendingRefs(),this.joinCount++,this.joinAttempts=0,this.maybeRecoverForms(h,()=>{this.onJoinComplete(t,h,l,a)})})}dropPendingRefs(){c.all(document,`[${W}="${this.refSrc()}"]`,t=>{t.removeAttribute(De),t.removeAttribute(W),t.removeAttribute(D)})}onJoinComplete({live_patch:t},i,s,n){if(this.joinCount>1||this.parent&&!this.parent.isJoinPending())return this.applyJoinPatch(t,i,s,n);c.findPhxChildrenInFragment(i,this.id).filter(o=>{let a=o.id&&this.el.querySelector(`[id="${o.id}"]`),h=a&&a.getAttribute(we);return h&&o.setAttribute(we,h),a&&a.setAttribute(re,this.root.id),this.joinChild(o)}).length===0?this.parent?(this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(t,i,s,n)]),this.parent.ackJoin(this)):(this.onAllChildJoinsComplete(),this.applyJoinPatch(t,i,s,n)):this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(t,i,s,n)])}attachTrueDocEl(){this.el=c.byId(this.id),this.el.setAttribute(re,this.root.id)}execNewMounted(t=document){let i=this.binding(Lt),s=this.binding(Dt);this.all(t,`[${i}], [${s}]`,n=>{c.maintainPrivateHooks(n,n,i,s),this.maybeAddNewHook(n)}),this.all(t,`[${this.binding(Ne)}], [data-phx-${Ne}]`,n=>{this.maybeAddNewHook(n)}),this.all(t,`[${this.binding(hi)}]`,n=>{this.maybeMounted(n)})}all(t,i,s){c.all(t,i,n=>{this.ownsElement(n)&&s(n)})}applyJoinPatch(t,i,s,n){this.joinCount>1&&this.pendingJoinOps.length&&(this.pendingJoinOps.forEach(o=>typeof o=="function"&&o()),this.pendingJoinOps=[]),this.attachTrueDocEl();let r=new nt(this,this.el,this.id,i,s,null);if(r.markPrunableContentForRemoval(),this.performPatch(r,!1,!0),this.joinNewChildren(),this.execNewMounted(),this.joinPending=!1,this.liveSocket.dispatchEvents(n),this.applyPendingUpdates(),t){let{kind:o,to:a}=t;this.liveSocket.historyPatch(a,o)}this.hideLoader(),this.joinCount>1&&this.triggerReconnected(),this.stopCallback()}triggerBeforeUpdateHook(t,i){this.liveSocket.triggerDOM("onBeforeElUpdated",[t,i]);let s=this.getHook(t),n=s&&c.isIgnored(t,this.binding(ut));if(s&&!t.isEqualNode(i)&&!(n&&Js(t.dataset,i.dataset)))return s.__beforeUpdate(),s}maybeMounted(t){let i=t.getAttribute(this.binding(hi)),s=i&&c.private(t,"mounted");i&&!s&&(this.liveSocket.execJS(t,i),c.putPrivate(t,"mounted",!0))}maybeAddNewHook(t){let i=this.addHook(t);i&&i.__mounted()}performPatch(t,i,s=!1){let n=[],r=!1,o=new Set;return this.liveSocket.triggerDOM("onPatchStart",[t.targetContainer]),t.after("added",a=>{this.liveSocket.triggerDOM("onNodeAdded",[a]);let h=this.binding(Lt),l=this.binding(Dt);c.maintainPrivateHooks(a,a,h,l),this.maybeAddNewHook(a),a.getAttribute&&this.maybeMounted(a)}),t.after("phxChildAdded",a=>{c.isPhxSticky(a)?this.liveSocket.joinRootViews():r=!0}),t.before("updated",(a,h)=>{this.triggerBeforeUpdateHook(a,h)&&o.add(a.id),A.onBeforeElUpdated(a,h)}),t.after("updated",a=>{o.has(a.id)&&this.getHook(a).__updated()}),t.after("discarded",a=>{a.nodeType===Node.ELEMENT_NODE&&n.push(a)}),t.after("transitionsDiscarded",a=>this.afterElementsRemoved(a,i)),t.perform(s),this.afterElementsRemoved(n,i),this.liveSocket.triggerDOM("onPatchEnd",[t.targetContainer]),r}afterElementsRemoved(t,i){let s=[];t.forEach(n=>{let r=c.all(n,`[${Le}="${this.id}"][${Z}]`),o=c.all(n,`[${this.binding(Ne)}], [data-phx-hook]`);r.concat(n).forEach(a=>{let h=this.componentID(a);ne(h)&&s.indexOf(h)===-1&&a.getAttribute(Le)===this.id&&s.push(h)}),o.concat(n).forEach(a=>{let h=this.getHook(a);h&&this.destroyHook(h)})}),i&&this.maybePushComponentsDestroyed(s)}joinNewChildren(){c.findPhxChildren(document,this.id).forEach(t=>this.joinChild(t))}maybeRecoverForms(t,i){let s=this.binding("change"),n=this.root.formsForRecovery,r=document.createElement("template");r.innerHTML=t,c.all(r.content,`[${Bt}]`).forEach(h=>{r.content.firstElementChild.appendChild(h.content.firstElementChild)});let o=r.content.firstElementChild;o.id=this.id,o.setAttribute(re,this.root.id),o.setAttribute(Q,this.getSession()),o.setAttribute(we,this.getStatic()),o.setAttribute(ye,this.parent?this.parent.id:null);let a=c.all(r.content,"form").filter(h=>h.id&&n[h.id]).filter(h=>!this.pendingForms.has(h.id)).filter(h=>n[h.id].getAttribute(s)===h.getAttribute(s)).map(h=>[n[h.id],h]);if(a.length===0)return i();a.forEach(([h,l],d)=>{this.pendingForms.add(l.id),this.pushFormRecovery(h,l,r.content.firstElementChild,()=>{this.pendingForms.delete(l.id),d===a.length-1&&i()})})}getChildById(t){return this.root.children[this.id][t]}getDescendentByEl(t){return t.id===this.id?this:this.children[t.getAttribute(ye)]?.[t.id]}destroyDescendent(t){for(let i in this.root.children)for(let s in this.root.children[i])if(s===t)return this.root.children[i][s].destroy()}joinChild(t){if(!this.getChildById(t.id)){let s=new Fi(t,this.liveSocket,this);return this.root.children[this.id][s.id]=s,s.join(),this.childJoins++,!0}}isJoinPending(){return this.joinPending}ackJoin(t){this.childJoins--,this.childJoins===0&&(this.parent?this.parent.ackJoin(this):this.onAllChildJoinsComplete())}onAllChildJoinsComplete(){this.pendingForms.clear(),this.formsForRecovery={},this.joinCallback(()=>{this.pendingJoinOps.forEach(([t,i])=>{t.isDestroyed()||i()}),this.pendingJoinOps=[]})}update(t,i,s=!1){if(this.isJoinPending()||this.liveSocket.hasPendingLink()&&this.root.isMain())return s||this.pendingDiffs.push({diff:t,events:i}),!1;this.rendered.mergeDiff(t);let n=!1;return this.rendered.isComponentOnlyDiff(t)?this.liveSocket.time("component patch complete",()=>{c.findExistingParentCIDs(this.id,this.rendered.componentCIDs(t)).forEach(o=>{this.componentPatch(this.rendered.getComponent(t,o),o)&&(n=!0)})}):gi(t)||this.liveSocket.time("full patch complete",()=>{let[r,o]=this.renderContainer(t,"update"),a=new nt(this,this.el,this.id,r,o,null);n=this.performPatch(a,!0)}),this.liveSocket.dispatchEvents(i),n&&this.joinNewChildren(),!0}renderContainer(t,i){return this.liveSocket.time(`toString diff (${i})`,()=>{let s=this.el.tagName,n=t?this.rendered.componentCIDs(t):null,{buffer:r,streams:o}=this.rendered.toString(n);return[`<${s}>${r}</${s}>`,o]})}componentPatch(t,i){if(gi(t))return!1;let{buffer:s,streams:n}=this.rendered.componentToString(i),r=new nt(this,this.el,this.id,s,n,i);return this.performPatch(r,!0)}getHook(t){return this.viewHooks[ge.elementID(t)]}addHook(t){let i=ge.elementID(t);if(!(t.getAttribute&&!this.ownsElement(t)))if(i&&!this.viewHooks[i]){if(ge.deadHook(t))return;let s=c.getCustomElHook(t)||P(`no hook found for custom element: ${t.id}`);return this.viewHooks[i]=s,s.__attachView(this),s}else{if(i||!t.getAttribute)return;{let s=t.getAttribute(`data-phx-${Ne}`)||t.getAttribute(this.binding(Ne));if(!s)return;let n=this.liveSocket.getHookDefinition(s);if(n){if(!t.id){P(`no DOM ID for hook "${s}". Hooks require a unique ID on each element.`,t);return}let r;try{if(typeof n=="function"&&n.prototype instanceof ge)r=new n(this,t);else if(typeof n=="object"&&n!==null)r=new ge(this,t,n);else{P(`Invalid hook definition for "${s}". Expected a class extending ViewHook or an object definition.`,t);return}}catch(o){let a=o instanceof Error?o.message:String(o);P(`Failed to create hook "${s}": ${a}`,t);return}return this.viewHooks[ge.elementID(r.el)]=r,r}else s!==null&&P(`unknown hook found for "${s}"`,t)}}}destroyHook(t){let i=ge.elementID(t.el);t.__destroyed(),t.__cleanup__(),delete this.viewHooks[i]}applyPendingUpdates(){this.pendingDiffs=this.pendingDiffs.filter(({diff:t,events:i})=>!this.update(t,i,!0)),this.eachChild(t=>t.applyPendingUpdates())}eachChild(t){let i=this.root.children[this.id]||{};for(let s in i)t(this.getChildById(s))}onChannel(t,i){this.liveSocket.onChannel(this.channel,t,s=>{this.isJoinPending()?this.joinCount>1?this.pendingJoinOps.push(()=>i(s)):this.root.pendingJoinOps.push([this,()=>i(s)]):this.liveSocket.requestDOMUpdate(()=>i(s))})}bindChannel(){this.liveSocket.onChannel(this.channel,"diff",t=>{this.liveSocket.requestDOMUpdate(()=>{this.applyDiff("update",t,({diff:i,events:s})=>this.update(i,s))})}),this.onChannel("redirect",({to:t,flash:i})=>this.onRedirect({to:t,flash:i})),this.onChannel("live_patch",t=>this.onLivePatch(t)),this.onChannel("live_redirect",t=>this.onLiveRedirect(t)),this.channel.onError(t=>this.onError(t)),this.channel.onClose(t=>this.onClose(t))}destroyAllChildren(){this.eachChild(t=>t.destroy())}onLiveRedirect(t){let{to:i,kind:s,flash:n}=t,r=this.expandURL(i),o=new CustomEvent("phx:server-navigate",{detail:{to:i,kind:s,flash:n}});this.liveSocket.historyRedirect(o,r,s,n)}onLivePatch(t){let{to:i,kind:s}=t;this.href=this.expandURL(i),this.liveSocket.historyPatch(i,s)}expandURL(t){return t.startsWith("/")?`${window.location.protocol}//${window.location.host}${t}`:t}onRedirect({to:t,flash:i,reloadToken:s}){this.liveSocket.redirect(t,i,s)}isDestroyed(){return this.destroyed}joinDead(){this.isDead=!0}joinPush(){return this.joinPush=this.joinPush||this.channel.join(),this.joinPush}join(t){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(){},t?t(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(t){if(t.reason==="reload"){this.log("error",()=>[`failed mount with ${t.status}. Falling back to page reload`,t]),this.onRedirect({to:this.liveSocket.main.href,reloadToken:t.token});return}else if(t.reason==="unauthorized"||t.reason==="stale"){this.log("error",()=>["unauthorized live_redirect. Falling back to page request",t]),this.onRedirect({to:this.liveSocket.main.href,flash:this.flash});return}if((t.redirect||t.live_redirect)&&(this.joinPending=!1,this.channel.leave()),t.redirect)return this.onRedirect(t.redirect);if(t.live_redirect)return this.onLiveRedirect(t.live_redirect);if(this.log("error",()=>["unable to join",t]),this.isMain())this.displayError([me,_e,He],{unstructuredError:t,errorKind:"server"}),this.liveSocket.isConnected()&&this.liveSocket.reloadWithJitter(this);else{this.joinAttempts>=ci&&(this.root.displayError([me,_e,He],{unstructuredError:t,errorKind:"server"}),this.log("error",()=>[`giving up trying to mount after ${ci} tries`,t]),this.destroy());let i=c.byId(this.el.id);i?(c.mergeAttrs(i,this.el),this.displayError([me,_e,He],{unstructuredError:t,errorKind:"server"}),this.el=i):this.destroy()}}onClose(t){if(!this.isDestroyed()){if(this.isMain()&&this.liveSocket.hasPendingLink()&&t!=="leave")return this.liveSocket.reloadWithJitter(this);this.destroyAllChildren(),this.liveSocket.dropActiveElement(this),this.liveSocket.isUnloaded()&&this.showLoader(Ns)}}onError(t){this.onClose(t),this.liveSocket.isConnected()&&this.log("error",()=>["view crashed",t]),this.liveSocket.isUnloaded()||(this.liveSocket.isConnected()?this.displayError([me,_e,He],{unstructuredError:t,errorKind:"server"}):this.displayError([me,_e,ri],{unstructuredError:t,errorKind:"client"}))}displayError(t,i={}){this.isMain()&&c.dispatchEvent(window,"phx:page-loading-start",{detail:{to:this.href,kind:"error",...i}}),this.showLoader(),this.setContainerClasses(...t),this.delayedDisconnected()}delayedDisconnected(){this.disconnectedTimer=setTimeout(()=>{this.execAll(this.binding("disconnected"))},this.liveSocket.disconnectedTimeout)}wrapPush(t,i){let s=this.liveSocket.getLatencySim(),n=s?r=>setTimeout(()=>!this.isDestroyed()&&r(),s):r=>!this.isDestroyed()&&r();n(()=>{t().receive("ok",r=>n(()=>i.ok&&i.ok(r))).receive("error",r=>n(()=>i.error&&i.error(r))).receive("timeout",()=>n(()=>i.timeout&&i.timeout()))})}pushWithReply(t,i,s){if(!this.isConnected())return Promise.reject(new Error("no connection"));let[n,[r],o]=t?t({payload:s}):[null,[],{}],a=this.joinCount,h=function(){};return o.page_loading&&(h=this.liveSocket.withPageLoading({kind:"element",target:r})),typeof s.cid!="number"&&delete s.cid,new Promise((l,d)=>{this.wrapPush(()=>this.channel.push(i,s,Us),{ok:p=>{n!==null&&(this.lastAckRef=n);let m=g=>{p.redirect&&this.onRedirect(p.redirect),p.live_patch&&this.onLivePatch(p.live_patch),p.live_redirect&&this.onLiveRedirect(p.live_redirect),h(),l({resp:p,reply:g,ref:n})};p.diff?this.liveSocket.requestDOMUpdate(()=>{this.applyDiff("update",p.diff,({diff:g,reply:u,events:v})=>{n!==null&&this.undoRefs(n,s.event),this.update(g,v),m(u)})}):(n!==null&&this.undoRefs(n,s.event),m(null))},error:p=>d(new Error(`failed with reason: ${JSON.stringify(p)}`)),timeout:()=>{d(new Error("timeout")),this.joinCount===a&&this.liveSocket.reloadWithJitter(this,()=>{this.log("timeout",()=>["received timeout while communicating with server. Falling back to hard refresh for recovery"])})}})})}undoRefs(t,i,s){if(!this.isConnected())return;let n=`[${W}="${this.refSrc()}"]`;s?(s=new Set(s),c.all(document,n,r=>{s&&!s.has(r)||(c.all(r,n,o=>this.undoElRef(o,t,i)),this.undoElRef(r,t,i))})):c.all(document,n,r=>this.undoElRef(r,t,i))}undoElRef(t,i,s){new Nt(t).maybeUndo(i,s,r=>{let o=new nt(this,t,this.id,r,[],null,{undoRef:i}),a=this.performPatch(o,!0);c.all(t,`[${W}="${this.refSrc()}"]`,h=>this.undoElRef(h,i,s)),a&&this.joinNewChildren()})}refSrc(){return this.el.id}putRef(t,i,s,n={}){let r=this.ref++,o=this.binding(oi);if(n.loading){let a=c.all(document,n.loading).map(h=>({el:h,lock:!0,loading:!0}));t=t.concat(a)}for(let{el:a,lock:h,loading:l}of t){if(!h&&!l)throw new Error("putRef requires lock or loading");if(a.setAttribute(W,this.refSrc()),l&&a.setAttribute(De,r),h&&a.setAttribute(D,r),!l||n.submitter&&!(a===n.submitter||a===n.form))continue;let d=new Promise(u=>{a.addEventListener(`phx:undo-lock:${r}`,()=>u(g),{once:!0})}),p=new Promise(u=>{a.addEventListener(`phx:undo-loading:${r}`,()=>u(g),{once:!0})});a.classList.add(`phx-${s}-loading`);let m=a.getAttribute(o);m!==null&&(a.getAttribute(dt)||a.setAttribute(dt,a.textContent),m!==""&&(a.textContent=m),a.setAttribute(Re,a.getAttribute(Re)||a.disabled),a.setAttribute("disabled",""));let g={event:i,eventType:s,ref:r,isLoading:l,isLocked:h,lockElements:t.filter(({lock:u})=>u).map(({el:u})=>u),loadingElements:t.filter(({loading:u})=>u).map(({el:u})=>u),unlock:u=>{u=Array.isArray(u)?u:[u],this.undoRefs(r,i,u)},lockComplete:d,loadingComplete:p,lock:u=>new Promise(v=>{if(this.isAcked(r))return v(g);u.setAttribute(D,r),u.setAttribute(W,this.refSrc()),u.addEventListener(`phx:lock-stop:${r}`,()=>v(g),{once:!0})})};n.payload&&(g.payload=n.payload),n.target&&(g.target=n.target),n.originalEvent&&(g.originalEvent=n.originalEvent),a.dispatchEvent(new CustomEvent("phx:push",{detail:g,bubbles:!0,cancelable:!1})),i&&a.dispatchEvent(new CustomEvent(`phx:push:${i}`,{detail:g,bubbles:!0,cancelable:!1}))}return[r,t.map(({el:a})=>a),n]}isAcked(t){return this.lastAckRef!==null&&this.lastAckRef>=t}componentID(t){let i=t.getAttribute&&t.getAttribute(Z);return i?parseInt(i):null}targetComponentID(t,i,s={}){if(ne(i))return i;let n=s.target||t.getAttribute(this.binding("target"));return ne(n)?parseInt(n):i&&(n!==null||s.target)?this.closestComponentID(i):null}closestComponentID(t){return ne(t)?t:t?Ie(t.closest(`[${Z}],[${fe}]`),i=>{if(i.hasAttribute(Z))return this.ownsElement(i)&&this.componentID(i);if(i.hasAttribute(fe)){let s=c.byId(i.getAttribute(fe));return this.closestComponentID(s)}}):null}pushHookEvent(t,i,s,n){if(!this.isConnected())return this.log("hook",()=>["unable to push hook event. LiveView not connected",s,n]),Promise.reject(new Error("unable to push hook event. LiveView not connected"));let r=()=>this.putRef([{el:t,loading:!0,lock:!0}],s,"hook",{payload:n,target:i});return this.pushWithReply(r,"event",{type:"hook",event:s,value:n,cid:this.closestComponentID(i)}).then(({resp:o,reply:a,ref:h})=>({reply:a,ref:h}))}extractMeta(t,i,s){let n=this.binding("value-");for(let r=0;r<t.attributes.length;r++){i||(i={});let o=t.attributes[r].name;o.startsWith(n)&&(i[o.replace(n,"")]=t.getAttribute(o))}if(t.value!==void 0&&!(t instanceof HTMLFormElement)&&(i||(i={}),i.value=t.value,t.tagName==="INPUT"&&Oi.indexOf(t.type)>=0&&!t.checked&&delete i.value),s){i||(i={});for(let r in s)i[r]=s[r]}return i}pushEvent(t,i,s,n,r,o={},a){this.pushWithReply(h=>this.putRef([{el:i,loading:!0,lock:!0}],n,t,{...o,payload:h?.payload}),"event",{type:t,event:n,value:this.extractMeta(i,r,o.value),cid:this.targetComponentID(i,s,o)}).then(({reply:h})=>a&&a(h)).catch(h=>P("Failed to push event",h))}pushFileProgress(t,i,s,n=function(){}){this.liveSocket.withinOwners(t.form,(r,o)=>{r.pushWithReply(null,"progress",{event:t.getAttribute(r.binding(Ms)),ref:t.getAttribute(oe),entry_ref:i,progress:s,cid:r.targetComponentID(t.form,o)}).then(()=>n()).catch(a=>P("Failed to push file progress",a))})}pushInput(t,i,s,n,r,o){if(!t.form)throw new Error("form events require the input to be inside a form");let a,h=ne(s)?s:this.targetComponentID(t.form,i,r),l=u=>this.putRef([{el:t,loading:!0,lock:!0},{el:t.form,loading:!0,lock:!0}],n,"change",{...r,payload:u?.payload}),d,p=this.extractMeta(t.form,{},r.value),m={};t instanceof HTMLButtonElement&&(m.submitter=t),t.getAttribute(this.binding("change"))?d=rt(t.form,m,[t.name]):d=rt(t.form,m),c.isUploadInput(t)&&t.files&&t.files.length>0&&M.trackFiles(t,Array.from(t.files)),a=M.serializeUploads(t);let g={type:"form",event:n,value:d,meta:{_target:r._target||"undefined",...p},uploads:a,cid:h};this.pushWithReply(l,"event",g).then(({resp:u})=>{c.isUploadInput(t)&&c.isAutoUpload(t)?Nt.onUnlock(t,()=>{if(M.filesAwaitingPreflight(t).length>0){let[v,w]=l();this.undoRefs(v,n,[t.form]),this.uploadFiles(t.form,n,i,v,h,O=>{o&&o(u),this.triggerAwaitingSubmit(t.form,n),this.undoRefs(v,n)})}}):o&&o(u)}).catch(u=>P("Failed to push input event",u))}triggerAwaitingSubmit(t,i){let s=this.getScheduledSubmit(t);if(s){let[n,r,o,a]=s;this.cancelSubmit(t,i),a()}}getScheduledSubmit(t){return this.formSubmits.find(([i,s,n,r])=>i.isSameNode(t))}scheduleSubmit(t,i,s,n){if(this.getScheduledSubmit(t))return!0;this.formSubmits.push([t,i,s,n])}cancelSubmit(t,i){this.formSubmits=this.formSubmits.filter(([s,n,r,o])=>s.isSameNode(t)?(this.undoRefs(n,i),!1):!0)}disableForm(t,i,s={}){let n=u=>!(be(u,`${this.binding(ut)}=ignore`,u.form)||be(u,"data-phx-update=ignore",u.form)),r=u=>u.hasAttribute(this.binding(oi)),o=u=>u.tagName=="BUTTON",a=u=>["INPUT","TEXTAREA","SELECT"].includes(u.tagName),h=Array.from(t.elements),l=h.filter(r),d=h.filter(o).filter(n),p=h.filter(a).filter(n);d.forEach(u=>{u.setAttribute(Re,u.disabled),u.disabled=!0}),p.forEach(u=>{u.setAttribute(Mt,u.readOnly),u.readOnly=!0,u.files&&(u.setAttribute(Re,u.disabled),u.disabled=!0)});let m=l.concat(d).concat(p).map(u=>({el:u,loading:!0,lock:!0})),g=[{el:t,loading:!0,lock:!1}].concat(m).reverse();return this.putRef(g,i,"submit",s)}pushFormSubmit(t,i,s,n,r,o){let a=l=>this.disableForm(t,s,{...r,form:t,payload:l?.payload,submitter:n});c.putPrivate(t,"submitter",n);let h=this.targetComponentID(t,i);if(M.hasUploadsInProgress(t)){let[l,d]=a(),p=()=>this.pushFormSubmit(t,i,s,n,r,o);return this.scheduleSubmit(t,l,r,p)}else if(M.inputsAwaitingPreflight(t).length>0){let[l,d]=a(),p=()=>[l,d,r];this.uploadFiles(t,s,i,l,h,m=>{if(M.inputsAwaitingPreflight(t).length>0)return this.undoRefs(l,s);let g=this.extractMeta(t,{},r.value),u=rt(t,{submitter:n});this.pushWithReply(p,"event",{type:"form",event:s,value:u,meta:g,cid:h}).then(({resp:v})=>o(v)).catch(v=>P("Failed to push form submit",v))})}else if(!(t.hasAttribute(W)&&t.classList.contains("phx-submit-loading"))){let l=this.extractMeta(t,{},r.value),d=rt(t,{submitter:n});this.pushWithReply(a,"event",{type:"form",event:s,value:d,meta:l,cid:h}).then(({resp:p})=>o(p)).catch(p=>P("Failed to push form submit",p))}}uploadFiles(t,i,s,n,r,o){let a=this.joinCount,h=M.activeFileInputs(t),l=h.length;h.forEach(d=>{let p=new M(d,this,()=>{l--,l===0&&o()}),m=p.entries().map(u=>u.toPreflightPayload());if(m.length===0){l--;return}let g={ref:d.getAttribute(oe),entries:m,cid:this.targetComponentID(d.form,s)};this.log("upload",()=>["sending preflight request",g]),this.pushWithReply(null,"allow_upload",g).then(({resp:u})=>{if(this.log("upload",()=>["got preflight response",u]),p.entries().forEach(v=>{u.entries&&!u.entries[v.ref]&&this.handleFailedEntryPreflight(v.ref,"failed preflight",p)}),u.error||Object.keys(u.entries).length===0)this.undoRefs(n,i),(u.error||[]).map(([w,O])=>{this.handleFailedEntryPreflight(w,O,p)});else{let v=w=>{this.channel.onError(()=>{this.joinCount===a&&w()})};p.initAdapterUpload(u,v,this.liveSocket)}}).catch(u=>P("Failed to push upload",u))})}handleFailedEntryPreflight(t,i,s){if(s.isAutoUpload()){let n=s.entries().find(r=>r.ref===t.toString());n&&n.cancel()}else s.entries().map(n=>n.cancel());this.log("upload",()=>[`error for entry ${t}`,i])}dispatchUploads(t,i,s){let n=this.targetCtxElement(t)||this.el,r=c.findUploadInputs(n).filter(o=>o.name===i);r.length===0?P(`no live file inputs found matching the name "${i}"`):r.length>1?P(`duplicate live file inputs found matching the name "${i}"`):c.dispatchEvent(r[0],Ii,{detail:{files:s}})}targetCtxElement(t){if(ne(t)){let[i]=c.findComponentNodeList(this.id,t);return i}else return t||null}pushFormRecovery(t,i,s,n){let r=this.binding("change"),o=i.getAttribute(this.binding("target"))||i,a=i.getAttribute(this.binding(ai))||i.getAttribute(this.binding("change")),h=Array.from(t.elements).filter(p=>c.isFormInput(p)&&p.name&&!p.hasAttribute(r));if(h.length===0){n();return}h.forEach(p=>p.hasAttribute(oe)&&M.clearFiles(p));let l=h.find(p=>p.type!=="hidden")||h[0],d=0;this.withinTargets(o,(p,m)=>{let g=this.targetComponentID(i,m);d++;let u=new CustomEvent("phx:form-recovery",{detail:{sourceElement:t}});A.exec(u,"change",a,this,l,["push",{_target:l.name,targetView:p,targetCtx:m,newCid:g,callback:()=>{d--,d===0&&n()}}])},s)}pushLinkPatch(t,i,s,n){let r=this.liveSocket.setPendingLink(i),o=t.isTrusted&&t.type!=="popstate",a=s?()=>this.putRef([{el:s,loading:o,lock:!0}],null,"click"):null,h=()=>this.liveSocket.redirect(window.location.href),l=i.startsWith("/")?`${location.protocol}//${location.host}${i}`:i;this.pushWithReply(a,"live_patch",{url:l}).then(({resp:d})=>{this.liveSocket.requestDOMUpdate(()=>{if(d.link_redirect)this.liveSocket.replaceMain(i,null,n,r);else{if(d.redirect)return;this.liveSocket.commitPendingLink(r)&&(this.href=i),this.applyPendingUpdates(),n&&n(r)}})},({error:d,timeout:p})=>h())}getFormsForRecovery(){if(this.joinCount===0)return{};let t=this.binding("change");return c.all(document,`#${CSS.escape(this.id)} form[${t}], [${Ee}="${CSS.escape(this.id)}"] form[${t}]`).filter(i=>i.id).filter(i=>i.elements.length>0).filter(i=>i.getAttribute(this.binding(ai))!=="ignore").map(i=>{let s=i.cloneNode(!0);$t(s,i,{onBeforeElUpdated:(r,o)=>(c.copyPrivates(r,o),r.getAttribute("form")===i.id?(r.parentNode.removeChild(r),!1):!0)});let n=document.querySelectorAll(`[form="${CSS.escape(i.id)}"]`);return Array.from(n).forEach(r=>{let o=r.cloneNode(!0);$t(o,r),c.copyPrivates(o,r),o.removeAttribute("form"),s.appendChild(o)}),s}).reduce((i,s)=>(i[s.id]=s,i),{})}maybePushComponentsDestroyed(t){let i=t.filter(n=>c.findComponentNodeList(this.id,n).length===0),s=n=>{this.isDestroyed()||P("Failed to push components destroyed",n)};i.length>0&&(i.forEach(n=>this.rendered.resetRender(n)),this.pushWithReply(null,"cids_will_destroy",{cids:i}).then(()=>{this.liveSocket.requestDOMUpdate(()=>{let n=i.filter(r=>c.findComponentNodeList(this.id,r).length===0);n.length>0&&this.pushWithReply(null,"cids_destroyed",{cids:n}).then(({resp:r})=>{this.rendered.pruneCIDs(r.cids)}).catch(s)})}).catch(s))}ownsElement(t){let i=c.closestViewEl(t);return t.getAttribute(ye)===this.id||i&&i.id===this.id||!i&&this.isDead}submitForm(t,i,s,n,r={}){c.putPrivate(t,We,!0),Array.from(t.elements).forEach(a=>c.putPrivate(a,We,!0)),this.liveSocket.blurActiveElement(this),this.pushFormSubmit(t,i,s,n,r,()=>{this.liveSocket.restorePreviouslyActiveFocus()})}binding(t){return this.liveSocket.binding(t)}pushPortalElementId(t){this.portalElementIds.add(t)}dropPortalElementId(t){this.portalElementIds.delete(t)}destroyPortalElements(){this.liveSocket.unloaded||this.portalElementIds.forEach(t=>{let i=document.getElementById(t);i&&i.remove()})}};var Sn=class{constructor(e,t,i={}){if(this.unloaded=!1,!t||t.constructor.name==="Object")throw new Error(`
a phoenix Socket must be provided as the second argument to the LiveSocket constructor. For example:
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
let liveSocket = new LiveSocket("/live", Socket, {...})
`);this.socket=new t(e,i),this.bindingPrefix=i.bindingPrefix||Fs,this.opts=i,this.params=Be(i.params||{}),this.viewLogger=i.viewLogger,this.metadataCallbacks=i.metadata||{},this.defaults=Object.assign(lt(Bs),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=lt(window.location),this.hooks=i.hooks||{},this.uploaders=i.uploaders||{},this.loaderTimeout=i.loaderTimeout||Hs,this.disconnectedTimeout=i.disconnectedTimeout||$s,this.reloadWithJitterTimer=null,this.maxReloads=i.maxReloads||Es,this.reloadJitterMin=i.reloadJitterMin||Ss,this.reloadJitterMax=i.reloadJitterMax||ks,this.failsafeJitter=i.failsafeJitter||As,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.serverCloseRef=null,this.domCallbacks=Object.assign({jsQuerySelectorAll:null,onPatchStart:Be(),onPatchEnd:Be(),onNodeAdded:Be(),onBeforeElUpdated:Be()},i.dom||{}),this.transitions=new kn,this.currentHistoryPosition=parseInt(this.sessionStorage.getItem(tt))||0,window.addEventListener("pagehide",s=>{this.unloaded=!0}),this.socket.onOpen(()=>{this.isUnloaded()&&window.location.reload()})}version(){return"1.1.28"}isProfileEnabled(){return this.sessionStorage.getItem(Tt)==="true"}isDebugEnabled(){return this.sessionStorage.getItem(et)==="true"}isDebugDisabled(){return this.sessionStorage.getItem(et)==="false"}enableDebug(){this.sessionStorage.setItem(et,"true")}enableProfiling(){this.sessionStorage.setItem(Tt,"true")}disableDebug(){this.sessionStorage.setItem(et,"false")}disableProfiling(){this.sessionStorage.removeItem(Tt)}enableLatencySim(e){this.enableDebug(),console.log("latency simulator enabled for the duration of this browser session. Call disableLatencySim() to disable"),this.sessionStorage.setItem(_t,e)}disableLatencySim(){this.sessionStorage.removeItem(_t)}getLatencySim(){let e=this.sessionStorage.getItem(_t);return e?parseInt(e):null}getSocket(){return this.socket}connect(){window.location.hostname==="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(e){clearTimeout(this.reloadWithJitterTimer),this.serverCloseRef&&(this.socket.off(this.serverCloseRef),this.serverCloseRef=null),this.socket.disconnect(e)}replaceTransport(e){clearTimeout(this.reloadWithJitterTimer),this.socket.replaceTransport(e),this.connect()}execJS(e,t,i=null){let s=new CustomEvent("phx:exec",{detail:{sourceElement:e}});this.owner(e,n=>A.exec(s,i,t,n,e))}js(){return Ni(this,"js")}unload(){this.unloaded||(this.main&&this.isConnected()&&this.log(this.main,"socket",()=>["disconnect for page nav"]),this.unloaded=!0,this.destroyAllViews(),this.disconnect())}triggerDOM(e,t){this.domCallbacks[e](...t)}time(e,t){if(!this.isProfileEnabled()||!console.time)return t();console.time(e);let i=t();return console.timeEnd(e),i}log(e,t,i){if(this.viewLogger){let[s,n]=i();this.viewLogger(e,t,s,n)}else if(this.isDebugEnabled()){let[s,n]=i();qs(e,t,s,n)}}requestDOMUpdate(e){this.transitions.after(e)}asyncTransition(e){this.transitions.addAsyncTransition(e)}transition(e,t,i=function(){}){this.transitions.addTransition(e,t,i)}onChannel(e,t,i){e.on(t,s=>{let n=this.getLatencySim();n?setTimeout(()=>i(s),n):i(s)})}reloadWithJitter(e,t){clearTimeout(this.reloadWithJitterTimer),this.disconnect();let i=this.reloadJitterMin,s=this.reloadJitterMax,n=Math.floor(Math.random()*(s-i+1))+i,r=U.updateLocal(this.localStorage,window.location.pathname,xi,0,o=>o+1);r>=this.maxReloads&&(n=this.failsafeJitter),this.reloadWithJitterTimer=setTimeout(()=>{e.isDestroyed()||e.isConnected()||(e.destroy(),t?t():this.log(e,"join",()=>[`encountered ${r} consecutive reloads`]),r>=this.maxReloads&&this.log(e,"join",()=>[`exceeded ${this.maxReloads} consecutive reloads. Entering failsafe mode`]),this.hasPendingLink()?window.location=this.pendingLink:window.location.reload())},n)}getHookDefinition(e){if(e)return this.maybeInternalHook(e)||this.hooks[e]||this.maybeRuntimeHook(e)}maybeInternalHook(e){return e&&e.startsWith("Phoenix.")&&en[e.split(".")[1]]}maybeRuntimeHook(e){let t=document.querySelector(`script[${ht}="${CSS.escape(e)}"]`);if(!t)return;let i=window[`phx_hook_${e}`];if(!i||typeof i!="function"){P("a runtime hook must be a function",t);return}let s=i();if(s&&(typeof s=="object"||typeof s=="function"))return s;P("runtime hook must return an object with hook callbacks or an instance of ViewHook",t)}isUnloaded(){return this.unloaded}isConnected(){return this.socket.isConnected()}getBindingPrefix(){return this.bindingPrefix}binding(e){return`${this.getBindingPrefix()}${e}`}channel(e,t){return this.socket.channel(e,t)}joinDeadView(){let e=document.body;if(e&&!this.isPhxView(e)&&!this.isPhxView(document.firstElementChild)){let t=this.newRootView(e);t.setHref(this.getHref()),t.joinDead(),this.main||(this.main=t),window.requestAnimationFrame(()=>{t.execNewMounted(),this.maybeScroll(history.state?.scroll)})}}joinRootViews(){let e=!1;return c.all(document,`${qe}:not([${ye}])`,t=>{if(!this.getRootById(t.id)){let i=this.newRootView(t);c.isPhxSticky(t)||i.setHref(this.getHref()),i.join(),t.hasAttribute(Ut)&&(this.main=i)}e=!0}),e}redirect(e,t,i){i&&U.setCookie(li,i,60),this.unload(),U.redirect(e,t)}replaceMain(e,t,i=null,s=this.setPendingLink(e)){let n=this.currentLocation.href;this.outgoingMainEl=this.outgoingMainEl||this.main.el;let r=c.findPhxSticky(document)||[],o=c.all(this.outgoingMainEl,`[${this.binding("remove")}]`).filter(h=>!c.isChildOfAny(h,r)),a=c.cloneNode(this.outgoingMainEl,"");this.main.showLoader(this.loaderTimeout),this.main.destroy(),this.main=this.newRootView(a,t,n),this.main.setRedirect(e),this.transitionRemoves(o),this.main.join((h,l)=>{h===1&&this.commitPendingLink(s)&&this.requestDOMUpdate(()=>{o.forEach(d=>d.remove()),r.forEach(d=>a.appendChild(d)),this.outgoingMainEl.replaceWith(a),this.outgoingMainEl=null,i&&i(s),l()})})}transitionRemoves(e,t){let i=this.binding("remove"),s=n=>{n.preventDefault(),n.stopImmediatePropagation()};e.forEach(n=>{for(let r of this.boundEventNames)n.addEventListener(r,s,!0);this.execJS(n,n.getAttribute(i),"remove")}),this.requestDOMUpdate(()=>{e.forEach(n=>{for(let r of this.boundEventNames)n.removeEventListener(r,s,!0)}),t&&t()})}isPhxView(e){return e.getAttribute&&e.getAttribute(Q)!==null}newRootView(e,t,i){let s=new En(e,this,null,t,i);return this.roots[s.id]=s,s}owner(e,t){let i,s=c.closestViewEl(e);if(s)i=this.getViewByEl(s);else{if(!e.isConnected)return null;i=this.main}return i&&t?t(i):i}withinOwners(e,t){this.owner(e,i=>t(i,e))}getViewByEl(e){let t=e.getAttribute(re);return Ie(this.getRootById(t),i=>i.getDescendentByEl(e))}getRootById(e){return this.roots[e]}destroyAllViews(){for(let e in this.roots)this.roots[e].destroy(),delete this.roots[e];this.main=null}destroyViewByEl(e){let t=this.getRootById(e.getAttribute(re));t&&t.id===e.id?(t.destroy(),delete this.roots[t.id]):t&&t.destroyDescendent(e.id)}getActiveElement(){return document.activeElement}dropActiveElement(e){this.prevActive&&e.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:e}={}){this.boundTopLevelEvents||(this.boundTopLevelEvents=!0,this.serverCloseRef=this.socket.onClose(t=>{if(t&&t.code===1e3&&this.main)return this.reloadWithJitter(this.main)}),document.body.addEventListener("click",function(){}),window.addEventListener("pageshow",t=>{t.persisted&&(this.getSocket().disconnect(),this.withPageLoading({to:window.location.href,kind:"redirect"}),window.location.reload())},!0),e||this.bindNav(),this.bindClicks(),e||this.bindForms(),this.bind({keyup:"keyup",keydown:"keydown"},(t,i,s,n,r,o)=>{let a=n.getAttribute(this.binding(Os)),h=t.key&&t.key.toLowerCase();if(a&&a.toLowerCase()!==h)return;let l={key:t.key,...this.eventMeta(i,t,n)};A.exec(t,i,r,s,n,["push",{data:l}])}),this.bind({blur:"focusout",focus:"focusin"},(t,i,s,n,r,o)=>{if(!o){let a={key:t.key,...this.eventMeta(i,t,n)};A.exec(t,i,r,s,n,["push",{data:a}])}}),this.bind({blur:"blur",focus:"focus"},(t,i,s,n,r,o)=>{if(o==="window"){let a=this.eventMeta(i,t,n);A.exec(t,i,r,s,n,["push",{data:a}])}}),this.on("dragover",t=>t.preventDefault()),this.on("dragenter",t=>{let i=be(t.target,this.binding(Qe));!i||!(i instanceof HTMLElement)||Ks(t)&&this.js().addClass(i,At)}),this.on("dragleave",t=>{let i=be(t.target,this.binding(Qe));if(!i||!(i instanceof HTMLElement))return;let s=i.getBoundingClientRect();(t.clientX<=s.left||t.clientX>=s.right||t.clientY<=s.top||t.clientY>=s.bottom)&&this.js().removeClass(i,At)}),this.on("drop",t=>{t.preventDefault();let i=be(t.target,this.binding(Qe));if(!i||!(i instanceof HTMLElement))return;this.js().removeClass(i,At);let s=i.getAttribute(this.binding(Qe)),n=s&&document.getElementById(s),r=Array.from(t.dataTransfer.files||[]);!n||!(n instanceof HTMLInputElement)||n.disabled||r.length===0||!(n.files instanceof FileList)||(M.trackFiles(n,r,t.dataTransfer),n.dispatchEvent(new Event("input",{bubbles:!0})))}),this.on(Ii,t=>{let i=t.target;if(!c.isUploadInput(i))return;let s=Array.from(t.detail.files||[]).filter(n=>n instanceof File||n instanceof Blob);M.trackFiles(i,s),i.dispatchEvent(new Event("input",{bubbles:!0}))}))}eventMeta(e,t,i){let s=this.metadataCallbacks[e];return s?s(t,i):{}}setPendingLink(e){return this.linkRef++,this.pendingLink=e,this.resetReloadStatus(),this.linkRef}resetReloadStatus(){U.deleteCookie(li)}commitPendingLink(e){return this.linkRef!==e?!1:(this.href=this.pendingLink,this.pendingLink=null,!0)}getHref(){return this.href}hasPendingLink(){return!!this.pendingLink}bind(e,t){for(let i in e){let s=e[i];this.on(s,n=>{let r=this.binding(i),o=this.binding(`window-${i}`),a=n.target.getAttribute&&n.target.getAttribute(r);a?this.debounce(n.target,n,s,()=>{this.withinOwners(n.target,h=>{t(n,i,h,n.target,a,null)})}):c.all(document,`[${o}]`,h=>{let l=h.getAttribute(o);this.debounce(h,n,s,()=>{this.withinOwners(h,d=>{t(n,i,d,h,l,"window")})})})})}}bindClicks(){this.on("mousedown",e=>this.clickStartedAtTarget=e.target),this.bindClick("click","click")}bindClick(e,t){let i=this.binding(t);window.addEventListener(e,s=>{let n=null;s.detail===0&&(this.clickStartedAtTarget=s.target);let r=this.clickStartedAtTarget||s.target;n=be(s.target,i),this.dispatchClickAway(s,r),this.clickStartedAtTarget=null;let o=n&&n.getAttribute(i);if(!o){c.isNewPageClick(s,window.location)&&this.unload();return}n.getAttribute("href")==="#"&&s.preventDefault(),!n.hasAttribute(W)&&this.debounce(n,s,"click",()=>{this.withinOwners(n,a=>{A.exec(s,"click",o,a,n,["push",{data:this.eventMeta("click",s,n)}])})})},!1)}dispatchClickAway(e,t){let i=this.binding("click-away"),s=t.closest(`[${fe}]`),n=s&&c.byId(s.getAttribute(fe));c.all(document,`[${i}]`,r=>{let o=t;s&&!s.contains(r)&&(o=n),r.isSameNode(o)||r.contains(o)||!A.isVisible(t)||this.withinOwners(r,a=>{let h=r.getAttribute(i);A.isVisible(r)&&A.isInViewport(r)&&A.exec(e,"click",h,a,r,["push",{data:this.eventMeta("click",e,e.target)}])})})}bindNav(){if(!U.canPushState())return;history.scrollRestoration&&(history.scrollRestoration="manual");let e=null;window.addEventListener("scroll",t=>{clearTimeout(e),e=setTimeout(()=>{U.updateCurrentState(i=>Object.assign(i,{scroll:window.scrollY}))},100)}),window.addEventListener("popstate",t=>{if(!this.registerNewLocation(window.location))return;let{type:i,backType:s,id:n,scroll:r,position:o}=t.state||{},a=window.location.href,h=o>this.currentHistoryPosition,l=h?i:s||i;this.currentHistoryPosition=o||0,this.sessionStorage.setItem(tt,this.currentHistoryPosition.toString()),c.dispatchEvent(window,"phx:navigate",{detail:{href:a,patch:l==="patch",pop:!0,direction:h?"forward":"backward"}}),this.requestDOMUpdate(()=>{let d=()=>{this.maybeScroll(r)};this.main.isConnected()&&l==="patch"&&n===this.main.id?this.main.pushLinkPatch(t,a,null,d):this.replaceMain(a,null,d)})},!1),window.addEventListener("click",t=>{let i=be(t.target,Ct),s=i&&i.getAttribute(Ct);if(!s||!this.isConnected()||!this.main||c.wantsNewTab(t))return;let n=i.href instanceof SVGAnimatedString?i.href.baseVal:i.href,r=i.getAttribute(Ts);t.preventDefault(),t.stopImmediatePropagation(),this.pendingLink!==n&&this.requestDOMUpdate(()=>{if(s==="patch")this.pushHistoryPatch(t,n,r,i);else if(s==="redirect")this.historyRedirect(t,n,r,null,i);else throw new Error(`expected ${Ct} to be "patch" or "redirect", got: ${s}`);let o=i.getAttribute(this.binding("click"));o&&this.requestDOMUpdate(()=>this.execJS(i,o,"click"))})},!1)}maybeScroll(e){typeof e=="number"&&requestAnimationFrame(()=>{window.scrollTo(0,e)})}dispatchEvent(e,t={}){c.dispatchEvent(window,`phx:${e}`,{detail:t})}dispatchEvents(e){e.forEach(([t,i])=>this.dispatchEvent(t,i))}withPageLoading(e,t){c.dispatchEvent(window,"phx:page-loading-start",{detail:e});let i=()=>c.dispatchEvent(window,"phx:page-loading-stop",{detail:e});return t?t(i):i}pushHistoryPatch(e,t,i,s){if(!this.isConnected()||!this.main.isMain())return U.redirect(t);this.withPageLoading({to:t,kind:"patch"},n=>{this.main.pushLinkPatch(e,t,s,r=>{this.historyPatch(t,i,r),n()})})}historyPatch(e,t,i=this.setPendingLink(e)){this.commitPendingLink(i)&&(this.currentHistoryPosition++,this.sessionStorage.setItem(tt,this.currentHistoryPosition.toString()),U.updateCurrentState(s=>({...s,backType:"patch"})),U.pushState(t,{type:"patch",id:this.main.id,position:this.currentHistoryPosition},e),c.dispatchEvent(window,"phx:navigate",{detail:{patch:!0,href:e,pop:!1,direction:"forward"}}),this.registerNewLocation(window.location))}historyRedirect(e,t,i,s,n){let r=n&&e.isTrusted&&e.type!=="popstate";if(r&&n.classList.add("phx-click-loading"),!this.isConnected()||!this.main.isMain())return U.redirect(t,s);if(/^\/$|^\/[^\/]+.*$/.test(t)){let{protocol:a,host:h}=window.location;t=`${a}//${h}${t}`}let o=window.scrollY;this.withPageLoading({to:t,kind:"redirect"},a=>{this.replaceMain(t,s,h=>{h===this.linkRef&&(this.currentHistoryPosition++,this.sessionStorage.setItem(tt,this.currentHistoryPosition.toString()),U.updateCurrentState(l=>({...l,backType:"redirect"})),U.pushState(i,{type:"redirect",id:this.main.id,scroll:o,position:this.currentHistoryPosition},t),c.dispatchEvent(window,"phx:navigate",{detail:{href:t,patch:!1,pop:!1,direction:"forward"}}),this.registerNewLocation(window.location)),r&&n.classList.remove("phx-click-loading"),a()})})}registerNewLocation(e){let{pathname:t,search:i}=this.currentLocation;return t+i===e.pathname+e.search?!1:(this.currentLocation=lt(e),!0)}bindForms(){let e=0,t=!1;this.on("submit",i=>{let s=i.target.getAttribute(this.binding("submit")),n=i.target.getAttribute(this.binding("change"));!t&&n&&!s&&(t=!0,i.preventDefault(),this.withinOwners(i.target,r=>{r.disableForm(i.target),window.requestAnimationFrame(()=>{c.isUnloadableFormSubmit(i)&&this.unload(),i.target.submit()})}))}),this.on("submit",i=>{let s=i.target.getAttribute(this.binding("submit"));if(!s){c.isUnloadableFormSubmit(i)&&this.unload();return}i.preventDefault(),i.target.disabled=!0,this.withinOwners(i.target,n=>{A.exec(i,"submit",s,n,i.target,["push",{submitter:i.submitter}])})});for(let i of["change","input"])this.on(i,s=>{if(s instanceof CustomEvent&&(s.target instanceof HTMLInputElement||s.target instanceof HTMLSelectElement||s.target instanceof HTMLTextAreaElement)&&s.target.form===void 0){if(s.detail&&s.detail.dispatcher)throw new Error(`dispatching a custom ${i} event is only supported on input elements inside a form`);return}let n=this.binding("change"),r=s.target;if(this.blockPhxChangeWhileComposing&&s.isComposing){let g=`composition-listener-${i}`;c.private(r,g)||(c.putPrivate(r,g,!0),r.addEventListener("compositionend",()=>{r.dispatchEvent(new Event(i,{bubbles:!0})),c.deletePrivate(r,g)},{once:!0}));return}let o=r.getAttribute(n),a=r.form&&r.form.getAttribute(n),h=o||a;if(!h||r.type==="number"&&r.validity&&r.validity.badInput)return;let l=o?r:r.form,d=e;e++;let{at:p,type:m}=c.private(r,"prev-iteration")||{};p===d-1&&i==="change"&&m==="input"||(c.putPrivate(r,"prev-iteration",{at:d,type:i}),this.debounce(r,s,i,()=>{this.withinOwners(l,g=>{c.putPrivate(r,ct,!0),A.exec(s,"change",h,g,r,["push",{_target:s.target.name,dispatcher:l}])})}))});this.on("reset",i=>{let s=i.target;c.resetForm(s);let n=Array.from(s.elements).find(r=>r.type==="reset");n&&window.requestAnimationFrame(()=>{n.dispatchEvent(new Event("input",{bubbles:!0,cancelable:!1}))})})}debounce(e,t,i,s){if(i==="blur"||i==="focusout")return s();let n=this.binding(Is),r=this.binding(Ls),o=this.defaults.debounce.toString(),a=this.defaults.throttle.toString();this.withinOwners(e,h=>{let l=()=>!h.isDestroyed()&&document.body.contains(e);c.debounce(e,t,n,o,r,a,l,()=>{s()})})}silenceEvents(e){this.silenced=!0,e(),this.silenced=!1}on(e,t){this.boundEventNames.add(e),window.addEventListener(e,i=>{this.silenced||t(i)})}jsQuerySelectorAll(e,t,i){let s=this.domCallbacks.jsQuerySelectorAll;return s?s(e,t,i):i()}},kn=class{constructor(){this.transitions=new Set,this.promises=new Set,this.pendingOps=[]}reset(){this.transitions.forEach(e=>{clearTimeout(e),this.transitions.delete(e)}),this.promises.clear(),this.flushPendingOps()}after(e){this.size()===0?e():this.pushPendingOp(e)}addTransition(e,t,i){t();let s=setTimeout(()=>{this.transitions.delete(s),i(),this.flushPendingOps()},e);this.transitions.add(s)}addAsyncTransition(e){this.promises.add(e),e.then(()=>{this.promises.delete(e),this.flushPendingOps()})}pushPendingOp(e){this.pendingOps.push(e)}size(){return this.transitions.size+this.promises.size}flushPendingOps(){if(this.size()>0)return;let e=this.pendingOps.shift();e&&(e(),this.flushPendingOps())}},Ui=Sn;(function(){var e=t();function t(){if(typeof window.CustomEvent=="function")return window.CustomEvent;function n(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 n.prototype=window.Event.prototype,n}function i(n,r){var o=document.createElement("input");return o.type="hidden",o.name=n,o.value=r,o}function s(n,r){var o=n.getAttribute("data-to"),a=i("_method",n.getAttribute("data-method")),h=i("_csrf_token",n.getAttribute("data-csrf")),l=document.createElement("form"),d=document.createElement("input"),p=n.getAttribute("target");l.method=n.getAttribute("data-method")==="get"?"get":"post",l.action=o,l.style.display="none",p?l.target=p:r&&(l.target="_blank"),l.appendChild(h),l.appendChild(a),document.body.appendChild(l),d.type="submit",l.appendChild(d),d.click()}window.addEventListener("click",function(n){var r=n.target;if(!n.defaultPrevented)for(;r&&r.getAttribute;){var o=new e("phoenix.link.click",{bubbles:!0,cancelable:!0});if(!r.dispatchEvent(o))return n.preventDefault(),n.stopImmediatePropagation(),!1;if(r.getAttribute("data-method")&&r.getAttribute("data-to"))return s(r,n.metaKey||n.shiftKey),n.preventDefault(),!1;r=r.parentNode}},!1),window.addEventListener("phoenix.link.click",function(n){var r=n.target.getAttribute("data-confirm");r&&!window.confirm(r)&&n.preventDefault()},!1)})();var ft="bds-panel-sidebar",pt="bds-panel-assistant-sidebar",Wt="bds-ui-language",Bi="bds-workbench-";var ae=(e,t,i)=>Math.max(t,Math.min(e,i)),ji=e=>{if(!e)return null;try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}},mt=(e,t)=>{let i=e?.closest(".media-thumbnail");i&&(t?i.classList.add("is-loaded"):i.classList.remove("is-loaded"))},qt=e=>{e.querySelectorAll(".media-thumbnail-image").forEach(t=>{mt(t,!!(t.complete&&t.naturalWidth>0))})};var gt=e=>{let t=document.querySelector(e);if(!t)return 0;let i=Number.parseInt(t.style.width||"0",10);return Number.isNaN(i)?Math.round(t.getBoundingClientRect().width):i},Vi=(e,t)=>{let i=document.querySelector(e);i&&(i.style.width=`${t}px`,i.classList.remove("is-hidden"))},Jt=(e,t)=>{let i=e==="assistant"?pt:ft;window.localStorage.setItem(i,String(t))},Xt=(e,t,i,s)=>{let n=window.localStorage.getItem(e);if(!n)return t;let r=Number.parseInt(n,10);return Number.isNaN(r)?t:ae(r,i,s)};var vt=e=>String(e||"").toLowerCase(),Wi=e=>{let t=e.target?.tagName||null;return e.target?.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(t)},qi=(e,t)=>{let i=t.metaKey||t.ctrlKey;return vt(t.key)===vt(e.key)&&i===!!e.primary&&t.shiftKey===!!e.shift&&t.altKey===!!e.alt},Ji=e=>{if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}};var Xi=()=>{let e=document.documentElement.style,t=(o,a)=>{e.setProperty("--bds-titlebar-overlay-left",`${o}px`),e.setProperty("--bds-titlebar-overlay-right",`${a}px`)},i=navigator.windowControlsOverlay;if(!i)return t(0,0),()=>{};let s=()=>{if(!i.visible){t(0,0);return}let o=i.getTitlebarAreaRect(),a=window.innerWidth||document.documentElement.clientWidth||o.right,h=Math.max(0,Math.round(o.left)),l=Math.max(0,Math.round(a-o.right));t(h,l)},n=()=>s(),r=()=>s();return s(),i.addEventListener("geometrychange",n),window.addEventListener("resize",r),()=>{i.removeEventListener("geometrychange",n),window.removeEventListener("resize",r)}};var Ki=e=>new Promise((t,i)=>{let s=document.querySelector(`script[src="${e}"]`);if(s){if(s.dataset.loaded==="true"){t();return}s.addEventListener("load",()=>t(),{once:!0}),s.addEventListener("error",()=>i(new Error(`Failed to load ${e}`)),{once:!0});return}let n=document.createElement("script");n.src=e,n.async=!0,n.addEventListener("load",()=>{n.dataset.loaded="true",t()},{once:!0}),n.addEventListener("error",()=>i(new Error(`Failed to load ${e}`)),{once:!0}),document.head.appendChild(n)});var X=(e,t)=>window.getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t,An=e=>{if(!e)return null;let t=e.match(/^#([0-9a-f]{6})$/i);if(t)return{r:Number.parseInt(t[1].slice(0,2),16),g:Number.parseInt(t[1].slice(2,4),16),b:Number.parseInt(t[1].slice(4,6),16)};let i=e.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/i);return i?{r:Number.parseInt(i[1],10),g:Number.parseInt(i[2],10),b:Number.parseInt(i[3],10)}:null},ee=(e,t)=>{let i=An(e);return i?`#${[i.r,i.g,i.b].map(s=>ae(s,0,255).toString(16).padStart(2,"0")).join("")}`:t};var zi=null,he=e=>{let t=ee(X("--vscode-editor-background",X("--vscode-input-background","#1e1e1e")),"#1e1e1e"),i=ee(X("--vscode-editor-foreground","#d4d4d4"),"#d4d4d4"),s=ee(X("--vscode-editorLineNumber-foreground","#858585"),"#858585"),n=ee(X("--vscode-editorLineNumber-activeForeground",i),i),r=ee(X("--vscode-editor-selectionBackground","#264f78"),"#264f78"),o=ee(X("--vscode-editor-inactiveSelectionBackground","#3a3d41"),"#3a3d41"),a=ee(X("--vscode-editorCursor-foreground",i),i),h=ee(X("--vscode-panel-border","#3c3c3c"),"#3c3c3c"),l=ee(X("--vscode-editor-lineHighlightBackground",t),t),d=[t,i,s,n,r,o,a,h].join("|");if(d===zi){e.editor.setTheme("bds-theme");return}e.editor.defineTheme("bds-theme",{base:"vs-dark",inherit:!0,rules:[{token:"keyword.macro",foreground:"C586C0",fontStyle:"bold"},{token:"attribute.name",foreground:"9CDCFE"},{token:"attribute.value",foreground:"CE9178"}],colors:{"editor.background":t,"editor.foreground":i,"editor.lineHighlightBackground":l,"editorCursor.foreground":a,"editor.selectionBackground":r,"editor.inactiveSelectionBackground":o,"editorLineNumber.foreground":s,"editorLineNumber.activeForeground":n,"editorIndentGuide.background1":h,"editorIndentGuide.activeBackground1":i,"editorWidget.border":h,"editorGutter.background":t,focusBorder:h,"input.border":h}}),zi=d,e.editor.setTheme("bds-theme")};var Gi=!1,Yi=!1,Kt=e=>{Gi||(e.languages.register({id:"liquid"}),e.languages.setLanguageConfiguration("liquid",{comments:{blockComment:["{% comment %}","{% endcomment %}"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}],surroundingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'},{open:"'",close:"'"}]}),e.languages.setMonarchTokensProvider("liquid",{defaultToken:"",tokenizer:{root:[[/\{\{-?/,{token:"delimiter.output",next:"@liquidOutput"}],[/\{%-?\s*comment\b[^%]*-?%\}/,{token:"comment.block",next:"@liquidComment"}],[/\{%-?/,{token:"delimiter.tag",next:"@liquidTag"}],[/<!DOCTYPE/i,"metatag"],[/<!--/,{token:"comment",next:"@htmlComment"}],[/(<)(script)/i,["delimiter.html","tag.html"],"@scriptTag"],[/(<)(style)/i,["delimiter.html","tag.html"],"@styleTag"],[/(<\/)([\w:-]+)/,["delimiter.html","tag.html"]],[/(<)([\w:-]+)/,["delimiter.html","tag.html"],"@htmlTag"],[/[^<{]+/,""],[/./,""]],liquidOutput:[[/-?\}\}/,{token:"delimiter.output",next:"@pop"}],[/\|\s*[a-zA-Z_][\w-]*/,"keyword"],[/\b(?:true|false|nil|blank|empty)\b/,"keyword"],[/\b\d+(?:\.\d+)?\b/,"number"],[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/,"string"],[/[a-zA-Z_][\w.-]*/,"identifier"],[/[,:()[\]]/,"delimiter"]],liquidTag:[[/-?%\}/,{token:"delimiter.tag",next:"@pop"}],[/\b(?:assign|capture|case|comment|cycle|decrement|echo|elsif|else|endcase|endcapture|endif|endfor|endunless|endcomment|for|if|include|increment|liquid|paginate|raw|render|tablerow|unless|when)\b/,"keyword"],[/\|\s*[a-zA-Z_][\w-]*/,"keyword"],[/\b(?:true|false|nil|blank|empty|contains)\b/,"keyword"],[/\b\d+(?:\.\d+)?\b/,"number"],[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/,"string"],[/[><=!]=?|\.|:/,"operator"],[/[a-zA-Z_][\w.-]*/,"identifier"],[/[,:()[\]]/,"delimiter"]],liquidComment:[[/\{%-?\s*endcomment\s*-?%\}/,{token:"comment.block",next:"@pop"}],[/./,"comment.block"]],htmlComment:[[/-->/,{token:"comment",next:"@pop"}],[/./,"comment"]],htmlTag:[[/\/>/,{token:"delimiter.html",next:"@pop"}],[/>/,{token:"delimiter.html",next:"@pop"}],[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/,"attribute.value"],[/[\w:-]+/,"attribute.name"],[/=/,"delimiter"]],scriptTag:[[/>/,{token:"delimiter.html",next:"@pop"}],[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/,"attribute.value"],[/[\w:-]+/,"attribute.name"],[/=/,"delimiter"]],styleTag:[[/>/,{token:"delimiter.html",next:"@pop"}],[/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/,"attribute.value"],[/[\w:-]+/,"attribute.name"],[/=/,"delimiter"]]}}),Gi=!0)},zt=e=>{Yi||(e.languages.register({id:"markdown-with-macros"}),e.languages.setMonarchTokensProvider("markdown-with-macros",{defaultToken:"",tokenPostfix:".md",tokenizer:{root:[[/\[\[[a-zA-Z][\w-]*/,{token:"keyword.macro",next:"@macroParams"}],[/^#{1,6}\s.*$/,"keyword.header"],[/^\s*>+/,"string.quote"],[/^\s*[-+*]\s/,"keyword"],[/^\s*\d+\.\s/,"keyword"],[/^\s*```\w*/,{token:"string.code",next:"@codeblock"}],[/\*\*[^*]+\*\*/,"strong"],[/\*[^*]+\*/,"emphasis"],[/__[^_]+__/,"strong"],[/_[^_]+_/,"emphasis"],[/`[^`]+`/,"variable"],[/!?\[[^\]]*\]\([^)]*\)/,"string.link"],[/!?\[[^\]]*\]\[[^\]]*\]/,"string.link"]],macroParams:[[/\]\]/,{token:"keyword.macro",next:"@root"}],[/[a-zA-Z][\w-]*(?=\s*=)/,"attribute.name"],[/=/,"delimiter"],[/"[^"]*"/,"string"],[/\s+/,"white"],[/[^\]"=\s]+/,"attribute.value"]],codeblock:[[/^\s*```\s*$/,{token:"string.code",next:"@root"}],[/.*$/,"variable.source"]]}}),Yi=!0)};var Je,Gt=new Map,Oe=()=>window.monaco?.editor?(he(window.monaco),Kt(window.monaco),zt(window.monaco),Promise.resolve(window.monaco)):Je||(Je=Ki("/monaco/vs/loader.js").then(()=>new Promise((e,t)=>{window.require.config({paths:{vs:"/monaco/vs"}}),window.require(["vs/editor/editor.main"],()=>{he(window.monaco),Kt(window.monaco),zt(window.monaco),e(window.monaco)},t)})).catch(e=>{throw Je=null,e}),Je),Zi=(e,t)=>{e&&Gt.set(e,t)},Qi=e=>{e&&Gt.delete(e)},es=()=>{for(let e of Gt.values())if(typeof e?.hasTextFocus=="function"&&e.hasTextFocus())return e;return null},te=(e,t,i=t)=>{if(!e)return!1;let s=typeof e.getAction=="function"?e.getAction(t):null;return s&&typeof s.run=="function"?(s.run(),!0):typeof e.trigger=="function"?(e.trigger("bds-menu",i,null),!0):!1},Yt=(e,t)=>{let i=String(e||"working-tree").replace(/^\/+/,"");return`inmemory://model/git-diff/${t}/${i}`};var bt=e=>{let t=ae(Math.round(e*100)/100,.5,2);window.__bdsAppZoom=t,document.documentElement.style.zoom=String(t)},pe=e=>{if(typeof document.execCommand!="function")return!1;try{return document.execCommand(e)}catch{return!1}};var ts=e=>{let t=es();switch(e){case"undo":return t?te(t,"undo"):pe("undo");case"redo":return t?te(t,"redo"):pe("redo");case"cut":return t?te(t,"editor.action.clipboardCutAction"):pe("cut");case"copy":return t?te(t,"editor.action.clipboardCopyAction"):pe("copy");case"paste":return t?te(t,"editor.action.clipboardPasteAction"):pe("paste");case"delete":return t?te(t,"deleteLeft"):pe("delete");case"select_all":return t?te(t,"editor.action.selectAll"):pe("selectAll");case"find":return t?te(t,"actions.find"):!1;case"replace":return t?te(t,"editor.action.startFindReplaceAction"):!1;case"reload":case"force_reload":return window.location.reload(),!0;case"reset_zoom":return bt(1),!0;case"zoom_in":return bt((window.__bdsAppZoom||1)+.1),!0;case"zoom_out":return bt((window.__bdsAppZoom||1)-.1),!0;case"toggle_full_screen":return document.fullscreenElement?document.exitFullscreen?.():document.documentElement.requestFullscreen?.(),!0;default:return!1}};var is={mounted(){this.shortcuts=Ji(this.el.dataset.shortcuts),this.currentProjectId=this.el.dataset.projectId||"",this.syncStoredLayout(),this.syncStoredUiLanguage(),this.destroyOverlaySync=Xi(),this.workbenchStorageKey=e=>e?`${Bi}${e}`:null,this.restoreStoredWorkbenchSession=()=>{let e=this.el.dataset.projectId||"",t=this.workbenchStorageKey(e);if(!t)return!1;let i=ji(window.localStorage.getItem(t));return i?(this.pushEvent("restore_workbench_session",{session:i}),!0):!1},this.persistWorkbenchSession=()=>{let e=this.el.dataset.projectId||"",t=this.workbenchStorageKey(e),i=this.el.dataset.workbenchSession;!t||!i||window.localStorage.setItem(t,i)},this.handleMouseDown=e=>{let t=e.target.closest("[data-role='resize-handle']");if(!t||!this.el.contains(t))return;e.preventDefault();let i=t.dataset.resize,s=e.clientX,n=i==="assistant"?gt("[data-testid='assistant-shell']"):gt("[data-testid='sidebar-shell']"),r=i==="assistant"?280:200,o=i==="assistant"?640:500,a=i==="assistant",h=d=>{let p=a?s-d.clientX:d.clientX-s,m=ae(n+p,r,o);Vi(i==="assistant"?"[data-testid='assistant-shell']":"[data-testid='sidebar-shell']",m),Jt(i,m)},l=d=>{let p=a?s-d.clientX:d.clientX-s,m=ae(n+p,r,o);Jt(i,m),this.pushEvent("resize_panel",{target:i,width:m}),window.removeEventListener("mousemove",h),window.removeEventListener("mouseup",l)};window.addEventListener("mousemove",h),window.addEventListener("mouseup",l)},this.el.addEventListener("mousedown",this.handleMouseDown),this.handleNativeMenuAction=e=>{let t=e.detail?.action,i=e.detail?.ackId;t&&this.pushEvent("native_menu_action",{action:t},()=>{i&&window.dispatchEvent(new CustomEvent("bds:native-menu-action-ack",{detail:{ackId:i}}))})},this.handleChange=e=>{let t=e.target.closest(".status-bar-language-select");t&&this.el.contains(t)&&window.localStorage.setItem(Wt,t.value)},this.handleShortcutKeyDown=e=>{Wi(e)||!this.shortcuts.find(i=>qi(i,e))||(e.preventDefault(),e.stopPropagation(),this.pushEvent("shortcut",{key:vt(e.key),meta:e.metaKey,ctrl:e.ctrlKey,alt:e.altKey,shift:e.shiftKey,tag:e.target?.tagName||null,contentEditable:e.target?.isContentEditable||!1}))},this.handleThumbnailLoad=e=>{e.target instanceof HTMLImageElement&&e.target.classList.contains("media-thumbnail-image")&&mt(e.target,!0)},this.handleThumbnailError=e=>{e.target instanceof HTMLImageElement&&e.target.classList.contains("media-thumbnail-image")&&mt(e.target,!1)},this.handleEvent("menu-runtime-command",({action:e})=>{e&&ts(String(e))}),this.handleEvent("url-state",({path:e})=>{e&&window.location.pathname+window.location.search!==e&&window.history.replaceState({},"",e)}),window.addEventListener("bds:native-menu-action",this.handleNativeMenuAction),window.addEventListener("keydown",this.handleShortcutKeyDown,!0),this.el.addEventListener("load",this.handleThumbnailLoad,!0),this.el.addEventListener("error",this.handleThumbnailError,!0),this.el.addEventListener("change",this.handleChange),qt(this.el),this.restoreStoredWorkbenchSession()},updated(){let e=this.el.dataset.projectId||"";e!==this.currentProjectId&&(this.currentProjectId=e,this.restoreStoredWorkbenchSession())||(qt(this.el),this.persistWorkbenchSession())},destroyed(){this.el.removeEventListener("mousedown",this.handleMouseDown),this.el.removeEventListener("load",this.handleThumbnailLoad,!0),this.el.removeEventListener("error",this.handleThumbnailError,!0),this.el.removeEventListener("change",this.handleChange),window.removeEventListener("bds:native-menu-action",this.handleNativeMenuAction),window.removeEventListener("keydown",this.handleShortcutKeyDown,!0),this.destroyOverlaySync&&this.destroyOverlaySync()},syncStoredLayout(){this.pushEvent("sync_layout",{sidebar_width:Xt(ft,gt("[data-testid='sidebar-shell']"),200,500),assistant_sidebar_width:Xt(pt,360,280,640)})},syncStoredUiLanguage(){let e=window.localStorage.getItem(Wt);e&&this.pushEvent("sync_ui_language",{language:e})}};var ss={mounted(){this.handleDblClick=e=>{let t=e.target.closest("[data-testid='sidebar-open-item']");!t||!this.el.contains(t)||this.pushEvent("pin_sidebar_item",{route:t.dataset.route,id:t.dataset.itemId,title:t.dataset.openTitle||"",subtitle:t.dataset.openSubtitle||""})},this.el.addEventListener("dblclick",this.handleDblClick)},destroyed(){this.el.removeEventListener("dblclick",this.handleDblClick)}};var ns=e=>({mounted(){this.lastTargetId=null,this.scrollToSelectedSection()},updated(){this.scrollToSelectedSection()},scrollToSelectedSection(){let t=this.el.dataset[e];!t||t===this.lastTargetId||(this.lastTargetId=t,window.requestAnimationFrame(()=>{let i=document.getElementById(t);i&&this.el.contains(i)&&i.scrollIntoView({block:"start",behavior:"smooth"})}))}}),rs=ns("settingsScrollTarget"),os=ns("tagsScrollTarget");var as={mounted(){this.stickToBottom=!0,this.scrollContainer=null,this.autoResize=()=>{let e=this.el.querySelector(".chat-input");if(!e)return;let t=getComputedStyle(e),i=parseFloat(t.getPropertyValue("--chat-input-min-height"))||20,s=parseFloat(t.getPropertyValue("--chat-input-max-height"))||160;if(e.rows=1,e.style.minHeight=`${i}px`,e.value.trim()===""){e.style.height=`${i}px`,e.style.maxHeight=`${i}px`,e.style.overflowY="hidden";return}e.style.maxHeight=`${s}px`,e.style.height="0px";let n=Math.min(Math.max(e.scrollHeight,i),s);e.style.height=`${n}px`,e.style.overflowY=n>=s?"auto":"hidden"},this.syncScrollContainer=()=>{let e=this.el.querySelector(".chat-messages");e!==this.scrollContainer&&(this.scrollContainer&&this.scrollContainer.removeEventListener("scroll",this.handleScroll),this.scrollContainer=e,this.scrollContainer&&this.scrollContainer.addEventListener("scroll",this.handleScroll))},this.scrollToBottom=(e=!1)=>{this.scrollContainer&&(e||this.stickToBottom)&&(this.scrollContainer.scrollTop=this.scrollContainer.scrollHeight)},this.syncExpandedSurfaces=()=>{this.el.querySelectorAll(".chat-inline-surface[data-expanded='true']").forEach(e=>{e.open=!0})},this.surfaceObserver=new MutationObserver(()=>{this.syncExpandedSurfaces()}),this.handleScroll=()=>{if(!this.scrollContainer){this.stickToBottom=!0;return}let e=this.scrollContainer.scrollHeight-this.scrollContainer.scrollTop-this.scrollContainer.clientHeight;this.stickToBottom=e<48},this.handleInput=e=>{e.target.closest(".chat-input")&&(this.stickToBottom=!0,this.autoResize())},this.handleKeyDown=e=>{if(e.target.closest(".chat-input")&&e.key==="Enter"&&!e.shiftKey&&!e.isComposing){e.preventDefault();let t=this.el.querySelector("[data-testid='chat-send-button']");t&&!t.disabled&&t.click()}},this.el.addEventListener("input",this.handleInput),this.el.addEventListener("keydown",this.handleKeyDown),this.syncScrollContainer(),this.syncExpandedSurfaces(),this.surfaceObserver.observe(this.el,{childList:!0,subtree:!0}),this.autoResize(),window.requestAnimationFrame(()=>this.scrollToBottom(!0))},updated(){this.syncScrollContainer(),this.syncExpandedSurfaces(),this.autoResize(),window.requestAnimationFrame(()=>this.scrollToBottom())},destroyed(){this.surfaceObserver.disconnect(),this.el.removeEventListener("input",this.handleInput),this.el.removeEventListener("keydown",this.handleKeyDown),this.scrollContainer&&this.scrollContainer.removeEventListener("scroll",this.handleScroll)}};var hs={mounted(){this._onClickAway=e=>{this.el.contains(e.target)||this.el.querySelector(".colour-picker-popover")?.classList.add("hidden")},document.addEventListener("mousedown",this._onClickAway),this._setupCustomInput()},updated(){this._setupCustomInput()},destroyed(){document.removeEventListener("mousedown",this._onClickAway)},_setupCustomInput(){let e=this.el.querySelector(".colour-picker-custom input");if(!e||e._cpBound)return;e._cpBound=!0;let t=()=>{let i=e.value.trim();if(i&&!i.startsWith("#")&&(i="#"+i),/^#[0-9a-fA-F]{6}$/.test(i)){let s=this.el.dataset.pickEvent;this.pushEventTo(this.el.dataset.target,s,{color:i}),this.el.querySelector(".colour-picker-popover")?.classList.add("hidden")}};e.addEventListener("keydown",i=>{i.key==="Enter"&&(i.preventDefault(),t())}),e.addEventListener("blur",t)}};var ls={mounted(){this.dragItemId=null,this.dragSourceEl=null,this.dropTargetEl=null,this.dropPosition=null,this.clearDropTarget=()=>{this.dropTargetEl&&this.dropTargetEl.classList.remove("is-drop-before","is-drop-after","is-drop-inside"),this.dropTargetEl=null,this.dropPosition=null},this.setDropTarget=(e,t)=>{this.dropTargetEl===e&&this.dropPosition===t||(this.clearDropTarget(),this.dropTargetEl=e,this.dropPosition=t,e.classList.add(`is-drop-${t}`))},this.handleDragStart=e=>{let t=e.target.closest("[data-menu-drag-handle='true']"),i=e.target.closest("[data-menu-item-id]");!t||!i||!this.el.contains(i)||(this.dragItemId=i.dataset.menuItemId||null,this.dragSourceEl=i,i.classList.add("is-dragging"),e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",this.dragItemId||"")))},this.handleDragOver=e=>{let t=e.target.closest("[data-menu-item-id]");if(!this.dragItemId||!t||!this.el.contains(t)){this.clearDropTarget();return}let i=t.dataset.menuItemId||"";if(!i||i===this.dragItemId){this.clearDropTarget();return}e.preventDefault();let s=t.getBoundingClientRect(),n=e.clientY-s.top,r=t.dataset.menuCanDropInside==="true",o=s.height*.3,a=s.height*.7,h=r&&n>=o&&n<=a?"inside":n<s.height/2?"before":"after";this.setDropTarget(t,h),e.dataTransfer&&(e.dataTransfer.dropEffect="move")},this.handleDrop=e=>{let t=e.target.closest("[data-menu-item-id]");if(!this.dragItemId||!t||!this.el.contains(t)||!this.dropPosition){this.clearDropTarget();return}e.preventDefault(),this.pushEvent("menu_editor_drop_item",{drag_item_id:this.dragItemId,target_item_id:t.dataset.menuItemId,position:this.dropPosition}),this.clearDropTarget()},this.handleDragLeave=e=>{let t=e.relatedTarget;this.dropTargetEl&&(!t||!this.dropTargetEl.contains(t))&&this.clearDropTarget()},this.handleDragEnd=()=>{this.dragSourceEl&&this.dragSourceEl.classList.remove("is-dragging"),this.dragItemId=null,this.dragSourceEl=null,this.clearDropTarget()},this.el.addEventListener("dragstart",this.handleDragStart),this.el.addEventListener("dragover",this.handleDragOver),this.el.addEventListener("drop",this.handleDrop),this.el.addEventListener("dragleave",this.handleDragLeave),this.el.addEventListener("dragend",this.handleDragEnd)},destroyed(){this.el.removeEventListener("dragstart",this.handleDragStart),this.el.removeEventListener("dragover",this.handleDragOver),this.el.removeEventListener("drop",this.handleDrop),this.el.removeEventListener("dragleave",this.handleDragLeave),this.el.removeEventListener("dragend",this.handleDragEnd)}};var cs={mounted(){this.textarea=document.getElementById(this.el.dataset.monacoInputId)||this.el.querySelector("textarea"),this.host=this.el.querySelector(".monaco-editor-instance"),this.language=this.el.dataset.monacoLanguage||"plaintext",this.wordWrap=this.el.dataset.monacoWordWrap||"off",this.editorId=this.el.dataset.monacoEditorId||"",this.insertEvent=this.el.dataset.monacoInsertEvent||"",this.syncTimer=null,this.isApplyingRemoteUpdate=!1,this.lastKnownValue=this.textarea?.value||"",this.syncEditorFromTextarea=()=>{if(this.textarea=document.getElementById(this.el.dataset.monacoInputId)||this.el.querySelector("textarea"),!this.textarea||!this.editor)return;let e=this.textarea.value||"";this.editor.getValue()!==e&&(this.isApplyingRemoteUpdate=!0,this.editor.setValue(e),this.isApplyingRemoteUpdate=!1),this.lastKnownValue=e},this.layoutEditorSoon=()=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{this.editor&&this.editor.layout()})})},this.waitForMonacoVisibleSize=()=>new Promise(e=>{let t=!1,i=0,s=()=>{let o=this.host?.getBoundingClientRect();return!!(o&&o.width>0&&o.height>0)},n=()=>{t||(t=!0,this.visibleSizeObserver?.disconnect(),this.visibleSizeObserver=null,e())},r=()=>{if(s()||i>=20){n();return}i+=1,window.requestAnimationFrame(r)};if(s()){n();return}window.ResizeObserver&&this.host&&(this.visibleSizeObserver=new ResizeObserver(()=>{s()&&n()}),this.visibleSizeObserver.observe(this.host)),window.requestAnimationFrame(r)}),this.queueSync=()=>{!this.textarea||!this.editor||(window.clearTimeout(this.syncTimer),this.syncTimer=window.setTimeout(()=>{if(!this.textarea||!this.editor)return;let e=this.editor.getValue();this.textarea.value!==e&&(this.lastKnownValue=e,this.textarea.value=e,this.textarea.dispatchEvent(new Event("input",{bubbles:!0})))},120))},this.dropEvent=this.el.dataset.monacoDropEvent||"",this.dropPostId=this.el.dataset.monacoDropPostId||"",this.handleDragOver=e=>{e.dataTransfer&&Array.from(e.dataTransfer.types||[]).includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},this.handleDrop=e=>{if(!this.dropEvent||!e.dataTransfer)return;let i=Array.from(e.dataTransfer.files||[]).filter(s=>(s.type||"").startsWith("image/")&&s.path);i.length!==0&&(e.preventDefault(),e.stopPropagation(),i.forEach(s=>{this.pushEvent(this.dropEvent,{"post-id":this.dropPostId,path:s.path})}))},this.handleInsert=({id:e,content:t})=>{if(!this.editor||!t||String(e)!==String(this.editorId))return;let i=this.editor.getModel(),s=this.editor.getSelection();if(!i||!s)return;let n=this.editor.getValue(),r=i.getOffsetAt(s.getStartPosition()),o=i.getOffsetAt(s.getEndPosition()),a=n.slice(0,r),h=n.slice(o),l=a!==""&&!a.endsWith(`
`)?`
`:"",d=h!==""&&!t.endsWith(`
`)?`
`:"",p=`${l}${t}${d}`;this.editor.executeEdits("bds-insert-content",[{range:s,text:p,forceMoveMarkers:!0}]),this.editor.focus()},Oe().then(async e=>{!this.host||!this.textarea||(await this.waitForMonacoVisibleSize(),he(e),this.editor=e.editor.create(this.host,{value:this.textarea.value||"",language:this.language,theme:"bds-theme",automaticLayout:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,wordWrap:this.wordWrap,lineNumbers:"on",lineNumbersMinChars:3,fontSize:14,fontFamily:"'Cascadia Code', 'Consolas', 'Courier New', monospace",padding:{top:12,bottom:12},roundedSelection:!1,renderLineHighlight:"line",formatOnPaste:!0,cursorStyle:"line",cursorBlinking:"smooth",quickSuggestions:this.language!=="markdown-with-macros",tabSize:2,insertSpaces:!0}),Zi(this.editorId||this.el.id,this.editor),e.editor.setTheme("bds-theme"),this.syncEditorFromTextarea(),this.layoutEditorSoon(),this.changeSubscription=this.editor.onDidChangeModelContent(()=>{this.isApplyingRemoteUpdate||this.queueSync()}),this.insertEvent&&this.handleEvent(this.insertEvent,this.handleInsert),this.dropEvent&&(this.el.addEventListener("dragover",this.handleDragOver),this.el.addEventListener("drop",this.handleDrop)))}).catch(e=>{console.error("Failed to load Monaco editor",e)})},updated(){this.textarea=document.getElementById(this.el.dataset.monacoInputId)||this.el.querySelector("textarea"),this.host=this.el.querySelector(".monaco-editor-instance"),this.language=this.el.dataset.monacoLanguage||this.language||"plaintext",this.wordWrap=this.el.dataset.monacoWordWrap||this.wordWrap||"off",!(!this.editor||!this.textarea)&&(Oe().then(e=>{he(e),e.editor.setTheme("bds-theme"),this.editor.getModel()?.getLanguageId()!==this.language&&e.editor.setModelLanguage(this.editor.getModel(),this.language),this.editor.updateOptions({wordWrap:this.wordWrap})}),this.syncEditorFromTextarea(),this.layoutEditorSoon())},destroyed(){window.clearTimeout(this.syncTimer),this.visibleSizeObserver?.disconnect(),this.changeSubscription?.dispose(),this.dropEvent&&(this.el.removeEventListener("dragover",this.handleDragOver),this.el.removeEventListener("drop",this.handleDrop)),Qi(this.editorId||this.el.id),this.editor?.dispose()}};var ds={mounted(){this.host=this.el.querySelector(".monaco-diff-editor-instance"),this.originalInput=this.el.querySelector(".monaco-diff-original"),this.modifiedInput=this.el.querySelector(".monaco-diff-modified"),this.filePath=this.el.dataset.monacoDiffFilePath||"working-tree",this.language=this.el.dataset.monacoDiffLanguage||"plaintext",this.viewStyle=this.el.dataset.monacoDiffViewStyle||"inline",this.wordWrap=this.el.dataset.monacoDiffWordWrap||"off",this.hideUnchanged=this.el.dataset.monacoDiffHideUnchanged==="true",this.readValues=()=>({original:this.originalInput?.value||"",modified:this.modifiedInput?.value||""}),this.applyDataset=()=>{this.filePath=this.el.dataset.monacoDiffFilePath||"working-tree",this.language=this.el.dataset.monacoDiffLanguage||"plaintext",this.viewStyle=this.el.dataset.monacoDiffViewStyle||"inline",this.wordWrap=this.el.dataset.monacoDiffWordWrap||"off",this.hideUnchanged=this.el.dataset.monacoDiffHideUnchanged==="true"},this.setModels=e=>{let t=this.readValues();this.originalModel?.dispose(),this.modifiedModel?.dispose(),this.originalModel=e.editor.createModel(t.original,this.language,e.Uri.parse(Yt(this.filePath,"original"))),this.modifiedModel=e.editor.createModel(t.modified,this.language,e.Uri.parse(Yt(this.filePath,"modified"))),this.editor.setModel({original:this.originalModel,modified:this.modifiedModel}),this.lastFilePath=this.filePath},Oe().then(e=>{this.host&&(he(e),this.editor=e.editor.createDiffEditor(this.host,{theme:"bds-theme",automaticLayout:!0,readOnly:!0,renderSideBySide:this.viewStyle==="side-by-side",minimap:{enabled:!1},scrollBeyondLastLine:!1,lineNumbers:"on",diffCodeLens:!1,originalEditable:!1,wordWrap:this.wordWrap,hideUnchangedRegions:{enabled:this.hideUnchanged},ignoreTrimWhitespace:!1}),this.setModels(e))}).catch(e=>{console.error("Failed to load Monaco diff editor",e)})},updated(){this.host=this.el.querySelector(".monaco-diff-editor-instance"),this.originalInput=this.el.querySelector(".monaco-diff-original"),this.modifiedInput=this.el.querySelector(".monaco-diff-modified"),this.applyDataset(),this.editor&&Oe().then(e=>{if(he(e),e.editor.setTheme("bds-theme"),this.editor.updateOptions({renderSideBySide:this.viewStyle==="side-by-side",wordWrap:this.wordWrap,hideUnchangedRegions:{enabled:this.hideUnchanged}}),this.lastFilePath!==this.filePath){this.setModels(e);return}let t=this.readValues();this.originalModel&&this.originalModel.getLanguageId()!==this.language&&e.editor.setModelLanguage(this.originalModel,this.language),this.modifiedModel&&this.modifiedModel.getLanguageId()!==this.language&&e.editor.setModelLanguage(this.modifiedModel,this.language),this.originalModel&&this.originalModel.getValue()!==t.original&&this.originalModel.setValue(t.original),this.modifiedModel&&this.modifiedModel.getValue()!==t.modified&&this.modifiedModel.setValue(t.modified)})},destroyed(){this.originalModel?.dispose(),this.modifiedModel?.dispose(),this.editor?.dispose()}};var us={AppShell:is,SidebarInteractions:ss,SettingsSectionScroll:rs,TagsSectionScroll:os,ChatSurface:as,ColourPicker:hs,MenuEditorTree:ls,MonacoEditor:cs,MonacoDiffEditor:ds};document.addEventListener("DOMContentLoaded",()=>{let e=document.querySelector("meta[name='csrf-token']").getAttribute("content"),t=new Ui("/live",ti,{params:{_csrf_token:e},hooks:us,metadata:{keydown:i=>({key:i.key,meta:i.metaKey,ctrl:i.ctrlKey,alt:i.altKey,shift:i.shiftKey,tag:i.target?.tagName||null,contentEditable:i.target?.isContentEditable||!1})}});t.connect(),window.liveSocket=t});})();