turbo-rails 2.0.0.pre.beta.1 → 2.0.0.pre.beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  /*!
2
- Turbo 8.0.0-beta.1
2
+ Turbo 8.0.0-beta.2
3
3
  Copyright © 2023 37signals LLC
4
4
  */
5
- !function(e){function t(e,t,s){throw new e("Failed to execute 'requestSubmit' on 'HTMLFormElement': "+t+".",s)}"function"!=typeof e.requestSubmit&&(e.requestSubmit=function(e){e?(!function(e,s){e instanceof HTMLElement||t(TypeError,"parameter 1 is not of type 'HTMLElement'"),"submit"==e.type||t(TypeError,"The specified element is not a submit button"),e.form==s||t(DOMException,"The specified element is not owned by this form element","NotFoundError")}(e,this),e.click()):((e=document.createElement("input")).type="submit",e.hidden=!0,this.appendChild(e),e.click(),this.removeChild(e))})}(HTMLFormElement.prototype);const e=new WeakMap;function t(t){const s=function(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null,s=t?t.closest("input, button"):null;return"submit"==s?.type?s:null}(t.target);s&&s.form&&e.set(s.form,s)}!function(){if("submitter"in Event.prototype)return;let s=window.Event.prototype;if("SubmitEvent"in window){const e=window.SubmitEvent.prototype;if(!/Apple Computer/.test(navigator.vendor)||"submitter"in e)return;s=e}addEventListener("click",t,!0),Object.defineProperty(s,"submitter",{get(){if("submit"==this.type&&this.target instanceof HTMLFormElement)return e.get(this.target)}})}();const s={eager:"eager",lazy:"lazy"};class i extends HTMLElement{static delegateConstructor=void 0;loaded=Promise.resolve();static get observedAttributes(){return["disabled","complete","loading","src"]}constructor(){super(),this.delegate=new i.delegateConstructor(this)}connectedCallback(){this.delegate.connect()}disconnectedCallback(){this.delegate.disconnect()}reload(){return this.delegate.sourceURLReloaded()}attributeChangedCallback(e){"loading"==e?this.delegate.loadingStyleChanged():"complete"==e?this.delegate.completeChanged():"src"==e?this.delegate.sourceURLChanged():this.delegate.disabledChanged()}get src(){return this.getAttribute("src")}set src(e){e?this.setAttribute("src",e):this.removeAttribute("src")}get refresh(){return this.getAttribute("refresh")}set refresh(e){e?this.setAttribute("refresh",e):this.removeAttribute("refresh")}get loading(){return function(e){if("lazy"===e.toLowerCase())return s.lazy;return s.eager}(this.getAttribute("loading")||"")}set loading(e){e?this.setAttribute("loading",e):this.removeAttribute("loading")}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get autoscroll(){return this.hasAttribute("autoscroll")}set autoscroll(e){e?this.setAttribute("autoscroll",""):this.removeAttribute("autoscroll")}get complete(){return!this.delegate.isLoading}get isActive(){return this.ownerDocument===document&&!this.isPreview}get isPreview(){return this.ownerDocument?.documentElement?.hasAttribute("data-turbo-preview")}}function r(e){return new URL(e.toString(),document.baseURI)}function n(e){let t;return e.hash?e.hash.slice(1):(t=e.href.match(/#(.*)$/))?t[1]:void 0}function o(e,t){return r(t?.getAttribute("formaction")||e.getAttribute("action")||e.action)}function a(e){return(function(e){return function(e){return e.pathname.split("/").slice(1)}(e).slice(-1)[0]}(e).match(/\.[^.]*$/)||[])[0]||""}function c(e,t){const s=function(e){return t=e.origin+e.pathname,t.endsWith("/")?t:t+"/";var t}(t);return e.href===r(s).href||e.href.startsWith(s)}function l(e,t){return c(e,t)&&!!a(e).match(/^(?:|\.(?:htm|html|xhtml|php))$/)}function h(e){const t=n(e);return null!=t?e.href.slice(0,-(t.length+1)):e.href}function d(e){return h(e)}class u{constructor(e){this.response=e}get succeeded(){return this.response.ok}get failed(){return!this.succeeded}get clientError(){return this.statusCode>=400&&this.statusCode<=499}get serverError(){return this.statusCode>=500&&this.statusCode<=599}get redirected(){return this.response.redirected}get location(){return r(this.response.url)}get isHTML(){return this.contentType&&this.contentType.match(/^(?:text\/([^\s;,]+\b)?html|application\/xhtml\+xml)\b/)}get statusCode(){return this.response.status}get contentType(){return this.header("Content-Type")}get responseText(){return this.response.clone().text()}get responseHTML(){return this.isHTML?this.response.clone().text():Promise.resolve(void 0)}header(e){return this.response.headers.get(e)}}function m(e){if("false"==e.getAttribute("data-turbo-eval"))return e;{const t=document.createElement("script"),s=T("csp-nonce");return s&&(t.nonce=s),t.textContent=e.textContent,t.async=!1,function(e,t){for(const{name:s,value:i}of t.attributes)e.setAttribute(s,i)}(t,e),t}}function p(e,{target:t,cancelable:s,detail:i}={}){const r=new CustomEvent(e,{cancelable:s,bubbles:!0,composed:!0,detail:i});return t&&t.isConnected?t.dispatchEvent(r):document.documentElement.dispatchEvent(r),r}function f(){return new Promise((e=>requestAnimationFrame((()=>e()))))}function g(){return new Promise((e=>setTimeout((()=>e()),0)))}function b(e=""){return(new DOMParser).parseFromString(e,"text/html")}function v(e,...t){const s=function(e,t){return e.reduce(((e,s,i)=>e+s+(null==t[i]?"":t[i])),"")}(e,t).replace(/^\n/,"").split("\n"),i=s[0].match(/^\s+/),r=i?i[0].length:0;return s.map((e=>e.slice(r))).join("\n")}function S(){return Array.from({length:36}).map(((e,t)=>8==t||13==t||18==t||23==t?"-":14==t?"4":19==t?(Math.floor(4*Math.random())+8).toString(16):Math.floor(15*Math.random()).toString(16))).join("")}function w(e,...t){for(const s of t.map((t=>t?.getAttribute(e))))if("string"==typeof s)return s;return null}function y(...e){for(const t of e)"turbo-frame"==t.localName&&t.setAttribute("busy",""),t.setAttribute("aria-busy","true")}function E(...e){for(const t of e)"turbo-frame"==t.localName&&t.removeAttribute("busy"),t.removeAttribute("aria-busy")}function R(e,t=2e3){return new Promise((s=>{const i=()=>{e.removeEventListener("error",i),e.removeEventListener("load",i),s()};e.addEventListener("load",i,{once:!0}),e.addEventListener("error",i,{once:!0}),setTimeout(s,t)}))}function A(e){switch(e){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}function L(...e){const t=w("data-turbo-action",...e);return function(e){return"advance"==e||"replace"==e||"restore"==e}(t)?t:null}function C(e){return document.querySelector(`meta[name="${e}"]`)}function T(e){const t=C(e);return t&&t.content}function P(e,t){if(e instanceof Element)return e.closest(t)||P(e.assignedSlot||e.getRootNode()?.host,t)}function k(e){return!!e&&null==e.closest("[inert], :disabled, [hidden], details:not([open]), dialog:not([open])")&&"function"==typeof e.focus}function M(e){return Array.from(e.querySelectorAll("[autofocus]")).find(k)}function F(e,t={}){const s=new Headers(t.headers||{}),i=S();return window.Turbo.session.recentRequests.add(i),s.append("X-Turbo-Request-Id",i),window.fetch(e,{...t,headers:s})}function I(e){switch(e.toLowerCase()){case"get":return H.get;case"post":return H.post;case"put":return H.put;case"patch":return H.patch;case"delete":return H.delete}}const H={get:"get",post:"post",put:"put",patch:"patch",delete:"delete"};function q(e){switch(e.toLowerCase()){case B.multipart:return B.multipart;case B.plain:return B.plain;default:return B.urlEncoded}}const B={urlEncoded:"application/x-www-form-urlencoded",multipart:"multipart/form-data",plain:"text/plain"};class O{abortController=new AbortController;#e=e=>{};constructor(e,t,s,i=new URLSearchParams,n=null,o=B.urlEncoded){const[a,c]=x(r(s),t,i,o);this.delegate=e,this.url=a,this.target=n,this.fetchOptions={credentials:"same-origin",redirect:"follow",method:t,headers:{...this.defaultHeaders},body:c,signal:this.abortSignal,referrer:this.delegate.referrer?.href},this.enctype=o}get method(){return this.fetchOptions.method}set method(e){const t=this.isSafe?this.url.searchParams:this.fetchOptions.body||new FormData,s=I(e)||H.get;this.url.search="";const[i,r]=x(this.url,s,t,this.enctype);this.url=i,this.fetchOptions.body=r,this.fetchOptions.method=s}get headers(){return this.fetchOptions.headers}set headers(e){this.fetchOptions.headers=e}get body(){return this.isSafe?this.url.searchParams:this.fetchOptions.body}set body(e){this.fetchOptions.body=e}get location(){return this.url}get params(){return this.url.searchParams}get entries(){return this.body?Array.from(this.body.entries()):[]}cancel(){this.abortController.abort()}async perform(){const{fetchOptions:e}=this;this.delegate.prepareRequest(this),await this.#t(e);try{this.delegate.requestStarted(this);const t=await F(this.url.href,e);return await this.receive(t)}catch(e){if("AbortError"!==e.name)throw this.#s(e)&&this.delegate.requestErrored(this,e),e}finally{this.delegate.requestFinished(this)}}async receive(e){const t=new u(e);return p("turbo:before-fetch-response",{cancelable:!0,detail:{fetchResponse:t},target:this.target}).defaultPrevented?this.delegate.requestPreventedHandlingResponse(this,t):t.succeeded?this.delegate.requestSucceededWithResponse(this,t):this.delegate.requestFailedWithResponse(this,t),t}get defaultHeaders(){return{Accept:"text/html, application/xhtml+xml"}}get isSafe(){return N(this.method)}get abortSignal(){return this.abortController.signal}acceptResponseType(e){this.headers.Accept=[e,this.headers.Accept].join(", ")}async#t(e){const t=new Promise((e=>this.#e=e)),s=p("turbo:before-fetch-request",{cancelable:!0,detail:{fetchOptions:e,url:this.url,resume:this.#e},target:this.target});this.url=s.detail.url,s.defaultPrevented&&await t}#s(e){return!p("turbo:fetch-request-error",{target:this.target,cancelable:!0,detail:{request:this,error:e}}).defaultPrevented}}function N(e){return I(e)==H.get}function x(e,t,s,i){const r=Array.from(s).length>0?new URLSearchParams(V(s)):e.searchParams;return N(t)?[W(e,r),null]:i==B.urlEncoded?[e,r]:[e,s]}function V(e){const t=[];for(const[s,i]of e)i instanceof File||t.push([s,i]);return t}function W(e,t){const s=new URLSearchParams(V(t));return e.search=s.toString(),e}class D{started=!1;constructor(e,t){this.delegate=e,this.element=t,this.intersectionObserver=new IntersectionObserver(this.intersect)}start(){this.started||(this.started=!0,this.intersectionObserver.observe(this.element))}stop(){this.started&&(this.started=!1,this.intersectionObserver.unobserve(this.element))}intersect=e=>{const t=e.slice(-1)[0];t?.isIntersecting&&this.delegate.elementAppearedInViewport(this.element)}}class U{static contentType="text/vnd.turbo-stream.html";static wrap(e){return"string"==typeof e?new this(function(e){const t=document.createElement("template");return t.innerHTML=e,t.content}(e)):e}constructor(e){this.fragment=function(e){for(const t of e.querySelectorAll("turbo-stream")){const e=document.importNode(t,!0);for(const t of e.templateElement.content.querySelectorAll("script"))t.replaceWith(m(t));t.replaceWith(e)}return e}(e)}}const _={initialized:"initialized",requesting:"requesting",waiting:"waiting",receiving:"receiving",stopping:"stopping",stopped:"stopped"};class ${state=_.initialized;static confirmMethod(e,t,s){return Promise.resolve(confirm(e))}constructor(e,t,s,i=!1){const n=function(e,t){const s=t?.getAttribute("formmethod")||e.getAttribute("method")||"";return I(s.toLowerCase())||H.get}(t,s),o=function(e,t){const s=r(e);N(t)&&(s.search="");return s}(function(e,t){const s="string"==typeof e.action?e.action:null;return t?.hasAttribute("formaction")?t.getAttribute("formaction")||"":e.getAttribute("action")||s||""}(t,s),n),a=function(e,t){const s=new FormData(e),i=t?.getAttribute("name"),r=t?.getAttribute("value");i&&s.append(i,r||"");return s}(t,s),c=function(e,t){return q(t?.getAttribute("formenctype")||e.enctype)}(t,s);this.delegate=e,this.formElement=t,this.submitter=s,this.fetchRequest=new O(this,n,o,a,t,c),this.mustRedirect=i}get method(){return this.fetchRequest.method}set method(e){this.fetchRequest.method=e}get action(){return this.fetchRequest.url.toString()}set action(e){this.fetchRequest.url=r(e)}get body(){return this.fetchRequest.body}get enctype(){return this.fetchRequest.enctype}get isSafe(){return this.fetchRequest.isSafe}get location(){return this.fetchRequest.url}async start(){const{initialized:e,requesting:t}=_,s=w("data-turbo-confirm",this.submitter,this.formElement);if("string"==typeof s){if(!await $.confirmMethod(s,this.formElement,this.submitter))return}if(this.state==e)return this.state=t,this.fetchRequest.perform()}stop(){const{stopping:e,stopped:t}=_;if(this.state!=e&&this.state!=t)return this.state=e,this.fetchRequest.cancel(),!0}prepareRequest(e){if(!e.isSafe){const t=function(e){if(null!=e){const t=(document.cookie?document.cookie.split("; "):[]).find((t=>t.startsWith(e)));if(t){const e=t.split("=").slice(1).join("=");return e?decodeURIComponent(e):void 0}}}(T("csrf-param"))||T("csrf-token");t&&(e.headers["X-CSRF-Token"]=t)}this.requestAcceptsTurboStreamResponse(e)&&e.acceptResponseType(U.contentType)}requestStarted(e){this.state=_.waiting,this.submitter?.setAttribute("disabled",""),this.setSubmitsWith(),p("turbo:submit-start",{target:this.formElement,detail:{formSubmission:this}}),this.delegate.formSubmissionStarted(this)}requestPreventedHandlingResponse(e,t){this.result={success:t.succeeded,fetchResponse:t}}requestSucceededWithResponse(e,t){if(t.clientError||t.serverError)this.delegate.formSubmissionFailedWithResponse(this,t);else if(this.requestMustRedirect(e)&&function(e){return 200==e.statusCode&&!e.redirected}(t)){const e=new Error("Form responses must redirect to another location");this.delegate.formSubmissionErrored(this,e)}else this.state=_.receiving,this.result={success:!0,fetchResponse:t},this.delegate.formSubmissionSucceededWithResponse(this,t)}requestFailedWithResponse(e,t){this.result={success:!1,fetchResponse:t},this.delegate.formSubmissionFailedWithResponse(this,t)}requestErrored(e,t){this.result={success:!1,error:t},this.delegate.formSubmissionErrored(this,t)}requestFinished(e){this.state=_.stopped,this.submitter?.removeAttribute("disabled"),this.resetSubmitterText(),p("turbo:submit-end",{target:this.formElement,detail:{formSubmission:this,...this.result}}),this.delegate.formSubmissionFinished(this)}setSubmitsWith(){if(this.submitter&&this.submitsWith)if(this.submitter.matches("button"))this.originalSubmitText=this.submitter.innerHTML,this.submitter.innerHTML=this.submitsWith;else if(this.submitter.matches("input")){const e=this.submitter;this.originalSubmitText=e.value,e.value=this.submitsWith}}resetSubmitterText(){if(this.submitter&&this.originalSubmitText)if(this.submitter.matches("button"))this.submitter.innerHTML=this.originalSubmitText;else if(this.submitter.matches("input")){this.submitter.value=this.originalSubmitText}}requestMustRedirect(e){return!e.isSafe&&this.mustRedirect}requestAcceptsTurboStreamResponse(e){return!e.isSafe||function(e,...t){return t.some((t=>t&&t.hasAttribute(e)))}("data-turbo-stream",this.submitter,this.formElement)}get submitsWith(){return this.submitter?.getAttribute("data-turbo-submits-with")}}class j{constructor(e){this.element=e}get activeElement(){return this.element.ownerDocument.activeElement}get children(){return[...this.element.children]}hasAnchor(e){return null!=this.getElementForAnchor(e)}getElementForAnchor(e){return e?this.element.querySelector(`[id='${e}'], a[name='${e}']`):null}get isConnected(){return this.element.isConnected}get firstAutofocusableElement(){return M(this.element)}get permanentElements(){return G(this.element)}getPermanentElementById(e){return z(this.element,e)}getPermanentElementMapForSnapshot(e){const t={};for(const s of this.permanentElements){const{id:i}=s,r=e.getPermanentElementById(i);r&&(t[i]=[s,r])}return t}}function z(e,t){return e.querySelector(`#${t}[data-turbo-permanent]`)}function G(e){return e.querySelectorAll("[id][data-turbo-permanent]")}class J{started=!1;constructor(e,t){this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.addEventListener("submit",this.submitCaptured,!0),this.started=!0)}stop(){this.started&&(this.eventTarget.removeEventListener("submit",this.submitCaptured,!0),this.started=!1)}submitCaptured=()=>{this.eventTarget.removeEventListener("submit",this.submitBubbled,!1),this.eventTarget.addEventListener("submit",this.submitBubbled,!1)};submitBubbled=e=>{if(!e.defaultPrevented){const t=e.target instanceof HTMLFormElement?e.target:void 0,s=e.submitter||void 0;t&&function(e,t){const s=t?.getAttribute("formmethod")||e.getAttribute("method");return"dialog"!=s}(t,s)&&function(e,t){if(t?.hasAttribute("formtarget")||e.hasAttribute("target")){const s=t?.getAttribute("formtarget")||e.target;for(const e of document.getElementsByName(s))if(e instanceof HTMLIFrameElement)return!1;return!0}return!0}(t,s)&&this.delegate.willSubmitForm(t,s)&&(e.preventDefault(),e.stopImmediatePropagation(),this.delegate.formSubmitted(t,s))}}}class K{#i=e=>{};#r=e=>{};constructor(e,t){this.delegate=e,this.element=t}scrollToAnchor(e){const t=this.snapshot.getElementForAnchor(e);t?(this.scrollToElement(t),this.focusElement(t)):this.scrollToPosition({x:0,y:0})}scrollToAnchorFromLocation(e){this.scrollToAnchor(n(e))}scrollToElement(e){e.scrollIntoView()}focusElement(e){e instanceof HTMLElement&&(e.hasAttribute("tabindex")?e.focus():(e.setAttribute("tabindex","-1"),e.focus(),e.removeAttribute("tabindex")))}scrollToPosition({x:e,y:t}){this.scrollRoot.scrollTo(e,t)}scrollToTop(){this.scrollToPosition({x:0,y:0})}get scrollRoot(){return window}async render(e){const{isPreview:t,shouldRender:s,newSnapshot:i}=e;if(s)try{this.renderPromise=new Promise((e=>this.#i=e)),this.renderer=e,await this.prepareToRenderSnapshot(e);const s=new Promise((e=>this.#r=e)),r={resume:this.#r,render:this.renderer.renderElement};this.delegate.allowsImmediateRender(i,t,r)||await s,await this.renderSnapshot(e),this.delegate.viewRenderedSnapshot(i,t,this.renderer.renderMethod),this.delegate.preloadOnLoadLinksForView(this.element),this.finishRenderingSnapshot(e)}finally{delete this.renderer,this.#i(void 0),delete this.renderPromise}else this.invalidate(e.reloadReason)}invalidate(e){this.delegate.viewInvalidated(e)}async prepareToRenderSnapshot(e){this.markAsPreview(e.isPreview),await e.prepareToRender()}markAsPreview(e){e?this.element.setAttribute("data-turbo-preview",""):this.element.removeAttribute("data-turbo-preview")}async renderSnapshot(e){await e.render()}finishRenderingSnapshot(e){e.finishRendering()}}class X extends K{missing(){this.element.innerHTML='<strong class="turbo-frame-error">Content missing</strong>'}get snapshot(){return new j(this.element)}}class Q{constructor(e,t){this.delegate=e,this.element=t}start(){this.element.addEventListener("click",this.clickBubbled),document.addEventListener("turbo:click",this.linkClicked),document.addEventListener("turbo:before-visit",this.willVisit)}stop(){this.element.removeEventListener("click",this.clickBubbled),document.removeEventListener("turbo:click",this.linkClicked),document.removeEventListener("turbo:before-visit",this.willVisit)}clickBubbled=e=>{this.respondsToEventTarget(e.target)?this.clickEvent=e:delete this.clickEvent};linkClicked=e=>{this.clickEvent&&this.respondsToEventTarget(e.target)&&e.target instanceof Element&&this.delegate.shouldInterceptLinkClick(e.target,e.detail.url,e.detail.originalEvent)&&(this.clickEvent.preventDefault(),e.preventDefault(),this.delegate.linkClickIntercepted(e.target,e.detail.url,e.detail.originalEvent)),delete this.clickEvent};willVisit=e=>{delete this.clickEvent};respondsToEventTarget(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null;return t&&t.closest("turbo-frame, html")==this.element}}class Y{started=!1;constructor(e,t){this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.addEventListener("click",this.clickCaptured,!0),this.started=!0)}stop(){this.started&&(this.eventTarget.removeEventListener("click",this.clickCaptured,!0),this.started=!1)}clickCaptured=()=>{this.eventTarget.removeEventListener("click",this.clickBubbled,!1),this.eventTarget.addEventListener("click",this.clickBubbled,!1)};clickBubbled=e=>{if(e instanceof MouseEvent&&this.clickEventIsSignificant(e)){const t=e.composedPath&&e.composedPath()[0]||e.target,s=this.findLinkFromClickTarget(t);if(s&&function(e){if(e.hasAttribute("target")){for(const t of document.getElementsByName(e.target))if(t instanceof HTMLIFrameElement)return!1;return!0}return!0}(s)){const t=this.getLocationForLink(s);this.delegate.willFollowLinkToLocation(s,t,e)&&(e.preventDefault(),this.delegate.followedLinkToLocation(s,t))}}};clickEventIsSignificant(e){return!(e.target&&e.target.isContentEditable||e.defaultPrevented||e.which>1||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)}findLinkFromClickTarget(e){return P(e,"a[href]:not([target^=_]):not([download])")}getLocationForLink(e){return r(e.getAttribute("href")||"")}}class Z{constructor(e,t){this.delegate=e,this.linkInterceptor=new Y(this,t)}start(){this.linkInterceptor.start()}stop(){this.linkInterceptor.stop()}willFollowLinkToLocation(e,t,s){return this.delegate.willSubmitFormLinkToLocation(e,t,s)&&(e.hasAttribute("data-turbo-method")||e.hasAttribute("data-turbo-stream"))}followedLinkToLocation(e,t){const s=document.createElement("form");for(const[e,i]of t.searchParams)s.append(Object.assign(document.createElement("input"),{type:"hidden",name:e,value:i}));const i=Object.assign(t,{search:""});s.setAttribute("data-turbo","true"),s.setAttribute("action",i.href),s.setAttribute("hidden","");const r=e.getAttribute("data-turbo-method");r&&s.setAttribute("method",r);const n=e.getAttribute("data-turbo-frame");n&&s.setAttribute("data-turbo-frame",n);const o=L(e);o&&s.setAttribute("data-turbo-action",o);const a=e.getAttribute("data-turbo-confirm");a&&s.setAttribute("data-turbo-confirm",a);e.hasAttribute("data-turbo-stream")&&s.setAttribute("data-turbo-stream",""),this.delegate.submittedFormLinkToLocation(e,t,s),document.body.appendChild(s),s.addEventListener("turbo:submit-end",(()=>s.remove()),{once:!0}),requestAnimationFrame((()=>s.requestSubmit()))}}class ee{static async preservingPermanentElements(e,t,s){const i=new this(e,t);i.enter(),await s(),i.leave()}constructor(e,t){this.delegate=e,this.permanentElementMap=t}enter(){for(const e in this.permanentElementMap){const[t,s]=this.permanentElementMap[e];this.delegate.enteringBardo(t,s),this.replaceNewPermanentElementWithPlaceholder(s)}}leave(){for(const e in this.permanentElementMap){const[t]=this.permanentElementMap[e];this.replaceCurrentPermanentElementWithClone(t),this.replacePlaceholderWithPermanentElement(t),this.delegate.leavingBardo(t)}}replaceNewPermanentElementWithPlaceholder(e){const t=function(e){const t=document.createElement("meta");return t.setAttribute("name","turbo-permanent-placeholder"),t.setAttribute("content",e.id),t}(e);e.replaceWith(t)}replaceCurrentPermanentElementWithClone(e){const t=e.cloneNode(!0);e.replaceWith(t)}replacePlaceholderWithPermanentElement(e){const t=this.getPlaceholderById(e.id);t?.replaceWith(e)}getPlaceholderById(e){return this.placeholders.find((t=>t.content==e))}get placeholders(){return[...document.querySelectorAll("meta[name=turbo-permanent-placeholder][content]")]}}class te{#n=null;constructor(e,t,s,i,r=!0){this.currentSnapshot=e,this.newSnapshot=t,this.isPreview=i,this.willRender=r,this.renderElement=s,this.promise=new Promise(((e,t)=>this.resolvingFunctions={resolve:e,reject:t}))}get shouldRender(){return!0}get reloadReason(){}prepareToRender(){}render(){}finishRendering(){this.resolvingFunctions&&(this.resolvingFunctions.resolve(),delete this.resolvingFunctions)}async preservingPermanentElements(e){await ee.preservingPermanentElements(this,this.permanentElementMap,e)}focusFirstAutofocusableElement(){const e=this.connectedSnapshot.firstAutofocusableElement;e&&e.focus()}enteringBardo(e){this.#n||e.contains(this.currentSnapshot.activeElement)&&(this.#n=this.currentSnapshot.activeElement)}leavingBardo(e){e.contains(this.#n)&&this.#n instanceof HTMLElement&&(this.#n.focus(),this.#n=null)}get connectedSnapshot(){return this.newSnapshot.isConnected?this.newSnapshot:this.currentSnapshot}get currentElement(){return this.currentSnapshot.element}get newElement(){return this.newSnapshot.element}get permanentElementMap(){return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot)}get renderMethod(){return"replace"}}class se extends te{static renderElement(e,t){const s=document.createRange();s.selectNodeContents(e),s.deleteContents();const i=t,r=i.ownerDocument?.createRange();r&&(r.selectNodeContents(i),e.appendChild(r.extractContents()))}constructor(e,t,s,i,r,n=!0){super(t,s,i,r,n),this.delegate=e}get shouldRender(){return!0}async render(){await f(),this.preservingPermanentElements((()=>{this.loadFrameElement()})),this.scrollFrameIntoView(),await f(),this.focusFirstAutofocusableElement(),await f(),this.activateScriptElements()}loadFrameElement(){this.delegate.willRenderFrame(this.currentElement,this.newElement),this.renderElement(this.currentElement,this.newElement)}scrollFrameIntoView(){if(this.currentElement.autoscroll||this.newElement.autoscroll){const s=this.currentElement.firstElementChild,i=(e=this.currentElement.getAttribute("data-autoscroll-block"),t="end","end"==e||"start"==e||"center"==e||"nearest"==e?e:t),r=function(e,t){return"auto"==e||"smooth"==e?e:t}(this.currentElement.getAttribute("data-autoscroll-behavior"),"auto");if(s)return s.scrollIntoView({block:i,behavior:r}),!0}var e,t;return!1}activateScriptElements(){for(const e of this.newScriptElements){const t=m(e);e.replaceWith(t)}}get newScriptElements(){return this.currentElement.querySelectorAll("script")}}class ie{static animationDuration=300;static get defaultCSS(){return v`
5
+ !function(e){function t(e,t,s){throw new e("Failed to execute 'requestSubmit' on 'HTMLFormElement': "+t+".",s)}"function"!=typeof e.requestSubmit&&(e.requestSubmit=function(e){e?(!function(e,s){e instanceof HTMLElement||t(TypeError,"parameter 1 is not of type 'HTMLElement'"),"submit"==e.type||t(TypeError,"The specified element is not a submit button"),e.form==s||t(DOMException,"The specified element is not owned by this form element","NotFoundError")}(e,this),e.click()):((e=document.createElement("input")).type="submit",e.hidden=!0,this.appendChild(e),e.click(),this.removeChild(e))})}(HTMLFormElement.prototype);const e=new WeakMap;function t(t){const s=function(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null,s=t?t.closest("input, button"):null;return"submit"==s?.type?s:null}(t.target);s&&s.form&&e.set(s.form,s)}!function(){if("submitter"in Event.prototype)return;let s=window.Event.prototype;if("SubmitEvent"in window){const e=window.SubmitEvent.prototype;if(!/Apple Computer/.test(navigator.vendor)||"submitter"in e)return;s=e}addEventListener("click",t,!0),Object.defineProperty(s,"submitter",{get(){if("submit"==this.type&&this.target instanceof HTMLFormElement)return e.get(this.target)}})}();const s={eager:"eager",lazy:"lazy"};class i extends HTMLElement{static delegateConstructor=void 0;loaded=Promise.resolve();static get observedAttributes(){return["disabled","complete","loading","src"]}constructor(){super(),this.delegate=new i.delegateConstructor(this)}connectedCallback(){this.delegate.connect()}disconnectedCallback(){this.delegate.disconnect()}reload(){return this.delegate.sourceURLReloaded()}attributeChangedCallback(e){"loading"==e?this.delegate.loadingStyleChanged():"complete"==e?this.delegate.completeChanged():"src"==e?this.delegate.sourceURLChanged():this.delegate.disabledChanged()}get src(){return this.getAttribute("src")}set src(e){e?this.setAttribute("src",e):this.removeAttribute("src")}get refresh(){return this.getAttribute("refresh")}set refresh(e){e?this.setAttribute("refresh",e):this.removeAttribute("refresh")}get loading(){return function(e){if("lazy"===e.toLowerCase())return s.lazy;return s.eager}(this.getAttribute("loading")||"")}set loading(e){e?this.setAttribute("loading",e):this.removeAttribute("loading")}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get autoscroll(){return this.hasAttribute("autoscroll")}set autoscroll(e){e?this.setAttribute("autoscroll",""):this.removeAttribute("autoscroll")}get complete(){return!this.delegate.isLoading}get isActive(){return this.ownerDocument===document&&!this.isPreview}get isPreview(){return this.ownerDocument?.documentElement?.hasAttribute("data-turbo-preview")}}function r(e){return new URL(e.toString(),document.baseURI)}function n(e){let t;return e.hash?e.hash.slice(1):(t=e.href.match(/#(.*)$/))?t[1]:void 0}function o(e,t){return r(t?.getAttribute("formaction")||e.getAttribute("action")||e.action)}function a(e){return(function(e){return function(e){return e.pathname.split("/").slice(1)}(e).slice(-1)[0]}(e).match(/\.[^.]*$/)||[])[0]||""}function c(e,t){const s=function(e){return t=e.origin+e.pathname,t.endsWith("/")?t:t+"/";var t}(t);return e.href===r(s).href||e.href.startsWith(s)}function l(e,t){return c(e,t)&&!!a(e).match(/^(?:|\.(?:htm|html|xhtml|php))$/)}function h(e){const t=n(e);return null!=t?e.href.slice(0,-(t.length+1)):e.href}function d(e){return h(e)}class u{constructor(e){this.response=e}get succeeded(){return this.response.ok}get failed(){return!this.succeeded}get clientError(){return this.statusCode>=400&&this.statusCode<=499}get serverError(){return this.statusCode>=500&&this.statusCode<=599}get redirected(){return this.response.redirected}get location(){return r(this.response.url)}get isHTML(){return this.contentType&&this.contentType.match(/^(?:text\/([^\s;,]+\b)?html|application\/xhtml\+xml)\b/)}get statusCode(){return this.response.status}get contentType(){return this.header("Content-Type")}get responseText(){return this.response.clone().text()}get responseHTML(){return this.isHTML?this.response.clone().text():Promise.resolve(void 0)}header(e){return this.response.headers.get(e)}}function m(e){if("false"==e.getAttribute("data-turbo-eval"))return e;{const t=document.createElement("script"),s=P("csp-nonce");return s&&(t.nonce=s),t.textContent=e.textContent,t.async=!1,function(e,t){for(const{name:s,value:i}of t.attributes)e.setAttribute(s,i)}(t,e),t}}function p(e,{target:t,cancelable:s,detail:i}={}){const r=new CustomEvent(e,{cancelable:s,bubbles:!0,composed:!0,detail:i});return t&&t.isConnected?t.dispatchEvent(r):document.documentElement.dispatchEvent(r),r}function f(){return"hidden"===document.visibilityState?b():g()}function g(){return new Promise((e=>requestAnimationFrame((()=>e()))))}function b(){return new Promise((e=>setTimeout((()=>e()),0)))}function v(e=""){return(new DOMParser).parseFromString(e,"text/html")}function S(e,...t){const s=function(e,t){return e.reduce(((e,s,i)=>e+s+(null==t[i]?"":t[i])),"")}(e,t).replace(/^\n/,"").split("\n"),i=s[0].match(/^\s+/),r=i?i[0].length:0;return s.map((e=>e.slice(r))).join("\n")}function w(){return Array.from({length:36}).map(((e,t)=>8==t||13==t||18==t||23==t?"-":14==t?"4":19==t?(Math.floor(4*Math.random())+8).toString(16):Math.floor(15*Math.random()).toString(16))).join("")}function y(e,...t){for(const s of t.map((t=>t?.getAttribute(e))))if("string"==typeof s)return s;return null}function E(...e){for(const t of e)"turbo-frame"==t.localName&&t.setAttribute("busy",""),t.setAttribute("aria-busy","true")}function A(...e){for(const t of e)"turbo-frame"==t.localName&&t.removeAttribute("busy"),t.removeAttribute("aria-busy")}function R(e,t=2e3){return new Promise((s=>{const i=()=>{e.removeEventListener("error",i),e.removeEventListener("load",i),s()};e.addEventListener("load",i,{once:!0}),e.addEventListener("error",i,{once:!0}),setTimeout(s,t)}))}function L(e){switch(e){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}function C(...e){const t=y("data-turbo-action",...e);return function(e){return"advance"==e||"replace"==e||"restore"==e}(t)?t:null}function T(e){return document.querySelector(`meta[name="${e}"]`)}function P(e){const t=T(e);return t&&t.content}function k(e,t){if(e instanceof Element)return e.closest(t)||k(e.assignedSlot||e.getRootNode()?.host,t)}function M(e){return!!e&&null==e.closest("[inert], :disabled, [hidden], details:not([open]), dialog:not([open])")&&"function"==typeof e.focus}function F(e){return Array.from(e.querySelectorAll("[autofocus]")).find(M)}class I extends Set{constructor(e){super(),this.maxSize=e}add(e){if(this.size>=this.maxSize){const e=this.values().next().value;this.delete(e)}super.add(e)}}const H=new I(20),q=window.fetch;function B(e,t={}){const s=new Headers(t.headers||{}),i=w();return H.add(i),s.append("X-Turbo-Request-Id",i),q(e,{...t,headers:s})}function O(e){switch(e.toLowerCase()){case"get":return N.get;case"post":return N.post;case"put":return N.put;case"patch":return N.patch;case"delete":return N.delete}}const N={get:"get",post:"post",put:"put",patch:"patch",delete:"delete"};function x(e){switch(e.toLowerCase()){case V.multipart:return V.multipart;case V.plain:return V.plain;default:return V.urlEncoded}}const V={urlEncoded:"application/x-www-form-urlencoded",multipart:"multipart/form-data",plain:"text/plain"};class D{abortController=new AbortController;#e=e=>{};constructor(e,t,s,i=new URLSearchParams,n=null,o=V.urlEncoded){const[a,c]=U(r(s),t,i,o);this.delegate=e,this.url=a,this.target=n,this.fetchOptions={credentials:"same-origin",redirect:"follow",method:t,headers:{...this.defaultHeaders},body:c,signal:this.abortSignal,referrer:this.delegate.referrer?.href},this.enctype=o}get method(){return this.fetchOptions.method}set method(e){const t=this.isSafe?this.url.searchParams:this.fetchOptions.body||new FormData,s=O(e)||N.get;this.url.search="";const[i,r]=U(this.url,s,t,this.enctype);this.url=i,this.fetchOptions.body=r,this.fetchOptions.method=s}get headers(){return this.fetchOptions.headers}set headers(e){this.fetchOptions.headers=e}get body(){return this.isSafe?this.url.searchParams:this.fetchOptions.body}set body(e){this.fetchOptions.body=e}get location(){return this.url}get params(){return this.url.searchParams}get entries(){return this.body?Array.from(this.body.entries()):[]}cancel(){this.abortController.abort()}async perform(){const{fetchOptions:e}=this;this.delegate.prepareRequest(this),await this.#t(e);try{this.delegate.requestStarted(this);const t=await B(this.url.href,e);return await this.receive(t)}catch(e){if("AbortError"!==e.name)throw this.#s(e)&&this.delegate.requestErrored(this,e),e}finally{this.delegate.requestFinished(this)}}async receive(e){const t=new u(e);return p("turbo:before-fetch-response",{cancelable:!0,detail:{fetchResponse:t},target:this.target}).defaultPrevented?this.delegate.requestPreventedHandlingResponse(this,t):t.succeeded?this.delegate.requestSucceededWithResponse(this,t):this.delegate.requestFailedWithResponse(this,t),t}get defaultHeaders(){return{Accept:"text/html, application/xhtml+xml"}}get isSafe(){return W(this.method)}get abortSignal(){return this.abortController.signal}acceptResponseType(e){this.headers.Accept=[e,this.headers.Accept].join(", ")}async#t(e){const t=new Promise((e=>this.#e=e)),s=p("turbo:before-fetch-request",{cancelable:!0,detail:{fetchOptions:e,url:this.url,resume:this.#e},target:this.target});this.url=s.detail.url,s.defaultPrevented&&await t}#s(e){return!p("turbo:fetch-request-error",{target:this.target,cancelable:!0,detail:{request:this,error:e}}).defaultPrevented}}function W(e){return O(e)==N.get}function U(e,t,s,i){const r=Array.from(s).length>0?new URLSearchParams(_(s)):e.searchParams;return W(t)?[$(e,r),null]:i==V.urlEncoded?[e,r]:[e,s]}function _(e){const t=[];for(const[s,i]of e)i instanceof File||t.push([s,i]);return t}function $(e,t){const s=new URLSearchParams(_(t));return e.search=s.toString(),e}class j{started=!1;constructor(e,t){this.delegate=e,this.element=t,this.intersectionObserver=new IntersectionObserver(this.intersect)}start(){this.started||(this.started=!0,this.intersectionObserver.observe(this.element))}stop(){this.started&&(this.started=!1,this.intersectionObserver.unobserve(this.element))}intersect=e=>{const t=e.slice(-1)[0];t?.isIntersecting&&this.delegate.elementAppearedInViewport(this.element)}}class z{static contentType="text/vnd.turbo-stream.html";static wrap(e){return"string"==typeof e?new this(function(e){const t=document.createElement("template");return t.innerHTML=e,t.content}(e)):e}constructor(e){this.fragment=function(e){for(const t of e.querySelectorAll("turbo-stream")){const e=document.importNode(t,!0);for(const t of e.templateElement.content.querySelectorAll("script"))t.replaceWith(m(t));t.replaceWith(e)}return e}(e)}}const G={initialized:"initialized",requesting:"requesting",waiting:"waiting",receiving:"receiving",stopping:"stopping",stopped:"stopped"};class J{state=G.initialized;static confirmMethod(e,t,s){return Promise.resolve(confirm(e))}constructor(e,t,s,i=!1){const n=function(e,t){const s=t?.getAttribute("formmethod")||e.getAttribute("method")||"";return O(s.toLowerCase())||N.get}(t,s),o=function(e,t){const s=r(e);W(t)&&(s.search="");return s}(function(e,t){const s="string"==typeof e.action?e.action:null;return t?.hasAttribute("formaction")?t.getAttribute("formaction")||"":e.getAttribute("action")||s||""}(t,s),n),a=function(e,t){const s=new FormData(e),i=t?.getAttribute("name"),r=t?.getAttribute("value");i&&s.append(i,r||"");return s}(t,s),c=function(e,t){return x(t?.getAttribute("formenctype")||e.enctype)}(t,s);this.delegate=e,this.formElement=t,this.submitter=s,this.fetchRequest=new D(this,n,o,a,t,c),this.mustRedirect=i}get method(){return this.fetchRequest.method}set method(e){this.fetchRequest.method=e}get action(){return this.fetchRequest.url.toString()}set action(e){this.fetchRequest.url=r(e)}get body(){return this.fetchRequest.body}get enctype(){return this.fetchRequest.enctype}get isSafe(){return this.fetchRequest.isSafe}get location(){return this.fetchRequest.url}async start(){const{initialized:e,requesting:t}=G,s=y("data-turbo-confirm",this.submitter,this.formElement);if("string"==typeof s){if(!await J.confirmMethod(s,this.formElement,this.submitter))return}if(this.state==e)return this.state=t,this.fetchRequest.perform()}stop(){const{stopping:e,stopped:t}=G;if(this.state!=e&&this.state!=t)return this.state=e,this.fetchRequest.cancel(),!0}prepareRequest(e){if(!e.isSafe){const t=function(e){if(null!=e){const t=(document.cookie?document.cookie.split("; "):[]).find((t=>t.startsWith(e)));if(t){const e=t.split("=").slice(1).join("=");return e?decodeURIComponent(e):void 0}}}(P("csrf-param"))||P("csrf-token");t&&(e.headers["X-CSRF-Token"]=t)}this.requestAcceptsTurboStreamResponse(e)&&e.acceptResponseType(z.contentType)}requestStarted(e){this.state=G.waiting,this.submitter?.setAttribute("disabled",""),this.setSubmitsWith(),E(this.formElement),p("turbo:submit-start",{target:this.formElement,detail:{formSubmission:this}}),this.delegate.formSubmissionStarted(this)}requestPreventedHandlingResponse(e,t){this.result={success:t.succeeded,fetchResponse:t}}requestSucceededWithResponse(e,t){if(t.clientError||t.serverError)this.delegate.formSubmissionFailedWithResponse(this,t);else if(this.requestMustRedirect(e)&&function(e){return 200==e.statusCode&&!e.redirected}(t)){const e=new Error("Form responses must redirect to another location");this.delegate.formSubmissionErrored(this,e)}else this.state=G.receiving,this.result={success:!0,fetchResponse:t},this.delegate.formSubmissionSucceededWithResponse(this,t)}requestFailedWithResponse(e,t){this.result={success:!1,fetchResponse:t},this.delegate.formSubmissionFailedWithResponse(this,t)}requestErrored(e,t){this.result={success:!1,error:t},this.delegate.formSubmissionErrored(this,t)}requestFinished(e){this.state=G.stopped,this.submitter?.removeAttribute("disabled"),this.resetSubmitterText(),A(this.formElement),p("turbo:submit-end",{target:this.formElement,detail:{formSubmission:this,...this.result}}),this.delegate.formSubmissionFinished(this)}setSubmitsWith(){if(this.submitter&&this.submitsWith)if(this.submitter.matches("button"))this.originalSubmitText=this.submitter.innerHTML,this.submitter.innerHTML=this.submitsWith;else if(this.submitter.matches("input")){const e=this.submitter;this.originalSubmitText=e.value,e.value=this.submitsWith}}resetSubmitterText(){if(this.submitter&&this.originalSubmitText)if(this.submitter.matches("button"))this.submitter.innerHTML=this.originalSubmitText;else if(this.submitter.matches("input")){this.submitter.value=this.originalSubmitText}}requestMustRedirect(e){return!e.isSafe&&this.mustRedirect}requestAcceptsTurboStreamResponse(e){return!e.isSafe||function(e,...t){return t.some((t=>t&&t.hasAttribute(e)))}("data-turbo-stream",this.submitter,this.formElement)}get submitsWith(){return this.submitter?.getAttribute("data-turbo-submits-with")}}class K{constructor(e){this.element=e}get activeElement(){return this.element.ownerDocument.activeElement}get children(){return[...this.element.children]}hasAnchor(e){return null!=this.getElementForAnchor(e)}getElementForAnchor(e){return e?this.element.querySelector(`[id='${e}'], a[name='${e}']`):null}get isConnected(){return this.element.isConnected}get firstAutofocusableElement(){return F(this.element)}get permanentElements(){return Q(this.element)}getPermanentElementById(e){return X(this.element,e)}getPermanentElementMapForSnapshot(e){const t={};for(const s of this.permanentElements){const{id:i}=s,r=e.getPermanentElementById(i);r&&(t[i]=[s,r])}return t}}function X(e,t){return e.querySelector(`#${t}[data-turbo-permanent]`)}function Q(e){return e.querySelectorAll("[id][data-turbo-permanent]")}class Y{started=!1;constructor(e,t){this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.addEventListener("submit",this.submitCaptured,!0),this.started=!0)}stop(){this.started&&(this.eventTarget.removeEventListener("submit",this.submitCaptured,!0),this.started=!1)}submitCaptured=()=>{this.eventTarget.removeEventListener("submit",this.submitBubbled,!1),this.eventTarget.addEventListener("submit",this.submitBubbled,!1)};submitBubbled=e=>{if(!e.defaultPrevented){const t=e.target instanceof HTMLFormElement?e.target:void 0,s=e.submitter||void 0;t&&function(e,t){const s=t?.getAttribute("formmethod")||e.getAttribute("method");return"dialog"!=s}(t,s)&&function(e,t){if(t?.hasAttribute("formtarget")||e.hasAttribute("target")){const s=t?.getAttribute("formtarget")||e.target;for(const e of document.getElementsByName(s))if(e instanceof HTMLIFrameElement)return!1;return!0}return!0}(t,s)&&this.delegate.willSubmitForm(t,s)&&(e.preventDefault(),e.stopImmediatePropagation(),this.delegate.formSubmitted(t,s))}}}class Z{#i=e=>{};#r=e=>{};constructor(e,t){this.delegate=e,this.element=t}scrollToAnchor(e){const t=this.snapshot.getElementForAnchor(e);t?(this.scrollToElement(t),this.focusElement(t)):this.scrollToPosition({x:0,y:0})}scrollToAnchorFromLocation(e){this.scrollToAnchor(n(e))}scrollToElement(e){e.scrollIntoView()}focusElement(e){e instanceof HTMLElement&&(e.hasAttribute("tabindex")?e.focus():(e.setAttribute("tabindex","-1"),e.focus(),e.removeAttribute("tabindex")))}scrollToPosition({x:e,y:t}){this.scrollRoot.scrollTo(e,t)}scrollToTop(){this.scrollToPosition({x:0,y:0})}get scrollRoot(){return window}async render(e){const{isPreview:t,shouldRender:s,newSnapshot:i}=e;if(s)try{this.renderPromise=new Promise((e=>this.#i=e)),this.renderer=e,await this.prepareToRenderSnapshot(e);const s=new Promise((e=>this.#r=e)),r={resume:this.#r,render:this.renderer.renderElement};this.delegate.allowsImmediateRender(i,t,r)||await s,await this.renderSnapshot(e),this.delegate.viewRenderedSnapshot(i,t,this.renderer.renderMethod),this.delegate.preloadOnLoadLinksForView(this.element),this.finishRenderingSnapshot(e)}finally{delete this.renderer,this.#i(void 0),delete this.renderPromise}else this.invalidate(e.reloadReason)}invalidate(e){this.delegate.viewInvalidated(e)}async prepareToRenderSnapshot(e){this.markAsPreview(e.isPreview),await e.prepareToRender()}markAsPreview(e){e?this.element.setAttribute("data-turbo-preview",""):this.element.removeAttribute("data-turbo-preview")}markVisitDirection(e){this.element.setAttribute("data-turbo-visit-direction",e)}unmarkVisitDirection(){this.element.removeAttribute("data-turbo-visit-direction")}async renderSnapshot(e){await e.render()}finishRenderingSnapshot(e){e.finishRendering()}}class ee extends Z{missing(){this.element.innerHTML='<strong class="turbo-frame-error">Content missing</strong>'}get snapshot(){return new K(this.element)}}class te{constructor(e,t){this.delegate=e,this.element=t}start(){this.element.addEventListener("click",this.clickBubbled),document.addEventListener("turbo:click",this.linkClicked),document.addEventListener("turbo:before-visit",this.willVisit)}stop(){this.element.removeEventListener("click",this.clickBubbled),document.removeEventListener("turbo:click",this.linkClicked),document.removeEventListener("turbo:before-visit",this.willVisit)}clickBubbled=e=>{this.respondsToEventTarget(e.target)?this.clickEvent=e:delete this.clickEvent};linkClicked=e=>{this.clickEvent&&this.respondsToEventTarget(e.target)&&e.target instanceof Element&&this.delegate.shouldInterceptLinkClick(e.target,e.detail.url,e.detail.originalEvent)&&(this.clickEvent.preventDefault(),e.preventDefault(),this.delegate.linkClickIntercepted(e.target,e.detail.url,e.detail.originalEvent)),delete this.clickEvent};willVisit=e=>{delete this.clickEvent};respondsToEventTarget(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null;return t&&t.closest("turbo-frame, html")==this.element}}class se{started=!1;constructor(e,t){this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.addEventListener("click",this.clickCaptured,!0),this.started=!0)}stop(){this.started&&(this.eventTarget.removeEventListener("click",this.clickCaptured,!0),this.started=!1)}clickCaptured=()=>{this.eventTarget.removeEventListener("click",this.clickBubbled,!1),this.eventTarget.addEventListener("click",this.clickBubbled,!1)};clickBubbled=e=>{if(e instanceof MouseEvent&&this.clickEventIsSignificant(e)){const t=e.composedPath&&e.composedPath()[0]||e.target,s=this.findLinkFromClickTarget(t);if(s&&function(e){if(e.hasAttribute("target")){for(const t of document.getElementsByName(e.target))if(t instanceof HTMLIFrameElement)return!1;return!0}return!0}(s)){const t=this.getLocationForLink(s);this.delegate.willFollowLinkToLocation(s,t,e)&&(e.preventDefault(),this.delegate.followedLinkToLocation(s,t))}}};clickEventIsSignificant(e){return!(e.target&&e.target.isContentEditable||e.defaultPrevented||e.which>1||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)}findLinkFromClickTarget(e){return k(e,"a[href]:not([target^=_]):not([download])")}getLocationForLink(e){return r(e.getAttribute("href")||"")}}class ie{constructor(e,t){this.delegate=e,this.linkInterceptor=new se(this,t)}start(){this.linkInterceptor.start()}stop(){this.linkInterceptor.stop()}willFollowLinkToLocation(e,t,s){return this.delegate.willSubmitFormLinkToLocation(e,t,s)&&(e.hasAttribute("data-turbo-method")||e.hasAttribute("data-turbo-stream"))}followedLinkToLocation(e,t){const s=document.createElement("form");for(const[e,i]of t.searchParams)s.append(Object.assign(document.createElement("input"),{type:"hidden",name:e,value:i}));const i=Object.assign(t,{search:""});s.setAttribute("data-turbo","true"),s.setAttribute("action",i.href),s.setAttribute("hidden","");const r=e.getAttribute("data-turbo-method");r&&s.setAttribute("method",r);const n=e.getAttribute("data-turbo-frame");n&&s.setAttribute("data-turbo-frame",n);const o=C(e);o&&s.setAttribute("data-turbo-action",o);const a=e.getAttribute("data-turbo-confirm");a&&s.setAttribute("data-turbo-confirm",a);e.hasAttribute("data-turbo-stream")&&s.setAttribute("data-turbo-stream",""),this.delegate.submittedFormLinkToLocation(e,t,s),document.body.appendChild(s),s.addEventListener("turbo:submit-end",(()=>s.remove()),{once:!0}),requestAnimationFrame((()=>s.requestSubmit()))}}class re{static async preservingPermanentElements(e,t,s){const i=new this(e,t);i.enter(),await s(),i.leave()}constructor(e,t){this.delegate=e,this.permanentElementMap=t}enter(){for(const e in this.permanentElementMap){const[t,s]=this.permanentElementMap[e];this.delegate.enteringBardo(t,s),this.replaceNewPermanentElementWithPlaceholder(s)}}leave(){for(const e in this.permanentElementMap){const[t]=this.permanentElementMap[e];this.replaceCurrentPermanentElementWithClone(t),this.replacePlaceholderWithPermanentElement(t),this.delegate.leavingBardo(t)}}replaceNewPermanentElementWithPlaceholder(e){const t=function(e){const t=document.createElement("meta");return t.setAttribute("name","turbo-permanent-placeholder"),t.setAttribute("content",e.id),t}(e);e.replaceWith(t)}replaceCurrentPermanentElementWithClone(e){const t=e.cloneNode(!0);e.replaceWith(t)}replacePlaceholderWithPermanentElement(e){const t=this.getPlaceholderById(e.id);t?.replaceWith(e)}getPlaceholderById(e){return this.placeholders.find((t=>t.content==e))}get placeholders(){return[...document.querySelectorAll("meta[name=turbo-permanent-placeholder][content]")]}}class ne{#n=null;constructor(e,t,s,i,r=!0){this.currentSnapshot=e,this.newSnapshot=t,this.isPreview=i,this.willRender=r,this.renderElement=s,this.promise=new Promise(((e,t)=>this.resolvingFunctions={resolve:e,reject:t}))}get shouldRender(){return!0}get reloadReason(){}prepareToRender(){}render(){}finishRendering(){this.resolvingFunctions&&(this.resolvingFunctions.resolve(),delete this.resolvingFunctions)}async preservingPermanentElements(e){await re.preservingPermanentElements(this,this.permanentElementMap,e)}focusFirstAutofocusableElement(){const e=this.connectedSnapshot.firstAutofocusableElement;e&&e.focus()}enteringBardo(e){this.#n||e.contains(this.currentSnapshot.activeElement)&&(this.#n=this.currentSnapshot.activeElement)}leavingBardo(e){e.contains(this.#n)&&this.#n instanceof HTMLElement&&(this.#n.focus(),this.#n=null)}get connectedSnapshot(){return this.newSnapshot.isConnected?this.newSnapshot:this.currentSnapshot}get currentElement(){return this.currentSnapshot.element}get newElement(){return this.newSnapshot.element}get permanentElementMap(){return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot)}get renderMethod(){return"replace"}}class oe extends ne{static renderElement(e,t){const s=document.createRange();s.selectNodeContents(e),s.deleteContents();const i=t,r=i.ownerDocument?.createRange();r&&(r.selectNodeContents(i),e.appendChild(r.extractContents()))}constructor(e,t,s,i,r,n=!0){super(t,s,i,r,n),this.delegate=e}get shouldRender(){return!0}async render(){await f(),this.preservingPermanentElements((()=>{this.loadFrameElement()})),this.scrollFrameIntoView(),await f(),this.focusFirstAutofocusableElement(),await f(),this.activateScriptElements()}loadFrameElement(){this.delegate.willRenderFrame(this.currentElement,this.newElement),this.renderElement(this.currentElement,this.newElement)}scrollFrameIntoView(){if(this.currentElement.autoscroll||this.newElement.autoscroll){const s=this.currentElement.firstElementChild,i=(e=this.currentElement.getAttribute("data-autoscroll-block"),t="end","end"==e||"start"==e||"center"==e||"nearest"==e?e:t),r=function(e,t){return"auto"==e||"smooth"==e?e:t}(this.currentElement.getAttribute("data-autoscroll-behavior"),"auto");if(s)return s.scrollIntoView({block:i,behavior:r}),!0}var e,t;return!1}activateScriptElements(){for(const e of this.newScriptElements){const t=m(e);e.replaceWith(t)}}get newScriptElements(){return this.currentElement.querySelectorAll("script")}}class ae{static animationDuration=300;static get defaultCSS(){return S`
6
6
  .turbo-progress-bar {
7
7
  position: fixed;
8
8
  display: block;
@@ -12,11 +12,11 @@ Copyright © 2023 37signals LLC
12
12
  background: #0076ff;
13
13
  z-index: 2147483647;
14
14
  transition:
15
- width ${ie.animationDuration}ms ease-out,
16
- opacity ${ie.animationDuration/2}ms ${ie.animationDuration/2}ms ease-in;
15
+ width ${ae.animationDuration}ms ease-out,
16
+ opacity ${ae.animationDuration/2}ms ${ae.animationDuration/2}ms ease-in;
17
17
  transform: translate3d(0, 0, 0);
18
18
  }
19
- `}hiding=!1;value=0;visible=!1;constructor(){this.stylesheetElement=this.createStylesheetElement(),this.progressElement=this.createProgressElement(),this.installStylesheetElement(),this.setValue(0)}show(){this.visible||(this.visible=!0,this.installProgressElement(),this.startTrickling())}hide(){this.visible&&!this.hiding&&(this.hiding=!0,this.fadeProgressElement((()=>{this.uninstallProgressElement(),this.stopTrickling(),this.visible=!1,this.hiding=!1})))}setValue(e){this.value=e,this.refresh()}installStylesheetElement(){document.head.insertBefore(this.stylesheetElement,document.head.firstChild)}installProgressElement(){this.progressElement.style.width="0",this.progressElement.style.opacity="1",document.documentElement.insertBefore(this.progressElement,document.body),this.refresh()}fadeProgressElement(e){this.progressElement.style.opacity="0",setTimeout(e,1.5*ie.animationDuration)}uninstallProgressElement(){this.progressElement.parentNode&&document.documentElement.removeChild(this.progressElement)}startTrickling(){this.trickleInterval||(this.trickleInterval=window.setInterval(this.trickle,ie.animationDuration))}stopTrickling(){window.clearInterval(this.trickleInterval),delete this.trickleInterval}trickle=()=>{this.setValue(this.value+Math.random()/100)};refresh(){requestAnimationFrame((()=>{this.progressElement.style.width=10+90*this.value+"%"}))}createStylesheetElement(){const e=document.createElement("style");return e.type="text/css",e.textContent=ie.defaultCSS,this.cspNonce&&(e.nonce=this.cspNonce),e}createProgressElement(){const e=document.createElement("div");return e.className="turbo-progress-bar",e}get cspNonce(){return T("csp-nonce")}}class re extends j{detailsByOuterHTML=this.children.filter((e=>!function(e){const t=e.localName;return"noscript"==t}(e))).map((e=>function(e){e.hasAttribute("nonce")&&e.setAttribute("nonce","");return e}(e))).reduce(((e,t)=>{const{outerHTML:s}=t,i=s in e?e[s]:{type:ne(t),tracked:oe(t),elements:[]};return{...e,[s]:{...i,elements:[...i.elements,t]}}}),{});get trackedElementSignature(){return Object.keys(this.detailsByOuterHTML).filter((e=>this.detailsByOuterHTML[e].tracked)).join("")}getScriptElementsNotInSnapshot(e){return this.getElementsMatchingTypeNotInSnapshot("script",e)}getStylesheetElementsNotInSnapshot(e){return this.getElementsMatchingTypeNotInSnapshot("stylesheet",e)}getElementsMatchingTypeNotInSnapshot(e,t){return Object.keys(this.detailsByOuterHTML).filter((e=>!(e in t.detailsByOuterHTML))).map((e=>this.detailsByOuterHTML[e])).filter((({type:t})=>t==e)).map((({elements:[e]})=>e))}get provisionalElements(){return Object.keys(this.detailsByOuterHTML).reduce(((e,t)=>{const{type:s,tracked:i,elements:r}=this.detailsByOuterHTML[t];return null!=s||i?r.length>1?[...e,...r.slice(1)]:e:[...e,...r]}),[])}getMetaValue(e){const t=this.findMetaElementByName(e);return t?t.getAttribute("content"):null}findMetaElementByName(e){return Object.keys(this.detailsByOuterHTML).reduce(((t,s)=>{const{elements:[i]}=this.detailsByOuterHTML[s];return function(e,t){const s=e.localName;return"meta"==s&&e.getAttribute("name")==t}(i,e)?i:t}),0)}}function ne(e){return function(e){const t=e.localName;return"script"==t}(e)?"script":function(e){const t=e.localName;return"style"==t||"link"==t&&"stylesheet"==e.getAttribute("rel")}(e)?"stylesheet":void 0}function oe(e){return"reload"==e.getAttribute("data-turbo-track")}class ae extends j{static fromHTMLString(e=""){return this.fromDocument(b(e))}static fromElement(e){return this.fromDocument(e.ownerDocument)}static fromDocument({documentElement:e,body:t,head:s}){return new this(e,t,new re(s))}constructor(e,t,s){super(t),this.documentElement=e,this.headSnapshot=s}clone(){const e=this.element.cloneNode(!0),t=this.element.querySelectorAll("select"),s=e.querySelectorAll("select");for(const[e,i]of t.entries()){const t=s[e];for(const e of t.selectedOptions)e.selected=!1;for(const e of i.selectedOptions)t.options[e.index].selected=!0}for(const t of e.querySelectorAll('input[type="password"]'))t.value="";return new ae(this.documentElement,e,this.headSnapshot)}get lang(){return this.documentElement.getAttribute("lang")}get headElement(){return this.headSnapshot.element}get rootLocation(){return r(this.getSetting("root")??"/")}get cacheControlValue(){return this.getSetting("cache-control")}get isPreviewable(){return"no-preview"!=this.cacheControlValue}get isCacheable(){return"no-cache"!=this.cacheControlValue}get isVisitable(){return"reload"!=this.getSetting("visit-control")}get prefersViewTransitions(){return"same-origin"===this.headSnapshot.getMetaValue("view-transition")}get shouldMorphPage(){return"morph"===this.getSetting("refresh-method")}get shouldPreserveScrollPosition(){return"preserve"===this.getSetting("refresh-scroll")}getSetting(e){return this.headSnapshot.getMetaValue(`turbo-${e}`)}}class ce{#o=!1;#a=Promise.resolve();renderChange(e,t){return e&&this.viewTransitionsAvailable&&!this.#o?(this.#o=!0,this.#a=this.#a.then((async()=>{await document.startViewTransition(t).finished}))):this.#a=this.#a.then(t),this.#a}get viewTransitionsAvailable(){return document.startViewTransition}}const le={action:"advance",historyChanged:!1,visitCachedSnapshot:()=>{},willRender:!0,updateHistory:!0,shouldCacheSnapshot:!0,acceptsStreamResponse:!1},he="visitStart",de="requestStart",ue="requestEnd",me="visitEnd",pe="initialized",fe="started",ge="canceled",be="failed",ve="completed",Se=0,we=-1,ye=-2;class Ee{identifier=S();timingMetrics={};followedRedirect=!1;historyChanged=!1;scrolled=!1;shouldCacheSnapshot=!0;acceptsStreamResponse=!1;snapshotCached=!1;state=pe;viewTransitioner=new ce;constructor(e,t,s,i={}){this.delegate=e,this.location=t,this.restorationIdentifier=s||S();const{action:r,historyChanged:n,referrer:o,snapshot:a,snapshotHTML:c,response:l,visitCachedSnapshot:h,willRender:d,updateHistory:u,shouldCacheSnapshot:m,acceptsStreamResponse:p}={...le,...i};this.action=r,this.historyChanged=n,this.referrer=o,this.snapshot=a,this.snapshotHTML=c,this.response=l,this.isSamePage=this.delegate.locationWithActionIsSamePage(this.location,this.action),this.visitCachedSnapshot=h,this.willRender=d,this.updateHistory=u,this.scrolled=!d,this.shouldCacheSnapshot=m,this.acceptsStreamResponse=p}get adapter(){return this.delegate.adapter}get view(){return this.delegate.view}get history(){return this.delegate.history}get restorationData(){return this.history.getRestorationDataForIdentifier(this.restorationIdentifier)}get silent(){return this.isSamePage}start(){this.state==pe&&(this.recordTimingMetric(he),this.state=fe,this.adapter.visitStarted(this),this.delegate.visitStarted(this))}cancel(){this.state==fe&&(this.request&&this.request.cancel(),this.cancelRender(),this.state=ge)}complete(){this.state==fe&&(this.recordTimingMetric(me),this.state=ve,this.followRedirect(),this.followedRedirect||(this.adapter.visitCompleted(this),this.delegate.visitCompleted(this)))}fail(){this.state==fe&&(this.state=be,this.adapter.visitFailed(this),this.delegate.visitCompleted(this))}changeHistory(){if(!this.historyChanged&&this.updateHistory){const e=A(this.location.href===this.referrer?.href?"replace":this.action);this.history.update(e,this.location,this.restorationIdentifier),this.historyChanged=!0}}issueRequest(){this.hasPreloadedResponse()?this.simulateRequest():this.shouldIssueRequest()&&!this.request&&(this.request=new O(this,H.get,this.location),this.request.perform())}simulateRequest(){this.response&&(this.startRequest(),this.recordResponse(),this.finishRequest())}startRequest(){this.recordTimingMetric(de),this.adapter.visitRequestStarted(this)}recordResponse(e=this.response){if(this.response=e,e){const{statusCode:t}=e;Re(t)?this.adapter.visitRequestCompleted(this):this.adapter.visitRequestFailedWithStatusCode(this,t)}}finishRequest(){this.recordTimingMetric(ue),this.adapter.visitRequestFinished(this)}loadResponse(){if(this.response){const{statusCode:e,responseHTML:t}=this.response;this.render((async()=>{if(this.shouldCacheSnapshot&&this.cacheSnapshot(),this.view.renderPromise&&await this.view.renderPromise,Re(e)&&null!=t){const e=ae.fromHTMLString(t);await this.renderPageSnapshot(e,!1),this.adapter.visitRendered(this),this.complete()}else await this.view.renderError(ae.fromHTMLString(t),this),this.adapter.visitRendered(this),this.fail()}))}}getCachedSnapshot(){const e=this.view.getCachedSnapshotForLocation(this.location)||this.getPreloadedSnapshot();if(e&&(!n(this.location)||e.hasAnchor(n(this.location)))&&("restore"==this.action||e.isPreviewable))return e}getPreloadedSnapshot(){if(this.snapshotHTML)return ae.fromHTMLString(this.snapshotHTML)}hasCachedSnapshot(){return null!=this.getCachedSnapshot()}loadCachedSnapshot(){const e=this.getCachedSnapshot();if(e){const t=this.shouldIssueRequest();this.render((async()=>{this.cacheSnapshot(),this.isSamePage?this.adapter.visitRendered(this):(this.view.renderPromise&&await this.view.renderPromise,await this.renderPageSnapshot(e,t),this.adapter.visitRendered(this),t||this.complete())}))}}followRedirect(){this.redirectedToLocation&&!this.followedRedirect&&this.response?.redirected&&(this.adapter.visitProposedToLocation(this.redirectedToLocation,{action:"replace",response:this.response,shouldCacheSnapshot:!1,willRender:!1}),this.followedRedirect=!0)}goToSamePageAnchor(){this.isSamePage&&this.render((async()=>{this.cacheSnapshot(),this.performScroll(),this.changeHistory(),this.adapter.visitRendered(this)}))}prepareRequest(e){this.acceptsStreamResponse&&e.acceptResponseType(U.contentType)}requestStarted(){this.startRequest()}requestPreventedHandlingResponse(e,t){}async requestSucceededWithResponse(e,t){const s=await t.responseHTML,{redirected:i,statusCode:r}=t;null==s?this.recordResponse({statusCode:ye,redirected:i}):(this.redirectedToLocation=t.redirected?t.location:void 0,this.recordResponse({statusCode:r,responseHTML:s,redirected:i}))}async requestFailedWithResponse(e,t){const s=await t.responseHTML,{redirected:i,statusCode:r}=t;null==s?this.recordResponse({statusCode:ye,redirected:i}):this.recordResponse({statusCode:r,responseHTML:s,redirected:i})}requestErrored(e,t){this.recordResponse({statusCode:Se,redirected:!1})}requestFinished(){this.finishRequest()}performScroll(){this.scrolled||this.view.forceReloaded||this.view.snapshot.shouldPreserveScrollPosition||("restore"==this.action?this.scrollToRestoredPosition()||this.scrollToAnchor()||this.view.scrollToTop():this.scrollToAnchor()||this.view.scrollToTop(),this.isSamePage&&this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation,this.location),this.scrolled=!0)}scrollToRestoredPosition(){const{scrollPosition:e}=this.restorationData;if(e)return this.view.scrollToPosition(e),!0}scrollToAnchor(){const e=n(this.location);if(null!=e)return this.view.scrollToAnchor(e),!0}recordTimingMetric(e){this.timingMetrics[e]=(new Date).getTime()}getTimingMetrics(){return{...this.timingMetrics}}getHistoryMethodForAction(e){switch(e){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}hasPreloadedResponse(){return"object"==typeof this.response}shouldIssueRequest(){return!this.isSamePage&&("restore"==this.action?!this.hasCachedSnapshot():this.willRender)}cacheSnapshot(){this.snapshotCached||(this.view.cacheSnapshot(this.snapshot).then((e=>e&&this.visitCachedSnapshot(e))),this.snapshotCached=!0)}async render(e){this.cancelRender(),await new Promise((e=>{this.frame=requestAnimationFrame((()=>e()))})),await e(),delete this.frame}async renderPageSnapshot(e,t){await this.viewTransitioner.renderChange(this.view.shouldTransitionTo(e),(async()=>{await this.view.renderPage(e,t,this.willRender,this),this.performScroll()}))}cancelRender(){this.frame&&(cancelAnimationFrame(this.frame),delete this.frame)}}function Re(e){return e>=200&&e<300}class Ae{progressBar=new ie;constructor(e){this.session=e}visitProposedToLocation(e,t){l(e,this.navigator.rootLocation)?this.navigator.startVisit(e,t?.restorationIdentifier||S(),t):window.location.href=e.toString()}visitStarted(e){this.location=e.location,e.loadCachedSnapshot(),e.issueRequest(),e.goToSamePageAnchor()}visitRequestStarted(e){this.progressBar.setValue(0),e.hasCachedSnapshot()||"restore"!=e.action?this.showVisitProgressBarAfterDelay():this.showProgressBar()}visitRequestCompleted(e){e.loadResponse()}visitRequestFailedWithStatusCode(e,t){switch(t){case Se:case we:case ye:return this.reload({reason:"request_failed",context:{statusCode:t}});default:return e.loadResponse()}}visitRequestFinished(e){}visitCompleted(e){this.progressBar.setValue(1),this.hideVisitProgressBar()}pageInvalidated(e){this.reload(e)}visitFailed(e){this.progressBar.setValue(1),this.hideVisitProgressBar()}visitRendered(e){}formSubmissionStarted(e){this.progressBar.setValue(0),this.showFormProgressBarAfterDelay()}formSubmissionFinished(e){this.progressBar.setValue(1),this.hideFormProgressBar()}showVisitProgressBarAfterDelay(){this.visitProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay)}hideVisitProgressBar(){this.progressBar.hide(),null!=this.visitProgressBarTimeout&&(window.clearTimeout(this.visitProgressBarTimeout),delete this.visitProgressBarTimeout)}showFormProgressBarAfterDelay(){null==this.formProgressBarTimeout&&(this.formProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay))}hideFormProgressBar(){this.progressBar.hide(),null!=this.formProgressBarTimeout&&(window.clearTimeout(this.formProgressBarTimeout),delete this.formProgressBarTimeout)}showProgressBar=()=>{this.progressBar.show()};reload(e){p("turbo:reload",{detail:e}),window.location.href=this.location?.toString()||window.location.href}get navigator(){return this.session.navigator}}class Le{selector="[data-turbo-temporary]";deprecatedSelector="[data-turbo-cache=false]";started=!1;start(){this.started||(this.started=!0,addEventListener("turbo:before-cache",this.removeTemporaryElements,!1))}stop(){this.started&&(this.started=!1,removeEventListener("turbo:before-cache",this.removeTemporaryElements,!1))}removeTemporaryElements=e=>{for(const e of this.temporaryElements)e.remove()};get temporaryElements(){return[...document.querySelectorAll(this.selector),...this.temporaryElementsWithDeprecation]}get temporaryElementsWithDeprecation(){const e=document.querySelectorAll(this.deprecatedSelector);return e.length&&console.warn(`The ${this.deprecatedSelector} selector is deprecated and will be removed in a future version. Use ${this.selector} instead.`),[...e]}}class Ce{constructor(e,t){this.session=e,this.element=t,this.linkInterceptor=new Q(this,t),this.formSubmitObserver=new J(this,t)}start(){this.linkInterceptor.start(),this.formSubmitObserver.start()}stop(){this.linkInterceptor.stop(),this.formSubmitObserver.stop()}shouldInterceptLinkClick(e,t,s){return this.#c(e)}linkClickIntercepted(e,t,s){const i=this.#l(e);i&&i.delegate.linkClickIntercepted(e,t,s)}willSubmitForm(e,t){return null==e.closest("turbo-frame")&&this.#h(e,t)&&this.#c(e,t)}formSubmitted(e,t){const s=this.#l(e,t);s&&s.delegate.formSubmitted(e,t)}#h(e,t){const s=o(e,t),i=this.element.ownerDocument.querySelector('meta[name="turbo-root"]'),n=r(i?.content??"/");return this.#c(e,t)&&l(s,n)}#c(e,t){if(e instanceof HTMLFormElement?this.session.submissionIsNavigatable(e,t):this.session.elementIsNavigatable(e)){const s=this.#l(e,t);return!!s&&s!=e.closest("turbo-frame")}return!1}#l(e,t){const s=t?.getAttribute("data-turbo-frame")||e.getAttribute("data-turbo-frame");if(s&&"_top"!=s){const e=this.element.querySelector(`#${s}:not([disabled])`);if(e instanceof i)return e}}}class Te{location;restorationIdentifier=S();restorationData={};started=!1;pageLoaded=!1;constructor(e){this.delegate=e}start(){this.started||(addEventListener("popstate",this.onPopState,!1),addEventListener("load",this.onPageLoad,!1),this.started=!0,this.replace(new URL(window.location.href)))}stop(){this.started&&(removeEventListener("popstate",this.onPopState,!1),removeEventListener("load",this.onPageLoad,!1),this.started=!1)}push(e,t){this.update(history.pushState,e,t)}replace(e,t){this.update(history.replaceState,e,t)}update(e,t,s=S()){const i={turbo:{restorationIdentifier:s}};e.call(history,i,"",t.href),this.location=t,this.restorationIdentifier=s}getRestorationDataForIdentifier(e){return this.restorationData[e]||{}}updateRestorationData(e){const{restorationIdentifier:t}=this,s=this.restorationData[t];this.restorationData[t]={...s,...e}}assumeControlOfScrollRestoration(){this.previousScrollRestoration||(this.previousScrollRestoration=history.scrollRestoration??"auto",history.scrollRestoration="manual")}relinquishControlOfScrollRestoration(){this.previousScrollRestoration&&(history.scrollRestoration=this.previousScrollRestoration,delete this.previousScrollRestoration)}onPopState=e=>{if(this.shouldHandlePopState()){const{turbo:t}=e.state||{};if(t){this.location=new URL(window.location.href);const{restorationIdentifier:e}=t;this.restorationIdentifier=e,this.delegate.historyPoppedToLocationWithRestorationIdentifier(this.location,e)}}};onPageLoad=async e=>{await Promise.resolve(),this.pageLoaded=!0};shouldHandlePopState(){return this.pageIsLoaded()}pageIsLoaded(){return this.pageLoaded||"complete"==document.readyState}}class Pe{constructor(e){this.delegate=e}proposeVisit(e,t={}){this.delegate.allowsVisitingLocationWithAction(e,t.action)&&this.delegate.visitProposedToLocation(e,t)}startVisit(e,t,s={}){this.stop(),this.currentVisit=new Ee(this,r(e),t,{referrer:this.location,...s}),this.currentVisit.start()}submitForm(e,t){this.stop(),this.formSubmission=new $(this,e,t,!0),this.formSubmission.start()}stop(){this.formSubmission&&(this.formSubmission.stop(),delete this.formSubmission),this.currentVisit&&(this.currentVisit.cancel(),delete this.currentVisit)}get adapter(){return this.delegate.adapter}get view(){return this.delegate.view}get rootLocation(){return this.view.snapshot.rootLocation}get history(){return this.delegate.history}formSubmissionStarted(e){"function"==typeof this.adapter.formSubmissionStarted&&this.adapter.formSubmissionStarted(e)}async formSubmissionSucceededWithResponse(e,t){if(e==this.formSubmission){const s=await t.responseHTML;if(s){const i=e.isSafe;i||this.view.clearSnapshotCache();const{statusCode:r,redirected:n}=t,o={action:this.#d(e,t),shouldCacheSnapshot:i,response:{statusCode:r,responseHTML:s,redirected:n}};this.proposeVisit(t.location,o)}}}async formSubmissionFailedWithResponse(e,t){const s=await t.responseHTML;if(s){const e=ae.fromHTMLString(s);t.serverError?await this.view.renderError(e,this.currentVisit):await this.view.renderPage(e,!1,!0,this.currentVisit),e.shouldPreserveScrollPosition||this.view.scrollToTop(),this.view.clearSnapshotCache()}}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished(e){"function"==typeof this.adapter.formSubmissionFinished&&this.adapter.formSubmissionFinished(e)}visitStarted(e){this.delegate.visitStarted(e)}visitCompleted(e){this.delegate.visitCompleted(e)}locationWithActionIsSamePage(e,t){const s=n(e),i=n(this.view.lastRenderedLocation),r="restore"===t&&void 0===s;return"replace"!==t&&h(e)===h(this.view.lastRenderedLocation)&&(r||null!=s&&s!==i)}visitScrolledToSamePageLocation(e,t){this.delegate.visitScrolledToSamePageLocation(e,t)}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}#d(e,t){const{submitter:s,formElement:i}=e;return L(s,i)||this.#u(t)}#u(e){return e.redirected&&e.location.href===this.location?.href?"replace":"advance"}}const ke=0,Me=1,Fe=2,Ie=3;class He{stage=ke;started=!1;constructor(e){this.delegate=e}start(){this.started||(this.stage==ke&&(this.stage=Me),document.addEventListener("readystatechange",this.interpretReadyState,!1),addEventListener("pagehide",this.pageWillUnload,!1),this.started=!0)}stop(){this.started&&(document.removeEventListener("readystatechange",this.interpretReadyState,!1),removeEventListener("pagehide",this.pageWillUnload,!1),this.started=!1)}interpretReadyState=()=>{const{readyState:e}=this;"interactive"==e?this.pageIsInteractive():"complete"==e&&this.pageIsComplete()};pageIsInteractive(){this.stage==Me&&(this.stage=Fe,this.delegate.pageBecameInteractive())}pageIsComplete(){this.pageIsInteractive(),this.stage==Fe&&(this.stage=Ie,this.delegate.pageLoaded())}pageWillUnload=()=>{this.delegate.pageWillUnload()};get readyState(){return document.readyState}}class qe{started=!1;constructor(e){this.delegate=e}start(){this.started||(addEventListener("scroll",this.onScroll,!1),this.onScroll(),this.started=!0)}stop(){this.started&&(removeEventListener("scroll",this.onScroll,!1),this.started=!1)}onScroll=()=>{this.updatePosition({x:window.pageXOffset,y:window.pageYOffset})};updatePosition(e){this.delegate.scrollPositionChanged(e)}}class Be{render({fragment:e}){ee.preservingPermanentElements(this,function(e){const t=G(document.documentElement),s={};for(const i of t){const{id:t}=i;for(const r of e.querySelectorAll("turbo-stream")){const e=z(r.templateElement.content,t);e&&(s[t]=[i,e])}}return s}(e),(()=>{!async function(e,t){const s=`turbo-stream-autofocus-${S()}`,i=e.querySelectorAll("turbo-stream"),r=function(e){for(const t of e){const e=M(t.templateElement.content);if(e)return e}return null}(i);let n=null;r&&(n=r.id?r.id:s,r.id=n);t(),await f();if((null==document.activeElement||document.activeElement==document.body)&&n){const e=document.getElementById(n);k(e)&&e.focus(),e&&e.id==s&&e.removeAttribute("id")}}(e,(()=>{!async function(e){const[t,s]=await async function(e,t){const s=t();return e(),await f(),[s,t()]}(e,(()=>document.activeElement)),i=t&&t.id;if(i){const e=document.getElementById(i);k(e)&&e!=s&&e.focus()}}((()=>{document.documentElement.appendChild(e)}))}))}))}enteringBardo(e,t){t.replaceWith(e.cloneNode(!0))}leavingBardo(){}}class Oe{sources=new Set;#m=!1;constructor(e){this.delegate=e}start(){this.#m||(this.#m=!0,addEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}stop(){this.#m&&(this.#m=!1,removeEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}connectStreamSource(e){this.streamSourceIsConnected(e)||(this.sources.add(e),e.addEventListener("message",this.receiveMessageEvent,!1))}disconnectStreamSource(e){this.streamSourceIsConnected(e)&&(this.sources.delete(e),e.removeEventListener("message",this.receiveMessageEvent,!1))}streamSourceIsConnected(e){return this.sources.has(e)}inspectFetchResponse=e=>{const t=function(e){const t=e.detail?.fetchResponse;if(t instanceof u)return t}(e);t&&function(e){const t=e.contentType??"";return t.startsWith(U.contentType)}(t)&&(e.preventDefault(),this.receiveMessageResponse(t))};receiveMessageEvent=e=>{this.#m&&"string"==typeof e.data&&this.receiveMessageHTML(e.data)};async receiveMessageResponse(e){const t=await e.responseHTML;t&&this.receiveMessageHTML(t)}receiveMessageHTML(e){this.delegate.receivedMessageFromStream(U.wrap(e))}}class Ne extends te{static renderElement(e,t){const{documentElement:s,body:i}=document;s.replaceChild(t,i)}async render(){this.replaceHeadAndBody(),this.activateScriptElements()}replaceHeadAndBody(){const{documentElement:e,head:t}=document;e.replaceChild(this.newHead,t),this.renderElement(this.currentElement,this.newElement)}activateScriptElements(){for(const e of this.scriptElements){const t=e.parentNode;if(t){const s=m(e);t.replaceChild(s,e)}}}get newHead(){return this.newSnapshot.headSnapshot.element}get scriptElements(){return document.documentElement.querySelectorAll("script")}}let xe=new Set;function Ve(e,t,s){if(s.head.block){let i=e.querySelector("head"),r=t.querySelector("head");if(i&&r){let n=_e(r,i,s);return void Promise.all(n).then((function(){Ve(e,t,Object.assign(s,{head:{block:!1,ignore:!0}}))}))}}if("innerHTML"===s.morphStyle)return De(t,e,s),e.children;if("outerHTML"===s.morphStyle||null==s.morphStyle){let i=function(e,t,s){let i;i=e.firstChild;let r=i,n=0;for(;i;){let e=Xe(i,t,s);e>n&&(r=i,n=e),i=i.nextSibling}return r}(t,e,s),r=i?.previousSibling,n=i?.nextSibling,o=We(e,i,s);return i?function(e,t,s){let i=[],r=[];for(;null!=e;)i.push(e),e=e.previousSibling;for(;i.length>0;){let e=i.pop();r.push(e),t.parentElement.insertBefore(e,t)}r.push(t);for(;null!=s;)i.push(s),r.push(s),s=s.nextSibling;for(;i.length>0;)t.parentElement.insertBefore(i.pop(),t.nextSibling);return r}(r,o,n):[]}throw"Do not understand how to morph style "+s.morphStyle}function We(e,t,s){if(!s.ignoreActive||e!==document.activeElement){if(null==t){if(!1===s.callbacks.beforeNodeRemoved(e))return;return e.remove(),s.callbacks.afterNodeRemoved(e),null}if(ze(e,t)){if(!1===s.callbacks.beforeNodeMorphed(e,t))return;return e instanceof HTMLHeadElement&&s.head.ignore||(e instanceof HTMLHeadElement&&"morph"!==s.head.style?_e(t,e,s):(!function(e,t){let s=e.nodeType;if(1===s){const s=e.attributes,i=t.attributes;for(const e of s)t.getAttribute(e.name)!==e.value&&t.setAttribute(e.name,e.value);for(const s of i)e.hasAttribute(s.name)||t.removeAttribute(s.name)}8!==s&&3!==s||t.nodeValue!==e.nodeValue&&(t.nodeValue=e.nodeValue);if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==e.type)t.value=e.value||"",Ue(e,t,"value"),Ue(e,t,"checked"),Ue(e,t,"disabled");else if(e instanceof HTMLOptionElement)Ue(e,t,"selected");else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let s=e.value;s!==t.value&&(t.value=s),t.firstChild&&t.firstChild.nodeValue!==s&&(t.firstChild.nodeValue=s)}}(t,e),De(t,e,s))),s.callbacks.afterNodeMorphed(e,t),e}if(!1===s.callbacks.beforeNodeRemoved(e))return;if(!1===s.callbacks.beforeNodeAdded(t))return;return e.parentElement.replaceChild(t,e),s.callbacks.afterNodeAdded(t),s.callbacks.afterNodeRemoved(e),t}}function De(e,t,s){let i,r=e.firstChild,n=t.firstChild;for(;r;){if(i=r,r=i.nextSibling,null==n){if(!1===s.callbacks.beforeNodeAdded(i))return;t.appendChild(i),s.callbacks.afterNodeAdded(i),et(s,i);continue}if(je(i,n,s)){We(n,i,s),n=n.nextSibling,et(s,i);continue}let o=Je(e,t,i,n,s);if(o){n=Ge(n,o,s),We(o,i,s),et(s,i);continue}let a=Ke(e,t,i,n,s);if(a)n=Ge(n,a,s),We(a,i,s),et(s,i);else{if(!1===s.callbacks.beforeNodeAdded(i))return;t.insertBefore(i,n),s.callbacks.afterNodeAdded(i),et(s,i)}}for(;null!==n;){let e=n;n=n.nextSibling,Qe(e,s)}}function Ue(e,t,s){e[s]!==t[s]&&(e[s]?t.setAttribute(s,e[s]):t.removeAttribute(s))}function _e(e,t,s){let i=[],r=[],n=[],o=[],a=s.head.style,c=new Map;for(const t of e.children)c.set(t.outerHTML,t);for(const e of t.children){let t=c.has(e.outerHTML),i=s.head.shouldReAppend(e),l=s.head.shouldPreserve(e);t||l?i?r.push(e):(c.delete(e.outerHTML),n.push(e)):"append"===a?i&&(r.push(e),o.push(e)):!1!==s.head.shouldRemove(e)&&r.push(e)}o.push(...c.values());let l=[];for(const e of o){let r=document.createRange().createContextualFragment(e.outerHTML).firstChild;if(!1!==s.callbacks.beforeNodeAdded(r)){if(r.href||r.src){let e=null,t=new Promise((function(t){e=t}));r.addEventListener("load",(function(){e()})),l.push(t)}t.appendChild(r),s.callbacks.afterNodeAdded(r),i.push(r)}}for(const e of r)!1!==s.callbacks.beforeNodeRemoved(e)&&(t.removeChild(e),s.callbacks.afterNodeRemoved(e));return s.head.afterHeadMorphed(t,{added:i,kept:n,removed:r}),l}function $e(){}function je(e,t,s){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName&&(""!==e.id&&e.id===t.id||tt(s,e,t)>0))}function ze(e,t){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName)}function Ge(e,t,s){for(;e!==t;){let t=e;e=e.nextSibling,Qe(t,s)}return et(s,t),t.nextSibling}function Je(e,t,s,i,r){let n=tt(r,s,t);if(n>0){let t=i,o=0;for(;null!=t;){if(je(s,t,r))return t;if(o+=tt(r,t,e),o>n)return null;t=t.nextSibling}}return null}function Ke(e,t,s,i,r){let n=i,o=s.nextSibling,a=0;for(;null!=n;){if(tt(r,n,e)>0)return null;if(ze(s,n))return n;if(ze(o,n)&&(a++,o=o.nextSibling,a>=2))return null;n=n.nextSibling}return n}function Xe(e,t,s){return ze(e,t)?.5+tt(s,e,t):0}function Qe(e,t){et(t,e),!1!==t.callbacks.beforeNodeRemoved(e)&&(e.remove(),t.callbacks.afterNodeRemoved(e))}function Ye(e,t){return!e.deadIds.has(t)}function Ze(e,t,s){return(e.idMap.get(s)||xe).has(t)}function et(e,t){let s=e.idMap.get(t)||xe;for(const t of s)e.deadIds.add(t)}function tt(e,t,s){let i=e.idMap.get(t)||xe,r=0;for(const t of i)Ye(e,t)&&Ze(e,t,s)&&++r;return r}function st(e,t){let s=e.parentElement,i=e.querySelectorAll("[id]");for(const e of i){let i=e;for(;i!==s&&null!=i;){let s=t.get(i);null==s&&(s=new Set,t.set(i,s)),s.add(e.id),i=i.parentElement}}}function it(e,t){let s=new Map;return st(e,s),st(t,s),s}var rt={morph:function(e,t,s={}){e instanceof Document&&(e=e.documentElement),"string"==typeof t&&(t=function(e){let t=new DOMParser,s=e.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(s.match(/<\/html>/)||s.match(/<\/head>/)||s.match(/<\/body>/)){let i=t.parseFromString(e,"text/html");if(s.match(/<\/html>/))return i.generatedByIdiomorph=!0,i;{let e=i.firstChild;return e?(e.generatedByIdiomorph=!0,e):null}}{let s=t.parseFromString("<body><template>"+e+"</template></body>","text/html").body.querySelector("template").content;return s.generatedByIdiomorph=!0,s}}(t));let i=function(e){if(null==e){return document.createElement("div")}if(e.generatedByIdiomorph)return e;if(e instanceof Node){const t=document.createElement("div");return t.append(e),t}{const t=document.createElement("div");for(const s of[...e])t.append(s);return t}}(t),r=function(e,t,s){return{target:e,newContent:t,config:s,morphStyle:s.morphStyle,ignoreActive:s.ignoreActive,idMap:it(e,t),deadIds:new Set,callbacks:Object.assign({beforeNodeAdded:$e,afterNodeAdded:$e,beforeNodeMorphed:$e,afterNodeMorphed:$e,beforeNodeRemoved:$e,afterNodeRemoved:$e},s.callbacks),head:Object.assign({style:"merge",shouldPreserve:function(e){return"true"===e.getAttribute("im-preserve")},shouldReAppend:function(e){return"true"===e.getAttribute("im-re-append")},shouldRemove:$e,afterHeadMorphed:$e},s.head)}}(e,i,s);return Ve(e,i,r)}};class nt extends te{async render(){this.willRender&&await this.#p()}get renderMethod(){return"morph"}async#p(){this.#f(this.currentElement,this.newElement),this.#g(),p("turbo:morph",{detail:{currentElement:this.currentElement,newElement:this.newElement}})}#f(e,t,s="outerHTML"){this.isMorphingTurboFrame=this.#b(e),rt.morph(e,t,{morphStyle:s,callbacks:{beforeNodeAdded:this.#v,beforeNodeMorphed:this.#S,beforeNodeRemoved:this.#w}})}#v=e=>!(e.id&&e.hasAttribute("data-turbo-permanent")&&document.getElementById(e.id));#S=(e,t)=>!(e instanceof HTMLElement)||!e.hasAttribute("data-turbo-permanent")&&(this.isMorphingTurboFrame||!this.#b(e));#w=e=>this.#S(e);#g(){this.#y().forEach((e=>{this.#b(e)&&(this.#E(e),e.reload())}))}#E(e){e.addEventListener("turbo:before-frame-render",(e=>{e.detail.render=this.#R}),{once:!0})}#R=(e,t)=>{p("turbo:before-frame-morph",{target:e,detail:{currentElement:e,newElement:t}}),this.#f(e,t.children,"innerHTML")};#b(e){return e.src&&"morph"===e.refresh}#y(){return Array.from(document.querySelectorAll("turbo-frame[src]")).filter((e=>!e.closest("[data-turbo-permanent]")))}}class ot extends te{static renderElement(e,t){document.body&&t instanceof HTMLBodyElement?document.body.replaceWith(t):document.documentElement.appendChild(t)}get shouldRender(){return this.newSnapshot.isVisitable&&this.trackedElementsAreIdentical}get reloadReason(){return this.newSnapshot.isVisitable?this.trackedElementsAreIdentical?void 0:{reason:"tracked_element_mismatch"}:{reason:"turbo_visit_control_is_reload"}}async prepareToRender(){this.#A(),await this.mergeHead()}async render(){this.willRender&&await this.replaceBody()}finishRendering(){super.finishRendering(),this.isPreview||this.focusFirstAutofocusableElement()}get currentHeadSnapshot(){return this.currentSnapshot.headSnapshot}get newHeadSnapshot(){return this.newSnapshot.headSnapshot}get newElement(){return this.newSnapshot.element}#A(){const{documentElement:e}=this.currentSnapshot,{lang:t}=this.newSnapshot;t?e.setAttribute("lang",t):e.removeAttribute("lang")}async mergeHead(){const e=this.mergeProvisionalElements(),t=this.copyNewHeadStylesheetElements();this.copyNewHeadScriptElements(),await e,await t}async replaceBody(){await this.preservingPermanentElements((async()=>{this.activateNewBody(),await this.assignNewBody()}))}get trackedElementsAreIdentical(){return this.currentHeadSnapshot.trackedElementSignature==this.newHeadSnapshot.trackedElementSignature}async copyNewHeadStylesheetElements(){const e=[];for(const t of this.newHeadStylesheetElements)e.push(R(t)),document.head.appendChild(t);await Promise.all(e)}copyNewHeadScriptElements(){for(const e of this.newHeadScriptElements)document.head.appendChild(m(e))}async mergeProvisionalElements(){const e=[...this.newHeadProvisionalElements];for(const t of this.currentHeadProvisionalElements)this.isCurrentElementInElementList(t,e)||document.head.removeChild(t);for(const t of e)document.head.appendChild(t)}isCurrentElementInElementList(e,t){for(const[s,i]of t.entries()){if("TITLE"==e.tagName){if("TITLE"!=i.tagName)continue;if(e.innerHTML==i.innerHTML)return t.splice(s,1),!0}if(i.isEqualNode(e))return t.splice(s,1),!0}return!1}removeCurrentHeadProvisionalElements(){for(const e of this.currentHeadProvisionalElements)document.head.removeChild(e)}copyNewHeadProvisionalElements(){for(const e of this.newHeadProvisionalElements)document.head.appendChild(e)}activateNewBody(){document.adoptNode(this.newElement),this.activateNewBodyScriptElements()}activateNewBodyScriptElements(){for(const e of this.newBodyScriptElements){const t=m(e);e.replaceWith(t)}}async assignNewBody(){await this.renderElement(this.currentElement,this.newElement)}get newHeadStylesheetElements(){return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot)}get newHeadScriptElements(){return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot)}get currentHeadProvisionalElements(){return this.currentHeadSnapshot.provisionalElements}get newHeadProvisionalElements(){return this.newHeadSnapshot.provisionalElements}get newBodyScriptElements(){return this.newElement.querySelectorAll("script")}}class at{keys=[];snapshots={};constructor(e){this.size=e}has(e){return d(e)in this.snapshots}get(e){if(this.has(e)){const t=this.read(e);return this.touch(e),t}}put(e,t){return this.write(e,t),this.touch(e),t}clear(){this.snapshots={}}read(e){return this.snapshots[d(e)]}write(e,t){this.snapshots[d(e)]=t}touch(e){const t=d(e),s=this.keys.indexOf(t);s>-1&&this.keys.splice(s,1),this.keys.unshift(t),this.trim()}trim(){for(const e of this.keys.splice(this.size))delete this.snapshots[e]}}class ct extends K{snapshotCache=new at(10);lastRenderedLocation=new URL(location.href);forceReloaded=!1;shouldTransitionTo(e){return this.snapshot.prefersViewTransitions&&e.prefersViewTransitions}renderPage(e,t=!1,s=!0,i){const r=new(this.isPageRefresh(i)&&this.snapshot.shouldMorphPage?nt:ot)(this.snapshot,e,ot.renderElement,t,s);return r.shouldRender?i?.changeHistory():this.forceReloaded=!0,this.render(r)}renderError(e,t){t?.changeHistory();const s=new Ne(this.snapshot,e,Ne.renderElement,!1);return this.render(s)}clearSnapshotCache(){this.snapshotCache.clear()}async cacheSnapshot(e=this.snapshot){if(e.isCacheable){this.delegate.viewWillCacheSnapshot();const{lastRenderedLocation:t}=this;await g();const s=e.clone();return this.snapshotCache.put(t,s),s}}getCachedSnapshotForLocation(e){return this.snapshotCache.get(e)}isPageRefresh(e){return!e||this.lastRenderedLocation.href===e.location.href&&"replace"===e.action}get snapshot(){return ae.fromElement(this.element)}}class lt{selector="a[data-turbo-preload]";constructor(e){this.delegate=e}get snapshotCache(){return this.delegate.navigator.view.snapshotCache}start(){if("loading"===document.readyState)return document.addEventListener("DOMContentLoaded",(()=>{this.preloadOnLoadLinksForView(document.body)}));this.preloadOnLoadLinksForView(document.body)}preloadOnLoadLinksForView(e){for(const t of e.querySelectorAll(this.selector))this.preloadURL(t)}async preloadURL(e){const t=new URL(e.href);if(!this.snapshotCache.has(t))try{const e=await F(t.toString(),{headers:{"Sec-Purpose":"prefetch",Accept:"text/html"}}),s=await e.text(),i=ae.fromHTMLString(s);this.snapshotCache.put(t,i)}catch(e){}}}class ht extends Set{constructor(e){super(),this.maxSize=e}add(e){if(this.size>=this.maxSize){const e=this.values().next().value;this.delete(e)}super.add(e)}}class dt{constructor(e){this.session=e}clear(){this.session.clearCache()}resetCacheControl(){this.#L("")}exemptPageFromCache(){this.#L("no-cache")}exemptPageFromPreview(){this.#L("no-preview")}#L(e){!function(e,t){let s=C(e);s||(s=document.createElement("meta"),s.setAttribute("name",e),document.head.appendChild(s)),s.setAttribute("content",t)}("turbo-cache-control",e)}}function ut(e){Object.defineProperties(e,mt)}const mt={absoluteURL:{get(){return this.toString()}}},pt=new class{navigator=new Pe(this);history=new Te(this);preloader=new lt(this);view=new ct(this,document.documentElement);adapter=new Ae(this);pageObserver=new He(this);cacheObserver=new Le;linkClickObserver=new Y(this,window);formSubmitObserver=new J(this,document);scrollObserver=new qe(this);streamObserver=new Oe(this);formLinkClickObserver=new Z(this,document.documentElement);frameRedirector=new Ce(this,document.documentElement);streamMessageRenderer=new Be;cache=new dt(this);recentRequests=new ht(20);drive=!0;enabled=!0;progressBarDelay=500;started=!1;formMode="on";start(){this.started||(this.pageObserver.start(),this.cacheObserver.start(),this.formLinkClickObserver.start(),this.linkClickObserver.start(),this.formSubmitObserver.start(),this.scrollObserver.start(),this.streamObserver.start(),this.frameRedirector.start(),this.history.start(),this.preloader.start(),this.started=!0,this.enabled=!0)}disable(){this.enabled=!1}stop(){this.started&&(this.pageObserver.stop(),this.cacheObserver.stop(),this.formLinkClickObserver.stop(),this.linkClickObserver.stop(),this.formSubmitObserver.stop(),this.scrollObserver.stop(),this.streamObserver.stop(),this.frameRedirector.stop(),this.history.stop(),this.started=!1)}registerAdapter(e){this.adapter=e}visit(e,t={}){const s=t.frame?document.getElementById(t.frame):null;s instanceof i?(s.src=e.toString(),s.loaded):this.navigator.proposeVisit(r(e),t)}refresh(e,t){t&&this.recentRequests.has(t)||(this.cache.exemptPageFromPreview(),this.visit(e,{action:"replace"}))}connectStreamSource(e){this.streamObserver.connectStreamSource(e)}disconnectStreamSource(e){this.streamObserver.disconnectStreamSource(e)}renderStreamMessage(e){this.streamMessageRenderer.render(U.wrap(e))}clearCache(){this.view.clearSnapshotCache()}setProgressBarDelay(e){this.progressBarDelay=e}setFormMode(e){this.formMode=e}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}historyPoppedToLocationWithRestorationIdentifier(e,t){this.enabled?this.navigator.startVisit(e,t,{action:"restore",historyChanged:!0}):this.adapter.pageInvalidated({reason:"turbo_disabled"})}scrollPositionChanged(e){this.history.updateRestorationData({scrollPosition:e})}willSubmitFormLinkToLocation(e,t){return this.elementIsNavigatable(e)&&l(t,this.snapshot.rootLocation)}submittedFormLinkToLocation(){}willFollowLinkToLocation(e,t,s){return this.elementIsNavigatable(e)&&l(t,this.snapshot.rootLocation)&&this.applicationAllowsFollowingLinkToLocation(e,t,s)}followedLinkToLocation(e,t){const s=this.getActionForLink(e),i=e.hasAttribute("data-turbo-stream");this.visit(t.href,{action:s,acceptsStreamResponse:i})}allowsVisitingLocationWithAction(e,t){return this.locationWithActionIsSamePage(e,t)||this.applicationAllowsVisitingLocation(e)}visitProposedToLocation(e,t){ut(e),this.adapter.visitProposedToLocation(e,t)}visitStarted(e){e.acceptsStreamResponse||y(document.documentElement),ut(e.location),e.silent||this.notifyApplicationAfterVisitingLocation(e.location,e.action)}visitCompleted(e){E(document.documentElement),this.notifyApplicationAfterPageLoad(e.getTimingMetrics())}locationWithActionIsSamePage(e,t){return this.navigator.locationWithActionIsSamePage(e,t)}visitScrolledToSamePageLocation(e,t){this.notifyApplicationAfterVisitingSamePageLocation(e,t)}willSubmitForm(e,t){const s=o(e,t);return this.submissionIsNavigatable(e,t)&&l(r(s),this.snapshot.rootLocation)}formSubmitted(e,t){this.navigator.submitForm(e,t)}pageBecameInteractive(){this.view.lastRenderedLocation=this.location,this.notifyApplicationAfterPageLoad()}pageLoaded(){this.history.assumeControlOfScrollRestoration()}pageWillUnload(){this.history.relinquishControlOfScrollRestoration()}receivedMessageFromStream(e){this.renderStreamMessage(e)}viewWillCacheSnapshot(){this.navigator.currentVisit?.silent||this.notifyApplicationBeforeCachingSnapshot()}allowsImmediateRender({element:e},t,s){const i=this.notifyApplicationBeforeRender(e,t,s),{defaultPrevented:r,detail:{render:n}}=i;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!r}viewRenderedSnapshot(e,t,s){this.view.lastRenderedLocation=this.history.location,this.notifyApplicationAfterRender(t,s)}preloadOnLoadLinksForView(e){this.preloader.preloadOnLoadLinksForView(e)}viewInvalidated(e){this.adapter.pageInvalidated(e)}frameLoaded(e){this.notifyApplicationAfterFrameLoad(e)}frameRendered(e,t){this.notifyApplicationAfterFrameRender(e,t)}applicationAllowsFollowingLinkToLocation(e,t,s){return!this.notifyApplicationAfterClickingLinkToLocation(e,t,s).defaultPrevented}applicationAllowsVisitingLocation(e){return!this.notifyApplicationBeforeVisitingLocation(e).defaultPrevented}notifyApplicationAfterClickingLinkToLocation(e,t,s){return p("turbo:click",{target:e,detail:{url:t.href,originalEvent:s},cancelable:!0})}notifyApplicationBeforeVisitingLocation(e){return p("turbo:before-visit",{detail:{url:e.href},cancelable:!0})}notifyApplicationAfterVisitingLocation(e,t){return p("turbo:visit",{detail:{url:e.href,action:t}})}notifyApplicationBeforeCachingSnapshot(){return p("turbo:before-cache")}notifyApplicationBeforeRender(e,t,s){return p("turbo:before-render",{detail:{newBody:e,isPreview:t,...s},cancelable:!0})}notifyApplicationAfterRender(e,t){return p("turbo:render",{detail:{isPreview:e,renderMethod:t}})}notifyApplicationAfterPageLoad(e={}){return p("turbo:load",{detail:{url:this.location.href,timing:e}})}notifyApplicationAfterVisitingSamePageLocation(e,t){dispatchEvent(new HashChangeEvent("hashchange",{oldURL:e.toString(),newURL:t.toString()}))}notifyApplicationAfterFrameLoad(e){return p("turbo:frame-load",{target:e})}notifyApplicationAfterFrameRender(e,t){return p("turbo:frame-render",{detail:{fetchResponse:e},target:t,cancelable:!0})}submissionIsNavigatable(e,t){if("off"==this.formMode)return!1;{const s=!t||this.elementIsNavigatable(t);return"optin"==this.formMode?s&&null!=e.closest('[data-turbo="true"]'):s&&this.elementIsNavigatable(e)}}elementIsNavigatable(e){const t=P(e,"[data-turbo]"),s=P(e,"turbo-frame");return this.drive||s?!t||"false"!=t.getAttribute("data-turbo"):!!t&&"true"==t.getAttribute("data-turbo")}getActionForLink(e){return L(e)||"advance"}get snapshot(){return this.view.snapshot}},{cache:ft,navigator:gt}=pt;function bt(){pt.start()}function vt(e){pt.registerAdapter(e)}function St(e,t){pt.visit(e,t)}function wt(e){pt.connectStreamSource(e)}function yt(e){pt.disconnectStreamSource(e)}function Et(e){pt.renderStreamMessage(e)}function Rt(){console.warn("Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),pt.clearCache()}function At(e){pt.setProgressBarDelay(e)}function Lt(e){$.confirmMethod=e}function Ct(e){pt.setFormMode(e)}var Tt=Object.freeze({__proto__:null,navigator:gt,session:pt,cache:ft,PageRenderer:ot,PageSnapshot:ae,FrameRenderer:se,fetch:F,start:bt,registerAdapter:vt,visit:St,connectStreamSource:wt,disconnectStreamSource:yt,renderStreamMessage:Et,clearCache:Rt,setProgressBarDelay:At,setConfirmMethod:Lt,setFormMode:Ct});class Pt extends Error{}function kt(e){if(null!=e){const t=document.getElementById(e);if(t instanceof i)return t}}function Mt(e,t){if(e){const n=e.getAttribute("src");if(null!=n&&null!=t&&(s=t,r(n).href==r(s).href))throw new Error(`Matching <turbo-frame id="${e.id}"> element has a source URL which references itself`);if(e.ownerDocument!==document&&(e=document.importNode(e,!0)),e instanceof i)return e.connectedCallback(),e.disconnectedCallback(),e}var s}const Ft={after(){this.targetElements.forEach((e=>e.parentElement?.insertBefore(this.templateContent,e.nextSibling)))},append(){this.removeDuplicateTargetChildren(),this.targetElements.forEach((e=>e.append(this.templateContent)))},before(){this.targetElements.forEach((e=>e.parentElement?.insertBefore(this.templateContent,e)))},prepend(){this.removeDuplicateTargetChildren(),this.targetElements.forEach((e=>e.prepend(this.templateContent)))},remove(){this.targetElements.forEach((e=>e.remove()))},replace(){this.targetElements.forEach((e=>e.replaceWith(this.templateContent)))},update(){this.targetElements.forEach((e=>{e.innerHTML="",e.append(this.templateContent)}))},refresh(){pt.refresh(this.baseURI,this.requestId)}};class It extends HTMLElement{static async renderElement(e){await e.performAction()}async connectedCallback(){try{await this.render()}catch(e){console.error(e)}finally{this.disconnect()}}async render(){return this.renderPromise??=(async()=>{const e=this.beforeRenderEvent;this.dispatchEvent(e)&&(await("hidden"===document.visibilityState?g():f()),await e.detail.render(this))})()}disconnect(){try{this.remove()}catch{}}removeDuplicateTargetChildren(){this.duplicateChildren.forEach((e=>e.remove()))}get duplicateChildren(){const e=this.targetElements.flatMap((e=>[...e.children])).filter((e=>!!e.id)),t=[...this.templateContent?.children||[]].filter((e=>!!e.id)).map((e=>e.id));return e.filter((e=>t.includes(e.id)))}get performAction(){if(this.action){const e=Ft[this.action];if(e)return e;this.#C("unknown action")}this.#C("action attribute is missing")}get targetElements(){return this.target?this.targetElementsById:this.targets?this.targetElementsByQuery:void this.#C("target or targets attribute is missing")}get templateContent(){return this.templateElement.content.cloneNode(!0)}get templateElement(){if(null===this.firstElementChild){const e=this.ownerDocument.createElement("template");return this.appendChild(e),e}if(this.firstElementChild instanceof HTMLTemplateElement)return this.firstElementChild;this.#C("first child element must be a <template> element")}get action(){return this.getAttribute("action")}get target(){return this.getAttribute("target")}get targets(){return this.getAttribute("targets")}get requestId(){return this.getAttribute("request-id")}#C(e){throw new Error(`${this.description}: ${e}`)}get description(){return(this.outerHTML.match(/<[^>]+>/)??[])[0]??"<turbo-stream>"}get beforeRenderEvent(){return new CustomEvent("turbo:before-stream-render",{bubbles:!0,cancelable:!0,detail:{newStream:this,render:It.renderElement}})}get targetElementsById(){const e=this.ownerDocument?.getElementById(this.target);return null!==e?[e]:[]}get targetElementsByQuery(){const e=this.ownerDocument?.querySelectorAll(this.targets);return 0!==e.length?Array.prototype.slice.call(e):[]}}class Ht extends HTMLElement{streamSource=null;connectedCallback(){this.streamSource=this.src.match(/^ws{1,2}:/)?new WebSocket(this.src):new EventSource(this.src),wt(this.streamSource)}disconnectedCallback(){this.streamSource&&(this.streamSource.close(),yt(this.streamSource))}get src(){return this.getAttribute("src")||""}}i.delegateConstructor=class{fetchResponseLoaded=e=>Promise.resolve();#T=null;#P=()=>{};#k=!1;#M=!1;#F=new Set;action=null;constructor(e){this.element=e,this.view=new X(this,this.element),this.appearanceObserver=new D(this,this.element),this.formLinkClickObserver=new Z(this,this.element),this.linkInterceptor=new Q(this,this.element),this.restorationIdentifier=S(),this.formSubmitObserver=new J(this,this.element)}connect(){this.#k||(this.#k=!0,this.loadingStyle==s.lazy?this.appearanceObserver.start():this.#I(),this.formLinkClickObserver.start(),this.linkInterceptor.start(),this.formSubmitObserver.start())}disconnect(){this.#k&&(this.#k=!1,this.appearanceObserver.stop(),this.formLinkClickObserver.stop(),this.linkInterceptor.stop(),this.formSubmitObserver.stop())}disabledChanged(){this.loadingStyle==s.eager&&this.#I()}sourceURLChanged(){this.#H("src")||(this.element.isConnected&&(this.complete=!1),(this.loadingStyle==s.eager||this.#M)&&this.#I())}sourceURLReloaded(){const{src:e}=this.element;return this.#q("complete",(()=>{this.element.removeAttribute("complete")})),this.element.src=null,this.element.src=e,this.element.loaded}completeChanged(){this.#H("complete")||this.#I()}loadingStyleChanged(){this.loadingStyle==s.lazy?this.appearanceObserver.start():(this.appearanceObserver.stop(),this.#I())}async#I(){this.enabled&&this.isActive&&!this.complete&&this.sourceURL&&(this.element.loaded=this.#B(r(this.sourceURL)),this.appearanceObserver.stop(),await this.element.loaded,this.#M=!0)}async loadResponse(e){(e.redirected||e.succeeded&&e.isHTML)&&(this.sourceURL=e.response.url);try{const t=await e.responseHTML;if(t){const s=b(t);ae.fromDocument(s).isVisitable?await this.#O(e,s):await this.#N(e)}}finally{this.fetchResponseLoaded=()=>Promise.resolve()}}elementAppearedInViewport(e){this.proposeVisitIfNavigatedWithAction(e,e),this.#I()}willSubmitFormLinkToLocation(e){return this.#x(e)}submittedFormLinkToLocation(e,t,s){const i=this.#l(e);i&&s.setAttribute("data-turbo-frame",i.id)}shouldInterceptLinkClick(e,t,s){return this.#x(e)}linkClickIntercepted(e,t){this.#V(e,t)}willSubmitForm(e,t){return e.closest("turbo-frame")==this.element&&this.#x(e,t)}formSubmitted(e,t){this.formSubmission&&this.formSubmission.stop(),this.formSubmission=new $(this,e,t);const{fetchRequest:s}=this.formSubmission;this.prepareRequest(s),this.formSubmission.start()}prepareRequest(e){e.headers["Turbo-Frame"]=this.id,this.currentNavigationElement?.hasAttribute("data-turbo-stream")&&e.acceptResponseType(U.contentType)}requestStarted(e){y(this.element)}requestPreventedHandlingResponse(e,t){this.#P()}async requestSucceededWithResponse(e,t){await this.loadResponse(t),this.#P()}async requestFailedWithResponse(e,t){await this.loadResponse(t),this.#P()}requestErrored(e,t){console.error(t),this.#P()}requestFinished(e){E(this.element)}formSubmissionStarted({formElement:e}){y(e,this.#l(e))}formSubmissionSucceededWithResponse(e,t){const s=this.#l(e.formElement,e.submitter);s.delegate.proposeVisitIfNavigatedWithAction(s,e.formElement,e.submitter),s.delegate.loadResponse(t),e.isSafe||pt.clearCache()}formSubmissionFailedWithResponse(e,t){this.element.delegate.loadResponse(t),pt.clearCache()}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished({formElement:e}){E(e,this.#l(e))}allowsImmediateRender({element:e},t,s){const i=p("turbo:before-frame-render",{target:this.element,detail:{newFrame:e,...s},cancelable:!0}),{defaultPrevented:r,detail:{render:n}}=i;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!r}viewRenderedSnapshot(e,t,s){}preloadOnLoadLinksForView(e){pt.preloadOnLoadLinksForView(e)}viewInvalidated(){}willRenderFrame(e,t){this.previousFrameElement=e.cloneNode(!0)}visitCachedSnapshot=({element:e})=>{const t=e.querySelector("#"+this.element.id);t&&this.previousFrameElement&&t.replaceChildren(...this.previousFrameElement.children),delete this.previousFrameElement};async#O(e,t){const s=await this.extractForeignFrameElement(t.body);if(s){const t=new j(s),i=new se(this,this.view.snapshot,t,se.renderElement,!1,!1);this.view.renderPromise&&await this.view.renderPromise,this.changeHistory(),await this.view.render(i),this.complete=!0,pt.frameRendered(e,this.element),pt.frameLoaded(this.element),await this.fetchResponseLoaded(e)}else this.#W(e)&&this.#D(e)}async#B(e){const t=new O(this,H.get,e,new URLSearchParams,this.element);return this.#T?.cancel(),this.#T=t,new Promise((e=>{this.#P=()=>{this.#P=()=>{},this.#T=null,e()},t.perform()}))}#V(e,t,s){const i=this.#l(e,s);i.delegate.proposeVisitIfNavigatedWithAction(i,e,s),this.#U(e,(()=>{i.src=t}))}proposeVisitIfNavigatedWithAction(e,t,s){if(this.action=L(s,t,e),this.action){const t=ae.fromElement(e).clone(),{visitCachedSnapshot:s}=e.delegate;e.delegate.fetchResponseLoaded=async i=>{if(e.src){const{statusCode:r,redirected:n}=i,o={response:{statusCode:r,redirected:n,responseHTML:await i.responseHTML},visitCachedSnapshot:s,willRender:!1,updateHistory:!1,restorationIdentifier:this.restorationIdentifier,snapshot:t};this.action&&(o.action=this.action),pt.visit(e.src,o)}}}}changeHistory(){if(this.action){const e=A(this.action);pt.history.update(e,r(this.element.src||""),this.restorationIdentifier)}}async#N(e){console.warn(`The response (${e.statusCode}) from <turbo-frame id="${this.element.id}"> is performing a full page visit due to turbo-visit-control.`),await this.#_(e.response)}#W(e){this.element.setAttribute("complete","");const t=e.response;return!p("turbo:frame-missing",{target:this.element,detail:{response:t,visit:async(e,t)=>{e instanceof Response?this.#_(e):pt.visit(e,t)}},cancelable:!0}).defaultPrevented}#D(e){this.view.missing(),this.#$(e)}#$(e){const t=`The response (${e.statusCode}) did not contain the expected <turbo-frame id="${this.element.id}"> and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;throw new Pt(t)}async#_(e){const t=new u(e),s=await t.responseHTML,{location:i,redirected:r,statusCode:n}=t;return pt.visit(i,{response:{redirected:r,statusCode:n,responseHTML:s}})}#l(e,t){return kt(w("data-turbo-frame",t,e)||this.element.getAttribute("target"))??this.element}async extractForeignFrameElement(e){let t;const s=CSS.escape(this.id);try{if(t=Mt(e.querySelector(`turbo-frame#${s}`),this.sourceURL),t)return t;if(t=Mt(e.querySelector(`turbo-frame[src][recurse~=${s}]`),this.sourceURL),t)return await t.loaded,await this.extractForeignFrameElement(t)}catch(e){return console.error(e),new i}return null}#j(e,t){return l(r(o(e,t)),this.rootLocation)}#x(e,t){const s=w("data-turbo-frame",t,e)||this.element.getAttribute("target");if(e instanceof HTMLFormElement&&!this.#j(e,t))return!1;if(!this.enabled||"_top"==s)return!1;if(s){const e=kt(s);if(e)return!e.disabled}return!!pt.elementIsNavigatable(e)&&!(t&&!pt.elementIsNavigatable(t))}get id(){return this.element.id}get enabled(){return!this.element.disabled}get sourceURL(){if(this.element.src)return this.element.src}set sourceURL(e){this.#q("src",(()=>{this.element.src=e??null}))}get loadingStyle(){return this.element.loading}get isLoading(){return void 0!==this.formSubmission||void 0!==this.#P()}get complete(){return this.element.hasAttribute("complete")}set complete(e){this.#q("complete",(()=>{e?this.element.setAttribute("complete",""):this.element.removeAttribute("complete")}))}get isActive(){return this.element.isActive&&this.#k}get rootLocation(){const e=this.element.ownerDocument.querySelector('meta[name="turbo-root"]');return r(e?.content??"/")}#H(e){return this.#F.has(e)}#q(e,t){this.#F.add(e),t(),this.#F.delete(e)}#U(e,t){this.currentNavigationElement=e,t(),delete this.currentNavigationElement}},void 0===customElements.get("turbo-frame")&&customElements.define("turbo-frame",i),void 0===customElements.get("turbo-stream")&&customElements.define("turbo-stream",It),void 0===customElements.get("turbo-stream-source")&&customElements.define("turbo-stream-source",Ht),(()=>{let e=document.currentScript;if(e&&!e.hasAttribute("data-turbo-suppress-warning"))for(e=e.parentElement;e;){if(e==document.body)return console.warn(v`
19
+ `}hiding=!1;value=0;visible=!1;constructor(){this.stylesheetElement=this.createStylesheetElement(),this.progressElement=this.createProgressElement(),this.installStylesheetElement(),this.setValue(0)}show(){this.visible||(this.visible=!0,this.installProgressElement(),this.startTrickling())}hide(){this.visible&&!this.hiding&&(this.hiding=!0,this.fadeProgressElement((()=>{this.uninstallProgressElement(),this.stopTrickling(),this.visible=!1,this.hiding=!1})))}setValue(e){this.value=e,this.refresh()}installStylesheetElement(){document.head.insertBefore(this.stylesheetElement,document.head.firstChild)}installProgressElement(){this.progressElement.style.width="0",this.progressElement.style.opacity="1",document.documentElement.insertBefore(this.progressElement,document.body),this.refresh()}fadeProgressElement(e){this.progressElement.style.opacity="0",setTimeout(e,1.5*ae.animationDuration)}uninstallProgressElement(){this.progressElement.parentNode&&document.documentElement.removeChild(this.progressElement)}startTrickling(){this.trickleInterval||(this.trickleInterval=window.setInterval(this.trickle,ae.animationDuration))}stopTrickling(){window.clearInterval(this.trickleInterval),delete this.trickleInterval}trickle=()=>{this.setValue(this.value+Math.random()/100)};refresh(){requestAnimationFrame((()=>{this.progressElement.style.width=10+90*this.value+"%"}))}createStylesheetElement(){const e=document.createElement("style");return e.type="text/css",e.textContent=ae.defaultCSS,this.cspNonce&&(e.nonce=this.cspNonce),e}createProgressElement(){const e=document.createElement("div");return e.className="turbo-progress-bar",e}get cspNonce(){return P("csp-nonce")}}class ce extends K{detailsByOuterHTML=this.children.filter((e=>!function(e){const t=e.localName;return"noscript"==t}(e))).map((e=>function(e){e.hasAttribute("nonce")&&e.setAttribute("nonce","");return e}(e))).reduce(((e,t)=>{const{outerHTML:s}=t,i=s in e?e[s]:{type:le(t),tracked:he(t),elements:[]};return{...e,[s]:{...i,elements:[...i.elements,t]}}}),{});get trackedElementSignature(){return Object.keys(this.detailsByOuterHTML).filter((e=>this.detailsByOuterHTML[e].tracked)).join("")}getScriptElementsNotInSnapshot(e){return this.getElementsMatchingTypeNotInSnapshot("script",e)}getStylesheetElementsNotInSnapshot(e){return this.getElementsMatchingTypeNotInSnapshot("stylesheet",e)}getElementsMatchingTypeNotInSnapshot(e,t){return Object.keys(this.detailsByOuterHTML).filter((e=>!(e in t.detailsByOuterHTML))).map((e=>this.detailsByOuterHTML[e])).filter((({type:t})=>t==e)).map((({elements:[e]})=>e))}get provisionalElements(){return Object.keys(this.detailsByOuterHTML).reduce(((e,t)=>{const{type:s,tracked:i,elements:r}=this.detailsByOuterHTML[t];return null!=s||i?r.length>1?[...e,...r.slice(1)]:e:[...e,...r]}),[])}getMetaValue(e){const t=this.findMetaElementByName(e);return t?t.getAttribute("content"):null}findMetaElementByName(e){return Object.keys(this.detailsByOuterHTML).reduce(((t,s)=>{const{elements:[i]}=this.detailsByOuterHTML[s];return function(e,t){const s=e.localName;return"meta"==s&&e.getAttribute("name")==t}(i,e)?i:t}),0)}}function le(e){return function(e){const t=e.localName;return"script"==t}(e)?"script":function(e){const t=e.localName;return"style"==t||"link"==t&&"stylesheet"==e.getAttribute("rel")}(e)?"stylesheet":void 0}function he(e){return"reload"==e.getAttribute("data-turbo-track")}class de extends K{static fromHTMLString(e=""){return this.fromDocument(v(e))}static fromElement(e){return this.fromDocument(e.ownerDocument)}static fromDocument({documentElement:e,body:t,head:s}){return new this(e,t,new ce(s))}constructor(e,t,s){super(t),this.documentElement=e,this.headSnapshot=s}clone(){const e=this.element.cloneNode(!0),t=this.element.querySelectorAll("select"),s=e.querySelectorAll("select");for(const[e,i]of t.entries()){const t=s[e];for(const e of t.selectedOptions)e.selected=!1;for(const e of i.selectedOptions)t.options[e.index].selected=!0}for(const t of e.querySelectorAll('input[type="password"]'))t.value="";return new de(this.documentElement,e,this.headSnapshot)}get lang(){return this.documentElement.getAttribute("lang")}get headElement(){return this.headSnapshot.element}get rootLocation(){return r(this.getSetting("root")??"/")}get cacheControlValue(){return this.getSetting("cache-control")}get isPreviewable(){return"no-preview"!=this.cacheControlValue}get isCacheable(){return"no-cache"!=this.cacheControlValue}get isVisitable(){return"reload"!=this.getSetting("visit-control")}get prefersViewTransitions(){return"same-origin"===this.headSnapshot.getMetaValue("view-transition")}get shouldMorphPage(){return"morph"===this.getSetting("refresh-method")}get shouldPreserveScrollPosition(){return"preserve"===this.getSetting("refresh-scroll")}getSetting(e){return this.headSnapshot.getMetaValue(`turbo-${e}`)}}class ue{#o=!1;#a=Promise.resolve();renderChange(e,t){return e&&this.viewTransitionsAvailable&&!this.#o?(this.#o=!0,this.#a=this.#a.then((async()=>{await document.startViewTransition(t).finished}))):this.#a=this.#a.then(t),this.#a}get viewTransitionsAvailable(){return document.startViewTransition}}const me={action:"advance",historyChanged:!1,visitCachedSnapshot:()=>{},willRender:!0,updateHistory:!0,shouldCacheSnapshot:!0,acceptsStreamResponse:!1},pe="visitStart",fe="requestStart",ge="requestEnd",be="visitEnd",ve="initialized",Se="started",we="canceled",ye="failed",Ee="completed",Ae=0,Re=-1,Le=-2,Ce={advance:"forward",restore:"back",replace:"none"};class Te{identifier=w();timingMetrics={};followedRedirect=!1;historyChanged=!1;scrolled=!1;shouldCacheSnapshot=!0;acceptsStreamResponse=!1;snapshotCached=!1;state=ve;viewTransitioner=new ue;constructor(e,t,s,i={}){this.delegate=e,this.location=t,this.restorationIdentifier=s||w();const{action:r,historyChanged:n,referrer:o,snapshot:a,snapshotHTML:c,response:l,visitCachedSnapshot:h,willRender:d,updateHistory:u,shouldCacheSnapshot:m,acceptsStreamResponse:p,direction:f}={...me,...i};this.action=r,this.historyChanged=n,this.referrer=o,this.snapshot=a,this.snapshotHTML=c,this.response=l,this.isSamePage=this.delegate.locationWithActionIsSamePage(this.location,this.action),this.visitCachedSnapshot=h,this.willRender=d,this.updateHistory=u,this.scrolled=!d,this.shouldCacheSnapshot=m,this.acceptsStreamResponse=p,this.direction=f||Ce[r]}get adapter(){return this.delegate.adapter}get view(){return this.delegate.view}get history(){return this.delegate.history}get restorationData(){return this.history.getRestorationDataForIdentifier(this.restorationIdentifier)}get silent(){return this.isSamePage}start(){this.state==ve&&(this.recordTimingMetric(pe),this.state=Se,this.adapter.visitStarted(this),this.delegate.visitStarted(this))}cancel(){this.state==Se&&(this.request&&this.request.cancel(),this.cancelRender(),this.state=we)}complete(){this.state==Se&&(this.recordTimingMetric(be),this.state=Ee,this.followRedirect(),this.followedRedirect||(this.adapter.visitCompleted(this),this.delegate.visitCompleted(this)))}fail(){this.state==Se&&(this.state=ye,this.adapter.visitFailed(this),this.delegate.visitCompleted(this))}changeHistory(){if(!this.historyChanged&&this.updateHistory){const e=L(this.location.href===this.referrer?.href?"replace":this.action);this.history.update(e,this.location,this.restorationIdentifier),this.historyChanged=!0}}issueRequest(){this.hasPreloadedResponse()?this.simulateRequest():this.shouldIssueRequest()&&!this.request&&(this.request=new D(this,N.get,this.location),this.request.perform())}simulateRequest(){this.response&&(this.startRequest(),this.recordResponse(),this.finishRequest())}startRequest(){this.recordTimingMetric(fe),this.adapter.visitRequestStarted(this)}recordResponse(e=this.response){if(this.response=e,e){const{statusCode:t}=e;Pe(t)?this.adapter.visitRequestCompleted(this):this.adapter.visitRequestFailedWithStatusCode(this,t)}}finishRequest(){this.recordTimingMetric(ge),this.adapter.visitRequestFinished(this)}loadResponse(){if(this.response){const{statusCode:e,responseHTML:t}=this.response;this.render((async()=>{if(this.shouldCacheSnapshot&&this.cacheSnapshot(),this.view.renderPromise&&await this.view.renderPromise,Pe(e)&&null!=t){const e=de.fromHTMLString(t);await this.renderPageSnapshot(e,!1),this.adapter.visitRendered(this),this.complete()}else await this.view.renderError(de.fromHTMLString(t),this),this.adapter.visitRendered(this),this.fail()}))}}getCachedSnapshot(){const e=this.view.getCachedSnapshotForLocation(this.location)||this.getPreloadedSnapshot();if(e&&(!n(this.location)||e.hasAnchor(n(this.location)))&&("restore"==this.action||e.isPreviewable))return e}getPreloadedSnapshot(){if(this.snapshotHTML)return de.fromHTMLString(this.snapshotHTML)}hasCachedSnapshot(){return null!=this.getCachedSnapshot()}loadCachedSnapshot(){const e=this.getCachedSnapshot();if(e){const t=this.shouldIssueRequest();this.render((async()=>{this.cacheSnapshot(),this.isSamePage?this.adapter.visitRendered(this):(this.view.renderPromise&&await this.view.renderPromise,await this.renderPageSnapshot(e,t),this.adapter.visitRendered(this),t||this.complete())}))}}followRedirect(){this.redirectedToLocation&&!this.followedRedirect&&this.response?.redirected&&(this.adapter.visitProposedToLocation(this.redirectedToLocation,{action:"replace",response:this.response,shouldCacheSnapshot:!1,willRender:!1}),this.followedRedirect=!0)}goToSamePageAnchor(){this.isSamePage&&this.render((async()=>{this.cacheSnapshot(),this.performScroll(),this.changeHistory(),this.adapter.visitRendered(this)}))}prepareRequest(e){this.acceptsStreamResponse&&e.acceptResponseType(z.contentType)}requestStarted(){this.startRequest()}requestPreventedHandlingResponse(e,t){}async requestSucceededWithResponse(e,t){const s=await t.responseHTML,{redirected:i,statusCode:r}=t;null==s?this.recordResponse({statusCode:Le,redirected:i}):(this.redirectedToLocation=t.redirected?t.location:void 0,this.recordResponse({statusCode:r,responseHTML:s,redirected:i}))}async requestFailedWithResponse(e,t){const s=await t.responseHTML,{redirected:i,statusCode:r}=t;null==s?this.recordResponse({statusCode:Le,redirected:i}):this.recordResponse({statusCode:r,responseHTML:s,redirected:i})}requestErrored(e,t){this.recordResponse({statusCode:Ae,redirected:!1})}requestFinished(){this.finishRequest()}performScroll(){this.scrolled||this.view.forceReloaded||this.view.shouldPreserveScrollPosition(this)||("restore"==this.action?this.scrollToRestoredPosition()||this.scrollToAnchor()||this.view.scrollToTop():this.scrollToAnchor()||this.view.scrollToTop(),this.isSamePage&&this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation,this.location),this.scrolled=!0)}scrollToRestoredPosition(){const{scrollPosition:e}=this.restorationData;if(e)return this.view.scrollToPosition(e),!0}scrollToAnchor(){const e=n(this.location);if(null!=e)return this.view.scrollToAnchor(e),!0}recordTimingMetric(e){this.timingMetrics[e]=(new Date).getTime()}getTimingMetrics(){return{...this.timingMetrics}}getHistoryMethodForAction(e){switch(e){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}hasPreloadedResponse(){return"object"==typeof this.response}shouldIssueRequest(){return!this.isSamePage&&("restore"==this.action?!this.hasCachedSnapshot():this.willRender)}cacheSnapshot(){this.snapshotCached||(this.view.cacheSnapshot(this.snapshot).then((e=>e&&this.visitCachedSnapshot(e))),this.snapshotCached=!0)}async render(e){this.cancelRender(),this.frame=await f(),await e(),delete this.frame}async renderPageSnapshot(e,t){await this.viewTransitioner.renderChange(this.view.shouldTransitionTo(e),(async()=>{await this.view.renderPage(e,t,this.willRender,this),this.performScroll()}))}cancelRender(){this.frame&&(cancelAnimationFrame(this.frame),delete this.frame)}}function Pe(e){return e>=200&&e<300}class ke{progressBar=new ae;constructor(e){this.session=e}visitProposedToLocation(e,t){l(e,this.navigator.rootLocation)?this.navigator.startVisit(e,t?.restorationIdentifier||w(),t):window.location.href=e.toString()}visitStarted(e){this.location=e.location,e.loadCachedSnapshot(),e.issueRequest(),e.goToSamePageAnchor()}visitRequestStarted(e){this.progressBar.setValue(0),e.hasCachedSnapshot()||"restore"!=e.action?this.showVisitProgressBarAfterDelay():this.showProgressBar()}visitRequestCompleted(e){e.loadResponse()}visitRequestFailedWithStatusCode(e,t){switch(t){case Ae:case Re:case Le:return this.reload({reason:"request_failed",context:{statusCode:t}});default:return e.loadResponse()}}visitRequestFinished(e){}visitCompleted(e){this.progressBar.setValue(1),this.hideVisitProgressBar()}pageInvalidated(e){this.reload(e)}visitFailed(e){this.progressBar.setValue(1),this.hideVisitProgressBar()}visitRendered(e){}formSubmissionStarted(e){this.progressBar.setValue(0),this.showFormProgressBarAfterDelay()}formSubmissionFinished(e){this.progressBar.setValue(1),this.hideFormProgressBar()}showVisitProgressBarAfterDelay(){this.visitProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay)}hideVisitProgressBar(){this.progressBar.hide(),null!=this.visitProgressBarTimeout&&(window.clearTimeout(this.visitProgressBarTimeout),delete this.visitProgressBarTimeout)}showFormProgressBarAfterDelay(){null==this.formProgressBarTimeout&&(this.formProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay))}hideFormProgressBar(){this.progressBar.hide(),null!=this.formProgressBarTimeout&&(window.clearTimeout(this.formProgressBarTimeout),delete this.formProgressBarTimeout)}showProgressBar=()=>{this.progressBar.show()};reload(e){p("turbo:reload",{detail:e}),window.location.href=this.location?.toString()||window.location.href}get navigator(){return this.session.navigator}}class Me{selector="[data-turbo-temporary]";deprecatedSelector="[data-turbo-cache=false]";started=!1;start(){this.started||(this.started=!0,addEventListener("turbo:before-cache",this.removeTemporaryElements,!1))}stop(){this.started&&(this.started=!1,removeEventListener("turbo:before-cache",this.removeTemporaryElements,!1))}removeTemporaryElements=e=>{for(const e of this.temporaryElements)e.remove()};get temporaryElements(){return[...document.querySelectorAll(this.selector),...this.temporaryElementsWithDeprecation]}get temporaryElementsWithDeprecation(){const e=document.querySelectorAll(this.deprecatedSelector);return e.length&&console.warn(`The ${this.deprecatedSelector} selector is deprecated and will be removed in a future version. Use ${this.selector} instead.`),[...e]}}class Fe{constructor(e,t){this.session=e,this.element=t,this.linkInterceptor=new te(this,t),this.formSubmitObserver=new Y(this,t)}start(){this.linkInterceptor.start(),this.formSubmitObserver.start()}stop(){this.linkInterceptor.stop(),this.formSubmitObserver.stop()}shouldInterceptLinkClick(e,t,s){return this.#c(e)}linkClickIntercepted(e,t,s){const i=this.#l(e);i&&i.delegate.linkClickIntercepted(e,t,s)}willSubmitForm(e,t){return null==e.closest("turbo-frame")&&this.#h(e,t)&&this.#c(e,t)}formSubmitted(e,t){const s=this.#l(e,t);s&&s.delegate.formSubmitted(e,t)}#h(e,t){const s=o(e,t),i=this.element.ownerDocument.querySelector('meta[name="turbo-root"]'),n=r(i?.content??"/");return this.#c(e,t)&&l(s,n)}#c(e,t){if(e instanceof HTMLFormElement?this.session.submissionIsNavigatable(e,t):this.session.elementIsNavigatable(e)){const s=this.#l(e,t);return!!s&&s!=e.closest("turbo-frame")}return!1}#l(e,t){const s=t?.getAttribute("data-turbo-frame")||e.getAttribute("data-turbo-frame");if(s&&"_top"!=s){const e=this.element.querySelector(`#${s}:not([disabled])`);if(e instanceof i)return e}}}class Ie{location;restorationIdentifier=w();restorationData={};started=!1;pageLoaded=!1;currentIndex=0;constructor(e){this.delegate=e}start(){this.started||(addEventListener("popstate",this.onPopState,!1),addEventListener("load",this.onPageLoad,!1),this.currentIndex=history.state?.turbo?.restorationIndex||0,this.started=!0,this.replace(new URL(window.location.href)))}stop(){this.started&&(removeEventListener("popstate",this.onPopState,!1),removeEventListener("load",this.onPageLoad,!1),this.started=!1)}push(e,t){this.update(history.pushState,e,t)}replace(e,t){this.update(history.replaceState,e,t)}update(e,t,s=w()){e===history.pushState&&++this.currentIndex;const i={turbo:{restorationIdentifier:s,restorationIndex:this.currentIndex}};e.call(history,i,"",t.href),this.location=t,this.restorationIdentifier=s}getRestorationDataForIdentifier(e){return this.restorationData[e]||{}}updateRestorationData(e){const{restorationIdentifier:t}=this,s=this.restorationData[t];this.restorationData[t]={...s,...e}}assumeControlOfScrollRestoration(){this.previousScrollRestoration||(this.previousScrollRestoration=history.scrollRestoration??"auto",history.scrollRestoration="manual")}relinquishControlOfScrollRestoration(){this.previousScrollRestoration&&(history.scrollRestoration=this.previousScrollRestoration,delete this.previousScrollRestoration)}onPopState=e=>{if(this.shouldHandlePopState()){const{turbo:t}=e.state||{};if(t){this.location=new URL(window.location.href);const{restorationIdentifier:e,restorationIndex:s}=t;this.restorationIdentifier=e;const i=s>this.currentIndex?"forward":"back";this.delegate.historyPoppedToLocationWithRestorationIdentifierAndDirection(this.location,e,i),this.currentIndex=s}}};onPageLoad=async e=>{await Promise.resolve(),this.pageLoaded=!0};shouldHandlePopState(){return this.pageIsLoaded()}pageIsLoaded(){return this.pageLoaded||"complete"==document.readyState}}class He{constructor(e){this.delegate=e}proposeVisit(e,t={}){this.delegate.allowsVisitingLocationWithAction(e,t.action)&&this.delegate.visitProposedToLocation(e,t)}startVisit(e,t,s={}){this.stop(),this.currentVisit=new Te(this,r(e),t,{referrer:this.location,...s}),this.currentVisit.start()}submitForm(e,t){this.stop(),this.formSubmission=new J(this,e,t,!0),this.formSubmission.start()}stop(){this.formSubmission&&(this.formSubmission.stop(),delete this.formSubmission),this.currentVisit&&(this.currentVisit.cancel(),delete this.currentVisit)}get adapter(){return this.delegate.adapter}get view(){return this.delegate.view}get rootLocation(){return this.view.snapshot.rootLocation}get history(){return this.delegate.history}formSubmissionStarted(e){"function"==typeof this.adapter.formSubmissionStarted&&this.adapter.formSubmissionStarted(e)}async formSubmissionSucceededWithResponse(e,t){if(e==this.formSubmission){const s=await t.responseHTML;if(s){const i=e.isSafe;i||this.view.clearSnapshotCache();const{statusCode:r,redirected:n}=t,o={action:this.#d(e,t),shouldCacheSnapshot:i,response:{statusCode:r,responseHTML:s,redirected:n}};this.proposeVisit(t.location,o)}}}async formSubmissionFailedWithResponse(e,t){const s=await t.responseHTML;if(s){const e=de.fromHTMLString(s);t.serverError?await this.view.renderError(e,this.currentVisit):await this.view.renderPage(e,!1,!0,this.currentVisit),e.shouldPreserveScrollPosition||this.view.scrollToTop(),this.view.clearSnapshotCache()}}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished(e){"function"==typeof this.adapter.formSubmissionFinished&&this.adapter.formSubmissionFinished(e)}visitStarted(e){this.delegate.visitStarted(e)}visitCompleted(e){this.delegate.visitCompleted(e)}locationWithActionIsSamePage(e,t){const s=n(e),i=n(this.view.lastRenderedLocation),r="restore"===t&&void 0===s;return"replace"!==t&&h(e)===h(this.view.lastRenderedLocation)&&(r||null!=s&&s!==i)}visitScrolledToSamePageLocation(e,t){this.delegate.visitScrolledToSamePageLocation(e,t)}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}#d(e,t){const{submitter:s,formElement:i}=e;return C(s,i)||this.#u(t)}#u(e){return e.redirected&&e.location.href===this.location?.href?"replace":"advance"}}const qe=0,Be=1,Oe=2,Ne=3;class xe{stage=qe;started=!1;constructor(e){this.delegate=e}start(){this.started||(this.stage==qe&&(this.stage=Be),document.addEventListener("readystatechange",this.interpretReadyState,!1),addEventListener("pagehide",this.pageWillUnload,!1),this.started=!0)}stop(){this.started&&(document.removeEventListener("readystatechange",this.interpretReadyState,!1),removeEventListener("pagehide",this.pageWillUnload,!1),this.started=!1)}interpretReadyState=()=>{const{readyState:e}=this;"interactive"==e?this.pageIsInteractive():"complete"==e&&this.pageIsComplete()};pageIsInteractive(){this.stage==Be&&(this.stage=Oe,this.delegate.pageBecameInteractive())}pageIsComplete(){this.pageIsInteractive(),this.stage==Oe&&(this.stage=Ne,this.delegate.pageLoaded())}pageWillUnload=()=>{this.delegate.pageWillUnload()};get readyState(){return document.readyState}}class Ve{started=!1;constructor(e){this.delegate=e}start(){this.started||(addEventListener("scroll",this.onScroll,!1),this.onScroll(),this.started=!0)}stop(){this.started&&(removeEventListener("scroll",this.onScroll,!1),this.started=!1)}onScroll=()=>{this.updatePosition({x:window.pageXOffset,y:window.pageYOffset})};updatePosition(e){this.delegate.scrollPositionChanged(e)}}class De{render({fragment:e}){re.preservingPermanentElements(this,function(e){const t=Q(document.documentElement),s={};for(const i of t){const{id:t}=i;for(const r of e.querySelectorAll("turbo-stream")){const e=X(r.templateElement.content,t);e&&(s[t]=[i,e])}}return s}(e),(()=>{!async function(e,t){const s=`turbo-stream-autofocus-${w()}`,i=e.querySelectorAll("turbo-stream"),r=function(e){for(const t of e){const e=F(t.templateElement.content);if(e)return e}return null}(i);let n=null;r&&(n=r.id?r.id:s,r.id=n);t(),await f();if((null==document.activeElement||document.activeElement==document.body)&&n){const e=document.getElementById(n);M(e)&&e.focus(),e&&e.id==s&&e.removeAttribute("id")}}(e,(()=>{!async function(e){const[t,s]=await async function(e,t){const s=t();return e(),await g(),[s,t()]}(e,(()=>document.activeElement)),i=t&&t.id;if(i){const e=document.getElementById(i);M(e)&&e!=s&&e.focus()}}((()=>{document.documentElement.appendChild(e)}))}))}))}enteringBardo(e,t){t.replaceWith(e.cloneNode(!0))}leavingBardo(){}}class We{sources=new Set;#m=!1;constructor(e){this.delegate=e}start(){this.#m||(this.#m=!0,addEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}stop(){this.#m&&(this.#m=!1,removeEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}connectStreamSource(e){this.streamSourceIsConnected(e)||(this.sources.add(e),e.addEventListener("message",this.receiveMessageEvent,!1))}disconnectStreamSource(e){this.streamSourceIsConnected(e)&&(this.sources.delete(e),e.removeEventListener("message",this.receiveMessageEvent,!1))}streamSourceIsConnected(e){return this.sources.has(e)}inspectFetchResponse=e=>{const t=function(e){const t=e.detail?.fetchResponse;if(t instanceof u)return t}(e);t&&function(e){const t=e.contentType??"";return t.startsWith(z.contentType)}(t)&&(e.preventDefault(),this.receiveMessageResponse(t))};receiveMessageEvent=e=>{this.#m&&"string"==typeof e.data&&this.receiveMessageHTML(e.data)};async receiveMessageResponse(e){const t=await e.responseHTML;t&&this.receiveMessageHTML(t)}receiveMessageHTML(e){this.delegate.receivedMessageFromStream(z.wrap(e))}}class Ue extends ne{static renderElement(e,t){const{documentElement:s,body:i}=document;s.replaceChild(t,i)}async render(){this.replaceHeadAndBody(),this.activateScriptElements()}replaceHeadAndBody(){const{documentElement:e,head:t}=document;e.replaceChild(this.newHead,t),this.renderElement(this.currentElement,this.newElement)}activateScriptElements(){for(const e of this.scriptElements){const t=e.parentNode;if(t){const s=m(e);t.replaceChild(s,e)}}}get newHead(){return this.newSnapshot.headSnapshot.element}get scriptElements(){return document.documentElement.querySelectorAll("script")}}let _e=new Set;function $e(e,t,s){if(s.head.block){let i=e.querySelector("head"),r=t.querySelector("head");if(i&&r){let n=Je(r,i,s);return void Promise.all(n).then((function(){$e(e,t,Object.assign(s,{head:{block:!1,ignore:!0}}))}))}}if("innerHTML"===s.morphStyle)return ze(t,e,s),e.children;if("outerHTML"===s.morphStyle||null==s.morphStyle){let i=function(e,t,s){let i;i=e.firstChild;let r=i,n=0;for(;i;){let e=tt(i,t,s);e>n&&(r=i,n=e),i=i.nextSibling}return r}(t,e,s),r=i?.previousSibling,n=i?.nextSibling,o=je(e,i,s);return i?function(e,t,s){let i=[],r=[];for(;null!=e;)i.push(e),e=e.previousSibling;for(;i.length>0;){let e=i.pop();r.push(e),t.parentElement.insertBefore(e,t)}r.push(t);for(;null!=s;)i.push(s),r.push(s),s=s.nextSibling;for(;i.length>0;)t.parentElement.insertBefore(i.pop(),t.nextSibling);return r}(r,o,n):[]}throw"Do not understand how to morph style "+s.morphStyle}function je(e,t,s){if(!s.ignoreActive||e!==document.activeElement){if(null==t){if(!1===s.callbacks.beforeNodeRemoved(e))return;return e.remove(),s.callbacks.afterNodeRemoved(e),null}if(Qe(e,t)){if(!1===s.callbacks.beforeNodeMorphed(e,t))return;return e instanceof HTMLHeadElement&&s.head.ignore||(e instanceof HTMLHeadElement&&"morph"!==s.head.style?Je(t,e,s):(!function(e,t){let s=e.nodeType;if(1===s){const s=e.attributes,i=t.attributes;for(const e of s)t.getAttribute(e.name)!==e.value&&t.setAttribute(e.name,e.value);for(const s of i)e.hasAttribute(s.name)||t.removeAttribute(s.name)}8!==s&&3!==s||t.nodeValue!==e.nodeValue&&(t.nodeValue=e.nodeValue);if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==e.type)t.value=e.value||"",Ge(e,t,"value"),Ge(e,t,"checked"),Ge(e,t,"disabled");else if(e instanceof HTMLOptionElement)Ge(e,t,"selected");else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let s=e.value;s!==t.value&&(t.value=s),t.firstChild&&t.firstChild.nodeValue!==s&&(t.firstChild.nodeValue=s)}}(t,e),ze(t,e,s))),s.callbacks.afterNodeMorphed(e,t),e}if(!1===s.callbacks.beforeNodeRemoved(e))return;if(!1===s.callbacks.beforeNodeAdded(t))return;return e.parentElement.replaceChild(t,e),s.callbacks.afterNodeAdded(t),s.callbacks.afterNodeRemoved(e),t}}function ze(e,t,s){let i,r=e.firstChild,n=t.firstChild;for(;r;){if(i=r,r=i.nextSibling,null==n){if(!1===s.callbacks.beforeNodeAdded(i))return;t.appendChild(i),s.callbacks.afterNodeAdded(i),nt(s,i);continue}if(Xe(i,n,s)){je(n,i,s),n=n.nextSibling,nt(s,i);continue}let o=Ze(e,t,i,n,s);if(o){n=Ye(n,o,s),je(o,i,s),nt(s,i);continue}let a=et(e,t,i,n,s);if(a)n=Ye(n,a,s),je(a,i,s),nt(s,i);else{if(!1===s.callbacks.beforeNodeAdded(i))return;t.insertBefore(i,n),s.callbacks.afterNodeAdded(i),nt(s,i)}}for(;null!==n;){let e=n;n=n.nextSibling,st(e,s)}}function Ge(e,t,s){e[s]!==t[s]&&(e[s]?t.setAttribute(s,e[s]):t.removeAttribute(s))}function Je(e,t,s){let i=[],r=[],n=[],o=[],a=s.head.style,c=new Map;for(const t of e.children)c.set(t.outerHTML,t);for(const e of t.children){let t=c.has(e.outerHTML),i=s.head.shouldReAppend(e),l=s.head.shouldPreserve(e);t||l?i?r.push(e):(c.delete(e.outerHTML),n.push(e)):"append"===a?i&&(r.push(e),o.push(e)):!1!==s.head.shouldRemove(e)&&r.push(e)}o.push(...c.values());let l=[];for(const e of o){let r=document.createRange().createContextualFragment(e.outerHTML).firstChild;if(!1!==s.callbacks.beforeNodeAdded(r)){if(r.href||r.src){let e=null,t=new Promise((function(t){e=t}));r.addEventListener("load",(function(){e()})),l.push(t)}t.appendChild(r),s.callbacks.afterNodeAdded(r),i.push(r)}}for(const e of r)!1!==s.callbacks.beforeNodeRemoved(e)&&(t.removeChild(e),s.callbacks.afterNodeRemoved(e));return s.head.afterHeadMorphed(t,{added:i,kept:n,removed:r}),l}function Ke(){}function Xe(e,t,s){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName&&(""!==e.id&&e.id===t.id||ot(s,e,t)>0))}function Qe(e,t){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName)}function Ye(e,t,s){for(;e!==t;){let t=e;e=e.nextSibling,st(t,s)}return nt(s,t),t.nextSibling}function Ze(e,t,s,i,r){let n=ot(r,s,t);if(n>0){let t=i,o=0;for(;null!=t;){if(Xe(s,t,r))return t;if(o+=ot(r,t,e),o>n)return null;t=t.nextSibling}}return null}function et(e,t,s,i,r){let n=i,o=s.nextSibling,a=0;for(;null!=n;){if(ot(r,n,e)>0)return null;if(Qe(s,n))return n;if(Qe(o,n)&&(a++,o=o.nextSibling,a>=2))return null;n=n.nextSibling}return n}function tt(e,t,s){return Qe(e,t)?.5+ot(s,e,t):0}function st(e,t){nt(t,e),!1!==t.callbacks.beforeNodeRemoved(e)&&(e.remove(),t.callbacks.afterNodeRemoved(e))}function it(e,t){return!e.deadIds.has(t)}function rt(e,t,s){return(e.idMap.get(s)||_e).has(t)}function nt(e,t){let s=e.idMap.get(t)||_e;for(const t of s)e.deadIds.add(t)}function ot(e,t,s){let i=e.idMap.get(t)||_e,r=0;for(const t of i)it(e,t)&&rt(e,t,s)&&++r;return r}function at(e,t){let s=e.parentElement,i=e.querySelectorAll("[id]");for(const e of i){let i=e;for(;i!==s&&null!=i;){let s=t.get(i);null==s&&(s=new Set,t.set(i,s)),s.add(e.id),i=i.parentElement}}}function ct(e,t){let s=new Map;return at(e,s),at(t,s),s}var lt={morph:function(e,t,s={}){e instanceof Document&&(e=e.documentElement),"string"==typeof t&&(t=function(e){let t=new DOMParser,s=e.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(s.match(/<\/html>/)||s.match(/<\/head>/)||s.match(/<\/body>/)){let i=t.parseFromString(e,"text/html");if(s.match(/<\/html>/))return i.generatedByIdiomorph=!0,i;{let e=i.firstChild;return e?(e.generatedByIdiomorph=!0,e):null}}{let s=t.parseFromString("<body><template>"+e+"</template></body>","text/html").body.querySelector("template").content;return s.generatedByIdiomorph=!0,s}}(t));let i=function(e){if(null==e){return document.createElement("div")}if(e.generatedByIdiomorph)return e;if(e instanceof Node){const t=document.createElement("div");return t.append(e),t}{const t=document.createElement("div");for(const s of[...e])t.append(s);return t}}(t),r=function(e,t,s){return{target:e,newContent:t,config:s,morphStyle:s.morphStyle,ignoreActive:s.ignoreActive,idMap:ct(e,t),deadIds:new Set,callbacks:Object.assign({beforeNodeAdded:Ke,afterNodeAdded:Ke,beforeNodeMorphed:Ke,afterNodeMorphed:Ke,beforeNodeRemoved:Ke,afterNodeRemoved:Ke},s.callbacks),head:Object.assign({style:"merge",shouldPreserve:function(e){return"true"===e.getAttribute("im-preserve")},shouldReAppend:function(e){return"true"===e.getAttribute("im-re-append")},shouldRemove:Ke,afterHeadMorphed:Ke},s.head)}}(e,i,s);return $e(e,i,r)}};class ht extends ne{async render(){this.willRender&&await this.#p()}get renderMethod(){return"morph"}async#p(){this.#f(this.currentElement,this.newElement),this.#g(),p("turbo:morph",{detail:{currentElement:this.currentElement,newElement:this.newElement}})}#f(e,t,s="outerHTML"){this.isMorphingTurboFrame=this.#b(e),lt.morph(e,t,{morphStyle:s,callbacks:{beforeNodeAdded:this.#v,beforeNodeMorphed:this.#S,beforeNodeRemoved:this.#w}})}#v=e=>!(e.id&&e.hasAttribute("data-turbo-permanent")&&document.getElementById(e.id));#S=(e,t)=>!(e instanceof HTMLElement)||!e.hasAttribute("data-turbo-permanent")&&(this.isMorphingTurboFrame||!this.#b(e));#w=e=>this.#S(e);#g(){this.#y().forEach((e=>{this.#b(e)&&(this.#E(e),e.reload())}))}#E(e){e.addEventListener("turbo:before-frame-render",(e=>{e.detail.render=this.#A}),{once:!0})}#A=(e,t)=>{p("turbo:before-frame-morph",{target:e,detail:{currentElement:e,newElement:t}}),this.#f(e,t.children,"innerHTML")};#b(e){return e.src&&"morph"===e.refresh}#y(){return Array.from(document.querySelectorAll("turbo-frame[src]")).filter((e=>!e.closest("[data-turbo-permanent]")))}}class dt extends ne{static renderElement(e,t){document.body&&t instanceof HTMLBodyElement?document.body.replaceWith(t):document.documentElement.appendChild(t)}get shouldRender(){return this.newSnapshot.isVisitable&&this.trackedElementsAreIdentical}get reloadReason(){return this.newSnapshot.isVisitable?this.trackedElementsAreIdentical?void 0:{reason:"tracked_element_mismatch"}:{reason:"turbo_visit_control_is_reload"}}async prepareToRender(){this.#R(),await this.mergeHead()}async render(){this.willRender&&await this.replaceBody()}finishRendering(){super.finishRendering(),this.isPreview||this.focusFirstAutofocusableElement()}get currentHeadSnapshot(){return this.currentSnapshot.headSnapshot}get newHeadSnapshot(){return this.newSnapshot.headSnapshot}get newElement(){return this.newSnapshot.element}#R(){const{documentElement:e}=this.currentSnapshot,{lang:t}=this.newSnapshot;t?e.setAttribute("lang",t):e.removeAttribute("lang")}async mergeHead(){const e=this.mergeProvisionalElements(),t=this.copyNewHeadStylesheetElements();this.copyNewHeadScriptElements(),await e,await t}async replaceBody(){await this.preservingPermanentElements((async()=>{this.activateNewBody(),await this.assignNewBody()}))}get trackedElementsAreIdentical(){return this.currentHeadSnapshot.trackedElementSignature==this.newHeadSnapshot.trackedElementSignature}async copyNewHeadStylesheetElements(){const e=[];for(const t of this.newHeadStylesheetElements)e.push(R(t)),document.head.appendChild(t);await Promise.all(e)}copyNewHeadScriptElements(){for(const e of this.newHeadScriptElements)document.head.appendChild(m(e))}async mergeProvisionalElements(){const e=[...this.newHeadProvisionalElements];for(const t of this.currentHeadProvisionalElements)this.isCurrentElementInElementList(t,e)||document.head.removeChild(t);for(const t of e)document.head.appendChild(t)}isCurrentElementInElementList(e,t){for(const[s,i]of t.entries()){if("TITLE"==e.tagName){if("TITLE"!=i.tagName)continue;if(e.innerHTML==i.innerHTML)return t.splice(s,1),!0}if(i.isEqualNode(e))return t.splice(s,1),!0}return!1}removeCurrentHeadProvisionalElements(){for(const e of this.currentHeadProvisionalElements)document.head.removeChild(e)}copyNewHeadProvisionalElements(){for(const e of this.newHeadProvisionalElements)document.head.appendChild(e)}activateNewBody(){document.adoptNode(this.newElement),this.activateNewBodyScriptElements()}activateNewBodyScriptElements(){for(const e of this.newBodyScriptElements){const t=m(e);e.replaceWith(t)}}async assignNewBody(){await this.renderElement(this.currentElement,this.newElement)}get newHeadStylesheetElements(){return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot)}get newHeadScriptElements(){return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot)}get currentHeadProvisionalElements(){return this.currentHeadSnapshot.provisionalElements}get newHeadProvisionalElements(){return this.newHeadSnapshot.provisionalElements}get newBodyScriptElements(){return this.newElement.querySelectorAll("script")}}class ut{keys=[];snapshots={};constructor(e){this.size=e}has(e){return d(e)in this.snapshots}get(e){if(this.has(e)){const t=this.read(e);return this.touch(e),t}}put(e,t){return this.write(e,t),this.touch(e),t}clear(){this.snapshots={}}read(e){return this.snapshots[d(e)]}write(e,t){this.snapshots[d(e)]=t}touch(e){const t=d(e),s=this.keys.indexOf(t);s>-1&&this.keys.splice(s,1),this.keys.unshift(t),this.trim()}trim(){for(const e of this.keys.splice(this.size))delete this.snapshots[e]}}class mt extends Z{snapshotCache=new ut(10);lastRenderedLocation=new URL(location.href);forceReloaded=!1;shouldTransitionTo(e){return this.snapshot.prefersViewTransitions&&e.prefersViewTransitions}renderPage(e,t=!1,s=!0,i){const r=new(this.isPageRefresh(i)&&this.snapshot.shouldMorphPage?ht:dt)(this.snapshot,e,dt.renderElement,t,s);return r.shouldRender?i?.changeHistory():this.forceReloaded=!0,this.render(r)}renderError(e,t){t?.changeHistory();const s=new Ue(this.snapshot,e,Ue.renderElement,!1);return this.render(s)}clearSnapshotCache(){this.snapshotCache.clear()}async cacheSnapshot(e=this.snapshot){if(e.isCacheable){this.delegate.viewWillCacheSnapshot();const{lastRenderedLocation:t}=this;await b();const s=e.clone();return this.snapshotCache.put(t,s),s}}getCachedSnapshotForLocation(e){return this.snapshotCache.get(e)}isPageRefresh(e){return!e||this.lastRenderedLocation.pathname===e.location.pathname&&"replace"===e.action}shouldPreserveScrollPosition(e){return this.isPageRefresh(e)&&this.snapshot.shouldPreserveScrollPosition}get snapshot(){return de.fromElement(this.element)}}class pt{selector="a[data-turbo-preload]";constructor(e,t){this.delegate=e,this.snapshotCache=t}start(){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",this.#L):this.preloadOnLoadLinksForView(document.body)}stop(){document.removeEventListener("DOMContentLoaded",this.#L)}preloadOnLoadLinksForView(e){for(const t of e.querySelectorAll(this.selector))this.delegate.shouldPreloadLink(t)&&this.preloadURL(t)}async preloadURL(e){const t=new URL(e.href);if(this.snapshotCache.has(t))return;const s=new D(this,N.get,t,new URLSearchParams,e);await s.perform()}prepareRequest(e){e.headers["Sec-Purpose"]="prefetch"}async requestSucceededWithResponse(e,t){try{const s=await t.responseHTML,i=de.fromHTMLString(s);this.snapshotCache.put(e.url,i)}catch(e){}}requestStarted(e){}requestErrored(e){}requestFinished(e){}requestPreventedHandlingResponse(e,t){}requestFailedWithResponse(e,t){}#L=()=>{this.preloadOnLoadLinksForView(document.body)}}class ft{constructor(e){this.session=e}clear(){this.session.clearCache()}resetCacheControl(){this.#C("")}exemptPageFromCache(){this.#C("no-cache")}exemptPageFromPreview(){this.#C("no-preview")}#C(e){!function(e,t){let s=T(e);s||(s=document.createElement("meta"),s.setAttribute("name",e),document.head.appendChild(s)),s.setAttribute("content",t)}("turbo-cache-control",e)}}function gt(e){Object.defineProperties(e,bt)}const bt={absoluteURL:{get(){return this.toString()}}},vt=new class{navigator=new He(this);history=new Ie(this);view=new mt(this,document.documentElement);adapter=new ke(this);pageObserver=new xe(this);cacheObserver=new Me;linkClickObserver=new se(this,window);formSubmitObserver=new Y(this,document);scrollObserver=new Ve(this);streamObserver=new We(this);formLinkClickObserver=new ie(this,document.documentElement);frameRedirector=new Fe(this,document.documentElement);streamMessageRenderer=new De;cache=new ft(this);drive=!0;enabled=!0;progressBarDelay=500;started=!1;formMode="on";constructor(e){this.recentRequests=e,this.preloader=new pt(this,this.view.snapshotCache)}start(){this.started||(this.pageObserver.start(),this.cacheObserver.start(),this.formLinkClickObserver.start(),this.linkClickObserver.start(),this.formSubmitObserver.start(),this.scrollObserver.start(),this.streamObserver.start(),this.frameRedirector.start(),this.history.start(),this.preloader.start(),this.started=!0,this.enabled=!0)}disable(){this.enabled=!1}stop(){this.started&&(this.pageObserver.stop(),this.cacheObserver.stop(),this.formLinkClickObserver.stop(),this.linkClickObserver.stop(),this.formSubmitObserver.stop(),this.scrollObserver.stop(),this.streamObserver.stop(),this.frameRedirector.stop(),this.history.stop(),this.preloader.stop(),this.started=!1)}registerAdapter(e){this.adapter=e}visit(e,t={}){const s=t.frame?document.getElementById(t.frame):null;s instanceof i?(s.src=e.toString(),s.loaded):this.navigator.proposeVisit(r(e),t)}refresh(e,t){t&&this.recentRequests.has(t)||(this.cache.exemptPageFromPreview(),this.visit(e,{action:"replace"}))}connectStreamSource(e){this.streamObserver.connectStreamSource(e)}disconnectStreamSource(e){this.streamObserver.disconnectStreamSource(e)}renderStreamMessage(e){this.streamMessageRenderer.render(z.wrap(e))}clearCache(){this.view.clearSnapshotCache()}setProgressBarDelay(e){this.progressBarDelay=e}setFormMode(e){this.formMode=e}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}shouldPreloadLink(e){const t=e.hasAttribute("data-turbo-method"),s=e.hasAttribute("data-turbo-stream"),r=e.getAttribute("data-turbo-frame"),n="_top"==r?null:document.getElementById(r)||k(e,"turbo-frame:not([disabled])");if(t||s||n instanceof i)return!1;{const t=new URL(e.href);return this.elementIsNavigatable(e)&&l(t,this.snapshot.rootLocation)}}historyPoppedToLocationWithRestorationIdentifierAndDirection(e,t,s){this.enabled?this.navigator.startVisit(e,t,{action:"restore",historyChanged:!0,direction:s}):this.adapter.pageInvalidated({reason:"turbo_disabled"})}scrollPositionChanged(e){this.history.updateRestorationData({scrollPosition:e})}willSubmitFormLinkToLocation(e,t){return this.elementIsNavigatable(e)&&l(t,this.snapshot.rootLocation)}submittedFormLinkToLocation(){}willFollowLinkToLocation(e,t,s){return this.elementIsNavigatable(e)&&l(t,this.snapshot.rootLocation)&&this.applicationAllowsFollowingLinkToLocation(e,t,s)}followedLinkToLocation(e,t){const s=this.getActionForLink(e),i=e.hasAttribute("data-turbo-stream");this.visit(t.href,{action:s,acceptsStreamResponse:i})}allowsVisitingLocationWithAction(e,t){return this.locationWithActionIsSamePage(e,t)||this.applicationAllowsVisitingLocation(e)}visitProposedToLocation(e,t){gt(e),this.adapter.visitProposedToLocation(e,t)}visitStarted(e){e.acceptsStreamResponse||(E(document.documentElement),this.view.markVisitDirection(e.direction)),gt(e.location),e.silent||this.notifyApplicationAfterVisitingLocation(e.location,e.action)}visitCompleted(e){this.view.unmarkVisitDirection(),A(document.documentElement),this.notifyApplicationAfterPageLoad(e.getTimingMetrics())}locationWithActionIsSamePage(e,t){return this.navigator.locationWithActionIsSamePage(e,t)}visitScrolledToSamePageLocation(e,t){this.notifyApplicationAfterVisitingSamePageLocation(e,t)}willSubmitForm(e,t){const s=o(e,t);return this.submissionIsNavigatable(e,t)&&l(r(s),this.snapshot.rootLocation)}formSubmitted(e,t){this.navigator.submitForm(e,t)}pageBecameInteractive(){this.view.lastRenderedLocation=this.location,this.notifyApplicationAfterPageLoad()}pageLoaded(){this.history.assumeControlOfScrollRestoration()}pageWillUnload(){this.history.relinquishControlOfScrollRestoration()}receivedMessageFromStream(e){this.renderStreamMessage(e)}viewWillCacheSnapshot(){this.navigator.currentVisit?.silent||this.notifyApplicationBeforeCachingSnapshot()}allowsImmediateRender({element:e},t,s){const i=this.notifyApplicationBeforeRender(e,t,s),{defaultPrevented:r,detail:{render:n}}=i;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!r}viewRenderedSnapshot(e,t,s){this.view.lastRenderedLocation=this.history.location,this.notifyApplicationAfterRender(t,s)}preloadOnLoadLinksForView(e){this.preloader.preloadOnLoadLinksForView(e)}viewInvalidated(e){this.adapter.pageInvalidated(e)}frameLoaded(e){this.notifyApplicationAfterFrameLoad(e)}frameRendered(e,t){this.notifyApplicationAfterFrameRender(e,t)}applicationAllowsFollowingLinkToLocation(e,t,s){return!this.notifyApplicationAfterClickingLinkToLocation(e,t,s).defaultPrevented}applicationAllowsVisitingLocation(e){return!this.notifyApplicationBeforeVisitingLocation(e).defaultPrevented}notifyApplicationAfterClickingLinkToLocation(e,t,s){return p("turbo:click",{target:e,detail:{url:t.href,originalEvent:s},cancelable:!0})}notifyApplicationBeforeVisitingLocation(e){return p("turbo:before-visit",{detail:{url:e.href},cancelable:!0})}notifyApplicationAfterVisitingLocation(e,t){return p("turbo:visit",{detail:{url:e.href,action:t}})}notifyApplicationBeforeCachingSnapshot(){return p("turbo:before-cache")}notifyApplicationBeforeRender(e,t,s){return p("turbo:before-render",{detail:{newBody:e,isPreview:t,...s},cancelable:!0})}notifyApplicationAfterRender(e,t){return p("turbo:render",{detail:{isPreview:e,renderMethod:t}})}notifyApplicationAfterPageLoad(e={}){return p("turbo:load",{detail:{url:this.location.href,timing:e}})}notifyApplicationAfterVisitingSamePageLocation(e,t){dispatchEvent(new HashChangeEvent("hashchange",{oldURL:e.toString(),newURL:t.toString()}))}notifyApplicationAfterFrameLoad(e){return p("turbo:frame-load",{target:e})}notifyApplicationAfterFrameRender(e,t){return p("turbo:frame-render",{detail:{fetchResponse:e},target:t,cancelable:!0})}submissionIsNavigatable(e,t){if("off"==this.formMode)return!1;{const s=!t||this.elementIsNavigatable(t);return"optin"==this.formMode?s&&null!=e.closest('[data-turbo="true"]'):s&&this.elementIsNavigatable(e)}}elementIsNavigatable(e){const t=k(e,"[data-turbo]"),s=k(e,"turbo-frame");return this.drive||s?!t||"false"!=t.getAttribute("data-turbo"):!!t&&"true"==t.getAttribute("data-turbo")}getActionForLink(e){return C(e)||"advance"}get snapshot(){return this.view.snapshot}}(H),{cache:St,navigator:wt}=vt;function yt(){vt.start()}function Et(e){vt.registerAdapter(e)}function At(e,t){vt.visit(e,t)}function Rt(e){vt.connectStreamSource(e)}function Lt(e){vt.disconnectStreamSource(e)}function Ct(e){vt.renderStreamMessage(e)}function Tt(){console.warn("Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),vt.clearCache()}function Pt(e){vt.setProgressBarDelay(e)}function kt(e){J.confirmMethod=e}function Mt(e){vt.setFormMode(e)}var Ft=Object.freeze({__proto__:null,navigator:wt,session:vt,cache:St,PageRenderer:dt,PageSnapshot:de,FrameRenderer:oe,fetch:B,start:yt,registerAdapter:Et,visit:At,connectStreamSource:Rt,disconnectStreamSource:Lt,renderStreamMessage:Ct,clearCache:Tt,setProgressBarDelay:Pt,setConfirmMethod:kt,setFormMode:Mt});class It extends Error{}function Ht(e){if(null!=e){const t=document.getElementById(e);if(t instanceof i)return t}}function qt(e,t){if(e){const n=e.getAttribute("src");if(null!=n&&null!=t&&(s=t,r(n).href==r(s).href))throw new Error(`Matching <turbo-frame id="${e.id}"> element has a source URL which references itself`);if(e.ownerDocument!==document&&(e=document.importNode(e,!0)),e instanceof i)return e.connectedCallback(),e.disconnectedCallback(),e}var s}const Bt={after(){this.targetElements.forEach((e=>e.parentElement?.insertBefore(this.templateContent,e.nextSibling)))},append(){this.removeDuplicateTargetChildren(),this.targetElements.forEach((e=>e.append(this.templateContent)))},before(){this.targetElements.forEach((e=>e.parentElement?.insertBefore(this.templateContent,e)))},prepend(){this.removeDuplicateTargetChildren(),this.targetElements.forEach((e=>e.prepend(this.templateContent)))},remove(){this.targetElements.forEach((e=>e.remove()))},replace(){this.targetElements.forEach((e=>e.replaceWith(this.templateContent)))},update(){this.targetElements.forEach((e=>{e.innerHTML="",e.append(this.templateContent)}))},refresh(){vt.refresh(this.baseURI,this.requestId)}};class Ot extends HTMLElement{static async renderElement(e){await e.performAction()}async connectedCallback(){try{await this.render()}catch(e){console.error(e)}finally{this.disconnect()}}async render(){return this.renderPromise??=(async()=>{const e=this.beforeRenderEvent;this.dispatchEvent(e)&&(await f(),await e.detail.render(this))})()}disconnect(){try{this.remove()}catch{}}removeDuplicateTargetChildren(){this.duplicateChildren.forEach((e=>e.remove()))}get duplicateChildren(){const e=this.targetElements.flatMap((e=>[...e.children])).filter((e=>!!e.id)),t=[...this.templateContent?.children||[]].filter((e=>!!e.id)).map((e=>e.id));return e.filter((e=>t.includes(e.id)))}get performAction(){if(this.action){const e=Bt[this.action];if(e)return e;this.#T("unknown action")}this.#T("action attribute is missing")}get targetElements(){return this.target?this.targetElementsById:this.targets?this.targetElementsByQuery:void this.#T("target or targets attribute is missing")}get templateContent(){return this.templateElement.content.cloneNode(!0)}get templateElement(){if(null===this.firstElementChild){const e=this.ownerDocument.createElement("template");return this.appendChild(e),e}if(this.firstElementChild instanceof HTMLTemplateElement)return this.firstElementChild;this.#T("first child element must be a <template> element")}get action(){return this.getAttribute("action")}get target(){return this.getAttribute("target")}get targets(){return this.getAttribute("targets")}get requestId(){return this.getAttribute("request-id")}#T(e){throw new Error(`${this.description}: ${e}`)}get description(){return(this.outerHTML.match(/<[^>]+>/)??[])[0]??"<turbo-stream>"}get beforeRenderEvent(){return new CustomEvent("turbo:before-stream-render",{bubbles:!0,cancelable:!0,detail:{newStream:this,render:Ot.renderElement}})}get targetElementsById(){const e=this.ownerDocument?.getElementById(this.target);return null!==e?[e]:[]}get targetElementsByQuery(){const e=this.ownerDocument?.querySelectorAll(this.targets);return 0!==e.length?Array.prototype.slice.call(e):[]}}class Nt extends HTMLElement{streamSource=null;connectedCallback(){this.streamSource=this.src.match(/^ws{1,2}:/)?new WebSocket(this.src):new EventSource(this.src),Rt(this.streamSource)}disconnectedCallback(){this.streamSource&&(this.streamSource.close(),Lt(this.streamSource))}get src(){return this.getAttribute("src")||""}}i.delegateConstructor=class{fetchResponseLoaded=e=>Promise.resolve();#P=null;#k=()=>{};#M=!1;#F=!1;#I=new Set;action=null;constructor(e){this.element=e,this.view=new ee(this,this.element),this.appearanceObserver=new j(this,this.element),this.formLinkClickObserver=new ie(this,this.element),this.linkInterceptor=new te(this,this.element),this.restorationIdentifier=w(),this.formSubmitObserver=new Y(this,this.element)}connect(){this.#M||(this.#M=!0,this.loadingStyle==s.lazy?this.appearanceObserver.start():this.#H(),this.formLinkClickObserver.start(),this.linkInterceptor.start(),this.formSubmitObserver.start())}disconnect(){this.#M&&(this.#M=!1,this.appearanceObserver.stop(),this.formLinkClickObserver.stop(),this.linkInterceptor.stop(),this.formSubmitObserver.stop())}disabledChanged(){this.loadingStyle==s.eager&&this.#H()}sourceURLChanged(){this.#q("src")||(this.element.isConnected&&(this.complete=!1),(this.loadingStyle==s.eager||this.#F)&&this.#H())}sourceURLReloaded(){const{src:e}=this.element;return this.#B("complete",(()=>{this.element.removeAttribute("complete")})),this.element.src=null,this.element.src=e,this.element.loaded}completeChanged(){this.#q("complete")||this.#H()}loadingStyleChanged(){this.loadingStyle==s.lazy?this.appearanceObserver.start():(this.appearanceObserver.stop(),this.#H())}async#H(){this.enabled&&this.isActive&&!this.complete&&this.sourceURL&&(this.element.loaded=this.#O(r(this.sourceURL)),this.appearanceObserver.stop(),await this.element.loaded,this.#F=!0)}async loadResponse(e){(e.redirected||e.succeeded&&e.isHTML)&&(this.sourceURL=e.response.url);try{const t=await e.responseHTML;if(t){const s=v(t);de.fromDocument(s).isVisitable?await this.#N(e,s):await this.#x(e)}}finally{this.fetchResponseLoaded=()=>Promise.resolve()}}elementAppearedInViewport(e){this.proposeVisitIfNavigatedWithAction(e,e),this.#H()}willSubmitFormLinkToLocation(e){return this.#V(e)}submittedFormLinkToLocation(e,t,s){const i=this.#l(e);i&&s.setAttribute("data-turbo-frame",i.id)}shouldInterceptLinkClick(e,t,s){return this.#V(e)}linkClickIntercepted(e,t){this.#D(e,t)}willSubmitForm(e,t){return e.closest("turbo-frame")==this.element&&this.#V(e,t)}formSubmitted(e,t){this.formSubmission&&this.formSubmission.stop(),this.formSubmission=new J(this,e,t);const{fetchRequest:s}=this.formSubmission;this.prepareRequest(s),this.formSubmission.start()}prepareRequest(e){e.headers["Turbo-Frame"]=this.id,this.currentNavigationElement?.hasAttribute("data-turbo-stream")&&e.acceptResponseType(z.contentType)}requestStarted(e){E(this.element)}requestPreventedHandlingResponse(e,t){this.#k()}async requestSucceededWithResponse(e,t){await this.loadResponse(t),this.#k()}async requestFailedWithResponse(e,t){await this.loadResponse(t),this.#k()}requestErrored(e,t){console.error(t),this.#k()}requestFinished(e){A(this.element)}formSubmissionStarted({formElement:e}){E(e,this.#l(e))}formSubmissionSucceededWithResponse(e,t){const s=this.#l(e.formElement,e.submitter);s.delegate.proposeVisitIfNavigatedWithAction(s,e.formElement,e.submitter),s.delegate.loadResponse(t),e.isSafe||vt.clearCache()}formSubmissionFailedWithResponse(e,t){this.element.delegate.loadResponse(t),vt.clearCache()}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished({formElement:e}){A(e,this.#l(e))}allowsImmediateRender({element:e},t,s){const i=p("turbo:before-frame-render",{target:this.element,detail:{newFrame:e,...s},cancelable:!0}),{defaultPrevented:r,detail:{render:n}}=i;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!r}viewRenderedSnapshot(e,t,s){}preloadOnLoadLinksForView(e){vt.preloadOnLoadLinksForView(e)}viewInvalidated(){}willRenderFrame(e,t){this.previousFrameElement=e.cloneNode(!0)}visitCachedSnapshot=({element:e})=>{const t=e.querySelector("#"+this.element.id);t&&this.previousFrameElement&&t.replaceChildren(...this.previousFrameElement.children),delete this.previousFrameElement};async#N(e,t){const s=await this.extractForeignFrameElement(t.body);if(s){const t=new K(s),i=new oe(this,this.view.snapshot,t,oe.renderElement,!1,!1);this.view.renderPromise&&await this.view.renderPromise,this.changeHistory(),await this.view.render(i),this.complete=!0,vt.frameRendered(e,this.element),vt.frameLoaded(this.element),await this.fetchResponseLoaded(e)}else this.#W(e)&&this.#U(e)}async#O(e){const t=new D(this,N.get,e,new URLSearchParams,this.element);return this.#P?.cancel(),this.#P=t,new Promise((e=>{this.#k=()=>{this.#k=()=>{},this.#P=null,e()},t.perform()}))}#D(e,t,s){const i=this.#l(e,s);i.delegate.proposeVisitIfNavigatedWithAction(i,e,s),this.#_(e,(()=>{i.src=t}))}proposeVisitIfNavigatedWithAction(e,t,s){if(this.action=C(s,t,e),this.action){const t=de.fromElement(e).clone(),{visitCachedSnapshot:s}=e.delegate;e.delegate.fetchResponseLoaded=async i=>{if(e.src){const{statusCode:r,redirected:n}=i,o={response:{statusCode:r,redirected:n,responseHTML:await i.responseHTML},visitCachedSnapshot:s,willRender:!1,updateHistory:!1,restorationIdentifier:this.restorationIdentifier,snapshot:t};this.action&&(o.action=this.action),vt.visit(e.src,o)}}}}changeHistory(){if(this.action){const e=L(this.action);vt.history.update(e,r(this.element.src||""),this.restorationIdentifier)}}async#x(e){console.warn(`The response (${e.statusCode}) from <turbo-frame id="${this.element.id}"> is performing a full page visit due to turbo-visit-control.`),await this.#$(e.response)}#W(e){this.element.setAttribute("complete","");const t=e.response;return!p("turbo:frame-missing",{target:this.element,detail:{response:t,visit:async(e,t)=>{e instanceof Response?this.#$(e):vt.visit(e,t)}},cancelable:!0}).defaultPrevented}#U(e){this.view.missing(),this.#j(e)}#j(e){const t=`The response (${e.statusCode}) did not contain the expected <turbo-frame id="${this.element.id}"> and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;throw new It(t)}async#$(e){const t=new u(e),s=await t.responseHTML,{location:i,redirected:r,statusCode:n}=t;return vt.visit(i,{response:{redirected:r,statusCode:n,responseHTML:s}})}#l(e,t){return Ht(y("data-turbo-frame",t,e)||this.element.getAttribute("target"))??this.element}async extractForeignFrameElement(e){let t;const s=CSS.escape(this.id);try{if(t=qt(e.querySelector(`turbo-frame#${s}`),this.sourceURL),t)return t;if(t=qt(e.querySelector(`turbo-frame[src][recurse~=${s}]`),this.sourceURL),t)return await t.loaded,await this.extractForeignFrameElement(t)}catch(e){return console.error(e),new i}return null}#z(e,t){return l(r(o(e,t)),this.rootLocation)}#V(e,t){const s=y("data-turbo-frame",t,e)||this.element.getAttribute("target");if(e instanceof HTMLFormElement&&!this.#z(e,t))return!1;if(!this.enabled||"_top"==s)return!1;if(s){const e=Ht(s);if(e)return!e.disabled}return!!vt.elementIsNavigatable(e)&&!(t&&!vt.elementIsNavigatable(t))}get id(){return this.element.id}get enabled(){return!this.element.disabled}get sourceURL(){if(this.element.src)return this.element.src}set sourceURL(e){this.#B("src",(()=>{this.element.src=e??null}))}get loadingStyle(){return this.element.loading}get isLoading(){return void 0!==this.formSubmission||void 0!==this.#k()}get complete(){return this.element.hasAttribute("complete")}set complete(e){this.#B("complete",(()=>{e?this.element.setAttribute("complete",""):this.element.removeAttribute("complete")}))}get isActive(){return this.element.isActive&&this.#M}get rootLocation(){const e=this.element.ownerDocument.querySelector('meta[name="turbo-root"]');return r(e?.content??"/")}#q(e){return this.#I.has(e)}#B(e,t){this.#I.add(e),t(),this.#I.delete(e)}#_(e,t){this.currentNavigationElement=e,t(),delete this.currentNavigationElement}},void 0===customElements.get("turbo-frame")&&customElements.define("turbo-frame",i),void 0===customElements.get("turbo-stream")&&customElements.define("turbo-stream",Ot),void 0===customElements.get("turbo-stream-source")&&customElements.define("turbo-stream-source",Nt),(()=>{let e=document.currentScript;if(e&&!e.hasAttribute("data-turbo-suppress-warning"))for(e=e.parentElement;e;){if(e==document.body)return console.warn(S`
20
20
  You are loading Turbo from a <script> element inside the <body> element. This is probably not what you meant to do!
21
21
 
22
22
  Load your application’s JavaScript bundle inside the <head> element instead. <script> elements in <body> are evaluated with each page change.
@@ -25,5 +25,5 @@ Copyright © 2023 37signals LLC
25
25
 
26
26
  ——
27
27
  Suppress this warning by adding a "data-turbo-suppress-warning" attribute to: %s
28
- `,e.outerHTML);e=e.parentElement}})(),window.Turbo=Tt,bt();var qt=Object.freeze({__proto__:null,FetchEnctype:B,FetchMethod:H,FetchRequest:O,FetchResponse:u,FrameElement:i,FrameLoadingStyle:s,FrameRenderer:se,PageRenderer:ot,PageSnapshot:ae,StreamActions:Ft,StreamElement:It,StreamSourceElement:Ht,cache:ft,clearCache:Rt,connectStreamSource:wt,disconnectStreamSource:yt,fetch:F,fetchEnctypeFromString:q,fetchMethodFromString:I,isSafe:N,navigator:gt,registerAdapter:vt,renderStreamMessage:Et,session:pt,setConfirmMethod:Lt,setFormMode:Ct,setProgressBarDelay:At,start:bt,visit:St});let Bt;async function Ot(){return Bt||Nt(xt().then(Nt))}function Nt(e){return Bt=e}async function xt(){const{createConsumer:e}=await Promise.resolve().then((function(){return cs}));return e()}async function Vt(e,t){const{subscriptions:s}=await Ot();return s.create(e,t)}var Wt=Object.freeze({__proto__:null,getConsumer:Ot,setConsumer:Nt,createConsumer:xt,subscribeTo:Vt});function Dt(e){return e&&"object"==typeof e?e instanceof Date||e instanceof RegExp?e:Array.isArray(e)?e.map(Dt):Object.keys(e).reduce((function(t,s){return t[s[0].toLowerCase()+s.slice(1).replace(/([A-Z]+)/g,(function(e,t){return"_"+t.toLowerCase()}))]=Dt(e[s]),t}),{}):e}class Ut extends HTMLElement{async connectedCallback(){wt(this),this.subscription=await Vt(this.channel,{received:this.dispatchMessageEvent.bind(this),connected:this.subscriptionConnected.bind(this),disconnected:this.subscriptionDisconnected.bind(this)})}disconnectedCallback(){yt(this),this.subscription&&this.subscription.unsubscribe()}dispatchMessageEvent(e){const t=new MessageEvent("message",{data:e});return this.dispatchEvent(t)}subscriptionConnected(){this.setAttribute("connected","")}subscriptionDisconnected(){this.removeAttribute("connected")}get channel(){return{channel:this.getAttribute("channel"),signed_stream_name:this.getAttribute("signed-stream-name"),...Dt({...this.dataset})}}}void 0===customElements.get("turbo-cable-stream-source")&&customElements.define("turbo-cable-stream-source",Ut),addEventListener("turbo:before-fetch-request",(function(e){if(e.target instanceof HTMLFormElement){const{target:t,detail:{fetchOptions:s}}=e;t.addEventListener("turbo:submit-start",(({detail:{formSubmission:{submitter:e}}})=>{const i=function(e){return e instanceof FormData||e instanceof URLSearchParams}(s.body)?s.body:new URLSearchParams,r=function(e,t,s){const i=function(e){return e instanceof HTMLButtonElement||e instanceof HTMLInputElement?"_method"===e.name?e.value:e.hasAttribute("formmethod")?e.formMethod:null:null}(e),r=t.get("_method"),n=s.getAttribute("method")||"get";return"string"==typeof i?i:"string"==typeof r?r:n}(e,i,t);/get/i.test(r)||(/post/i.test(r)?i.delete("_method"):i.set("_method",r),s.method="post")}),{once:!0})}}));var _t={logger:self.console,WebSocket:self.WebSocket},$t={log(...e){this.enabled&&(e.push(Date.now()),_t.logger.log("[ActionCable]",...e))}};const jt=()=>(new Date).getTime(),zt=e=>(jt()-e)/1e3;class Gt{constructor(e){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=e,this.reconnectAttempts=0}start(){this.isRunning()||(this.startedAt=jt(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),$t.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`))}stop(){this.isRunning()&&(this.stoppedAt=jt(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),$t.log("ConnectionMonitor stopped"))}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=jt()}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,$t.log("ConnectionMonitor recorded connect")}recordDisconnect(){this.disconnectedAt=jt(),$t.log("ConnectionMonitor recorded disconnect")}startPolling(){this.stopPolling(),this.poll()}stopPolling(){clearTimeout(this.pollTimeout)}poll(){this.pollTimeout=setTimeout((()=>{this.reconnectIfStale(),this.poll()}),this.getPollInterval())}getPollInterval(){const{staleThreshold:e,reconnectionBackoffRate:t}=this.constructor;return 1e3*e*Math.pow(1+t,Math.min(this.reconnectAttempts,10))*(1+(0===this.reconnectAttempts?1:t)*Math.random())}reconnectIfStale(){this.connectionIsStale()&&($t.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${zt(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?$t.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${zt(this.disconnectedAt)} s`):($t.log("ConnectionMonitor reopening"),this.connection.reopen()))}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return zt(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&zt(this.disconnectedAt)<this.constructor.staleThreshold}visibilityDidChange(){"visible"===document.visibilityState&&setTimeout((()=>{!this.connectionIsStale()&&this.connection.isOpen()||($t.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen())}),200)}}Gt.staleThreshold=6,Gt.reconnectionBackoffRate=.15;var Jt=Gt,Kt={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]};const{message_types:Xt,protocols:Qt}=Kt,Yt=Qt.slice(0,Qt.length-1),Zt=[].indexOf;class es{constructor(e){this.open=this.open.bind(this),this.consumer=e,this.subscriptions=this.consumer.subscriptions,this.monitor=new Jt(this),this.disconnected=!0}send(e){return!!this.isOpen()&&(this.webSocket.send(JSON.stringify(e)),!0)}open(){if(this.isActive())return $t.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{const e=[...Qt,...this.consumer.subprotocols||[]];return $t.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${e}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new _t.WebSocket(this.consumer.url,e),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:e}={allowReconnect:!0}){if(e||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if($t.log(`Reopening WebSocket, current state is ${this.getState()}`),!this.isActive())return this.open();try{return this.close()}catch(e){$t.log("Failed to reopen WebSocket",e)}finally{$t.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay)}}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return Zt.call(Yt,this.getProtocol())>=0}isState(...e){return Zt.call(e,this.getState())>=0}getState(){if(this.webSocket)for(let e in _t.WebSocket)if(_t.WebSocket[e]===this.webSocket.readyState)return e.toLowerCase();return null}installEventHandlers(){for(let e in this.events){const t=this.events[e].bind(this);this.webSocket[`on${e}`]=t}}uninstallEventHandlers(){for(let e in this.events)this.webSocket[`on${e}`]=function(){}}}es.reopenDelay=500,es.prototype.events={message(e){if(!this.isProtocolSupported())return;const{identifier:t,message:s,reason:i,reconnect:r,type:n}=JSON.parse(e.data);switch(n){case Xt.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case Xt.disconnect:return $t.log(`Disconnecting. Reason: ${i}`),this.close({allowReconnect:r});case Xt.ping:return this.monitor.recordPing();case Xt.confirmation:return this.subscriptions.confirmSubscription(t),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(t,"connected",{reconnected:!0})):this.subscriptions.notify(t,"connected",{reconnected:!1});case Xt.rejection:return this.subscriptions.reject(t);default:return this.subscriptions.notify(t,"received",s)}},open(){if($t.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return $t.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(e){if($t.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){$t.log("WebSocket onerror event")}};var ts=es;class ss{constructor(e,t={},s){this.consumer=e,this.identifier=JSON.stringify(t),function(e,t){if(null!=t)for(let s in t){const i=t[s];e[s]=i}}(this,s)}perform(e,t={}){return t.action=e,this.send(t)}send(e){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(e)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}}var is=class{constructor(e){this.subscriptions=e,this.pendingSubscriptions=[]}guarantee(e){-1==this.pendingSubscriptions.indexOf(e)?($t.log(`SubscriptionGuarantor guaranteeing ${e.identifier}`),this.pendingSubscriptions.push(e)):$t.log(`SubscriptionGuarantor already guaranteeing ${e.identifier}`),this.startGuaranteeing()}forget(e){$t.log(`SubscriptionGuarantor forgetting ${e.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter((t=>t!==e))}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing()}stopGuaranteeing(){clearTimeout(this.retryTimeout)}retrySubscribing(){this.retryTimeout=setTimeout((()=>{this.subscriptions&&"function"==typeof this.subscriptions.subscribe&&this.pendingSubscriptions.map((e=>{$t.log(`SubscriptionGuarantor resubscribing ${e.identifier}`),this.subscriptions.subscribe(e)}))}),500)}};class rs{constructor(e){this.consumer=e,this.guarantor=new is(this),this.subscriptions=[]}create(e,t){const s="object"==typeof e?e:{channel:e},i=new ss(this.consumer,s,t);return this.add(i)}add(e){return this.subscriptions.push(e),this.consumer.ensureActiveConnection(),this.notify(e,"initialized"),this.subscribe(e),e}remove(e){return this.forget(e),this.findAll(e.identifier).length||this.sendCommand(e,"unsubscribe"),e}reject(e){return this.findAll(e).map((e=>(this.forget(e),this.notify(e,"rejected"),e)))}forget(e){return this.guarantor.forget(e),this.subscriptions=this.subscriptions.filter((t=>t!==e)),e}findAll(e){return this.subscriptions.filter((t=>t.identifier===e))}reload(){return this.subscriptions.map((e=>this.subscribe(e)))}notifyAll(e,...t){return this.subscriptions.map((s=>this.notify(s,e,...t)))}notify(e,t,...s){let i;return i="string"==typeof e?this.findAll(e):[e],i.map((e=>"function"==typeof e[t]?e[t](...s):void 0))}subscribe(e){this.sendCommand(e,"subscribe")&&this.guarantor.guarantee(e)}confirmSubscription(e){$t.log(`Subscription confirmed ${e}`),this.findAll(e).map((e=>this.guarantor.forget(e)))}sendCommand(e,t){const{identifier:s}=e;return this.consumer.send({command:t,identifier:s})}}class ns{constructor(e){this._url=e,this.subscriptions=new rs(this),this.connection=new ts(this),this.subprotocols=[]}get url(){return os(this._url)}send(e){return this.connection.send(e)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(e){this.subprotocols=[...this.subprotocols,e]}}function os(e){if("function"==typeof e&&(e=e()),e&&!/^wss?:/i.test(e)){const t=document.createElement("a");return t.href=e,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}return e}function as(e){const t=document.head.querySelector(`meta[name='action-cable-${e}']`);if(t)return t.getAttribute("content")}var cs=Object.freeze({__proto__:null,Connection:ts,ConnectionMonitor:Jt,Consumer:ns,INTERNAL:Kt,Subscription:ss,Subscriptions:rs,SubscriptionGuarantor:is,adapters:_t,createWebSocketURL:os,logger:$t,createConsumer:function(e=as("url")||Kt.default_mount_path){return new ns(e)},getConfig:as});export{qt as Turbo,Wt as cable};
28
+ `,e.outerHTML);e=e.parentElement}})(),window.Turbo={...Ft,StreamActions:Bt},yt();var xt=Object.freeze({__proto__:null,FetchEnctype:V,FetchMethod:N,FetchRequest:D,FetchResponse:u,FrameElement:i,FrameLoadingStyle:s,FrameRenderer:oe,PageRenderer:dt,PageSnapshot:de,StreamActions:Bt,StreamElement:Ot,StreamSourceElement:Nt,cache:St,clearCache:Tt,connectStreamSource:Rt,disconnectStreamSource:Lt,fetch:B,fetchEnctypeFromString:x,fetchMethodFromString:O,isSafe:W,navigator:wt,registerAdapter:Et,renderStreamMessage:Ct,session:vt,setConfirmMethod:kt,setFormMode:Mt,setProgressBarDelay:Pt,start:yt,visit:At});let Vt;async function Dt(){return Vt||Wt(Ut().then(Wt))}function Wt(e){return Vt=e}async function Ut(){const{createConsumer:e}=await Promise.resolve().then((function(){return us}));return e()}async function _t(e,t){const{subscriptions:s}=await Dt();return s.create(e,t)}var $t=Object.freeze({__proto__:null,getConsumer:Dt,setConsumer:Wt,createConsumer:Ut,subscribeTo:_t});function jt(e){return e&&"object"==typeof e?e instanceof Date||e instanceof RegExp?e:Array.isArray(e)?e.map(jt):Object.keys(e).reduce((function(t,s){return t[s[0].toLowerCase()+s.slice(1).replace(/([A-Z]+)/g,(function(e,t){return"_"+t.toLowerCase()}))]=jt(e[s]),t}),{}):e}class zt extends HTMLElement{async connectedCallback(){Rt(this),this.subscription=await _t(this.channel,{received:this.dispatchMessageEvent.bind(this),connected:this.subscriptionConnected.bind(this),disconnected:this.subscriptionDisconnected.bind(this)})}disconnectedCallback(){Lt(this),this.subscription&&this.subscription.unsubscribe()}dispatchMessageEvent(e){const t=new MessageEvent("message",{data:e});return this.dispatchEvent(t)}subscriptionConnected(){this.setAttribute("connected","")}subscriptionDisconnected(){this.removeAttribute("connected")}get channel(){return{channel:this.getAttribute("channel"),signed_stream_name:this.getAttribute("signed-stream-name"),...jt({...this.dataset})}}}void 0===customElements.get("turbo-cable-stream-source")&&customElements.define("turbo-cable-stream-source",zt),window.Turbo=xt,addEventListener("turbo:before-fetch-request",(function(e){if(e.target instanceof HTMLFormElement){const{target:t,detail:{fetchOptions:s}}=e;t.addEventListener("turbo:submit-start",(({detail:{formSubmission:{submitter:e}}})=>{const i=function(e){return e instanceof FormData||e instanceof URLSearchParams}(s.body)?s.body:new URLSearchParams,r=function(e,t,s){const i=function(e){return e instanceof HTMLButtonElement||e instanceof HTMLInputElement?"_method"===e.name?e.value:e.hasAttribute("formmethod")?e.formMethod:null:null}(e),r=t.get("_method"),n=s.getAttribute("method")||"get";return"string"==typeof i?i:"string"==typeof r?r:n}(e,i,t);/get/i.test(r)||(/post/i.test(r)?i.delete("_method"):i.set("_method",r),s.method="post")}),{once:!0})}}));var Gt={logger:self.console,WebSocket:self.WebSocket},Jt={log(...e){this.enabled&&(e.push(Date.now()),Gt.logger.log("[ActionCable]",...e))}};const Kt=()=>(new Date).getTime(),Xt=e=>(Kt()-e)/1e3;class Qt{constructor(e){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=e,this.reconnectAttempts=0}start(){this.isRunning()||(this.startedAt=Kt(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),Jt.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`))}stop(){this.isRunning()&&(this.stoppedAt=Kt(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),Jt.log("ConnectionMonitor stopped"))}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=Kt()}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,Jt.log("ConnectionMonitor recorded connect")}recordDisconnect(){this.disconnectedAt=Kt(),Jt.log("ConnectionMonitor recorded disconnect")}startPolling(){this.stopPolling(),this.poll()}stopPolling(){clearTimeout(this.pollTimeout)}poll(){this.pollTimeout=setTimeout((()=>{this.reconnectIfStale(),this.poll()}),this.getPollInterval())}getPollInterval(){const{staleThreshold:e,reconnectionBackoffRate:t}=this.constructor;return 1e3*e*Math.pow(1+t,Math.min(this.reconnectAttempts,10))*(1+(0===this.reconnectAttempts?1:t)*Math.random())}reconnectIfStale(){this.connectionIsStale()&&(Jt.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${Xt(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?Jt.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${Xt(this.disconnectedAt)} s`):(Jt.log("ConnectionMonitor reopening"),this.connection.reopen()))}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return Xt(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&Xt(this.disconnectedAt)<this.constructor.staleThreshold}visibilityDidChange(){"visible"===document.visibilityState&&setTimeout((()=>{!this.connectionIsStale()&&this.connection.isOpen()||(Jt.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen())}),200)}}Qt.staleThreshold=6,Qt.reconnectionBackoffRate=.15;var Yt=Qt,Zt={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]};const{message_types:es,protocols:ts}=Zt,ss=ts.slice(0,ts.length-1),is=[].indexOf;class rs{constructor(e){this.open=this.open.bind(this),this.consumer=e,this.subscriptions=this.consumer.subscriptions,this.monitor=new Yt(this),this.disconnected=!0}send(e){return!!this.isOpen()&&(this.webSocket.send(JSON.stringify(e)),!0)}open(){if(this.isActive())return Jt.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{const e=[...ts,...this.consumer.subprotocols||[]];return Jt.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${e}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new Gt.WebSocket(this.consumer.url,e),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:e}={allowReconnect:!0}){if(e||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(Jt.log(`Reopening WebSocket, current state is ${this.getState()}`),!this.isActive())return this.open();try{return this.close()}catch(e){Jt.log("Failed to reopen WebSocket",e)}finally{Jt.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay)}}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return is.call(ss,this.getProtocol())>=0}isState(...e){return is.call(e,this.getState())>=0}getState(){if(this.webSocket)for(let e in Gt.WebSocket)if(Gt.WebSocket[e]===this.webSocket.readyState)return e.toLowerCase();return null}installEventHandlers(){for(let e in this.events){const t=this.events[e].bind(this);this.webSocket[`on${e}`]=t}}uninstallEventHandlers(){for(let e in this.events)this.webSocket[`on${e}`]=function(){}}}rs.reopenDelay=500,rs.prototype.events={message(e){if(!this.isProtocolSupported())return;const{identifier:t,message:s,reason:i,reconnect:r,type:n}=JSON.parse(e.data);switch(n){case es.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case es.disconnect:return Jt.log(`Disconnecting. Reason: ${i}`),this.close({allowReconnect:r});case es.ping:return this.monitor.recordPing();case es.confirmation:return this.subscriptions.confirmSubscription(t),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(t,"connected",{reconnected:!0})):this.subscriptions.notify(t,"connected",{reconnected:!1});case es.rejection:return this.subscriptions.reject(t);default:return this.subscriptions.notify(t,"received",s)}},open(){if(Jt.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return Jt.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(e){if(Jt.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){Jt.log("WebSocket onerror event")}};var ns=rs;class os{constructor(e,t={},s){this.consumer=e,this.identifier=JSON.stringify(t),function(e,t){if(null!=t)for(let s in t){const i=t[s];e[s]=i}}(this,s)}perform(e,t={}){return t.action=e,this.send(t)}send(e){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(e)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}}var as=class{constructor(e){this.subscriptions=e,this.pendingSubscriptions=[]}guarantee(e){-1==this.pendingSubscriptions.indexOf(e)?(Jt.log(`SubscriptionGuarantor guaranteeing ${e.identifier}`),this.pendingSubscriptions.push(e)):Jt.log(`SubscriptionGuarantor already guaranteeing ${e.identifier}`),this.startGuaranteeing()}forget(e){Jt.log(`SubscriptionGuarantor forgetting ${e.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter((t=>t!==e))}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing()}stopGuaranteeing(){clearTimeout(this.retryTimeout)}retrySubscribing(){this.retryTimeout=setTimeout((()=>{this.subscriptions&&"function"==typeof this.subscriptions.subscribe&&this.pendingSubscriptions.map((e=>{Jt.log(`SubscriptionGuarantor resubscribing ${e.identifier}`),this.subscriptions.subscribe(e)}))}),500)}};class cs{constructor(e){this.consumer=e,this.guarantor=new as(this),this.subscriptions=[]}create(e,t){const s="object"==typeof e?e:{channel:e},i=new os(this.consumer,s,t);return this.add(i)}add(e){return this.subscriptions.push(e),this.consumer.ensureActiveConnection(),this.notify(e,"initialized"),this.subscribe(e),e}remove(e){return this.forget(e),this.findAll(e.identifier).length||this.sendCommand(e,"unsubscribe"),e}reject(e){return this.findAll(e).map((e=>(this.forget(e),this.notify(e,"rejected"),e)))}forget(e){return this.guarantor.forget(e),this.subscriptions=this.subscriptions.filter((t=>t!==e)),e}findAll(e){return this.subscriptions.filter((t=>t.identifier===e))}reload(){return this.subscriptions.map((e=>this.subscribe(e)))}notifyAll(e,...t){return this.subscriptions.map((s=>this.notify(s,e,...t)))}notify(e,t,...s){let i;return i="string"==typeof e?this.findAll(e):[e],i.map((e=>"function"==typeof e[t]?e[t](...s):void 0))}subscribe(e){this.sendCommand(e,"subscribe")&&this.guarantor.guarantee(e)}confirmSubscription(e){Jt.log(`Subscription confirmed ${e}`),this.findAll(e).map((e=>this.guarantor.forget(e)))}sendCommand(e,t){const{identifier:s}=e;return this.consumer.send({command:t,identifier:s})}}class ls{constructor(e){this._url=e,this.subscriptions=new cs(this),this.connection=new ns(this),this.subprotocols=[]}get url(){return hs(this._url)}send(e){return this.connection.send(e)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(e){this.subprotocols=[...this.subprotocols,e]}}function hs(e){if("function"==typeof e&&(e=e()),e&&!/^wss?:/i.test(e)){const t=document.createElement("a");return t.href=e,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}return e}function ds(e){const t=document.head.querySelector(`meta[name='action-cable-${e}']`);if(t)return t.getAttribute("content")}var us=Object.freeze({__proto__:null,Connection:ns,ConnectionMonitor:Yt,Consumer:ls,INTERNAL:Zt,Subscription:os,Subscriptions:cs,SubscriptionGuarantor:as,adapters:Gt,createWebSocketURL:hs,logger:Jt,createConsumer:function(e=ds("url")||Zt.default_mount_path){return new ls(e)},getConfig:ds});export{xt as Turbo,$t as cable};
29
29
  //# sourceMappingURL=turbo.min.js.map