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