Current section

Files

Jump to
phx_live_storybook priv static js iframe.js
Raw

priv/static/js/iframe.js

(()=>{var bt="consecutive-reloads",Dt=10,It=5e3,Ot=1e4,Ht=3e4,yt=["phx-click-loading","phx-change-loading","phx-submit-loading","phx-keydown-loading","phx-keyup-loading","phx-blur-loading","phx-focus-loading"],L="data-phx-component",De="data-phx-link",Nt="track-static",Mt="data-phx-link-state",M="data-phx-ref",z="data-phx-ref-src",St="track-uploads",K="data-phx-upload-ref",We="data-phx-preflighted-refs",Ut="data-phx-done-refs",Qe="drop-target",$e="data-phx-active-refs",Fe="phx:live-file:updated",Be="data-phx-skip",Ze="data-phx-prune",et="page-loading",tt="phx-connected",Ie="phx-loading",it="phx-no-feedback",st="phx-error",Q="data-phx-parent-id",qe="data-phx-main",ae="data-phx-root-id",jt="trigger-action",Je="feedback-for",wt="phx-has-focused",$t=["text","textarea","number","email","password","search","tel","url","date","time","datetime-local","color","range"],kt=["checkbox","radio"],At="phx-has-submitted",W="data-phx-session",Z=`[${W}]`,nt="data-phx-sticky",re="data-phx-static",Oe="data-phx-readonly",me="data-phx-disabled",Ve="disable-with",be="data-phx-disable-with-restore",ee="hook",Ft="debounce",Bt="throttle",Xe="update",Jt="key",O="phxPrivate",rt="auto-recover",ye="phx:live-socket:debug",He="phx:live-socket:profiling",Ne="phx:live-socket:latency-sim",Vt="progress",Xt=1,Wt=200,qt="phx-",zt=3e4,te="debounce-trigger",Se="throttled",ot="debounce-prev-key",Kt={debounce:300,throttle:300},at="d",H="s",R="c",ht="e",lt="r",dt="t",Gt="p",Yt=class{constructor(e,t,i){this.liveSocket=i,this.entry=e,this.offset=0,this.chunkSize=t,this.chunkTimer=null,this.uploadChannel=i.channel(`lvu:${e.ref}`,{token:e.metadata()})}error(e){clearTimeout(this.chunkTimer),this.uploadChannel.leave(),this.entry.error(e)}upload(){this.uploadChannel.onError(e=>this.error(e)),this.uploadChannel.join().receive("ok",e=>this.readNextChunk()).receive("error",e=>this.error(e))}isDone(){return this.offset>=this.entry.file.size}readNextChunk(){let e=new window.FileReader,t=this.entry.file.slice(this.offset,this.chunkSize+this.offset);e.onload=i=>{if(i.target.error===null)this.offset+=i.target.result.byteLength,this.pushChunk(i.target.result);else return T("Read error: "+i.target.error)},e.readAsArrayBuffer(t)}pushChunk(e){!this.uploadChannel.isJoined()||this.uploadChannel.push("chunk",e).receive("ok",()=>{this.entry.progress(this.offset/this.entry.file.size*100),this.isDone()||(this.chunkTimer=setTimeout(()=>this.readNextChunk(),this.liveSocket.getLatencySim()||0))})}},T=(e,t)=>console.error&&console.error(e,t),X=e=>{let t=typeof e;return t==="number"||t==="string"&&/^(0|[1-9]\d*)$/.test(e)};function Qt(){let e=new Set,t=document.querySelectorAll("*[id]");for(let i=0,s=t.length;i<s;i++)e.has(t[i].id)?console.error(`Multiple IDs detected: ${t[i].id}. Ensure unique element ids.`):e.add(t[i].id)}var Zt=(e,t,i,s)=>{e.liveSocket.isDebugEnabled()&&console.log(`${e.id} ${t}: ${i} - `,s)},Me=e=>typeof e=="function"?e:function(){return e},Ee=e=>JSON.parse(JSON.stringify(e)),oe=(e,t,i)=>{do{if(e.matches(`[${t}]`))return e;e=e.parentElement||e.parentNode}while(e!==null&&e.nodeType===1&&!(i&&i.isSameNode(e)||e.matches(Z)));return null},ie=e=>e!==null&&typeof e=="object"&&!(e instanceof Array),ei=(e,t)=>JSON.stringify(e)===JSON.stringify(t),ct=e=>{for(let t in e)return!1;return!0},j=(e,t)=>e&&t(e),ti=function(e,t,i,s){e.forEach(n=>{new Yt(n,i.config.chunk_size,s).upload()})},Ct={canPushState(){return typeof history.pushState<"u"},dropLocal(e,t,i){return e.removeItem(this.localKey(t,i))},updateLocal(e,t,i,s,n){let r=this.getLocal(e,t,i),o=this.localKey(t,i),a=r===null?s:n(r);return e.setItem(o,JSON.stringify(a)),a},getLocal(e,t,i){return JSON.parse(e.getItem(this.localKey(t,i)))},updateCurrentState(e){!this.canPushState()||history.replaceState(e(history.state||{}),"",window.location.href)},pushState(e,t,i){if(this.canPushState()){if(i!==window.location.href){if(t.type=="redirect"&&t.scroll){let n=history.state||{};n.scroll=t.scroll,history.replaceState(n,"",window.location.href)}delete t.scroll,history[e+"State"](t,"",i||null);let s=this.getHashTargetEl(window.location.hash);s?s.scrollIntoView():t.type==="redirect"&&window.scroll(0,0)}}else this.redirect(i)},setCookie(e,t){document.cookie=`${e}=${t}`},getCookie(e){return document.cookie.replace(new RegExp(`(?:(?:^|.*;s*)${e}s*=s*([^;]*).*$)|^.*$`),"$1")},redirect(e,t){t&&Ct.setCookie("__phoenix_flash__",t+"; max-age=60000; path=/"),window.location=e},localKey(e,t){return`${e}-${t}`},getHashTargetEl(e){let t=e.toString().substring(1);if(t!=="")return document.getElementById(t)||document.querySelector(`a[name="${t}"]`)}},V=Ct,I={byId(e){return document.getElementById(e)||T(`no id found for ${e}`)},removeClass(e,t){e.classList.remove(t),e.classList.length===0&&e.removeAttribute("class")},all(e,t,i){if(!e)return[];let s=Array.from(e.querySelectorAll(t));return i?s.forEach(i):s},childNodeLength(e){let t=document.createElement("template");return t.innerHTML=e,t.content.childElementCount},isUploadInput(e){return e.type==="file"&&e.getAttribute(K)!==null},findUploadInputs(e){return this.all(e,`input[type="file"][${K}]`)},findComponentNodeList(e,t){return this.filterWithinSameLiveView(this.all(e,`[${L}="${t}"]`),e)},isPhxDestroyed(e){return!!(e.id&&I.private(e,"destroyed"))},markPhxChildDestroyed(e){this.isPhxChild(e)&&e.setAttribute(W,""),this.putPrivate(e,"destroyed",!0)},findPhxChildrenInFragment(e,t){let i=document.createElement("template");return i.innerHTML=e,this.findPhxChildren(i.content,t)},isIgnored(e,t){return(e.getAttribute(t)||e.getAttribute("data-phx-update"))==="ignore"},isPhxUpdate(e,t,i){return e.getAttribute&&i.indexOf(e.getAttribute(t))>=0},findPhxSticky(e){return this.all(e,`[${nt}]`)},findPhxChildren(e,t){return this.all(e,`${Z}[${Q}="${t}"]`)},findParentCIDs(e,t){let i=new Set(t);return t.reduce((s,n)=>{let r=`[${L}="${n}"] [${L}]`;return this.filterWithinSameLiveView(this.all(e,r),e).map(o=>parseInt(o.getAttribute(L))).forEach(o=>s.delete(o)),s},i)},filterWithinSameLiveView(e,t){return t.querySelector(Z)?e.filter(i=>this.withinSameLiveView(i,t)):e},withinSameLiveView(e,t){for(;e=e.parentNode;){if(e.isSameNode(t))return!0;if(e.getAttribute(W)!==null)return!1}},private(e,t){return e[O]&&e[O][t]},deletePrivate(e,t){e[O]&&delete e[O][t]},putPrivate(e,t,i){e[O]||(e[O]={}),e[O][t]=i},updatePrivate(e,t,i,s){let n=this.private(e,t);n===void 0?this.putPrivate(e,t,s(i)):this.putPrivate(e,t,s(n))},copyPrivates(e,t){t[O]&&(e[O]=t[O])},putTitle(e){let t=document.querySelector("title"),{prefix:i,suffix:s}=t.dataset;document.title=`${i||""}${e}${s||""}`},debounce(e,t,i,s,n,r,o,a){let h=e.getAttribute(i),c=e.getAttribute(n);h===""&&(h=s),c===""&&(c=r);let f=h||c;switch(f){case null:return a();case"blur":this.once(e,"debounce-blur")&&e.addEventListener("blur",()=>a());return;default:let u=parseInt(f),v=()=>c?this.deletePrivate(e,Se):a(),y=this.incCycle(e,te,v);if(isNaN(u))return T(`invalid throttle/debounce value: ${f}`);if(c){let p=!1;if(t.type==="keydown"){let A=this.private(e,ot);this.putPrivate(e,ot,t.key),p=A!==t.key}if(!p&&this.private(e,Se))return!1;a(),this.putPrivate(e,Se,!0),setTimeout(()=>{o()&&this.triggerCycle(e,te)},u)}else setTimeout(()=>{o()&&this.triggerCycle(e,te,y)},u);let S=e.form;S&&this.once(S,"bind-debounce")&&S.addEventListener("submit",()=>{Array.from(new FormData(S).entries(),([p])=>{let A=S.querySelector(`[name="${p}"]`);this.incCycle(A,te),this.deletePrivate(A,Se)})}),this.once(e,"bind-debounce")&&e.addEventListener("blur",()=>this.triggerCycle(e,te))}},triggerCycle(e,t,i){let[s,n]=this.private(e,t);i||(i=s),i===s&&(this.incCycle(e,t),n())},once(e,t){return this.private(e,t)===!0?!1:(this.putPrivate(e,t,!0),!0)},incCycle(e,t,i=function(){}){let[s]=this.private(e,t)||[0,i];return s++,this.putPrivate(e,t,[s,i]),s},discardError(e,t,i){let s=t.getAttribute&&t.getAttribute(i),n=s&&e.querySelector(`[id="${s}"], [name="${s}"]`);!n||this.private(n,wt)||this.private(n.form,At)||t.classList.add(it)},showError(e,t){(e.id||e.name)&&this.all(e.form,`[${t}="${e.id}"], [${t}="${e.name}"]`,i=>{this.removeClass(i,it)})},isPhxChild(e){return e.getAttribute&&e.getAttribute(Q)},isPhxSticky(e){return e.getAttribute&&e.getAttribute(nt)!==null},firstPhxChild(e){return this.isPhxChild(e)?e:this.all(e,`[${Q}]`)[0]},dispatchEvent(e,t,i={}){let n={bubbles:i.bubbles===void 0?!0:!!i.bubbles,cancelable:!0,detail:i.detail||{}},r=t==="click"?new MouseEvent("click",n):new CustomEvent(t,n);e.dispatchEvent(r)},cloneNode(e,t){if(typeof t>"u")return e.cloneNode(!0);{let i=e.cloneNode(!1);return i.innerHTML=t,i}},mergeAttrs(e,t,i={}){let s=i.exclude||[],n=i.isIgnored,r=t.attributes;for(let a=r.length-1;a>=0;a--){let h=r[a].name;s.indexOf(h)<0&&e.setAttribute(h,t.getAttribute(h))}let o=e.attributes;for(let a=o.length-1;a>=0;a--){let h=o[a].name;n?h.startsWith("data-")&&!t.hasAttribute(h)&&e.removeAttribute(h):t.hasAttribute(h)||e.removeAttribute(h)}},mergeFocusedInput(e,t){e instanceof HTMLSelectElement||I.mergeAttrs(e,t,{exclude:["value"]}),t.readOnly?e.setAttribute("readonly",!0):e.removeAttribute("readonly")},hasSelectionRange(e){return e.setSelectionRange&&(e.type==="text"||e.type==="textarea")},restoreFocus(e,t,i){if(!I.isTextualInput(e))return;let s=e.matches(":focus");e.readOnly&&e.blur(),s||e.focus(),this.hasSelectionRange(e)&&e.setSelectionRange(t,i)},isFormInput(e){return/^(?:input|select|textarea)$/i.test(e.tagName)&&e.type!=="button"},syncAttrsToProps(e){e instanceof HTMLInputElement&&kt.indexOf(e.type.toLocaleLowerCase())>=0&&(e.checked=e.getAttribute("checked")!==null)},isTextualInput(e){return $t.indexOf(e.type)>=0},isNowTriggerFormExternal(e,t){return e.getAttribute&&e.getAttribute(t)!==null},syncPendingRef(e,t,i){let s=e.getAttribute(M);if(s===null)return!0;let n=e.getAttribute(z);return I.isFormInput(e)||e.getAttribute(i)!==null?(I.isUploadInput(e)&&I.mergeAttrs(e,t,{isIgnored:!0}),I.putPrivate(e,M,t),!1):(yt.forEach(r=>{e.classList.contains(r)&&t.classList.add(r)}),t.setAttribute(M,s),t.setAttribute(z,n),!0)},cleanChildNodes(e,t){if(I.isPhxUpdate(e,t,["append","prepend"])){let i=[];e.childNodes.forEach(s=>{s.id||(s.nodeType===Node.TEXT_NODE&&s.nodeValue.trim()===""||T(`only HTML element tags with an id are allowed inside containers with phx-update.
removing illegal node: "${(s.outerHTML||s.nodeValue).trim()}"
`),i.push(s))}),i.forEach(s=>s.remove())}},replaceRootContainer(e,t,i){let s=new Set(["id",W,re,qe,ae]);if(e.tagName.toLowerCase()===t.toLowerCase())return Array.from(e.attributes).filter(n=>!s.has(n.name.toLowerCase())).forEach(n=>e.removeAttribute(n.name)),Object.keys(i).filter(n=>!s.has(n.toLowerCase())).forEach(n=>e.setAttribute(n,i[n])),e;{let n=document.createElement(t);return Object.keys(i).forEach(r=>n.setAttribute(r,i[r])),s.forEach(r=>n.setAttribute(r,e.getAttribute(r))),n.innerHTML=e.innerHTML,e.replaceWith(n),n}},getSticky(e,t,i){let s=(I.private(e,"sticky")||[]).find(([n])=>t===n);if(s){let[n,r,o]=s;return o}else return typeof i=="function"?i():i},deleteSticky(e,t){this.updatePrivate(e,"sticky",[],i=>i.filter(([s,n])=>s!==t))},putSticky(e,t,i){let s=i(e);this.updatePrivate(e,"sticky",[],n=>{let r=n.findIndex(([o])=>t===o);return r>=0?n[r]=[t,i,s]:n.push([t,i,s]),n})},applyStickyOperations(e){let t=I.private(e,"sticky");!t||t.forEach(([i,s,n])=>this.putSticky(e,i,s))}},l=I,Ue=class{static isActive(e,t){let i=t._phxRef===void 0,n=e.getAttribute($e).split(",").indexOf(E.genFileRef(t))>=0;return t.size>0&&(i||n)}static isPreflighted(e,t){return e.getAttribute(We).split(",").indexOf(E.genFileRef(t))>=0&&this.isActive(e,t)}constructor(e,t,i){this.ref=E.genFileRef(t),this.fileEl=e,this.file=t,this.view=i,this.meta=null,this._isCancelled=!1,this._isDone=!1,this._progress=0,this._lastProgressSent=-1,this._onDone=function(){},this._onElUpdated=this.onElUpdated.bind(this),this.fileEl.addEventListener(Fe,this._onElUpdated)}metadata(){return this.meta}progress(e){this._progress=Math.floor(e),this._progress>this._lastProgressSent&&(this._progress>=100?(this._progress=100,this._lastProgressSent=100,this._isDone=!0,this.view.pushFileProgress(this.fileEl,this.ref,100,()=>{E.untrackFile(this.fileEl,this.file),this._onDone()})):(this._lastProgressSent=this._progress,this.view.pushFileProgress(this.fileEl,this.ref,this._progress)))}cancel(){this._isCancelled=!0,this._isDone=!0,this._onDone()}isDone(){return this._isDone}error(e="failed"){this.view.pushFileProgress(this.fileEl,this.ref,{error:e}),E.clearFiles(this.fileEl)}onDone(e){this._onDone=()=>{this.fileEl.removeEventListener(Fe,this._onElUpdated),e()}}onElUpdated(){this.fileEl.getAttribute($e).split(",").indexOf(this.ref)===-1&&this.cancel()}toPreflightPayload(){return{last_modified:this.file.lastModified,name:this.file.name,size:this.file.size,type:this.file.type,ref:this.ref}}uploader(e){if(this.meta.uploader){let t=e[this.meta.uploader]||T(`no uploader configured for ${this.meta.uploader}`);return{name:this.meta.uploader,callback:t}}else return{name:"channel",callback:ti}}zipPostFlight(e){this.meta=e.entries[this.ref],this.meta||T(`no preflight upload response returned with ref ${this.ref}`,{input:this.fileEl,response:e})}},ii=0,E=class{static genFileRef(e){let t=e._phxRef;return t!==void 0?t:(e._phxRef=(ii++).toString(),e._phxRef)}static getEntryDataURL(e,t,i){let s=this.activeFiles(e).find(n=>this.genFileRef(n)===t);i(URL.createObjectURL(s))}static hasUploadsInProgress(e){let t=0;return l.findUploadInputs(e).forEach(i=>{i.getAttribute(We)!==i.getAttribute(Ut)&&t++}),t>0}static serializeUploads(e){let t=this.activeFiles(e),i={};return t.forEach(s=>{let n={path:e.name},r=e.getAttribute(K);i[r]=i[r]||[],n.ref=this.genFileRef(s),n.name=s.name||n.ref,n.type=s.type,n.size=s.size,i[r].push(n)}),i}static clearFiles(e){e.value=null,e.removeAttribute(K),l.putPrivate(e,"files",[])}static untrackFile(e,t){l.putPrivate(e,"files",l.private(e,"files").filter(i=>!Object.is(i,t)))}static trackFiles(e,t){if(e.getAttribute("multiple")!==null){let i=t.filter(s=>!this.activeFiles(e).find(n=>Object.is(n,s)));l.putPrivate(e,"files",this.activeFiles(e).concat(i)),e.value=null}else l.putPrivate(e,"files",t)}static activeFileInputs(e){let t=l.findUploadInputs(e);return Array.from(t).filter(i=>i.files&&this.activeFiles(i).length>0)}static activeFiles(e){return(l.private(e,"files")||[]).filter(t=>Ue.isActive(e,t))}static inputsAwaitingPreflight(e){let t=l.findUploadInputs(e);return Array.from(t).filter(i=>this.filesAwaitingPreflight(i).length>0)}static filesAwaitingPreflight(e){return this.activeFiles(e).filter(t=>!Ue.isPreflighted(e,t))}constructor(e,t,i){this.view=t,this.onComplete=i,this._entries=Array.from(E.filesAwaitingPreflight(e)||[]).map(s=>new Ue(e,s,t)),this.numEntriesInProgress=this._entries.length}entries(){return this._entries}initAdapterUpload(e,t,i){this._entries=this._entries.map(n=>(n.zipPostFlight(e),n.onDone(()=>{this.numEntriesInProgress--,this.numEntriesInProgress===0&&this.onComplete()}),n));let s=this._entries.reduce((n,r)=>{let{name:o,callback:a}=r.uploader(i.uploaders);return n[o]=n[o]||{callback:a,entries:[]},n[o].entries.push(r),n},{});for(let n in s){let{callback:r,entries:o}=s[n];r(o,t,e,i)}}},si={LiveFileUpload:{activeRefs(){return this.el.getAttribute($e)},preflightedRefs(){return this.el.getAttribute(We)},mounted(){this.preflightedWas=this.preflightedRefs()},updated(){let e=this.preflightedRefs();this.preflightedWas!==e&&(this.preflightedWas=e,e===""&&this.__view.cancelSubmit(this.el.form)),this.activeRefs()===""&&(this.el.value=null),this.el.dispatchEvent(new CustomEvent(Fe))}},LiveImgPreview:{mounted(){this.ref=this.el.getAttribute("data-phx-entry-ref"),this.inputEl=document.getElementById(this.el.getAttribute(K)),E.getEntryDataURL(this.inputEl,this.ref,e=>{this.url=e,this.el.src=e})},destroyed(){URL.revokeObjectURL(this.url)}}},ni=si,ri=class{constructor(e,t,i){let s=new Set,n=new Set([...t.children].map(o=>o.id)),r=[];Array.from(e.children).forEach(o=>{if(o.id&&(s.add(o.id),n.has(o.id))){let a=o.previousElementSibling&&o.previousElementSibling.id;r.push({elementId:o.id,previousElementId:a})}}),this.containerId=t.id,this.updateType=i,this.elementsToModify=r,this.elementIdsToAdd=[...n].filter(o=>!s.has(o))}perform(){let e=l.byId(this.containerId);this.elementsToModify.forEach(t=>{t.previousElementId?j(document.getElementById(t.previousElementId),i=>{j(document.getElementById(t.elementId),s=>{s.previousElementSibling&&s.previousElementSibling.id==i.id||i.insertAdjacentElement("afterend",s)})}):j(document.getElementById(t.elementId),i=>{i.previousElementSibling==null||e.insertAdjacentElement("afterbegin",i)})}),this.updateType=="prepend"&&this.elementIdsToAdd.reverse().forEach(t=>{j(document.getElementById(t),i=>e.insertAdjacentElement("afterbegin",i))})}},ut=11;function oi(e,t){var i=t.attributes,s,n,r,o,a;if(!(t.nodeType===ut||e.nodeType===ut)){for(var h=i.length-1;h>=0;h--)s=i[h],n=s.name,r=s.namespaceURI,o=s.value,r?(n=s.localName||n,a=e.getAttributeNS(r,n),a!==o&&(s.prefix==="xmlns"&&(n=s.name),e.setAttributeNS(r,n,o))):(a=e.getAttribute(n),a!==o&&e.setAttribute(n,o));for(var c=e.attributes,f=c.length-1;f>=0;f--)s=c[f],n=s.name,r=s.namespaceURI,r?(n=s.localName||n,t.hasAttributeNS(r,n)||e.removeAttributeNS(r,n)):t.hasAttribute(n)||e.removeAttribute(n)}}var we,ai="http://www.w3.org/1999/xhtml",_=typeof document>"u"?void 0:document,hi=!!_&&"content"in _.createElement("template"),li=!!_&&_.createRange&&"createContextualFragment"in _.createRange();function di(e){var t=_.createElement("template");return t.innerHTML=e,t.content.childNodes[0]}function ci(e){we||(we=_.createRange(),we.selectNode(_.body));var t=we.createContextualFragment(e);return t.childNodes[0]}function ui(e){var t=_.createElement("body");return t.innerHTML=e,t.childNodes[0]}function fi(e){return e=e.trim(),hi?di(e):li?ci(e):ui(e)}function ke(e,t){var i=e.nodeName,s=t.nodeName,n,r;return i===s?!0:(n=i.charCodeAt(0),r=s.charCodeAt(0),n<=90&&r>=97?i===s.toUpperCase():r<=90&&n>=97?s===i.toUpperCase():!1)}function pi(e,t){return!t||t===ai?_.createElement(e):_.createElementNS(t,e)}function gi(e,t){for(var i=e.firstChild;i;){var s=i.nextSibling;t.appendChild(i),i=s}return t}function je(e,t,i){e[i]!==t[i]&&(e[i]=t[i],e[i]?e.setAttribute(i,""):e.removeAttribute(i))}var ft={OPTION:function(e,t){var i=e.parentNode;if(i){var s=i.nodeName.toUpperCase();s==="OPTGROUP"&&(i=i.parentNode,s=i&&i.nodeName.toUpperCase()),s==="SELECT"&&!i.hasAttribute("multiple")&&(e.hasAttribute("selected")&&!t.selected&&(e.setAttribute("selected","selected"),e.removeAttribute("selected")),i.selectedIndex=-1)}je(e,t,"selected")},INPUT:function(e,t){je(e,t,"checked"),je(e,t,"disabled"),e.value!==t.value&&(e.value=t.value),t.hasAttribute("value")||e.removeAttribute("value")},TEXTAREA:function(e,t){var i=t.value;e.value!==i&&(e.value=i);var s=e.firstChild;if(s){var n=s.nodeValue;if(n==i||!i&&n==e.placeholder)return;s.nodeValue=i}},SELECT:function(e,t){if(!t.hasAttribute("multiple")){for(var i=-1,s=0,n=e.firstChild,r,o;n;)if(o=n.nodeName&&n.nodeName.toUpperCase(),o==="OPTGROUP")r=n,n=r.firstChild;else{if(o==="OPTION"){if(n.hasAttribute("selected")){i=s;break}s++}n=n.nextSibling,!n&&r&&(n=r.nextSibling,r=null)}e.selectedIndex=i}}},se=1,vi=11,pt=3,gt=8;function q(){}function mi(e){if(e)return e.getAttribute&&e.getAttribute("id")||e.id}function bi(e){return function(i,s,n){if(n||(n={}),typeof s=="string")if(i.nodeName==="#document"||i.nodeName==="HTML"||i.nodeName==="BODY"){var r=s;s=_.createElement("html"),s.innerHTML=r}else s=fi(s);var o=n.getNodeKey||mi,a=n.onBeforeNodeAdded||q,h=n.onNodeAdded||q,c=n.onBeforeElUpdated||q,f=n.onElUpdated||q,u=n.onBeforeNodeDiscarded||q,v=n.onNodeDiscarded||q,y=n.onBeforeElChildrenUpdated||q,S=n.childrenOnly===!0,p=Object.create(null),A=[];function P(b){A.push(b)}function G(b,m){if(b.nodeType===se)for(var g=b.firstChild;g;){var w=void 0;m&&(w=o(g))?P(w):(v(g),g.firstChild&&G(g,m)),g=g.nextSibling}}function d(b,m,g){u(b)!==!1&&(m&&m.removeChild(b),v(b),G(b,g))}function k(b){if(b.nodeType===se||b.nodeType===vi)for(var m=b.firstChild;m;){var g=o(m);g&&(p[g]=m),k(m),m=m.nextSibling}}k(i);function ce(b){h(b);for(var m=b.firstChild;m;){var g=m.nextSibling,w=o(m);if(w){var D=p[w];D&&ke(m,D)?(m.parentNode.replaceChild(D,m),fe(D,m)):ce(m)}else ce(m);m=g}}function ue(b,m,g){for(;m;){var w=m.nextSibling;(g=o(m))?P(g):d(m,b,!0),m=w}}function fe(b,m,g){var w=o(m);w&&delete p[w],!(!g&&(c(b,m)===!1||(e(b,m),f(b),y(b,m)===!1)))&&(b.nodeName!=="TEXTAREA"?Lt(b,m):ft.TEXTAREA(b,m))}function Lt(b,m){var g=m.firstChild,w=b.firstChild,D,F,Y,ge,B;e:for(;g;){for(ge=g.nextSibling,D=o(g);w;){if(Y=w.nextSibling,g.isSameNode&&g.isSameNode(w)){g=ge,w=Y;continue e}F=o(w);var ve=w.nodeType,J=void 0;if(ve===g.nodeType&&(ve===se?(D?D!==F&&((B=p[D])?Y===B?J=!1:(b.insertBefore(B,w),F?P(F):d(w,b,!0),w=B):J=!1):F&&(J=!1),J=J!==!1&&ke(w,g),J&&fe(w,g)):(ve===pt||ve==gt)&&(J=!0,w.nodeValue!==g.nodeValue&&(w.nodeValue=g.nodeValue))),J){g=ge,w=Y;continue e}F?P(F):d(w,b,!0),w=Y}if(D&&(B=p[D])&&ke(B,g))b.appendChild(B),fe(B,g);else{var xe=a(g);xe!==!1&&(xe&&(g=xe),g.actualize&&(g=g.actualize(b.ownerDocument||_)),b.appendChild(g),ce(g))}g=ge,w=Y}ue(b,w,F);var Ye=ft[b.nodeName];Ye&&Ye(b,m)}var C=i,pe=C.nodeType,Ge=s.nodeType;if(!S){if(pe===se)Ge===se?ke(i,s)||(v(i),C=gi(i,pi(s.nodeName,s.namespaceURI))):C=s;else if(pe===pt||pe===gt){if(Ge===pe)return C.nodeValue!==s.nodeValue&&(C.nodeValue=s.nodeValue),C;C=s}}if(C===s)v(i);else{if(s.isSameNode&&s.isSameNode(C))return;if(fe(C,s,S),A)for(var Re=0,xt=A.length;Re<xt;Re++){var Le=p[A[Re]];Le&&d(Le,Le.parentNode,!1)}}return!S&&C!==i&&i.parentNode&&(C.actualize&&(C=C.actualize(i.ownerDocument||_)),i.parentNode.replaceChild(C,i)),C}}var yi=bi(oi),vt=yi,Ae=class{static patchEl(e,t,i){vt(e,t,{childrenOnly:!1,onBeforeElUpdated:(s,n)=>{if(i&&i.isSameNode(s)&&l.isFormInput(s))return l.mergeFocusedInput(s,n),!1}})}constructor(e,t,i,s,n){this.view=e,this.liveSocket=e.liveSocket,this.container=t,this.id=i,this.rootID=e.root.id,this.html=s,this.targetCID=n,this.cidPatch=X(this.targetCID),this.callbacks={beforeadded:[],beforeupdated:[],beforephxChildAdded:[],afteradded:[],afterupdated:[],afterdiscarded:[],afterphxChildAdded:[],aftertransitionsDiscarded:[]}}before(e,t){this.callbacks[`before${e}`].push(t)}after(e,t){this.callbacks[`after${e}`].push(t)}trackBefore(e,...t){this.callbacks[`before${e}`].forEach(i=>i(...t))}trackAfter(e,...t){this.callbacks[`after${e}`].forEach(i=>i(...t))}markPrunableContentForRemoval(){l.all(this.container,"[phx-update=append] > *, [phx-update=prepend] > *",e=>{e.setAttribute(Ze,"")})}perform(){let{view:e,liveSocket:t,container:i,html:s}=this,n=this.isCIDPatch()?this.targetCIDContainer(s):i;if(this.isCIDPatch()&&!n)return;let r=t.getActiveElement(),{selectionStart:o,selectionEnd:a}=r&&l.hasSelectionRange(r)?r:{},h=t.binding(Xe),c=t.binding(Je),f=t.binding(Ve),u=t.binding(jt),v=t.binding("remove"),y=[],S=[],p=[],A=[],P=null,G=t.time("premorph container prep",()=>this.buildDiffHTML(i,s,h,n));return this.trackBefore("added",i),this.trackBefore("updated",i,i),t.time("morphdom",()=>{vt(n,G,{childrenOnly:n.getAttribute(L)===null,getNodeKey:d=>l.isPhxDestroyed(d)?null:d.id,onBeforeNodeAdded:d=>(this.trackBefore("added",d),d),onNodeAdded:d=>{d instanceof HTMLImageElement&&d.srcset?d.srcset=d.srcset:d instanceof HTMLVideoElement&&d.autoplay&&d.play(),l.isNowTriggerFormExternal(d,u)&&(P=d),l.discardError(n,d,c),(l.isPhxChild(d)&&e.ownsElement(d)||l.isPhxSticky(d)&&e.ownsElement(d.parentNode))&&this.trackAfter("phxChildAdded",d),y.push(d)},onNodeDiscarded:d=>{(l.isPhxChild(d)||l.isPhxSticky(d))&&t.destroyViewByEl(d),this.trackAfter("discarded",d)},onBeforeNodeDiscarded:d=>d.getAttribute&&d.getAttribute(Ze)!==null?!0:d.parentNode!==null&&l.isPhxUpdate(d.parentNode,h,["append","prepend"])&&d.id?!1:d.getAttribute&&d.getAttribute(v)?(A.push(d),!1):!this.skipCIDSibling(d),onElUpdated:d=>{l.isNowTriggerFormExternal(d,u)&&(P=d),S.push(d)},onBeforeElUpdated:(d,k)=>{if(l.cleanChildNodes(k,h),this.skipCIDSibling(k)||l.isPhxSticky(d))return!1;if(l.isIgnored(d,h))return this.trackBefore("updated",d,k),l.mergeAttrs(d,k,{isIgnored:!0}),S.push(d),l.applyStickyOperations(d),!1;if(d.type==="number"&&d.validity&&d.validity.badInput)return!1;if(!l.syncPendingRef(d,k,f))return l.isUploadInput(d)&&(this.trackBefore("updated",d,k),S.push(d)),l.applyStickyOperations(d),!1;if(l.isPhxChild(k)){let ue=d.getAttribute(W);return l.mergeAttrs(d,k,{exclude:[re]}),ue!==""&&d.setAttribute(W,ue),d.setAttribute(ae,this.rootID),l.applyStickyOperations(d),!1}return l.copyPrivates(k,d),l.discardError(n,k,c),r&&d.isSameNode(r)&&l.isFormInput(d)?(this.trackBefore("updated",d,k),l.mergeFocusedInput(d,k),l.syncAttrsToProps(d),S.push(d),l.applyStickyOperations(d),!1):(l.isPhxUpdate(k,h,["append","prepend"])&&p.push(new ri(d,k,k.getAttribute(h))),l.syncAttrsToProps(k),l.applyStickyOperations(k),this.trackBefore("updated",d,k),!0)}})}),t.isDebugEnabled()&&Qt(),p.length>0&&t.time("post-morph append/prepend restoration",()=>{p.forEach(d=>d.perform())}),t.silenceEvents(()=>l.restoreFocus(r,o,a)),l.dispatchEvent(document,"phx:update"),y.forEach(d=>this.trackAfter("added",d)),S.forEach(d=>this.trackAfter("updated",d)),A.length>0&&(t.transitionRemoves(A),t.requestDOMUpdate(()=>{A.forEach(d=>{let k=l.firstPhxChild(d);k&&t.destroyViewByEl(k),d.remove()}),this.trackAfter("transitionsDiscarded",A)})),P&&(t.disconnect(),P.submit()),!0}isCIDPatch(){return this.cidPatch}skipCIDSibling(e){return e.nodeType===Node.ELEMENT_NODE&&e.getAttribute(Be)!==null}targetCIDContainer(e){if(!this.isCIDPatch())return;let[t,...i]=l.findComponentNodeList(this.container,this.targetCID);return i.length===0&&l.childNodeLength(e)===1?t:t&&t.parentNode}buildDiffHTML(e,t,i,s){let n=this.isCIDPatch(),r=n&&s.getAttribute(L)===this.targetCID.toString();if(!n||r)return t;{let o=null,a=document.createElement("template");o=l.cloneNode(s);let[h,...c]=l.findComponentNodeList(o,this.targetCID);return a.innerHTML=t,c.forEach(f=>f.remove()),Array.from(o.childNodes).forEach(f=>{f.id&&f.nodeType===Node.ELEMENT_NODE&&f.getAttribute(L)!==this.targetCID.toString()&&(f.setAttribute(Be,""),f.innerHTML="")}),Array.from(a.content.childNodes).forEach(f=>o.insertBefore(f,h)),h.remove(),o.outerHTML}}},mt=class{static extract(e){let{[lt]:t,[ht]:i,[dt]:s}=e;return delete e[lt],delete e[ht],delete e[dt],{diff:e,title:s,reply:t||null,events:i||[]}}constructor(e,t){this.viewId=e,this.rendered={},this.mergeDiff(t)}parentViewId(){return this.viewId}toString(e){return this.recursiveToString(this.rendered,this.rendered[R],e)}recursiveToString(e,t=e[R],i){i=i?new Set(i):null;let s={buffer:"",components:t,onlyCids:i};return this.toOutputBuffer(e,null,s),s.buffer}componentCIDs(e){return Object.keys(e[R]||{}).map(t=>parseInt(t))}isComponentOnlyDiff(e){return e[R]?Object.keys(e).length===1:!1}getComponent(e,t){return e[R][t]}mergeDiff(e){let t=e[R],i={};if(delete e[R],this.rendered=this.mutableMerge(this.rendered,e),this.rendered[R]=this.rendered[R]||{},t){let s=this.rendered[R];for(let n in t)t[n]=this.cachedFindComponent(n,t[n],s,t,i);for(let n in t)s[n]=t[n];e[R]=t}}cachedFindComponent(e,t,i,s,n){if(n[e])return n[e];{let r,o,a=t[H];if(X(a)){let h;a>0?h=this.cachedFindComponent(a,s[a],i,s,n):h=i[-a],o=h[H],r=this.cloneMerge(h,t),r[H]=o}else r=t[H]!==void 0?t:this.cloneMerge(i[e]||{},t);return n[e]=r,r}}mutableMerge(e,t){return t[H]!==void 0?t:(this.doMutableMerge(e,t),e)}doMutableMerge(e,t){for(let i in t){let s=t[i],n=e[i];ie(s)&&s[H]===void 0&&ie(n)?this.doMutableMerge(n,s):e[i]=s}}cloneMerge(e,t){let i={...e,...t};for(let s in i){let n=t[s],r=e[s];ie(n)&&n[H]===void 0&&ie(r)&&(i[s]=this.cloneMerge(r,n))}return i}componentToString(e){return this.recursiveCIDToString(this.rendered[R],e)}pruneCIDs(e){e.forEach(t=>delete this.rendered[R][t])}get(){return this.rendered}isNewFingerprint(e={}){return!!e[H]}templateStatic(e,t){return typeof e=="number"?t[e]:e}toOutputBuffer(e,t,i){if(e[at])return this.comprehensionToBuffer(e,t,i);let{[H]:s}=e;s=this.templateStatic(s,t),i.buffer+=s[0];for(let n=1;n<s.length;n++)this.dynamicToBuffer(e[n-1],t,i),i.buffer+=s[n]}comprehensionToBuffer(e,t,i){let{[at]:s,[H]:n}=e;n=this.templateStatic(n,t);let r=t||e[Gt];for(let o=0;o<s.length;o++){let a=s[o];i.buffer+=n[0];for(let h=1;h<n.length;h++)this.dynamicToBuffer(a[h-1],r,i),i.buffer+=n[h]}}dynamicToBuffer(e,t,i){typeof e=="number"?i.buffer+=this.recursiveCIDToString(i.components,e,i.onlyCids):ie(e)?this.toOutputBuffer(e,t,i):i.buffer+=e}recursiveCIDToString(e,t,i){let s=e[t]||T(`no component for CID ${t}`,e),n=document.createElement("template");n.innerHTML=this.recursiveToString(s,e,i);let r=n.content,o=i&&!i.has(t),[a,h]=Array.from(r.childNodes).reduce(([c,f],u,v)=>u.nodeType===Node.ELEMENT_NODE?u.getAttribute(L)?[c,!0]:(u.setAttribute(L,t),u.id||(u.id=`${this.parentViewId()}-${t}-${v}`),o&&(u.setAttribute(Be,""),u.innerHTML=""),[!0,f]):u.nodeValue.trim()!==""?(T(`only HTML element tags are allowed at the root of components.
got: "${u.nodeValue.trim()}"
within:
`,n.innerHTML.trim()),u.replaceWith(this.createSpan(u.nodeValue,t)),[!0,f]):(u.remove(),[c,f]),[!1,!1]);return!a&&!h?(T(`expected at least one HTML element tag inside a component, but the component is empty:
`,n.innerHTML.trim()),this.createSpan("",t).outerHTML):(!a&&h&&T("expected at least one HTML element tag directly inside a component, but only subcomponents were found. A component must render at least one HTML tag directly inside itself.",n.innerHTML.trim()),n.innerHTML)}createSpan(e,t){let i=document.createElement("span");return i.innerText=e,i.setAttribute(L,t),i}},Si=1,ne=class{static makeID(){return Si++}static elementID(e){return e.phxHookId}constructor(e,t,i){this.__view=e,this.liveSocket=e.liveSocket,this.__callbacks=i,this.__listeners=new Set,this.__isDisconnected=!1,this.el=t,this.el.phxHookId=this.constructor.makeID();for(let s in this.__callbacks)this[s]=this.__callbacks[s]}__mounted(){this.mounted&&this.mounted()}__updated(){this.updated&&this.updated()}__beforeUpdate(){this.beforeUpdate&&this.beforeUpdate()}__destroyed(){this.destroyed&&this.destroyed()}__reconnected(){this.__isDisconnected&&(this.__isDisconnected=!1,this.reconnected&&this.reconnected())}__disconnected(){this.__isDisconnected=!0,this.disconnected&&this.disconnected()}pushEvent(e,t={},i=function(){}){return this.__view.pushHookEvent(null,e,t,i)}pushEventTo(e,t,i={},s=function(){}){return this.__view.withinTargets(e,(n,r)=>n.pushHookEvent(r,t,i,s))}handleEvent(e,t){let i=(s,n)=>n?e:t(s.detail);return window.addEventListener(`phx:${e}`,i),this.__listeners.add(i),i}removeHandleEvent(e){let t=e(null,!0);window.removeEventListener(`phx:${t}`,e),this.__listeners.delete(e)}upload(e,t){return this.__view.dispatchUploads(e,t)}uploadTo(e,t,i){return this.__view.withinTargets(e,s=>s.dispatchUploads(t,i))}__cleanup__(){this.__listeners.forEach(e=>this.removeHandleEvent(e))}},wi={exec(e,t,i,s,n){let[r,o]=n||[null,{}];(t.charAt(0)==="["?JSON.parse(t):[[r,o]]).forEach(([h,c])=>{h===r&&o.data&&(c.data=Object.assign(c.data||{},o.data)),this.filterToEls(s,c).forEach(f=>{this[`exec_${h}`](e,t,i,s,f,c)})})},isVisible(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length>0)},exec_dispatch(e,t,i,s,n,{to:r,event:o,detail:a,bubbles:h}){a=a||{},a.dispatcher=s,l.dispatchEvent(n,o,{detail:a,bubbles:h})},exec_push(e,t,i,s,n,r){if(!i.isConnected())return;let{event:o,data:a,target:h,page_loading:c,loading:f,value:u,dispatcher:v}=r,y={loading:f,value:u,target:h,page_loading:!!c},S=e==="change"&&v?v:s,p=h||S.getAttribute(i.binding("target"))||S;i.withinTargets(p,(A,P)=>{if(e==="change"){let{newCid:G,_target:d,callback:k}=r;d=d||(s instanceof HTMLInputElement?s.name:void 0),d&&(y._target=d),A.pushInput(s,P,G,o||t,y,k)}else e==="submit"?A.submitForm(s,P,o||t,y):A.pushEvent(e,s,P,o||t,a,y)})},exec_add_class(e,t,i,s,n,{names:r,transition:o,time:a}){this.addOrRemoveClasses(n,r,[],o,a,i)},exec_remove_class(e,t,i,s,n,{names:r,transition:o,time:a}){this.addOrRemoveClasses(n,[],r,o,a,i)},exec_transition(e,t,i,s,n,{time:r,transition:o}){let[a,h,c]=o,f=()=>this.addOrRemoveClasses(n,a.concat(h),[]),u=()=>this.addOrRemoveClasses(n,c,a.concat(h));i.transition(r,f,u)},exec_toggle(e,t,i,s,n,{display:r,ins:o,outs:a,time:h}){this.toggle(e,i,n,r,o,a,h)},exec_show(e,t,i,s,n,{display:r,transition:o,time:a}){this.show(e,i,n,r,o,a)},exec_hide(e,t,i,s,n,{display:r,transition:o,time:a}){this.hide(e,i,n,r,o,a)},exec_set_attr(e,t,i,s,n,{attr:[r,o]}){this.setOrRemoveAttrs(n,[[r,o]],[])},exec_remove_attr(e,t,i,s,n,{attr:r}){this.setOrRemoveAttrs(n,[],[r])},show(e,t,i,s,n,r){this.isVisible(i)||this.toggle(e,t,i,s,n,null,r)},hide(e,t,i,s,n,r){this.isVisible(i)&&this.toggle(e,t,i,s,null,n,r)},toggle(e,t,i,s,n,r,o){let[a,h,c]=n||[[],[],[]],[f,u,v]=r||[[],[],[]];if(a.length>0||f.length>0)if(this.isVisible(i)){let y=()=>{this.addOrRemoveClasses(i,u,a.concat(h).concat(c)),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(i,f,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(i,v,u))})};i.dispatchEvent(new Event("phx:hide-start")),t.transition(o,y,()=>{this.addOrRemoveClasses(i,[],f.concat(v)),l.putSticky(i,"toggle",S=>S.style.display="none"),i.dispatchEvent(new Event("phx:hide-end"))})}else{if(e==="remove")return;let y=()=>{this.addOrRemoveClasses(i,h,f.concat(u).concat(v)),l.putSticky(i,"toggle",S=>S.style.display=s||"block"),window.requestAnimationFrame(()=>{this.addOrRemoveClasses(i,a,[]),window.requestAnimationFrame(()=>this.addOrRemoveClasses(i,c,h))})};i.dispatchEvent(new Event("phx:show-start")),t.transition(o,y,()=>{this.addOrRemoveClasses(i,[],a.concat(c)),i.dispatchEvent(new Event("phx:show-end"))})}else this.isVisible(i)?window.requestAnimationFrame(()=>{i.dispatchEvent(new Event("phx:hide-start")),l.putSticky(i,"toggle",y=>y.style.display="none"),i.dispatchEvent(new Event("phx:hide-end"))}):window.requestAnimationFrame(()=>{i.dispatchEvent(new Event("phx:show-start")),l.putSticky(i,"toggle",y=>y.style.display=s||"block"),i.dispatchEvent(new Event("phx:show-end"))})},addOrRemoveClasses(e,t,i,s,n,r){let[o,a,h]=s||[[],[],[]];if(o.length>0){let c=()=>this.addOrRemoveClasses(e,a.concat(o),[]),f=()=>this.addOrRemoveClasses(e,t.concat(h),i.concat(o).concat(a));return r.transition(n,c,f)}window.requestAnimationFrame(()=>{let[c,f]=l.getSticky(e,"classes",[[],[]]),u=t.filter(p=>c.indexOf(p)<0&&!e.classList.contains(p)),v=i.filter(p=>f.indexOf(p)<0&&e.classList.contains(p)),y=c.filter(p=>i.indexOf(p)<0).concat(u),S=f.filter(p=>t.indexOf(p)<0).concat(v);l.putSticky(e,"classes",p=>(p.classList.remove(...S),p.classList.add(...y),[y,S]))})},setOrRemoveAttrs(e,t,i){let[s,n]=l.getSticky(e,"attrs",[[],[]]),r=t.map(([h,c])=>h).concat(i),o=s.filter(([h,c])=>!r.includes(h)).concat(t),a=n.filter(h=>!r.includes(h)).concat(i);l.putSticky(e,"attrs",h=>(a.forEach(c=>h.removeAttribute(c)),o.forEach(([c,f])=>h.setAttribute(c,f)),[o,a]))},hasAllClasses(e,t){return t.every(i=>e.classList.contains(i))},isToggledOut(e,t){return!this.isVisible(e)||this.hasAllClasses(e,t)},filterToEls(e,{to:t}){return t?l.all(document,t):[e]}},N=wi,Ce=(e,t,i=[])=>{let s=new FormData(e),n=[];s.forEach((o,a,h)=>{o instanceof File&&n.push(a)}),n.forEach(o=>s.delete(o));let r=new URLSearchParams;for(let[o,a]of s.entries())(i.length===0||i.indexOf(o)>=0)&&r.append(o,a);for(let o in t)r.append(o,t[o]);return r.toString()},Et=class{constructor(e,t,i,s){this.liveSocket=t,this.flash=s,this.parent=i,this.root=i?i.root:this,this.el=e,this.id=this.el.id,this.ref=0,this.childJoins=0,this.loaderTimer=null,this.pendingDiffs=[],this.pruningCIDs=[],this.redirect=!1,this.href=null,this.joinCount=this.parent?this.parent.joinCount-1:0,this.joinPending=!0,this.destroyed=!1,this.joinCallback=function(n){n&&n()},this.stopCallback=function(){},this.pendingJoinOps=this.parent?null:[],this.viewHooks={},this.uploaders={},this.formSubmits=[],this.children=this.parent?null:{},this.root.children[this.id]={},this.channel=this.liveSocket.channel(`lv:${this.id}`,()=>({redirect:this.redirect?this.href:void 0,url:this.redirect?void 0:this.href||void 0,params:this.connectParams(),session:this.getSession(),static:this.getStatic(),flash:this.flash})),this.showLoader(this.liveSocket.loaderTimeout),this.bindChannel()}setHref(e){this.href=e}setRedirect(e){this.redirect=!0,this.href=e}isMain(){return this.el.getAttribute(qe)!==null}connectParams(){let e=this.liveSocket.params(this.el),t=l.all(document,`[${this.binding(Nt)}]`).map(i=>i.src||i.href).filter(i=>typeof i=="string");return t.length>0&&(e._track_static=t),e._mounts=this.joinCount,e}isConnected(){return this.channel.canPush()}getSession(){return this.el.getAttribute(W)}getStatic(){let e=this.el.getAttribute(re);return e===""?null:e}destroy(e=function(){}){this.destroyAllChildren(),this.destroyed=!0,delete this.root.children[this.id],this.parent&&delete this.root.children[this.parent.id][this.id],clearTimeout(this.loaderTimer);let t=()=>{e();for(let i in this.viewHooks)this.destroyHook(this.viewHooks[i])};l.markPhxChildDestroyed(this.el),this.log("destroyed",()=>["the child has been removed from the parent"]),this.channel.leave().receive("ok",t).receive("error",t).receive("timeout",t)}setContainerClasses(...e){this.el.classList.remove(tt,Ie,st),this.el.classList.add(...e)}showLoader(e){if(clearTimeout(this.loaderTimer),e)this.loaderTimer=setTimeout(()=>this.showLoader(),e);else{for(let t in this.viewHooks)this.viewHooks[t].__disconnected();this.setContainerClasses(Ie)}}hideLoader(){clearTimeout(this.loaderTimer),this.setContainerClasses(tt)}triggerReconnected(){for(let e in this.viewHooks)this.viewHooks[e].__reconnected()}log(e,t){this.liveSocket.log(this,e,t)}transition(e,t,i=function(){}){this.liveSocket.transition(e,t,i)}withinTargets(e,t){if(e instanceof HTMLElement||e instanceof SVGElement)return this.liveSocket.owner(e,i=>t(i,e));if(X(e))l.findComponentNodeList(this.el,e).length===0?T(`no component found matching phx-target of ${e}`):t(this,parseInt(e));else{let i=Array.from(document.querySelectorAll(e));i.length===0&&T(`nothing found matching the phx-target selector "${e}"`),i.forEach(s=>this.liveSocket.owner(s,n=>t(n,s)))}}applyDiff(e,t,i){this.log(e,()=>["",Ee(t)]);let{diff:s,reply:n,events:r,title:o}=mt.extract(t);return o&&l.putTitle(o),i({diff:s,reply:n,events:r}),n}onJoin(e){let{rendered:t,container:i}=e;if(i){let[s,n]=i;this.el=l.replaceRootContainer(this.el,s,n)}this.childJoins=0,this.joinPending=!0,this.flash=null,V.dropLocal(this.liveSocket.localStorage,window.location.pathname,bt),this.applyDiff("mount",t,({diff:s,events:n})=>{this.rendered=new mt(this.id,s);let r=this.renderContainer(null,"join");this.dropPendingRefs();let o=this.formsForRecovery(r);this.joinCount++,o.length>0?o.forEach(([a,h,c],f)=>{this.pushFormRecovery(a,c,u=>{f===o.length-1&&this.onJoinComplete(u,r,n)})}):this.onJoinComplete(e,r,n)})}dropPendingRefs(){l.all(document,`[${z}="${this.id}"][${M}]`,e=>{e.removeAttribute(M),e.removeAttribute(z)})}onJoinComplete({live_patch:e},t,i){if(this.joinCount>1||this.parent&&!this.parent.isJoinPending())return this.applyJoinPatch(e,t,i);l.findPhxChildrenInFragment(t,this.id).filter(n=>{let r=n.id&&this.el.querySelector(`[id="${n.id}"]`),o=r&&r.getAttribute(re);return o&&n.setAttribute(re,o),this.joinChild(n)}).length===0?this.parent?(this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(e,t,i)]),this.parent.ackJoin(this)):(this.onAllChildJoinsComplete(),this.applyJoinPatch(e,t,i)):this.root.pendingJoinOps.push([this,()=>this.applyJoinPatch(e,t,i)])}attachTrueDocEl(){this.el=l.byId(this.id),this.el.setAttribute(ae,this.root.id)}applyJoinPatch(e,t,i){this.attachTrueDocEl();let s=new Ae(this,this.el,this.id,t,null);if(s.markPrunableContentForRemoval(),this.performPatch(s,!1),this.joinNewChildren(),l.all(this.el,`[${this.binding(ee)}], [data-phx-${ee}]`,n=>{let r=this.addHook(n);r&&r.__mounted()}),this.joinPending=!1,this.liveSocket.dispatchEvents(i),this.applyPendingUpdates(),e){let{kind:n,to:r}=e;this.liveSocket.historyPatch(r,n)}this.hideLoader(),this.joinCount>1&&this.triggerReconnected(),this.stopCallback()}triggerBeforeUpdateHook(e,t){this.liveSocket.triggerDOM("onBeforeElUpdated",[e,t]);let i=this.getHook(e),s=i&&l.isIgnored(e,this.binding(Xe));if(i&&!e.isEqualNode(t)&&!(s&&ei(e.dataset,t.dataset)))return i.__beforeUpdate(),i}performPatch(e,t){let i=[],s=!1,n=new Set;return e.after("added",r=>{this.liveSocket.triggerDOM("onNodeAdded",[r]);let o=this.addHook(r);o&&o.__mounted()}),e.after("phxChildAdded",r=>{l.isPhxSticky(r)?this.liveSocket.joinRootViews():s=!0}),e.before("updated",(r,o)=>{this.triggerBeforeUpdateHook(r,o)&&n.add(r.id)}),e.after("updated",r=>{n.has(r.id)&&this.getHook(r).__updated()}),e.after("discarded",r=>{r.nodeType===Node.ELEMENT_NODE&&i.push(r)}),e.after("transitionsDiscarded",r=>this.afterElementsRemoved(r,t)),e.perform(),this.afterElementsRemoved(i,t),s}afterElementsRemoved(e,t){let i=[];e.forEach(s=>{let n=l.all(s,`[${L}]`),r=l.all(s,`[${this.binding(ee)}]`);n.concat(s).forEach(o=>{let a=this.componentID(o);X(a)&&i.indexOf(a)===-1&&i.push(a)}),r.concat(s).forEach(o=>{let a=this.getHook(o);a&&this.destroyHook(a)})}),t&&this.maybePushComponentsDestroyed(i)}joinNewChildren(){l.findPhxChildren(this.el,this.id).forEach(e=>this.joinChild(e))}getChildById(e){return this.root.children[this.id][e]}getDescendentByEl(e){return e.id===this.id?this:this.children[e.getAttribute(Q)][e.id]}destroyDescendent(e){for(let t in this.root.children)for(let i in this.root.children[t])if(i===e)return this.root.children[t][i].destroy()}joinChild(e){if(!this.getChildById(e.id)){let i=new Et(e,this.liveSocket,this);return this.root.children[this.id][i.id]=i,i.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.joinCallback(()=>{this.pendingJoinOps.forEach(([e,t])=>{e.isDestroyed()||t()}),this.pendingJoinOps=[]})}update(e,t){if(this.isJoinPending()||this.liveSocket.hasPendingLink()&&!l.isPhxSticky(this.el))return this.pendingDiffs.push({diff:e,events:t});this.rendered.mergeDiff(e);let i=!1;this.rendered.isComponentOnlyDiff(e)?this.liveSocket.time("component patch complete",()=>{l.findParentCIDs(this.el,this.rendered.componentCIDs(e)).forEach(n=>{this.componentPatch(this.rendered.getComponent(e,n),n)&&(i=!0)})}):ct(e)||this.liveSocket.time("full patch complete",()=>{let s=this.renderContainer(e,"update"),n=new Ae(this,this.el,this.id,s,null);i=this.performPatch(n,!0)}),this.liveSocket.dispatchEvents(t),i&&this.joinNewChildren()}renderContainer(e,t){return this.liveSocket.time(`toString diff (${t})`,()=>{let i=this.el.tagName,s=e?this.rendered.componentCIDs(e).concat(this.pruningCIDs):null,n=this.rendered.toString(s);return`<${i}>${n}</${i}>`})}componentPatch(e,t){if(ct(e))return!1;let i=this.rendered.componentToString(t),s=new Ae(this,this.el,this.id,i,t);return this.performPatch(s,!0)}getHook(e){return this.viewHooks[ne.elementID(e)]}addHook(e){if(ne.elementID(e)||!e.getAttribute)return;let t=e.getAttribute(`data-phx-${ee}`)||e.getAttribute(this.binding(ee));if(t&&!this.ownsElement(e))return;let i=this.liveSocket.getHookCallbacks(t);if(i){e.id||T(`no DOM ID for hook "${t}". Hooks require a unique ID on each element.`,e);let s=new ne(this,e,i);return this.viewHooks[ne.elementID(s.el)]=s,s}else t!==null&&T(`unknown hook found for "${t}"`,e)}destroyHook(e){e.__destroyed(),e.__cleanup__(),delete this.viewHooks[ne.elementID(e.el)]}applyPendingUpdates(){this.pendingDiffs.forEach(({diff:e,events:t})=>this.update(e,t)),this.pendingDiffs=[]}onChannel(e,t){this.liveSocket.onChannel(this.channel,e,i=>{this.isJoinPending()?this.root.pendingJoinOps.push([this,()=>t(i)]):this.liveSocket.requestDOMUpdate(()=>t(i))})}bindChannel(){this.liveSocket.onChannel(this.channel,"diff",e=>{this.liveSocket.requestDOMUpdate(()=>{this.applyDiff("update",e,({diff:t,events:i})=>this.update(t,i))})}),this.onChannel("redirect",({to:e,flash:t})=>this.onRedirect({to:e,flash:t})),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(){for(let e in this.root.children[this.id])this.getChildById(e).destroy()}onLiveRedirect(e){let{to:t,kind:i,flash:s}=e,n=this.expandURL(t);this.liveSocket.historyRedirect(n,i,s)}onLivePatch(e){let{to:t,kind:i}=e;this.href=this.expandURL(t),this.liveSocket.historyPatch(t,i)}expandURL(e){return e.startsWith("/")?`${window.location.protocol}//${window.location.host}${e}`:e}onRedirect({to:e,flash:t}){this.liveSocket.redirect(e,t)}isDestroyed(){return this.destroyed}join(e){this.isMain()&&(this.stopCallback=this.liveSocket.withPageLoading({to:this.href,kind:"initial"})),this.joinCallback=t=>{t=t||function(){},e?e(this.joinCount,t):t()},this.liveSocket.wrapPush(this,{timeout:!1},()=>this.channel.join().receive("ok",t=>{this.isDestroyed()||this.liveSocket.requestDOMUpdate(()=>this.onJoin(t))}).receive("error",t=>!this.isDestroyed()&&this.onJoinError(t)).receive("timeout",()=>!this.isDestroyed()&&this.onJoinError({reason:"timeout"})))}onJoinError(e){if(e.reason==="unauthorized"||e.reason==="stale")return this.log("error",()=>["unauthorized live_redirect. Falling back to page request",e]),this.onRedirect({to:this.href});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);this.log("error",()=>["unable to join",e]),this.liveSocket.isConnected()&&this.liveSocket.reloadWithJitter(this)}onClose(e){if(!this.isDestroyed()){if(this.liveSocket.hasPendingLink()&&e!=="leave")return this.liveSocket.reloadWithJitter(this);this.destroyAllChildren(),this.liveSocket.dropActiveElement(this),document.activeElement&&document.activeElement.blur(),this.liveSocket.isUnloaded()&&this.showLoader(Wt)}}onError(e){this.onClose(e),this.liveSocket.isConnected()&&this.log("error",()=>["view crashed",e]),this.liveSocket.isUnloaded()||this.displayError()}displayError(){this.isMain()&&l.dispatchEvent(window,"phx:page-loading-start",{detail:{to:this.href,kind:"error"}}),this.showLoader(),this.setContainerClasses(Ie,st)}pushWithReply(e,t,i,s=function(){}){if(!this.isConnected())return;let[n,[r],o]=e?e():[null,[],{}],a=function(){};return(o.page_loading||r&&r.getAttribute(this.binding(et))!==null)&&(a=this.liveSocket.withPageLoading({kind:"element",target:r})),typeof i.cid!="number"&&delete i.cid,this.liveSocket.wrapPush(this,{timeout:!0},()=>this.channel.push(t,i,zt).receive("ok",h=>{n!==null&&this.undoRefs(n);let c=f=>{h.redirect&&this.onRedirect(h.redirect),h.live_patch&&this.onLivePatch(h.live_patch),h.live_redirect&&this.onLiveRedirect(h.live_redirect),a(),s(h,f)};h.diff?this.liveSocket.requestDOMUpdate(()=>{let f=this.applyDiff("update",h.diff,({diff:u,events:v})=>{this.update(u,v)});c(f)}):c(null)}))}undoRefs(e){l.all(document,`[${z}="${this.id}"][${M}="${e}"]`,t=>{let i=t.getAttribute(me);t.removeAttribute(M),t.removeAttribute(z),t.getAttribute(Oe)!==null&&(t.readOnly=!1,t.removeAttribute(Oe)),i!==null&&(t.disabled=i==="true",t.removeAttribute(me)),yt.forEach(r=>l.removeClass(t,r));let s=t.getAttribute(be);s!==null&&(t.innerText=s,t.removeAttribute(be));let n=l.private(t,M);if(n){let r=this.triggerBeforeUpdateHook(t,n);Ae.patchEl(t,n,this.liveSocket.getActiveElement()),r&&r.__updated(),l.deletePrivate(t,M)}})}putRef(e,t,i={}){let s=this.ref++,n=this.binding(Ve);return i.loading&&(e=e.concat(l.all(document,i.loading))),e.forEach(r=>{r.classList.add(`phx-${t}-loading`),r.setAttribute(M,s),r.setAttribute(z,this.el.id);let o=r.getAttribute(n);o!==null&&(r.getAttribute(be)||r.setAttribute(be,r.innerText),o!==""&&(r.innerText=o),r.setAttribute("disabled",""))}),[s,e,i]}componentID(e){let t=e.getAttribute&&e.getAttribute(L);return t?parseInt(t):null}targetComponentID(e,t,i={}){if(X(t))return t;let s=e.getAttribute(this.binding("target"));return X(s)?parseInt(s):t&&(s!==null||i.target)?this.closestComponentID(t):null}closestComponentID(e){return X(e)?e:e?j(e.closest(`[${L}]`),t=>this.ownsElement(t)&&this.componentID(t)):null}pushHookEvent(e,t,i,s){if(!this.isConnected())return this.log("hook",()=>["unable to push hook event. LiveView not connected",t,i]),!1;let[n,r,o]=this.putRef([],"hook");return this.pushWithReply(()=>[n,r,o],"event",{type:"hook",event:t,value:i,cid:this.closestComponentID(e)},(a,h)=>s(h,n)),n}extractMeta(e,t,i){let s=this.binding("value-");for(let n=0;n<e.attributes.length;n++){t||(t={});let r=e.attributes[n].name;r.startsWith(s)&&(t[r.replace(s,"")]=e.getAttribute(r))}if(e.value!==void 0&&(t||(t={}),t.value=e.value,e.tagName==="INPUT"&&kt.indexOf(e.type)>=0&&!e.checked&&delete t.value),i){t||(t={});for(let n in i)t[n]=i[n]}return t}pushEvent(e,t,i,s,n,r={}){this.pushWithReply(()=>this.putRef([t],e,r),"event",{type:e,event:s,value:this.extractMeta(t,n,r.value),cid:this.targetComponentID(t,i,r)})}pushFileProgress(e,t,i,s=function(){}){this.liveSocket.withinOwners(e.form,(n,r)=>{n.pushWithReply(null,"progress",{event:e.getAttribute(n.binding(Vt)),ref:e.getAttribute(K),entry_ref:t,progress:i,cid:n.targetComponentID(e.form,r)},s)})}pushInput(e,t,i,s,n,r){let o,a=X(i)?i:this.targetComponentID(e.form,t),h=()=>this.putRef([e,e.form],"change",n),c;e.getAttribute(this.binding("change"))?c=Ce(e.form,{_target:n._target},[e.name]):c=Ce(e.form,{_target:n._target}),l.isUploadInput(e)&&e.files&&e.files.length>0&&E.trackFiles(e,Array.from(e.files)),o=E.serializeUploads(e);let f={type:"form",event:s,value:c,uploads:o,cid:a};this.pushWithReply(h,"event",f,u=>{if(l.showError(e,this.liveSocket.binding(Je)),l.isUploadInput(e)&&e.getAttribute("data-phx-auto-upload")!==null){if(E.filesAwaitingPreflight(e).length>0){let[v,y]=h();this.uploadFiles(e.form,t,v,a,S=>{r&&r(u),this.triggerAwaitingSubmit(e.form)})}}else r&&r(u)})}triggerAwaitingSubmit(e){let t=this.getScheduledSubmit(e);if(t){let[i,s,n,r]=t;this.cancelSubmit(e),r()}}getScheduledSubmit(e){return this.formSubmits.find(([t,i,s,n])=>t.isSameNode(e))}scheduleSubmit(e,t,i,s){if(this.getScheduledSubmit(e))return!0;this.formSubmits.push([e,t,i,s])}cancelSubmit(e){this.formSubmits=this.formSubmits.filter(([t,i,s])=>t.isSameNode(e)?(this.undoRefs(i),!1):!0)}pushFormSubmit(e,t,i,s,n){let r=u=>!(oe(u,`${this.binding(Xe)}=ignore`,u.form)||oe(u,"data-phx-update=ignore",u.form)),o=u=>u.hasAttribute(this.binding(Ve)),a=u=>u.tagName=="BUTTON",h=u=>["INPUT","TEXTAREA","SELECT"].includes(u.tagName),c=()=>{let u=Array.from(e.elements),v=u.filter(o),y=u.filter(a).filter(r),S=u.filter(h).filter(r);return y.forEach(p=>{p.setAttribute(me,p.disabled),p.disabled=!0}),S.forEach(p=>{p.setAttribute(Oe,p.readOnly),p.readOnly=!0,p.files&&(p.setAttribute(me,p.disabled),p.disabled=!0)}),e.setAttribute(this.binding(et),""),this.putRef([e].concat(v).concat(y).concat(S),"submit",s)},f=this.targetComponentID(e,t);if(E.hasUploadsInProgress(e)){let[u,v]=c(),y=()=>this.pushFormSubmit(e,t,i,s,n);return this.scheduleSubmit(e,u,s,y)}else if(E.inputsAwaitingPreflight(e).length>0){let[u,v]=c(),y=()=>[u,v,s];this.uploadFiles(e,t,u,f,S=>{let p=Ce(e,{});this.pushWithReply(y,"event",{type:"form",event:i,value:p,cid:f},n)})}else{let u=Ce(e,{});this.pushWithReply(c,"event",{type:"form",event:i,value:u,cid:f},n)}}uploadFiles(e,t,i,s,n){let r=this.joinCount,o=E.activeFileInputs(e),a=o.length;o.forEach(h=>{let c=new E(h,this,()=>{a--,a===0&&n()});this.uploaders[h]=c;let f=c.entries().map(v=>v.toPreflightPayload()),u={ref:h.getAttribute(K),entries:f,cid:this.targetComponentID(h.form,t)};this.log("upload",()=>["sending preflight request",u]),this.pushWithReply(null,"allow_upload",u,v=>{if(this.log("upload",()=>["got preflight response",v]),v.error){this.undoRefs(i);let[y,S]=v.error;this.log("upload",()=>[`error for entry ${y}`,S])}else{let y=S=>{this.channel.onError(()=>{this.joinCount===r&&S()})};c.initAdapterUpload(v,y,this.liveSocket)}})})}dispatchUploads(e,t){let i=l.findUploadInputs(this.el).filter(s=>s.name===e);i.length===0?T(`no live file inputs found matching the name "${e}"`):i.length>1?T(`duplicate live file inputs found matching the name "${e}"`):l.dispatchEvent(i[0],St,{detail:{files:t}})}pushFormRecovery(e,t,i){this.liveSocket.withinOwners(e,(s,n)=>{let r=e.elements[0],o=e.getAttribute(this.binding(rt))||e.getAttribute(this.binding("change"));N.exec("change",o,s,r,["push",{_target:r.name,newCid:t,callback:i}])})}pushLinkPatch(e,t,i){let s=this.liveSocket.setPendingLink(e),n=t?()=>this.putRef([t],"click"):null,r=()=>this.liveSocket.redirect(window.location.href),o=this.pushWithReply(n,"live_patch",{url:e},a=>{this.liveSocket.requestDOMUpdate(()=>{a.link_redirect?this.liveSocket.replaceMain(e,null,i,s):(this.liveSocket.commitPendingLink(s)&&(this.href=e),this.applyPendingUpdates(),i&&i(s))})});o?o.receive("timeout",r):r()}formsForRecovery(e){if(this.joinCount===0)return[];let t=this.binding("change"),i=document.createElement("template");return i.innerHTML=e,l.all(this.el,`form[${t}]`).filter(s=>s.id&&this.ownsElement(s)).filter(s=>s.elements.length>0).filter(s=>s.getAttribute(this.binding(rt))!=="ignore").map(s=>{let n=i.content.querySelector(`form[id="${s.id}"][${t}="${s.getAttribute(t)}"]`);return n?[s,n,this.targetComponentID(n)]:[s,null,null]}).filter(([s,n,r])=>n)}maybePushComponentsDestroyed(e){let t=e.filter(i=>l.findComponentNodeList(this.el,i).length===0);t.length>0&&(this.pruningCIDs.push(...t),this.pushWithReply(null,"cids_will_destroy",{cids:t},()=>{this.pruningCIDs=this.pruningCIDs.filter(s=>t.indexOf(s)!==-1);let i=t.filter(s=>l.findComponentNodeList(this.el,s).length===0);i.length>0&&this.pushWithReply(null,"cids_destroyed",{cids:i},s=>{this.rendered.pruneCIDs(s.cids)})}))}ownsElement(e){return e.getAttribute(Q)===this.id||j(e.closest(Z),t=>t.id)===this.id}submitForm(e,t,i,s={}){l.putPrivate(e,At,!0);let n=this.liveSocket.binding(Je),r=Array.from(e.elements);this.liveSocket.blurActiveElement(this),this.pushFormSubmit(e,t,i,s,()=>{r.forEach(o=>l.showError(o,n)),this.liveSocket.restorePreviouslyActiveFocus()})}binding(e){return this.liveSocket.binding(e)}},Tt=class{constructor(e,t,i={}){if(this.unloaded=!1,!t||t.constructor.name==="Object")throw new Error(`
a phoenix Socket must be provided as the second argument to the LiveSocket constructor. For example:
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
let liveSocket = new LiveSocket("/live", Socket, {...})
`);this.socket=new t(e,i),this.bindingPrefix=i.bindingPrefix||qt,this.opts=i,this.params=Me(i.params||{}),this.viewLogger=i.viewLogger,this.metadataCallbacks=i.metadata||{},this.defaults=Object.assign(Ee(Kt),i.defaults||{}),this.activeElement=null,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=Ee(window.location),this.hooks=i.hooks||{},this.uploaders=i.uploaders||{},this.loaderTimeout=i.loaderTimeout||Xt,this.reloadWithJitterTimer=null,this.maxReloads=i.maxReloads||Dt,this.reloadJitterMin=i.reloadJitterMin||It,this.reloadJitterMax=i.reloadJitterMax||Ot,this.failsafeJitter=i.failsafeJitter||Ht,this.localStorage=i.localStorage||window.localStorage,this.sessionStorage=i.sessionStorage||window.sessionStorage,this.boundTopLevelEvents=!1,this.domCallbacks=Object.assign({onNodeAdded:Me(),onBeforeElUpdated:Me()},i.dom||{}),this.transitions=new ki,window.addEventListener("pagehide",s=>{this.unloaded=!0}),this.socket.onOpen(()=>{this.isUnloaded()&&window.location.reload()})}isProfileEnabled(){return this.sessionStorage.getItem(He)==="true"}isDebugEnabled(){return this.sessionStorage.getItem(ye)==="true"}isDebugDisabled(){return this.sessionStorage.getItem(ye)==="false"}enableDebug(){this.sessionStorage.setItem(ye,"true")}enableProfiling(){this.sessionStorage.setItem(He,"true")}disableDebug(){this.sessionStorage.setItem(ye,"false")}disableProfiling(){this.sessionStorage.removeItem(He)}enableLatencySim(e){this.enableDebug(),console.log("latency simulator enabled for the duration of this browser session. Call disableLatencySim() to disable"),this.sessionStorage.setItem(Ne,e)}disableLatencySim(){this.sessionStorage.removeItem(Ne)}getLatencySim(){let e=this.sessionStorage.getItem(Ne);return e?parseInt(e):null}getSocket(){return this.socket}connect(){window.location.hostname==="localhost"&&!this.isDebugDisabled()&&this.enableDebug();let e=()=>{this.joinRootViews()?(this.bindTopLevelEvents(),this.socket.connect()):this.main&&this.socket.connect()};["complete","loaded","interactive"].indexOf(document.readyState)>=0?e():document.addEventListener("DOMContentLoaded",()=>e())}disconnect(e){clearTimeout(this.reloadWithJitterTimer),this.socket.disconnect(e)}replaceTransport(e){clearTimeout(this.reloadWithJitterTimer),this.socket.replaceTransport(e),this.connect()}execJS(e,t,i=null){this.owner(e,s=>N.exec(i,t,s,e))}triggerDOM(e,t){this.domCallbacks[e](...t)}time(e,t){if(!this.isProfileEnabled()||!console.time)return t();console.time(e);let i=t();return console.timeEnd(e),i}log(e,t,i){if(this.viewLogger){let[s,n]=i();this.viewLogger(e,t,s,n)}else if(this.isDebugEnabled()){let[s,n]=i();Zt(e,t,s,n)}}requestDOMUpdate(e){this.transitions.after(e)}transition(e,t,i=function(){}){this.transitions.addTransition(e,t,i)}onChannel(e,t,i){e.on(t,s=>{let n=this.getLatencySim();n?(console.log(`simulating ${n}ms of latency from server to client`),setTimeout(()=>i(s),n)):i(s)})}wrapPush(e,t,i){let s=this.getLatencySim(),n=e.joinCount;if(!s)return this.isConnected()&&t.timeout?i().receive("timeout",()=>{e.joinCount===n&&!e.isDestroyed()&&this.reloadWithJitter(e,()=>{this.log(e,"timeout",()=>["received timeout while communicating with server. Falling back to hard refresh for recovery"])})}):i();console.log(`simulating ${s}ms of latency from client to server`);let r={receives:[],receive(o,a){this.receives.push([o,a])}};return setTimeout(()=>{e.isDestroyed()||r.receives.reduce((o,[a,h])=>o.receive(a,h),i())},s),r}reloadWithJitter(e,t){clearTimeout(this.reloadWithJitterTimer),this.disconnect();let i=this.reloadJitterMin,s=this.reloadJitterMax,n=Math.floor(Math.random()*(s-i+1))+i,r=V.updateLocal(this.localStorage,window.location.pathname,bt,0,o=>o+1);r>this.maxReloads&&(n=this.failsafeJitter),this.reloadWithJitterTimer=setTimeout(()=>{e.isDestroyed()||e.isConnected()||(e.destroy(),t?t():this.log(e,"join",()=>[`encountered ${r} consecutive reloads`]),r>this.maxReloads&&this.log(e,"join",()=>[`exceeded ${this.maxReloads} consecutive reloads. Entering failsafe mode`]),this.hasPendingLink()?window.location=this.pendingLink:window.location.reload())},n)}getHookCallbacks(e){return e&&e.startsWith("Phoenix.")?ni[e.split(".")[1]]:this.hooks[e]}isUnloaded(){return this.unloaded}isConnected(){return this.socket.isConnected()}getBindingPrefix(){return this.bindingPrefix}binding(e){return`${this.getBindingPrefix()}${e}`}channel(e,t){return this.socket.channel(e,t)}joinRootViews(){let e=!1;return l.all(document,`${Z}:not([${Q}])`,t=>{if(!this.getRootById(t.id)){let i=this.newRootView(t);i.setHref(this.getHref()),i.join(),t.getAttribute(qe)&&(this.main=i)}e=!0}),e}redirect(e,t){this.disconnect(),V.redirect(e,t)}replaceMain(e,t,i=null,s=this.setPendingLink(e)){this.outgoingMainEl=this.outgoingMainEl||this.main.el;let n=l.cloneNode(this.outgoingMainEl,"");this.main.showLoader(this.loaderTimeout),this.main.destroy(),this.main=this.newRootView(n,t),this.main.setRedirect(e),this.transitionRemoves(),this.main.join((r,o)=>{r===1&&this.commitPendingLink(s)&&this.requestDOMUpdate(()=>{l.findPhxSticky(document).forEach(a=>n.appendChild(a)),this.outgoingMainEl.replaceWith(n),this.outgoingMainEl=null,i&&requestAnimationFrame(i),o()})})}transitionRemoves(e){let t=this.binding("remove");e=e||l.all(document,`[${t}]`),e.forEach(i=>{document.body.contains(i)&&this.execJS(i,i.getAttribute(t),"remove")})}isPhxView(e){return e.getAttribute&&e.getAttribute(W)!==null}newRootView(e,t){let i=new Et(e,this,null,t);return this.roots[i.id]=i,i}owner(e,t){let i=j(e.closest(Z),s=>this.getViewByEl(s))||this.main;i&&t(i)}withinOwners(e,t){this.owner(e,i=>t(i,e))}getViewByEl(e){let t=e.getAttribute(ae);return j(this.getRootById(t),i=>i.getDescendentByEl(e))}getRootById(e){return this.roots[e]}destroyAllViews(){for(let e in this.roots)this.roots[e].destroy(),delete this.roots[e];this.main=null}destroyViewByEl(e){let t=this.getRootById(e.getAttribute(ae));t&&t.id===e.id?(t.destroy(),delete this.roots[t.id]):t&&t.destroyDescendent(e.id)}setActiveElement(e){if(this.activeElement===e)return;this.activeElement=e;let t=()=>{e===this.activeElement&&(this.activeElement=null),e.removeEventListener("mouseup",this),e.removeEventListener("touchend",this)};e.addEventListener("mouseup",t),e.addEventListener("touchend",t)}getActiveElement(){return document.activeElement===document.body?this.activeElement||document.activeElement:document.activeElement||document.body}dropActiveElement(e){this.prevActive&&e.ownsElement(this.prevActive)&&(this.prevActive=null)}restorePreviouslyActiveFocus(){this.prevActive&&this.prevActive!==document.body&&this.prevActive.focus()}blurActiveElement(){this.prevActive=this.getActiveElement(),this.prevActive!==document.body&&this.prevActive.blur()}bindTopLevelEvents(){this.boundTopLevelEvents||(this.boundTopLevelEvents=!0,this.socket.onClose(e=>{e&&e.code===1e3&&this.main&&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),this.bindNav(),this.bindClicks(),this.bindForms(),this.bind({keyup:"keyup",keydown:"keydown"},(e,t,i,s,n,r)=>{let o=s.getAttribute(this.binding(Jt)),a=e.key&&e.key.toLowerCase();if(o&&o.toLowerCase()!==a)return;let h={key:e.key,...this.eventMeta(t,e,s)};N.exec(t,n,i,s,["push",{data:h}])}),this.bind({blur:"focusout",focus:"focusin"},(e,t,i,s,n,r)=>{if(!r){let o={key:e.key,...this.eventMeta(t,e,s)};N.exec(t,n,i,s,["push",{data:o}])}}),this.bind({blur:"blur",focus:"focus"},(e,t,i,s,n,r,o)=>{if(o==="window"){let a=this.eventMeta(t,e,s);N.exec(t,r,i,s,["push",{data:a}])}}),window.addEventListener("dragover",e=>e.preventDefault()),window.addEventListener("drop",e=>{e.preventDefault();let t=j(oe(e.target,this.binding(Qe)),n=>n.getAttribute(this.binding(Qe))),i=t&&document.getElementById(t),s=Array.from(e.dataTransfer.files||[]);!i||i.disabled||s.length===0||!(i.files instanceof FileList)||(E.trackFiles(i,s),i.dispatchEvent(new Event("input",{bubbles:!0})))}),this.on(St,e=>{let t=e.target;if(!l.isUploadInput(t))return;let i=Array.from(e.detail.files||[]).filter(s=>s instanceof File||s instanceof Blob);E.trackFiles(t,i),t.dispatchEvent(new Event("input",{bubbles:!0}))}))}eventMeta(e,t,i){let s=this.metadataCallbacks[e];return s?s(t,i):{}}setPendingLink(e){return this.linkRef++,this.pendingLink=e,this.linkRef}commitPendingLink(e){return this.linkRef!==e?!1:(this.href=this.pendingLink,this.pendingLink=null,!0)}getHref(){return this.href}hasPendingLink(){return!!this.pendingLink}bind(e,t){for(let i in e){let s=e[i];this.on(s,n=>{let r=this.binding(i),o=this.binding(`window-${i}`),a=n.target.getAttribute&&n.target.getAttribute(r);a?this.debounce(n.target,n,s,()=>{this.withinOwners(n.target,h=>{t(n,i,h,n.target,a,null)})}):l.all(document,`[${o}]`,h=>{let c=h.getAttribute(o);this.debounce(h,n,s,()=>{this.withinOwners(h,f=>{t(n,i,f,h,c,"window")})})})})}}bindClicks(){window.addEventListener("mousedown",e=>this.clickStartedAtTarget=e.target),this.bindClick("click","click",!1),this.bindClick("mousedown","capture-click",!0)}bindClick(e,t,i){let s=this.binding(t);window.addEventListener(e,n=>{let r=null;if(i)r=n.target.matches(`[${s}]`)?n.target:n.target.querySelector(`[${s}]`);else{let a=this.clickStartedAtTarget||n.target;r=oe(a,s),this.dispatchClickAway(n,a),this.clickStartedAtTarget=null}let o=r&&r.getAttribute(s);!o||(r.getAttribute("href")==="#"&&n.preventDefault(),this.debounce(r,n,"click",()=>{this.withinOwners(r,a=>{N.exec("click",o,a,r,["push",{data:this.eventMeta("click",n,r)}])})}))},i)}dispatchClickAway(e,t){let i=this.binding("click-away");l.all(document,`[${i}]`,s=>{s.isSameNode(t)||s.contains(t)||this.withinOwners(e.target,n=>{let r=s.getAttribute(i);N.isVisible(s)&&N.exec("click",r,n,s,["push",{data:this.eventMeta("click",e,e.target)}])})})}bindNav(){if(!V.canPushState())return;history.scrollRestoration&&(history.scrollRestoration="manual");let e=null;window.addEventListener("scroll",t=>{clearTimeout(e),e=setTimeout(()=>{V.updateCurrentState(i=>Object.assign(i,{scroll:window.scrollY}))},100)}),window.addEventListener("popstate",t=>{if(!this.registerNewLocation(window.location))return;let{type:i,id:s,root:n,scroll:r}=t.state||{},o=window.location.href;this.requestDOMUpdate(()=>{this.main.isConnected()&&i==="patch"&&s===this.main.id?this.main.pushLinkPatch(o,null):this.replaceMain(o,null,()=>{n&&this.replaceRootHistory(),typeof r=="number"&&setTimeout(()=>{window.scrollTo(0,r)},0)})})},!1),window.addEventListener("click",t=>{let i=oe(t.target,De),s=i&&i.getAttribute(De),n=t.metaKey||t.ctrlKey||t.button===1;if(!s||!this.isConnected()||!this.main||n)return;let r=i.href,o=i.getAttribute(Mt);t.preventDefault(),t.stopImmediatePropagation(),this.pendingLink!==r&&this.requestDOMUpdate(()=>{if(s==="patch")this.pushHistoryPatch(r,o,i);else if(s==="redirect")this.historyRedirect(r,o);else throw new Error(`expected ${De} to be "patch" or "redirect", got: ${s}`)})},!1)}dispatchEvent(e,t={}){l.dispatchEvent(window,`phx:${e}`,{detail:t})}dispatchEvents(e){e.forEach(([t,i])=>this.dispatchEvent(t,i))}withPageLoading(e,t){l.dispatchEvent(window,"phx:page-loading-start",{detail:e});let i=()=>l.dispatchEvent(window,"phx:page-loading-stop",{detail:e});return t?t(i):i}pushHistoryPatch(e,t,i){this.withPageLoading({to:e,kind:"patch"},s=>{this.main.pushLinkPatch(e,i,n=>{this.historyPatch(e,t,n),s()})})}historyPatch(e,t,i=this.setPendingLink(e)){!this.commitPendingLink(i)||(V.pushState(t,{type:"patch",id:this.main.id},e),this.registerNewLocation(window.location))}historyRedirect(e,t,i){let s=window.scrollY;this.withPageLoading({to:e,kind:"redirect"},n=>{this.replaceMain(e,i,()=>{V.pushState(t,{type:"redirect",id:this.main.id,scroll:s},e),this.registerNewLocation(window.location),n()})})}replaceRootHistory(){V.pushState("replace",{root:!0,type:"patch",id:this.main.id})}registerNewLocation(e){let{pathname:t,search:i}=this.currentLocation;return t+i===e.pathname+e.search?!1:(this.currentLocation=Ee(e),!0)}bindForms(){let e=0;this.on("submit",t=>{let i=t.target.getAttribute(this.binding("submit"));!i||(t.preventDefault(),t.target.disabled=!0,this.withinOwners(t.target,s=>{N.exec("submit",i,s,t.target,["push",{}])}))},!1);for(let t of["change","input"])this.on(t,i=>{let s=this.binding("change"),n=i.target,r=n.getAttribute(s),o=n.form&&n.form.getAttribute(s),a=r||o;if(!a||n.type==="number"&&n.validity&&n.validity.badInput)return;let h=r?n:n.form,c=e;e++;let{at:f,type:u}=l.private(n,"prev-iteration")||{};f===c-1&&t!==u||(l.putPrivate(n,"prev-iteration",{at:c,type:t}),this.debounce(n,i,t,()=>{this.withinOwners(h,v=>{l.putPrivate(n,wt,!0),l.isTextualInput(n)||this.setActiveElement(n),N.exec("change",a,v,n,["push",{_target:i.target.name,dispatcher:h}])})}))},!1)}debounce(e,t,i,s){if(i==="blur"||i==="focusout")return s();let n=this.binding(Ft),r=this.binding(Bt),o=this.defaults.debounce.toString(),a=this.defaults.throttle.toString();this.withinOwners(e,h=>{let c=()=>!h.isDestroyed()&&document.body.contains(e);l.debounce(e,t,n,o,r,a,c,()=>{s()})})}silenceEvents(e){this.silenced=!0,e(),this.silenced=!1}on(e,t){window.addEventListener(e,i=>{this.silenced||t(i)})}},ki=class{constructor(){this.transitions=new Set,this.pendingOps=[],this.reset()}reset(){this.transitions.forEach(e=>{cancelTimeout(e),this.transitions.delete(e)}),this.flushPendingOps()}after(e){this.size()===0?e():this.pushPendingOp(e)}addTransition(e,t,i){t();let s=setTimeout(()=>{this.transitions.delete(s),i(),this.size()===0&&this.flushPendingOps()},e);this.transitions.add(s)}pushPendingOp(e){this.pendingOps.push(e)}size(){return this.transitions.size}flushPendingOps(){this.pendingOps.forEach(e=>e()),this.pendingOps=[]}};var le=e=>typeof e=="function"?e:function(){return e},Ai=typeof self<"u"?self:null,he=typeof window<"u"?window:null,de=Ai||he||de,Ci="2.0.0",U={connecting:0,open:1,closing:2,closed:3},Ei=1e4,Ti=1e3,x={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},$={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ke={longpoll:"longpoll",websocket:"websocket"},_i={complete:4},Te=class{constructor(e,t,i,s){this.channel=e,this.event=t,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:i}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}cancelRefEvent(){!this.refEvent||this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},_t=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Pi=class{constructor(e,t,i){this.state=x.closed,this.topic=e,this.params=le(t||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Te(this,$.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new _t(()=>{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=x.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",()=>{this.state=x.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=x.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=x.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 Te(this,$.leave,le({}),this.timeout).send(),this.state=x.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on($.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on($.close,e)}onError(e){return this.on($.error,t=>e(t))}on(e,t){let i=this.bindingRef++;return this.bindings.push({event:e,ref:i,callback:t}),i}off(e,t){this.bindings=this.bindings.filter(i=>!(i.event===e&&(typeof t>"u"||t===i.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,i=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new Te(this,e,function(){return t},i);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=x.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger($.close,"leave")},i=new Te(this,$.leave,le({}),e);return i.receive("ok",()=>t()).receive("timeout",()=>t()),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(e,t,i){return t}isMember(e,t,i,s){return this.topic!==e?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:i,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=x.joining,this.joinPush.resend(e))}trigger(e,t,i,s){let n=this.onMessage(e,t,i,s);if(t&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let r=this.bindings.filter(o=>o.event===e);for(let o=0;o<r.length;o++)r[o].callback(n,i,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===x.closed}isErrored(){return this.state===x.errored}isJoined(){return this.state===x.joined}isJoining(){return this.state===x.joining}isLeaving(){return this.state===x.leaving}},Pe=class{static request(e,t,i,s,n,r,o){if(de.XDomainRequest){let a=new de.XDomainRequest;return this.xdomainRequest(a,e,t,s,n,r,o)}else{let a=new de.XMLHttpRequest;return this.xhrRequest(a,e,t,i,s,n,r,o)}}static xdomainRequest(e,t,i,s,n,r,o){return e.timeout=n,e.open(t,i),e.onload=()=>{let a=this.parseJSON(e.responseText);o&&o(a)},r&&(e.ontimeout=r),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,i,s,n,r,o,a){return e.open(t,i,!0),e.timeout=r,e.setRequestHeader("Content-Type",s),e.onerror=()=>a&&a(null),e.onreadystatechange=()=>{if(e.readyState===_i.complete&&a){let h=this.parseJSON(e.responseText);a(h)}},o&&(e.ontimeout=o),e.send(n),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let i=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let n=t?`${t}[${s}]`:s,r=e[s];typeof r=="object"?i.push(this.serialize(r,n)):i.push(encodeURIComponent(n)+"="+encodeURIComponent(r))}return i.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let i=e.match(/\?/)?"&":"?";return`${e}${i}${this.serialize(t)}`}},ze=class{constructor(e){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=U.connecting,this.poll()}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ke.websocket),"$1/"+Ke.longpoll)}endpointURL(){return Pe.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,i){this.close(e,t,i),this.readyState=U.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===U.open||this.readyState===U.connecting}poll(){this.ajax("GET",null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:i,messages:s}=e;this.token=i}else t=0;switch(t){case 200:s.forEach(n=>{setTimeout(()=>this.onmessage({data:n}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=U.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 ${t}`)}})}send(e){this.ajax("POST",e,()=>this.onerror("timeout"),t=>{(!t||t.status!==200)&&(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1))})}close(e,t,i){for(let n of this.reqs)n.abort();this.readyState=U.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:i});typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,i,s){let n,r=()=>{this.reqs.delete(n),i()};n=Pe.request(e,this.endpointURL(),"application/json",t,this.timeout,r,o=>{this.reqs.delete(n),this.isActive()&&s(o)}),this.reqs.add(n)}};var _e={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let i=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(i))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[i,s,n,r,o]=JSON.parse(e);return t({join_ref:i,ref:s,topic:n,event:r,payload:o})}},binaryEncode(e){let{join_ref:t,ref:i,event:s,topic:n,payload:r}=e,o=this.META_LENGTH+t.length+i.length+n.length+s.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),h=new DataView(a),c=0;h.setUint8(c++,this.KINDS.push),h.setUint8(c++,t.length),h.setUint8(c++,i.length),h.setUint8(c++,n.length),h.setUint8(c++,s.length),Array.from(t,u=>h.setUint8(c++,u.charCodeAt(0))),Array.from(i,u=>h.setUint8(c++,u.charCodeAt(0))),Array.from(n,u=>h.setUint8(c++,u.charCodeAt(0))),Array.from(s,u=>h.setUint8(c++,u.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(e){let t=new DataView(e),i=t.getUint8(0),s=new TextDecoder;switch(i){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=i.decode(e.slice(o,o+s));o=o+s;let h=i.decode(e.slice(o,o+n));o=o+n;let c=i.decode(e.slice(o,o+r));o=o+r;let f=e.slice(o,e.byteLength);return{join_ref:a,ref:null,topic:h,event:c,payload:f}},decodeReply(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=t.getUint8(3),o=t.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,h=i.decode(e.slice(a,a+s));a=a+s;let c=i.decode(e.slice(a,a+n));a=a+n;let f=i.decode(e.slice(a,a+r));a=a+r;let u=i.decode(e.slice(a,a+o));a=a+o;let v=e.slice(a,e.byteLength),y={status:u,response:v};return{join_ref:h,ref:c,topic:f,event:$.reply,payload:y}},decodeBroadcast(e,t,i){let s=t.getUint8(1),n=t.getUint8(2),r=this.HEADER_LENGTH+2,o=i.decode(e.slice(r,r+s));r=r+s;let a=i.decode(e.slice(r,r+n));r=r+n;let h=e.slice(r,e.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:h}}},Pt=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=t.timeout||Ei,this.transport=t.transport||de.WebSocket||ze,this.establishedConnections=0,this.defaultEncoder=_e.encode.bind(_e),this.defaultDecoder=_e.decode.bind(_e),this.closeWasClean=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.transport!==ze?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;he&&he.addEventListener&&(he.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),i=this.connectClock)}),he.addEventListener("pageshow",s=>{i===this.connectClock&&(i=null,this.connect())})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=s=>t.rejoinAfterMs?t.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>t.reconnectAfterMs?t.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=t.logger||null,this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=le(t.params||{}),this.endPoint=`${e}/${Ke.websocket}`,this.vsn=t.vsn||Ci,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new _t(()=>{this.teardown(()=>this.connect())},this.reconnectAfterMs)}getLongPollTransport(){return ze}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.sendBuffer=[],this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Pe.appendParams(Pe.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,i){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.teardown(e,t,i)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=le(e)),!this.conn&&(this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t))}log(e,t,i){this.logger(e,t,i)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(n=>{n.ref===t&&(this.off([s]),e(Date.now()-i))});return!0}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,e])=>e())}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.abnormalClose("heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,clearTimeout(this.heartbeatTimer),setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,i){if(!this.conn)return e&&e();this.waitForBufferDone(()=>{this.conn&&(t?this.conn.close(t,i||""):this.conn.close()),this.waitForSocketClosed(()=>{this.conn&&(this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t=1){if(t===5||!this.conn||!this.conn.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(e,t+1)},150*t)}waitForSocketClosed(e,t=1){if(t===5||!this.conn||this.conn.readyState===U.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(e,t+1)},150*t)}onConnClose(e){let t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),clearTimeout(this.heartbeatTimer),!this.closeWasClean&&t!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,i])=>i(e))}onConnError(e){this.hasLogger()&&this.log("transport",e);let t=this.transport,i=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,s])=>{s(e,t,i)}),(t===this.transport||i>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger($.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case U.connecting:return"connecting";case U.open:return"open";case U.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t.joinRef()!==e.joinRef())}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([i])=>e.indexOf(i)===-1)}channel(e,t={}){let i=new Pi(e,t,this);return this.channels.push(i),i}push(e){if(this.hasLogger()){let{topic:t,event:i,payload:s,ref:n,join_ref:r}=e;this.log("push",`${t} ${i} (${r}, ${n})`,s)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs))}abnormalClose(e){this.closeWasClean=!1,this.isConnected()&&this.conn.close(Ti,e)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:i,event:s,payload:n,ref:r,join_ref:o}=t;r&&r===this.pendingHeartbeatRef&&(clearTimeout(this.heartbeatTimer),this.pendingHeartbeatRef=null,setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${n.status||""} ${i} ${s} ${r&&"("+r+")"||""}`,n);for(let a=0;a<this.channels.length;a++){let h=this.channels[a];!h.isMember(i,s,n,o)||h.trigger(s,n,r,o)}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,h]=this.stateChangeCallbacks.message[a];h(t)}})}leaveOpenTopic(e){let t=this.channels.find(i=>i.topic===e&&(i.isJoined()||i.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};window.storybook===void 0&&(console.warn("No storybook configuration detected."),console.warn("If you need to use custom hooks or uploaders, please define them in JS file and declare this file in your Elixir app config (:js_path key) "),window.storybook={});var Ri=document.querySelector("html").getAttribute("phx-socket")||"/live",Li=window.parent.document.querySelector("meta[name='csrf-token']").getAttribute("content"),Rt=new Tt(Ri,Pt,{hooks:{...window.storybook.Hooks},uploaders:window.storybook.Uploaders,params:e=>({_csrf_token:Li})});Rt.connect();window.liveSocket=Rt;})();