phlex-reactive 0.11.4 → 0.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{Controller as Xj}from"@hotwired/stimulus";import{confirmResolver as b}from"phlex/reactive/confirm";import{computeReducer as Zj}from"phlex/reactive/compute";import{confirmPredicate as $j}from"phlex/reactive/confirm_predicate";function Jj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:visit"])return;j["reactive:visit"]=function(){let X=this.getAttribute("data-url");if(X)window.Turbo.visit(X,{action:"advance"})}}function Qj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:token"])return;j["reactive:token"]=function(){let X=this.getAttribute("data-reactive-token-value"),Z=this.getAttribute("target");if(!X||!Z)return;let $=document.getElementById(Z);if($)$.setAttribute("data-reactive-token-value",X)}}function Gj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:js"])return;j["reactive:js"]=function(){let X=e(this.getAttribute("data-reactive-ops"));if(!X.length)return;let Z=this.getAttribute("target"),$=Z?document.getElementById(Z):null;if(Z&&!$)return;jj(X,(J)=>wj(J,$))}}var V=new Map;function p(j,X){let Z=!V.has(j);if(V.set(j,X),Z)l()}function O(j){if(V.delete(j))o()}function fj(){V.clear(),T=!1}function pj(j){return V.get(j)?.via}var T=!1;function zj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:defer"])return;if(j["reactive:defer"]=function(){let X=this.getAttribute("target");if(!X)return;if(this.getAttribute("data-reactive-defer-via")==="stream"){qj(X,this);return}let Z=this.getAttribute("data-reactive-defer-token");if(!Z)return;P(X,Z)},!T&&typeof document<"u"&&document.addEventListener)T=!0,document.addEventListener("turbo:before-stream-render",Kj)}function Kj(j){let Z=j.target?.getAttribute?.("target");if(!Z)return;let $=Z.startsWith("reactive-defer-src-")?Z.slice(19):Z;if(V.get($)?.via==="stream")O($)}function P(j,X){let Z=document.getElementById(j);if(!Z){console.warn(`[phlex-reactive] reactive:defer target #${j} is not on the page — skipped`);return}m(j),g(Z);let $={via:"fetch",abort:new AbortController,timedOut:!1};p(j,$),Yj(j,$,X)}function qj(j,X){let Z=document.getElementById(j);if(!Z){console.warn(`[phlex-reactive] reactive:defer target #${j} is not on the page — skipped`);return}let $=X.getAttribute("data-reactive-defer-src");if(!$)return;if(!globalThis.customElements?.get?.("pgbus-stream-source")){let Q=X.getAttribute("data-reactive-defer-token");if(Q){P(j,Q);return}console.error("[phlex-reactive] reactive:defer via=stream but <pgbus-stream-source> is not registered "+"and no fallback token was provided — is the pgbus client loaded on this page?");return}m(j),g(Z);let J=document.createElement("pgbus-stream-source");J.id=u(j),J.setAttribute("src",$),J.setAttribute("since-id",X.getAttribute("data-reactive-defer-since-id")??"0"),J.setAttribute("hidden",""),document.body.appendChild(J),p(j,{via:"stream"})}function u(j){return`reactive-defer-src-${j}`}async function Yj(j,X,Z){let $=setTimeout(()=>{X.timedOut=!0,X.abort.abort()},Wj()),J;try{J=await fetch(Uj(),{method:"POST",headers:{Accept:"text/vnd.turbo-stream.html","Content-Type":"application/json","X-CSRF-Token":Hj()},body:JSON.stringify({token:Z}),credentials:"same-origin",signal:X.abort.signal})}catch(G){if(clearTimeout($),V.get(j)!==X)return;console.error("[phlex-reactive] deferred render failed",G),F(j,Z);return}if(V.get(j)!==X){clearTimeout($);return}if(J.status===204){clearTimeout($),h(j);return}if(!J.ok){clearTimeout($),console.error(`[phlex-reactive] deferred render failed: HTTP ${J.status}`),F(j,Z,J.status);return}let Q;try{Q=await J.text()}catch(G){if(clearTimeout($),V.get(j)!==X)return;console.error("[phlex-reactive] deferred render failed reading the body",G),F(j,Z);return}if(clearTimeout($),V.get(j)!==X)return;h(j),window.Turbo.renderStreamMessage(Q)}function m(j){let X=V.get(j);if(!X)return;if(O(j),X.via==="fetch")X.abort.abort();else document.getElementById(u(j))?.remove?.()}function g(j){j.setAttribute("data-reactive-defer-pending","true"),j.setAttribute("aria-busy","true")}function c(j){j.removeAttribute("data-reactive-defer-pending"),j.removeAttribute("aria-busy")}function h(j){O(j);let X=document.getElementById(j);if(!X)return;c(X),X.removeAttribute("data-reactive-error")}function F(j,X,Z){O(j);let $=document.getElementById(j);if(!$)return;c($),$.setAttribute("data-reactive-error","defer");let J=()=>{let Q=document.getElementById(j);if(!Q){console.warn("[phlex-reactive] defer retry() ignored — the target left the DOM");return}Q.removeAttribute("data-reactive-error"),P(j,X)};$.dispatchEvent(new CustomEvent("reactive:error",{bubbles:!0,composed:!0,detail:{kind:"defer",target:j,status:Z,retry:J}}))}function Uj(){return document.querySelector('meta[name="phlex-reactive-defer-path"]')?.content||"/reactive/defer"}function Hj(){return document.querySelector('meta[name="csrf-token"]')?.content??""}function Wj(){let j=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,X=Number(j);return Number.isFinite(X)&&X>0?X:30000}var I=!1;function _j(){if(I)return;if(typeof document>"u"||!document.addEventListener)return;I=!0,document.addEventListener("turbo:before-stream-render",Lj)}function Lj(j){let X=j.detail,Z=X?.render;if(typeof Z!=="function"||Z.__reactiveDismissWrapped){if(typeof requestAnimationFrame==="function")requestAnimationFrame(C);else setTimeout(C,0);return}let $=async(J)=>{await Z(J),C()};$.__reactiveDismissWrapped=!0,X.render=$}function C(){let j=document.querySelectorAll("[data-reactive-dismiss-after]");for(let X of j){if(X.hasAttribute("data-reactive-dismiss-scheduled"))continue;let Z=Number(X.getAttribute("data-reactive-dismiss-after"));if(!Number.isFinite(Z)||Z<=0)continue;X.setAttribute("data-reactive-dismiss-scheduled",""),setTimeout(()=>X.remove(),Z)}}function uj(){I=!1}var k=!1;function Nj(){if(k)return;if(typeof window>"u"||typeof document>"u")return;if(typeof window.addEventListener!=="function")return;k=!0;let j=()=>{let X=document.documentElement;if(typeof X?.toggleAttribute!=="function")return;X.toggleAttribute("data-reactive-offline",globalThis.navigator?.onLine===!1)};j(),window.addEventListener("online",j),window.addEventListener("offline",j)}function mj(){k=!1}var S="phlex-reactive:latency",x=!1;function Vj(j){if(typeof sessionStorage>"u")return;sessionStorage.setItem(S,String(j))}function Mj(){if(typeof sessionStorage>"u")return;sessionStorage.removeItem(S),x=!1}function Aj(){if(typeof window>"u"||typeof document>"u")return;if(document.querySelector?.('meta[name="phlex-reactive-env"]')?.content!=="development")return;window.PhlexReactive={enableLatencySim:Vj,disableLatencySim:Mj}}function gj(){x=!1}var d="data-reactive-active",M=0;function l(){if(M++,M===1)s("reactive:busy")}function o(){if(M===0)return;if(M--,M===0)s("reactive:idle")}function cj(){return M}function dj(){M=0,(typeof document<"u"?document.documentElement:null)?.removeAttribute?.(d)}function s(j){if(typeof document>"u")return;let X=document.documentElement;if(typeof X?.toggleAttribute==="function")X.toggleAttribute(d,M>0);if(typeof document.dispatchEvent==="function"&&typeof CustomEvent==="function")document.dispatchEvent(new CustomEvent(j,{detail:{count:M}}))}function y(){Jj(),Qj(),Gj(),zj(),_j(),Nj(),Aj()}function Bj(j){return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}if(typeof window<"u")if(window.Turbo)y();else document.addEventListener("turbo:load",y,{once:!0});var E=!1;function xj(){if(E)return;if(typeof document>"u")return;let j=document.querySelectorAll('[data-controller~="reactive"]');if(!j||j.length===0)return;console.warn("[phlex-reactive] found "+j.length+' element(s) with data-controller="reactive" '+"but the reactive controller never connected. It is loaded but not registered — "+'add `application.register("reactive", ReactiveController)` (importmap) or import it into app/javascript/controllers/ for lazyLoadControllersFrom apps. See the README.')}function lj(){E=!1}function oj(){E=!0}if(typeof window<"u"&&typeof document<"u"){let j=()=>setTimeout(xj,0);if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",j,{once:!0});else j()}var Oj=new Set(["href","src","srcdoc","action","formaction","xlink:href","style"]);function Pj(j){let X=String(j).toLowerCase();return X.startsWith("on")||Oj.has(X)}function Ej(j,X,Z){let[$,J,Q]=X;j.classList.add($,J),Z(),requestAnimationFrame(()=>{j.classList.remove(J),j.classList.add(Q)});let G=!1,K=()=>{if(G)return;G=!0,j.classList.remove($,Q)};j.addEventListener("animationend",K,{once:!0}),setTimeout(K,350)}var v=Object.freeze({show:(j,X)=>R(j,!1,X),hide:(j,X)=>R(j,!0,X),toggle:(j,X)=>R(j,!j.hidden,X),add_class:(j,X)=>j.classList.add(...X.classes??[]),remove_class:(j,X)=>j.classList.remove(...X.classes??[]),toggle_class:(j,X)=>(X.classes??[]).forEach((Z)=>j.classList.toggle(Z)),set_attr:(j,X)=>{if(D(X.name))j.setAttribute(X.name,X.value??"")},remove_attr:(j,X)=>{if(D(X.name))j.removeAttribute(X.name)},toggle_attr:(j,X)=>{if(!D(X.name))return;if(j.hasAttribute(X.name))j.removeAttribute(X.name);else j.setAttribute(X.name,"")},focus:(j)=>j.focus?.(),focus_first:(j)=>Sj(j)?.focus?.(),text:(j,X)=>{let Z=String(X.value??"");if(j.textContent!==Z)j.textContent=Z},dispatch:(j,X)=>{j.dispatchEvent(new CustomEvent(X.name,{bubbles:!0,composed:!0,detail:X.detail??{}}))}});function R(j,X,Z){if(Z?.transition)Ej(j,Z.transition,()=>j.hidden=X);else j.hidden=X}function D(j){if(!Pj(j))return!0;return console.warn(`[phlex-reactive] refused client attr op on ${JSON.stringify(j)} — skipped`),!1}var i=/^#[A-Za-z_][\w-]*$/;function Fj(j){if(typeof j==="string"&&i.test(j))return!0;return console.warn(`[phlex-reactive] refused cross-root mirror target ${JSON.stringify(j)} — skipped`),!1}function Cj(j,X){let Z=j.getAttribute("data-reactive-show-equals");if(Z!==null)return X===Z;let $=j.getAttribute("data-reactive-show-not");if($!==null)return X!==$;let J=j.getAttribute("data-reactive-show-in");if(J!==null){try{let Q=JSON.parse(J);if(Array.isArray(Q))return Q.includes(X)}catch{}return console.warn(`[phlex-reactive] malformed reactive_show in: list ${JSON.stringify(J)} — skipped`),null}for(let Q of n){let G=j.getAttribute(`data-reactive-show-${Q}`);if(G!==null)return a(Q,G,X)}return console.warn("[phlex-reactive] a reactive_show binding declares no predicate — skipped"),null}var n=["gte","gt","lte","lt"];function a(j,X,Z){let $=Number(X);if(Number.isNaN($))return console.warn(`[phlex-reactive] reactive_show ${j}: needs a numeric literal, got ${JSON.stringify(X)} — skipped`),null;let J=Z==null?"":String(Z).trim(),Q=J===""?NaN:Number(J);if(Number.isNaN(Q))return!1;switch(j){case"gte":return Q>=$;case"gt":return Q>$;case"lte":return Q<=$;case"lt":return Q<$;default:return null}}function r(j,X){if(!j||typeof j!=="object")return null;if(typeof j.equals==="string")return X===j.equals;if(typeof j.not==="string")return X!==j.not;if(Array.isArray(j.in))return j.in.includes(X);for(let Z of n)if(Z in j)return a(Z,j[Z],X);return null}var f="[data-reactive-show-field], [data-reactive-show]";function Rj(j){try{let X=JSON.parse(j);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return console.warn(`[phlex-reactive] malformed compound reactive_show payload ${JSON.stringify(j)} — skipped`),null}function w(j,X){if(!j||typeof j!=="object"||typeof j.field!=="string")return!1;let Z=X(j.field)??"";return r(j,Z)===!0}function t(j,X){if(!Array.isArray(j)||j.length===0)return null;return j.some((Z)=>Array.isArray(Z)&&Z.length>0&&Z.every(($)=>w($,X)))}function Dj(j,X){if(!j||typeof j!=="object")return null;let Z=j.any;if(Array.isArray(Z)&&(Z.length===0||Array.isArray(Z[0])))return t(Z,X);return Tj(j,X)}function Tj(j,X){let Z=Array.isArray(j.all)?"all":Array.isArray(j.any)?"any":null;if(!Z)return null;let $=j[Z];if($.length===0)return null;let J=$.map((Q)=>w(Q,X));return Z==="all"?J.every(Boolean):J.some(Boolean)}function Ij(j){if(typeof j==="string"&&i.test(j))return!0;return console.warn(`[phlex-reactive] refused cross-root show target ${JSON.stringify(j)} — skipped`),!1}var kj='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Sj(j){return j.querySelectorAll?.(kj)?.[0]??null}function e(j){if(Array.isArray(j))return j;if(typeof j!=="string")return[];try{let X=JSON.parse(j);return Array.isArray(X)?X:[]}catch{return[]}}function jj(j,X){for(let Z of j){if(!Array.isArray(Z))continue;let[$,J={}]=Z;if(!Object.hasOwn(v,$)){console.warn(`[phlex-reactive] unknown client op ${JSON.stringify($)} — skipped`);continue}for(let Q of X(J))v[$](Q,J)}}function wj(j,X){let Z=j.to;if(X){if(Z==="@root")return[X];if(typeof Z!=="string"||Z==="")return[];if(j.global)return[...document.querySelectorAll(Z)];return[...X.querySelectorAll(Z)]}if(typeof Z!=="string"||Z===""||Z==="@root")return[];return[...document.querySelectorAll(Z)]}class sj extends Xj{static values={token:String};#b;#V=new Map;#q=new Map;#Kj;#F;#h;#C=0;#Y=new Map;#R=new WeakMap;#M=new Map;#y=new WeakSet;#U;#H;#W;#j;#$;#_;#v=!1;#L;#A;connect(){if(E=!0,this.element.id==="")console.warn("[phlex-reactive] a reactive root has no id; its next-action token can't self-match "+"and may fall back to the first token in the response → a silent HTTP 403 on the NEXT action. "+"Put id: on the SAME element as reactive_attrs — use div(**reactive_root) (emits id + token together), "+"or div(id:, **reactive_attrs). The id: must NOT be on a child. See the README.");if(this.element.getAttribute?.("data-reactive-defer-token"))this.#f(),this.#A=()=>this.#f(),this.element.addEventListener?.("turbo:morph-element",this.#A);if(this.#qj()){if(this.#U=()=>this.#T(),this.element.addEventListener?.("turbo:morph-element",this.#U),this.#T(),this.element.getAttribute?.("data-reactive-warn-unsaved")==="true")this.#Tj()}if(this.#kj())this.#j=()=>this.#a(),this.element.addEventListener?.("input",this.#j),this.element.addEventListener?.("change",this.#j),this.element.addEventListener?.("turbo:morph-element",this.#j),this.#a();if(this.#P())this.#$=(j)=>{if(j?.type==="input"&&!this.#yj(j))return;this.#N()},this.element.addEventListener?.("input",this.#$),this.element.addEventListener?.("turbo:morph-element",this.#$),this.#N();if(this.#E())this.#_=()=>this.#S(),this.element.addEventListener?.("turbo:morph-element",this.#_),this.#S();if(this.#hj())this.#L=()=>this.recompute(),this.element.addEventListener?.("turbo:morph-element",this.#L),this.recompute()}#qj(){if((this.element.getAttribute?.("data-action")??"").includes("reactive#trackDirty"))return!0;let j=this.element.querySelectorAll?.('[data-action*="reactive#trackDirty"]')??[];for(let X of j)if(this.#X(X))return!0;return!1}disconnect(){if(this.#Mj(),this.#Bj(),this.#Ij(),this.#bj(),this.#vj(),this.#mj(),this.#gj(),this.#A)this.element.removeEventListener?.("turbo:morph-element",this.#A)}#f(){let j=this.element;if(!j?.id)return;let X=j.getAttribute?.("data-reactive-defer-token");if(!X)return;if(j.getAttribute?.("data-reactive-defer-pending")!=="true")return;P(j.id,X)}dispatch(j){let{action:X,params:Z,debounce:$,throttle:J,confirm:Q,confirmWhen:G,outside:K,window:z,optimistic:Y}=j.params;if(!X)return;let H=j.params.busy??this.#tj(j.params.loading);if(K&&this.element.contains(j.target))return;let L=j.currentTarget??j.target;if(!z&&!this.#lj(Y,L))j.preventDefault();let W=this.#s(Q,G);if(!W)return this.#g(L,X,Z,$,J,Y,H);Promise.resolve().then(()=>b(W)).catch(()=>!1).then((_)=>{if(_)this.#g(L,X,Z,$,J,Y,H)})}runOps(j){let{ops:X,confirm:Z,confirmWhen:$,outside:J,window:Q}=j.params;if(J&&this.element.contains(j.target))return;if(!Q)j.preventDefault();let G=this.#s(Z,$);if(!G)return this.#$j(this.#Zj(X));Promise.resolve().then(()=>b(G)).catch(()=>!1).then((K)=>{if(K)this.#$j(this.#Zj(X))})}trackDirty(){this.#T()}recompute(j){if(j&&this.#y.has(j))return;let X=this.#Uj(),Z=X.map(([q])=>q),$=this.element.getAttribute?.("data-reactive-scope")||null,J=(q)=>$&&!q.includes("[")?`${$}[${q}]`:q,Q=this.#Z(),G=new Map,K=(q)=>{if(G.has(q))return G.get(q);let U=null;for(let A of this.element.querySelectorAll(`[name="${J(q)}"]`))if(Q(A)){U=A;break}return G.set(q,U),U};for(let q of Z)this.#u(q,K(q)?.value??"");let z=this.element.getAttribute("data-reactive-compute-reducer-param"),Y=z?Zj(z):null;if(!Y){this.#m({},K);return}let H=this.#Yj("data-reactive-compute-outputs-param"),L={};for(let[q,U]of X){let A=K(q);if(U==="string")L[q]=A?.value??"";else{let N=Number(A?.value);L[q]=Number.isFinite(N)?N:0}}let W=Y(L,{changed:this.#Hj(j,Z,$)})||{},_=[];for(let q of H){if(!(q in W))continue;let U=K(q);if(!U)continue;if(String(W[q])===U.value)continue;U.value=W[q],_.push(U)}for(let q of Object.keys(W)){let U=W[q];if(U===void 0||U===null)continue;this.#u(q,U)}this.#m(W,K);for(let q of _){let U=new Event("input",{bubbles:!0});this.#y.add(U),q.dispatchEvent(U)}}listnavNext(j){this.#p(j,1)}listnavPrev(j){this.#p(j,-1)}listnavPick(j){let X=this.#B(j),Z=X.findIndex(($)=>$.hasAttribute("data-reactive-highlighted"));if(Z<0)return;j.preventDefault(),X[Z].click()}listnavClose(j){for(let X of this.#B(j))X.removeAttribute("data-reactive-highlighted")}#p(j,X){let Z=this.#B(j);if(!Z.length)return;j.preventDefault();let $=Z.findIndex((G)=>G.hasAttribute("data-reactive-highlighted")),J=$<0?X>0?0:Z.length-1:($+X+Z.length)%Z.length;for(let G of Z)G.removeAttribute("data-reactive-highlighted");let Q=Z[J];Q.setAttribute("data-reactive-highlighted","true"),Q.scrollIntoView?.({block:"nearest"})}#B(j){let Z=(j?.currentTarget??j?.target??this.element).getAttribute?.("data-reactive-listnav-option-param")??this.element.getAttribute("data-reactive-listnav-option-param");if(!Z)return[];let $=this.#Z();return Array.from(this.element.querySelectorAll(Z)).filter((J)=>!J.hidden&&$(J))}tagsAdd(j){if(!this.#E())return;if(j?.defaultPrevented)return;if(this.#B(j).some(($)=>$.hasAttribute?.("data-reactive-highlighted")))return;j?.preventDefault?.();let X=j?.currentTarget??j?.target;if(!X)return;if(!this.#e(String(X.value??"").split(",")))return;if(X.value="",this.#P())this.#N()}tagsPick(j){if(!this.#E())return;j?.preventDefault?.();let Z=(j?.currentTarget??j?.target)?.getAttribute?.("data-reactive-tag-param");if(!Z)return;if(!this.#e([Z]))return;let $=this.#fj();if(!$)return;$.value="",this.#N(),$.focus?.()}tagsRemove(j){if(!this.#E())return;j?.preventDefault?.();let Z=(j?.currentTarget??j?.target)?.getAttribute?.("data-reactive-tag-param");if(!Z)return;let $=this.#I();if(!$)return;let J=this.#k($),Q=J.filter((G)=>G.toLowerCase()!==Z.toLowerCase());if(Q.length===J.length)return;this.#jj($,Q)}#Yj(j){let X=this.element.getAttribute(j);if(!X)return[];try{let Z=JSON.parse(X);return Array.isArray(Z)?Z:[]}catch{return[]}}#Uj(){let j=this.element.getAttribute("data-reactive-compute-inputs-param");if(!j)return[];try{let X=JSON.parse(j);if(Array.isArray(X))return X.map((Z)=>[Z,"number"]);if(X&&typeof X==="object")return Object.entries(X);return[]}catch{return[]}}#Hj(j,X,Z){let $=j?.target;if(!$?.name||typeof $.closest!=="function")return null;let J=this.#Wj($.name,Z);if(!X.includes(J))return null;return this.#X($)?J:null}#Wj(j,X){if(!X)return j;let Z=`${X}[`;return j.startsWith(Z)&&j.endsWith("]")?j.slice(Z.length,-1):j}#u(j,X){let Z=String(X);for(let $ of this.#_j(j)){if($.textContent===Z)continue;$.textContent=Z}}#_j(j){let X=this.element.querySelectorAll(`[data-reactive-text="${j}"]`);return Array.from(X).filter((Z)=>this.#X(Z))}#m(j,X){let Z=this.#Lj();for(let[$,J]of Object.entries(Z)){let Q=$ in j?j[$]:X($)?.value;if(Q===void 0||Q===null)continue;let G=String(Q);for(let K of Array.isArray(J)?J:[J]){if(!Fj(K))continue;for(let z of document.querySelectorAll(K)){if(z.textContent===G)continue;z.textContent=G}}}}#Lj(){let j=this.element.getAttribute("data-reactive-compute-mirror-param");if(!j)return{};try{let X=JSON.parse(j);return X&&typeof X==="object"&&!Array.isArray(X)?X:{}}catch{return{}}}#g(j,X,Z,$,J,Q,G){if(this.#O("reactive:before-dispatch",{action:X,params:this.#Xj(Z),element:this.element},{cancelable:!0}).defaultPrevented)return;let z=Number($)||0;if(z>0)return this.#Vj(j,z,X,Z,Q,G);let Y=Number(J)||0;if(Y>0)return this.#Aj(j,Y,X,Z,Q,G);return this.#x(X,Z,Q,j,G)}#x(j,X,Z,$,J){let Q=this.#oj(Z,$),G=this.#sj(j,$,J),K=this.#c()?this.#Nj(Z,$):null;return this.queue=(this.queue??Promise.resolve()).then(()=>this.#Cj(j,X,Q,G,K)),this.queue}#Nj(j,X){if(!j?.hide)return null;let Z=this.#Gj(j,X);if(!Z.length)return null;return()=>{let $=Z.filter((J)=>J.isConnected&&!J.hidden);if(!$.length)return;console.warn("[phlex-reactive] optimistic: { hide: true } was undone by the reply's re-render — "+"the element is visible again. For an instant delete, return reply.remove so the server removes it; otherwise the hide only flashes.",$)}}#Vj(j,X,Z,$,J,Q){this.#D(j);let G=()=>{this.#D(j),this.#x(Z,$,J,j,Q)},K=setTimeout(G,X);j?.addEventListener?.("blur",G,{once:!0}),this.#V.set(j,{timer:K,flush:G})}#D(j){let X=this.#V.get(j);if(!X)return;clearTimeout(X.timer),j?.removeEventListener?.("blur",X.flush),this.#V.delete(j)}#Mj(){for(let j of[...this.#V.keys()])this.#D(j)}#Aj(j,X,Z,$,J,Q){let G=this.#q.get(j)??new Map;if(G.has(Z))return;let K=setTimeout(()=>{if(G.delete(Z),G.size===0)this.#q.delete(j)},X);return G.set(Z,K),this.#q.set(j,G),this.#x(Z,$,J,j,Q)}#Bj(){for(let j of this.#q.values())for(let X of j.values())clearTimeout(X);this.#q.clear()}#O(j,X,{cancelable:Z=!1}={}){let $=new CustomEvent(j,{bubbles:!0,composed:!0,cancelable:Z,detail:X});return(this.element.isConnected?this.element:document).dispatchEvent($),$}#J(j,X,Z,$){let J=()=>{if(!this.element.isConnected){console.warn("[phlex-reactive] retry() ignored — the reactive root left the DOM");return}return this.#x(j,X)};this.#O("reactive:error",{action:j,params:Z,...$,retry:J})}#Q(j){if(this.element?.isConnected===!1)return;this.element?.setAttribute?.("data-reactive-error",j)}#xj(){this.element?.removeAttribute?.("data-reactive-error")}#Oj(){let j=document.querySelector("[data-reactive-error-flash]");if(!j?.content)return;let X=j.getAttribute("data-reactive-error-flash")||"flash",Z=document.getElementById(X);if(!Z)return;Z.appendChild(j.content.cloneNode(!0))}#Pj(){if(typeof sessionStorage>"u")return Promise.resolve();let j=Number(sessionStorage.getItem(S));if(!Number.isFinite(j)||j<=0)return Promise.resolve();if(!x)x=!0,console.warn(`[phlex-reactive] latency simulator ACTIVE — every action is delayed by ${j}ms. Call PhlexReactive.disableLatencySim() (or clear sessionStorage) to turn it off.`);return new Promise((X)=>setTimeout(X,j))}#c(){return this.element?.getAttribute?.("data-reactive-debug")==="true"}#d(){return typeof performance<"u"&&typeof performance.now==="function"?performance.now():Date.now()}#Ej(j){if(!j)return[];let X=[],Z=/<turbo-stream\b([^>]*)>/g,$;while(($=Z.exec(j))!==null){let J=$[1],Q=J.match(/\baction="([^"]*)"/)?.[1]??"?",G=J.match(/\btarget="([^"]*)"/)?.[1];X.push(G?`${Q} → #${G}`:Q)}return X}#Fj(j){let{action:X,status:Z,ms:$}=j,Q=`reactive ${this.element?.id?`#${this.element.id} `:""}${X} → ${Z??"—"} (${Math.round($)}ms)`;if(console.groupCollapsed(Q),console.log(`params: [${j.paramNames.join(", ")}] + collected: [${j.fieldNames.join(", ")}]`),console.log(`encoding: ${j.encoding}`),j.streams.length)console.log(`streams: ${j.streams.join(" ")}`);console.log(`token: ${j.tokenRefreshed?"refreshed ✓":"unchanged"}`),console.groupEnd()}async#Cj(j,X,Z,$,J){let{fields:Q,files:G}=this.#i(),K=this.#Xj(X),z={...Q,...K},Y=this.#G,H=G.length>0,L=H?this.#cj(Y,j,z,G):JSON.stringify({token:Y,act:j,params:z}),W=this.#c()?{action:j,paramNames:Object.keys(K),fieldNames:Object.keys(Q),encoding:H?"multipart":"json",status:null,streams:[],tokenRefreshed:!1,started:this.#d()}:null;await this.#Pj();try{if(navigator.onLine===!1){this.#z(Z),this.#Q("offline"),this.#J(j,X,z,{kind:"offline"});return}let _;try{let N={Accept:"text/vnd.turbo-stream.html","X-CSRF-Token":this.#XX()};if(!H)N["Content-Type"]="application/json";let B=this.#ZX();if(B)N["X-Pgbus-Connection"]=B;_=await fetch(this.#ej(),{method:"POST",headers:N,body:L,credentials:"same-origin",signal:AbortSignal.timeout(this.#jX())})}catch(N){if(console.error("[phlex-reactive] action error",N),this.#z(Z),N?.name==="TimeoutError"||N?.name==="AbortError"){this.#Q("timeout"),this.#J(j,X,z,{kind:"timeout"});return}this.#Oj(),this.#Q("network"),this.#J(j,X,z,{kind:"network"});return}if(W)W.status=_.status;if(_.redirected){console.error("[phlex-reactive] action was redirected (auth/CSRF?) — no update applied"),this.#z(Z),this.#Q("redirected"),this.#J(j,X,z,{kind:"redirected",status:_.status});return}if(!_.ok){let N=await _.text();if(console.error(`[phlex-reactive] action failed: HTTP ${_.status}`,N),this.#z(Z),(_.headers.get("Content-Type")||"").includes("turbo-stream")){let B=this.#o(N);if(this.#G=B??this.#G,W)this.#l(W,N,B);window.Turbo.renderStreamMessage(N)}this.#Q("http"),this.#J(j,X,z,{kind:"http",status:_.status,body:N});return}let q=_.headers.get("Content-Type")||"";if(!q.includes("turbo-stream")){console.error(`[phlex-reactive] expected a turbo-stream, got "${q}" — no update applied`),this.#z(Z),this.#Q("content-type"),this.#J(j,X,z,{kind:"content-type",status:_.status});return}let U=await _.text(),A=this.#o(U);if(this.#G=A??this.#G,W)this.#l(W,U,A);if(window.Turbo.renderStreamMessage(U),J)queueMicrotask(J);this.#xj(),this.#O("reactive:applied",{action:j,params:z,html:U})}catch(_){console.error("[phlex-reactive] action error",_),this.#z(Z),this.#O("reactive:error",{action:j,params:z,kind:"apply"})}finally{if($?.(),W)this.#Fj({...W,ms:this.#d()-W.started})}}#l(j,X,Z){j.streams=this.#Ej(X),j.tokenRefreshed=Z!=null}get#G(){return this.#b??this.tokenValue}set#G(j){this.#b=j}#o(j){let X=this.element.id;if(!X)return j.match(/data-reactive-token-value="([^"]+)"/)?.[1];let{token:Z,self:$}=this.#Rj(X),J=j.match(Z);if(J)return J[1];let Q=j.match($);if(Q)return Q[1].match(/data-reactive-token-value="([^"]+)"/)?.[1];return}#Rj(j){let X=this.#h;if(X&&X.id===j)return X;let Z=Bj(j);return this.#h={id:j,token:new RegExp(`<turbo-stream\\b[^>]*\\baction="reactive:token"[^>]*\\btarget="${Z}"[^>]*\\bdata-reactive-token-value="([^"]+)"`),self:new RegExp(`<turbo-stream\\b[^>]*\\baction="(?:replace|update)"[^>]*\\btarget="${Z}"[^>]*>([\\s\\S]*?)</turbo-stream>`)}}#X(j){return j.closest('[data-controller~="reactive"]')===this.element}#Z(){if(this.element.querySelectorAll('[data-controller~="reactive"]').length===0)return()=>!0;return(X)=>this.#X(X)}#s(j,X){if(j)return j;if(!X)return null;let Z=X;if(typeof X==="string")try{Z=JSON.parse(X)}catch{return console.warn(`[phlex-reactive] malformed conditional confirm payload ${JSON.stringify(X)} — skipped`),null}if(!Z||typeof Z!=="object")return null;let{fields:$}=this.#i(),J=(G)=>$[G],Q;if(typeof Z.predicate==="string"){let G=$j(Z.predicate);if(!G)return console.warn(`[phlex-reactive] confirm predicate "${Z.predicate}" is not registered — proceeding without a dialog (register it with setConfirmPredicate)`),null;Q=!!G($)}else Q=t(Z.groups?.any,J)===!0;return Q?Z.message:null}#i(){let j={},X=[],Z=this.#Z();return this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach(($)=>{if(!Z($))return;if($.type==="file")for(let J of $.files??[])X.push({name:$.name,file:J,multiple:$.multiple});else if($.type==="checkbox")j[$.name]=$.checked;else if($.type==="radio"){if($.checked)j[$.name]=$.value}else j[$.name]=$.value}),this.element.querySelectorAll("[name]:is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])").forEach(($)=>{if(!Z($))return;let J=$.getAttribute("name");if(!J)return;let Q=j[J];if(Q==null||Q==="")j[J]=$.value??$.textContent??$.innerHTML??""}),{fields:j,files:X}}#T(){if(typeof this.element?.querySelectorAll!=="function")return;let j=0;if(this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach((X)=>{if(!this.#X(X))return;if(X.type==="file")return;if(this.#Dj(X))X.setAttribute("data-reactive-dirty","true"),j++;else X.removeAttribute("data-reactive-dirty")}),j>0)this.element.setAttribute("data-reactive-dirty",String(j));else this.element.removeAttribute("data-reactive-dirty")}#Dj(j){if(j.type==="checkbox"||j.type==="radio")return j.checked!==j.defaultChecked;if(j.tag==="select"||j.options)return Array.from(j.options??[]).some((X)=>X.selected!==X.defaultSelected);return j.value!==j.defaultValue}#n(){let j=this.element.getAttribute?.("data-reactive-dirty"),X=Number(j);return Number.isFinite(X)&&X>0?X:0}#Tj(){if(typeof window>"u"||typeof window.addEventListener!=="function")return;this.#H=(j)=>{if(this.#n()===0)return;return j.preventDefault(),j.returnValue="You have unsaved changes.",j.returnValue},this.#W=(j)=>{if(this.#n()===0)return;if(!(typeof window.confirm==="function"?window.confirm("You have unsaved changes. Leave anyway?"):!0))j.preventDefault?.()},window.addEventListener("beforeunload",this.#H),window.addEventListener("turbo:before-visit",this.#W)}#Ij(){if(this.#U)this.element.removeEventListener?.("turbo:morph-element",this.#U),this.#U=void 0;if(typeof window<"u"&&typeof window.removeEventListener==="function"){if(this.#H)window.removeEventListener("beforeunload",this.#H);if(this.#W)window.removeEventListener("turbo:before-visit",this.#W)}this.#H=void 0,this.#W=void 0}#kj(){if(this.element.getAttribute?.("data-reactive-show-targets"))return!0;let j=this.element.querySelectorAll?.(f)??[];for(let X of j)if(this.#X(X))return!0;return!1}#a(){if(typeof this.element?.querySelectorAll!=="function")return;let j=this.#Z(),X=this.element.getAttribute?.("data-reactive-scope")||null,Z=new Map,$=(J)=>{if(!Z.has(J))Z.set(J,this.#t(J,j,X));return Z.get(J)};for(let J of this.element.querySelectorAll(f)){if(!j(J))continue;let Q=J.getAttribute("data-reactive-show");if(Q!==null){let Y=Dj(Rj(Q),$);if(Y!==null)this.#r(J,Y,j,X);continue}let G=J.getAttribute("data-reactive-show-field");if(!G)continue;let K=$(G);if(K===null)continue;let z=Cj(J,K);if(z===null)continue;this.#r(J,z,j,X)}this.#Sj(j,Z,X)}#r(j,X,Z,$){if(j.hidden=!X,j.getAttribute("data-reactive-show-disable")!=="true")return;if(typeof j.querySelectorAll!=="function")return;for(let J of j.querySelectorAll("input[name], select[name], textarea[name]"))if(Z(J))J.disabled=!X;if(j.name&&Z(j))j.disabled=!X}#Sj(j,X,Z){let $=this.#wj();for(let[J,Q]of Object.entries($)){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;if(!X.has(J))X.set(J,this.#t(J,j,Z));let G=X.get(J);if(G===null)continue;let K=()=>G;for(let[z,Y]of Object.entries(Q)){if(!Ij(z))continue;let H;if(Array.isArray(Y)){if(Y.length===0){console.warn(`[phlex-reactive] malformed reactive_show_targets group for ${z} — skipped`);continue}H=Y.every((L)=>w(L,K))}else{let L=r(Y,G);if(L===null){console.warn(`[phlex-reactive] malformed reactive_show_targets predicate for ${z} — skipped`);continue}H=L}for(let L of document.querySelectorAll(z))L.hidden=!H}}}#wj(){let j=this.element.getAttribute?.("data-reactive-show-targets");if(!j)return{};try{let X=JSON.parse(j);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return console.warn("[phlex-reactive] malformed data-reactive-show-targets — ignored. "+"Did two reactive_show_targets calls collide on one root? Declare every field in ONE call: reactive_show_targets(mode: { ... }, kind: { ... })"),{}}#t(j,X,Z){let $=Z&&!j.includes("[")?`${Z}[${j}]`:j,J=!1,Q=null;for(let G of this.element.querySelectorAll(`[name="${$}"]`)){if(!X(G))continue;if(G.type==="checkbox")return G.checked?"true":"false";if(G.type==="radio"){if(G.checked)return G.value??"";J=!0;continue}Q??=G}if(Q)return Q.value??"";return J?"":null}#bj(){if(!this.#j)return;this.element.removeEventListener?.("input",this.#j),this.element.removeEventListener?.("change",this.#j),this.element.removeEventListener?.("turbo:morph-element",this.#j),this.#j=void 0}#P(){return!!(this.element.getAttribute?.("data-reactive-filter-input")&&this.element.getAttribute?.("data-reactive-filter-option"))}#hj(){return this.element.getAttribute?.("data-reactive-compute-seed")==="true"}#yj(j){let X=this.element.getAttribute("data-reactive-filter-input");return!!X&&typeof j.target?.matches==="function"&&j.target.matches(X)}#N(){if(typeof this.element?.querySelectorAll!=="function")return;let j=this.element.getAttribute("data-reactive-filter-input"),X=this.element.getAttribute("data-reactive-filter-option");if(!j||!X)return;let Z=this.#Z(),$=[...this.element.querySelectorAll(j)].find(Z);if(!$)return;let J=($.value??"").trim().toLowerCase(),Q=0;for(let z of this.element.querySelectorAll(X)){if(!Z(z))continue;let Y=(z.getAttribute("data-reactive-filter-text")??z.textContent??"").toLowerCase(),H=z.hasAttribute?.("data-reactive-tags-selected")||J!==""&&!Y.includes(J);if(z.hidden=H,H)z.removeAttribute("data-reactive-highlighted");else Q++}let G=this.element.getAttribute("data-reactive-filter-group");if(G)for(let z of this.element.querySelectorAll(G)){if(!Z(z))continue;let Y=[...z.querySelectorAll(X)].filter(Z);if(Y.length===0)continue;z.hidden=Y.every((H)=>H.hidden)}let K=this.element.getAttribute("data-reactive-filter-empty");if(K){for(let z of this.element.querySelectorAll(K))if(Z(z))z.hidden=Q>0}}#vj(){if(!this.#$)return;this.element.removeEventListener?.("input",this.#$),this.element.removeEventListener?.("turbo:morph-element",this.#$),this.#$=void 0}#E(){return!!this.element.getAttribute?.("data-reactive-tags-field")}#I(){if(typeof this.element?.querySelectorAll!=="function")return null;let j=this.element.getAttribute("data-reactive-tags-field");if(!j)return null;let X=this.#Z();return[...this.element.querySelectorAll(j)].find(X)??null}#k(j){let X=new Set,Z=[];for(let $ of String(j.value??"").split(",")){let J=$.trim();if(J===""||X.has(J.toLowerCase()))continue;X.add(J.toLowerCase()),Z.push(J)}return Z}#e(j){let X=this.#I();if(!X)return!1;let Z=this.#k(X),$=new Set(Z.map((Q)=>Q.toLowerCase())),J=!1;for(let Q of j){let G=String(Q??"").trim();if(G===""||$.has(G.toLowerCase()))continue;$.add(G.toLowerCase()),Z.push(G),J=!0}if(J)this.#jj(X,Z);return J}#jj(j,X){if(j.value=X.join(","),typeof j.dispatchEvent==="function")j.dispatchEvent(new Event("input",{bubbles:!0}));this.#S()}#fj(){if(typeof this.element?.querySelectorAll!=="function")return null;let j=this.element.getAttribute("data-reactive-filter-input");if(!j)return null;let X=this.#Z();return[...this.element.querySelectorAll(j)].find(X)??null}#S(){let j=this.#I();if(!j)return;let X=this.#k(j),Z=this.#Z();this.#pj(X,Z),this.#uj(X,Z)}#pj(j,X){let Z=[...this.element.querySelectorAll("[data-reactive-tags-list]")].find(X);if(!Z)return;let J=[...this.element.querySelectorAll("[data-reactive-tags-template]")].find(X)?.content?.firstElementChild;if(!J){if(!this.#v)console.warn("[phlex-reactive] reactive_tags: no chip <template data-reactive-tags-template> found in this root — "+"chips will not render (the hidden field still updates). Add a template with a [data-reactive-tag-text] node and a reactive_tags_remove button."),this.#v=!0;return}while(Z.firstChild)Z.removeChild(Z.firstChild);for(let Q of j){let G=J.cloneNode(!0);G.setAttribute?.("data-reactive-tag",Q);let K=G.matches?.("[data-reactive-tag-text]")?G:(G.querySelectorAll?.("[data-reactive-tag-text]")??[])[0];if(K)K.textContent=Q;let z=[...G.querySelectorAll?.('[data-action*="reactive#tagsRemove"]')??[]];if(G.matches?.('[data-action*="reactive#tagsRemove"]'))z.push(G);for(let Y of z)Y.setAttribute?.("data-reactive-tag-param",Q);Z.appendChild(G)}}#uj(j,X){let Z=new Set(j.map(($)=>$.toLowerCase()));for(let $ of this.element.querySelectorAll("[role=option]")){if(!X($))continue;let J=$.getAttribute?.("data-reactive-tag-param");if(!J)continue;if(Z.has(J.toLowerCase()))$.setAttribute("data-reactive-tags-selected","true"),$.hidden=!0,$.removeAttribute?.("data-reactive-highlighted");else if($.hasAttribute?.("data-reactive-tags-selected")){if($.removeAttribute("data-reactive-tags-selected"),!this.#P())$.hidden=!1}}if(this.#P())this.#N()}#mj(){if(!this.#_)return;this.element.removeEventListener?.("turbo:morph-element",this.#_),this.#_=void 0}#gj(){if(!this.#L)return;this.element.removeEventListener?.("turbo:morph-element",this.#L),this.#L=void 0}#cj(j,X,Z,$){let J=new FormData;J.append("token",j),J.append("act",X);for(let[G,K]of Object.entries(Z))this.#w(J,`params[${G}]`,K);let Q=this.#dj($);for(let{name:G,file:K,multiple:z}of $){let H=z||Q.has(G)?`params[${G}][]`:`params[${G}]`;J.append(H,K,K.name)}return J}#w(j,X,Z){if(Z==null)j.append(X,"");else if(Array.isArray(Z))Z.forEach(($,J)=>this.#w(j,`${X}[${J}]`,$));else if(typeof Z==="object")for(let[$,J]of Object.entries(Z))this.#w(j,`${X}[${$}]`,J);else j.append(X,String(Z))}#dj(j){let X=new Map;for(let{name:Z}of j)X.set(Z,(X.get(Z)??0)+1);return new Set([...X].filter(([,Z])=>Z>1).map(([Z])=>Z))}#Xj(j){if(!j)return{};try{return typeof j==="string"?JSON.parse(j):j}catch{return{}}}#Zj(j){return e(j)}#$j(j){jj(j,(X)=>this.#Jj(X))}#Jj(j){let X=j.to;if(X==="@root")return[this.element];if(typeof X!=="string"||X==="")return[];if(j.global)return[...document.querySelectorAll(X)];return[...this.element.querySelectorAll(X)].filter((Z)=>this.#X(Z))}#lj(j,X){if(j?.checked!=="keep")return!1;let Z=X?.type;return Z==="checkbox"||Z==="radio"}#oj(j,X){if(!j)return null;let Z=this.#Qj(j,X,!0);return Z.length?Z:null}#z(j){if(!j)return;if(!this.element.isConnected)return;for(let X of j)X()}#sj(j,X,Z){this.#nj(j,X);let $=Z?this.#Qj(Z,X,!1):[];l();let J=!1;return()=>{if(J)return;J=!0,this.#aj(j,X),o();for(let Q of $)Q()}}#Qj(j,X,Z){let $=[];for(let J of this.#Gj(j,X)){if(j.add_class){let Q=j.add_class.filter((G)=>!J.classList.contains(G));if(J.classList.add(...Q),Q.length)$.push(()=>J.classList.remove(...Q))}if(j.remove_class){let Q=j.remove_class.filter((G)=>J.classList.contains(G));if(J.classList.remove(...Q),Q.length)$.push(()=>J.classList.add(...Q))}if(j.toggle_class)j.toggle_class.forEach((Q)=>J.classList.toggle(Q)),$.push(()=>j.toggle_class.forEach((Q)=>J.classList.toggle(Q)));if(j.hide)J.hidden=!0,$.push(()=>J.hidden=!1);if(j.show)J.hidden=!1,$.push(()=>J.hidden=!0)}if(X&&(j.disable||j.text!=null))$.push(this.#ij(j,X));if(Z&&j.checked==="keep"&&X&&"checked"in X){let J=X.checked;$.push(()=>X.checked=!J)}return $}#Gj(j,X){if(j.to==null)return X?[X]:[];return this.#Jj({to:j.to})}#ij(j,X){let Z=this.#M.get(X);if(Z)Z.count++;else this.#M.set(X,{count:1,disabled:X.disabled,html:X.innerHTML,hadText:j.text!=null,swappedTo:j.text});if(j.disable)X.disabled=!0;if(j.text!=null)X.innerHTML=j.text;return()=>this.#rj(X,j)}#nj(j,X){if(this.#K(X,j,1),this.#K(this.element,j,1),this.#Y.set(j,(this.#Y.get(j)??0)+1),this.#C++===0)this.element.setAttribute("aria-busy","true");for(let Z of this.#zj(j))this.#K(Z,j,1)}#aj(j,X){this.#K(X,j,-1),this.#K(this.element,j,-1);let Z=(this.#Y.get(j)??1)-1;if(Z<=0)this.#Y.delete(j);else this.#Y.set(j,Z);if(--this.#C<=0)this.#C=0,this.element.removeAttribute("aria-busy");for(let $ of this.#zj(j))this.#K($,j,-1)}#K(j,X,Z){if(!j||typeof j.getAttribute!=="function")return;let $=this.#R.get(j)??new Map,J=($.get(X)??0)+Z;if(J<=0)$.delete(X);else $.set(X,J);if($.size===0){this.#R.delete(j),j.removeAttribute("data-reactive-busy");return}this.#R.set(j,$),j.setAttribute("data-reactive-busy",[...$.keys()].join(" "))}#zj(j){return[...this.element.querySelectorAll?.("[data-reactive-busy-on]")??[]].filter((Z)=>Z.getAttribute("data-reactive-busy-on")===j&&this.#X(Z))}#rj(j,X){let Z=this.#M.get(j);if(!Z)return;if(--Z.count>0)return;if(this.#M.delete(j),!j.isConnected)return;if(X.disable)j.disabled=Z.disabled;if(Z.hadText&&j.innerHTML===Z.swappedTo)j.innerHTML=Z.html}#tj(j){if(!j||typeof j!=="object")return null;let{class:X,...Z}=j;return X==null?j:{...Z,add_class:X}}#ej(){return this.#Kj??=document.querySelector('meta[name="phlex-reactive-action-path"]')?.content||"/reactive/actions"}#jX(){if(this.#F!=null)return this.#F;let j=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,X=Number(j);return this.#F=Number.isFinite(X)&&X>0?X:30000}#XX(){return document.querySelector('meta[name="csrf-token"]')?.content??""}#ZX(){return document.querySelector("pgbus-stream-source[connection-id]")?.getAttribute("connection-id")||document.querySelector('meta[name="pgbus-connection-id"]')?.content||null}}export{fj as resetReactiveDefers,dj as resetReactiveActivity,Jj as registerReactiveVisit,Qj as registerReactiveToken,Nj as registerReactiveOffline,Gj as registerReactiveJs,_j as registerReactiveDismiss,zj as registerReactiveDefer,y as registerReactiveActions,cj as reactiveActivityCount,pj as pendingDeferVia,o as exitReactiveActivity,Bj as escapeRegExp,l as enterReactiveActivity,Vj as enableLatencySim,Mj as disableLatencySim,sj as default,xj as checkReactiveRegistration,lj as __resetReactiveRegistrationForTest,mj as __resetReactiveOfflineForTest,gj as __resetReactiveLatencyForTest,uj as __resetReactiveDismissForTest,oj as __markReactiveConnectedForTest,S as LATENCY_KEY,d as ACTIVE_ATTR};
1
+ import{Controller as Xj}from"@hotwired/stimulus";import{confirmResolver as w}from"phlex/reactive/confirm";import{computeReducer as Zj}from"phlex/reactive/compute";import{confirmPredicate as $j}from"phlex/reactive/confirm_predicate";function Jj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:visit"])return;j["reactive:visit"]=function(){let X=this.getAttribute("data-url");if(X)window.Turbo.visit(X,{action:"advance"})}}function Qj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:token"])return;j["reactive:token"]=function(){let X=this.getAttribute("data-reactive-token-value"),Z=this.getAttribute("target");if(!X||!Z)return;let $=document.getElementById(Z);if($)$.setAttribute("data-reactive-token-value",X)}}function Gj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:js"])return;j["reactive:js"]=function(){let X=e(this.getAttribute("data-reactive-ops"));if(!X.length)return;let Z=this.getAttribute("target"),$=Z?document.getElementById(Z):null;if(Z&&!$)return;jj(X,(J)=>bj(J,$))}}var N=new Map;function p(j,X){let Z=!N.has(j);if(N.set(j,X),Z)l()}function x(j){if(N.delete(j))o()}function fj(){N.clear(),T=!1}function pj(j){return N.get(j)?.via}var T=!1;function zj(){let j=window.Turbo?.StreamActions;if(!j||j["reactive:defer"])return;if(j["reactive:defer"]=function(){let X=this.getAttribute("target");if(!X)return;if(this.getAttribute("data-reactive-defer-via")==="stream"){qj(X,this);return}let Z=this.getAttribute("data-reactive-defer-token");if(!Z)return;P(X,Z)},!T&&typeof document<"u"&&document.addEventListener)T=!0,document.addEventListener("turbo:before-stream-render",Kj)}function Kj(j){let Z=j.target?.getAttribute?.("target");if(!Z)return;let $=Z.startsWith("reactive-defer-src-")?Z.slice(19):Z;if(N.get($)?.via==="stream")x($)}function P(j,X){let Z=document.getElementById(j);if(!Z){console.warn(`[phlex-reactive] reactive:defer target #${j} is not on the page — skipped`);return}m(j),g(Z);let $={via:"fetch",abort:new AbortController,timedOut:!1};p(j,$),Yj(j,$,X)}function qj(j,X){let Z=document.getElementById(j);if(!Z){console.warn(`[phlex-reactive] reactive:defer target #${j} is not on the page — skipped`);return}let $=X.getAttribute("data-reactive-defer-src");if(!$)return;if(!globalThis.customElements?.get?.("pgbus-stream-source")){let Q=X.getAttribute("data-reactive-defer-token");if(Q){P(j,Q);return}console.error("[phlex-reactive] reactive:defer via=stream but <pgbus-stream-source> is not registered "+"and no fallback token was provided — is the pgbus client loaded on this page?");return}m(j),g(Z);let J=document.createElement("pgbus-stream-source");J.id=u(j),J.setAttribute("src",$),J.setAttribute("since-id",X.getAttribute("data-reactive-defer-since-id")??"0"),J.setAttribute("hidden",""),document.body.appendChild(J),p(j,{via:"stream"})}function u(j){return`reactive-defer-src-${j}`}async function Yj(j,X,Z){let $=setTimeout(()=>{X.timedOut=!0,X.abort.abort()},Wj()),J;try{J=await fetch(Uj(),{method:"POST",headers:{Accept:"text/vnd.turbo-stream.html","Content-Type":"application/json","X-CSRF-Token":Hj()},body:JSON.stringify({token:Z}),credentials:"same-origin",signal:X.abort.signal})}catch(G){if(clearTimeout($),N.get(j)!==X)return;console.error("[phlex-reactive] deferred render failed",G),F(j,Z);return}if(N.get(j)!==X){clearTimeout($);return}if(J.status===204){clearTimeout($),h(j);return}if(!J.ok){clearTimeout($),console.error(`[phlex-reactive] deferred render failed: HTTP ${J.status}`),F(j,Z,J.status);return}let Q;try{Q=await J.text()}catch(G){if(clearTimeout($),N.get(j)!==X)return;console.error("[phlex-reactive] deferred render failed reading the body",G),F(j,Z);return}if(clearTimeout($),N.get(j)!==X)return;h(j),window.Turbo.renderStreamMessage(Q)}function m(j){let X=N.get(j);if(!X)return;if(x(j),X.via==="fetch")X.abort.abort();else document.getElementById(u(j))?.remove?.()}function g(j){j.setAttribute("data-reactive-defer-pending","true"),j.setAttribute("aria-busy","true")}function c(j){j.removeAttribute("data-reactive-defer-pending"),j.removeAttribute("aria-busy")}function h(j){x(j);let X=document.getElementById(j);if(!X)return;c(X),X.removeAttribute("data-reactive-error")}function F(j,X,Z){x(j);let $=document.getElementById(j);if(!$)return;c($),$.setAttribute("data-reactive-error","defer");let J=()=>{let Q=document.getElementById(j);if(!Q){console.warn("[phlex-reactive] defer retry() ignored — the target left the DOM");return}Q.removeAttribute("data-reactive-error"),P(j,X)};$.dispatchEvent(new CustomEvent("reactive:error",{bubbles:!0,composed:!0,detail:{kind:"defer",target:j,status:Z,retry:J}}))}function Uj(){return document.querySelector('meta[name="phlex-reactive-defer-path"]')?.content||"/reactive/defer"}function Hj(){return document.querySelector('meta[name="csrf-token"]')?.content??""}function Wj(){let j=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,X=Number(j);return Number.isFinite(X)&&X>0?X:30000}var I=!1;function _j(){if(I)return;if(typeof document>"u"||!document.addEventListener)return;I=!0,document.addEventListener("turbo:before-stream-render",Lj)}function Lj(j){let X=j.detail,Z=X?.render;if(typeof Z!=="function"||Z.__reactiveDismissWrapped){if(typeof requestAnimationFrame==="function")requestAnimationFrame(C);else setTimeout(C,0);return}let $=async(J)=>{await Z(J),C()};$.__reactiveDismissWrapped=!0,X.render=$}function C(){let j=document.querySelectorAll("[data-reactive-dismiss-after]");for(let X of j){if(X.hasAttribute("data-reactive-dismiss-scheduled"))continue;let Z=Number(X.getAttribute("data-reactive-dismiss-after"));if(!Number.isFinite(Z)||Z<=0)continue;X.setAttribute("data-reactive-dismiss-scheduled",""),setTimeout(()=>X.remove(),Z)}}function uj(){I=!1}var k=!1;function Vj(){if(k)return;if(typeof window>"u"||typeof document>"u")return;if(typeof window.addEventListener!=="function")return;k=!0;let j=()=>{let X=document.documentElement;if(typeof X?.toggleAttribute!=="function")return;X.toggleAttribute("data-reactive-offline",globalThis.navigator?.onLine===!1)};j(),window.addEventListener("online",j),window.addEventListener("offline",j)}function mj(){k=!1}var S="phlex-reactive:latency",O=!1;function Nj(j){if(typeof sessionStorage>"u")return;sessionStorage.setItem(S,String(j))}function Mj(){if(typeof sessionStorage>"u")return;sessionStorage.removeItem(S),O=!1}function Aj(){if(typeof window>"u"||typeof document>"u")return;if(document.querySelector?.('meta[name="phlex-reactive-env"]')?.content!=="development")return;window.PhlexReactive={enableLatencySim:Nj,disableLatencySim:Mj}}function gj(){O=!1}var d="data-reactive-active",M=0;function l(){if(M++,M===1)s("reactive:busy")}function o(){if(M===0)return;if(M--,M===0)s("reactive:idle")}function cj(){return M}function dj(){M=0,(typeof document<"u"?document.documentElement:null)?.removeAttribute?.(d)}function s(j){if(typeof document>"u")return;let X=document.documentElement;if(typeof X?.toggleAttribute==="function")X.toggleAttribute(d,M>0);if(typeof document.dispatchEvent==="function"&&typeof CustomEvent==="function")document.dispatchEvent(new CustomEvent(j,{detail:{count:M}}))}function y(){Jj(),Qj(),Gj(),zj(),_j(),Vj(),Aj()}function Bj(j){return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}if(typeof window<"u")if(window.Turbo)y();else document.addEventListener("turbo:load",y,{once:!0});var E=!1;function Oj(){if(E)return;if(typeof document>"u")return;let j=document.querySelectorAll('[data-controller~="reactive"]');if(!j||j.length===0)return;console.warn("[phlex-reactive] found "+j.length+' element(s) with data-controller="reactive" '+"but the reactive controller never connected. It is loaded but not registered — "+'add `application.register("reactive", ReactiveController)` (importmap) or import it into app/javascript/controllers/ for lazyLoadControllersFrom apps. See the README.')}function lj(){E=!1}function oj(){E=!0}if(typeof window<"u"&&typeof document<"u"){let j=()=>setTimeout(Oj,0);if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",j,{once:!0});else j()}var xj=new Set(["href","src","srcdoc","action","formaction","xlink:href","style"]);function Pj(j){let X=String(j).toLowerCase();return X.startsWith("on")||xj.has(X)}function Ej(j,X,Z){let[$,J,Q]=X;j.classList.add($,J),Z(),requestAnimationFrame(()=>{j.classList.remove(J),j.classList.add(Q)});let G=!1,K=()=>{if(G)return;G=!0,j.classList.remove($,Q)};j.addEventListener("animationend",K,{once:!0}),setTimeout(K,350)}var v=Object.freeze({show:(j,X)=>R(j,!1,X),hide:(j,X)=>R(j,!0,X),toggle:(j,X)=>R(j,!j.hidden,X),add_class:(j,X)=>j.classList.add(...X.classes??[]),remove_class:(j,X)=>j.classList.remove(...X.classes??[]),toggle_class:(j,X)=>(X.classes??[]).forEach((Z)=>j.classList.toggle(Z)),set_attr:(j,X)=>{if(D(X.name))j.setAttribute(X.name,X.value??"")},remove_attr:(j,X)=>{if(D(X.name))j.removeAttribute(X.name)},toggle_attr:(j,X)=>{if(!D(X.name))return;if(j.hasAttribute(X.name))j.removeAttribute(X.name);else j.setAttribute(X.name,"")},focus:(j)=>j.focus?.(),focus_first:(j)=>Sj(j)?.focus?.(),text:(j,X)=>{let Z=String(X.value??"");if(j.textContent!==Z)j.textContent=Z},dispatch:(j,X)=>{j.dispatchEvent(new CustomEvent(X.name,{bubbles:!0,composed:!0,detail:X.detail??{}}))}});function R(j,X,Z){if(Z?.transition)Ej(j,Z.transition,()=>j.hidden=X);else j.hidden=X}function D(j){if(!Pj(j))return!0;return console.warn(`[phlex-reactive] refused client attr op on ${JSON.stringify(j)} — skipped`),!1}var i=/^#[A-Za-z_][\w-]*$/;function Fj(j){if(typeof j==="string"&&i.test(j))return!0;return console.warn(`[phlex-reactive] refused cross-root mirror target ${JSON.stringify(j)} — skipped`),!1}function Cj(j,X){let Z=j.getAttribute("data-reactive-show-equals");if(Z!==null)return X===Z;let $=j.getAttribute("data-reactive-show-not");if($!==null)return X!==$;let J=j.getAttribute("data-reactive-show-in");if(J!==null){try{let Q=JSON.parse(J);if(Array.isArray(Q))return Q.includes(X)}catch{}return console.warn(`[phlex-reactive] malformed reactive_show in: list ${JSON.stringify(J)} — skipped`),null}for(let Q of n){let G=j.getAttribute(`data-reactive-show-${Q}`);if(G!==null)return a(Q,G,X)}return console.warn("[phlex-reactive] a reactive_show binding declares no predicate — skipped"),null}var n=["gte","gt","lte","lt"];function a(j,X,Z){let $=Number(X);if(Number.isNaN($))return console.warn(`[phlex-reactive] reactive_show ${j}: needs a numeric literal, got ${JSON.stringify(X)} — skipped`),null;let J=Z==null?"":String(Z).trim(),Q=J===""?NaN:Number(J);if(Number.isNaN(Q))return!1;switch(j){case"gte":return Q>=$;case"gt":return Q>$;case"lte":return Q<=$;case"lt":return Q<$;default:return null}}function r(j,X){if(!j||typeof j!=="object")return null;if(typeof j.equals==="string")return X===j.equals;if(typeof j.not==="string")return X!==j.not;if(Array.isArray(j.in))return j.in.includes(X);for(let Z of n)if(Z in j)return a(Z,j[Z],X);return null}var f="[data-reactive-show-field], [data-reactive-show]";function Rj(j){try{let X=JSON.parse(j);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return console.warn(`[phlex-reactive] malformed compound reactive_show payload ${JSON.stringify(j)} — skipped`),null}function b(j,X){if(!j||typeof j!=="object"||typeof j.field!=="string")return!1;let Z=X(j.field)??"";return r(j,Z)===!0}function t(j,X){if(!Array.isArray(j)||j.length===0)return null;return j.some((Z)=>Array.isArray(Z)&&Z.length>0&&Z.every(($)=>b($,X)))}function Dj(j,X){if(!j||typeof j!=="object")return null;let Z=j.any;if(Array.isArray(Z)&&(Z.length===0||Array.isArray(Z[0])))return t(Z,X);return Tj(j,X)}function Tj(j,X){let Z=Array.isArray(j.all)?"all":Array.isArray(j.any)?"any":null;if(!Z)return null;let $=j[Z];if($.length===0)return null;let J=$.map((Q)=>b(Q,X));return Z==="all"?J.every(Boolean):J.some(Boolean)}function Ij(j){if(typeof j==="string"&&i.test(j))return!0;return console.warn(`[phlex-reactive] refused cross-root show target ${JSON.stringify(j)} — skipped`),!1}var kj='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Sj(j){return j.querySelectorAll?.(kj)?.[0]??null}function e(j){if(Array.isArray(j))return j;if(typeof j!=="string")return[];try{let X=JSON.parse(j);return Array.isArray(X)?X:[]}catch{return[]}}function jj(j,X){for(let Z of j){if(!Array.isArray(Z))continue;let[$,J={}]=Z;if(!Object.hasOwn(v,$)){console.warn(`[phlex-reactive] unknown client op ${JSON.stringify($)} — skipped`);continue}for(let Q of X(J))v[$](Q,J)}}function bj(j,X){let Z=j.to;if(X){if(Z==="@root")return[X];if(typeof Z!=="string"||Z==="")return[];if(j.global)return[...document.querySelectorAll(Z)];return[...X.querySelectorAll(Z)]}if(typeof Z!=="string"||Z===""||Z==="@root")return[];return[...document.querySelectorAll(Z)]}class sj extends Xj{static values={token:String};#h;#N=new Map;#q=new Map;#Yj;#F;#y;#C=0;#Y=new Map;#R=new WeakMap;#M=new Map;#v=new WeakSet;#U;#H;#W;#j;#$;#_;#f=!1;#D=0;#p=!1;#L;#A;connect(){if(E=!0,this.element.id==="")console.warn("[phlex-reactive] a reactive root has no id; its next-action token can't self-match "+"and may fall back to the first token in the response → a silent HTTP 403 on the NEXT action. "+"Put id: on the SAME element as reactive_attrs — use div(**reactive_root) (emits id + token together), "+"or div(id:, **reactive_attrs). The id: must NOT be on a child. See the README.");if(this.element.getAttribute?.("data-reactive-defer-token"))this.#u(),this.#A=()=>this.#u(),this.element.addEventListener?.("turbo:morph-element",this.#A);if(this.#Uj()){if(this.#U=()=>this.#I(),this.element.addEventListener?.("turbo:morph-element",this.#U),this.#I(),this.element.getAttribute?.("data-reactive-warn-unsaved")==="true")this.#kj()}if(this.#bj())this.#j=()=>this.#t(),this.element.addEventListener?.("input",this.#j),this.element.addEventListener?.("change",this.#j),this.element.addEventListener?.("turbo:morph-element",this.#j),this.#t();if(this.#P())this.#$=(j)=>{if(j?.type==="input"&&!this.#fj(j))return;this.#V()},this.element.addEventListener?.("input",this.#$),this.element.addEventListener?.("turbo:morph-element",this.#$),this.#V();if(this.#E())this.#_=()=>this.#b(),this.element.addEventListener?.("turbo:morph-element",this.#_),this.#b();if(this.#vj())this.#L=()=>this.recompute(),this.element.addEventListener?.("turbo:morph-element",this.#L),this.recompute()}#Uj(){if((this.element.getAttribute?.("data-action")??"").includes("reactive#trackDirty"))return!0;let j=this.element.querySelectorAll?.('[data-action*="reactive#trackDirty"]')??[];for(let X of j)if(this.#Z(X))return!0;return!1}disconnect(){if(this.#Bj(),this.#xj(),this.#Sj(),this.#yj(),this.#pj(),this.#oj(),this.#sj(),this.#A)this.element.removeEventListener?.("turbo:morph-element",this.#A)}#u(){let j=this.element;if(!j?.id)return;let X=j.getAttribute?.("data-reactive-defer-token");if(!X)return;if(j.getAttribute?.("data-reactive-defer-pending")!=="true")return;P(j.id,X)}dispatch(j){let{action:X,params:Z,debounce:$,throttle:J,confirm:Q,confirmWhen:G,outside:K,window:z,optimistic:Y}=j.params;if(!X)return;let H=j.params.busy??this.#$X(j.params.loading);if(K&&this.element.contains(j.target))return;let L=j.currentTarget??j.target;if(!z&&!this.#aj(Y,L))j.preventDefault();let W=this.#n(Q,G);if(!W)return this.#d(L,X,Z,$,J,Y,H);Promise.resolve().then(()=>w(W)).catch(()=>!1).then((_)=>{if(_)this.#d(L,X,Z,$,J,Y,H)})}runOps(j){let{ops:X,confirm:Z,confirmWhen:$,outside:J,window:Q}=j.params;if(J&&this.element.contains(j.target))return;if(!Q)j.preventDefault();let G=this.#n(Z,$);if(!G)return this.#Qj(this.#Jj(X));Promise.resolve().then(()=>w(G)).catch(()=>!1).then((K)=>{if(K)this.#Qj(this.#Jj(X))})}trackDirty(){this.#I()}recompute(j){if(j&&this.#v.has(j))return;let X=this.#Wj(),Z=X.map(([q])=>q),$=this.element.getAttribute?.("data-reactive-scope")||null,J=(q)=>$&&!q.includes("[")?`${$}[${q}]`:q,Q=this.#X(),G=new Map,K=(q)=>{if(G.has(q))return G.get(q);let U=null;for(let A of this.element.querySelectorAll(`[name="${J(q)}"]`))if(Q(A)){U=A;break}return G.set(q,U),U};for(let q of Z)this.#g(q,K(q)?.value??"");let z=this.element.getAttribute("data-reactive-compute-reducer-param"),Y=z?Zj(z):null;if(!Y){this.#c({},K);return}let H=this.#Hj("data-reactive-compute-outputs-param"),L={};for(let[q,U]of X){let A=K(q);if(U==="string")L[q]=A?.value??"";else{let V=Number(A?.value);L[q]=Number.isFinite(V)?V:0}}let W=Y(L,{changed:this.#_j(j,Z,$)})||{},_=[];for(let q of H){if(!(q in W))continue;let U=K(q);if(!U)continue;if(String(W[q])===U.value)continue;U.value=W[q],_.push(U)}for(let q of Object.keys(W)){let U=W[q];if(U===void 0||U===null)continue;this.#g(q,U)}this.#c(W,K);for(let q of _){let U=new Event("input",{bubbles:!0});this.#v.add(U),q.dispatchEvent(U)}}listnavNext(j){this.#m(j,1)}listnavPrev(j){this.#m(j,-1)}listnavPick(j){let X=this.#B(j),Z=X.findIndex(($)=>$.hasAttribute("data-reactive-highlighted"));if(Z<0)return;j.preventDefault(),X[Z].click()}listnavClose(j){for(let X of this.#B(j))X.removeAttribute("data-reactive-highlighted")}#m(j,X){let Z=this.#B(j);if(!Z.length)return;j.preventDefault();let $=Z.findIndex((G)=>G.hasAttribute("data-reactive-highlighted")),J=$<0?X>0?0:Z.length-1:($+X+Z.length)%Z.length;for(let G of Z)G.removeAttribute("data-reactive-highlighted");let Q=Z[J];Q.setAttribute("data-reactive-highlighted","true"),Q.scrollIntoView?.({block:"nearest"})}#B(j){let Z=(j?.currentTarget??j?.target??this.element).getAttribute?.("data-reactive-listnav-option-param")??this.element.getAttribute("data-reactive-listnav-option-param");if(!Z)return[];let $=this.#X();return Array.from(this.element.querySelectorAll(Z)).filter((J)=>!J.hidden&&$(J))}tagsAdd(j){if(!this.#E())return;if(j?.defaultPrevented)return;if(this.#B(j).some(($)=>$.hasAttribute?.("data-reactive-highlighted")))return;j?.preventDefault?.();let X=j?.currentTarget??j?.target;if(!X)return;if(!this.#Xj(String(X.value??"").split(",")))return;if(X.value="",this.#P())this.#V()}tagsPick(j){if(!this.#E())return;j?.preventDefault?.();let Z=(j?.currentTarget??j?.target)?.getAttribute?.("data-reactive-tag-param");if(!Z)return;if(!this.#Xj([Z]))return;let $=this.#uj();if(!$)return;$.value="",this.#V(),$.focus?.()}tagsRemove(j){if(!this.#E())return;j?.preventDefault?.();let Z=(j?.currentTarget??j?.target)?.getAttribute?.("data-reactive-tag-param");if(!Z)return;let $=this.#k();if(!$)return;let J=this.#S($),Q=J.filter((G)=>G.toLowerCase()!==Z.toLowerCase());if(Q.length===J.length)return;this.#Zj($,Q)}nestedAdd(j){j?.preventDefault?.();let Z=(j?.currentTarget??j?.target)?.getAttribute?.("data-reactive-association-param");if(!Z)return;if(typeof this.element?.querySelectorAll!=="function")return;let $=this.#X(),J=[...this.element.querySelectorAll(`[data-reactive-nested-list="${Z}"]`)].find($),G=[...this.element.querySelectorAll(`[data-reactive-nested-template="${Z}"]`)].find($)?.content?.firstElementChild;if(!J||!G){this.#lj(Z);return}let K=G.cloneNode(!0);this.#dj(K,this.#cj()),J.appendChild(K),[...K.querySelectorAll?.("input, select, textarea")??[]][0]?.focus?.()}nestedRemove(j){j?.preventDefault?.();let Z=(j?.currentTarget??j?.target)?.closest?.("[data-reactive-nested-row]");if(!Z)return;if(Z.closest?.('[data-controller~="reactive"]')!==this.element)return;let $=[...Z.querySelectorAll?.('input[name$="[_destroy]"]')??[]][0];if($){if($.value="1",typeof $.dispatchEvent==="function")$.dispatchEvent(new Event("input",{bubbles:!0}));Z.hidden=!0}else Z.parentNode?.removeChild?.(Z)}#Hj(j){let X=this.element.getAttribute(j);if(!X)return[];try{let Z=JSON.parse(X);return Array.isArray(Z)?Z:[]}catch{return[]}}#Wj(){let j=this.element.getAttribute("data-reactive-compute-inputs-param");if(!j)return[];try{let X=JSON.parse(j);if(Array.isArray(X))return X.map((Z)=>[Z,"number"]);if(X&&typeof X==="object")return Object.entries(X);return[]}catch{return[]}}#_j(j,X,Z){let $=j?.target;if(!$?.name||typeof $.closest!=="function")return null;let J=this.#Lj($.name,Z);if(!X.includes(J))return null;return this.#Z($)?J:null}#Lj(j,X){if(!X)return j;let Z=`${X}[`;return j.startsWith(Z)&&j.endsWith("]")?j.slice(Z.length,-1):j}#g(j,X){let Z=String(X);for(let $ of this.#Vj(j)){if($.textContent===Z)continue;$.textContent=Z}}#Vj(j){let X=this.element.querySelectorAll(`[data-reactive-text="${j}"]`);return Array.from(X).filter((Z)=>this.#Z(Z))}#c(j,X){let Z=this.#Nj();for(let[$,J]of Object.entries(Z)){let Q=$ in j?j[$]:X($)?.value;if(Q===void 0||Q===null)continue;let G=String(Q);for(let K of Array.isArray(J)?J:[J]){if(!Fj(K))continue;for(let z of document.querySelectorAll(K)){if(z.textContent===G)continue;z.textContent=G}}}}#Nj(){let j=this.element.getAttribute("data-reactive-compute-mirror-param");if(!j)return{};try{let X=JSON.parse(j);return X&&typeof X==="object"&&!Array.isArray(X)?X:{}}catch{return{}}}#d(j,X,Z,$,J,Q,G){if(this.#x("reactive:before-dispatch",{action:X,params:this.#$j(Z),element:this.element},{cancelable:!0}).defaultPrevented)return;let z=Number($)||0;if(z>0)return this.#Aj(j,z,X,Z,Q,G);let Y=Number(J)||0;if(Y>0)return this.#Oj(j,Y,X,Z,Q,G);return this.#O(X,Z,Q,j,G)}#O(j,X,Z,$,J){let Q=this.#rj(Z,$),G=this.#tj(j,$,J),K=this.#l()?this.#Mj(Z,$):null;return this.queue=(this.queue??Promise.resolve()).then(()=>this.#Dj(j,X,Q,G,K)),this.queue}#Mj(j,X){if(!j?.hide)return null;let Z=this.#Kj(j,X);if(!Z.length)return null;return()=>{let $=Z.filter((J)=>J.isConnected&&!J.hidden);if(!$.length)return;console.warn("[phlex-reactive] optimistic: { hide: true } was undone by the reply's re-render — "+"the element is visible again. For an instant delete, return reply.remove so the server removes it; otherwise the hide only flashes.",$)}}#Aj(j,X,Z,$,J,Q){this.#T(j);let G=()=>{this.#T(j),this.#O(Z,$,J,j,Q)},K=setTimeout(G,X);j?.addEventListener?.("blur",G,{once:!0}),this.#N.set(j,{timer:K,flush:G})}#T(j){let X=this.#N.get(j);if(!X)return;clearTimeout(X.timer),j?.removeEventListener?.("blur",X.flush),this.#N.delete(j)}#Bj(){for(let j of[...this.#N.keys()])this.#T(j)}#Oj(j,X,Z,$,J,Q){let G=this.#q.get(j)??new Map;if(G.has(Z))return;let K=setTimeout(()=>{if(G.delete(Z),G.size===0)this.#q.delete(j)},X);return G.set(Z,K),this.#q.set(j,G),this.#O(Z,$,J,j,Q)}#xj(){for(let j of this.#q.values())for(let X of j.values())clearTimeout(X);this.#q.clear()}#x(j,X,{cancelable:Z=!1}={}){let $=new CustomEvent(j,{bubbles:!0,composed:!0,cancelable:Z,detail:X});return(this.element.isConnected?this.element:document).dispatchEvent($),$}#J(j,X,Z,$){let J=()=>{if(!this.element.isConnected){console.warn("[phlex-reactive] retry() ignored — the reactive root left the DOM");return}return this.#O(j,X)};this.#x("reactive:error",{action:j,params:Z,...$,retry:J})}#Q(j){if(this.element?.isConnected===!1)return;this.element?.setAttribute?.("data-reactive-error",j)}#Pj(){this.element?.removeAttribute?.("data-reactive-error")}#Ej(){let j=document.querySelector("[data-reactive-error-flash]");if(!j?.content)return;let X=j.getAttribute("data-reactive-error-flash")||"flash",Z=document.getElementById(X);if(!Z)return;Z.appendChild(j.content.cloneNode(!0))}#Fj(){if(typeof sessionStorage>"u")return Promise.resolve();let j=Number(sessionStorage.getItem(S));if(!Number.isFinite(j)||j<=0)return Promise.resolve();if(!O)O=!0,console.warn(`[phlex-reactive] latency simulator ACTIVE — every action is delayed by ${j}ms. Call PhlexReactive.disableLatencySim() (or clear sessionStorage) to turn it off.`);return new Promise((X)=>setTimeout(X,j))}#l(){return this.element?.getAttribute?.("data-reactive-debug")==="true"}#o(){return typeof performance<"u"&&typeof performance.now==="function"?performance.now():Date.now()}#Cj(j){if(!j)return[];let X=[],Z=/<turbo-stream\b([^>]*)>/g,$;while(($=Z.exec(j))!==null){let J=$[1],Q=J.match(/\baction="([^"]*)"/)?.[1]??"?",G=J.match(/\btarget="([^"]*)"/)?.[1];X.push(G?`${Q} → #${G}`:Q)}return X}#Rj(j){let{action:X,status:Z,ms:$}=j,Q=`reactive ${this.element?.id?`#${this.element.id} `:""}${X} → ${Z??"—"} (${Math.round($)}ms)`;if(console.groupCollapsed(Q),console.log(`params: [${j.paramNames.join(", ")}] + collected: [${j.fieldNames.join(", ")}]`),console.log(`encoding: ${j.encoding}`),j.streams.length)console.log(`streams: ${j.streams.join(" ")}`);console.log(`token: ${j.tokenRefreshed?"refreshed ✓":"unchanged"}`),console.groupEnd()}async#Dj(j,X,Z,$,J){let{fields:Q,files:G}=this.#a(),K=this.#$j(X),z={...Q,...K},Y=this.#G,H=G.length>0,L=H?this.#ij(Y,j,z,G):JSON.stringify({token:Y,act:j,params:z}),W=this.#l()?{action:j,paramNames:Object.keys(K),fieldNames:Object.keys(Q),encoding:H?"multipart":"json",status:null,streams:[],tokenRefreshed:!1,started:this.#o()}:null;await this.#Fj();try{if(navigator.onLine===!1){this.#z(Z),this.#Q("offline"),this.#J(j,X,z,{kind:"offline"});return}let _;try{let V={Accept:"text/vnd.turbo-stream.html","X-CSRF-Token":this.#GX()};if(!H)V["Content-Type"]="application/json";let B=this.#zX();if(B)V["X-Pgbus-Connection"]=B;_=await fetch(this.#JX(),{method:"POST",headers:V,body:L,credentials:"same-origin",signal:AbortSignal.timeout(this.#QX())})}catch(V){if(console.error("[phlex-reactive] action error",V),this.#z(Z),V?.name==="TimeoutError"||V?.name==="AbortError"){this.#Q("timeout"),this.#J(j,X,z,{kind:"timeout"});return}this.#Ej(),this.#Q("network"),this.#J(j,X,z,{kind:"network"});return}if(W)W.status=_.status;if(_.redirected){console.error("[phlex-reactive] action was redirected (auth/CSRF?) — no update applied"),this.#z(Z),this.#Q("redirected"),this.#J(j,X,z,{kind:"redirected",status:_.status});return}if(!_.ok){let V=await _.text();if(console.error(`[phlex-reactive] action failed: HTTP ${_.status}`,V),this.#z(Z),(_.headers.get("Content-Type")||"").includes("turbo-stream")){let B=this.#i(V);if(this.#G=B??this.#G,W)this.#s(W,V,B);window.Turbo.renderStreamMessage(V)}this.#Q("http"),this.#J(j,X,z,{kind:"http",status:_.status,body:V});return}let q=_.headers.get("Content-Type")||"";if(!q.includes("turbo-stream")){console.error(`[phlex-reactive] expected a turbo-stream, got "${q}" — no update applied`),this.#z(Z),this.#Q("content-type"),this.#J(j,X,z,{kind:"content-type",status:_.status});return}let U=await _.text(),A=this.#i(U);if(this.#G=A??this.#G,W)this.#s(W,U,A);if(window.Turbo.renderStreamMessage(U),J)queueMicrotask(J);this.#Pj(),this.#x("reactive:applied",{action:j,params:z,html:U})}catch(_){console.error("[phlex-reactive] action error",_),this.#z(Z),this.#x("reactive:error",{action:j,params:z,kind:"apply"})}finally{if($?.(),W)this.#Rj({...W,ms:this.#o()-W.started})}}#s(j,X,Z){j.streams=this.#Cj(X),j.tokenRefreshed=Z!=null}get#G(){return this.#h??this.tokenValue}set#G(j){this.#h=j}#i(j){let X=this.element.id;if(!X)return j.match(/data-reactive-token-value="([^"]+)"/)?.[1];let{token:Z,self:$}=this.#Tj(X),J=j.match(Z);if(J)return J[1];let Q=j.match($);if(Q)return Q[1].match(/data-reactive-token-value="([^"]+)"/)?.[1];return}#Tj(j){let X=this.#y;if(X&&X.id===j)return X;let Z=Bj(j);return this.#y={id:j,token:new RegExp(`<turbo-stream\\b[^>]*\\baction="reactive:token"[^>]*\\btarget="${Z}"[^>]*\\bdata-reactive-token-value="([^"]+)"`),self:new RegExp(`<turbo-stream\\b[^>]*\\baction="(?:replace|update)"[^>]*\\btarget="${Z}"[^>]*>([\\s\\S]*?)</turbo-stream>`)}}#Z(j){return j.closest('[data-controller~="reactive"]')===this.element}#X(){if(this.element.querySelectorAll('[data-controller~="reactive"]').length===0)return()=>!0;return(X)=>this.#Z(X)}#n(j,X){if(j)return j;if(!X)return null;let Z=X;if(typeof X==="string")try{Z=JSON.parse(X)}catch{return console.warn(`[phlex-reactive] malformed conditional confirm payload ${JSON.stringify(X)} — skipped`),null}if(!Z||typeof Z!=="object")return null;let{fields:$}=this.#a(),J=(G)=>$[G],Q;if(typeof Z.predicate==="string"){let G=$j(Z.predicate);if(!G)return console.warn(`[phlex-reactive] confirm predicate "${Z.predicate}" is not registered — proceeding without a dialog (register it with setConfirmPredicate)`),null;Q=!!G($)}else Q=t(Z.groups?.any,J)===!0;return Q?Z.message:null}#a(){let j={},X=[],Z=this.#X();return this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach(($)=>{if(!Z($))return;if($.type==="file")for(let J of $.files??[])X.push({name:$.name,file:J,multiple:$.multiple});else if($.type==="checkbox")j[$.name]=$.checked;else if($.type==="radio"){if($.checked)j[$.name]=$.value}else j[$.name]=$.value}),this.element.querySelectorAll("[name]:is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])").forEach(($)=>{if(!Z($))return;let J=$.getAttribute("name");if(!J)return;let Q=j[J];if(Q==null||Q==="")j[J]=$.value??$.textContent??$.innerHTML??""}),{fields:j,files:X}}#I(){if(typeof this.element?.querySelectorAll!=="function")return;let j=0;if(this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach((X)=>{if(!this.#Z(X))return;if(X.type==="file")return;if(this.#Ij(X))X.setAttribute("data-reactive-dirty","true"),j++;else X.removeAttribute("data-reactive-dirty")}),j>0)this.element.setAttribute("data-reactive-dirty",String(j));else this.element.removeAttribute("data-reactive-dirty")}#Ij(j){if(j.type==="checkbox"||j.type==="radio")return j.checked!==j.defaultChecked;if(j.tag==="select"||j.options)return Array.from(j.options??[]).some((X)=>X.selected!==X.defaultSelected);return j.value!==j.defaultValue}#r(){let j=this.element.getAttribute?.("data-reactive-dirty"),X=Number(j);return Number.isFinite(X)&&X>0?X:0}#kj(){if(typeof window>"u"||typeof window.addEventListener!=="function")return;this.#H=(j)=>{if(this.#r()===0)return;return j.preventDefault(),j.returnValue="You have unsaved changes.",j.returnValue},this.#W=(j)=>{if(this.#r()===0)return;if(!(typeof window.confirm==="function"?window.confirm("You have unsaved changes. Leave anyway?"):!0))j.preventDefault?.()},window.addEventListener("beforeunload",this.#H),window.addEventListener("turbo:before-visit",this.#W)}#Sj(){if(this.#U)this.element.removeEventListener?.("turbo:morph-element",this.#U),this.#U=void 0;if(typeof window<"u"&&typeof window.removeEventListener==="function"){if(this.#H)window.removeEventListener("beforeunload",this.#H);if(this.#W)window.removeEventListener("turbo:before-visit",this.#W)}this.#H=void 0,this.#W=void 0}#bj(){if(this.element.getAttribute?.("data-reactive-show-targets"))return!0;let j=this.element.querySelectorAll?.(f)??[];for(let X of j)if(this.#Z(X))return!0;return!1}#t(){if(typeof this.element?.querySelectorAll!=="function")return;let j=this.#X(),X=this.element.getAttribute?.("data-reactive-scope")||null,Z=new Map,$=(J)=>{if(!Z.has(J))Z.set(J,this.#jj(J,j,X));return Z.get(J)};for(let J of this.element.querySelectorAll(f)){if(!j(J))continue;let Q=J.getAttribute("data-reactive-show");if(Q!==null){let Y=Dj(Rj(Q),$);if(Y!==null)this.#e(J,Y,j,X);continue}let G=J.getAttribute("data-reactive-show-field");if(!G)continue;let K=$(G);if(K===null)continue;let z=Cj(J,K);if(z===null)continue;this.#e(J,z,j,X)}this.#wj(j,Z,X)}#e(j,X,Z,$){if(j.hidden=!X,j.getAttribute("data-reactive-show-disable")!=="true")return;if(typeof j.querySelectorAll!=="function")return;for(let J of j.querySelectorAll("input[name], select[name], textarea[name]"))if(Z(J))J.disabled=!X;if(j.name&&Z(j))j.disabled=!X}#wj(j,X,Z){let $=this.#hj();for(let[J,Q]of Object.entries($)){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;if(!X.has(J))X.set(J,this.#jj(J,j,Z));let G=X.get(J);if(G===null)continue;let K=()=>G;for(let[z,Y]of Object.entries(Q)){if(!Ij(z))continue;let H;if(Array.isArray(Y)){if(Y.length===0){console.warn(`[phlex-reactive] malformed reactive_show_targets group for ${z} — skipped`);continue}H=Y.every((L)=>b(L,K))}else{let L=r(Y,G);if(L===null){console.warn(`[phlex-reactive] malformed reactive_show_targets predicate for ${z} — skipped`);continue}H=L}for(let L of document.querySelectorAll(z))L.hidden=!H}}}#hj(){let j=this.element.getAttribute?.("data-reactive-show-targets");if(!j)return{};try{let X=JSON.parse(j);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return console.warn("[phlex-reactive] malformed data-reactive-show-targets — ignored. "+"Did two reactive_show_targets calls collide on one root? Declare every field in ONE call: reactive_show_targets(mode: { ... }, kind: { ... })"),{}}#jj(j,X,Z){let $=Z&&!j.includes("[")?`${Z}[${j}]`:j,J=!1,Q=null;for(let G of this.element.querySelectorAll(`[name="${$}"]`)){if(!X(G))continue;if(G.type==="checkbox")return G.checked?"true":"false";if(G.type==="radio"){if(G.checked)return G.value??"";J=!0;continue}Q??=G}if(Q)return Q.value??"";return J?"":null}#yj(){if(!this.#j)return;this.element.removeEventListener?.("input",this.#j),this.element.removeEventListener?.("change",this.#j),this.element.removeEventListener?.("turbo:morph-element",this.#j),this.#j=void 0}#P(){return!!(this.element.getAttribute?.("data-reactive-filter-input")&&this.element.getAttribute?.("data-reactive-filter-option"))}#vj(){return this.element.getAttribute?.("data-reactive-compute-seed")==="true"}#fj(j){let X=this.element.getAttribute("data-reactive-filter-input");return!!X&&typeof j.target?.matches==="function"&&j.target.matches(X)}#V(){if(typeof this.element?.querySelectorAll!=="function")return;let j=this.element.getAttribute("data-reactive-filter-input"),X=this.element.getAttribute("data-reactive-filter-option");if(!j||!X)return;let Z=this.#X(),$=[...this.element.querySelectorAll(j)].find(Z);if(!$)return;let J=($.value??"").trim().toLowerCase(),Q=0;for(let z of this.element.querySelectorAll(X)){if(!Z(z))continue;let Y=(z.getAttribute("data-reactive-filter-text")??z.textContent??"").toLowerCase(),H=z.hasAttribute?.("data-reactive-tags-selected")||J!==""&&!Y.includes(J);if(z.hidden=H,H)z.removeAttribute("data-reactive-highlighted");else Q++}let G=this.element.getAttribute("data-reactive-filter-group");if(G)for(let z of this.element.querySelectorAll(G)){if(!Z(z))continue;let Y=[...z.querySelectorAll(X)].filter(Z);if(Y.length===0)continue;z.hidden=Y.every((H)=>H.hidden)}let K=this.element.getAttribute("data-reactive-filter-empty");if(K){for(let z of this.element.querySelectorAll(K))if(Z(z))z.hidden=Q>0}}#pj(){if(!this.#$)return;this.element.removeEventListener?.("input",this.#$),this.element.removeEventListener?.("turbo:morph-element",this.#$),this.#$=void 0}#E(){return!!this.element.getAttribute?.("data-reactive-tags-field")}#k(){if(typeof this.element?.querySelectorAll!=="function")return null;let j=this.element.getAttribute("data-reactive-tags-field");if(!j)return null;let X=this.#X();return[...this.element.querySelectorAll(j)].find(X)??null}#S(j){let X=new Set,Z=[];for(let $ of String(j.value??"").split(",")){let J=$.trim();if(J===""||X.has(J.toLowerCase()))continue;X.add(J.toLowerCase()),Z.push(J)}return Z}#Xj(j){let X=this.#k();if(!X)return!1;let Z=this.#S(X),$=new Set(Z.map((Q)=>Q.toLowerCase())),J=!1;for(let Q of j){let G=String(Q??"").trim();if(G===""||$.has(G.toLowerCase()))continue;$.add(G.toLowerCase()),Z.push(G),J=!0}if(J)this.#Zj(X,Z);return J}#Zj(j,X){if(j.value=X.join(","),typeof j.dispatchEvent==="function")j.dispatchEvent(new Event("input",{bubbles:!0}));this.#b()}#uj(){if(typeof this.element?.querySelectorAll!=="function")return null;let j=this.element.getAttribute("data-reactive-filter-input");if(!j)return null;let X=this.#X();return[...this.element.querySelectorAll(j)].find(X)??null}#b(){let j=this.#k();if(!j)return;let X=this.#S(j),Z=this.#X();this.#mj(X,Z),this.#gj(X,Z)}#mj(j,X){let Z=[...this.element.querySelectorAll("[data-reactive-tags-list]")].find(X);if(!Z)return;let J=[...this.element.querySelectorAll("[data-reactive-tags-template]")].find(X)?.content?.firstElementChild;if(!J){if(!this.#f)console.warn("[phlex-reactive] reactive_tags: no chip <template data-reactive-tags-template> found in this root — "+"chips will not render (the hidden field still updates). Add a template with a [data-reactive-tag-text] node and a reactive_tags_remove button."),this.#f=!0;return}while(Z.firstChild)Z.removeChild(Z.firstChild);for(let Q of j){let G=J.cloneNode(!0);G.setAttribute?.("data-reactive-tag",Q);let K=G.matches?.("[data-reactive-tag-text]")?G:(G.querySelectorAll?.("[data-reactive-tag-text]")??[])[0];if(K)K.textContent=Q;let z=[...G.querySelectorAll?.('[data-action*="reactive#tagsRemove"]')??[]];if(G.matches?.('[data-action*="reactive#tagsRemove"]'))z.push(G);for(let Y of z)Y.setAttribute?.("data-reactive-tag-param",Q);Z.appendChild(G)}}#gj(j,X){let Z=new Set(j.map(($)=>$.toLowerCase()));for(let $ of this.element.querySelectorAll("[role=option]")){if(!X($))continue;let J=$.getAttribute?.("data-reactive-tag-param");if(!J)continue;if(Z.has(J.toLowerCase()))$.setAttribute("data-reactive-tags-selected","true"),$.hidden=!0,$.removeAttribute?.("data-reactive-highlighted");else if($.hasAttribute?.("data-reactive-tags-selected")){if($.removeAttribute("data-reactive-tags-selected"),!this.#P())$.hidden=!1}}if(this.#P())this.#V()}#cj(){return this.#D=Math.max(this.#D+1,Date.now()),this.#D}#dj(j,X){let Z=[j,...j.querySelectorAll?.("*")??[]];for(let $ of Z)for(let J of["name","id","for"]){let Q=$.getAttribute?.(J);if(Q&&Q.includes("NEW_ROW"))$.setAttribute?.(J,Q.replaceAll("NEW_ROW",String(X)))}}#lj(j){if(this.#p)return;console.warn(`[phlex-reactive] nested rows: no owned [data-reactive-nested-list="${j}"] container + <template data-reactive-nested-template="${j}"> pair found in this root — the add `+"trigger did nothing. Render both inside the same reactive root (reactive_nested_list / reactive_nested_template)."),this.#p=!0}#oj(){if(!this.#_)return;this.element.removeEventListener?.("turbo:morph-element",this.#_),this.#_=void 0}#sj(){if(!this.#L)return;this.element.removeEventListener?.("turbo:morph-element",this.#L),this.#L=void 0}#ij(j,X,Z,$){let J=new FormData;J.append("token",j),J.append("act",X);for(let[G,K]of Object.entries(Z))this.#w(J,`params[${G}]`,K);let Q=this.#nj($);for(let{name:G,file:K,multiple:z}of $){let H=z||Q.has(G)?`params[${G}][]`:`params[${G}]`;J.append(H,K,K.name)}return J}#w(j,X,Z){if(Z==null)j.append(X,"");else if(Array.isArray(Z))Z.forEach(($,J)=>this.#w(j,`${X}[${J}]`,$));else if(typeof Z==="object")for(let[$,J]of Object.entries(Z))this.#w(j,`${X}[${$}]`,J);else j.append(X,String(Z))}#nj(j){let X=new Map;for(let{name:Z}of j)X.set(Z,(X.get(Z)??0)+1);return new Set([...X].filter(([,Z])=>Z>1).map(([Z])=>Z))}#$j(j){if(!j)return{};try{return typeof j==="string"?JSON.parse(j):j}catch{return{}}}#Jj(j){return e(j)}#Qj(j){jj(j,(X)=>this.#Gj(X))}#Gj(j){let X=j.to;if(X==="@root")return[this.element];if(typeof X!=="string"||X==="")return[];if(j.global)return[...document.querySelectorAll(X)];return[...this.element.querySelectorAll(X)].filter((Z)=>this.#Z(Z))}#aj(j,X){if(j?.checked!=="keep")return!1;let Z=X?.type;return Z==="checkbox"||Z==="radio"}#rj(j,X){if(!j)return null;let Z=this.#zj(j,X,!0);return Z.length?Z:null}#z(j){if(!j)return;if(!this.element.isConnected)return;for(let X of j)X()}#tj(j,X,Z){this.#jX(j,X);let $=Z?this.#zj(Z,X,!1):[];l();let J=!1;return()=>{if(J)return;J=!0,this.#XX(j,X),o();for(let Q of $)Q()}}#zj(j,X,Z){let $=[];for(let J of this.#Kj(j,X)){if(j.add_class){let Q=j.add_class.filter((G)=>!J.classList.contains(G));if(J.classList.add(...Q),Q.length)$.push(()=>J.classList.remove(...Q))}if(j.remove_class){let Q=j.remove_class.filter((G)=>J.classList.contains(G));if(J.classList.remove(...Q),Q.length)$.push(()=>J.classList.add(...Q))}if(j.toggle_class)j.toggle_class.forEach((Q)=>J.classList.toggle(Q)),$.push(()=>j.toggle_class.forEach((Q)=>J.classList.toggle(Q)));if(j.hide)J.hidden=!0,$.push(()=>J.hidden=!1);if(j.show)J.hidden=!1,$.push(()=>J.hidden=!0)}if(X&&(j.disable||j.text!=null))$.push(this.#ej(j,X));if(Z&&j.checked==="keep"&&X&&"checked"in X){let J=X.checked;$.push(()=>X.checked=!J)}return $}#Kj(j,X){if(j.to==null)return X?[X]:[];return this.#Gj({to:j.to})}#ej(j,X){let Z=this.#M.get(X);if(Z)Z.count++;else this.#M.set(X,{count:1,disabled:X.disabled,html:X.innerHTML,hadText:j.text!=null,swappedTo:j.text});if(j.disable)X.disabled=!0;if(j.text!=null)X.innerHTML=j.text;return()=>this.#ZX(X,j)}#jX(j,X){if(this.#K(X,j,1),this.#K(this.element,j,1),this.#Y.set(j,(this.#Y.get(j)??0)+1),this.#C++===0)this.element.setAttribute("aria-busy","true");for(let Z of this.#qj(j))this.#K(Z,j,1)}#XX(j,X){this.#K(X,j,-1),this.#K(this.element,j,-1);let Z=(this.#Y.get(j)??1)-1;if(Z<=0)this.#Y.delete(j);else this.#Y.set(j,Z);if(--this.#C<=0)this.#C=0,this.element.removeAttribute("aria-busy");for(let $ of this.#qj(j))this.#K($,j,-1)}#K(j,X,Z){if(!j||typeof j.getAttribute!=="function")return;let $=this.#R.get(j)??new Map,J=($.get(X)??0)+Z;if(J<=0)$.delete(X);else $.set(X,J);if($.size===0){this.#R.delete(j),j.removeAttribute("data-reactive-busy");return}this.#R.set(j,$),j.setAttribute("data-reactive-busy",[...$.keys()].join(" "))}#qj(j){return[...this.element.querySelectorAll?.("[data-reactive-busy-on]")??[]].filter((Z)=>Z.getAttribute("data-reactive-busy-on")===j&&this.#Z(Z))}#ZX(j,X){let Z=this.#M.get(j);if(!Z)return;if(--Z.count>0)return;if(this.#M.delete(j),!j.isConnected)return;if(X.disable)j.disabled=Z.disabled;if(Z.hadText&&j.innerHTML===Z.swappedTo)j.innerHTML=Z.html}#$X(j){if(!j||typeof j!=="object")return null;let{class:X,...Z}=j;return X==null?j:{...Z,add_class:X}}#JX(){return this.#Yj??=document.querySelector('meta[name="phlex-reactive-action-path"]')?.content||"/reactive/actions"}#QX(){if(this.#F!=null)return this.#F;let j=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,X=Number(j);return this.#F=Number.isFinite(X)&&X>0?X:30000}#GX(){return document.querySelector('meta[name="csrf-token"]')?.content??""}#zX(){return document.querySelector("pgbus-stream-source[connection-id]")?.getAttribute("connection-id")||document.querySelector('meta[name="pgbus-connection-id"]')?.content||null}}export{fj as resetReactiveDefers,dj as resetReactiveActivity,Jj as registerReactiveVisit,Qj as registerReactiveToken,Vj as registerReactiveOffline,Gj as registerReactiveJs,_j as registerReactiveDismiss,zj as registerReactiveDefer,y as registerReactiveActions,cj as reactiveActivityCount,pj as pendingDeferVia,o as exitReactiveActivity,Bj as escapeRegExp,l as enterReactiveActivity,Nj as enableLatencySim,Mj as disableLatencySim,sj as default,Oj as checkReactiveRegistration,lj as __resetReactiveRegistrationForTest,mj as __resetReactiveOfflineForTest,gj as __resetReactiveLatencyForTest,uj as __resetReactiveDismissForTest,oj as __markReactiveConnectedForTest,S as LATENCY_KEY,d as ACTIVE_ATTR};
2
2
 
3
- //# debugId=5113E7379078B03464756E2164756E21
3
+ //# debugId=C019D09F55CE970764756E2164756E21
4
4
  //# sourceMappingURL=reactive_controller.min.js.map