rails_ai_admin 0.4.1 → 0.5.0
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +64 -0
- data/README.md +4 -9
- data/SECURITY.md +1 -1
- data/app/assets/builds/rails_ai_admin.js +5 -5
- data/app/controllers/rails_ai_admin/application_controller.rb +19 -6
- data/app/controllers/rails_ai_admin/assistant_controller.rb +20 -7
- data/app/controllers/rails_ai_admin/audit_controller.rb +5 -1
- data/app/controllers/rails_ai_admin/bulk_changes_controller.rb +26 -6
- data/app/controllers/rails_ai_admin/dashboard_controller.rb +3 -2
- data/app/controllers/rails_ai_admin/deleted_records_controller.rb +12 -4
- data/app/controllers/rails_ai_admin/files_controller.rb +16 -4
- data/app/controllers/rails_ai_admin/mcp_controller.rb +30 -4
- data/app/controllers/rails_ai_admin/mcp_tokens_controller.rb +4 -2
- data/app/controllers/rails_ai_admin/operations_controller.rb +5 -2
- data/app/controllers/rails_ai_admin/resources_controller.rb +44 -5
- data/app/controllers/rails_ai_admin/selections_controller.rb +41 -5
- data/app/helpers/rails_ai_admin/assistant_helper.rb +3 -1
- data/app/helpers/rails_ai_admin/fields_helper.rb +36 -7
- data/app/helpers/rails_ai_admin/history_helper.rb +1 -1
- data/app/views/layouts/rails_ai_admin/application.html.erb +1 -0
- data/app/views/layouts/rails_ai_admin/frame.html.erb +1 -1
- data/app/views/layouts/rails_ai_admin/status.html.erb +2 -2
- data/app/views/rails_ai_admin/assistant/_transcript.html.erb +5 -1
- data/app/views/rails_ai_admin/audit/index.html.erb +1 -1
- data/app/views/rails_ai_admin/deleted_records/index.html.erb +3 -2
- data/app/views/rails_ai_admin/fields/_input.html.erb +2 -1
- data/app/views/rails_ai_admin/selections/confirm_destroy.html.erb +1 -0
- data/config/locales/en.yml +2 -0
- data/db/assistant_migrate/20261103000001_create_rails_ai_admin_assistant.rb +1 -0
- data/db/migrate/20261122000001_add_missing_indexes_to_rails_ai_admin_tables.rb +12 -0
- data/lib/generators/rails_ai_admin/assistant/assistant_generator.rb +4 -1
- data/lib/generators/rails_ai_admin/assistant/templates/admin_assistant.rb +6 -0
- data/lib/generators/rails_ai_admin/assistant/templates/assistant_eval.yml +25 -0
- data/lib/generators/rails_ai_admin/install/templates/admin_context_devise.rb.tt +2 -1
- data/lib/generators/rails_ai_admin/install/templates/admin_context_rails.rb.tt +5 -2
- data/lib/rails_ai_admin/assistant/budget.rb +4 -2
- data/lib/rails_ai_admin/assistant/coordinator.rb +18 -4
- data/lib/rails_ai_admin/assistant/evaluation.rb +124 -0
- data/lib/rails_ai_admin/assistant/records.rb +2 -1
- data/lib/rails_ai_admin/assistant/retention.rb +12 -1
- data/lib/rails_ai_admin/assistant/runtime.rb +49 -1
- data/lib/rails_ai_admin/assistant/tools.rb +58 -18
- data/lib/rails_ai_admin/assistant.rb +1 -0
- data/lib/rails_ai_admin/authorization/access.rb +34 -23
- data/lib/rails_ai_admin/authorization/pundit_adapter.rb +6 -3
- data/lib/rails_ai_admin/collections/dispatcher.rb +3 -3
- data/lib/rails_ai_admin/collections/queries.rb +1 -1
- data/lib/rails_ai_admin/configuration.rb +39 -8
- data/lib/rails_ai_admin/doctor.rb +44 -9
- data/lib/rails_ai_admin/field.rb +37 -22
- data/lib/rails_ai_admin/fields/association.rb +27 -10
- data/lib/rails_ai_admin/fields/type.rb +1 -1
- data/lib/rails_ai_admin/forms/plan.rb +4 -2
- data/lib/rails_ai_admin/input_schema.rb +4 -4
- data/lib/rails_ai_admin/integrations/propose_operation.rb +18 -4
- data/lib/rails_ai_admin/integrations/tool_views.rb +29 -3
- data/lib/rails_ai_admin/mcp.rb +23 -13
- data/lib/rails_ai_admin/navigation/list_state.rb +3 -3
- data/lib/rails_ai_admin/navigation/saved_views.rb +6 -5
- data/lib/rails_ai_admin/operations/restore.rb +25 -4
- data/lib/rails_ai_admin/operations/runner.rb +51 -15
- data/lib/rails_ai_admin/outbox/dispatcher.rb +6 -2
- data/lib/rails_ai_admin/presentation/association_panel.rb +6 -6
- data/lib/rails_ai_admin/presentation/audit_log.rb +8 -3
- data/lib/rails_ai_admin/presentation/csv_export.rb +21 -8
- data/lib/rails_ai_admin/presentation/csv_import.rb +9 -1
- data/lib/rails_ai_admin/presentation/dashboard.rb +5 -2
- data/lib/rails_ai_admin/presentation/history.rb +1 -1
- data/lib/rails_ai_admin/prune.rb +16 -5
- data/lib/rails_ai_admin/queries/list.rb +138 -38
- data/lib/rails_ai_admin/record_version.rb +1 -1
- data/lib/rails_ai_admin/registry.rb +5 -0
- data/lib/rails_ai_admin/request_log_filter.rb +4 -2
- data/lib/rails_ai_admin/resource.rb +4 -0
- data/lib/rails_ai_admin/schema_suggestions.rb +13 -5
- data/lib/rails_ai_admin/templates/catalog.rb +4 -2
- data/lib/rails_ai_admin/templates/inspector.rb +6 -2
- data/lib/rails_ai_admin/templates/safe_paths.rb +2 -1
- data/lib/rails_ai_admin/version.rb +1 -1
- data/lib/rails_ai_admin/work.rb +1 -1
- data/lib/rails_ai_admin.rb +10 -6
- data/lib/tasks/rails_ai_admin.rake +20 -0
- metadata +25 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var Qs=Object.defineProperty;var er=(r,e)=>{for(var t in e)Qs(r,t,{get:e[t],enumerable:!0})};var Vs={};er(Vs,{FetchEnctype:()=>_,FetchMethod:()=>I,FetchRequest:()=>W,FetchResponse:()=>Q,FrameElement:()=>P,FrameLoadingStyle:()=>z,FrameRenderer:()=>te,PageRenderer:()=>se,PageSnapshot:()=>B,StreamActions:()=>Et,StreamElement:()=>Re,StreamSourceElement:()=>ke,cache:()=>ks,config:()=>R,connectStreamSource:()=>yt,disconnectStreamSource:()=>wt,fetch:()=>bt,fetchEnctypeFromString:()=>Ss,fetchMethodFromString:()=>Oe,isSafe:()=>Fe,morphBodyElements:()=>Ds,morphChildren:()=>Ie,morphElements:()=>le,morphTurboFrameElements:()=>xs,navigator:()=>Os,registerAdapter:()=>Fs,renderStreamMessage:()=>Ps,session:()=>M,setConfirmMethod:()=>
|
|
1
|
+
var Qs=Object.defineProperty;var er=(r,e)=>{for(var t in e)Qs(r,t,{get:e[t],enumerable:!0})};var Vs={};er(Vs,{FetchEnctype:()=>_,FetchMethod:()=>I,FetchRequest:()=>W,FetchResponse:()=>Q,FrameElement:()=>P,FrameLoadingStyle:()=>z,FrameRenderer:()=>te,PageRenderer:()=>se,PageSnapshot:()=>B,StreamActions:()=>Et,StreamElement:()=>Re,StreamSourceElement:()=>ke,cache:()=>ks,config:()=>R,connectStreamSource:()=>yt,disconnectStreamSource:()=>wt,fetch:()=>bt,fetchEnctypeFromString:()=>Ss,fetchMethodFromString:()=>Oe,isSafe:()=>Fe,morphBodyElements:()=>Ds,morphChildren:()=>Ie,morphElements:()=>le,morphTurboFrameElements:()=>xs,navigator:()=>Os,registerAdapter:()=>Fs,renderStreamMessage:()=>Ps,session:()=>M,setConfirmMethod:()=>qs,setFormMode:()=>Ns,setProgressBarDelay:()=>Bs,start:()=>vt,visit:()=>Is});/*!
|
|
2
2
|
Turbo 8.0.23
|
|
3
3
|
Copyright © 2026 37signals LLC
|
|
4
4
|
*/var z={eager:"eager",lazy:"lazy"},P=class r extends HTMLElement{static delegateConstructor=void 0;loaded=Promise.resolve();static get observedAttributes(){return["disabled","loading","src"]}constructor(){super(),this.delegate=new r.delegateConstructor(this)}connectedCallback(){this.delegate.connect()}disconnectedCallback(){this.delegate.disconnect()}reload(){return this.delegate.sourceURLReloaded()}attributeChangedCallback(e){e=="loading"?this.delegate.loadingStyleChanged():e=="src"?this.delegate.sourceURLChanged():e=="disabled"&&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 shouldReloadWithMorph(){return this.src&&this.refresh==="morph"}get loading(){return tr(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 tr(r){return r.toLowerCase()==="lazy"?z.lazy:z.eager}var sr={enabled:!0,progressBarDelay:500,unvisitableExtensions:new Set([".7z",".aac",".apk",".avi",".bmp",".bz2",".css",".csv",".deb",".dmg",".doc",".docx",".exe",".gif",".gz",".heic",".heif",".ico",".iso",".jpeg",".jpg",".js",".json",".m4a",".mkv",".mov",".mp3",".mp4",".mpeg",".mpg",".msi",".ogg",".ogv",".pdf",".pkg",".png",".ppt",".pptx",".rar",".rtf",".svg",".tar",".tif",".tiff",".txt",".wav",".webm",".webp",".wma",".wmv",".xls",".xlsx",".xml",".zip"])};function oe(r){if(r.getAttribute("data-turbo-eval")=="false")return r;{let e=document.createElement("script"),t=ps();return t&&(e.nonce=t),e.textContent=r.textContent,e.async=!1,rr(e,r),e}}function rr(r,e){for(let{name:t,value:s}of e.attributes)r.setAttribute(t,s)}function ir(r){let e=document.createElement("template");return e.innerHTML=r,e.content}function L(r,{target:e,cancelable:t,detail:s}={}){let i=new CustomEvent(r,{cancelable:t,bubbles:!0,composed:!0,detail:s});return e&&e.isConnected?e.dispatchEvent(i):document.documentElement.dispatchEvent(i),i}function is(r){r.preventDefault(),r.stopImmediatePropagation()}function ie(){return document.visibilityState==="hidden"?us():hs()}function hs(){return new Promise(r=>requestAnimationFrame(()=>r()))}function us(){return new Promise(r=>setTimeout(()=>r(),0))}function ds(r=""){return new DOMParser().parseFromString(r,"text/html")}function ms(r,...e){let t=nr(r,e).replace(/^\n/,"").split(`
|
|
5
5
|
`),s=t[0].match(/^\s+/),i=s?s[0].length:0;return t.map(n=>n.slice(i)).join(`
|
|
6
|
-
`)}function nr(r,e){return r.reduce((t,s,i)=>{let n=e[i]==null?"":e[i];return t+s+n},"")}function U(){return Array.from({length:36}).map((r,e)=>e==8||e==13||e==18||e==23?"-":e==14?"4":e==19?(Math.floor(Math.random()*4)+8).toString(16):Math.floor(Math.random()*16).toString(16)).join("")}function pe(r,...e){for(let t of e.map(s=>s?.getAttribute(r)))if(typeof t=="string")return t;return null}function or(r,...e){return e.some(t=>t&&t.hasAttribute(r))}function ge(...r){for(let e of r)e.localName=="turbo-frame"&&e.setAttribute("busy",""),e.setAttribute("aria-busy","true")}function be(...r){for(let e of r)e.localName=="turbo-frame"&&e.removeAttribute("busy"),e.removeAttribute("aria-busy")}function ar(r,e=2e3){return new Promise(t=>{let s=()=>{r.removeEventListener("error",s),r.removeEventListener("load",s),t()};r.addEventListener("load",s,{once:!0}),r.addEventListener("error",s,{once:!0}),setTimeout(t,e)})}function fs(r){switch(r){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}function cr(r){return r=="advance"||r=="replace"||r=="restore"}function X(...r){let e=pe("data-turbo-action",...r);return cr(e)?e:null}function ft(r){return document.querySelector(`meta[name="${r}"]`)}function ve(r){let e=ft(r);return e&&e.content}function ps(){let r=ft("csp-nonce");if(r){let{nonce:e,content:t}=r;return e==""?t:e}}function lr(r,e){let t=ft(r);return t||(t=document.createElement("meta"),t.setAttribute("name",r),document.head.appendChild(t)),t.setAttribute("content",e),t}function Z(r,e){if(r instanceof Element)return r.closest(e)||Z(r.assignedSlot||r.getRootNode()?.host,e)}function pt(r){return!!r&&r.closest("[inert], :disabled, [hidden], details:not([open]), dialog:not([open])")==null&&typeof r.focus=="function"}function gs(r){return Array.from(r.querySelectorAll("[autofocus]")).find(pt)}async function hr(r,e){let t=e();r(),await hs();let s=e();return[t,s]}function bs(r){if(r==="_blank")return!1;if(r){for(let e of document.getElementsByName(r))if(e instanceof HTMLIFrameElement)return!1;return!0}else return!0}function vs(r){let e=Z(r,"a[href], a[xlink\\:href]");if(!e||e.href.startsWith("#")||e.hasAttribute("download"))return null;let t=e.getAttribute("target");return t&&t!=="_self"?null:e}function ur(r,e){let t=null;return(...s)=>{let i=()=>r.apply(this,s);clearTimeout(t),t=setTimeout(i,e)}}var dr={"aria-disabled":{beforeSubmit:r=>{r.setAttribute("aria-disabled","true"),r.addEventListener("click",is)},afterSubmit:r=>{r.removeAttribute("aria-disabled"),r.removeEventListener("click",is)}},disabled:{beforeSubmit:r=>r.disabled=!0,afterSubmit:r=>r.disabled=!1}},He=class{#e=null;constructor(e){Object.assign(this,e)}get submitter(){return this.#e}set submitter(e){this.#e=dr[e]||e}},mr=new He({mode:"on",submitter:"disabled"}),R={drive:sr,forms:mr};function F(r){return new URL(r.toString(),document.baseURI)}function ne(r){let e;if(r.hash)return r.hash.slice(1);if(e=r.href.match(/#(.*)$/))return e[1]}function gt(r,e){let t=e?.getAttribute("formaction")||r.getAttribute("action")||r.action;return F(t)}function fr(r){return(vr(r).match(/\.[^.]*$/)||[])[0]||""}function pr(r,e){let t=ns(e.origin+e.pathname);return ns(r.href)===t||r.href.startsWith(t)}function $(r,e){return pr(r,e)&&!R.drive.unvisitableExtensions.has(fr(r))}function ys(r){return F(r.getAttribute("href")||"")}function gr(r){let e=ne(r);return e!=null?r.href.slice(0,-(e.length+1)):r.href}function fe(r){return gr(r)}function ws(r,e){return F(r).href==F(e).href}function br(r){return r.pathname.split("/").slice(1)}function vr(r){return br(r).slice(-1)[0]}function ns(r){return r.endsWith("/")?r:r+"/"}var Q=class{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 F(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)}},$e=class extends Set{constructor(e){super(),this.maxSize=e}add(e){if(this.size>=this.maxSize){let s=this.values().next().value;this.delete(s)}super.add(e)}},Es=new $e(20);function bt(r,e={}){let t=new Headers(e.headers||{}),s=U();return Es.add(s),t.append("X-Turbo-Request-Id",s),window.fetch(r,{...e,headers:t})}function Oe(r){switch(r.toLowerCase()){case"get":return I.get;case"post":return I.post;case"put":return I.put;case"patch":return I.patch;case"delete":return I.delete}}var I={get:"get",post:"post",put:"put",patch:"patch",delete:"delete"};function Ss(r){switch(r.toLowerCase()){case _.multipart:return _.multipart;case _.plain:return _.plain;default:return _.urlEncoded}}var _={urlEncoded:"application/x-www-form-urlencoded",multipart:"multipart/form-data",plain:"text/plain"},W=class{abortController=new AbortController;#e=e=>{};constructor(e,t,s,i=new URLSearchParams,n=null,o=_.urlEncoded){let[m,w]=os(F(s),t,i,o);this.delegate=e,this.url=m,this.target=n,this.fetchOptions={credentials:"same-origin",redirect:"follow",method:t.toUpperCase(),headers:{...this.defaultHeaders},body:w,signal:this.abortSignal,referrer:this.delegate.referrer?.href},this.enctype=o}get method(){return this.fetchOptions.method}set method(e){let t=this.isSafe?this.url.searchParams:this.fetchOptions.body||new FormData,s=Oe(e)||I.get;this.url.search="";let[i,n]=os(this.url,s,t,this.enctype);this.url=i,this.fetchOptions.body=n,this.fetchOptions.method=s.toUpperCase()}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(){let{fetchOptions:e}=this;this.delegate.prepareRequest(this);let t=await this.#t(e);try{this.delegate.requestStarted(this),t.detail.fetchRequest?this.response=t.detail.fetchRequest.response:this.response=bt(this.url.href,e);let s=await this.response;return await this.receive(s)}catch(s){if(s.name!=="AbortError")throw this.#s(s)&&this.delegate.requestErrored(this,s),s}finally{this.delegate.requestFinished(this)}}async receive(e){let t=new Q(e);return L("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 Fe(this.method)}get abortSignal(){return this.abortController.signal}acceptResponseType(e){this.headers.Accept=[e,this.headers.Accept].join(", ")}async#t(e){let t=new Promise(i=>this.#e=i),s=L("turbo:before-fetch-request",{cancelable:!0,detail:{fetchOptions:e,url:this.url,resume:this.#e},target:this.target});return this.url=s.detail.url,s.defaultPrevented&&await t,s}#s(e){return!L("turbo:fetch-request-error",{target:this.target,cancelable:!0,detail:{request:this,error:e}}).defaultPrevented}};function Fe(r){return Oe(r)==I.get}function os(r,e,t,s){let i=Array.from(t).length>0?new URLSearchParams(As(t)):r.searchParams;return Fe(e)?[yr(r,i),null]:s==_.urlEncoded?[r,i]:[r,t]}function As(r){let e=[];for(let[t,s]of r)s instanceof File||e.push([t,s]);return e}function yr(r,e){let t=new URLSearchParams(As(e));return r.search=t.toString(),r}var _e=class{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=>{e.slice(-1)[0]?.isIntersecting&&this.delegate.elementAppearedInViewport(this.element)}},j=class{static contentType="text/vnd.turbo-stream.html";static wrap(e){return typeof e=="string"?new this(ir(e)):e}constructor(e){this.fragment=wr(e)}};function wr(r){for(let e of r.querySelectorAll("turbo-stream")){let t=document.importNode(e,!0);for(let s of t.templateElement.content.querySelectorAll("script"))s.replaceWith(oe(s));e.replaceWith(t)}return r}var Er=r=>r,ye=class{keys=[];entries={};#e;constructor(e,t=Er){this.size=e,this.#e=t}has(e){return this.#e(e)in this.entries}get(e){if(this.has(e)){let t=this.read(e);return this.touch(e),t}}put(e,t){return this.write(e,t),this.touch(e),t}clear(){for(let e of Object.keys(this.entries))this.evict(e)}read(e){return this.entries[this.#e(e)]}write(e,t){this.entries[this.#e(e)]=t}touch(e){e=this.#e(e);let t=this.keys.indexOf(e);t>-1&&this.keys.splice(t,1),this.keys.unshift(e),this.trim()}trim(){for(let e of this.keys.splice(this.size))this.evict(e)}evict(e){delete this.entries[e]}},Sr=100,Ue=class extends ye{#e=null;#t={};constructor(e=1,t=Sr){super(e,fe),this.prefetchDelay=t}putLater(e,t,s){this.#e=setTimeout(()=>{t.perform(),this.put(e,t,s),this.#e=null},this.prefetchDelay)}put(e,t,s=Ts){super.put(e,t),this.#t[fe(e)]=new Date(new Date().getTime()+s)}clear(){super.clear(),this.#e&&clearTimeout(this.#e)}evict(e){super.evict(e),delete this.#t[e]}has(e){if(super.has(e)){let t=this.#t[fe(e)];return t&&t>Date.now()}else return!1}},Ts=10*1e3,Y=new Ue,J={initialized:"initialized",requesting:"requesting",waiting:"waiting",receiving:"receiving",stopping:"stopping",stopped:"stopped"},we=class r{state=J.initialized;static confirmMethod(e){return Promise.resolve(confirm(e))}constructor(e,t,s,i=!1){let n=Rr(t,s),o=Mr(Cr(t,s),n),m=Ar(t,s),w=kr(t,s);this.delegate=e,this.formElement=t,this.submitter=s,this.fetchRequest=new W(this,n,o,m,t,w),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=F(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(){let{initialized:e,requesting:t}=J,s=pe("data-turbo-confirm",this.submitter,this.formElement);if(!(typeof s=="string"&&!await(typeof R.forms.confirm=="function"?R.forms.confirm:r.confirmMethod)(s,this.formElement,this.submitter))&&this.state==e)return this.state=t,this.fetchRequest.perform()}stop(){let{stopping:e,stopped:t}=J;if(this.state!=e&&this.state!=t)return this.state=e,this.fetchRequest.cancel(),!0}prepareRequest(e){if(!e.isSafe){let t=Tr(ve("csrf-param"))||ve("csrf-token");t&&(e.headers["X-CSRF-Token"]=t)}this.requestAcceptsTurboStreamResponse(e)&&e.acceptResponseType(j.contentType)}requestStarted(e){this.state=J.waiting,this.submitter&&R.forms.submitter.beforeSubmit(this.submitter),this.setSubmitsWith(),ge(this.formElement),L("turbo:submit-start",{target:this.formElement,detail:{formSubmission:this}}),this.delegate.formSubmissionStarted(this)}requestPreventedHandlingResponse(e,t){Y.clear(),this.result={success:t.succeeded,fetchResponse:t}}requestSucceededWithResponse(e,t){if(t.clientError||t.serverError){this.delegate.formSubmissionFailedWithResponse(this,t);return}if(Y.clear(),this.requestMustRedirect(e)&&Lr(t)){let s=new Error("Form responses must redirect to another location");this.delegate.formSubmissionErrored(this,s)}else this.state=J.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=J.stopped,this.submitter&&R.forms.submitter.afterSubmit(this.submitter),this.resetSubmitterText(),be(this.formElement),L("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")){let 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")){let e=this.submitter;e.value=this.originalSubmitText}}}requestMustRedirect(e){return!e.isSafe&&this.mustRedirect}requestAcceptsTurboStreamResponse(e){return!e.isSafe||or("data-turbo-stream",this.submitter,this.formElement)}get submitsWith(){return this.submitter?.getAttribute("data-turbo-submits-with")}};function Ar(r,e){let t=new FormData(r),s=e?.getAttribute("name"),i=e?.getAttribute("value");return s&&t.append(s,i||""),t}function Tr(r){if(r!=null){let t=(document.cookie?document.cookie.split("; "):[]).find(s=>s.startsWith(r));if(t){let s=t.split("=").slice(1).join("=");return s?decodeURIComponent(s):void 0}}}function Lr(r){return r.statusCode==200&&!r.redirected}function Cr(r,e){let t=typeof r.action=="string"?r.action:null;return e?.hasAttribute("formaction")?e.getAttribute("formaction")||"":r.getAttribute("action")||t||""}function Mr(r,e){let t=F(r);return Fe(e)&&(t.search=""),t}function Rr(r,e){let t=e?.getAttribute("formmethod")||r.getAttribute("method")||"";return Oe(t.toLowerCase())||I.get}function kr(r,e){return Ss(e?.getAttribute("formenctype")||r.enctype)}var ee=class{constructor(e){this.element=e}get activeElement(){return this.element.ownerDocument.activeElement}get children(){return[...this.element.children]}hasAnchor(e){return this.getElementForAnchor(e)!=null}getElementForAnchor(e){return e?this.element.querySelector(`[id='${e}'], a[name='${e}']`):null}get isConnected(){return this.element.isConnected}get firstAutofocusableElement(){return gs(this.element)}get permanentElements(){return Cs(this.element)}getPermanentElementById(e){return Ls(this.element,e)}getPermanentElementMapForSnapshot(e){let t={};for(let s of this.permanentElements){let{id:i}=s,n=e.getPermanentElementById(i);n&&(t[i]=[s,n])}return t}};function Ls(r,e){return r.querySelector(`#${e}[data-turbo-permanent]`)}function Cs(r){return r.querySelectorAll("[id][data-turbo-permanent]")}var ae=class{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){let t=e.target instanceof HTMLFormElement?e.target:void 0,s=e.submitter||void 0;t&&Or(t,s)&&Fr(t,s)&&this.delegate.willSubmitForm(t,s)&&(e.preventDefault(),e.stopImmediatePropagation(),this.delegate.formSubmitted(t,s))}}};function Or(r,e){return(e?.getAttribute("formmethod")||r.getAttribute("method"))!="dialog"}function Fr(r,e){let t=e?.getAttribute("formtarget")||r.getAttribute("target");return bs(t)}var Ee=class{#e=e=>{};#t=e=>{};constructor(e,t){this.delegate=e,this.element=t}scrollToAnchor(e){let t=this.snapshot.getElementForAnchor(e);t?(this.focusElement(t),this.scrollToElement(t)):this.scrollToPosition({x:0,y:0})}scrollToAnchorFromLocation(e){this.scrollToAnchor(ne(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){let{isPreview:t,shouldRender:s,willRender:i,newSnapshot:n}=e,o=i;if(s)try{this.renderPromise=new Promise(k=>this.#e=k),this.renderer=e,await this.prepareToRenderSnapshot(e);let m=new Promise(k=>this.#t=k),w={resume:this.#t,render:this.renderer.renderElement,renderMethod:this.renderer.renderMethod};this.delegate.allowsImmediateRender(n,w)||await m,await this.renderSnapshot(e),this.delegate.viewRenderedSnapshot(n,t,this.renderer.renderMethod),this.delegate.preloadOnLoadLinksForView(this.element),this.finishRenderingSnapshot(e)}finally{delete this.renderer,this.#e(void 0),delete this.renderPromise}else o&&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()}},We=class extends Ee{missing(){this.element.innerHTML='<strong class="turbo-frame-error">Content missing</strong>'}get snapshot(){return new ee(this.element)}},Se=class{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.clickEventIsSignificant(e)?this.clickEvent=e:delete this.clickEvent};linkClicked=e=>{this.clickEvent&&this.clickEventIsSignificant(e)&&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};clickEventIsSignificant(e){let t=e.composed?e.target?.parentElement:e.target,s=vs(t)||t;return s instanceof Element&&s.closest("turbo-frame, html")==this.element}},Ae=class{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)){let t=e.composedPath&&e.composedPath()[0]||e.target,s=vs(t);if(s&&bs(s.target)){let i=ys(s);this.delegate.willFollowLinkToLocation(s,i,e)&&(e.preventDefault(),this.delegate.followedLinkToLocation(s,i))}}};clickEventIsSignificant(e){return!(e.target&&e.target.isContentEditable||e.defaultPrevented||e.which>1||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)}},Te=class{constructor(e,t){this.delegate=e,this.linkInterceptor=new Ae(this,t)}start(){this.linkInterceptor.start()}stop(){this.linkInterceptor.stop()}canPrefetchRequestToLocation(e,t){return!1}prefetchAndCacheRequestToLocation(e,t){}willFollowLinkToLocation(e,t,s){return this.delegate.willSubmitFormLinkToLocation(e,t,s)&&(e.hasAttribute("data-turbo-method")||e.hasAttribute("data-turbo-stream"))}followedLinkToLocation(e,t){let s=document.createElement("form"),i="hidden";for(let[N,f]of t.searchParams)s.append(Object.assign(document.createElement("input"),{type:i,name:N,value:f}));let n=Object.assign(t,{search:""});s.setAttribute("data-turbo","true"),s.setAttribute("action",n.href),s.setAttribute("hidden","");let o=e.getAttribute("data-turbo-method");o&&s.setAttribute("method",o);let m=e.getAttribute("data-turbo-frame");m&&s.setAttribute("data-turbo-frame",m);let w=X(e);w&&s.setAttribute("data-turbo-action",w);let C=e.getAttribute("data-turbo-confirm");C&&s.setAttribute("data-turbo-confirm",C),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())}},Le=class{static async preservingPermanentElements(e,t,s){let i=new this(e,t);i.enter(),await s(),i.leave()}constructor(e,t){this.delegate=e,this.permanentElementMap=t}enter(){for(let e in this.permanentElementMap){let[t,s]=this.permanentElementMap[e];this.delegate.enteringBardo(t,s),this.replaceNewPermanentElementWithPlaceholder(s)}}leave(){for(let e in this.permanentElementMap){let[t]=this.permanentElementMap[e];this.replaceCurrentPermanentElementWithClone(t),this.replacePlaceholderWithPermanentElement(t),this.delegate.leavingBardo(t)}}replaceNewPermanentElementWithPlaceholder(e){let t=Ir(e);e.replaceWith(t)}replaceCurrentPermanentElementWithClone(e){let t=e.cloneNode(!0);e.replaceWith(t)}replacePlaceholderWithPermanentElement(e){this.getPlaceholderById(e.id)?.replaceWith(e)}getPlaceholderById(e){return this.placeholders.find(t=>t.content==e)}get placeholders(){return[...document.querySelectorAll("meta[name=turbo-permanent-placeholder][content]")]}};function Ir(r){let e=document.createElement("meta");return e.setAttribute("name","turbo-permanent-placeholder"),e.setAttribute("content",r.id),e}var ce=class{#e=null;static renderElement(e,t){}constructor(e,t,s,i=!0){this.currentSnapshot=e,this.newSnapshot=t,this.isPreview=s,this.willRender=i,this.renderElement=this.constructor.renderElement,this.promise=new Promise((n,o)=>this.resolvingFunctions={resolve:n,reject:o})}get shouldRender(){return!0}get shouldAutofocus(){return!0}get reloadReason(){}prepareToRender(){}render(){}finishRendering(){this.resolvingFunctions&&(this.resolvingFunctions.resolve(),delete this.resolvingFunctions)}async preservingPermanentElements(e){await Le.preservingPermanentElements(this,this.permanentElementMap,e)}focusFirstAutofocusableElement(){if(this.shouldAutofocus){let e=this.connectedSnapshot.firstAutofocusableElement;e&&e.focus()}}enteringBardo(e){this.#e||e.contains(this.currentSnapshot.activeElement)&&(this.#e=this.currentSnapshot.activeElement)}leavingBardo(e){e.contains(this.#e)&&this.#e instanceof HTMLElement&&(this.#e.focus(),this.#e=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"}},te=class extends ce{static renderElement(e,t){let s=document.createRange();s.selectNodeContents(e),s.deleteContents();let i=t,n=i.ownerDocument?.createRange();n&&(n.selectNodeContents(i),e.appendChild(n.extractContents()))}constructor(e,t,s,i,n,o=!0){super(t,s,i,n,o),this.delegate=e}get shouldRender(){return!0}async render(){await ie(),this.preservingPermanentElements(()=>{this.loadFrameElement()}),this.scrollFrameIntoView(),await ie(),this.focusFirstAutofocusableElement(),await ie(),this.activateScriptElements()}loadFrameElement(){this.delegate.willRenderFrame(this.currentElement,this.newElement),this.renderElement(this.currentElement,this.newElement)}scrollFrameIntoView(){if(this.currentElement.autoscroll||this.newElement.autoscroll){let e=this.currentElement.firstElementChild,t=Pr(this.currentElement.getAttribute("data-autoscroll-block"),"end"),s=Br(this.currentElement.getAttribute("data-autoscroll-behavior"),"auto");if(e)return e.scrollIntoView({block:t,behavior:s}),!0}return!1}activateScriptElements(){for(let e of this.newScriptElements){let t=oe(e);e.replaceWith(t)}}get newScriptElements(){return this.currentElement.querySelectorAll("script")}};function Pr(r,e){return r=="end"||r=="start"||r=="center"||r=="nearest"?r:e}function Br(r,e){return r=="auto"||r=="smooth"?r:e}var Nr=(function(){let r=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:r,afterNodeAdded:r,beforeNodeMorphed:r,afterNodeMorphed:r,beforeNodeRemoved:r,afterNodeRemoved:r,beforeAttributeUpdated:r},head:{style:"merge",shouldPreserve:f=>f.getAttribute("im-preserve")==="true",shouldReAppend:f=>f.getAttribute("im-re-append")==="true",shouldRemove:r,afterHeadMorphed:r},restoreFocus:!0};function t(f,A,b={}){f=k(f);let S=N(A),E=C(f,S,b),v=i(E,()=>m(E,f,S,l=>l.morphStyle==="innerHTML"?(n(l,f,S),Array.from(f.childNodes)):s(l,f,S)));return E.pantry.remove(),v}function s(f,A,b){let S=N(A);return n(f,S,b,A,A.nextSibling),Array.from(S.childNodes)}function i(f,A){if(!f.config.restoreFocus)return A();let b=document.activeElement;if(!(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement))return A();let{id:S,selectionStart:E,selectionEnd:v}=b,l=A();return S&&S!==document.activeElement?.getAttribute("id")&&(b=f.target.querySelector(`[id="${S}"]`),b?.focus()),b&&!b.selectionEnd&&v&&b.setSelectionRange(E,v),l}let n=(function(){function f(a,c,u,h=null,p=null){c instanceof HTMLTemplateElement&&u instanceof HTMLTemplateElement&&(c=c.content,u=u.content),h||=c.firstChild;for(let g of u.childNodes){if(h&&h!=p){let T=b(a,g,h,p);if(T){T!==h&&E(a,h,T),o(T,g,a),h=T.nextSibling;continue}}if(g instanceof Element){let T=g.getAttribute("id");if(a.persistentIds.has(T)){let x=v(c,T,h,a);o(x,g,a),h=x.nextSibling;continue}}let y=A(c,g,h,a);y&&(h=y.nextSibling)}for(;h&&h!=p;){let g=h;h=h.nextSibling,S(a,g)}}function A(a,c,u,h){if(h.callbacks.beforeNodeAdded(c)===!1)return null;if(h.idMap.has(c)){let p=document.createElement(c.tagName);return a.insertBefore(p,u),o(p,c,h),h.callbacks.afterNodeAdded(p),p}else{let p=document.importNode(c,!0);return a.insertBefore(p,u),h.callbacks.afterNodeAdded(p),p}}let b=(function(){function a(h,p,g,y){let T=null,x=p.nextSibling,rs=0,q=g;for(;q&&q!=y;){if(u(q,p)){if(c(h,q,p))return q;T===null&&(h.idMap.has(q)||(T=q))}if(T===null&&x&&u(q,x)&&(rs++,x=x.nextSibling,rs>=2&&(T=void 0)),h.activeElementAndParents.includes(q))break;q=q.nextSibling}return T||null}function c(h,p,g){let y=h.idMap.get(p),T=h.idMap.get(g);if(!T||!y)return!1;for(let x of y)if(T.has(x))return!0;return!1}function u(h,p){let g=h,y=p;return g.nodeType===y.nodeType&&g.tagName===y.tagName&&(!g.getAttribute?.("id")||g.getAttribute?.("id")===y.getAttribute?.("id"))}return a})();function S(a,c){if(a.idMap.has(c))d(a.pantry,c,null);else{if(a.callbacks.beforeNodeRemoved(c)===!1)return;c.parentNode?.removeChild(c),a.callbacks.afterNodeRemoved(c)}}function E(a,c,u){let h=c;for(;h&&h!==u;){let p=h;h=h.nextSibling,S(a,p)}return h}function v(a,c,u,h){let p=h.target.getAttribute?.("id")===c&&h.target||h.target.querySelector(`[id="${c}"]`)||h.pantry.querySelector(`[id="${c}"]`);return l(p,h),d(a,p,u),p}function l(a,c){let u=a.getAttribute("id");for(;a=a.parentNode;){let h=c.idMap.get(a);h&&(h.delete(u),h.size||c.idMap.delete(a))}}function d(a,c,u){if(a.moveBefore)try{a.moveBefore(c,u)}catch{a.insertBefore(c,u)}else a.insertBefore(c,u)}return f})(),o=(function(){function f(l,d,a){return a.ignoreActive&&l===document.activeElement?null:(a.callbacks.beforeNodeMorphed(l,d)===!1||(l instanceof HTMLHeadElement&&a.head.ignore||(l instanceof HTMLHeadElement&&a.head.style!=="morph"?w(l,d,a):(A(l,d,a),v(l,a)||n(a,l,d))),a.callbacks.afterNodeMorphed(l,d)),l)}function A(l,d,a){let c=d.nodeType;if(c===1){let u=l,h=d,p=u.attributes,g=h.attributes;for(let y of g)E(y.name,u,"update",a)||u.getAttribute(y.name)!==y.value&&u.setAttribute(y.name,y.value);for(let y=p.length-1;0<=y;y--){let T=p[y];if(T&&!h.hasAttribute(T.name)){if(E(T.name,u,"remove",a))continue;u.removeAttribute(T.name)}}v(u,a)||b(u,h,a)}(c===8||c===3)&&l.nodeValue!==d.nodeValue&&(l.nodeValue=d.nodeValue)}function b(l,d,a){if(l instanceof HTMLInputElement&&d instanceof HTMLInputElement&&d.type!=="file"){let c=d.value,u=l.value;S(l,d,"checked",a),S(l,d,"disabled",a),d.hasAttribute("value")?u!==c&&(E("value",l,"update",a)||(l.setAttribute("value",c),l.value=c)):E("value",l,"remove",a)||(l.value="",l.removeAttribute("value"))}else if(l instanceof HTMLOptionElement&&d instanceof HTMLOptionElement)S(l,d,"selected",a);else if(l instanceof HTMLTextAreaElement&&d instanceof HTMLTextAreaElement){let c=d.value,u=l.value;if(E("value",l,"update",a))return;c!==u&&(l.value=c),l.firstChild&&l.firstChild.nodeValue!==c&&(l.firstChild.nodeValue=c)}}function S(l,d,a,c){let u=d[a],h=l[a];if(u!==h){let p=E(a,l,"update",c);p||(l[a]=d[a]),u?p||l.setAttribute(a,""):E(a,l,"remove",c)||l.removeAttribute(a)}}function E(l,d,a,c){return l==="value"&&c.ignoreActiveValue&&d===document.activeElement?!0:c.callbacks.beforeAttributeUpdated(l,d,a)===!1}function v(l,d){return!!d.ignoreActiveValue&&l===document.activeElement&&l!==document.body}return f})();function m(f,A,b,S){if(f.head.block){let E=A.querySelector("head"),v=b.querySelector("head");if(E&&v){let l=w(E,v,f);return Promise.all(l).then(()=>{let d=Object.assign(f,{head:{block:!1,ignore:!0}});return S(d)})}}return S(f)}function w(f,A,b){let S=[],E=[],v=[],l=[],d=new Map;for(let c of A.children)d.set(c.outerHTML,c);for(let c of f.children){let u=d.has(c.outerHTML),h=b.head.shouldReAppend(c),p=b.head.shouldPreserve(c);u||p?h?E.push(c):(d.delete(c.outerHTML),v.push(c)):b.head.style==="append"?h&&(E.push(c),l.push(c)):b.head.shouldRemove(c)!==!1&&E.push(c)}l.push(...d.values());let a=[];for(let c of l){let u=document.createRange().createContextualFragment(c.outerHTML).firstChild;if(b.callbacks.beforeNodeAdded(u)!==!1){if("href"in u&&u.href||"src"in u&&u.src){let h,p=new Promise(function(g){h=g});u.addEventListener("load",function(){h()}),a.push(p)}f.appendChild(u),b.callbacks.afterNodeAdded(u),S.push(u)}}for(let c of E)b.callbacks.beforeNodeRemoved(c)!==!1&&(f.removeChild(c),b.callbacks.afterNodeRemoved(c));return b.head.afterHeadMorphed(f,{added:S,kept:v,removed:E}),a}let C=(function(){function f(a,c,u){let{persistentIds:h,idMap:p}=l(a,c),g=A(u),y=g.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(y))throw`Do not understand how to morph style ${y}`;return{target:a,newContent:c,config:g,morphStyle:y,ignoreActive:g.ignoreActive,ignoreActiveValue:g.ignoreActiveValue,restoreFocus:g.restoreFocus,idMap:p,persistentIds:h,pantry:b(),activeElementAndParents:S(a),callbacks:g.callbacks,head:g.head}}function A(a){let c=Object.assign({},e);return Object.assign(c,a),c.callbacks=Object.assign({},e.callbacks,a.callbacks),c.head=Object.assign({},e.head,a.head),c}function b(){let a=document.createElement("div");return a.hidden=!0,document.body.insertAdjacentElement("afterend",a),a}function S(a){let c=[],u=document.activeElement;if(u?.tagName!=="BODY"&&a.contains(u))for(;u&&(c.push(u),u!==a);)u=u.parentElement;return c}function E(a){let c=Array.from(a.querySelectorAll("[id]"));return a.getAttribute?.("id")&&c.push(a),c}function v(a,c,u,h){for(let p of h){let g=p.getAttribute("id");if(c.has(g)){let y=p;for(;y;){let T=a.get(y);if(T==null&&(T=new Set,a.set(y,T)),T.add(g),y===u)break;y=y.parentElement}}}}function l(a,c){let u=E(a),h=E(c),p=d(u,h),g=new Map;v(g,p,a,u);let y=c.__idiomorphRoot||c;return v(g,p,y,h),{persistentIds:p,idMap:g}}function d(a,c){let u=new Set,h=new Map;for(let{id:g,tagName:y}of a)h.has(g)?u.add(g):h.set(g,y);let p=new Set;for(let{id:g,tagName:y}of c)p.has(g)?u.add(g):h.get(g)===y&&p.add(g);for(let g of u)p.delete(g);return p}return f})(),{normalizeElement:k,normalizeParent:N}=(function(){let f=new WeakSet;function A(v){return v instanceof Document?v.documentElement:v}function b(v){if(v==null)return document.createElement("div");if(typeof v=="string")return b(E(v));if(f.has(v))return v;if(v instanceof Node){if(v.parentNode)return new S(v);{let l=document.createElement("div");return l.append(v),l}}else{let l=document.createElement("div");for(let d of[...v])l.append(d);return l}}class S{constructor(l){this.originalNode=l,this.realParentNode=l.parentNode,this.previousSibling=l.previousSibling,this.nextSibling=l.nextSibling}get childNodes(){let l=[],d=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;d&&d!=this.nextSibling;)l.push(d),d=d.nextSibling;return l}querySelectorAll(l){return this.childNodes.reduce((d,a)=>{if(a instanceof Element){a.matches(l)&&d.push(a);let c=a.querySelectorAll(l);for(let u=0;u<c.length;u++)d.push(c[u])}return d},[])}insertBefore(l,d){return this.realParentNode.insertBefore(l,d)}moveBefore(l,d){return this.realParentNode.moveBefore(l,d)}get __idiomorphRoot(){return this.originalNode}}function E(v){let l=new DOMParser,d=v.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(d.match(/<\/html>/)||d.match(/<\/head>/)||d.match(/<\/body>/)){let a=l.parseFromString(v,"text/html");if(d.match(/<\/html>/))return f.add(a),a;{let c=a.firstChild;return c&&f.add(c),c}}else{let c=l.parseFromString("<body><template>"+v+"</template></body>","text/html").body.querySelector("template").content;return f.add(c),c}}return{normalizeElement:A,normalizeParent:b}})();return{morph:t,defaults:e}})();function le(r,e,{callbacks:t,...s}={}){Nr.morph(r,e,{...s,callbacks:new je(t)})}function Ie(r,e,t={}){le(r,e.childNodes,{...t,morphStyle:"innerHTML"})}function Ms(r,e){return r instanceof P&&r.shouldReloadWithMorph&&(!e||qr(r,e))&&!r.closest("[data-turbo-permanent]")}function qr(r,e){return e instanceof Element&&e.nodeName==="TURBO-FRAME"&&r.id===e.id&&(!e.getAttribute("src")||ws(r.src,e.getAttribute("src")))}function Rs(r){return r.parentElement.closest("turbo-frame[src][refresh=morph]")}var je=class{#e;constructor({beforeNodeMorphed:e}={}){this.#e=e||(()=>!0)}beforeNodeAdded=e=>!(e.id&&e.hasAttribute("data-turbo-permanent")&&document.getElementById(e.id));beforeNodeMorphed=(e,t)=>{if(e instanceof Element)return!e.hasAttribute("data-turbo-permanent")&&this.#e(e,t)?!L("turbo:before-morph-element",{cancelable:!0,target:e,detail:{currentElement:e,newElement:t}}).defaultPrevented:!1};beforeAttributeUpdated=(e,t,s)=>!L("turbo:before-morph-attribute",{cancelable:!0,target:t,detail:{attributeName:e,mutationType:s}}).defaultPrevented;beforeNodeRemoved=e=>this.beforeNodeMorphed(e);afterNodeMorphed=(e,t)=>{e instanceof Element&&L("turbo:morph-element",{target:e,detail:{currentElement:e,newElement:t}})}},Ce=class extends te{static renderElement(e,t){L("turbo:before-frame-morph",{target:e,detail:{currentElement:e,newElement:t}}),Ie(e,t,{callbacks:{beforeNodeMorphed:(s,i)=>Ms(s,i)&&Rs(s)===e?(s.reload(),!1):!0}})}async preservingPermanentElements(e){return await e()}},Ke=class r{static animationDuration=300;static get defaultCSS(){return ms`
|
|
6
|
+
`)}function nr(r,e){return r.reduce((t,s,i)=>{let n=e[i]==null?"":e[i];return t+s+n},"")}function U(){return Array.from({length:36}).map((r,e)=>e==8||e==13||e==18||e==23?"-":e==14?"4":e==19?(Math.floor(Math.random()*4)+8).toString(16):Math.floor(Math.random()*16).toString(16)).join("")}function pe(r,...e){for(let t of e.map(s=>s?.getAttribute(r)))if(typeof t=="string")return t;return null}function or(r,...e){return e.some(t=>t&&t.hasAttribute(r))}function ge(...r){for(let e of r)e.localName=="turbo-frame"&&e.setAttribute("busy",""),e.setAttribute("aria-busy","true")}function be(...r){for(let e of r)e.localName=="turbo-frame"&&e.removeAttribute("busy"),e.removeAttribute("aria-busy")}function ar(r,e=2e3){return new Promise(t=>{let s=()=>{r.removeEventListener("error",s),r.removeEventListener("load",s),t()};r.addEventListener("load",s,{once:!0}),r.addEventListener("error",s,{once:!0}),setTimeout(t,e)})}function fs(r){switch(r){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}function cr(r){return r=="advance"||r=="replace"||r=="restore"}function X(...r){let e=pe("data-turbo-action",...r);return cr(e)?e:null}function ft(r){return document.querySelector(`meta[name="${r}"]`)}function ve(r){let e=ft(r);return e&&e.content}function ps(){let r=ft("csp-nonce");if(r){let{nonce:e,content:t}=r;return e==""?t:e}}function lr(r,e){let t=ft(r);return t||(t=document.createElement("meta"),t.setAttribute("name",r),document.head.appendChild(t)),t.setAttribute("content",e),t}function Z(r,e){if(r instanceof Element)return r.closest(e)||Z(r.assignedSlot||r.getRootNode()?.host,e)}function pt(r){return!!r&&r.closest("[inert], :disabled, [hidden], details:not([open]), dialog:not([open])")==null&&typeof r.focus=="function"}function gs(r){return Array.from(r.querySelectorAll("[autofocus]")).find(pt)}async function hr(r,e){let t=e();r(),await hs();let s=e();return[t,s]}function bs(r){if(r==="_blank")return!1;if(r){for(let e of document.getElementsByName(r))if(e instanceof HTMLIFrameElement)return!1;return!0}else return!0}function vs(r){let e=Z(r,"a[href], a[xlink\\:href]");if(!e||e.href.startsWith("#")||e.hasAttribute("download"))return null;let t=e.getAttribute("target");return t&&t!=="_self"?null:e}function ur(r,e){let t=null;return(...s)=>{let i=()=>r.apply(this,s);clearTimeout(t),t=setTimeout(i,e)}}var dr={"aria-disabled":{beforeSubmit:r=>{r.setAttribute("aria-disabled","true"),r.addEventListener("click",is)},afterSubmit:r=>{r.removeAttribute("aria-disabled"),r.removeEventListener("click",is)}},disabled:{beforeSubmit:r=>r.disabled=!0,afterSubmit:r=>r.disabled=!1}},He=class{#e=null;constructor(e){Object.assign(this,e)}get submitter(){return this.#e}set submitter(e){this.#e=dr[e]||e}},mr=new He({mode:"on",submitter:"disabled"}),R={drive:sr,forms:mr};function F(r){return new URL(r.toString(),document.baseURI)}function ne(r){let e;if(r.hash)return r.hash.slice(1);if(e=r.href.match(/#(.*)$/))return e[1]}function gt(r,e){let t=e?.getAttribute("formaction")||r.getAttribute("action")||r.action;return F(t)}function fr(r){return(vr(r).match(/\.[^.]*$/)||[])[0]||""}function pr(r,e){let t=ns(e.origin+e.pathname);return ns(r.href)===t||r.href.startsWith(t)}function $(r,e){return pr(r,e)&&!R.drive.unvisitableExtensions.has(fr(r))}function ys(r){return F(r.getAttribute("href")||"")}function gr(r){let e=ne(r);return e!=null?r.href.slice(0,-(e.length+1)):r.href}function fe(r){return gr(r)}function ws(r,e){return F(r).href==F(e).href}function br(r){return r.pathname.split("/").slice(1)}function vr(r){return br(r).slice(-1)[0]}function ns(r){return r.endsWith("/")?r:r+"/"}var Q=class{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 F(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)}},$e=class extends Set{constructor(e){super(),this.maxSize=e}add(e){if(this.size>=this.maxSize){let s=this.values().next().value;this.delete(s)}super.add(e)}},Es=new $e(20);function bt(r,e={}){let t=new Headers(e.headers||{}),s=U();return Es.add(s),t.append("X-Turbo-Request-Id",s),window.fetch(r,{...e,headers:t})}function Oe(r){switch(r.toLowerCase()){case"get":return I.get;case"post":return I.post;case"put":return I.put;case"patch":return I.patch;case"delete":return I.delete}}var I={get:"get",post:"post",put:"put",patch:"patch",delete:"delete"};function Ss(r){switch(r.toLowerCase()){case _.multipart:return _.multipart;case _.plain:return _.plain;default:return _.urlEncoded}}var _={urlEncoded:"application/x-www-form-urlencoded",multipart:"multipart/form-data",plain:"text/plain"},W=class{abortController=new AbortController;#e=e=>{};constructor(e,t,s,i=new URLSearchParams,n=null,o=_.urlEncoded){let[m,w]=os(F(s),t,i,o);this.delegate=e,this.url=m,this.target=n,this.fetchOptions={credentials:"same-origin",redirect:"follow",method:t.toUpperCase(),headers:{...this.defaultHeaders},body:w,signal:this.abortSignal,referrer:this.delegate.referrer?.href},this.enctype=o}get method(){return this.fetchOptions.method}set method(e){let t=this.isSafe?this.url.searchParams:this.fetchOptions.body||new FormData,s=Oe(e)||I.get;this.url.search="";let[i,n]=os(this.url,s,t,this.enctype);this.url=i,this.fetchOptions.body=n,this.fetchOptions.method=s.toUpperCase()}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(){let{fetchOptions:e}=this;this.delegate.prepareRequest(this);let t=await this.#t(e);try{this.delegate.requestStarted(this),t.detail.fetchRequest?this.response=t.detail.fetchRequest.response:this.response=bt(this.url.href,e);let s=await this.response;return await this.receive(s)}catch(s){if(s.name!=="AbortError")throw this.#s(s)&&this.delegate.requestErrored(this,s),s}finally{this.delegate.requestFinished(this)}}async receive(e){let t=new Q(e);return L("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 Fe(this.method)}get abortSignal(){return this.abortController.signal}acceptResponseType(e){this.headers.Accept=[e,this.headers.Accept].join(", ")}async#t(e){let t=new Promise(i=>this.#e=i),s=L("turbo:before-fetch-request",{cancelable:!0,detail:{fetchOptions:e,url:this.url,resume:this.#e},target:this.target});return this.url=s.detail.url,s.defaultPrevented&&await t,s}#s(e){return!L("turbo:fetch-request-error",{target:this.target,cancelable:!0,detail:{request:this,error:e}}).defaultPrevented}};function Fe(r){return Oe(r)==I.get}function os(r,e,t,s){let i=Array.from(t).length>0?new URLSearchParams(As(t)):r.searchParams;return Fe(e)?[yr(r,i),null]:s==_.urlEncoded?[r,i]:[r,t]}function As(r){let e=[];for(let[t,s]of r)s instanceof File||e.push([t,s]);return e}function yr(r,e){let t=new URLSearchParams(As(e));return r.search=t.toString(),r}var _e=class{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=>{e.slice(-1)[0]?.isIntersecting&&this.delegate.elementAppearedInViewport(this.element)}},j=class{static contentType="text/vnd.turbo-stream.html";static wrap(e){return typeof e=="string"?new this(ir(e)):e}constructor(e){this.fragment=wr(e)}};function wr(r){for(let e of r.querySelectorAll("turbo-stream")){let t=document.importNode(e,!0);for(let s of t.templateElement.content.querySelectorAll("script"))s.replaceWith(oe(s));e.replaceWith(t)}return r}var Er=r=>r,ye=class{keys=[];entries={};#e;constructor(e,t=Er){this.size=e,this.#e=t}has(e){return this.#e(e)in this.entries}get(e){if(this.has(e)){let t=this.read(e);return this.touch(e),t}}put(e,t){return this.write(e,t),this.touch(e),t}clear(){for(let e of Object.keys(this.entries))this.evict(e)}read(e){return this.entries[this.#e(e)]}write(e,t){this.entries[this.#e(e)]=t}touch(e){e=this.#e(e);let t=this.keys.indexOf(e);t>-1&&this.keys.splice(t,1),this.keys.unshift(e),this.trim()}trim(){for(let e of this.keys.splice(this.size))this.evict(e)}evict(e){delete this.entries[e]}},Sr=100,Ue=class extends ye{#e=null;#t={};constructor(e=1,t=Sr){super(e,fe),this.prefetchDelay=t}putLater(e,t,s){this.#e=setTimeout(()=>{t.perform(),this.put(e,t,s),this.#e=null},this.prefetchDelay)}put(e,t,s=Ts){super.put(e,t),this.#t[fe(e)]=new Date(new Date().getTime()+s)}clear(){super.clear(),this.#e&&clearTimeout(this.#e)}evict(e){super.evict(e),delete this.#t[e]}has(e){if(super.has(e)){let t=this.#t[fe(e)];return t&&t>Date.now()}else return!1}},Ts=10*1e3,Y=new Ue,J={initialized:"initialized",requesting:"requesting",waiting:"waiting",receiving:"receiving",stopping:"stopping",stopped:"stopped"},we=class r{state=J.initialized;static confirmMethod(e){return Promise.resolve(confirm(e))}constructor(e,t,s,i=!1){let n=Rr(t,s),o=Mr(Cr(t,s),n),m=Ar(t,s),w=kr(t,s);this.delegate=e,this.formElement=t,this.submitter=s,this.fetchRequest=new W(this,n,o,m,t,w),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=F(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(){let{initialized:e,requesting:t}=J,s=pe("data-turbo-confirm",this.submitter,this.formElement);if(!(typeof s=="string"&&!await(typeof R.forms.confirm=="function"?R.forms.confirm:r.confirmMethod)(s,this.formElement,this.submitter))&&this.state==e)return this.state=t,this.fetchRequest.perform()}stop(){let{stopping:e,stopped:t}=J;if(this.state!=e&&this.state!=t)return this.state=e,this.fetchRequest.cancel(),!0}prepareRequest(e){if(!e.isSafe){let t=Tr(ve("csrf-param"))||ve("csrf-token");t&&(e.headers["X-CSRF-Token"]=t)}this.requestAcceptsTurboStreamResponse(e)&&e.acceptResponseType(j.contentType)}requestStarted(e){this.state=J.waiting,this.submitter&&R.forms.submitter.beforeSubmit(this.submitter),this.setSubmitsWith(),ge(this.formElement),L("turbo:submit-start",{target:this.formElement,detail:{formSubmission:this}}),this.delegate.formSubmissionStarted(this)}requestPreventedHandlingResponse(e,t){Y.clear(),this.result={success:t.succeeded,fetchResponse:t}}requestSucceededWithResponse(e,t){if(t.clientError||t.serverError){this.delegate.formSubmissionFailedWithResponse(this,t);return}if(Y.clear(),this.requestMustRedirect(e)&&Lr(t)){let s=new Error("Form responses must redirect to another location");this.delegate.formSubmissionErrored(this,s)}else this.state=J.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=J.stopped,this.submitter&&R.forms.submitter.afterSubmit(this.submitter),this.resetSubmitterText(),be(this.formElement),L("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")){let 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")){let e=this.submitter;e.value=this.originalSubmitText}}}requestMustRedirect(e){return!e.isSafe&&this.mustRedirect}requestAcceptsTurboStreamResponse(e){return!e.isSafe||or("data-turbo-stream",this.submitter,this.formElement)}get submitsWith(){return this.submitter?.getAttribute("data-turbo-submits-with")}};function Ar(r,e){let t=new FormData(r),s=e?.getAttribute("name"),i=e?.getAttribute("value");return s&&t.append(s,i||""),t}function Tr(r){if(r!=null){let t=(document.cookie?document.cookie.split("; "):[]).find(s=>s.startsWith(r));if(t){let s=t.split("=").slice(1).join("=");return s?decodeURIComponent(s):void 0}}}function Lr(r){return r.statusCode==200&&!r.redirected}function Cr(r,e){let t=typeof r.action=="string"?r.action:null;return e?.hasAttribute("formaction")?e.getAttribute("formaction")||"":r.getAttribute("action")||t||""}function Mr(r,e){let t=F(r);return Fe(e)&&(t.search=""),t}function Rr(r,e){let t=e?.getAttribute("formmethod")||r.getAttribute("method")||"";return Oe(t.toLowerCase())||I.get}function kr(r,e){return Ss(e?.getAttribute("formenctype")||r.enctype)}var ee=class{constructor(e){this.element=e}get activeElement(){return this.element.ownerDocument.activeElement}get children(){return[...this.element.children]}hasAnchor(e){return this.getElementForAnchor(e)!=null}getElementForAnchor(e){return e?this.element.querySelector(`[id='${e}'], a[name='${e}']`):null}get isConnected(){return this.element.isConnected}get firstAutofocusableElement(){return gs(this.element)}get permanentElements(){return Cs(this.element)}getPermanentElementById(e){return Ls(this.element,e)}getPermanentElementMapForSnapshot(e){let t={};for(let s of this.permanentElements){let{id:i}=s,n=e.getPermanentElementById(i);n&&(t[i]=[s,n])}return t}};function Ls(r,e){return r.querySelector(`#${e}[data-turbo-permanent]`)}function Cs(r){return r.querySelectorAll("[id][data-turbo-permanent]")}var ae=class{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){let t=e.target instanceof HTMLFormElement?e.target:void 0,s=e.submitter||void 0;t&&Or(t,s)&&Fr(t,s)&&this.delegate.willSubmitForm(t,s)&&(e.preventDefault(),e.stopImmediatePropagation(),this.delegate.formSubmitted(t,s))}}};function Or(r,e){return(e?.getAttribute("formmethod")||r.getAttribute("method"))!="dialog"}function Fr(r,e){let t=e?.getAttribute("formtarget")||r.getAttribute("target");return bs(t)}var Ee=class{#e=e=>{};#t=e=>{};constructor(e,t){this.delegate=e,this.element=t}scrollToAnchor(e){let t=this.snapshot.getElementForAnchor(e);t?(this.focusElement(t),this.scrollToElement(t)):this.scrollToPosition({x:0,y:0})}scrollToAnchorFromLocation(e){this.scrollToAnchor(ne(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){let{isPreview:t,shouldRender:s,willRender:i,newSnapshot:n}=e,o=i;if(s)try{this.renderPromise=new Promise(k=>this.#e=k),this.renderer=e,await this.prepareToRenderSnapshot(e);let m=new Promise(k=>this.#t=k),w={resume:this.#t,render:this.renderer.renderElement,renderMethod:this.renderer.renderMethod};this.delegate.allowsImmediateRender(n,w)||await m,await this.renderSnapshot(e),this.delegate.viewRenderedSnapshot(n,t,this.renderer.renderMethod),this.delegate.preloadOnLoadLinksForView(this.element),this.finishRenderingSnapshot(e)}finally{delete this.renderer,this.#e(void 0),delete this.renderPromise}else o&&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()}},We=class extends Ee{missing(){this.element.innerHTML='<strong class="turbo-frame-error">Content missing</strong>'}get snapshot(){return new ee(this.element)}},Se=class{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.clickEventIsSignificant(e)?this.clickEvent=e:delete this.clickEvent};linkClicked=e=>{this.clickEvent&&this.clickEventIsSignificant(e)&&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};clickEventIsSignificant(e){let t=e.composed?e.target?.parentElement:e.target,s=vs(t)||t;return s instanceof Element&&s.closest("turbo-frame, html")==this.element}},Ae=class{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)){let t=e.composedPath&&e.composedPath()[0]||e.target,s=vs(t);if(s&&bs(s.target)){let i=ys(s);this.delegate.willFollowLinkToLocation(s,i,e)&&(e.preventDefault(),this.delegate.followedLinkToLocation(s,i))}}};clickEventIsSignificant(e){return!(e.target&&e.target.isContentEditable||e.defaultPrevented||e.which>1||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)}},Te=class{constructor(e,t){this.delegate=e,this.linkInterceptor=new Ae(this,t)}start(){this.linkInterceptor.start()}stop(){this.linkInterceptor.stop()}canPrefetchRequestToLocation(e,t){return!1}prefetchAndCacheRequestToLocation(e,t){}willFollowLinkToLocation(e,t,s){return this.delegate.willSubmitFormLinkToLocation(e,t,s)&&(e.hasAttribute("data-turbo-method")||e.hasAttribute("data-turbo-stream"))}followedLinkToLocation(e,t){let s=document.createElement("form"),i="hidden";for(let[q,d]of t.searchParams)s.append(Object.assign(document.createElement("input"),{type:i,name:q,value:d}));let n=Object.assign(t,{search:""});s.setAttribute("data-turbo","true"),s.setAttribute("action",n.href),s.setAttribute("hidden","");let o=e.getAttribute("data-turbo-method");o&&s.setAttribute("method",o);let m=e.getAttribute("data-turbo-frame");m&&s.setAttribute("data-turbo-frame",m);let w=X(e);w&&s.setAttribute("data-turbo-action",w);let C=e.getAttribute("data-turbo-confirm");C&&s.setAttribute("data-turbo-confirm",C),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())}},Le=class{static async preservingPermanentElements(e,t,s){let i=new this(e,t);i.enter(),await s(),i.leave()}constructor(e,t){this.delegate=e,this.permanentElementMap=t}enter(){for(let e in this.permanentElementMap){let[t,s]=this.permanentElementMap[e];this.delegate.enteringBardo(t,s),this.replaceNewPermanentElementWithPlaceholder(s)}}leave(){for(let e in this.permanentElementMap){let[t]=this.permanentElementMap[e];this.replaceCurrentPermanentElementWithClone(t),this.replacePlaceholderWithPermanentElement(t),this.delegate.leavingBardo(t)}}replaceNewPermanentElementWithPlaceholder(e){let t=Ir(e);e.replaceWith(t)}replaceCurrentPermanentElementWithClone(e){let t=e.cloneNode(!0);e.replaceWith(t)}replacePlaceholderWithPermanentElement(e){this.getPlaceholderById(e.id)?.replaceWith(e)}getPlaceholderById(e){return this.placeholders.find(t=>t.content==e)}get placeholders(){return[...document.querySelectorAll("meta[name=turbo-permanent-placeholder][content]")]}};function Ir(r){let e=document.createElement("meta");return e.setAttribute("name","turbo-permanent-placeholder"),e.setAttribute("content",r.id),e}var ce=class{#e=null;static renderElement(e,t){}constructor(e,t,s,i=!0){this.currentSnapshot=e,this.newSnapshot=t,this.isPreview=s,this.willRender=i,this.renderElement=this.constructor.renderElement,this.promise=new Promise((n,o)=>this.resolvingFunctions={resolve:n,reject:o})}get shouldRender(){return!0}get shouldAutofocus(){return!0}get reloadReason(){}prepareToRender(){}render(){}finishRendering(){this.resolvingFunctions&&(this.resolvingFunctions.resolve(),delete this.resolvingFunctions)}async preservingPermanentElements(e){await Le.preservingPermanentElements(this,this.permanentElementMap,e)}focusFirstAutofocusableElement(){if(this.shouldAutofocus){let e=this.connectedSnapshot.firstAutofocusableElement;e&&e.focus()}}enteringBardo(e){this.#e||e.contains(this.currentSnapshot.activeElement)&&(this.#e=this.currentSnapshot.activeElement)}leavingBardo(e){e.contains(this.#e)&&this.#e instanceof HTMLElement&&(this.#e.focus(),this.#e=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"}},te=class extends ce{static renderElement(e,t){let s=document.createRange();s.selectNodeContents(e),s.deleteContents();let i=t,n=i.ownerDocument?.createRange();n&&(n.selectNodeContents(i),e.appendChild(n.extractContents()))}constructor(e,t,s,i,n,o=!0){super(t,s,i,n,o),this.delegate=e}get shouldRender(){return!0}async render(){await ie(),this.preservingPermanentElements(()=>{this.loadFrameElement()}),this.scrollFrameIntoView(),await ie(),this.focusFirstAutofocusableElement(),await ie(),this.activateScriptElements()}loadFrameElement(){this.delegate.willRenderFrame(this.currentElement,this.newElement),this.renderElement(this.currentElement,this.newElement)}scrollFrameIntoView(){if(this.currentElement.autoscroll||this.newElement.autoscroll){let e=this.currentElement.firstElementChild,t=Pr(this.currentElement.getAttribute("data-autoscroll-block"),"end"),s=Br(this.currentElement.getAttribute("data-autoscroll-behavior"),"auto");if(e)return e.scrollIntoView({block:t,behavior:s}),!0}return!1}activateScriptElements(){for(let e of this.newScriptElements){let t=oe(e);e.replaceWith(t)}}get newScriptElements(){return this.currentElement.querySelectorAll("script")}};function Pr(r,e){return r=="end"||r=="start"||r=="center"||r=="nearest"?r:e}function Br(r,e){return r=="auto"||r=="smooth"?r:e}var qr=(function(){let r=()=>{},e={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:r,afterNodeAdded:r,beforeNodeMorphed:r,afterNodeMorphed:r,beforeNodeRemoved:r,afterNodeRemoved:r,beforeAttributeUpdated:r},head:{style:"merge",shouldPreserve:d=>d.getAttribute("im-preserve")==="true",shouldReAppend:d=>d.getAttribute("im-re-append")==="true",shouldRemove:r,afterHeadMorphed:r},restoreFocus:!0};function t(d,A,y={}){d=k(d);let E=q(A),S=C(d,E,y),g=i(S,()=>m(S,d,E,l=>l.morphStyle==="innerHTML"?(n(l,d,E),Array.from(d.childNodes)):s(l,d,E)));return S.pantry.remove(),g}function s(d,A,y){let E=q(A);return n(d,E,y,A,A.nextSibling),Array.from(E.childNodes)}function i(d,A){if(!d.config.restoreFocus)return A();let y=document.activeElement;if(!(y instanceof HTMLInputElement||y instanceof HTMLTextAreaElement))return A();let{id:E,selectionStart:S,selectionEnd:g}=y,l=A();return E&&E!==document.activeElement?.getAttribute("id")&&(y=d.target.querySelector(`[id="${E}"]`),y?.focus()),y&&!y.selectionEnd&&g&&y.setSelectionRange(S,g),l}let n=(function(){function d(a,c,u,h=null,p=null){c instanceof HTMLTemplateElement&&u instanceof HTMLTemplateElement&&(c=c.content,u=u.content),h||=c.firstChild;for(let b of u.childNodes){if(h&&h!=p){let T=y(a,b,h,p);if(T){T!==h&&S(a,h,T),o(T,b,a),h=T.nextSibling;continue}}if(b instanceof Element){let T=b.getAttribute("id");if(a.persistentIds.has(T)){let x=g(c,T,h,a);o(x,b,a),h=x.nextSibling;continue}}let v=A(c,b,h,a);v&&(h=v.nextSibling)}for(;h&&h!=p;){let b=h;h=h.nextSibling,E(a,b)}}function A(a,c,u,h){if(h.callbacks.beforeNodeAdded(c)===!1)return null;if(h.idMap.has(c)){let p=document.createElement(c.tagName);return a.insertBefore(p,u),o(p,c,h),h.callbacks.afterNodeAdded(p),p}else{let p=document.importNode(c,!0);return a.insertBefore(p,u),h.callbacks.afterNodeAdded(p),p}}let y=(function(){function a(h,p,b,v){let T=null,x=p.nextSibling,rs=0,N=b;for(;N&&N!=v;){if(u(N,p)){if(c(h,N,p))return N;T===null&&(h.idMap.has(N)||(T=N))}if(T===null&&x&&u(N,x)&&(rs++,x=x.nextSibling,rs>=2&&(T=void 0)),h.activeElementAndParents.includes(N))break;N=N.nextSibling}return T||null}function c(h,p,b){let v=h.idMap.get(p),T=h.idMap.get(b);if(!T||!v)return!1;for(let x of v)if(T.has(x))return!0;return!1}function u(h,p){let b=h,v=p;return b.nodeType===v.nodeType&&b.tagName===v.tagName&&(!b.getAttribute?.("id")||b.getAttribute?.("id")===v.getAttribute?.("id"))}return a})();function E(a,c){if(a.idMap.has(c))f(a.pantry,c,null);else{if(a.callbacks.beforeNodeRemoved(c)===!1)return;c.parentNode?.removeChild(c),a.callbacks.afterNodeRemoved(c)}}function S(a,c,u){let h=c;for(;h&&h!==u;){let p=h;h=h.nextSibling,E(a,p)}return h}function g(a,c,u,h){let p=h.target.getAttribute?.("id")===c&&h.target||h.target.querySelector(`[id="${c}"]`)||h.pantry.querySelector(`[id="${c}"]`);return l(p,h),f(a,p,u),p}function l(a,c){let u=a.getAttribute("id");for(;a=a.parentNode;){let h=c.idMap.get(a);h&&(h.delete(u),h.size||c.idMap.delete(a))}}function f(a,c,u){if(a.moveBefore)try{a.moveBefore(c,u)}catch{a.insertBefore(c,u)}else a.insertBefore(c,u)}return d})(),o=(function(){function d(l,f,a){return a.ignoreActive&&l===document.activeElement?null:(a.callbacks.beforeNodeMorphed(l,f)===!1||(l instanceof HTMLHeadElement&&a.head.ignore||(l instanceof HTMLHeadElement&&a.head.style!=="morph"?w(l,f,a):(A(l,f,a),g(l,a)||n(a,l,f))),a.callbacks.afterNodeMorphed(l,f)),l)}function A(l,f,a){let c=f.nodeType;if(c===1){let u=l,h=f,p=u.attributes,b=h.attributes;for(let v of b)S(v.name,u,"update",a)||u.getAttribute(v.name)!==v.value&&u.setAttribute(v.name,v.value);for(let v=p.length-1;0<=v;v--){let T=p[v];if(T&&!h.hasAttribute(T.name)){if(S(T.name,u,"remove",a))continue;u.removeAttribute(T.name)}}g(u,a)||y(u,h,a)}(c===8||c===3)&&l.nodeValue!==f.nodeValue&&(l.nodeValue=f.nodeValue)}function y(l,f,a){if(l instanceof HTMLInputElement&&f instanceof HTMLInputElement&&f.type!=="file"){let c=f.value,u=l.value;E(l,f,"checked",a),E(l,f,"disabled",a),f.hasAttribute("value")?u!==c&&(S("value",l,"update",a)||(l.setAttribute("value",c),l.value=c)):S("value",l,"remove",a)||(l.value="",l.removeAttribute("value"))}else if(l instanceof HTMLOptionElement&&f instanceof HTMLOptionElement)E(l,f,"selected",a);else if(l instanceof HTMLTextAreaElement&&f instanceof HTMLTextAreaElement){let c=f.value,u=l.value;if(S("value",l,"update",a))return;c!==u&&(l.value=c),l.firstChild&&l.firstChild.nodeValue!==c&&(l.firstChild.nodeValue=c)}}function E(l,f,a,c){let u=f[a],h=l[a];if(u!==h){let p=S(a,l,"update",c);p||(l[a]=f[a]),u?p||l.setAttribute(a,""):S(a,l,"remove",c)||l.removeAttribute(a)}}function S(l,f,a,c){return l==="value"&&c.ignoreActiveValue&&f===document.activeElement?!0:c.callbacks.beforeAttributeUpdated(l,f,a)===!1}function g(l,f){return!!f.ignoreActiveValue&&l===document.activeElement&&l!==document.body}return d})();function m(d,A,y,E){if(d.head.block){let S=A.querySelector("head"),g=y.querySelector("head");if(S&&g){let l=w(S,g,d);return Promise.all(l).then(()=>{let f=Object.assign(d,{head:{block:!1,ignore:!0}});return E(f)})}}return E(d)}function w(d,A,y){let E=[],S=[],g=[],l=[],f=new Map;for(let c of A.children)f.set(c.outerHTML,c);for(let c of d.children){let u=f.has(c.outerHTML),h=y.head.shouldReAppend(c),p=y.head.shouldPreserve(c);u||p?h?S.push(c):(f.delete(c.outerHTML),g.push(c)):y.head.style==="append"?h&&(S.push(c),l.push(c)):y.head.shouldRemove(c)!==!1&&S.push(c)}l.push(...f.values());let a=[];for(let c of l){let u=document.createRange().createContextualFragment(c.outerHTML).firstChild;if(y.callbacks.beforeNodeAdded(u)!==!1){if("href"in u&&u.href||"src"in u&&u.src){let h,p=new Promise(function(b){h=b});u.addEventListener("load",function(){h()}),a.push(p)}d.appendChild(u),y.callbacks.afterNodeAdded(u),E.push(u)}}for(let c of S)y.callbacks.beforeNodeRemoved(c)!==!1&&(d.removeChild(c),y.callbacks.afterNodeRemoved(c));return y.head.afterHeadMorphed(d,{added:E,kept:g,removed:S}),a}let C=(function(){function d(a,c,u){let{persistentIds:h,idMap:p}=l(a,c),b=A(u),v=b.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(v))throw`Do not understand how to morph style ${v}`;return{target:a,newContent:c,config:b,morphStyle:v,ignoreActive:b.ignoreActive,ignoreActiveValue:b.ignoreActiveValue,restoreFocus:b.restoreFocus,idMap:p,persistentIds:h,pantry:y(),activeElementAndParents:E(a),callbacks:b.callbacks,head:b.head}}function A(a){let c=Object.assign({},e);return Object.assign(c,a),c.callbacks=Object.assign({},e.callbacks,a.callbacks),c.head=Object.assign({},e.head,a.head),c}function y(){let a=document.createElement("div");return a.hidden=!0,document.body.insertAdjacentElement("afterend",a),a}function E(a){let c=[],u=document.activeElement;if(u?.tagName!=="BODY"&&a.contains(u))for(;u&&(c.push(u),u!==a);)u=u.parentElement;return c}function S(a){let c=Array.from(a.querySelectorAll("[id]"));return a.getAttribute?.("id")&&c.push(a),c}function g(a,c,u,h){for(let p of h){let b=p.getAttribute("id");if(c.has(b)){let v=p;for(;v;){let T=a.get(v);if(T==null&&(T=new Set,a.set(v,T)),T.add(b),v===u)break;v=v.parentElement}}}}function l(a,c){let u=S(a),h=S(c),p=f(u,h),b=new Map;g(b,p,a,u);let v=c.__idiomorphRoot||c;return g(b,p,v,h),{persistentIds:p,idMap:b}}function f(a,c){let u=new Set,h=new Map;for(let{id:b,tagName:v}of a)h.has(b)?u.add(b):h.set(b,v);let p=new Set;for(let{id:b,tagName:v}of c)p.has(b)?u.add(b):h.get(b)===v&&p.add(b);for(let b of u)p.delete(b);return p}return d})(),{normalizeElement:k,normalizeParent:q}=(function(){let d=new WeakSet;function A(g){return g instanceof Document?g.documentElement:g}function y(g){if(g==null)return document.createElement("div");if(typeof g=="string")return y(S(g));if(d.has(g))return g;if(g instanceof Node){if(g.parentNode)return new E(g);{let l=document.createElement("div");return l.append(g),l}}else{let l=document.createElement("div");for(let f of[...g])l.append(f);return l}}class E{constructor(l){this.originalNode=l,this.realParentNode=l.parentNode,this.previousSibling=l.previousSibling,this.nextSibling=l.nextSibling}get childNodes(){let l=[],f=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;f&&f!=this.nextSibling;)l.push(f),f=f.nextSibling;return l}querySelectorAll(l){return this.childNodes.reduce((f,a)=>{if(a instanceof Element){a.matches(l)&&f.push(a);let c=a.querySelectorAll(l);for(let u=0;u<c.length;u++)f.push(c[u])}return f},[])}insertBefore(l,f){return this.realParentNode.insertBefore(l,f)}moveBefore(l,f){return this.realParentNode.moveBefore(l,f)}get __idiomorphRoot(){return this.originalNode}}function S(g){let l=new DOMParser,f=g.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(f.match(/<\/html>/)||f.match(/<\/head>/)||f.match(/<\/body>/)){let a=l.parseFromString(g,"text/html");if(f.match(/<\/html>/))return d.add(a),a;{let c=a.firstChild;return c&&d.add(c),c}}else{let c=l.parseFromString("<body><template>"+g+"</template></body>","text/html").body.querySelector("template").content;return d.add(c),c}}return{normalizeElement:A,normalizeParent:y}})();return{morph:t,defaults:e}})();function le(r,e,{callbacks:t,...s}={}){qr.morph(r,e,{...s,callbacks:new je(t)})}function Ie(r,e,t={}){le(r,e.childNodes,{...t,morphStyle:"innerHTML"})}function Ms(r,e){return r instanceof P&&r.shouldReloadWithMorph&&(!e||Nr(r,e))&&!r.closest("[data-turbo-permanent]")}function Nr(r,e){return e instanceof Element&&e.nodeName==="TURBO-FRAME"&&r.id===e.id&&(!e.getAttribute("src")||ws(r.src,e.getAttribute("src")))}function Rs(r){return r.parentElement.closest("turbo-frame[src][refresh=morph]")}var je=class{#e;constructor({beforeNodeMorphed:e}={}){this.#e=e||(()=>!0)}beforeNodeAdded=e=>!(e.id&&e.hasAttribute("data-turbo-permanent")&&document.getElementById(e.id));beforeNodeMorphed=(e,t)=>{if(e instanceof Element)return!e.hasAttribute("data-turbo-permanent")&&this.#e(e,t)?!L("turbo:before-morph-element",{cancelable:!0,target:e,detail:{currentElement:e,newElement:t}}).defaultPrevented:!1};beforeAttributeUpdated=(e,t,s)=>!L("turbo:before-morph-attribute",{cancelable:!0,target:t,detail:{attributeName:e,mutationType:s}}).defaultPrevented;beforeNodeRemoved=e=>this.beforeNodeMorphed(e);afterNodeMorphed=(e,t)=>{e instanceof Element&&L("turbo:morph-element",{target:e,detail:{currentElement:e,newElement:t}})}},Ce=class extends te{static renderElement(e,t){L("turbo:before-frame-morph",{target:e,detail:{currentElement:e,newElement:t}}),Ie(e,t,{callbacks:{beforeNodeMorphed:(s,i)=>Ms(s,i)&&Rs(s)===e?(s.reload(),!1):!0}})}async preservingPermanentElements(e){return await e()}},Ke=class r{static animationDuration=300;static get defaultCSS(){return ms`
|
|
7
7
|
.turbo-progress-bar {
|
|
8
8
|
position: fixed;
|
|
9
9
|
display: block;
|
|
@@ -17,7 +17,7 @@ Copyright © 2026 37signals LLC
|
|
|
17
17
|
opacity ${r.animationDuration/2}ms ${r.animationDuration/2}ms ease-in;
|
|
18
18
|
transform: translate3d(0, 0, 0);
|
|
19
19
|
}
|
|
20
|
-
`}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,r.animationDuration*1.5)}uninstallProgressElement(){this.progressElement.parentNode&&document.documentElement.removeChild(this.progressElement)}startTrickling(){this.trickleInterval||(this.trickleInterval=window.setInterval(this.trickle,r.animationDuration))}stopTrickling(){window.clearInterval(this.trickleInterval),delete this.trickleInterval}trickle=()=>{this.setValue(this.value+Math.random()/100)};refresh(){requestAnimationFrame(()=>{this.progressElement.style.width=`${10+this.value*90}%`})}createStylesheetElement(){let e=document.createElement("style");e.type="text/css",e.textContent=r.defaultCSS;let t=ps();return t&&(e.nonce=t),e}createProgressElement(){let e=document.createElement("div");return e.className="turbo-progress-bar",e}},ze=class extends ee{detailsByOuterHTML=this.children.filter(e=>!Hr(e)).map(e=>Ur(e)).reduce((e,t)=>{let{outerHTML:s}=t,i=s in e?e[s]:{type:Dr(t),tracked:xr(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(s=>!(s in t.detailsByOuterHTML)).map(s=>this.detailsByOuterHTML[s]).filter(({type:s})=>s==e).map(({elements:[s]})=>s)}get provisionalElements(){return Object.keys(this.detailsByOuterHTML).reduce((e,t)=>{let{type:s,tracked:i,elements:n}=this.detailsByOuterHTML[t];return s==null&&!i?[...e,...n]:n.length>1?[...e,...n.slice(1)]:e},[])}getMetaValue(e){let t=this.findMetaElementByName(e);return t?t.getAttribute("content"):null}findMetaElementByName(e){return Object.keys(this.detailsByOuterHTML).reduce((t,s)=>{let{elements:[i]}=this.detailsByOuterHTML[s];return _r(i,e)?i:t},void 0|void 0)}};function Dr(r){if(Vr(r))return"script";if($r(r))return"stylesheet"}function xr(r){return r.getAttribute("data-turbo-track")=="reload"}function Vr(r){return r.localName=="script"}function Hr(r){return r.localName=="noscript"}function $r(r){let e=r.localName;return e=="style"||e=="link"&&r.getAttribute("rel")=="stylesheet"}function _r(r,e){return r.localName=="meta"&&r.getAttribute("name")==e}function Ur(r){return r.hasAttribute("nonce")&&r.setAttribute("nonce",""),r}var B=class r extends ee{static fromHTMLString(e=""){return this.fromDocument(ds(e))}static fromElement(e){return this.fromDocument(e.ownerDocument)}static fromDocument({documentElement:e,body:t,head:s}){return new this(e,t,new ze(s))}constructor(e,t,s){super(t),this.documentElement=e,this.headSnapshot=s}clone(){let e=this.element.cloneNode(!0),t=this.element.querySelectorAll("select"),s=e.querySelectorAll("select");for(let[i,n]of t.entries()){let o=s[i];for(let m of o.selectedOptions)m.selected=!1;for(let m of n.selectedOptions)o.options[m.index].selected=!0}for(let i of e.querySelectorAll('input[type="password"]'))i.value="";for(let i of e.querySelectorAll("noscript"))i.remove();return new r(this.documentElement,e,this.headSnapshot)}get lang(){return this.documentElement.getAttribute("lang")}get dir(){return this.documentElement.getAttribute("dir")}get headElement(){return this.headSnapshot.element}get rootLocation(){let e=this.getSetting("root")??"/";return F(e)}get cacheControlValue(){return this.getSetting("cache-control")}get isPreviewable(){return this.cacheControlValue!="no-preview"}get isCacheable(){return this.cacheControlValue!="no-cache"}get isVisitable(){return this.getSetting("visit-control")!="reload"}get prefersViewTransitions(){return(this.getSetting("view-transition")==="true"||this.headSnapshot.getMetaValue("view-transition")==="same-origin")&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches}get refreshMethod(){return this.getSetting("refresh-method")}get refreshScroll(){return this.getSetting("refresh-scroll")}getSetting(e){return this.headSnapshot.getMetaValue(`turbo-${e}`)}},Xe=class{#e=!1;#t=Promise.resolve();renderChange(e,t){return e&&this.viewTransitionsAvailable&&!this.#e?(this.#e=!0,this.#t=this.#t.then(async()=>{await document.startViewTransition(t).finished})):this.#t=this.#t.then(t),this.#t}get viewTransitionsAvailable(){return document.startViewTransition}},Wr={action:"advance",historyChanged:!1,visitCachedSnapshot:()=>{},willRender:!0,updateHistory:!0,shouldCacheSnapshot:!0,acceptsStreamResponse:!1,refresh:{}},me={visitStart:"visitStart",requestStart:"requestStart",requestEnd:"requestEnd",visitEnd:"visitEnd"},V={initialized:"initialized",started:"started",canceled:"canceled",failed:"failed",completed:"completed"},G={networkFailure:0,timeoutFailure:-1,contentTypeMismatch:-2},jr={advance:"forward",restore:"back",replace:"none"},Je=class{identifier=U();timingMetrics={};followedRedirect=!1;historyChanged=!1;scrolled=!1;shouldCacheSnapshot=!0;acceptsStreamResponse=!1;snapshotCached=!1;state=V.initialized;viewTransitioner=new Xe;constructor(e,t,s,i={}){this.delegate=e,this.location=t,this.restorationIdentifier=s||U();let{action:n,historyChanged:o,referrer:m,snapshot:w,snapshotHTML:C,response:k,visitCachedSnapshot:N,willRender:f,updateHistory:A,shouldCacheSnapshot:b,acceptsStreamResponse:S,direction:E,refresh:v}={...Wr,...i};this.action=n,this.historyChanged=o,this.referrer=m,this.snapshot=w,this.snapshotHTML=C,this.response=k,this.isPageRefresh=this.view.isPageRefresh(this),this.visitCachedSnapshot=N,this.willRender=f,this.updateHistory=A,this.scrolled=!f,this.shouldCacheSnapshot=b,this.acceptsStreamResponse=S,this.direction=E||jr[n],this.refresh=v}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)}start(){this.state==V.initialized&&(this.recordTimingMetric(me.visitStart),this.state=V.started,this.adapter.visitStarted(this),this.delegate.visitStarted(this))}cancel(){this.state==V.started&&(this.request&&this.request.cancel(),this.cancelRender(),this.state=V.canceled)}complete(){this.state==V.started&&(this.recordTimingMetric(me.visitEnd),this.adapter.visitCompleted(this),this.state=V.completed,this.followRedirect(),this.followedRedirect||this.delegate.visitCompleted(this))}fail(){this.state==V.started&&(this.state=V.failed,this.adapter.visitFailed(this),this.delegate.visitCompleted(this))}changeHistory(){if(!this.historyChanged&&this.updateHistory){let e=this.location.href===this.referrer?.href?"replace":this.action,t=fs(e);this.history.update(t,this.location,this.restorationIdentifier),this.historyChanged=!0}}issueRequest(){this.hasPreloadedResponse()?this.simulateRequest():this.shouldIssueRequest()&&!this.request&&(this.request=new W(this,I.get,this.location),this.request.perform())}simulateRequest(){this.response&&(this.startRequest(),this.recordResponse(),this.finishRequest())}startRequest(){this.recordTimingMetric(me.requestStart),this.adapter.visitRequestStarted(this)}recordResponse(e=this.response){if(this.response=e,e){let{statusCode:t}=e;as(t)?this.adapter.visitRequestCompleted(this):this.adapter.visitRequestFailedWithStatusCode(this,t)}}finishRequest(){this.recordTimingMetric(me.requestEnd),this.adapter.visitRequestFinished(this)}loadResponse(){if(this.response){let{statusCode:e,responseHTML:t}=this.response;this.render(async()=>{if(this.shouldCacheSnapshot&&this.cacheSnapshot(),this.view.renderPromise&&await this.view.renderPromise,as(e)&&t!=null){let s=B.fromHTMLString(t);await this.renderPageSnapshot(s,!1),this.adapter.visitRendered(this),this.complete()}else await this.view.renderError(B.fromHTMLString(t),this),this.adapter.visitRendered(this),this.fail()})}}getCachedSnapshot(){let e=this.view.getCachedSnapshotForLocation(this.location)||this.getPreloadedSnapshot();if(e&&(!ne(this.location)||e.hasAnchor(ne(this.location)))&&(this.action=="restore"||e.isPreviewable))return e}getPreloadedSnapshot(){if(this.snapshotHTML)return B.fromHTMLString(this.snapshotHTML)}hasCachedSnapshot(){return this.getCachedSnapshot()!=null}loadCachedSnapshot(){let e=this.getCachedSnapshot();if(e){let t=this.shouldIssueRequest();this.render(async()=>{this.cacheSnapshot(),this.isPageRefresh?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)}prepareRequest(e){this.acceptsStreamResponse&&e.acceptResponseType(j.contentType)}requestStarted(){this.startRequest()}requestPreventedHandlingResponse(e,t){}async requestSucceededWithResponse(e,t){let s=await t.responseHTML,{redirected:i,statusCode:n}=t;s==null?this.recordResponse({statusCode:G.contentTypeMismatch,redirected:i}):(this.redirectedToLocation=t.redirected?t.location:void 0,this.recordResponse({statusCode:n,responseHTML:s,redirected:i}))}async requestFailedWithResponse(e,t){let s=await t.responseHTML,{redirected:i,statusCode:n}=t;s==null?this.recordResponse({statusCode:G.contentTypeMismatch,redirected:i}):this.recordResponse({statusCode:n,responseHTML:s,redirected:i})}requestErrored(e,t){this.recordResponse({statusCode:G.networkFailure,redirected:!1})}requestFinished(){this.finishRequest()}performScroll(){!this.scrolled&&!this.view.forceReloaded&&!this.view.shouldPreserveScrollPosition(this)&&(this.action=="restore"?this.scrollToRestoredPosition()||this.scrollToAnchor()||this.view.scrollToTop():this.scrollToAnchor()||this.view.scrollToTop(),this.scrolled=!0)}scrollToRestoredPosition(){let{scrollPosition:e}=this.restorationData;if(e)return this.view.scrollToPosition(e),!0}scrollToAnchor(){let e=ne(this.location);if(e!=null)return this.view.scrollToAnchor(e),!0}recordTimingMetric(e){this.timingMetrics[e]=new Date().getTime()}getTimingMetrics(){return{...this.timingMetrics}}hasPreloadedResponse(){return typeof this.response=="object"}shouldIssueRequest(){return this.action=="restore"?!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(t=>{this.frame=document.visibilityState==="hidden"?setTimeout(()=>t(),0):requestAnimationFrame(()=>t())}),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 as(r){return r>=200&&r<300}var Ye=class{progressBar=new Ke;constructor(e){this.session=e}visitProposedToLocation(e,t){$(e,this.navigator.rootLocation)?this.navigator.startVisit(e,t?.restorationIdentifier||U(),t):window.location.href=e.toString()}visitStarted(e){this.location=e.location,this.redirectedToLocation=null,e.loadCachedSnapshot(),e.issueRequest()}visitRequestStarted(e){this.progressBar.setValue(0),e.hasCachedSnapshot()||e.action!="restore"?this.showVisitProgressBarAfterDelay():this.showProgressBar()}visitRequestCompleted(e){e.loadResponse(),e.response.redirected&&(this.redirectedToLocation=e.redirectedToLocation)}visitRequestFailedWithStatusCode(e,t){switch(t){case G.networkFailure:case G.timeoutFailure:case G.contentTypeMismatch: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){}linkPrefetchingIsEnabledForLocation(e){return!0}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(),this.visitProgressBarTimeout!=null&&(window.clearTimeout(this.visitProgressBarTimeout),delete this.visitProgressBarTimeout)}showFormProgressBarAfterDelay(){this.formProgressBarTimeout==null&&(this.formProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay))}hideFormProgressBar(){this.progressBar.hide(),this.formProgressBarTimeout!=null&&(window.clearTimeout(this.formProgressBarTimeout),delete this.formProgressBarTimeout)}showProgressBar=()=>{this.progressBar.show()};reload(e){L("turbo:reload",{detail:e}),window.location.href=(this.redirectedToLocation||this.location)?.toString()||window.location.href}get navigator(){return this.session.navigator}},Ze=class{selector="[data-turbo-temporary]";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(let t of this.temporaryElements)t.remove()};get temporaryElements(){return[...document.querySelectorAll(this.selector)]}},Ge=class{constructor(e,t){this.session=e,this.element=t,this.linkInterceptor=new Se(this,t),this.formSubmitObserver=new ae(this,t)}start(){this.linkInterceptor.start(),this.formSubmitObserver.start()}stop(){this.linkInterceptor.stop(),this.formSubmitObserver.stop()}shouldInterceptLinkClick(e,t,s){return this.#t(e)}linkClickIntercepted(e,t,s){let i=this.#s(e);i&&i.delegate.linkClickIntercepted(e,t,s)}willSubmitForm(e,t){return e.closest("turbo-frame")==null&&this.#e(e,t)&&this.#t(e,t)}formSubmitted(e,t){let s=this.#s(e,t);s&&s.delegate.formSubmitted(e,t)}#e(e,t){let s=gt(e,t),i=this.element.ownerDocument.querySelector('meta[name="turbo-root"]'),n=F(i?.content??"/");return this.#t(e,t)&&$(s,n)}#t(e,t){if(e instanceof HTMLFormElement?this.session.submissionIsNavigatable(e,t):this.session.elementIsNavigatable(e)){let i=this.#s(e,t);return i?i!=e.closest("turbo-frame"):!1}else return!1}#s(e,t){let s=t?.getAttribute("data-turbo-frame")||e.getAttribute("data-turbo-frame");if(s&&s!="_top"){let i=this.element.querySelector(`#${s}:not([disabled])`);if(i instanceof P)return i}}},Qe=class{location;restorationIdentifier=U();restorationData={};started=!1;currentIndex=0;constructor(e){this.delegate=e}start(){this.started||(addEventListener("popstate",this.onPopState,!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),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=U()){e===history.pushState&&++this.currentIndex;let 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){let{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=>{let{turbo:t}=e.state||{};if(this.location=new URL(window.location.href),t){let{restorationIdentifier:s,restorationIndex:i}=t;this.restorationIdentifier=s;let n=i>this.currentIndex?"forward":"back";this.delegate.historyPoppedToLocationWithRestorationIdentifierAndDirection(this.location,s,n),this.currentIndex=i}else this.currentIndex++,this.delegate.historyPoppedWithEmptyState(this.location)}},et=class{started=!1;#e=null;constructor(e,t){this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.readyState==="loading"?this.eventTarget.addEventListener("DOMContentLoaded",this.#t,{once:!0}):this.#t())}stop(){this.started&&(this.eventTarget.removeEventListener("mouseenter",this.#s,{capture:!0,passive:!0}),this.eventTarget.removeEventListener("mouseleave",this.#o,{capture:!0,passive:!0}),this.eventTarget.removeEventListener("turbo:before-fetch-request",this.#i,!0),this.started=!1)}#t=()=>{this.eventTarget.addEventListener("mouseenter",this.#s,{capture:!0,passive:!0}),this.eventTarget.addEventListener("mouseleave",this.#o,{capture:!0,passive:!0}),this.eventTarget.addEventListener("turbo:before-fetch-request",this.#i,!0),this.started=!0};#s=e=>{if(ve("turbo-prefetch")==="false")return;let t=e.target;if(t.matches&&t.matches("a[href]:not([target^=_]):not([download])")&&this.#c(t)){let i=t,n=ys(i);if(this.delegate.canPrefetchRequestToLocation(i,n)){this.#e=i;let o=new W(this,I.get,n,new URLSearchParams,t);o.fetchOptions.priority="low",Y.putLater(n,o,this.#r)}}};#o=e=>{e.target===this.#e&&this.#a()};#a=()=>{Y.clear(),this.#e=null};#i=e=>{if(e.target.tagName!=="FORM"&&e.detail.fetchOptions.method==="GET"){let t=Y.get(e.detail.url);t&&(e.detail.fetchRequest=t),Y.clear()}};prepareRequest(e){let t=e.target;e.headers["X-Sec-Purpose"]="prefetch";let s=t.closest("turbo-frame"),i=t.getAttribute("data-turbo-frame")||s?.getAttribute("target")||s?.id;i&&i!=="_top"&&(e.headers["Turbo-Frame"]=i)}requestSucceededWithResponse(){}requestStarted(e){}requestErrored(e){}requestFinished(e){}requestPreventedHandlingResponse(e,t){}requestFailedWithResponse(e,t){}get#r(){return Number(ve("turbo-prefetch-cache-time"))||Ts}#c(e){return!(!e.getAttribute("href")||Kr(e)||zr(e)||Xr(e)||Jr(e)||Zr(e))}},Kr=r=>r.origin!==document.location.origin||!["http:","https:"].includes(r.protocol)||r.hasAttribute("target"),zr=r=>r.pathname+r.search===document.location.pathname+document.location.search||r.href.startsWith("#"),Xr=r=>{if(r.getAttribute("data-turbo-prefetch")==="false"||r.getAttribute("data-turbo")==="false")return!0;let e=Z(r,"[data-turbo-prefetch]");return!!(e&&e.getAttribute("data-turbo-prefetch")==="false")},Jr=r=>{let e=r.getAttribute("data-turbo-method");return!!(e&&e.toLowerCase()!=="get"||Yr(r)||r.hasAttribute("data-turbo-confirm")||r.hasAttribute("data-turbo-stream"))},Yr=r=>r.hasAttribute("data-remote")||r.hasAttribute("data-behavior")||r.hasAttribute("data-confirm")||r.hasAttribute("data-method"),Zr=r=>L("turbo:before-prefetch",{target:r,cancelable:!0}).defaultPrevented,tt=class{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 Je(this,F(e),t,{referrer:this.location,...s}),this.currentVisit.start()}submitForm(e,t){this.stop(),this.formSubmission=new we(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){typeof this.adapter.formSubmissionStarted=="function"&&this.adapter.formSubmissionStarted(e)}async formSubmissionSucceededWithResponse(e,t){if(e==this.formSubmission){let s=await t.responseHTML;if(s){let i=e.isSafe;i||this.view.clearSnapshotCache();let{statusCode:n,redirected:o}=t,w={action:this.#e(e,t),shouldCacheSnapshot:i,response:{statusCode:n,responseHTML:s,redirected:o}};this.proposeVisit(t.location,w)}}}async formSubmissionFailedWithResponse(e,t){let s=await t.responseHTML;if(s){let i=B.fromHTMLString(s);t.serverError?await this.view.renderError(i,this.currentVisit):await this.view.renderPage(i,!1,!0,this.currentVisit),i.refreshScroll!=="preserve"&&this.view.scrollToTop(),this.view.clearSnapshotCache()}}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished(e){typeof this.adapter.formSubmissionFinished=="function"&&this.adapter.formSubmissionFinished(e)}linkPrefetchingIsEnabledForLocation(e){return typeof this.adapter.linkPrefetchingIsEnabledForLocation=="function"?this.adapter.linkPrefetchingIsEnabledForLocation(e):!0}visitStarted(e){this.delegate.visitStarted(e)}visitCompleted(e){this.delegate.visitCompleted(e),delete this.currentVisit}locationWithActionIsSamePage(e,t){return!1}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}#e(e,t){let{submitter:s,formElement:i}=e;return X(s,i)||this.#t(t)}#t(e){return e.redirected&&e.location.href===this.location?.href?"replace":"advance"}},K={initial:0,loading:1,interactive:2,complete:3},st=class{stage=K.initial;started=!1;constructor(e){this.delegate=e}start(){this.started||(this.stage==K.initial&&(this.stage=K.loading),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=()=>{let{readyState:e}=this;e=="interactive"?this.pageIsInteractive():e=="complete"&&this.pageIsComplete()};pageIsInteractive(){this.stage==K.loading&&(this.stage=K.interactive,this.delegate.pageBecameInteractive())}pageIsComplete(){this.pageIsInteractive(),this.stage==K.interactive&&(this.stage=K.complete,this.delegate.pageLoaded())}pageWillUnload=()=>{this.delegate.pageWillUnload()};get readyState(){return document.readyState}},rt=class{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)}},it=class{render({fragment:e}){Le.preservingPermanentElements(this,Gr(e),()=>{Qr(e,()=>{ei(()=>{document.documentElement.appendChild(e)})})})}enteringBardo(e,t){t.replaceWith(e.cloneNode(!0))}leavingBardo(){}};function Gr(r){let e=Cs(document.documentElement),t={};for(let s of e){let{id:i}=s;for(let n of r.querySelectorAll("turbo-stream")){let o=Ls(n.templateElement.content,i);o&&(t[i]=[s,o])}}return t}async function Qr(r,e){let t=`turbo-stream-autofocus-${U()}`,s=r.querySelectorAll("turbo-stream"),i=ti(s),n=null;if(i&&(i.id?n=i.id:n=t,i.id=n),e(),await ie(),(document.activeElement==null||document.activeElement==document.body)&&n){let m=document.getElementById(n);pt(m)&&m.focus(),m&&m.id==t&&m.removeAttribute("id")}}async function ei(r){let[e,t]=await hr(r,()=>document.activeElement),s=e&&e.id;if(s){let i=document.getElementById(s);pt(i)&&i!=t&&i.focus()}}function ti(r){for(let e of r){let t=gs(e.templateElement.content);if(t)return t}return null}var nt=class{sources=new Set;#e=!1;constructor(e){this.delegate=e}start(){this.#e||(this.#e=!0,addEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}stop(){this.#e&&(this.#e=!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=>{let t=si(e);t&&ri(t)&&(e.preventDefault(),this.receiveMessageResponse(t))};receiveMessageEvent=e=>{this.#e&&typeof e.data=="string"&&this.receiveMessageHTML(e.data)};async receiveMessageResponse(e){let t=await e.responseHTML;t&&this.receiveMessageHTML(t)}receiveMessageHTML(e){this.delegate.receivedMessageFromStream(j.wrap(e))}};function si(r){let e=r.detail?.fetchResponse;if(e instanceof Q)return e}function ri(r){return(r.contentType??"").startsWith(j.contentType)}var ot=class extends ce{static renderElement(e,t){let{documentElement:s,body:i}=document;s.replaceChild(t,i)}async render(){this.replaceHeadAndBody(),this.activateScriptElements()}replaceHeadAndBody(){let{documentElement:e,head:t}=document;e.replaceChild(this.newHead,t),this.renderElement(this.currentElement,this.newElement)}activateScriptElements(){for(let e of this.scriptElements){let t=e.parentNode;if(t){let s=oe(e);t.replaceChild(s,e)}}}get newHead(){return this.newSnapshot.headSnapshot.element}get scriptElements(){return document.documentElement.querySelectorAll("script")}},se=class extends ce{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(){if(!this.newSnapshot.isVisitable)return{reason:"turbo_visit_control_is_reload"};if(!this.trackedElementsAreIdentical)return{reason:"tracked_element_mismatch"}}async prepareToRender(){this.#e(),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}#e(){let{documentElement:e}=this.currentSnapshot,{dir:t,lang:s}=this.newSnapshot;s?e.setAttribute("lang",s):e.removeAttribute("lang"),t?e.setAttribute("dir",t):e.removeAttribute("dir")}async mergeHead(){let e=this.mergeProvisionalElements(),t=this.copyNewHeadStylesheetElements();this.copyNewHeadScriptElements(),await e,await t,this.willRender&&this.removeUnusedDynamicStylesheetElements()}async replaceBody(){await this.preservingPermanentElements(async()=>{this.activateNewBody(),await this.assignNewBody()})}get trackedElementsAreIdentical(){return this.currentHeadSnapshot.trackedElementSignature==this.newHeadSnapshot.trackedElementSignature}async copyNewHeadStylesheetElements(){let e=[];for(let t of this.newHeadStylesheetElements)e.push(ar(t)),document.head.appendChild(t);await Promise.all(e)}copyNewHeadScriptElements(){for(let e of this.newHeadScriptElements)document.head.appendChild(oe(e))}removeUnusedDynamicStylesheetElements(){for(let e of this.unusedDynamicStylesheetElements)document.head.removeChild(e)}async mergeProvisionalElements(){let e=[...this.newHeadProvisionalElements];for(let t of this.currentHeadProvisionalElements)this.isCurrentElementInElementList(t,e)||document.head.removeChild(t);for(let t of e)document.head.appendChild(t)}isCurrentElementInElementList(e,t){for(let[s,i]of t.entries()){if(e.tagName=="TITLE"){if(i.tagName!="TITLE")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(let e of this.currentHeadProvisionalElements)document.head.removeChild(e)}copyNewHeadProvisionalElements(){for(let e of this.newHeadProvisionalElements)document.head.appendChild(e)}activateNewBody(){document.adoptNode(this.newElement),this.removeNoscriptElements(),this.activateNewBodyScriptElements()}removeNoscriptElements(){for(let e of this.newElement.querySelectorAll("noscript"))e.remove()}activateNewBodyScriptElements(){for(let e of this.newBodyScriptElements){let t=oe(e);e.replaceWith(t)}}async assignNewBody(){await this.renderElement(this.currentElement,this.newElement)}get unusedDynamicStylesheetElements(){return this.oldHeadStylesheetElements.filter(e=>e.getAttribute("data-turbo-track")==="dynamic")}get oldHeadStylesheetElements(){return this.currentHeadSnapshot.getStylesheetElementsNotInSnapshot(this.newHeadSnapshot)}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")}},Me=class extends se{static renderElement(e,t){le(e,t,{callbacks:{beforeNodeMorphed:(s,i)=>Ms(s,i)&&!Rs(s)?(s.reload(),!1):!0}}),L("turbo:morph",{detail:{currentElement:e,newElement:t}})}async preservingPermanentElements(e){return await e()}get renderMethod(){return"morph"}get shouldAutofocus(){return!1}},at=class extends ye{constructor(e){super(e,fe)}get snapshots(){return this.entries}},ct=class extends Ee{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){let o=this.isPageRefresh(i)&&(i?.refresh?.method||this.snapshot.refreshMethod)==="morph"?Me:se,m=new o(this.snapshot,e,t,s);return m.shouldRender?i?.changeHistory():this.forceReloaded=!0,this.render(m)}renderError(e,t){t?.changeHistory();let s=new ot(this.snapshot,e,!1);return this.render(s)}clearSnapshotCache(){this.snapshotCache.clear()}async cacheSnapshot(e=this.snapshot){if(e.isCacheable){this.delegate.viewWillCacheSnapshot();let{lastRenderedLocation:t}=this;await us();let 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&&e.action==="replace"}shouldPreserveScrollPosition(e){return this.isPageRefresh(e)&&(e?.refresh?.scroll||this.snapshot.refreshScroll)==="preserve"}get snapshot(){return B.fromElement(this.element)}},lt=class{selector="a[data-turbo-preload]";constructor(e,t){this.delegate=e,this.snapshotCache=t}start(){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.#e):this.preloadOnLoadLinksForView(document.body)}stop(){document.removeEventListener("DOMContentLoaded",this.#e)}preloadOnLoadLinksForView(e){for(let t of e.querySelectorAll(this.selector))this.delegate.shouldPreloadLink(t)&&this.preloadURL(t)}async preloadURL(e){let t=new URL(e.href);if(this.snapshotCache.has(t))return;await new W(this,I.get,t,new URLSearchParams,e).perform()}prepareRequest(e){e.headers["X-Sec-Purpose"]="prefetch"}async requestSucceededWithResponse(e,t){try{let s=await t.responseHTML,i=B.fromHTMLString(s);this.snapshotCache.put(e.url,i)}catch{}}requestStarted(e){}requestErrored(e){}requestFinished(e){}requestPreventedHandlingResponse(e,t){}requestFailedWithResponse(e,t){}#e=()=>{this.preloadOnLoadLinksForView(document.body)}},ht=class{constructor(e){this.session=e}clear(){this.session.clearCache()}resetCacheControl(){this.#e("")}exemptPageFromCache(){this.#e("no-cache")}exemptPageFromPreview(){this.#e("no-preview")}#e(e){lr("turbo-cache-control",e)}},ut=class{navigator=new tt(this);history=new Qe(this);view=new ct(this,document.documentElement);adapter=new Ye(this);pageObserver=new st(this);cacheObserver=new Ze;linkPrefetchObserver=new et(this,document);linkClickObserver=new Ae(this,window);formSubmitObserver=new ae(this,document);scrollObserver=new rt(this);streamObserver=new nt(this);formLinkClickObserver=new Te(this,document.documentElement);frameRedirector=new Ge(this,document.documentElement);streamMessageRenderer=new it;cache=new ht(this);enabled=!0;started=!1;#e=150;constructor(e){this.recentRequests=e,this.preloader=new lt(this,this.view.snapshotCache),this.debouncedRefresh=this.refresh,this.pageRefreshDebouncePeriod=this.pageRefreshDebouncePeriod}start(){this.started||(this.pageObserver.start(),this.cacheObserver.start(),this.linkPrefetchObserver.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.linkPrefetchObserver.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={}){let s=t.frame?document.getElementById(t.frame):null;if(s instanceof P){let i=t.action||X(s);s.delegate.proposeVisitIfNavigatedWithAction(s,i),s.src=e.toString()}else this.navigator.proposeVisit(F(e),t)}refresh(e,t={}){t=typeof t=="string"?{requestId:t}:t;let{method:s,requestId:i,scroll:n}=t,o=i&&this.recentRequests.has(i),m=e===document.baseURI;!o&&!this.navigator.currentVisit&&m&&this.visit(e,{action:"replace",shouldCacheSnapshot:!1,refresh:{method:s,scroll:n}})}connectStreamSource(e){this.streamObserver.connectStreamSource(e)}disconnectStreamSource(e){this.streamObserver.disconnectStreamSource(e)}renderStreamMessage(e){this.streamMessageRenderer.render(j.wrap(e))}clearCache(){this.view.clearSnapshotCache()}setProgressBarDelay(e){console.warn("Please replace `session.setProgressBarDelay(delay)` with `session.progressBarDelay = delay`. The function is deprecated and will be removed in a future version of Turbo.`"),this.progressBarDelay=e}set progressBarDelay(e){R.drive.progressBarDelay=e}get progressBarDelay(){return R.drive.progressBarDelay}set drive(e){R.drive.enabled=e}get drive(){return R.drive.enabled}set formMode(e){R.forms.mode=e}get formMode(){return R.forms.mode}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}get pageRefreshDebouncePeriod(){return this.#e}set pageRefreshDebouncePeriod(e){this.refresh=ur(this.debouncedRefresh.bind(this),e),this.#e=e}shouldPreloadLink(e){let t=e.hasAttribute("data-turbo-method"),s=e.hasAttribute("data-turbo-stream"),i=e.getAttribute("data-turbo-frame"),n=i=="_top"?null:document.getElementById(i)||Z(e,"turbo-frame:not([disabled])");if(t||s||n instanceof P)return!1;{let o=new URL(e.href);return this.elementIsNavigatable(e)&&$(o,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"})}historyPoppedWithEmptyState(e){this.history.replace(e),this.view.lastRenderedLocation=e,this.view.cacheSnapshot()}scrollPositionChanged(e){this.history.updateRestorationData({scrollPosition:e})}willSubmitFormLinkToLocation(e,t){return this.elementIsNavigatable(e)&&$(t,this.snapshot.rootLocation)}submittedFormLinkToLocation(){}canPrefetchRequestToLocation(e,t){return this.elementIsNavigatable(e)&&$(t,this.snapshot.rootLocation)&&this.navigator.linkPrefetchingIsEnabledForLocation(t)}willFollowLinkToLocation(e,t,s){return this.elementIsNavigatable(e)&&$(t,this.snapshot.rootLocation)&&this.applicationAllowsFollowingLinkToLocation(e,t,s)}followedLinkToLocation(e,t){let s=this.getActionForLink(e),i=e.hasAttribute("data-turbo-stream");this.visit(t.href,{action:s,acceptsStreamResponse:i})}allowsVisitingLocationWithAction(e,t){return this.applicationAllowsVisitingLocation(e)}visitProposedToLocation(e,t){cs(e),this.adapter.visitProposedToLocation(e,t)}visitStarted(e){e.acceptsStreamResponse||(ge(document.documentElement),this.view.markVisitDirection(e.direction)),cs(e.location),this.notifyApplicationAfterVisitingLocation(e.location,e.action)}visitCompleted(e){this.view.unmarkVisitDirection(),be(document.documentElement),this.notifyApplicationAfterPageLoad(e.getTimingMetrics())}willSubmitForm(e,t){let s=gt(e,t);return this.submissionIsNavigatable(e,t)&&$(F(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.notifyApplicationBeforeCachingSnapshot()}allowsImmediateRender({element:e},t){let s=this.notifyApplicationBeforeRender(e,t),{defaultPrevented:i,detail:{render:n}}=s;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!i}viewRenderedSnapshot(e,t,s){this.view.lastRenderedLocation=this.history.location,this.notifyApplicationAfterRender(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 L("turbo:click",{target:e,detail:{url:t.href,originalEvent:s},cancelable:!0})}notifyApplicationBeforeVisitingLocation(e){return L("turbo:before-visit",{detail:{url:e.href},cancelable:!0})}notifyApplicationAfterVisitingLocation(e,t){return L("turbo:visit",{detail:{url:e.href,action:t}})}notifyApplicationBeforeCachingSnapshot(){return L("turbo:before-cache")}notifyApplicationBeforeRender(e,t){return L("turbo:before-render",{detail:{newBody:e,...t},cancelable:!0})}notifyApplicationAfterRender(e){return L("turbo:render",{detail:{renderMethod:e}})}notifyApplicationAfterPageLoad(e={}){return L("turbo:load",{detail:{url:this.location.href,timing:e}})}notifyApplicationAfterFrameLoad(e){return L("turbo:frame-load",{target:e})}notifyApplicationAfterFrameRender(e,t){return L("turbo:frame-render",{detail:{fetchResponse:e},target:t,cancelable:!0})}submissionIsNavigatable(e,t){if(R.forms.mode=="off")return!1;{let s=t?this.elementIsNavigatable(t):!0;return R.forms.mode=="optin"?s&&e.closest('[data-turbo="true"]')!=null:s&&this.elementIsNavigatable(e)}}elementIsNavigatable(e){let t=Z(e,"[data-turbo]"),s=Z(e,"turbo-frame");return R.drive.enabled||s?t?t.getAttribute("data-turbo")!="false":!0:t?t.getAttribute("data-turbo")=="true":!1}getActionForLink(e){return X(e)||"advance"}get snapshot(){return this.view.snapshot}};function cs(r){Object.defineProperties(r,ii)}var ii={absoluteURL:{get(){return this.toString()}}},M=new ut(Es),{cache:ks,navigator:Os}=M;function vt(){M.start()}function Fs(r){M.registerAdapter(r)}function Is(r,e){M.visit(r,e)}function yt(r){M.connectStreamSource(r)}function wt(r){M.disconnectStreamSource(r)}function Ps(r){M.renderStreamMessage(r)}function Bs(r){console.warn("Please replace `Turbo.setProgressBarDelay(delay)` with `Turbo.config.drive.progressBarDelay = delay`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),R.drive.progressBarDelay=r}function Ns(r){console.warn("Please replace `Turbo.setConfirmMethod(confirmMethod)` with `Turbo.config.forms.confirm = confirmMethod`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),R.forms.confirm=r}function qs(r){console.warn("Please replace `Turbo.setFormMode(mode)` with `Turbo.config.forms.mode = mode`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),R.forms.mode=r}function Ds(r,e){Me.renderElement(r,e)}function xs(r,e){Ce.renderElement(r,e)}var ni=Object.freeze({__proto__:null,PageRenderer:se,PageSnapshot:B,FrameRenderer:te,fetch:bt,config:R,session:M,cache:ks,navigator:Os,start:vt,registerAdapter:Fs,visit:Is,connectStreamSource:yt,disconnectStreamSource:wt,renderStreamMessage:Ps,setProgressBarDelay:Bs,setConfirmMethod:Ns,setFormMode:qs,morphBodyElements:Ds,morphTurboFrameElements:xs,morphChildren:Ie,morphElements:le}),dt=class extends Error{},mt=class{fetchResponseLoaded=e=>Promise.resolve();#e=null;#t=()=>{};#s=!1;#o=!1;#a=new Set;#i=!1;action=null;constructor(e){this.element=e,this.view=new We(this,this.element),this.appearanceObserver=new _e(this,this.element),this.formLinkClickObserver=new Te(this,this.element),this.linkInterceptor=new Se(this,this.element),this.restorationIdentifier=U(),this.formSubmitObserver=new ae(this,this.element)}connect(){this.#s||(this.#s=!0,this.loadingStyle==z.lazy?this.appearanceObserver.start():this.#r(),this.formLinkClickObserver.start(),this.linkInterceptor.start(),this.formSubmitObserver.start())}disconnect(){this.#s&&(this.#s=!1,this.appearanceObserver.stop(),this.formLinkClickObserver.stop(),this.linkInterceptor.stop(),this.formSubmitObserver.stop(),this.element.hasAttribute("recurse")||this.#e?.cancel())}disabledChanged(){this.disabled?this.#e?.cancel():this.loadingStyle==z.eager&&this.#r()}sourceURLChanged(){this.#y("src")||(this.sourceURL||this.#e?.cancel(),this.element.isConnected&&(this.complete=!1),(this.loadingStyle==z.eager||this.#o)&&this.#r())}sourceURLReloaded(){let{refresh:e,src:t}=this.element;return this.#i=t&&e==="morph",this.element.removeAttribute("complete"),this.element.src=null,this.element.src=t,this.element.loaded}loadingStyleChanged(){this.loadingStyle==z.lazy?this.appearanceObserver.start():(this.appearanceObserver.stop(),this.#r())}async#r(){this.enabled&&this.isActive&&!this.complete&&this.sourceURL&&(this.element.loaded=this.#d(F(this.sourceURL)),this.appearanceObserver.stop(),await this.element.loaded,this.#o=!0)}async loadResponse(e){(e.redirected||e.succeeded&&e.isHTML)&&(this.sourceURL=e.response.url);try{let t=await e.responseHTML;if(t){let s=ds(t);B.fromDocument(s).isVisitable?await this.#c(e,s):await this.#f(e)}}finally{this.#i=!1,this.fetchResponseLoaded=()=>Promise.resolve()}}elementAppearedInViewport(e){this.proposeVisitIfNavigatedWithAction(e,X(e)),this.#r()}willSubmitFormLinkToLocation(e){return this.#l(e)}submittedFormLinkToLocation(e,t,s){let i=this.#n(e);i&&s.setAttribute("data-turbo-frame",i.id)}shouldInterceptLinkClick(e,t,s){return this.#l(e)}linkClickIntercepted(e,t){this.#m(e,t)}willSubmitForm(e,t){return e.closest("turbo-frame")==this.element&&this.#l(e,t)}formSubmitted(e,t){this.formSubmission&&this.formSubmission.stop(),this.formSubmission=new we(this,e,t);let{fetchRequest:s}=this.formSubmission,i=this.#n(e,t);this.prepareRequest(s,i),this.formSubmission.start()}prepareRequest(e,t=this){e.headers["Turbo-Frame"]=t.id,this.currentNavigationElement?.hasAttribute("data-turbo-stream")&&e.acceptResponseType(j.contentType)}requestStarted(e){ge(this.element)}requestPreventedHandlingResponse(e,t){this.#t()}async requestSucceededWithResponse(e,t){await this.loadResponse(t),this.#t()}async requestFailedWithResponse(e,t){await this.loadResponse(t),this.#t()}requestErrored(e,t){console.error(t),this.#t()}requestFinished(e){be(this.element)}formSubmissionStarted({formElement:e}){ge(e,this.#n(e))}formSubmissionSucceededWithResponse(e,t){let s=this.#n(e.formElement,e.submitter);s.delegate.proposeVisitIfNavigatedWithAction(s,X(e.submitter,e.formElement,s)),s.delegate.loadResponse(t),e.isSafe||M.clearCache()}formSubmissionFailedWithResponse(e,t){this.element.delegate.loadResponse(t),M.clearCache()}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished({formElement:e}){be(e,this.#n(e))}allowsImmediateRender({element:e},t){let s=L("turbo:before-frame-render",{target:this.element,detail:{newFrame:e,...t},cancelable:!0}),{defaultPrevented:i,detail:{render:n}}=s;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!i}viewRenderedSnapshot(e,t,s){}preloadOnLoadLinksForView(e){M.preloadOnLoadLinksForView(e)}viewInvalidated(){}willRenderFrame(e,t){this.previousFrameElement=e.cloneNode(!0)}visitCachedSnapshot=({element:e})=>{let t=e.querySelector("#"+this.element.id);t&&this.previousFrameElement&&t.replaceChildren(...this.previousFrameElement.children),delete this.previousFrameElement};async#c(e,t){let s=await this.extractForeignFrameElement(t.body),i=this.#i?Ce:te;if(s){let n=new ee(s),o=new i(this,this.view.snapshot,n,!1,!1);this.view.renderPromise&&await this.view.renderPromise,this.changeHistory(),await this.view.render(o),this.complete=!0,M.frameRendered(e,this.element),M.frameLoaded(this.element),await this.fetchResponseLoaded(e)}else this.#p(e)&&this.#g(e)}async#d(e){let t=new W(this,I.get,e,new URLSearchParams,this.element);return this.#e?.cancel(),this.#e=t,new Promise(s=>{this.#t=()=>{this.#t=()=>{},this.#e=null,s()},t.perform()})}#m(e,t,s){let i=this.#n(e,s);i.delegate.proposeVisitIfNavigatedWithAction(i,X(s,e,i)),this.#E(e,()=>{i.src=t})}proposeVisitIfNavigatedWithAction(e,t=null){if(this.action=t,this.action){let s=B.fromElement(e).clone(),{visitCachedSnapshot:i}=e.delegate;e.delegate.fetchResponseLoaded=async n=>{if(e.src){let{statusCode:o,redirected:m}=n,w=await n.responseHTML,k={response:{statusCode:o,redirected:m,responseHTML:w},visitCachedSnapshot:i,willRender:!1,updateHistory:!1,restorationIdentifier:this.restorationIdentifier,snapshot:s};this.action&&(k.action=this.action),M.visit(e.src,k)}}}}changeHistory(){if(this.action){let e=fs(this.action);M.history.update(e,F(this.element.src||""),this.restorationIdentifier)}}async#f(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.#h(e.response)}#p(e){this.element.setAttribute("complete","");let t=e.response,s=async(n,o)=>{n instanceof Response?this.#h(n):M.visit(n,o)};return!L("turbo:frame-missing",{target:this.element,detail:{response:t,visit:s},cancelable:!0}).defaultPrevented}#g(e){this.view.missing(),this.#b(e)}#b(e){let 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 dt(t)}async#h(e){let t=new Q(e),s=await t.responseHTML,{location:i,redirected:n,statusCode:o}=t;return M.visit(i,{response:{redirected:n,statusCode:o,responseHTML:s}})}#n(e,t){let s=pe("data-turbo-frame",t,e)||this.element.getAttribute("target"),i=this.#u(s);return i instanceof P?i:this.element}async extractForeignFrameElement(e){let t,s=CSS.escape(this.id);try{if(t=ls(e.querySelector(`turbo-frame#${s}`),this.sourceURL),t)return t;if(t=ls(e.querySelector(`turbo-frame[src][recurse~=${s}]`),this.sourceURL),t)return await t.loaded,await this.extractForeignFrameElement(t)}catch(i){return console.error(i),new P}return null}#v(e,t){let s=gt(e,t);return $(F(s),this.rootLocation)}#l(e,t){let s=pe("data-turbo-frame",t,e)||this.element.getAttribute("target");if(e instanceof HTMLFormElement&&!this.#v(e,t)||!this.enabled||s=="_top")return!1;if(s){let i=this.#u(s);if(i)return!i.disabled;if(s=="_parent")return!1}return!(!M.elementIsNavigatable(e)||t&&!M.elementIsNavigatable(t))}get id(){return this.element.id}get disabled(){return this.element.disabled}get enabled(){return!this.disabled}get sourceURL(){if(this.element.src)return this.element.src}set sourceURL(e){this.#w("src",()=>{this.element.src=e??null})}get loadingStyle(){return this.element.loading}get isLoading(){return this.formSubmission!==void 0||this.#t()!==void 0}get complete(){return this.element.hasAttribute("complete")}set complete(e){e?this.element.setAttribute("complete",""):this.element.removeAttribute("complete")}get isActive(){return this.element.isActive&&this.#s}get rootLocation(){let t=this.element.ownerDocument.querySelector('meta[name="turbo-root"]')?.content??"/";return F(t)}#y(e){return this.#a.has(e)}#w(e,t){this.#a.add(e),t(),this.#a.delete(e)}#E(e,t){this.currentNavigationElement=e,t(),delete this.currentNavigationElement}#u(e){if(e!=null){let t=e==="_parent"?this.element.parentElement.closest("turbo-frame"):document.getElementById(e);if(t instanceof P)return t}}};function ls(r,e){if(r){let t=r.getAttribute("src");if(t!=null&&e!=null&&ws(t,e))throw new Error(`Matching <turbo-frame id="${r.id}"> element has a source URL which references itself`);if(r.ownerDocument!==document&&(r=document.importNode(r,!0)),r instanceof P)return r.connectedCallback(),r.disconnectedCallback(),r}}var Et={after(){this.removeDuplicateTargetSiblings(),this.targetElements.forEach(r=>r.parentElement?.insertBefore(this.templateContent,r.nextSibling))},append(){this.removeDuplicateTargetChildren(),this.targetElements.forEach(r=>r.append(this.templateContent))},before(){this.removeDuplicateTargetSiblings(),this.targetElements.forEach(r=>r.parentElement?.insertBefore(this.templateContent,r))},prepend(){this.removeDuplicateTargetChildren(),this.targetElements.forEach(r=>r.prepend(this.templateContent))},remove(){this.targetElements.forEach(r=>r.remove())},replace(){let r=this.getAttribute("method");this.targetElements.forEach(e=>{r==="morph"?le(e,this.templateContent):e.replaceWith(this.templateContent)})},update(){let r=this.getAttribute("method");this.targetElements.forEach(e=>{r==="morph"?Ie(e,this.templateContent):(e.innerHTML="",e.append(this.templateContent))})},refresh(){let r=this.getAttribute("method"),e=this.requestId,t=this.getAttribute("scroll");M.refresh(this.baseURI,{method:r,requestId:e,scroll:t})}},Re=class r 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()=>{let e=this.beforeRenderEvent;this.dispatchEvent(e)&&(await ie(),await e.detail.render(this))})()}disconnect(){try{this.remove()}catch{}}removeDuplicateTargetChildren(){this.duplicateChildren.forEach(e=>e.remove())}get duplicateChildren(){let e=this.targetElements.flatMap(s=>[...s.children]).filter(s=>!!s.getAttribute("id")),t=[...this.templateContent?.children||[]].filter(s=>!!s.getAttribute("id")).map(s=>s.getAttribute("id"));return e.filter(s=>t.includes(s.getAttribute("id")))}removeDuplicateTargetSiblings(){this.duplicateSiblings.forEach(e=>e.remove())}get duplicateSiblings(){let e=this.targetElements.flatMap(s=>[...s.parentElement.children]).filter(s=>!!s.id),t=[...this.templateContent?.children||[]].filter(s=>!!s.id).map(s=>s.id);return e.filter(s=>t.includes(s.id))}get performAction(){if(this.action){let e=Et[this.action];if(e)return e;this.#e("unknown action")}this.#e("action attribute is missing")}get targetElements(){if(this.target)return this.targetElementsById;if(this.targets)return this.targetElementsByQuery;this.#e("target or targets attribute is missing")}get templateContent(){return this.templateElement.content.cloneNode(!0)}get templateElement(){if(this.firstElementChild===null){let e=this.ownerDocument.createElement("template");return this.appendChild(e),e}else if(this.firstElementChild instanceof HTMLTemplateElement)return this.firstElementChild;this.#e("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")}#e(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:r.renderElement}})}get targetElementsById(){let e=this.ownerDocument?.getElementById(this.target);return e!==null?[e]:[]}get targetElementsByQuery(){let e=this.ownerDocument?.querySelectorAll(this.targets);return e.length!==0?Array.prototype.slice.call(e):[]}},ke=class extends HTMLElement{streamSource=null;connectedCallback(){this.streamSource=this.src.match(/^ws{1,2}:/)?new WebSocket(this.src):new EventSource(this.src),yt(this.streamSource)}disconnectedCallback(){this.streamSource&&(this.streamSource.close(),wt(this.streamSource))}get src(){return this.getAttribute("src")||""}};P.delegateConstructor=mt;customElements.get("turbo-frame")===void 0&&customElements.define("turbo-frame",P);customElements.get("turbo-stream")===void 0&&customElements.define("turbo-stream",Re);customElements.get("turbo-stream-source")===void 0&&customElements.define("turbo-stream-source",ke);(()=>{let r=document.currentScript;if(!r||r.hasAttribute("data-turbo-suppress-warning"))return;let e=r.parentElement;for(;e;){if(e==document.body)return console.warn(ms`
|
|
20
|
+
`}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,r.animationDuration*1.5)}uninstallProgressElement(){this.progressElement.parentNode&&document.documentElement.removeChild(this.progressElement)}startTrickling(){this.trickleInterval||(this.trickleInterval=window.setInterval(this.trickle,r.animationDuration))}stopTrickling(){window.clearInterval(this.trickleInterval),delete this.trickleInterval}trickle=()=>{this.setValue(this.value+Math.random()/100)};refresh(){requestAnimationFrame(()=>{this.progressElement.style.width=`${10+this.value*90}%`})}createStylesheetElement(){let e=document.createElement("style");e.type="text/css",e.textContent=r.defaultCSS;let t=ps();return t&&(e.nonce=t),e}createProgressElement(){let e=document.createElement("div");return e.className="turbo-progress-bar",e}},ze=class extends ee{detailsByOuterHTML=this.children.filter(e=>!Hr(e)).map(e=>Ur(e)).reduce((e,t)=>{let{outerHTML:s}=t,i=s in e?e[s]:{type:Dr(t),tracked:xr(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(s=>!(s in t.detailsByOuterHTML)).map(s=>this.detailsByOuterHTML[s]).filter(({type:s})=>s==e).map(({elements:[s]})=>s)}get provisionalElements(){return Object.keys(this.detailsByOuterHTML).reduce((e,t)=>{let{type:s,tracked:i,elements:n}=this.detailsByOuterHTML[t];return s==null&&!i?[...e,...n]:n.length>1?[...e,...n.slice(1)]:e},[])}getMetaValue(e){let t=this.findMetaElementByName(e);return t?t.getAttribute("content"):null}findMetaElementByName(e){return Object.keys(this.detailsByOuterHTML).reduce((t,s)=>{let{elements:[i]}=this.detailsByOuterHTML[s];return _r(i,e)?i:t},void 0|void 0)}};function Dr(r){if(Vr(r))return"script";if($r(r))return"stylesheet"}function xr(r){return r.getAttribute("data-turbo-track")=="reload"}function Vr(r){return r.localName=="script"}function Hr(r){return r.localName=="noscript"}function $r(r){let e=r.localName;return e=="style"||e=="link"&&r.getAttribute("rel")=="stylesheet"}function _r(r,e){return r.localName=="meta"&&r.getAttribute("name")==e}function Ur(r){return r.hasAttribute("nonce")&&r.setAttribute("nonce",""),r}var B=class r extends ee{static fromHTMLString(e=""){return this.fromDocument(ds(e))}static fromElement(e){return this.fromDocument(e.ownerDocument)}static fromDocument({documentElement:e,body:t,head:s}){return new this(e,t,new ze(s))}constructor(e,t,s){super(t),this.documentElement=e,this.headSnapshot=s}clone(){let e=this.element.cloneNode(!0),t=this.element.querySelectorAll("select"),s=e.querySelectorAll("select");for(let[i,n]of t.entries()){let o=s[i];for(let m of o.selectedOptions)m.selected=!1;for(let m of n.selectedOptions)o.options[m.index].selected=!0}for(let i of e.querySelectorAll('input[type="password"]'))i.value="";for(let i of e.querySelectorAll("noscript"))i.remove();return new r(this.documentElement,e,this.headSnapshot)}get lang(){return this.documentElement.getAttribute("lang")}get dir(){return this.documentElement.getAttribute("dir")}get headElement(){return this.headSnapshot.element}get rootLocation(){let e=this.getSetting("root")??"/";return F(e)}get cacheControlValue(){return this.getSetting("cache-control")}get isPreviewable(){return this.cacheControlValue!="no-preview"}get isCacheable(){return this.cacheControlValue!="no-cache"}get isVisitable(){return this.getSetting("visit-control")!="reload"}get prefersViewTransitions(){return(this.getSetting("view-transition")==="true"||this.headSnapshot.getMetaValue("view-transition")==="same-origin")&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches}get refreshMethod(){return this.getSetting("refresh-method")}get refreshScroll(){return this.getSetting("refresh-scroll")}getSetting(e){return this.headSnapshot.getMetaValue(`turbo-${e}`)}},Xe=class{#e=!1;#t=Promise.resolve();renderChange(e,t){return e&&this.viewTransitionsAvailable&&!this.#e?(this.#e=!0,this.#t=this.#t.then(async()=>{await document.startViewTransition(t).finished})):this.#t=this.#t.then(t),this.#t}get viewTransitionsAvailable(){return document.startViewTransition}},Wr={action:"advance",historyChanged:!1,visitCachedSnapshot:()=>{},willRender:!0,updateHistory:!0,shouldCacheSnapshot:!0,acceptsStreamResponse:!1,refresh:{}},me={visitStart:"visitStart",requestStart:"requestStart",requestEnd:"requestEnd",visitEnd:"visitEnd"},V={initialized:"initialized",started:"started",canceled:"canceled",failed:"failed",completed:"completed"},G={networkFailure:0,timeoutFailure:-1,contentTypeMismatch:-2},jr={advance:"forward",restore:"back",replace:"none"},Je=class{identifier=U();timingMetrics={};followedRedirect=!1;historyChanged=!1;scrolled=!1;shouldCacheSnapshot=!0;acceptsStreamResponse=!1;snapshotCached=!1;state=V.initialized;viewTransitioner=new Xe;constructor(e,t,s,i={}){this.delegate=e,this.location=t,this.restorationIdentifier=s||U();let{action:n,historyChanged:o,referrer:m,snapshot:w,snapshotHTML:C,response:k,visitCachedSnapshot:q,willRender:d,updateHistory:A,shouldCacheSnapshot:y,acceptsStreamResponse:E,direction:S,refresh:g}={...Wr,...i};this.action=n,this.historyChanged=o,this.referrer=m,this.snapshot=w,this.snapshotHTML=C,this.response=k,this.isPageRefresh=this.view.isPageRefresh(this),this.visitCachedSnapshot=q,this.willRender=d,this.updateHistory=A,this.scrolled=!d,this.shouldCacheSnapshot=y,this.acceptsStreamResponse=E,this.direction=S||jr[n],this.refresh=g}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)}start(){this.state==V.initialized&&(this.recordTimingMetric(me.visitStart),this.state=V.started,this.adapter.visitStarted(this),this.delegate.visitStarted(this))}cancel(){this.state==V.started&&(this.request&&this.request.cancel(),this.cancelRender(),this.state=V.canceled)}complete(){this.state==V.started&&(this.recordTimingMetric(me.visitEnd),this.adapter.visitCompleted(this),this.state=V.completed,this.followRedirect(),this.followedRedirect||this.delegate.visitCompleted(this))}fail(){this.state==V.started&&(this.state=V.failed,this.adapter.visitFailed(this),this.delegate.visitCompleted(this))}changeHistory(){if(!this.historyChanged&&this.updateHistory){let e=this.location.href===this.referrer?.href?"replace":this.action,t=fs(e);this.history.update(t,this.location,this.restorationIdentifier),this.historyChanged=!0}}issueRequest(){this.hasPreloadedResponse()?this.simulateRequest():this.shouldIssueRequest()&&!this.request&&(this.request=new W(this,I.get,this.location),this.request.perform())}simulateRequest(){this.response&&(this.startRequest(),this.recordResponse(),this.finishRequest())}startRequest(){this.recordTimingMetric(me.requestStart),this.adapter.visitRequestStarted(this)}recordResponse(e=this.response){if(this.response=e,e){let{statusCode:t}=e;as(t)?this.adapter.visitRequestCompleted(this):this.adapter.visitRequestFailedWithStatusCode(this,t)}}finishRequest(){this.recordTimingMetric(me.requestEnd),this.adapter.visitRequestFinished(this)}loadResponse(){if(this.response){let{statusCode:e,responseHTML:t}=this.response;this.render(async()=>{if(this.shouldCacheSnapshot&&this.cacheSnapshot(),this.view.renderPromise&&await this.view.renderPromise,as(e)&&t!=null){let s=B.fromHTMLString(t);await this.renderPageSnapshot(s,!1),this.adapter.visitRendered(this),this.complete()}else await this.view.renderError(B.fromHTMLString(t),this),this.adapter.visitRendered(this),this.fail()})}}getCachedSnapshot(){let e=this.view.getCachedSnapshotForLocation(this.location)||this.getPreloadedSnapshot();if(e&&(!ne(this.location)||e.hasAnchor(ne(this.location)))&&(this.action=="restore"||e.isPreviewable))return e}getPreloadedSnapshot(){if(this.snapshotHTML)return B.fromHTMLString(this.snapshotHTML)}hasCachedSnapshot(){return this.getCachedSnapshot()!=null}loadCachedSnapshot(){let e=this.getCachedSnapshot();if(e){let t=this.shouldIssueRequest();this.render(async()=>{this.cacheSnapshot(),this.isPageRefresh?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)}prepareRequest(e){this.acceptsStreamResponse&&e.acceptResponseType(j.contentType)}requestStarted(){this.startRequest()}requestPreventedHandlingResponse(e,t){}async requestSucceededWithResponse(e,t){let s=await t.responseHTML,{redirected:i,statusCode:n}=t;s==null?this.recordResponse({statusCode:G.contentTypeMismatch,redirected:i}):(this.redirectedToLocation=t.redirected?t.location:void 0,this.recordResponse({statusCode:n,responseHTML:s,redirected:i}))}async requestFailedWithResponse(e,t){let s=await t.responseHTML,{redirected:i,statusCode:n}=t;s==null?this.recordResponse({statusCode:G.contentTypeMismatch,redirected:i}):this.recordResponse({statusCode:n,responseHTML:s,redirected:i})}requestErrored(e,t){this.recordResponse({statusCode:G.networkFailure,redirected:!1})}requestFinished(){this.finishRequest()}performScroll(){!this.scrolled&&!this.view.forceReloaded&&!this.view.shouldPreserveScrollPosition(this)&&(this.action=="restore"?this.scrollToRestoredPosition()||this.scrollToAnchor()||this.view.scrollToTop():this.scrollToAnchor()||this.view.scrollToTop(),this.scrolled=!0)}scrollToRestoredPosition(){let{scrollPosition:e}=this.restorationData;if(e)return this.view.scrollToPosition(e),!0}scrollToAnchor(){let e=ne(this.location);if(e!=null)return this.view.scrollToAnchor(e),!0}recordTimingMetric(e){this.timingMetrics[e]=new Date().getTime()}getTimingMetrics(){return{...this.timingMetrics}}hasPreloadedResponse(){return typeof this.response=="object"}shouldIssueRequest(){return this.action=="restore"?!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(t=>{this.frame=document.visibilityState==="hidden"?setTimeout(()=>t(),0):requestAnimationFrame(()=>t())}),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 as(r){return r>=200&&r<300}var Ye=class{progressBar=new Ke;constructor(e){this.session=e}visitProposedToLocation(e,t){$(e,this.navigator.rootLocation)?this.navigator.startVisit(e,t?.restorationIdentifier||U(),t):window.location.href=e.toString()}visitStarted(e){this.location=e.location,this.redirectedToLocation=null,e.loadCachedSnapshot(),e.issueRequest()}visitRequestStarted(e){this.progressBar.setValue(0),e.hasCachedSnapshot()||e.action!="restore"?this.showVisitProgressBarAfterDelay():this.showProgressBar()}visitRequestCompleted(e){e.loadResponse(),e.response.redirected&&(this.redirectedToLocation=e.redirectedToLocation)}visitRequestFailedWithStatusCode(e,t){switch(t){case G.networkFailure:case G.timeoutFailure:case G.contentTypeMismatch: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){}linkPrefetchingIsEnabledForLocation(e){return!0}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(),this.visitProgressBarTimeout!=null&&(window.clearTimeout(this.visitProgressBarTimeout),delete this.visitProgressBarTimeout)}showFormProgressBarAfterDelay(){this.formProgressBarTimeout==null&&(this.formProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay))}hideFormProgressBar(){this.progressBar.hide(),this.formProgressBarTimeout!=null&&(window.clearTimeout(this.formProgressBarTimeout),delete this.formProgressBarTimeout)}showProgressBar=()=>{this.progressBar.show()};reload(e){L("turbo:reload",{detail:e}),window.location.href=(this.redirectedToLocation||this.location)?.toString()||window.location.href}get navigator(){return this.session.navigator}},Ze=class{selector="[data-turbo-temporary]";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(let t of this.temporaryElements)t.remove()};get temporaryElements(){return[...document.querySelectorAll(this.selector)]}},Ge=class{constructor(e,t){this.session=e,this.element=t,this.linkInterceptor=new Se(this,t),this.formSubmitObserver=new ae(this,t)}start(){this.linkInterceptor.start(),this.formSubmitObserver.start()}stop(){this.linkInterceptor.stop(),this.formSubmitObserver.stop()}shouldInterceptLinkClick(e,t,s){return this.#t(e)}linkClickIntercepted(e,t,s){let i=this.#s(e);i&&i.delegate.linkClickIntercepted(e,t,s)}willSubmitForm(e,t){return e.closest("turbo-frame")==null&&this.#e(e,t)&&this.#t(e,t)}formSubmitted(e,t){let s=this.#s(e,t);s&&s.delegate.formSubmitted(e,t)}#e(e,t){let s=gt(e,t),i=this.element.ownerDocument.querySelector('meta[name="turbo-root"]'),n=F(i?.content??"/");return this.#t(e,t)&&$(s,n)}#t(e,t){if(e instanceof HTMLFormElement?this.session.submissionIsNavigatable(e,t):this.session.elementIsNavigatable(e)){let i=this.#s(e,t);return i?i!=e.closest("turbo-frame"):!1}else return!1}#s(e,t){let s=t?.getAttribute("data-turbo-frame")||e.getAttribute("data-turbo-frame");if(s&&s!="_top"){let i=this.element.querySelector(`#${s}:not([disabled])`);if(i instanceof P)return i}}},Qe=class{location;restorationIdentifier=U();restorationData={};started=!1;currentIndex=0;constructor(e){this.delegate=e}start(){this.started||(addEventListener("popstate",this.onPopState,!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),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=U()){e===history.pushState&&++this.currentIndex;let 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){let{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=>{let{turbo:t}=e.state||{};if(this.location=new URL(window.location.href),t){let{restorationIdentifier:s,restorationIndex:i}=t;this.restorationIdentifier=s;let n=i>this.currentIndex?"forward":"back";this.delegate.historyPoppedToLocationWithRestorationIdentifierAndDirection(this.location,s,n),this.currentIndex=i}else this.currentIndex++,this.delegate.historyPoppedWithEmptyState(this.location)}},et=class{started=!1;#e=null;constructor(e,t){this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.readyState==="loading"?this.eventTarget.addEventListener("DOMContentLoaded",this.#t,{once:!0}):this.#t())}stop(){this.started&&(this.eventTarget.removeEventListener("mouseenter",this.#s,{capture:!0,passive:!0}),this.eventTarget.removeEventListener("mouseleave",this.#o,{capture:!0,passive:!0}),this.eventTarget.removeEventListener("turbo:before-fetch-request",this.#i,!0),this.started=!1)}#t=()=>{this.eventTarget.addEventListener("mouseenter",this.#s,{capture:!0,passive:!0}),this.eventTarget.addEventListener("mouseleave",this.#o,{capture:!0,passive:!0}),this.eventTarget.addEventListener("turbo:before-fetch-request",this.#i,!0),this.started=!0};#s=e=>{if(ve("turbo-prefetch")==="false")return;let t=e.target;if(t.matches&&t.matches("a[href]:not([target^=_]):not([download])")&&this.#c(t)){let i=t,n=ys(i);if(this.delegate.canPrefetchRequestToLocation(i,n)){this.#e=i;let o=new W(this,I.get,n,new URLSearchParams,t);o.fetchOptions.priority="low",Y.putLater(n,o,this.#r)}}};#o=e=>{e.target===this.#e&&this.#a()};#a=()=>{Y.clear(),this.#e=null};#i=e=>{if(e.target.tagName!=="FORM"&&e.detail.fetchOptions.method==="GET"){let t=Y.get(e.detail.url);t&&(e.detail.fetchRequest=t),Y.clear()}};prepareRequest(e){let t=e.target;e.headers["X-Sec-Purpose"]="prefetch";let s=t.closest("turbo-frame"),i=t.getAttribute("data-turbo-frame")||s?.getAttribute("target")||s?.id;i&&i!=="_top"&&(e.headers["Turbo-Frame"]=i)}requestSucceededWithResponse(){}requestStarted(e){}requestErrored(e){}requestFinished(e){}requestPreventedHandlingResponse(e,t){}requestFailedWithResponse(e,t){}get#r(){return Number(ve("turbo-prefetch-cache-time"))||Ts}#c(e){return!(!e.getAttribute("href")||Kr(e)||zr(e)||Xr(e)||Jr(e)||Zr(e))}},Kr=r=>r.origin!==document.location.origin||!["http:","https:"].includes(r.protocol)||r.hasAttribute("target"),zr=r=>r.pathname+r.search===document.location.pathname+document.location.search||r.href.startsWith("#"),Xr=r=>{if(r.getAttribute("data-turbo-prefetch")==="false"||r.getAttribute("data-turbo")==="false")return!0;let e=Z(r,"[data-turbo-prefetch]");return!!(e&&e.getAttribute("data-turbo-prefetch")==="false")},Jr=r=>{let e=r.getAttribute("data-turbo-method");return!!(e&&e.toLowerCase()!=="get"||Yr(r)||r.hasAttribute("data-turbo-confirm")||r.hasAttribute("data-turbo-stream"))},Yr=r=>r.hasAttribute("data-remote")||r.hasAttribute("data-behavior")||r.hasAttribute("data-confirm")||r.hasAttribute("data-method"),Zr=r=>L("turbo:before-prefetch",{target:r,cancelable:!0}).defaultPrevented,tt=class{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 Je(this,F(e),t,{referrer:this.location,...s}),this.currentVisit.start()}submitForm(e,t){this.stop(),this.formSubmission=new we(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){typeof this.adapter.formSubmissionStarted=="function"&&this.adapter.formSubmissionStarted(e)}async formSubmissionSucceededWithResponse(e,t){if(e==this.formSubmission){let s=await t.responseHTML;if(s){let i=e.isSafe;i||this.view.clearSnapshotCache();let{statusCode:n,redirected:o}=t,w={action:this.#e(e,t),shouldCacheSnapshot:i,response:{statusCode:n,responseHTML:s,redirected:o}};this.proposeVisit(t.location,w)}}}async formSubmissionFailedWithResponse(e,t){let s=await t.responseHTML;if(s){let i=B.fromHTMLString(s);t.serverError?await this.view.renderError(i,this.currentVisit):await this.view.renderPage(i,!1,!0,this.currentVisit),i.refreshScroll!=="preserve"&&this.view.scrollToTop(),this.view.clearSnapshotCache()}}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished(e){typeof this.adapter.formSubmissionFinished=="function"&&this.adapter.formSubmissionFinished(e)}linkPrefetchingIsEnabledForLocation(e){return typeof this.adapter.linkPrefetchingIsEnabledForLocation=="function"?this.adapter.linkPrefetchingIsEnabledForLocation(e):!0}visitStarted(e){this.delegate.visitStarted(e)}visitCompleted(e){this.delegate.visitCompleted(e),delete this.currentVisit}locationWithActionIsSamePage(e,t){return!1}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}#e(e,t){let{submitter:s,formElement:i}=e;return X(s,i)||this.#t(t)}#t(e){return e.redirected&&e.location.href===this.location?.href?"replace":"advance"}},K={initial:0,loading:1,interactive:2,complete:3},st=class{stage=K.initial;started=!1;constructor(e){this.delegate=e}start(){this.started||(this.stage==K.initial&&(this.stage=K.loading),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=()=>{let{readyState:e}=this;e=="interactive"?this.pageIsInteractive():e=="complete"&&this.pageIsComplete()};pageIsInteractive(){this.stage==K.loading&&(this.stage=K.interactive,this.delegate.pageBecameInteractive())}pageIsComplete(){this.pageIsInteractive(),this.stage==K.interactive&&(this.stage=K.complete,this.delegate.pageLoaded())}pageWillUnload=()=>{this.delegate.pageWillUnload()};get readyState(){return document.readyState}},rt=class{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)}},it=class{render({fragment:e}){Le.preservingPermanentElements(this,Gr(e),()=>{Qr(e,()=>{ei(()=>{document.documentElement.appendChild(e)})})})}enteringBardo(e,t){t.replaceWith(e.cloneNode(!0))}leavingBardo(){}};function Gr(r){let e=Cs(document.documentElement),t={};for(let s of e){let{id:i}=s;for(let n of r.querySelectorAll("turbo-stream")){let o=Ls(n.templateElement.content,i);o&&(t[i]=[s,o])}}return t}async function Qr(r,e){let t=`turbo-stream-autofocus-${U()}`,s=r.querySelectorAll("turbo-stream"),i=ti(s),n=null;if(i&&(i.id?n=i.id:n=t,i.id=n),e(),await ie(),(document.activeElement==null||document.activeElement==document.body)&&n){let m=document.getElementById(n);pt(m)&&m.focus(),m&&m.id==t&&m.removeAttribute("id")}}async function ei(r){let[e,t]=await hr(r,()=>document.activeElement),s=e&&e.id;if(s){let i=document.getElementById(s);pt(i)&&i!=t&&i.focus()}}function ti(r){for(let e of r){let t=gs(e.templateElement.content);if(t)return t}return null}var nt=class{sources=new Set;#e=!1;constructor(e){this.delegate=e}start(){this.#e||(this.#e=!0,addEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}stop(){this.#e&&(this.#e=!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=>{let t=si(e);t&&ri(t)&&(e.preventDefault(),this.receiveMessageResponse(t))};receiveMessageEvent=e=>{this.#e&&typeof e.data=="string"&&this.receiveMessageHTML(e.data)};async receiveMessageResponse(e){let t=await e.responseHTML;t&&this.receiveMessageHTML(t)}receiveMessageHTML(e){this.delegate.receivedMessageFromStream(j.wrap(e))}};function si(r){let e=r.detail?.fetchResponse;if(e instanceof Q)return e}function ri(r){return(r.contentType??"").startsWith(j.contentType)}var ot=class extends ce{static renderElement(e,t){let{documentElement:s,body:i}=document;s.replaceChild(t,i)}async render(){this.replaceHeadAndBody(),this.activateScriptElements()}replaceHeadAndBody(){let{documentElement:e,head:t}=document;e.replaceChild(this.newHead,t),this.renderElement(this.currentElement,this.newElement)}activateScriptElements(){for(let e of this.scriptElements){let t=e.parentNode;if(t){let s=oe(e);t.replaceChild(s,e)}}}get newHead(){return this.newSnapshot.headSnapshot.element}get scriptElements(){return document.documentElement.querySelectorAll("script")}},se=class extends ce{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(){if(!this.newSnapshot.isVisitable)return{reason:"turbo_visit_control_is_reload"};if(!this.trackedElementsAreIdentical)return{reason:"tracked_element_mismatch"}}async prepareToRender(){this.#e(),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}#e(){let{documentElement:e}=this.currentSnapshot,{dir:t,lang:s}=this.newSnapshot;s?e.setAttribute("lang",s):e.removeAttribute("lang"),t?e.setAttribute("dir",t):e.removeAttribute("dir")}async mergeHead(){let e=this.mergeProvisionalElements(),t=this.copyNewHeadStylesheetElements();this.copyNewHeadScriptElements(),await e,await t,this.willRender&&this.removeUnusedDynamicStylesheetElements()}async replaceBody(){await this.preservingPermanentElements(async()=>{this.activateNewBody(),await this.assignNewBody()})}get trackedElementsAreIdentical(){return this.currentHeadSnapshot.trackedElementSignature==this.newHeadSnapshot.trackedElementSignature}async copyNewHeadStylesheetElements(){let e=[];for(let t of this.newHeadStylesheetElements)e.push(ar(t)),document.head.appendChild(t);await Promise.all(e)}copyNewHeadScriptElements(){for(let e of this.newHeadScriptElements)document.head.appendChild(oe(e))}removeUnusedDynamicStylesheetElements(){for(let e of this.unusedDynamicStylesheetElements)document.head.removeChild(e)}async mergeProvisionalElements(){let e=[...this.newHeadProvisionalElements];for(let t of this.currentHeadProvisionalElements)this.isCurrentElementInElementList(t,e)||document.head.removeChild(t);for(let t of e)document.head.appendChild(t)}isCurrentElementInElementList(e,t){for(let[s,i]of t.entries()){if(e.tagName=="TITLE"){if(i.tagName!="TITLE")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(let e of this.currentHeadProvisionalElements)document.head.removeChild(e)}copyNewHeadProvisionalElements(){for(let e of this.newHeadProvisionalElements)document.head.appendChild(e)}activateNewBody(){document.adoptNode(this.newElement),this.removeNoscriptElements(),this.activateNewBodyScriptElements()}removeNoscriptElements(){for(let e of this.newElement.querySelectorAll("noscript"))e.remove()}activateNewBodyScriptElements(){for(let e of this.newBodyScriptElements){let t=oe(e);e.replaceWith(t)}}async assignNewBody(){await this.renderElement(this.currentElement,this.newElement)}get unusedDynamicStylesheetElements(){return this.oldHeadStylesheetElements.filter(e=>e.getAttribute("data-turbo-track")==="dynamic")}get oldHeadStylesheetElements(){return this.currentHeadSnapshot.getStylesheetElementsNotInSnapshot(this.newHeadSnapshot)}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")}},Me=class extends se{static renderElement(e,t){le(e,t,{callbacks:{beforeNodeMorphed:(s,i)=>Ms(s,i)&&!Rs(s)?(s.reload(),!1):!0}}),L("turbo:morph",{detail:{currentElement:e,newElement:t}})}async preservingPermanentElements(e){return await e()}get renderMethod(){return"morph"}get shouldAutofocus(){return!1}},at=class extends ye{constructor(e){super(e,fe)}get snapshots(){return this.entries}},ct=class extends Ee{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){let o=this.isPageRefresh(i)&&(i?.refresh?.method||this.snapshot.refreshMethod)==="morph"?Me:se,m=new o(this.snapshot,e,t,s);return m.shouldRender?i?.changeHistory():this.forceReloaded=!0,this.render(m)}renderError(e,t){t?.changeHistory();let s=new ot(this.snapshot,e,!1);return this.render(s)}clearSnapshotCache(){this.snapshotCache.clear()}async cacheSnapshot(e=this.snapshot){if(e.isCacheable){this.delegate.viewWillCacheSnapshot();let{lastRenderedLocation:t}=this;await us();let 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&&e.action==="replace"}shouldPreserveScrollPosition(e){return this.isPageRefresh(e)&&(e?.refresh?.scroll||this.snapshot.refreshScroll)==="preserve"}get snapshot(){return B.fromElement(this.element)}},lt=class{selector="a[data-turbo-preload]";constructor(e,t){this.delegate=e,this.snapshotCache=t}start(){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.#e):this.preloadOnLoadLinksForView(document.body)}stop(){document.removeEventListener("DOMContentLoaded",this.#e)}preloadOnLoadLinksForView(e){for(let t of e.querySelectorAll(this.selector))this.delegate.shouldPreloadLink(t)&&this.preloadURL(t)}async preloadURL(e){let t=new URL(e.href);if(this.snapshotCache.has(t))return;await new W(this,I.get,t,new URLSearchParams,e).perform()}prepareRequest(e){e.headers["X-Sec-Purpose"]="prefetch"}async requestSucceededWithResponse(e,t){try{let s=await t.responseHTML,i=B.fromHTMLString(s);this.snapshotCache.put(e.url,i)}catch{}}requestStarted(e){}requestErrored(e){}requestFinished(e){}requestPreventedHandlingResponse(e,t){}requestFailedWithResponse(e,t){}#e=()=>{this.preloadOnLoadLinksForView(document.body)}},ht=class{constructor(e){this.session=e}clear(){this.session.clearCache()}resetCacheControl(){this.#e("")}exemptPageFromCache(){this.#e("no-cache")}exemptPageFromPreview(){this.#e("no-preview")}#e(e){lr("turbo-cache-control",e)}},ut=class{navigator=new tt(this);history=new Qe(this);view=new ct(this,document.documentElement);adapter=new Ye(this);pageObserver=new st(this);cacheObserver=new Ze;linkPrefetchObserver=new et(this,document);linkClickObserver=new Ae(this,window);formSubmitObserver=new ae(this,document);scrollObserver=new rt(this);streamObserver=new nt(this);formLinkClickObserver=new Te(this,document.documentElement);frameRedirector=new Ge(this,document.documentElement);streamMessageRenderer=new it;cache=new ht(this);enabled=!0;started=!1;#e=150;constructor(e){this.recentRequests=e,this.preloader=new lt(this,this.view.snapshotCache),this.debouncedRefresh=this.refresh,this.pageRefreshDebouncePeriod=this.pageRefreshDebouncePeriod}start(){this.started||(this.pageObserver.start(),this.cacheObserver.start(),this.linkPrefetchObserver.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.linkPrefetchObserver.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={}){let s=t.frame?document.getElementById(t.frame):null;if(s instanceof P){let i=t.action||X(s);s.delegate.proposeVisitIfNavigatedWithAction(s,i),s.src=e.toString()}else this.navigator.proposeVisit(F(e),t)}refresh(e,t={}){t=typeof t=="string"?{requestId:t}:t;let{method:s,requestId:i,scroll:n}=t,o=i&&this.recentRequests.has(i),m=e===document.baseURI;!o&&!this.navigator.currentVisit&&m&&this.visit(e,{action:"replace",shouldCacheSnapshot:!1,refresh:{method:s,scroll:n}})}connectStreamSource(e){this.streamObserver.connectStreamSource(e)}disconnectStreamSource(e){this.streamObserver.disconnectStreamSource(e)}renderStreamMessage(e){this.streamMessageRenderer.render(j.wrap(e))}clearCache(){this.view.clearSnapshotCache()}setProgressBarDelay(e){console.warn("Please replace `session.setProgressBarDelay(delay)` with `session.progressBarDelay = delay`. The function is deprecated and will be removed in a future version of Turbo.`"),this.progressBarDelay=e}set progressBarDelay(e){R.drive.progressBarDelay=e}get progressBarDelay(){return R.drive.progressBarDelay}set drive(e){R.drive.enabled=e}get drive(){return R.drive.enabled}set formMode(e){R.forms.mode=e}get formMode(){return R.forms.mode}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}get pageRefreshDebouncePeriod(){return this.#e}set pageRefreshDebouncePeriod(e){this.refresh=ur(this.debouncedRefresh.bind(this),e),this.#e=e}shouldPreloadLink(e){let t=e.hasAttribute("data-turbo-method"),s=e.hasAttribute("data-turbo-stream"),i=e.getAttribute("data-turbo-frame"),n=i=="_top"?null:document.getElementById(i)||Z(e,"turbo-frame:not([disabled])");if(t||s||n instanceof P)return!1;{let o=new URL(e.href);return this.elementIsNavigatable(e)&&$(o,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"})}historyPoppedWithEmptyState(e){this.history.replace(e),this.view.lastRenderedLocation=e,this.view.cacheSnapshot()}scrollPositionChanged(e){this.history.updateRestorationData({scrollPosition:e})}willSubmitFormLinkToLocation(e,t){return this.elementIsNavigatable(e)&&$(t,this.snapshot.rootLocation)}submittedFormLinkToLocation(){}canPrefetchRequestToLocation(e,t){return this.elementIsNavigatable(e)&&$(t,this.snapshot.rootLocation)&&this.navigator.linkPrefetchingIsEnabledForLocation(t)}willFollowLinkToLocation(e,t,s){return this.elementIsNavigatable(e)&&$(t,this.snapshot.rootLocation)&&this.applicationAllowsFollowingLinkToLocation(e,t,s)}followedLinkToLocation(e,t){let s=this.getActionForLink(e),i=e.hasAttribute("data-turbo-stream");this.visit(t.href,{action:s,acceptsStreamResponse:i})}allowsVisitingLocationWithAction(e,t){return this.applicationAllowsVisitingLocation(e)}visitProposedToLocation(e,t){cs(e),this.adapter.visitProposedToLocation(e,t)}visitStarted(e){e.acceptsStreamResponse||(ge(document.documentElement),this.view.markVisitDirection(e.direction)),cs(e.location),this.notifyApplicationAfterVisitingLocation(e.location,e.action)}visitCompleted(e){this.view.unmarkVisitDirection(),be(document.documentElement),this.notifyApplicationAfterPageLoad(e.getTimingMetrics())}willSubmitForm(e,t){let s=gt(e,t);return this.submissionIsNavigatable(e,t)&&$(F(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.notifyApplicationBeforeCachingSnapshot()}allowsImmediateRender({element:e},t){let s=this.notifyApplicationBeforeRender(e,t),{defaultPrevented:i,detail:{render:n}}=s;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!i}viewRenderedSnapshot(e,t,s){this.view.lastRenderedLocation=this.history.location,this.notifyApplicationAfterRender(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 L("turbo:click",{target:e,detail:{url:t.href,originalEvent:s},cancelable:!0})}notifyApplicationBeforeVisitingLocation(e){return L("turbo:before-visit",{detail:{url:e.href},cancelable:!0})}notifyApplicationAfterVisitingLocation(e,t){return L("turbo:visit",{detail:{url:e.href,action:t}})}notifyApplicationBeforeCachingSnapshot(){return L("turbo:before-cache")}notifyApplicationBeforeRender(e,t){return L("turbo:before-render",{detail:{newBody:e,...t},cancelable:!0})}notifyApplicationAfterRender(e){return L("turbo:render",{detail:{renderMethod:e}})}notifyApplicationAfterPageLoad(e={}){return L("turbo:load",{detail:{url:this.location.href,timing:e}})}notifyApplicationAfterFrameLoad(e){return L("turbo:frame-load",{target:e})}notifyApplicationAfterFrameRender(e,t){return L("turbo:frame-render",{detail:{fetchResponse:e},target:t,cancelable:!0})}submissionIsNavigatable(e,t){if(R.forms.mode=="off")return!1;{let s=t?this.elementIsNavigatable(t):!0;return R.forms.mode=="optin"?s&&e.closest('[data-turbo="true"]')!=null:s&&this.elementIsNavigatable(e)}}elementIsNavigatable(e){let t=Z(e,"[data-turbo]"),s=Z(e,"turbo-frame");return R.drive.enabled||s?t?t.getAttribute("data-turbo")!="false":!0:t?t.getAttribute("data-turbo")=="true":!1}getActionForLink(e){return X(e)||"advance"}get snapshot(){return this.view.snapshot}};function cs(r){Object.defineProperties(r,ii)}var ii={absoluteURL:{get(){return this.toString()}}},M=new ut(Es),{cache:ks,navigator:Os}=M;function vt(){M.start()}function Fs(r){M.registerAdapter(r)}function Is(r,e){M.visit(r,e)}function yt(r){M.connectStreamSource(r)}function wt(r){M.disconnectStreamSource(r)}function Ps(r){M.renderStreamMessage(r)}function Bs(r){console.warn("Please replace `Turbo.setProgressBarDelay(delay)` with `Turbo.config.drive.progressBarDelay = delay`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),R.drive.progressBarDelay=r}function qs(r){console.warn("Please replace `Turbo.setConfirmMethod(confirmMethod)` with `Turbo.config.forms.confirm = confirmMethod`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),R.forms.confirm=r}function Ns(r){console.warn("Please replace `Turbo.setFormMode(mode)` with `Turbo.config.forms.mode = mode`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),R.forms.mode=r}function Ds(r,e){Me.renderElement(r,e)}function xs(r,e){Ce.renderElement(r,e)}var ni=Object.freeze({__proto__:null,PageRenderer:se,PageSnapshot:B,FrameRenderer:te,fetch:bt,config:R,session:M,cache:ks,navigator:Os,start:vt,registerAdapter:Fs,visit:Is,connectStreamSource:yt,disconnectStreamSource:wt,renderStreamMessage:Ps,setProgressBarDelay:Bs,setConfirmMethod:qs,setFormMode:Ns,morphBodyElements:Ds,morphTurboFrameElements:xs,morphChildren:Ie,morphElements:le}),dt=class extends Error{},mt=class{fetchResponseLoaded=e=>Promise.resolve();#e=null;#t=()=>{};#s=!1;#o=!1;#a=new Set;#i=!1;action=null;constructor(e){this.element=e,this.view=new We(this,this.element),this.appearanceObserver=new _e(this,this.element),this.formLinkClickObserver=new Te(this,this.element),this.linkInterceptor=new Se(this,this.element),this.restorationIdentifier=U(),this.formSubmitObserver=new ae(this,this.element)}connect(){this.#s||(this.#s=!0,this.loadingStyle==z.lazy?this.appearanceObserver.start():this.#r(),this.formLinkClickObserver.start(),this.linkInterceptor.start(),this.formSubmitObserver.start())}disconnect(){this.#s&&(this.#s=!1,this.appearanceObserver.stop(),this.formLinkClickObserver.stop(),this.linkInterceptor.stop(),this.formSubmitObserver.stop(),this.element.hasAttribute("recurse")||this.#e?.cancel())}disabledChanged(){this.disabled?this.#e?.cancel():this.loadingStyle==z.eager&&this.#r()}sourceURLChanged(){this.#y("src")||(this.sourceURL||this.#e?.cancel(),this.element.isConnected&&(this.complete=!1),(this.loadingStyle==z.eager||this.#o)&&this.#r())}sourceURLReloaded(){let{refresh:e,src:t}=this.element;return this.#i=t&&e==="morph",this.element.removeAttribute("complete"),this.element.src=null,this.element.src=t,this.element.loaded}loadingStyleChanged(){this.loadingStyle==z.lazy?this.appearanceObserver.start():(this.appearanceObserver.stop(),this.#r())}async#r(){this.enabled&&this.isActive&&!this.complete&&this.sourceURL&&(this.element.loaded=this.#d(F(this.sourceURL)),this.appearanceObserver.stop(),await this.element.loaded,this.#o=!0)}async loadResponse(e){(e.redirected||e.succeeded&&e.isHTML)&&(this.sourceURL=e.response.url);try{let t=await e.responseHTML;if(t){let s=ds(t);B.fromDocument(s).isVisitable?await this.#c(e,s):await this.#f(e)}}finally{this.#i=!1,this.fetchResponseLoaded=()=>Promise.resolve()}}elementAppearedInViewport(e){this.proposeVisitIfNavigatedWithAction(e,X(e)),this.#r()}willSubmitFormLinkToLocation(e){return this.#l(e)}submittedFormLinkToLocation(e,t,s){let i=this.#n(e);i&&s.setAttribute("data-turbo-frame",i.id)}shouldInterceptLinkClick(e,t,s){return this.#l(e)}linkClickIntercepted(e,t){this.#m(e,t)}willSubmitForm(e,t){return e.closest("turbo-frame")==this.element&&this.#l(e,t)}formSubmitted(e,t){this.formSubmission&&this.formSubmission.stop(),this.formSubmission=new we(this,e,t);let{fetchRequest:s}=this.formSubmission,i=this.#n(e,t);this.prepareRequest(s,i),this.formSubmission.start()}prepareRequest(e,t=this){e.headers["Turbo-Frame"]=t.id,this.currentNavigationElement?.hasAttribute("data-turbo-stream")&&e.acceptResponseType(j.contentType)}requestStarted(e){ge(this.element)}requestPreventedHandlingResponse(e,t){this.#t()}async requestSucceededWithResponse(e,t){await this.loadResponse(t),this.#t()}async requestFailedWithResponse(e,t){await this.loadResponse(t),this.#t()}requestErrored(e,t){console.error(t),this.#t()}requestFinished(e){be(this.element)}formSubmissionStarted({formElement:e}){ge(e,this.#n(e))}formSubmissionSucceededWithResponse(e,t){let s=this.#n(e.formElement,e.submitter);s.delegate.proposeVisitIfNavigatedWithAction(s,X(e.submitter,e.formElement,s)),s.delegate.loadResponse(t),e.isSafe||M.clearCache()}formSubmissionFailedWithResponse(e,t){this.element.delegate.loadResponse(t),M.clearCache()}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished({formElement:e}){be(e,this.#n(e))}allowsImmediateRender({element:e},t){let s=L("turbo:before-frame-render",{target:this.element,detail:{newFrame:e,...t},cancelable:!0}),{defaultPrevented:i,detail:{render:n}}=s;return this.view.renderer&&n&&(this.view.renderer.renderElement=n),!i}viewRenderedSnapshot(e,t,s){}preloadOnLoadLinksForView(e){M.preloadOnLoadLinksForView(e)}viewInvalidated(){}willRenderFrame(e,t){this.previousFrameElement=e.cloneNode(!0)}visitCachedSnapshot=({element:e})=>{let t=e.querySelector("#"+this.element.id);t&&this.previousFrameElement&&t.replaceChildren(...this.previousFrameElement.children),delete this.previousFrameElement};async#c(e,t){let s=await this.extractForeignFrameElement(t.body),i=this.#i?Ce:te;if(s){let n=new ee(s),o=new i(this,this.view.snapshot,n,!1,!1);this.view.renderPromise&&await this.view.renderPromise,this.changeHistory(),await this.view.render(o),this.complete=!0,M.frameRendered(e,this.element),M.frameLoaded(this.element),await this.fetchResponseLoaded(e)}else this.#p(e)&&this.#g(e)}async#d(e){let t=new W(this,I.get,e,new URLSearchParams,this.element);return this.#e?.cancel(),this.#e=t,new Promise(s=>{this.#t=()=>{this.#t=()=>{},this.#e=null,s()},t.perform()})}#m(e,t,s){let i=this.#n(e,s);i.delegate.proposeVisitIfNavigatedWithAction(i,X(s,e,i)),this.#E(e,()=>{i.src=t})}proposeVisitIfNavigatedWithAction(e,t=null){if(this.action=t,this.action){let s=B.fromElement(e).clone(),{visitCachedSnapshot:i}=e.delegate;e.delegate.fetchResponseLoaded=async n=>{if(e.src){let{statusCode:o,redirected:m}=n,w=await n.responseHTML,k={response:{statusCode:o,redirected:m,responseHTML:w},visitCachedSnapshot:i,willRender:!1,updateHistory:!1,restorationIdentifier:this.restorationIdentifier,snapshot:s};this.action&&(k.action=this.action),M.visit(e.src,k)}}}}changeHistory(){if(this.action){let e=fs(this.action);M.history.update(e,F(this.element.src||""),this.restorationIdentifier)}}async#f(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.#h(e.response)}#p(e){this.element.setAttribute("complete","");let t=e.response,s=async(n,o)=>{n instanceof Response?this.#h(n):M.visit(n,o)};return!L("turbo:frame-missing",{target:this.element,detail:{response:t,visit:s},cancelable:!0}).defaultPrevented}#g(e){this.view.missing(),this.#b(e)}#b(e){let 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 dt(t)}async#h(e){let t=new Q(e),s=await t.responseHTML,{location:i,redirected:n,statusCode:o}=t;return M.visit(i,{response:{redirected:n,statusCode:o,responseHTML:s}})}#n(e,t){let s=pe("data-turbo-frame",t,e)||this.element.getAttribute("target"),i=this.#u(s);return i instanceof P?i:this.element}async extractForeignFrameElement(e){let t,s=CSS.escape(this.id);try{if(t=ls(e.querySelector(`turbo-frame#${s}`),this.sourceURL),t)return t;if(t=ls(e.querySelector(`turbo-frame[src][recurse~=${s}]`),this.sourceURL),t)return await t.loaded,await this.extractForeignFrameElement(t)}catch(i){return console.error(i),new P}return null}#v(e,t){let s=gt(e,t);return $(F(s),this.rootLocation)}#l(e,t){let s=pe("data-turbo-frame",t,e)||this.element.getAttribute("target");if(e instanceof HTMLFormElement&&!this.#v(e,t)||!this.enabled||s=="_top")return!1;if(s){let i=this.#u(s);if(i)return!i.disabled;if(s=="_parent")return!1}return!(!M.elementIsNavigatable(e)||t&&!M.elementIsNavigatable(t))}get id(){return this.element.id}get disabled(){return this.element.disabled}get enabled(){return!this.disabled}get sourceURL(){if(this.element.src)return this.element.src}set sourceURL(e){this.#w("src",()=>{this.element.src=e??null})}get loadingStyle(){return this.element.loading}get isLoading(){return this.formSubmission!==void 0||this.#t()!==void 0}get complete(){return this.element.hasAttribute("complete")}set complete(e){e?this.element.setAttribute("complete",""):this.element.removeAttribute("complete")}get isActive(){return this.element.isActive&&this.#s}get rootLocation(){let t=this.element.ownerDocument.querySelector('meta[name="turbo-root"]')?.content??"/";return F(t)}#y(e){return this.#a.has(e)}#w(e,t){this.#a.add(e),t(),this.#a.delete(e)}#E(e,t){this.currentNavigationElement=e,t(),delete this.currentNavigationElement}#u(e){if(e!=null){let t=e==="_parent"?this.element.parentElement.closest("turbo-frame"):document.getElementById(e);if(t instanceof P)return t}}};function ls(r,e){if(r){let t=r.getAttribute("src");if(t!=null&&e!=null&&ws(t,e))throw new Error(`Matching <turbo-frame id="${r.id}"> element has a source URL which references itself`);if(r.ownerDocument!==document&&(r=document.importNode(r,!0)),r instanceof P)return r.connectedCallback(),r.disconnectedCallback(),r}}var Et={after(){this.removeDuplicateTargetSiblings(),this.targetElements.forEach(r=>r.parentElement?.insertBefore(this.templateContent,r.nextSibling))},append(){this.removeDuplicateTargetChildren(),this.targetElements.forEach(r=>r.append(this.templateContent))},before(){this.removeDuplicateTargetSiblings(),this.targetElements.forEach(r=>r.parentElement?.insertBefore(this.templateContent,r))},prepend(){this.removeDuplicateTargetChildren(),this.targetElements.forEach(r=>r.prepend(this.templateContent))},remove(){this.targetElements.forEach(r=>r.remove())},replace(){let r=this.getAttribute("method");this.targetElements.forEach(e=>{r==="morph"?le(e,this.templateContent):e.replaceWith(this.templateContent)})},update(){let r=this.getAttribute("method");this.targetElements.forEach(e=>{r==="morph"?Ie(e,this.templateContent):(e.innerHTML="",e.append(this.templateContent))})},refresh(){let r=this.getAttribute("method"),e=this.requestId,t=this.getAttribute("scroll");M.refresh(this.baseURI,{method:r,requestId:e,scroll:t})}},Re=class r 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()=>{let e=this.beforeRenderEvent;this.dispatchEvent(e)&&(await ie(),await e.detail.render(this))})()}disconnect(){try{this.remove()}catch{}}removeDuplicateTargetChildren(){this.duplicateChildren.forEach(e=>e.remove())}get duplicateChildren(){let e=this.targetElements.flatMap(s=>[...s.children]).filter(s=>!!s.getAttribute("id")),t=[...this.templateContent?.children||[]].filter(s=>!!s.getAttribute("id")).map(s=>s.getAttribute("id"));return e.filter(s=>t.includes(s.getAttribute("id")))}removeDuplicateTargetSiblings(){this.duplicateSiblings.forEach(e=>e.remove())}get duplicateSiblings(){let e=this.targetElements.flatMap(s=>[...s.parentElement.children]).filter(s=>!!s.id),t=[...this.templateContent?.children||[]].filter(s=>!!s.id).map(s=>s.id);return e.filter(s=>t.includes(s.id))}get performAction(){if(this.action){let e=Et[this.action];if(e)return e;this.#e("unknown action")}this.#e("action attribute is missing")}get targetElements(){if(this.target)return this.targetElementsById;if(this.targets)return this.targetElementsByQuery;this.#e("target or targets attribute is missing")}get templateContent(){return this.templateElement.content.cloneNode(!0)}get templateElement(){if(this.firstElementChild===null){let e=this.ownerDocument.createElement("template");return this.appendChild(e),e}else if(this.firstElementChild instanceof HTMLTemplateElement)return this.firstElementChild;this.#e("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")}#e(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:r.renderElement}})}get targetElementsById(){let e=this.ownerDocument?.getElementById(this.target);return e!==null?[e]:[]}get targetElementsByQuery(){let e=this.ownerDocument?.querySelectorAll(this.targets);return e.length!==0?Array.prototype.slice.call(e):[]}},ke=class extends HTMLElement{streamSource=null;connectedCallback(){this.streamSource=this.src.match(/^ws{1,2}:/)?new WebSocket(this.src):new EventSource(this.src),yt(this.streamSource)}disconnectedCallback(){this.streamSource&&(this.streamSource.close(),wt(this.streamSource))}get src(){return this.getAttribute("src")||""}};P.delegateConstructor=mt;customElements.get("turbo-frame")===void 0&&customElements.define("turbo-frame",P);customElements.get("turbo-stream")===void 0&&customElements.define("turbo-stream",Re);customElements.get("turbo-stream-source")===void 0&&customElements.define("turbo-stream-source",ke);(()=>{let r=document.currentScript;if(!r||r.hasAttribute("data-turbo-suppress-warning"))return;let e=r.parentElement;for(;e;){if(e==document.body)return console.warn(ms`
|
|
21
21
|
You are loading Turbo from a <script> element inside the <body> element. This is probably not what you meant to do!
|
|
22
22
|
|
|
23
23
|
Load your application’s JavaScript bundle inside the <head> element instead. <script> elements in <body> are evaluated with each page change.
|
|
@@ -26,8 +26,8 @@ Copyright © 2026 37signals LLC
|
|
|
26
26
|
|
|
27
27
|
——
|
|
28
28
|
Suppress this warning by adding a "data-turbo-suppress-warning" attribute to: %s
|
|
29
|
-
`,r.outerHTML);e=e.parentElement}})();window.Turbo={...ni,StreamActions:Et};vt();var St=class{constructor(e,t,s){this.eventTarget=e,this.eventName=t,this.eventOptions=s,this.unorderedBindings=new Set}connect(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)}disconnect(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)}bindingConnected(e){this.unorderedBindings.add(e)}bindingDisconnected(e){this.unorderedBindings.delete(e)}handleEvent(e){let t=oi(e);for(let s of this.bindings){if(t.immediatePropagationStopped)break;s.handleEvent(t)}}hasBindings(){return this.unorderedBindings.size>0}get bindings(){return Array.from(this.unorderedBindings).sort((e,t)=>{let s=e.index,i=t.index;return s<i?-1:s>i?1:0})}};function oi(r){if("immediatePropagationStopped"in r)return r;{let{stopImmediatePropagation:e}=r;return Object.assign(r,{immediatePropagationStopped:!1,stopImmediatePropagation(){this.immediatePropagationStopped=!0,e.call(this)}})}}var At=class{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach(e=>e.connect()))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach(e=>e.disconnect()))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce((e,t)=>e.concat(Array.from(t.values())),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,s={}){this.application.handleError(e,`Error ${t}`,s)}clearEventListenersForBinding(e){let t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){let{eventTarget:t,eventName:s,eventOptions:i}=e,n=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(s,i);n.delete(o),n.size==0&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){let{eventTarget:t,eventName:s,eventOptions:i}=e;return this.fetchEventListener(t,s,i)}fetchEventListener(e,t,s){let i=this.fetchEventListenerMapForEventTarget(e),n=this.cacheKey(t,s),o=i.get(n);return o||(o=this.createEventListener(e,t,s),i.set(n,o)),o}createEventListener(e,t,s){let i=new St(e,t,s);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){let s=[e];return Object.keys(t).sort().forEach(i=>{s.push(`${t[i]?"":"!"}${i}`)}),s.join(":")}},ai={stop({event:r,value:e}){return e&&r.stopPropagation(),!0},prevent({event:r,value:e}){return e&&r.preventDefault(),!0},self({event:r,value:e,element:t}){return e?t===r.target:!0}},ci=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function li(r){let t=r.trim().match(ci)||[],s=t[2],i=t[3];return i&&!["keydown","keyup","keypress"].includes(s)&&(s+=`.${i}`,i=""),{eventTarget:hi(t[4]),eventName:s,eventOptions:t[7]?ui(t[7]):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||i}}function hi(r){if(r=="window")return window;if(r=="document")return document}function ui(r){return r.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})}function di(r){if(r==window)return"window";if(r==document)return"document"}function jt(r){return r.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function Tt(r){return jt(r.replace(/--/g,"-").replace(/__/g,"_"))}function ue(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Js(r){return r.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function mi(r){return r.match(/[^\s]+/g)||[]}function Hs(r){return r!=null}function Lt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var $s=["meta","ctrl","alt","shift"],Ct=class{constructor(e,t,s,i){this.element=e,this.index=t,this.eventTarget=s.eventTarget||e,this.eventName=s.eventName||fi(e)||Pe("missing event name"),this.eventOptions=s.eventOptions||{},this.identifier=s.identifier||Pe("missing identifier"),this.methodName=s.methodName||Pe("missing method name"),this.keyFilter=s.keyFilter||"",this.schema=i}static forToken(e,t){return new this(e.element,e.index,li(e.content),t)}toString(){let e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;let t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;let s=t.filter(i=>!$s.includes(i))[0];return s?(Lt(this.keyMappings,s)||Pe(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[s].toLowerCase()!==e.key.toLowerCase()):!1}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;let t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){let e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(let{name:s,value:i}of Array.from(this.element.attributes)){let n=s.match(t),o=n&&n[1];o&&(e[jt(o)]=pi(i))}return e}get eventTargetName(){return di(this.eventTarget)}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){let[s,i,n,o]=$s.map(m=>t.includes(m));return e.metaKey!==s||e.ctrlKey!==i||e.altKey!==n||e.shiftKey!==o}},_s={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:r=>r.getAttribute("type")=="submit"?"click":"input",select:()=>"change",textarea:()=>"input"};function fi(r){let e=r.tagName.toLowerCase();if(e in _s)return _s[e](r)}function Pe(r){throw new Error(r)}function pi(r){try{return JSON.parse(r)}catch{return r}}var Mt=class{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){let t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){let e=this.controller[this.methodName];if(typeof e=="function")return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){let{element:t}=this.action,{actionDescriptorFilters:s}=this.context.application,{controller:i}=this.context,n=!0;for(let[o,m]of Object.entries(this.eventOptions))if(o in s){let w=s[o];n=n&&w({name:o,value:m,event:e,element:t,controller:i})}else continue;return n}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){let{target:t,currentTarget:s}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:s,action:this.methodName})}catch(i){let{identifier:n,controller:o,element:m,index:w}=this,C={identifier:n,controller:o,element:m,index:w,event:e};this.context.handleError(i,`invoking action "${this.action}"`,C)}}willBeInvokedByEvent(e){let t=e.target;return e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e)||e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e)?!1:this.element===t?!0:t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element)}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}},Be=class{constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver(s=>this.processMutations(s))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){let e=new Set(this.matchElementsInTree());for(let t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(let t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(let t of e)this.processMutation(t)}processMutation(e){e.type=="attributes"?this.processAttributeChange(e.target,e.attributeName):e.type=="childList"&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(let t of Array.from(e)){let s=this.elementFromNode(t);s&&this.processTree(s,this.removeElement)}}processAddedNodes(e){for(let t of Array.from(e)){let s=this.elementFromNode(t);s&&this.elementIsActive(s)&&this.processTree(s,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(let s of this.matchElementsInTree(e))t.call(this,s)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected!=this.element.isConnected?!1:this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}},Ne=class{constructor(e,t,s){this.attributeName=t,this.delegate=s,this.elementObserver=new Be(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){let t=this.matchElement(e)?[e]:[],s=Array.from(e.querySelectorAll(this.selector));return t.concat(s)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}};function gi(r,e,t){Ys(r,e).add(t)}function bi(r,e,t){Ys(r,e).delete(t),vi(r,e)}function Ys(r,e){let t=r.get(e);return t||(t=new Set,r.set(e,t)),t}function vi(r,e){let t=r.get(e);t!=null&&t.size==0&&r.delete(e)}var H=class{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce((t,s)=>t.concat(Array.from(s)),[])}get size(){return Array.from(this.valuesByKey.values()).reduce((t,s)=>t+s.size,0)}add(e,t){gi(this.valuesByKey,e,t)}delete(e,t){bi(this.valuesByKey,e,t)}has(e,t){let s=this.valuesByKey.get(e);return s!=null&&s.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some(s=>s.has(e))}getValuesForKey(e){let t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter(([t,s])=>s.has(e)).map(([t,s])=>t)}};var Rt=class{constructor(e,t,s,i){this._selector=t,this.details=i,this.elementObserver=new Be(e,this),this.delegate=s,this.matchesByElement=new H}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){let{selector:t}=this;if(t){let s=e.matches(t);return this.delegate.selectorMatchElement?s&&this.delegate.selectorMatchElement(e,this.details):s}else return!1}matchElementsInTree(e){let{selector:t}=this;if(t){let s=this.matchElement(e)?[e]:[],i=Array.from(e.querySelectorAll(t)).filter(n=>this.matchElement(n));return s.concat(i)}else return[]}elementMatched(e){let{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){let t=this.matchesByElement.getKeysForValue(e);for(let s of t)this.selectorUnmatched(e,s)}elementAttributeChanged(e,t){let{selector:s}=this;if(s){let i=this.matchElement(e),n=this.matchesByElement.has(s,e);i&&!n?this.selectorMatched(e,s):!i&&n&&this.selectorUnmatched(e,s)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}},kt=class{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver(s=>this.processMutations(s))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(let e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(let t of e)this.processMutation(t)}processMutation(e){let t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){let s=this.delegate.getStringMapKeyForAttribute(e);if(s!=null){this.stringMap.has(e)||this.stringMapKeyAdded(s,e);let i=this.element.getAttribute(e);if(this.stringMap.get(e)!=i&&this.stringMapValueChanged(i,s,t),i==null){let n=this.stringMap.get(e);this.stringMap.delete(e),n&&this.stringMapKeyRemoved(s,e,n)}else this.stringMap.set(e,i)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,s){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,s)}stringMapKeyRemoved(e,t,s){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,s)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map(e=>e.name)}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}},qe=class{constructor(e,t,s){this.attributeObserver=new Ne(e,t,this),this.delegate=s,this.tokensByElement=new H}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){let[t,s]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(s)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach(t=>this.tokenMatched(t))}tokensUnmatched(e){e.forEach(t=>this.tokenUnmatched(t))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){let t=this.tokensByElement.getValuesForKey(e),s=this.readTokensForElement(e),i=wi(t,s).findIndex(([n,o])=>!Ei(n,o));return i==-1?[[],[]]:[t.slice(i),s.slice(i)]}readTokensForElement(e){let t=this.attributeName,s=e.getAttribute(t)||"";return yi(s,e,t)}};function yi(r,e,t){return r.trim().split(/\s+/).filter(s=>s.length).map((s,i)=>({element:e,attributeName:t,content:s,index:i}))}function wi(r,e){let t=Math.max(r.length,e.length);return Array.from({length:t},(s,i)=>[r[i],e[i]])}function Ei(r,e){return r&&e&&r.index==e.index&&r.content==e.content}var De=class{constructor(e,t,s){this.tokenListObserver=new qe(e,t,this),this.delegate=s,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){let{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).set(e,s),this.delegate.elementMatchedValue(t,s))}tokenUnmatched(e){let{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,s))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(t){return{error:t}}}},Ot=class{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new De(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){let t=new Mt(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){let t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach(e=>this.delegate.bindingDisconnected(e,!0)),this.bindingsByAction.clear()}parseValueForToken(e){let t=Ct.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}},Ft=class{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new kt(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){let s=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,s.writer(this.receiver[e]),s.writer(s.defaultValue))}stringMapValueChanged(e,t,s){let i=this.valueDescriptorNameMap[t];e!==null&&(s===null&&(s=i.writer(i.defaultValue)),this.invokeChangedCallback(t,e,s))}stringMapKeyRemoved(e,t,s){let i=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,i.writer(this.receiver[e]),s):this.invokeChangedCallback(e,i.writer(i.defaultValue),s)}invokeChangedCallbacksForDefaultValues(){for(let{key:e,name:t,defaultValue:s,writer:i}of this.valueDescriptors)s!=null&&!this.controller.data.has(e)&&this.invokeChangedCallback(t,i(s),void 0)}invokeChangedCallback(e,t,s){let i=`${e}Changed`,n=this.receiver[i];if(typeof n=="function"){let o=this.valueDescriptorNameMap[e];try{let m=o.reader(t),w=s;s&&(w=o.reader(s)),n.call(this.receiver,m,w)}catch(m){throw m instanceof TypeError&&(m.message=`Stimulus Value "${this.context.identifier}.${o.name}" - ${m.message}`),m}}}get valueDescriptors(){let{valueDescriptorMap:e}=this;return Object.keys(e).map(t=>e[t])}get valueDescriptorNameMap(){let e={};return Object.keys(this.valueDescriptorMap).forEach(t=>{let s=this.valueDescriptorMap[t];e[s.name]=s}),e}hasValue(e){let t=this.valueDescriptorNameMap[e],s=`has${ue(t.name)}`;return this.receiver[s]}},It=class{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new H}start(){this.tokenListObserver||(this.tokenListObserver=new qe(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var s;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),(s=this.tokenListObserver)===null||s===void 0||s.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var s;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),(s=this.tokenListObserver)===null||s===void 0||s.pause(()=>this.delegate.targetDisconnected(e,t)))}disconnectAllTargets(){for(let e of this.targetsByName.keys)for(let t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}};function de(r,e){let t=Zs(r);return Array.from(t.reduce((s,i)=>(Ai(i,e).forEach(n=>s.add(n)),s),new Set))}function Si(r,e){return Zs(r).reduce((s,i)=>(s.push(...Ti(i,e)),s),[])}function Zs(r){let e=[];for(;r;)e.push(r),r=Object.getPrototypeOf(r);return e.reverse()}function Ai(r,e){let t=r[e];return Array.isArray(t)?t:[]}function Ti(r,e){let t=r[e];return t?Object.keys(t).map(s=>[s,t[s]]):[]}var Pt=class{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new H,this.outletElementsByName=new H,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach(e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)}),this.started=!0,this.dependentContexts.forEach(e=>e.refresh()))}refresh(){this.selectorObserverMap.forEach(e=>e.refresh()),this.attributeObserverMap.forEach(e=>e.refresh())}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach(e=>e.stop()),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach(e=>e.stop()),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:s}){let i=this.getOutlet(e,s);i&&this.connectOutlet(i,e,s)}selectorUnmatched(e,t,{outletName:s}){let i=this.getOutletFromMap(e,s);i&&this.disconnectOutlet(i,e,s)}selectorMatchElement(e,{outletName:t}){let s=this.selector(t),i=this.hasOutlet(e,t),n=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return s?i&&n&&e.matches(s):!1}elementMatchedAttribute(e,t){let s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementAttributeValueChanged(e,t){let s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementUnmatchedAttribute(e,t){let s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}connectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)||(this.outletsByName.add(s,e),this.outletElementsByName.add(s,t),(i=this.selectorObserverMap.get(s))===null||i===void 0||i.pause(()=>this.delegate.outletConnected(e,t,s)))}disconnectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)&&(this.outletsByName.delete(s,e),this.outletElementsByName.delete(s,t),(i=this.selectorObserverMap.get(s))===null||i===void 0||i.pause(()=>this.delegate.outletDisconnected(e,t,s)))}disconnectAllOutlets(){for(let e of this.outletElementsByName.keys)for(let t of this.outletElementsByName.getValuesForKey(e))for(let s of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(s,t,e)}updateSelectorObserverForOutlet(e){let t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){let t=this.selector(e),s=new Rt(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,s),s.start()}setupAttributeObserverForOutlet(e){let t=this.attributeNameForOutletName(e),s=new Ne(this.scope.element,t,this);this.attributeObserverMap.set(e,s),s.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find(t=>this.attributeNameForOutletName(t)===e)}get outletDependencies(){let e=new H;return this.router.modules.forEach(t=>{let s=t.definition.controllerConstructor;de(s,"outlets").forEach(n=>e.add(n,t.identifier))}),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){let e=this.dependentControllerIdentifiers;return this.router.contexts.filter(t=>e.includes(t.identifier))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find(s=>s.element===e)}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}},Bt=class{constructor(e,t){this.logDebugActivity=(s,i={})=>{let{identifier:n,controller:o,element:m}=this;i=Object.assign({identifier:n,controller:o,element:m},i),this.application.logDebugActivity(this.identifier,s,i)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new Ot(this,this.dispatcher),this.valueObserver=new Ft(this,this.controller),this.targetObserver=new It(this,this),this.outletObserver=new Pt(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(s){this.handleError(s,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,s={}){let{identifier:i,controller:n,element:o}=this;s=Object.assign({identifier:i,controller:n,element:o},s),this.application.handleError(e,`Error ${t}`,s)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,s){this.invokeControllerMethod(`${Tt(s)}OutletConnected`,e,t)}outletDisconnected(e,t,s){this.invokeControllerMethod(`${Tt(s)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){let s=this.controller;typeof s[e]=="function"&&s[e](...t)}};function Li(r){return Ci(r,Mi(r))}function Ci(r,e){let t=Fi(r),s=Ri(r.prototype,e);return Object.defineProperties(t.prototype,s),t}function Mi(r){return de(r,"blessings").reduce((t,s)=>{let i=s(r);for(let n in i){let o=t[n]||{};t[n]=Object.assign(o,i[n])}return t},{})}function Ri(r,e){return Oi(e).reduce((t,s)=>{let i=ki(r,e,s);return i&&Object.assign(t,{[s]:i}),t},{})}function ki(r,e,t){let s=Object.getOwnPropertyDescriptor(r,t);if(!(s&&"value"in s)){let n=Object.getOwnPropertyDescriptor(e,t).value;return s&&(n.get=s.get||n.get,n.set=s.set||n.set),n}}var Oi=typeof Object.getOwnPropertySymbols=="function"?r=>[...Object.getOwnPropertyNames(r),...Object.getOwnPropertySymbols(r)]:Object.getOwnPropertyNames,Fi=(()=>{function r(t){function s(){return Reflect.construct(t,arguments,new.target)}return s.prototype=Object.create(t.prototype,{constructor:{value:s}}),Reflect.setPrototypeOf(s,t),s}function e(){let s=r(function(){this.a.call(this)});return s.prototype.a=function(){},new s}try{return e(),r}catch{return s=>class extends s{}}})();function Ii(r){return{identifier:r.identifier,controllerConstructor:Li(r.controllerConstructor)}}var Nt=class{constructor(e,t){this.application=e,this.definition=Ii(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){let t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){let t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new Bt(this,e),this.contextsByScope.set(e,t)),t}},qt=class{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){let t=this.data.get(this.getDataKey(e))||"";return mi(t)}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}},Dt=class{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){let t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){let s=this.getAttributeNameForKey(e);return this.element.setAttribute(s,t),this.get(e)}has(e){let t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){let t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}else return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${Js(e)}`}},xt=class{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,s){let i=this.warnedKeysByObject.get(e);i||(i=new Set,this.warnedKeysByObject.set(e,i)),i.has(t)||(i.add(t),this.logger.warn(s,e))}};function Vt(r,e){return`[${r}~="${e}"]`}var Ht=class{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return this.find(e)!=null}find(...e){return e.reduce((t,s)=>t||this.findTarget(s)||this.findLegacyTarget(s),void 0)}findAll(...e){return e.reduce((t,s)=>[...t,...this.findAllTargets(s),...this.findAllLegacyTargets(s)],[])}findTarget(e){let t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){let t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){let t=this.schema.targetAttributeForScope(this.identifier);return Vt(t,e)}findLegacyTarget(e){let t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){let t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map(s=>this.deprecate(s,e))}getLegacySelectorForTargetName(e){let t=`${this.identifier}.${e}`;return Vt(this.schema.targetAttribute,t)}deprecate(e,t){if(e){let{identifier:s}=this,i=this.schema.targetAttribute,n=this.schema.targetAttributeForScope(s);this.guide.warn(e,`target:${t}`,`Please replace ${i}="${s}.${t}" with ${n}="${t}". The ${i} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}},$t=class{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return this.find(e)!=null}find(...e){return e.reduce((t,s)=>t||this.findOutlet(s),void 0)}findAll(...e){return e.reduce((t,s)=>[...t,...this.findAllOutlets(s)],[])}getSelectorForOutletName(e){let t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){let t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){let t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter(i=>this.matchesElement(i,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(i=>this.matchesElement(i,e,t))}matchesElement(e,t,s){let i=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&i.split(" ").includes(s)}},_t=class r{constructor(e,t,s,i){this.targets=new Ht(this),this.classes=new qt(this),this.data=new Dt(this),this.containsElement=n=>n.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=s,this.guide=new xt(i),this.outlets=new $t(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return Vt(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new r(this.schema,document.documentElement,this.identifier,this.guide.logger)}},Ut=class{constructor(e,t,s){this.element=e,this.schema=t,this.delegate=s,this.valueListObserver=new De(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){let{element:t,content:s}=e;return this.parseValueForElementAndIdentifier(t,s)}parseValueForElementAndIdentifier(e,t){let s=this.fetchScopesByIdentifierForElement(e),i=s.get(t);return i||(i=this.delegate.createScopeForElementAndIdentifier(e,t),s.set(t,i)),i}elementMatchedValue(e,t){let s=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,s),s==1&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){let s=this.scopeReferenceCounts.get(t);s&&(this.scopeReferenceCounts.set(t,s-1),s==1&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}},Wt=class{constructor(e){this.application=e,this.scopeObserver=new Ut(this.element,this.schema,this),this.scopesByIdentifier=new H,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce((e,t)=>e.concat(t.contexts),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);let t=new Nt(this.application,e);this.connectModule(t);let s=e.controllerConstructor.afterLoad;s&&s.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){let t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){let s=this.modulesByIdentifier.get(t);if(s)return s.contexts.find(i=>i.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){let s=this.scopeObserver.parseValueForElementAndIdentifier(e,t);s?this.scopeObserver.elementMatchedValue(s.element,s):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,s){this.application.handleError(e,t,s)}createScopeForElementAndIdentifier(e,t){return new _t(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);let t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);let t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(s=>e.connectContextForScope(s))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(s=>e.disconnectContextForScope(s))}},Pi={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:r=>`data-${r}-target`,outletAttributeForScope:(r,e)=>`data-${r}-${e}-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},Us("abcdefghijklmnopqrstuvwxyz".split("").map(r=>[r,r]))),Us("0123456789".split("").map(r=>[r,r])))};function Us(r){return r.reduce((e,[t,s])=>Object.assign(Object.assign({},e),{[t]:s}),{})}var xe=class{constructor(e=document.documentElement,t=Pi){this.logger=console,this.debug=!1,this.logDebugActivity=(s,i,n={})=>{this.debug&&this.logFormattedMessage(s,i,n)},this.element=e,this.schema=t,this.dispatcher=new At(this),this.router=new Wt(this),this.actionDescriptorFilters=Object.assign({},ai)}static start(e,t){let s=new this(e,t);return s.start(),s}async start(){await Bi(),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(i=>{i.controllerConstructor.shouldLoad&&this.router.loadDefinition(i)})}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(i=>this.router.unloadIdentifier(i))}get controllers(){return this.router.contexts.map(e=>e.controller)}getControllerForElementAndIdentifier(e,t){let s=this.router.getContextForElementAndIdentifier(e,t);return s?s.controller:null}handleError(e,t,s){var i;this.logger.error(`%s
|
|
29
|
+
`,r.outerHTML);e=e.parentElement}})();window.Turbo={...ni,StreamActions:Et};vt();var St=class{constructor(e,t,s){this.eventTarget=e,this.eventName=t,this.eventOptions=s,this.unorderedBindings=new Set}connect(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)}disconnect(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)}bindingConnected(e){this.unorderedBindings.add(e)}bindingDisconnected(e){this.unorderedBindings.delete(e)}handleEvent(e){let t=oi(e);for(let s of this.bindings){if(t.immediatePropagationStopped)break;s.handleEvent(t)}}hasBindings(){return this.unorderedBindings.size>0}get bindings(){return Array.from(this.unorderedBindings).sort((e,t)=>{let s=e.index,i=t.index;return s<i?-1:s>i?1:0})}};function oi(r){if("immediatePropagationStopped"in r)return r;{let{stopImmediatePropagation:e}=r;return Object.assign(r,{immediatePropagationStopped:!1,stopImmediatePropagation(){this.immediatePropagationStopped=!0,e.call(this)}})}}var At=class{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach(e=>e.connect()))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach(e=>e.disconnect()))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce((e,t)=>e.concat(Array.from(t.values())),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,s={}){this.application.handleError(e,`Error ${t}`,s)}clearEventListenersForBinding(e){let t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){let{eventTarget:t,eventName:s,eventOptions:i}=e,n=this.fetchEventListenerMapForEventTarget(t),o=this.cacheKey(s,i);n.delete(o),n.size==0&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){let{eventTarget:t,eventName:s,eventOptions:i}=e;return this.fetchEventListener(t,s,i)}fetchEventListener(e,t,s){let i=this.fetchEventListenerMapForEventTarget(e),n=this.cacheKey(t,s),o=i.get(n);return o||(o=this.createEventListener(e,t,s),i.set(n,o)),o}createEventListener(e,t,s){let i=new St(e,t,s);return this.started&&i.connect(),i}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){let s=[e];return Object.keys(t).sort().forEach(i=>{s.push(`${t[i]?"":"!"}${i}`)}),s.join(":")}},ai={stop({event:r,value:e}){return e&&r.stopPropagation(),!0},prevent({event:r,value:e}){return e&&r.preventDefault(),!0},self({event:r,value:e,element:t}){return e?t===r.target:!0}},ci=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function li(r){let t=r.trim().match(ci)||[],s=t[2],i=t[3];return i&&!["keydown","keyup","keypress"].includes(s)&&(s+=`.${i}`,i=""),{eventTarget:hi(t[4]),eventName:s,eventOptions:t[7]?ui(t[7]):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||i}}function hi(r){if(r=="window")return window;if(r=="document")return document}function ui(r){return r.split(":").reduce((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)}),{})}function di(r){if(r==window)return"window";if(r==document)return"document"}function jt(r){return r.replace(/(?:[_-])([a-z0-9])/g,(e,t)=>t.toUpperCase())}function Tt(r){return jt(r.replace(/--/g,"-").replace(/__/g,"_"))}function ue(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Js(r){return r.replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`)}function mi(r){return r.match(/[^\s]+/g)||[]}function Hs(r){return r!=null}function Lt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var $s=["meta","ctrl","alt","shift"],Ct=class{constructor(e,t,s,i){this.element=e,this.index=t,this.eventTarget=s.eventTarget||e,this.eventName=s.eventName||fi(e)||Pe("missing event name"),this.eventOptions=s.eventOptions||{},this.identifier=s.identifier||Pe("missing identifier"),this.methodName=s.methodName||Pe("missing method name"),this.keyFilter=s.keyFilter||"",this.schema=i}static forToken(e,t){return new this(e.element,e.index,li(e.content),t)}toString(){let e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;let t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;let s=t.filter(i=>!$s.includes(i))[0];return s?(Lt(this.keyMappings,s)||Pe(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[s].toLowerCase()!==e.key.toLowerCase()):!1}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;let t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){let e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(let{name:s,value:i}of Array.from(this.element.attributes)){let n=s.match(t),o=n&&n[1];o&&(e[jt(o)]=pi(i))}return e}get eventTargetName(){return di(this.eventTarget)}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){let[s,i,n,o]=$s.map(m=>t.includes(m));return e.metaKey!==s||e.ctrlKey!==i||e.altKey!==n||e.shiftKey!==o}},_s={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:r=>r.getAttribute("type")=="submit"?"click":"input",select:()=>"change",textarea:()=>"input"};function fi(r){let e=r.tagName.toLowerCase();if(e in _s)return _s[e](r)}function Pe(r){throw new Error(r)}function pi(r){try{return JSON.parse(r)}catch{return r}}var Mt=class{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){let t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){let e=this.controller[this.methodName];if(typeof e=="function")return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){let{element:t}=this.action,{actionDescriptorFilters:s}=this.context.application,{controller:i}=this.context,n=!0;for(let[o,m]of Object.entries(this.eventOptions))if(o in s){let w=s[o];n=n&&w({name:o,value:m,event:e,element:t,controller:i})}else continue;return n}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){let{target:t,currentTarget:s}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:s,action:this.methodName})}catch(i){let{identifier:n,controller:o,element:m,index:w}=this,C={identifier:n,controller:o,element:m,index:w,event:e};this.context.handleError(i,`invoking action "${this.action}"`,C)}}willBeInvokedByEvent(e){let t=e.target;return e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e)||e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e)?!1:this.element===t?!0:t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element)}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}},Be=class{constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver(s=>this.processMutations(s))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){let e=new Set(this.matchElementsInTree());for(let t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(let t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(let t of e)this.processMutation(t)}processMutation(e){e.type=="attributes"?this.processAttributeChange(e.target,e.attributeName):e.type=="childList"&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(let t of Array.from(e)){let s=this.elementFromNode(t);s&&this.processTree(s,this.removeElement)}}processAddedNodes(e){for(let t of Array.from(e)){let s=this.elementFromNode(t);s&&this.elementIsActive(s)&&this.processTree(s,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(let s of this.matchElementsInTree(e))t.call(this,s)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected!=this.element.isConnected?!1:this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}},qe=class{constructor(e,t,s){this.attributeName=t,this.delegate=s,this.elementObserver=new Be(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){let t=this.matchElement(e)?[e]:[],s=Array.from(e.querySelectorAll(this.selector));return t.concat(s)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}};function gi(r,e,t){Ys(r,e).add(t)}function bi(r,e,t){Ys(r,e).delete(t),vi(r,e)}function Ys(r,e){let t=r.get(e);return t||(t=new Set,r.set(e,t)),t}function vi(r,e){let t=r.get(e);t!=null&&t.size==0&&r.delete(e)}var H=class{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce((t,s)=>t.concat(Array.from(s)),[])}get size(){return Array.from(this.valuesByKey.values()).reduce((t,s)=>t+s.size,0)}add(e,t){gi(this.valuesByKey,e,t)}delete(e,t){bi(this.valuesByKey,e,t)}has(e,t){let s=this.valuesByKey.get(e);return s!=null&&s.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some(s=>s.has(e))}getValuesForKey(e){let t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter(([t,s])=>s.has(e)).map(([t,s])=>t)}};var Rt=class{constructor(e,t,s,i){this._selector=t,this.details=i,this.elementObserver=new Be(e,this),this.delegate=s,this.matchesByElement=new H}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){let{selector:t}=this;if(t){let s=e.matches(t);return this.delegate.selectorMatchElement?s&&this.delegate.selectorMatchElement(e,this.details):s}else return!1}matchElementsInTree(e){let{selector:t}=this;if(t){let s=this.matchElement(e)?[e]:[],i=Array.from(e.querySelectorAll(t)).filter(n=>this.matchElement(n));return s.concat(i)}else return[]}elementMatched(e){let{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){let t=this.matchesByElement.getKeysForValue(e);for(let s of t)this.selectorUnmatched(e,s)}elementAttributeChanged(e,t){let{selector:s}=this;if(s){let i=this.matchElement(e),n=this.matchesByElement.has(s,e);i&&!n?this.selectorMatched(e,s):!i&&n&&this.selectorUnmatched(e,s)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}},kt=class{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver(s=>this.processMutations(s))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(let e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(let t of e)this.processMutation(t)}processMutation(e){let t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){let s=this.delegate.getStringMapKeyForAttribute(e);if(s!=null){this.stringMap.has(e)||this.stringMapKeyAdded(s,e);let i=this.element.getAttribute(e);if(this.stringMap.get(e)!=i&&this.stringMapValueChanged(i,s,t),i==null){let n=this.stringMap.get(e);this.stringMap.delete(e),n&&this.stringMapKeyRemoved(s,e,n)}else this.stringMap.set(e,i)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,s){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,s)}stringMapKeyRemoved(e,t,s){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,s)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map(e=>e.name)}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}},Ne=class{constructor(e,t,s){this.attributeObserver=new qe(e,t,this),this.delegate=s,this.tokensByElement=new H}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){let[t,s]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(s)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach(t=>this.tokenMatched(t))}tokensUnmatched(e){e.forEach(t=>this.tokenUnmatched(t))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){let t=this.tokensByElement.getValuesForKey(e),s=this.readTokensForElement(e),i=wi(t,s).findIndex(([n,o])=>!Ei(n,o));return i==-1?[[],[]]:[t.slice(i),s.slice(i)]}readTokensForElement(e){let t=this.attributeName,s=e.getAttribute(t)||"";return yi(s,e,t)}};function yi(r,e,t){return r.trim().split(/\s+/).filter(s=>s.length).map((s,i)=>({element:e,attributeName:t,content:s,index:i}))}function wi(r,e){let t=Math.max(r.length,e.length);return Array.from({length:t},(s,i)=>[r[i],e[i]])}function Ei(r,e){return r&&e&&r.index==e.index&&r.content==e.content}var De=class{constructor(e,t,s){this.tokenListObserver=new Ne(e,t,this),this.delegate=s,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){let{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).set(e,s),this.delegate.elementMatchedValue(t,s))}tokenUnmatched(e){let{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,s))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(t){return{error:t}}}},Ot=class{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new De(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){let t=new Mt(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){let t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach(e=>this.delegate.bindingDisconnected(e,!0)),this.bindingsByAction.clear()}parseValueForToken(e){let t=Ct.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}},Ft=class{constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new kt(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){let s=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,s.writer(this.receiver[e]),s.writer(s.defaultValue))}stringMapValueChanged(e,t,s){let i=this.valueDescriptorNameMap[t];e!==null&&(s===null&&(s=i.writer(i.defaultValue)),this.invokeChangedCallback(t,e,s))}stringMapKeyRemoved(e,t,s){let i=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,i.writer(this.receiver[e]),s):this.invokeChangedCallback(e,i.writer(i.defaultValue),s)}invokeChangedCallbacksForDefaultValues(){for(let{key:e,name:t,defaultValue:s,writer:i}of this.valueDescriptors)s!=null&&!this.controller.data.has(e)&&this.invokeChangedCallback(t,i(s),void 0)}invokeChangedCallback(e,t,s){let i=`${e}Changed`,n=this.receiver[i];if(typeof n=="function"){let o=this.valueDescriptorNameMap[e];try{let m=o.reader(t),w=s;s&&(w=o.reader(s)),n.call(this.receiver,m,w)}catch(m){throw m instanceof TypeError&&(m.message=`Stimulus Value "${this.context.identifier}.${o.name}" - ${m.message}`),m}}}get valueDescriptors(){let{valueDescriptorMap:e}=this;return Object.keys(e).map(t=>e[t])}get valueDescriptorNameMap(){let e={};return Object.keys(this.valueDescriptorMap).forEach(t=>{let s=this.valueDescriptorMap[t];e[s.name]=s}),e}hasValue(e){let t=this.valueDescriptorNameMap[e],s=`has${ue(t.name)}`;return this.receiver[s]}},It=class{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new H}start(){this.tokenListObserver||(this.tokenListObserver=new Ne(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var s;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),(s=this.tokenListObserver)===null||s===void 0||s.pause(()=>this.delegate.targetConnected(e,t)))}disconnectTarget(e,t){var s;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),(s=this.tokenListObserver)===null||s===void 0||s.pause(()=>this.delegate.targetDisconnected(e,t)))}disconnectAllTargets(){for(let e of this.targetsByName.keys)for(let t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}};function de(r,e){let t=Zs(r);return Array.from(t.reduce((s,i)=>(Ai(i,e).forEach(n=>s.add(n)),s),new Set))}function Si(r,e){return Zs(r).reduce((s,i)=>(s.push(...Ti(i,e)),s),[])}function Zs(r){let e=[];for(;r;)e.push(r),r=Object.getPrototypeOf(r);return e.reverse()}function Ai(r,e){let t=r[e];return Array.isArray(t)?t:[]}function Ti(r,e){let t=r[e];return t?Object.keys(t).map(s=>[s,t[s]]):[]}var Pt=class{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new H,this.outletElementsByName=new H,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach(e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)}),this.started=!0,this.dependentContexts.forEach(e=>e.refresh()))}refresh(){this.selectorObserverMap.forEach(e=>e.refresh()),this.attributeObserverMap.forEach(e=>e.refresh())}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach(e=>e.stop()),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach(e=>e.stop()),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:s}){let i=this.getOutlet(e,s);i&&this.connectOutlet(i,e,s)}selectorUnmatched(e,t,{outletName:s}){let i=this.getOutletFromMap(e,s);i&&this.disconnectOutlet(i,e,s)}selectorMatchElement(e,{outletName:t}){let s=this.selector(t),i=this.hasOutlet(e,t),n=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return s?i&&n&&e.matches(s):!1}elementMatchedAttribute(e,t){let s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementAttributeValueChanged(e,t){let s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementUnmatchedAttribute(e,t){let s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}connectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)||(this.outletsByName.add(s,e),this.outletElementsByName.add(s,t),(i=this.selectorObserverMap.get(s))===null||i===void 0||i.pause(()=>this.delegate.outletConnected(e,t,s)))}disconnectOutlet(e,t,s){var i;this.outletElementsByName.has(s,t)&&(this.outletsByName.delete(s,e),this.outletElementsByName.delete(s,t),(i=this.selectorObserverMap.get(s))===null||i===void 0||i.pause(()=>this.delegate.outletDisconnected(e,t,s)))}disconnectAllOutlets(){for(let e of this.outletElementsByName.keys)for(let t of this.outletElementsByName.getValuesForKey(e))for(let s of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(s,t,e)}updateSelectorObserverForOutlet(e){let t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){let t=this.selector(e),s=new Rt(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,s),s.start()}setupAttributeObserverForOutlet(e){let t=this.attributeNameForOutletName(e),s=new qe(this.scope.element,t,this);this.attributeObserverMap.set(e,s),s.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find(t=>this.attributeNameForOutletName(t)===e)}get outletDependencies(){let e=new H;return this.router.modules.forEach(t=>{let s=t.definition.controllerConstructor;de(s,"outlets").forEach(n=>e.add(n,t.identifier))}),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){let e=this.dependentControllerIdentifiers;return this.router.contexts.filter(t=>e.includes(t.identifier))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find(s=>s.element===e)}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}},Bt=class{constructor(e,t){this.logDebugActivity=(s,i={})=>{let{identifier:n,controller:o,element:m}=this;i=Object.assign({identifier:n,controller:o,element:m},i),this.application.logDebugActivity(this.identifier,s,i)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new Ot(this,this.dispatcher),this.valueObserver=new Ft(this,this.controller),this.targetObserver=new It(this,this),this.outletObserver=new Pt(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(s){this.handleError(s,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,s={}){let{identifier:i,controller:n,element:o}=this;s=Object.assign({identifier:i,controller:n,element:o},s),this.application.handleError(e,`Error ${t}`,s)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,s){this.invokeControllerMethod(`${Tt(s)}OutletConnected`,e,t)}outletDisconnected(e,t,s){this.invokeControllerMethod(`${Tt(s)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){let s=this.controller;typeof s[e]=="function"&&s[e](...t)}};function Li(r){return Ci(r,Mi(r))}function Ci(r,e){let t=Fi(r),s=Ri(r.prototype,e);return Object.defineProperties(t.prototype,s),t}function Mi(r){return de(r,"blessings").reduce((t,s)=>{let i=s(r);for(let n in i){let o=t[n]||{};t[n]=Object.assign(o,i[n])}return t},{})}function Ri(r,e){return Oi(e).reduce((t,s)=>{let i=ki(r,e,s);return i&&Object.assign(t,{[s]:i}),t},{})}function ki(r,e,t){let s=Object.getOwnPropertyDescriptor(r,t);if(!(s&&"value"in s)){let n=Object.getOwnPropertyDescriptor(e,t).value;return s&&(n.get=s.get||n.get,n.set=s.set||n.set),n}}var Oi=typeof Object.getOwnPropertySymbols=="function"?r=>[...Object.getOwnPropertyNames(r),...Object.getOwnPropertySymbols(r)]:Object.getOwnPropertyNames,Fi=(()=>{function r(t){function s(){return Reflect.construct(t,arguments,new.target)}return s.prototype=Object.create(t.prototype,{constructor:{value:s}}),Reflect.setPrototypeOf(s,t),s}function e(){let s=r(function(){this.a.call(this)});return s.prototype.a=function(){},new s}try{return e(),r}catch{return s=>class extends s{}}})();function Ii(r){return{identifier:r.identifier,controllerConstructor:Li(r.controllerConstructor)}}var qt=class{constructor(e,t){this.application=e,this.definition=Ii(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){let t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){let t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new Bt(this,e),this.contextsByScope.set(e,t)),t}},Nt=class{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){let t=this.data.get(this.getDataKey(e))||"";return mi(t)}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}},Dt=class{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){let t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){let s=this.getAttributeNameForKey(e);return this.element.setAttribute(s,t),this.get(e)}has(e){let t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){let t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}else return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${Js(e)}`}},xt=class{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,s){let i=this.warnedKeysByObject.get(e);i||(i=new Set,this.warnedKeysByObject.set(e,i)),i.has(t)||(i.add(t),this.logger.warn(s,e))}};function Vt(r,e){return`[${r}~="${e}"]`}var Ht=class{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return this.find(e)!=null}find(...e){return e.reduce((t,s)=>t||this.findTarget(s)||this.findLegacyTarget(s),void 0)}findAll(...e){return e.reduce((t,s)=>[...t,...this.findAllTargets(s),...this.findAllLegacyTargets(s)],[])}findTarget(e){let t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){let t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){let t=this.schema.targetAttributeForScope(this.identifier);return Vt(t,e)}findLegacyTarget(e){let t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){let t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map(s=>this.deprecate(s,e))}getLegacySelectorForTargetName(e){let t=`${this.identifier}.${e}`;return Vt(this.schema.targetAttribute,t)}deprecate(e,t){if(e){let{identifier:s}=this,i=this.schema.targetAttribute,n=this.schema.targetAttributeForScope(s);this.guide.warn(e,`target:${t}`,`Please replace ${i}="${s}.${t}" with ${n}="${t}". The ${i} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}},$t=class{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return this.find(e)!=null}find(...e){return e.reduce((t,s)=>t||this.findOutlet(s),void 0)}findAll(...e){return e.reduce((t,s)=>[...t,...this.findAllOutlets(s)],[])}getSelectorForOutletName(e){let t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){let t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){let t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter(i=>this.matchesElement(i,e,t))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter(i=>this.matchesElement(i,e,t))}matchesElement(e,t,s){let i=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&i.split(" ").includes(s)}},_t=class r{constructor(e,t,s,i){this.targets=new Ht(this),this.classes=new Nt(this),this.data=new Dt(this),this.containsElement=n=>n.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=s,this.guide=new xt(i),this.outlets=new $t(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return Vt(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new r(this.schema,document.documentElement,this.identifier,this.guide.logger)}},Ut=class{constructor(e,t,s){this.element=e,this.schema=t,this.delegate=s,this.valueListObserver=new De(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){let{element:t,content:s}=e;return this.parseValueForElementAndIdentifier(t,s)}parseValueForElementAndIdentifier(e,t){let s=this.fetchScopesByIdentifierForElement(e),i=s.get(t);return i||(i=this.delegate.createScopeForElementAndIdentifier(e,t),s.set(t,i)),i}elementMatchedValue(e,t){let s=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,s),s==1&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){let s=this.scopeReferenceCounts.get(t);s&&(this.scopeReferenceCounts.set(t,s-1),s==1&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}},Wt=class{constructor(e){this.application=e,this.scopeObserver=new Ut(this.element,this.schema,this),this.scopesByIdentifier=new H,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce((e,t)=>e.concat(t.contexts),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);let t=new qt(this.application,e);this.connectModule(t);let s=e.controllerConstructor.afterLoad;s&&s.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){let t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){let s=this.modulesByIdentifier.get(t);if(s)return s.contexts.find(i=>i.element==e)}proposeToConnectScopeForElementAndIdentifier(e,t){let s=this.scopeObserver.parseValueForElementAndIdentifier(e,t);s?this.scopeObserver.elementMatchedValue(s.element,s):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,s){this.application.handleError(e,t,s)}createScopeForElementAndIdentifier(e,t){return new _t(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);let t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);let t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(s=>e.connectContextForScope(s))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier),this.scopesByIdentifier.getValuesForKey(e.identifier).forEach(s=>e.disconnectContextForScope(s))}},Pi={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:r=>`data-${r}-target`,outletAttributeForScope:(r,e)=>`data-${r}-${e}-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},Us("abcdefghijklmnopqrstuvwxyz".split("").map(r=>[r,r]))),Us("0123456789".split("").map(r=>[r,r])))};function Us(r){return r.reduce((e,[t,s])=>Object.assign(Object.assign({},e),{[t]:s}),{})}var xe=class{constructor(e=document.documentElement,t=Pi){this.logger=console,this.debug=!1,this.logDebugActivity=(s,i,n={})=>{this.debug&&this.logFormattedMessage(s,i,n)},this.element=e,this.schema=t,this.dispatcher=new At(this),this.router=new Wt(this),this.actionDescriptorFilters=Object.assign({},ai)}static start(e,t){let s=new this(e,t);return s.start(),s}async start(){await Bi(),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(i=>{i.controllerConstructor.shouldLoad&&this.router.loadDefinition(i)})}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach(i=>this.router.unloadIdentifier(i))}get controllers(){return this.router.contexts.map(e=>e.controller)}getControllerForElementAndIdentifier(e,t){let s=this.router.getContextForElementAndIdentifier(e,t);return s?s.controller:null}handleError(e,t,s){var i;this.logger.error(`%s
|
|
30
30
|
|
|
31
31
|
%o
|
|
32
32
|
|
|
33
|
-
%o`,t,e,s),(i=window.onerror)===null||i===void 0||i.call(window,t,"",0,0,e)}logFormattedMessage(e,t,s={}){s=Object.assign({application:this},s),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},s)),this.logger.groupEnd()}};function Bi(){return new Promise(r=>{document.readyState=="loading"?document.addEventListener("DOMContentLoaded",()=>r()):r()})}function Ni(r){return de(r,"classes").reduce((t,s)=>Object.assign(t,qi(s)),{})}function qi(r){return{[`${r}Class`]:{get(){let{classes:e}=this;if(e.has(r))return e.get(r);{let t=e.getAttributeName(r);throw new Error(`Missing attribute "${t}"`)}}},[`${r}Classes`]:{get(){return this.classes.getAll(r)}},[`has${ue(r)}Class`]:{get(){return this.classes.has(r)}}}}function Di(r){return de(r,"outlets").reduce((t,s)=>Object.assign(t,xi(s)),{})}function Ws(r,e,t){return r.application.getControllerForElementAndIdentifier(e,t)}function js(r,e,t){let s=Ws(r,e,t);if(s||(r.application.router.proposeToConnectScopeForElementAndIdentifier(e,t),s=Ws(r,e,t),s))return s}function xi(r){let e=Tt(r);return{[`${e}Outlet`]:{get(){let t=this.outlets.find(r),s=this.outlets.getSelectorForOutletName(r);if(t){let i=js(this,t,r);if(i)return i;throw new Error(`The provided outlet element is missing an outlet controller "${r}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${r}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${e}Outlets`]:{get(){let t=this.outlets.findAll(r);return t.length>0?t.map(s=>{let i=js(this,s,r);if(i)return i;console.warn(`The provided outlet element is missing an outlet controller "${r}" instance for host controller "${this.identifier}"`,s)}).filter(s=>s):[]}},[`${e}OutletElement`]:{get(){let t=this.outlets.find(r),s=this.outlets.getSelectorForOutletName(r);if(t)return t;throw new Error(`Missing outlet element "${r}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${e}OutletElements`]:{get(){return this.outlets.findAll(r)}},[`has${ue(e)}Outlet`]:{get(){return this.outlets.has(r)}}}}function Vi(r){return de(r,"targets").reduce((t,s)=>Object.assign(t,Hi(s)),{})}function Hi(r){return{[`${r}Target`]:{get(){let e=this.targets.find(r);if(e)return e;throw new Error(`Missing target element "${r}" for "${this.identifier}" controller`)}},[`${r}Targets`]:{get(){return this.targets.findAll(r)}},[`has${ue(r)}Target`]:{get(){return this.targets.has(r)}}}}function $i(r){let e=Si(r,"values"),t={valueDescriptorMap:{get(){return e.reduce((s,i)=>{let n=Gs(i,this.identifier),o=this.data.getAttributeNameForKey(n.key);return Object.assign(s,{[o]:n})},{})}}};return e.reduce((s,i)=>Object.assign(s,_i(i)),t)}function _i(r,e){let t=Gs(r,e),{key:s,name:i,reader:n,writer:o}=t;return{[i]:{get(){let m=this.data.get(s);return m!==null?n(m):t.defaultValue},set(m){m===void 0?this.data.delete(s):this.data.set(s,o(m))}},[`has${ue(i)}`]:{get(){return this.data.has(s)||t.hasCustomDefaultValue}}}}function Gs([r,e],t){return Ki({controller:t,token:r,typeDefinition:e})}function Ve(r){switch(r){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function he(r){switch(typeof r){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}if(Array.isArray(r))return"array";if(Object.prototype.toString.call(r)==="[object Object]")return"object"}function Ui(r){let{controller:e,token:t,typeObject:s}=r,i=Hs(s.type),n=Hs(s.default),o=i&&n,m=i&&!n,w=!i&&n,C=Ve(s.type),k=he(r.typeObject.default);if(m)return C;if(w)return k;if(C!==k){let N=e?`${e}.${t}`:t;throw new Error(`The specified default value for the Stimulus Value "${N}" must match the defined type "${C}". The provided default value of "${s.default}" is of type "${k}".`)}if(o)return C}function Wi(r){let{controller:e,token:t,typeDefinition:s}=r,n=Ui({controller:e,token:t,typeObject:s}),o=he(s),m=Ve(s),w=n||o||m;if(w)return w;let C=e?`${e}.${s}`:t;throw new Error(`Unknown value type "${C}" for "${t}" value`)}function ji(r){let e=Ve(r);if(e)return Ks[e];let t=Lt(r,"default"),s=Lt(r,"type"),i=r;if(t)return i.default;if(s){let{type:n}=i,o=Ve(n);if(o)return Ks[o]}return r}function Ki(r){let{token:e,typeDefinition:t}=r,s=`${Js(e)}-value`,i=Wi(r);return{type:i,key:s,name:jt(s),get defaultValue(){return ji(t)},get hasCustomDefaultValue(){return he(t)!==void 0},reader:zi[i],writer:zs[i]||zs.default}}var Ks={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},zi={array(r){let e=JSON.parse(r);if(!Array.isArray(e))throw new TypeError(`expected value of type "array" but instead got value "${r}" of type "${he(e)}"`);return e},boolean(r){return!(r=="0"||String(r).toLowerCase()=="false")},number(r){return Number(r.replace(/_/g,""))},object(r){let e=JSON.parse(r);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`expected value of type "object" but instead got value "${r}" of type "${he(e)}"`);return e},string(r){return r}},zs={default:Xi,array:Xs,object:Xs};function Xs(r){return JSON.stringify(r)}function Xi(r){return`${r}`}var O=class{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:s={},prefix:i=this.identifier,bubbles:n=!0,cancelable:o=!0}={}){let m=i?`${i}:${e}`:e,w=new CustomEvent(m,{detail:s,bubbles:n,cancelable:o});return t.dispatchEvent(w),w}};O.blessings=[Ni,Vi,$i,Di];O.targets=[];O.outlets=[];O.values={};function Kt(r){return class extends r{static targets=["status","error"];static values={revision:Number,saving:{type:String,default:"Saving changes\u2026"},failed:{type:String,default:"Changes could not be saved. Review the message and try again."}};connect(){this.start=()=>{this.element.setAttribute("aria-busy","true"),this.hasStatusTarget&&(this.statusTarget.textContent=this.savingValue)},this.end=t=>{this.element.removeAttribute("aria-busy"),!t.detail.success&&this.hasStatusTarget&&(this.statusTarget.textContent=this.failedValue)},this.beforeStream=t=>{let s=t.target;if(s.getAttribute("target")!==this.element.id)return;let i=s.querySelector("template")?.content.firstElementChild,n=Number(i?.getAttribute("data-rails-tool-views-revision-value"));n&&n<this.revisionValue?t.preventDefault():i?.setAttribute("data-rails-tool-views-replaced","")},this.element.ownerDocument.addEventListener("turbo:before-stream-render",this.beforeStream),this.element.addEventListener("turbo:submit-start",this.start),this.element.addEventListener("turbo:submit-end",this.end);let e=this.element.hasAttribute("data-rails-tool-views-replaced");this.element.removeAttribute("data-rails-tool-views-replaced"),this.hasErrorTarget?this.errorTarget.focus({preventScroll:!0}):e&&this.hasStatusTarget&&this.statusTarget.focus({preventScroll:!0})}disconnect(){this.element.ownerDocument.removeEventListener("turbo:before-stream-render",this.beforeStream),this.element.removeEventListener("turbo:submit-start",this.start),this.element.removeEventListener("turbo:submit-end",this.end)}}}var Ji={leave_form:"Leave this form? Unsaved changes will be lost.",session_attention:"Your session needs attention. Sign in in another tab, then resume here. Unsaved input stays only in this open tab.",restored_partial:"Session restored. Some fields are no longer editable; their input was not restored. Review the form, then save explicitly.",restored:"Session restored. Your input is ready for review. Nothing has been saved; submit explicitly when ready.",return_changed:"Some list settings changed; return links use the current permitted list.",recovery_failed:"Recovery was not completed. Sign in as the original user and tenant, then try again. Changed records, permissions, schema, time zone, expired recovery windows or completed requests require a fresh form. This tab still holds your input; nothing was submitted again."};function re(r){try{let e=JSON.parse(document.body?.dataset.raaMessages||"{}")[r];if(typeof e=="string"&&e!=="")return e}catch{}return Ji[r]}var D=xe.start(),zt=class extends O{static values={restored:Boolean};connect(){this.dirty=this.restoredValue,this.warnUnload=e=>{this.dirty&&!this.submitting&&(e.preventDefault(),e.returnValue="")},this.warnVisit=e=>{this.dirty&&!this.submitting&&!window.confirm(re("leave_form"))&&e.preventDefault()},window.addEventListener("beforeunload",this.warnUnload),document.addEventListener("turbo:before-visit",this.warnVisit)}change(){this.dirty=!0}submit(){this.submitting=!0}pause(){this.submitting=!1,this.dirty=!0}finish(e){this.submitting=!1,e.detail.success&&(this.dirty=!1)}disconnect(){window.removeEventListener("beforeunload",this.warnUnload),document.removeEventListener("turbo:before-visit",this.warnVisit)}},Xt=class extends O{static targets=["notice","message","resume"];static values={url:String,intent:String,timeZone:String,fields:Array,returnState:String};connect(){this.paused=!1,this.pending=!1,this.abortController=new AbortController,this.blockSubmit=e=>{this.paused&&(e.preventDefault(),e.stopImmediatePropagation())},this.element.addEventListener("submit",this.blockSubmit,!0)}inspectResponse(e){let t=e.detail.fetchResponse.response,s=new URL(this.element.action,location.href);e.target!==this.element||s.origin!==location.origin||t.url!==s.href||t.redirected||t.headers.get("X-RailsAiAdmin-Form-Recovery")!=="session"||![401,422].includes(t.status)||(e.preventDefault(),this.paused=!0,this.pending=!0,this.element.querySelectorAll("input[type=submit], button[type=submit]").forEach(i=>{i.disabled=!0}),this.element.dispatchEvent(new CustomEvent("raa:form-paused",{bubbles:!0})),this.show(re("session_attention")))}finished(){this.pending=!1,this.paused&&(this.resumeTarget.disabled=!1,this.element.querySelectorAll("input[type=submit], button[type=submit]").forEach(e=>{e.disabled=!0}))}show(e){this.messageTarget.textContent=e,this.noticeTarget.hidden=!1,this.noticeTarget.focus()}snapshot(){let e=new Map,t=0;for(let[s,i]of new FormData(this.element))if(/^record\[[a-z][a-z0-9_]*\]$/.test(s)&&!(typeof File<"u"&&i instanceof File)){if(typeof i!="string")throw new Error("Unsupported form input");if(t+=new TextEncoder().encode(s+i).byteLength,t>1048576)throw new Error("Form input bound exceeded");if(e.set(s,i),e.size>128)throw new Error("Form input bound exceeded")}return e}async resume(){if(!(!this.paused||this.pending)){this.pending=!0,this.resumeTarget.disabled=!0;try{let e=new URL(this.urlValue,location.href);if(e.origin!==location.origin||e.search||e.hash)throw new Error("Invalid recovery path");let t=await fetch(e,{method:"GET",mode:"same-origin",credentials:"same-origin",redirect:"error",cache:"no-store",signal:this.abortController.signal,headers:{Accept:"text/html","X-RailsAiAdmin-Recovery-Intent":this.intentValue,"X-RailsAiAdmin-Return-State":this.returnStateValue}});if(!t.ok||t.redirected||t.url!==e.href||t.headers.get("X-RailsAiAdmin-Form-Recovery")!=="ready"||!t.headers.get("Content-Type")?.startsWith("text/html"))throw new Error("Recovery was not authorized");let s=await t.text();if(new TextEncoder().encode(s).byteLength>2097152)throw new Error("Form response bound exceeded");let i=new DOMParser().parseFromString(s,"text/html"),n=i.querySelector('form[data-controller~="raa-form-recovery"]');if(!n||n.querySelector('input[name="intent_ref"]')?.value!==this.intentValue||n.querySelector('input[name="_method"]')?.value!==this.element.querySelector('input[name="_method"]')?.value||n.dataset.raaFormRecoveryIntentValue!==this.intentValue||n.dataset.raaFormRecoveryTimeZoneValue!==this.timeZoneValue||new URL(n.getAttribute("action"),e).href!==this.element.action||n.method!==this.element.method)throw new Error("Form binding changed");if(!this.element.isConnected)return;let o=this.snapshot(),m=JSON.parse(n.dataset.raaFormRecoveryFieldsValue);if(!Array.isArray(m)||m.some(f=>typeof f!="string"||!/^[a-z][a-z0-9_]*$/.test(f)))throw new Error("Invalid form fields");let w=new Set;for(let f of n.elements){if(!m.some(b=>f.name===`record[${b}]`)||!o.has(f.name)||f.disabled||f.readOnly||!["INPUT","SELECT","TEXTAREA"].includes(f.tagName))continue;let A=o.get(f.name);if(!["file","submit","hidden","button","reset"].includes(f.type)){if(["checkbox","radio"].includes(f.type))f.checked=f.value===A;else{if(f.tagName==="SELECT"&&![...f.options].some(b=>b.value===A&&!b.disabled))continue;f.value=A}w.add(f.name)}}n.dataset.raaDirtyFormRestoredValue="true";let C=n.querySelector('[data-raa-form-recovery-target="notice"]');C.hidden=!1,C.querySelector('[data-raa-form-recovery-target="message"]').textContent=w.size<o.size?re("restored_partial"):re("restored"),n.dataset.raaFormRecoveryReturnDiscardedValue==="true"&&(C.querySelector('[data-raa-form-recovery-target="message"]').textContent+=" "+re("return_changed")),n.querySelector('[data-raa-form-recovery-target="resume"]').hidden=!0;let k=document.importNode(n,!0),N=i.querySelector('meta[name="csrf-token"]');N&&document.querySelector('meta[name="csrf-token"]')&&(document.querySelector('meta[name="csrf-token"]').content=N.content),this.element.replaceWith(k),requestAnimationFrame(()=>k.querySelector('[data-raa-form-recovery-target="notice"]').focus())}catch{this.element.isConnected&&this.show(re("recovery_failed"))}finally{this.pending=!1,this.element.isConnected&&(this.resumeTarget.disabled=!1)}}}disconnect(){this.abortController.abort(),this.element.removeEventListener("submit",this.blockSubmit,!0)}},Jt=class extends O{static targets=["list","tab","panel"];connect(){!this.hasListTarget||this.tabTargets.length<2||(this.listTarget.setAttribute("role","tablist"),this.tabTargets.forEach((e,t)=>{e.setAttribute("role","tab"),e.setAttribute("aria-controls",this.panelTargets[t].id),this.panelTargets[t].setAttribute("role","tabpanel"),this.panelTargets[t].setAttribute("aria-labelledby",e.id)}),this.activate(Math.max(0,this.panelTargets.findIndex(e=>e.querySelector('[aria-invalid="true"]')))),this.form=this.element.closest("form"),this.invalid=()=>{let e=this.form.querySelector("input:invalid, select:invalid, textarea:invalid");e&&this.showControl(e)},this.form?.addEventListener("invalid",this.invalid,!0))}activate(e,t=!1){this.tabTargets.forEach((s,i)=>{let n=i===e;s.setAttribute("aria-selected",String(n)),s.tabIndex=n?0:-1,this.panelTargets[i].hidden=!n}),t&&this.tabTargets[e].focus()}choose(e){e.preventDefault(),this.activate(this.tabTargets.indexOf(e.currentTarget))}keydown(e){let t=this.tabTargets.indexOf(e.currentTarget),s;e.key==="ArrowRight"&&(s=(t+1)%this.tabTargets.length),e.key==="ArrowLeft"&&(s=(t+this.tabTargets.length-1)%this.tabTargets.length),e.key==="Home"&&(s=0),e.key==="End"&&(s=this.tabTargets.length-1),(e.key===" "||e.key==="Enter")&&(s=t),s!==void 0&&(e.preventDefault(),this.activate(s,!0))}showControl(e){let t=this.panelTargets.findIndex(s=>s.contains(e));t>=0&&this.hasListTarget&&this.activate(t)}reveal(e){this.showControl(e.target)}disconnect(){this.form?.removeEventListener("invalid",this.invalid,!0),this.panelTargets.forEach(e=>{e.hidden=!1,e.removeAttribute("role"),e.removeAttribute("aria-labelledby")}),this.tabTargets.forEach(e=>{e.removeAttribute("role"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-selected"),e.removeAttribute("tabindex")}),this.hasListTarget&&this.listTarget.removeAttribute("role")}},Yt=class extends O{connect(){this.element.focus()}reveal(e){let t=document.getElementById(e.currentTarget.dataset.raaTargetField);!t||!this.element.closest("form")?.contains(t)||(e.preventDefault(),t.dispatchEvent(new CustomEvent("raa:reveal",{bubbles:!0})),t.focus())}},Zt=class extends O{static targets=["thread","latest","shortcut"];connect(){this.hasThreadTarget&&(this.following=!0,this.shortcutTarget.hidden=!1,this.follow())}track(){let e=this.threadTarget;this.following=e.scrollHeight-e.scrollTop-e.clientHeight<=48,this.latestTarget.hidden=this.following}follow(){this.following&&(this.threadTarget.scrollTop=this.threadTarget.scrollHeight)}jump(){this.following=!0,this.follow(),this.threadTarget.focus({preventScroll:!0}),this.latestTarget.hidden=!0}submitOnEnter(e){if(e.key!=="Enter"||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;e.preventDefault();let t=e.target;!e.repeat&&t.value.trim()&&t.form.getAttribute("aria-busy")!=="true"&&t.form.requestSubmit()}},Gt=class extends O{static values={url:String};connect(){this.loaded=()=>this.schedule(),this.changed=()=>this.schedule(1e3,!0),this.element.addEventListener("turbo:frame-load",this.loaded),this.element.addEventListener("turbo:submit-end",this.changed),this.schedule()}schedule(e=null,t=!1){clearTimeout(this.timer),!(!t&&!this.pending())&&(e===null&&(e=this.element.querySelector("[data-raa-pending=streaming]")?700:2e3),this.timer=setTimeout(()=>{this.element.getAttribute("src")?this.element.reload():this.element.setAttribute("src",this.urlValue)},e))}pending(){return this.element.querySelector("[data-raa-pending]")!==null}disconnect(){clearTimeout(this.timer),this.element.removeEventListener("turbo:frame-load",this.loaded),this.element.removeEventListener("turbo:submit-end",this.changed)}},Qt=class extends O{static targets=["submit","count","all"];static values={counts:Object};connect(){this.all=document.querySelector("[data-raa-select-all]"),this.all&&(this.all.hidden=!1),this.update=e=>{let t=[...document.querySelectorAll(`input[type="checkbox"][form="${this.element.id}"]`)];e?.target===this.all&&t.forEach(o=>{o.checked=this.all.checked});let s=t.filter(o=>o.checked).length;this.all&&(this.all.checked=t.length>0&&s===t.length,this.all.indeterminate=s>0&&s<t.length);let i=this.hasAllTarget&&this.allTarget.checked,n=i?Number(this.allTarget.dataset.count):s;if(this.submitTargets.forEach(o=>{o.disabled=n===0}),this.hasCountTarget){let o=i?this.countsValue.all:n===0?this.countsValue.none:n===1?this.countsValue.one:this.countsValue.other;o&&(this.countTarget.textContent=o.replace("%{count}",n))}},document.addEventListener("change",this.update),this.update()}disconnect(){document.removeEventListener("change",this.update)}},es=class extends O{refuse(e){e.preventDefault()}change(){this.element.dispatchEvent(new Event("input",{bubbles:!0}))}},ts=class extends O{static targets=["panel","query","status","results","current"];static values={url:String,key:String,messages:Object};connect(){this.key=document.getElementById(this.keyValue),this.key&&(this.panelTarget.hidden=!1,this.sequence=0)}disconnect(){clearTimeout(this.timer),this.abort?.abort()}keydown(e){e.key==="Enter"?(e.preventDefault(),this.resultsTarget.querySelector("button")?.focus()):e.key==="Escape"&&this.clear()}search(e){e.stopPropagation(),clearTimeout(this.timer),this.timer=setTimeout(()=>this.fetch(this.queryTarget.value.trim()),250)}async fetch(e){if(this.abort?.abort(),e===""){this.clear();return}let t=++this.sequence;this.abort=new AbortController,this.statusTarget.textContent=this.messagesValue.searching;try{let s=new URL(this.urlValue,location.href);s.searchParams.set("q",e);let i=await fetch(s,{headers:{Accept:"application/json"},credentials:"same-origin",signal:this.abort.signal});if(!i.ok||s.origin!==location.origin)throw new Error("search failed");let n=await i.json();t===this.sequence&&this.render(Array.isArray(n.results)?n.results:[])}catch(s){s.name!=="AbortError"&&t===this.sequence&&(this.resultsTarget.replaceChildren(),this.statusTarget.textContent=this.messagesValue.failed)}}render(e){let t=e.filter(i=>typeof i.id=="string"&&typeof i.label=="string").map(i=>{let n=document.createElement("li"),o=document.createElement("button");return o.type="button",o.textContent=i.label,o.addEventListener("click",()=>this.choose(i)),n.append(o),n});this.resultsTarget.replaceChildren(...t);let s=t.length===0?this.messagesValue.none:t.length===1?this.messagesValue.one:this.messagesValue.other;this.statusTarget.textContent=s.replace("%{count}",String(t.length))}choose(e){this.key.value=e.id,this.key.dispatchEvent(new Event("input",{bubbles:!0})),this.key.dispatchEvent(new Event("change",{bubbles:!0})),this.currentTarget.textContent=this.messagesValue.chosen.replace("%{label}",e.label),this.currentTarget.hidden=!1,this.clear(),this.key.focus()}clear(){clearTimeout(this.timer),this.queryTarget.value="",this.resultsTarget.replaceChildren(),this.statusTarget.textContent=""}},ss=class extends O{static targets=["toggle","menu"];connect(){this.toggleTarget.hidden=!1,this.element.classList.add("raa-menu-collapsible")}toggle(){let e=this.element.toggleAttribute("data-raa-menu-open");this.toggleTarget.setAttribute("aria-expanded",String(e))}};D.register("raa-menu",ss);D.register("raa-selection",Qt);D.register("raa-reference-picker",ts);D.register("raa-rich-text",es);D.register("rails-tool-views",Kt(O));D.register("raa-poll",Gt);D.register("raa-conversation",Zt);D.register("raa-form-recovery",Xt);D.register("raa-dirty-form",zt);D.register("raa-tabs",Jt);D.register("raa-error-summary",Yt);export{Vs as Turbo,D as application};
|
|
33
|
+
%o`,t,e,s),(i=window.onerror)===null||i===void 0||i.call(window,t,"",0,0,e)}logFormattedMessage(e,t,s={}){s=Object.assign({application:this},s),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},s)),this.logger.groupEnd()}};function Bi(){return new Promise(r=>{document.readyState=="loading"?document.addEventListener("DOMContentLoaded",()=>r()):r()})}function qi(r){return de(r,"classes").reduce((t,s)=>Object.assign(t,Ni(s)),{})}function Ni(r){return{[`${r}Class`]:{get(){let{classes:e}=this;if(e.has(r))return e.get(r);{let t=e.getAttributeName(r);throw new Error(`Missing attribute "${t}"`)}}},[`${r}Classes`]:{get(){return this.classes.getAll(r)}},[`has${ue(r)}Class`]:{get(){return this.classes.has(r)}}}}function Di(r){return de(r,"outlets").reduce((t,s)=>Object.assign(t,xi(s)),{})}function Ws(r,e,t){return r.application.getControllerForElementAndIdentifier(e,t)}function js(r,e,t){let s=Ws(r,e,t);if(s||(r.application.router.proposeToConnectScopeForElementAndIdentifier(e,t),s=Ws(r,e,t),s))return s}function xi(r){let e=Tt(r);return{[`${e}Outlet`]:{get(){let t=this.outlets.find(r),s=this.outlets.getSelectorForOutletName(r);if(t){let i=js(this,t,r);if(i)return i;throw new Error(`The provided outlet element is missing an outlet controller "${r}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${r}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${e}Outlets`]:{get(){let t=this.outlets.findAll(r);return t.length>0?t.map(s=>{let i=js(this,s,r);if(i)return i;console.warn(`The provided outlet element is missing an outlet controller "${r}" instance for host controller "${this.identifier}"`,s)}).filter(s=>s):[]}},[`${e}OutletElement`]:{get(){let t=this.outlets.find(r),s=this.outlets.getSelectorForOutletName(r);if(t)return t;throw new Error(`Missing outlet element "${r}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${e}OutletElements`]:{get(){return this.outlets.findAll(r)}},[`has${ue(e)}Outlet`]:{get(){return this.outlets.has(r)}}}}function Vi(r){return de(r,"targets").reduce((t,s)=>Object.assign(t,Hi(s)),{})}function Hi(r){return{[`${r}Target`]:{get(){let e=this.targets.find(r);if(e)return e;throw new Error(`Missing target element "${r}" for "${this.identifier}" controller`)}},[`${r}Targets`]:{get(){return this.targets.findAll(r)}},[`has${ue(r)}Target`]:{get(){return this.targets.has(r)}}}}function $i(r){let e=Si(r,"values"),t={valueDescriptorMap:{get(){return e.reduce((s,i)=>{let n=Gs(i,this.identifier),o=this.data.getAttributeNameForKey(n.key);return Object.assign(s,{[o]:n})},{})}}};return e.reduce((s,i)=>Object.assign(s,_i(i)),t)}function _i(r,e){let t=Gs(r,e),{key:s,name:i,reader:n,writer:o}=t;return{[i]:{get(){let m=this.data.get(s);return m!==null?n(m):t.defaultValue},set(m){m===void 0?this.data.delete(s):this.data.set(s,o(m))}},[`has${ue(i)}`]:{get(){return this.data.has(s)||t.hasCustomDefaultValue}}}}function Gs([r,e],t){return Ki({controller:t,token:r,typeDefinition:e})}function Ve(r){switch(r){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function he(r){switch(typeof r){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}if(Array.isArray(r))return"array";if(Object.prototype.toString.call(r)==="[object Object]")return"object"}function Ui(r){let{controller:e,token:t,typeObject:s}=r,i=Hs(s.type),n=Hs(s.default),o=i&&n,m=i&&!n,w=!i&&n,C=Ve(s.type),k=he(r.typeObject.default);if(m)return C;if(w)return k;if(C!==k){let q=e?`${e}.${t}`:t;throw new Error(`The specified default value for the Stimulus Value "${q}" must match the defined type "${C}". The provided default value of "${s.default}" is of type "${k}".`)}if(o)return C}function Wi(r){let{controller:e,token:t,typeDefinition:s}=r,n=Ui({controller:e,token:t,typeObject:s}),o=he(s),m=Ve(s),w=n||o||m;if(w)return w;let C=e?`${e}.${s}`:t;throw new Error(`Unknown value type "${C}" for "${t}" value`)}function ji(r){let e=Ve(r);if(e)return Ks[e];let t=Lt(r,"default"),s=Lt(r,"type"),i=r;if(t)return i.default;if(s){let{type:n}=i,o=Ve(n);if(o)return Ks[o]}return r}function Ki(r){let{token:e,typeDefinition:t}=r,s=`${Js(e)}-value`,i=Wi(r);return{type:i,key:s,name:jt(s),get defaultValue(){return ji(t)},get hasCustomDefaultValue(){return he(t)!==void 0},reader:zi[i],writer:zs[i]||zs.default}}var Ks={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},zi={array(r){let e=JSON.parse(r);if(!Array.isArray(e))throw new TypeError(`expected value of type "array" but instead got value "${r}" of type "${he(e)}"`);return e},boolean(r){return!(r=="0"||String(r).toLowerCase()=="false")},number(r){return Number(r.replace(/_/g,""))},object(r){let e=JSON.parse(r);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`expected value of type "object" but instead got value "${r}" of type "${he(e)}"`);return e},string(r){return r}},zs={default:Xi,array:Xs,object:Xs};function Xs(r){return JSON.stringify(r)}function Xi(r){return`${r}`}var O=class{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:s={},prefix:i=this.identifier,bubbles:n=!0,cancelable:o=!0}={}){let m=i?`${i}:${e}`:e,w=new CustomEvent(m,{detail:s,bubbles:n,cancelable:o});return t.dispatchEvent(w),w}};O.blessings=[qi,Vi,$i,Di];O.targets=[];O.outlets=[];O.values={};function Kt(r){return class extends r{static targets=["status","error"];static values={revision:Number,saving:{type:String,default:"Saving changes\u2026"},failed:{type:String,default:"Changes could not be saved. Review the message and try again."}};connect(){this.start=()=>{this.element.setAttribute("aria-busy","true"),this.hasStatusTarget&&(this.statusTarget.textContent=this.savingValue)},this.end=t=>{this.element.removeAttribute("aria-busy"),!t.detail.success&&this.hasStatusTarget&&(this.statusTarget.textContent=this.failedValue)},this.beforeStream=t=>{let s=t.target;if(s.getAttribute("target")!==this.element.id)return;let i=s.querySelector("template")?.content.firstElementChild,n=Number(i?.getAttribute("data-rails-tool-views-revision-value"));n&&n<this.revisionValue?t.preventDefault():i?.setAttribute("data-rails-tool-views-replaced","")},this.element.ownerDocument.addEventListener("turbo:before-stream-render",this.beforeStream),this.element.addEventListener("turbo:submit-start",this.start),this.element.addEventListener("turbo:submit-end",this.end);let e=this.element.hasAttribute("data-rails-tool-views-replaced");this.element.removeAttribute("data-rails-tool-views-replaced"),this.hasErrorTarget?this.errorTarget.focus({preventScroll:!0}):e&&this.hasStatusTarget&&this.statusTarget.focus({preventScroll:!0})}disconnect(){this.element.ownerDocument.removeEventListener("turbo:before-stream-render",this.beforeStream),this.element.removeEventListener("turbo:submit-start",this.start),this.element.removeEventListener("turbo:submit-end",this.end)}}}var Ji={leave_form:"Leave this form? Unsaved changes will be lost.",session_attention:"Your session needs attention. Sign in in another tab, then resume here. Unsaved input stays only in this open tab.",restored_partial:"Session restored. Some fields are no longer editable; their input was not restored. Review the form, then save explicitly.",restored:"Session restored. Your input is ready for review. Nothing has been saved; submit explicitly when ready.",return_changed:"Some list settings changed; return links use the current permitted list.",recovery_failed:"Recovery was not completed. Sign in as the original user and tenant, then try again. Changed records, permissions, schema, time zone, expired recovery windows or completed requests require a fresh form. This tab still holds your input; nothing was submitted again."};function re(r){try{let e=JSON.parse(document.body?.dataset.raaMessages||"{}")[r];if(typeof e=="string"&&e!=="")return e}catch{}return Ji[r]}var D=xe.start(),zt=class extends O{static values={restored:Boolean};connect(){this.dirty=this.restoredValue,this.warnUnload=e=>{this.dirty&&!this.submitting&&(e.preventDefault(),e.returnValue="")},this.warnVisit=e=>{this.dirty&&!this.submitting&&!window.confirm(re("leave_form"))&&e.preventDefault()},window.addEventListener("beforeunload",this.warnUnload),document.addEventListener("turbo:before-visit",this.warnVisit)}change(){this.dirty=!0}submit(){this.submitting=!0}pause(){this.submitting=!1,this.dirty=!0}finish(e){this.submitting=!1,e.detail.success&&(this.dirty=!1)}disconnect(){window.removeEventListener("beforeunload",this.warnUnload),document.removeEventListener("turbo:before-visit",this.warnVisit)}},Xt=class extends O{static targets=["notice","message","resume"];static values={url:String,intent:String,timeZone:String,fields:Array,returnState:String};connect(){this.paused=!1,this.pending=!1,this.abortController=new AbortController,this.blockSubmit=e=>{this.paused&&(e.preventDefault(),e.stopImmediatePropagation())},this.element.addEventListener("submit",this.blockSubmit,!0)}inspectResponse(e){let t=e.detail.fetchResponse.response,s=new URL(this.element.action,location.href);e.target!==this.element||s.origin!==location.origin||t.url!==s.href||t.redirected||t.headers.get("X-RailsAiAdmin-Form-Recovery")!=="session"||![401,422].includes(t.status)||(e.preventDefault(),this.paused=!0,this.pending=!0,this.element.querySelectorAll("input[type=submit], button[type=submit]").forEach(i=>{i.disabled=!0}),this.element.dispatchEvent(new CustomEvent("raa:form-paused",{bubbles:!0})),this.show(re("session_attention")))}finished(){this.pending=!1,this.paused&&(this.resumeTarget.disabled=!1,this.element.querySelectorAll("input[type=submit], button[type=submit]").forEach(e=>{e.disabled=!0}))}show(e){this.messageTarget.textContent=e,this.noticeTarget.hidden=!1,this.noticeTarget.focus()}snapshot(){let e=new Map,t=0;for(let[s,i]of new FormData(this.element)){let n=/^record\[([a-z][a-z0-9_]*)\](\[\])?$/.exec(s);if(n&&!(typeof File<"u"&&i instanceof File)){if(typeof i!="string")throw new Error("Unsupported form input");if(t+=new TextEncoder().encode(s+i).byteLength,t>1048576)throw new Error("Form input bound exceeded");if(n[2]){let o=e.get(s)||[];i!==""&&o.push(i),e.set(s,o)}else e.set(s,i);if(e.size>128)throw new Error("Form input bound exceeded")}}return e}async resume(){if(!(!this.paused||this.pending)){this.pending=!0,this.resumeTarget.disabled=!0;try{let e=new URL(this.urlValue,location.href);if(e.origin!==location.origin||e.search||e.hash)throw new Error("Invalid recovery path");let t=await fetch(e,{method:"GET",mode:"same-origin",credentials:"same-origin",redirect:"error",cache:"no-store",signal:this.abortController.signal,headers:{Accept:"text/html","X-RailsAiAdmin-Recovery-Intent":this.intentValue,"X-RailsAiAdmin-Return-State":this.returnStateValue}});if(!t.ok||t.redirected||t.url!==e.href||t.headers.get("X-RailsAiAdmin-Form-Recovery")!=="ready"||!t.headers.get("Content-Type")?.startsWith("text/html"))throw new Error("Recovery was not authorized");let s=await t.text();if(new TextEncoder().encode(s).byteLength>2097152)throw new Error("Form response bound exceeded");let i=new DOMParser().parseFromString(s,"text/html"),n=i.querySelector('form[data-controller~="raa-form-recovery"]');if(!n||n.querySelector('input[name="intent_ref"]')?.value!==this.intentValue||n.querySelector('input[name="_method"]')?.value!==this.element.querySelector('input[name="_method"]')?.value||n.dataset.raaFormRecoveryIntentValue!==this.intentValue||n.dataset.raaFormRecoveryTimeZoneValue!==this.timeZoneValue||new URL(n.getAttribute("action"),e).href!==this.element.action||n.method!==this.element.method)throw new Error("Form binding changed");if(!this.element.isConnected)return;let o=this.snapshot(),m=JSON.parse(n.dataset.raaFormRecoveryFieldsValue);if(!Array.isArray(m)||m.some(d=>typeof d!="string"||!/^[a-z][a-z0-9_]*$/.test(d)))throw new Error("Invalid form fields");let w=new Set;for(let d of n.elements){let A=m.some(g=>d.name===`record[${g}][]`),y=!A&&m.some(g=>d.name===`record[${g}]`);if(!A&&!y||!o.has(d.name)||d.disabled||d.readOnly||!["INPUT","SELECT","TEXTAREA"].includes(d.tagName))continue;let E=o.get(d.name),S=d.type==="hidden"&&d.id&&n.querySelector(`trix-editor[input="${CSS.escape(d.id)}"]`);if(!(["file","submit","button","reset"].includes(d.type)||d.type==="hidden"&&!S)){if(A&&Array.isArray(E)){d.type==="checkbox"&&(d.checked=E.includes(d.value),w.add(d.name));continue}if(["checkbox","radio"].includes(d.type))d.checked=d.value===E;else{if(d.tagName==="SELECT"&&![...d.options].some(g=>g.value===E&&!g.disabled))continue;d.value=E}w.add(d.name)}}n.dataset.raaDirtyFormRestoredValue="true";let C=n.querySelector('[data-raa-form-recovery-target="notice"]');C.hidden=!1,C.querySelector('[data-raa-form-recovery-target="message"]').textContent=w.size<o.size?re("restored_partial"):re("restored"),n.dataset.raaFormRecoveryReturnDiscardedValue==="true"&&(C.querySelector('[data-raa-form-recovery-target="message"]').textContent+=" "+re("return_changed")),n.querySelector('[data-raa-form-recovery-target="resume"]').hidden=!0;let k=document.importNode(n,!0),q=i.querySelector('meta[name="csrf-token"]');q&&document.querySelector('meta[name="csrf-token"]')&&(document.querySelector('meta[name="csrf-token"]').content=q.content),this.element.replaceWith(k),requestAnimationFrame(()=>k.querySelector('[data-raa-form-recovery-target="notice"]').focus())}catch{this.element.isConnected&&this.show(re("recovery_failed"))}finally{this.pending=!1,this.element.isConnected&&(this.resumeTarget.disabled=!1)}}}disconnect(){this.abortController.abort(),this.element.removeEventListener("submit",this.blockSubmit,!0)}},Jt=class extends O{static targets=["list","tab","panel"];connect(){!this.hasListTarget||this.tabTargets.length<2||(this.listTarget.setAttribute("role","tablist"),this.tabTargets.forEach((e,t)=>{e.setAttribute("role","tab"),e.setAttribute("aria-controls",this.panelTargets[t].id),this.panelTargets[t].setAttribute("role","tabpanel"),this.panelTargets[t].setAttribute("aria-labelledby",e.id)}),this.activate(Math.max(0,this.panelTargets.findIndex(e=>e.querySelector('[aria-invalid="true"]')))),this.form=this.element.closest("form"),this.invalid=()=>{let e=this.form.querySelector("input:invalid, select:invalid, textarea:invalid");e&&this.showControl(e)},this.form?.addEventListener("invalid",this.invalid,!0))}activate(e,t=!1){this.tabTargets.forEach((s,i)=>{let n=i===e;s.setAttribute("aria-selected",String(n)),s.tabIndex=n?0:-1,this.panelTargets[i].hidden=!n}),t&&this.tabTargets[e].focus()}choose(e){e.preventDefault(),this.activate(this.tabTargets.indexOf(e.currentTarget))}keydown(e){let t=this.tabTargets.indexOf(e.currentTarget),s;e.key==="ArrowRight"&&(s=(t+1)%this.tabTargets.length),e.key==="ArrowLeft"&&(s=(t+this.tabTargets.length-1)%this.tabTargets.length),e.key==="Home"&&(s=0),e.key==="End"&&(s=this.tabTargets.length-1),(e.key===" "||e.key==="Enter")&&(s=t),s!==void 0&&(e.preventDefault(),this.activate(s,!0))}showControl(e){let t=this.panelTargets.findIndex(s=>s.contains(e));t>=0&&this.hasListTarget&&this.activate(t)}reveal(e){this.showControl(e.target)}disconnect(){this.form?.removeEventListener("invalid",this.invalid,!0),this.panelTargets.forEach(e=>{e.hidden=!1,e.removeAttribute("role"),e.removeAttribute("aria-labelledby")}),this.tabTargets.forEach(e=>{e.removeAttribute("role"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-selected"),e.removeAttribute("tabindex")}),this.hasListTarget&&this.listTarget.removeAttribute("role")}},Yt=class extends O{connect(){this.element.focus()}reveal(e){let t=document.getElementById(e.currentTarget.dataset.raaTargetField);!t||!this.element.closest("form")?.contains(t)||(e.preventDefault(),t.dispatchEvent(new CustomEvent("raa:reveal",{bubbles:!0})),t.focus())}},Zt=class extends O{static targets=["thread","latest","shortcut"];connect(){this.hasThreadTarget&&(this.following=!0,this.shortcutTarget.hidden=!1,this.follow())}track(){let e=this.threadTarget;this.following=e.scrollHeight-e.scrollTop-e.clientHeight<=48,this.latestTarget.hidden=this.following}follow(){this.following&&(this.threadTarget.scrollTop=this.threadTarget.scrollHeight)}jump(){this.following=!0,this.follow(),this.threadTarget.focus({preventScroll:!0}),this.latestTarget.hidden=!0}submitOnEnter(e){if(e.key!=="Enter"||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.isComposing||e.keyCode===229)return;e.preventDefault();let t=e.target;!e.repeat&&t.value.trim()&&t.form.getAttribute("aria-busy")!=="true"&&t.form.requestSubmit()}},Gt=class extends O{static values={url:String};connect(){this.loaded=()=>this.schedule(),this.changed=()=>this.schedule(1e3,!0),this.element.addEventListener("turbo:frame-load",this.loaded),this.element.addEventListener("turbo:submit-end",this.changed),this.schedule()}schedule(e=null,t=!1){clearTimeout(this.timer),!(!t&&!this.pending())&&(e===null&&(e=this.element.querySelector("[data-raa-pending=streaming]")?700:2e3),this.timer=setTimeout(()=>{this.element.getAttribute("src")?this.element.reload():this.element.setAttribute("src",this.urlValue)},e))}pending(){return this.element.querySelector("[data-raa-pending]")!==null}disconnect(){clearTimeout(this.timer),this.element.removeEventListener("turbo:frame-load",this.loaded),this.element.removeEventListener("turbo:submit-end",this.changed)}},Qt=class extends O{static targets=["submit","count","all"];static values={counts:Object};connect(){this.all=document.querySelector("[data-raa-select-all]"),this.all&&(this.all.hidden=!1),this.update=e=>{let t=[...document.querySelectorAll(`input[type="checkbox"][form="${this.element.id}"]`)];e?.target===this.all&&t.forEach(o=>{o.checked=this.all.checked});let s=t.filter(o=>o.checked).length;this.all&&(this.all.checked=t.length>0&&s===t.length,this.all.indeterminate=s>0&&s<t.length);let i=this.hasAllTarget&&this.allTarget.checked,n=i?Number(this.allTarget.dataset.count):s;if(this.submitTargets.forEach(o=>{o.disabled=n===0}),this.hasCountTarget){let o=i?this.countsValue.all:n===0?this.countsValue.none:n===1?this.countsValue.one:this.countsValue.other;o&&(this.countTarget.textContent=o.replace("%{count}",n))}},document.addEventListener("change",this.update),this.update()}disconnect(){document.removeEventListener("change",this.update)}},es=class extends O{refuse(e){e.preventDefault()}change(){this.element.dispatchEvent(new Event("input",{bubbles:!0}))}},ts=class extends O{static targets=["panel","query","status","results","current"];static values={url:String,key:String,messages:Object};connect(){this.key=document.getElementById(this.keyValue),this.key&&(this.panelTarget.hidden=!1,this.sequence=0)}disconnect(){clearTimeout(this.timer),this.abort?.abort()}keydown(e){e.key==="Enter"?(e.preventDefault(),this.resultsTarget.querySelector("button")?.focus()):e.key==="Escape"&&this.clear()}search(e){e.stopPropagation(),clearTimeout(this.timer),this.timer=setTimeout(()=>this.fetch(this.queryTarget.value.trim()),250)}async fetch(e){if(this.abort?.abort(),e===""){this.clear();return}let t=++this.sequence;this.abort=new AbortController,this.statusTarget.textContent=this.messagesValue.searching;try{let s=new URL(this.urlValue,location.href);if(s.origin!==location.origin)throw new Error("search failed");s.searchParams.set("q",e);let i=await fetch(s,{headers:{Accept:"application/json"},credentials:"same-origin",signal:this.abort.signal});if(!i.ok)throw new Error("search failed");let n=await i.json();t===this.sequence&&this.render(Array.isArray(n.results)?n.results:[])}catch(s){s.name!=="AbortError"&&t===this.sequence&&(this.resultsTarget.replaceChildren(),this.statusTarget.textContent=this.messagesValue.failed)}}render(e){let t=e.filter(i=>typeof i.id=="string"&&typeof i.label=="string").map(i=>{let n=document.createElement("li"),o=document.createElement("button");return o.type="button",o.textContent=i.label,o.addEventListener("click",()=>this.choose(i)),n.append(o),n});this.resultsTarget.replaceChildren(...t);let s=t.length===0?this.messagesValue.none:t.length===1?this.messagesValue.one:this.messagesValue.other;this.statusTarget.textContent=s.replace("%{count}",String(t.length))}choose(e){this.key.value=e.id,this.key.dispatchEvent(new Event("input",{bubbles:!0})),this.key.dispatchEvent(new Event("change",{bubbles:!0})),this.currentTarget.textContent=this.messagesValue.chosen.replace("%{label}",()=>e.label),this.currentTarget.hidden=!1,this.clear(),this.key.focus()}clear(){clearTimeout(this.timer),this.queryTarget.value="",this.resultsTarget.replaceChildren(),this.statusTarget.textContent=""}},ss=class extends O{static targets=["toggle","menu"];connect(){this.toggleTarget.hidden=!1,this.element.classList.add("raa-menu-collapsible")}toggle(){let e=this.element.toggleAttribute("data-raa-menu-open");this.toggleTarget.setAttribute("aria-expanded",String(e))}};D.register("raa-menu",ss);D.register("raa-selection",Qt);D.register("raa-reference-picker",ts);D.register("raa-rich-text",es);D.register("rails-tool-views",Kt(O));D.register("raa-poll",Gt);D.register("raa-conversation",Zt);D.register("raa-form-recovery",Xt);D.register("raa-dirty-form",zt);D.register("raa-tabs",Jt);D.register("raa-error-summary",Yt);export{Vs as Turbo,D as application};
|