phlex-reactive 0.12.5 → 0.12.6

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 BX}from"@hotwired/stimulus";import{confirmResolver as C}from"phlex/reactive/confirm";import{computeReducer as _X}from"phlex/reactive/compute";import{confirmPredicate as MX}from"phlex/reactive/confirm_predicate";function AX(){let X=window.Turbo?.StreamActions;if(!X||X["reactive:visit"])return;X["reactive:visit"]=function(){let $=this.getAttribute("data-url");if($)window.Turbo.visit($,{action:"advance"})}}function xX(){let X=window.Turbo?.StreamActions;if(!X||X["reactive:token"])return;X["reactive:token"]=function(){let $=this.getAttribute("data-reactive-token-value"),Q=this.getAttribute("target");if(!$||!Q)return;let j=document.getElementById(Q);if(j)j.setAttribute("data-reactive-token-value",$)}}function PX(){let X=window.Turbo?.StreamActions;if(!X||X["reactive:js"])return;X["reactive:js"]=function(){let $=WX(this.getAttribute("data-reactive-ops"));if(!$.length)return;let Q=this.getAttribute("target"),j=this.getAttribute("data-reactive-verbose")==="true",q=Q?document.getElementById(Q):null;if(Q&&!q){if(j&&!LX(`missing-root|#${Q}`))console.warn(`[phlex-reactive] reactive:js stream target root #${Q} is not in the DOM — its ops were dropped`);return}N($,(Y)=>J0(Y,q),j?(Y,z)=>U0(Y,z,q):void 0)}}var _=new Map;function r(X,$){let Q=!_.has(X);if(_.set(X,$),Q)zX()}function R(X){if(_.delete(X))GX()}function _0(){_.clear(),b=!1}function M0(X){return _.get(X)?.via}var b=!1;function NX(){let X=window.Turbo?.StreamActions;if(!X||X["reactive:defer"])return;if(X["reactive:defer"]=function(){let $=this.getAttribute("target");if(!$)return;if(this.getAttribute("data-reactive-defer-via")==="stream"){DX($,this);return}let Q=this.getAttribute("data-reactive-defer-token");if(!Q)return;F($,Q)},!b&&typeof document<"u"&&document.addEventListener)b=!0,document.addEventListener("turbo:before-stream-render",OX)}function OX(X){let Q=X.target?.getAttribute?.("target");if(!Q)return;let j=Q.startsWith("reactive-defer-src-")?Q.slice(19):Q;if(_.get(j)?.via==="stream")R(j)}function F(X,$){let Q=document.getElementById(X);if(!Q){console.warn(`[phlex-reactive] reactive:defer target #${X} is not on the page — skipped`);return}e(X),XX(Q);let j={via:"fetch",abort:new AbortController,timedOut:!1};r(X,j),RX(X,j,$)}function DX(X,$){let Q=document.getElementById(X);if(!Q){console.warn(`[phlex-reactive] reactive:defer target #${X} is not on the page — skipped`);return}let j=$.getAttribute("data-reactive-defer-src");if(!j)return;if(!globalThis.customElements?.get?.("pgbus-stream-source")){let Y=$.getAttribute("data-reactive-defer-token");if(Y){F(X,Y);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}e(X),XX(Q);let q=document.createElement("pgbus-stream-source");q.id=t(X),q.setAttribute("src",j),q.setAttribute("since-id",$.getAttribute("data-reactive-defer-since-id")??"0"),q.setAttribute("hidden",""),document.body.appendChild(q),r(X,{via:"stream"})}function t(X){return`reactive-defer-src-${X}`}async function RX(X,$,Q){let j=setTimeout(()=>{$.timedOut=!0,$.abort.abort()},CX()),q;try{q=await fetch(FX(),{method:"POST",headers:{Accept:"text/vnd.turbo-stream.html","Content-Type":"application/json","X-CSRF-Token":IX()},body:JSON.stringify({token:Q}),credentials:"same-origin",signal:$.abort.signal})}catch(z){if(clearTimeout(j),_.get(X)!==$)return;console.error("[phlex-reactive] deferred render failed",z),E(X,Q);return}if(_.get(X)!==$){clearTimeout(j);return}if(q.status===204){clearTimeout(j),d(X);return}if(!q.ok){clearTimeout(j),console.error(`[phlex-reactive] deferred render failed: HTTP ${q.status}`),E(X,Q,q.status);return}let Y;try{Y=await q.text()}catch(z){if(clearTimeout(j),_.get(X)!==$)return;console.error("[phlex-reactive] deferred render failed reading the body",z),E(X,Q);return}if(clearTimeout(j),_.get(X)!==$)return;d(X),window.Turbo.renderStreamMessage(Y)}function e(X){let $=_.get(X);if(!$)return;if(R(X),$.via==="fetch")$.abort.abort();else document.getElementById(t(X))?.remove?.()}function XX(X){X.setAttribute("data-reactive-defer-pending","true"),X.setAttribute("aria-busy","true")}function $X(X){X.removeAttribute("data-reactive-defer-pending"),X.removeAttribute("aria-busy")}function d(X){R(X);let $=document.getElementById(X);if(!$)return;$X($),$.removeAttribute("data-reactive-error")}function E(X,$,Q){R(X);let j=document.getElementById(X);if(!j)return;$X(j),j.setAttribute("data-reactive-error","defer");let q=()=>{let Y=document.getElementById(X);if(!Y){console.warn("[phlex-reactive] defer retry() ignored — the target left the DOM");return}Y.removeAttribute("data-reactive-error"),F(X,$)};j.dispatchEvent(new CustomEvent("reactive:error",{bubbles:!0,composed:!0,detail:{kind:"defer",target:X,status:Q,retry:q}}))}function FX(){return document.querySelector('meta[name="phlex-reactive-defer-path"]')?.content||"/reactive/defer"}function IX(){return document.querySelector('meta[name="csrf-token"]')?.content??""}function CX(){let X=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,$=Number(X);return Number.isFinite($)&&$>0?$:30000}var h=!1;function EX(){if(h)return;if(typeof document>"u"||!document.addEventListener)return;h=!0,document.addEventListener("turbo:before-stream-render",TX)}function TX(X){let $=X.detail,Q=$?.render;if(typeof Q!=="function"||Q.__reactiveDismissWrapped){if(typeof requestAnimationFrame==="function")requestAnimationFrame(T);else setTimeout(T,0);return}let j=async(q)=>{await Q(q),T()};j.__reactiveDismissWrapped=!0,$.render=j}function T(){let X=document.querySelectorAll("[data-reactive-dismiss-after]");for(let $ of X){if($.hasAttribute("data-reactive-dismiss-scheduled"))continue;let Q=Number($.getAttribute("data-reactive-dismiss-after"));if(!Number.isFinite(Q)||Q<=0)continue;$.setAttribute("data-reactive-dismiss-scheduled",""),setTimeout(()=>$.remove(),Q)}}function A0(){h=!1}var kX=Object.freeze({append:"enter",prepend:"enter",replace:"update",update:"update",remove:"exit"}),k=Object.freeze(["fade","slide","scale","highlight","shake"]),v="data-reactive-fx-pending",QX=1000,y=!1;function SX(){if(y)return;if(typeof document>"u"||typeof document.addEventListener!=="function")return;y=!0,document.addEventListener("turbo:before-stream-render",wX)}function x0(){y=!1}function wX(X){let $=X.detail,Q=$?.render;if(typeof Q!=="function"||Q.__reactiveEffectsWrapped)return;let j=$?.newStream??X.target,q=kX[j?.getAttribute?.("action")];if(!q||vX())return;let Y=bX(j,q);if(!Y)return;let z=q==="exit"?async(G)=>{await pX(O(j),Y),await Q(G)}:async(G)=>{let Z=q==="enter"?yX(j):null;if(await Q(G),q==="enter")fX(Z,Y);else jX(O(j),Y)};z.__reactiveEffectsWrapped=!0,$.render=z}function bX(X,$){let Q=X.getAttribute?.("data-reactive-effect");if(Q==="off")return null;if(Q)return l(Q,$);let q=($==="enter"?hX(X):O(X))?.getAttribute?.(`data-reactive-effect-${$}`);return q?l(q,$):null}function O(X){let $=X.getAttribute?.("target");return $?document.getElementById?.($)??null:null}function hX(X){return X.querySelector?.("template")?.content?.firstElementChild??null}function l(X,$){if(X.startsWith("[")){let j=null;try{let q=JSON.parse(X);if(Array.isArray(q)&&q.length===3)j=q.map(String)}catch{}if(j)return{legs:j};return console.warn(`[phlex-reactive] malformed effect legs ${JSON.stringify(X)} — skipped`),null}let Q=X==="random"?k[Math.floor(Math.random()*k.length)]:X;if(!k.includes(Q))return console.warn(`[phlex-reactive] unknown effect ${JSON.stringify(X)} — skipped`),null;return{className:`reactive-fx--${Q}-${$}`}}function vX(){try{return typeof matchMedia==="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}}function yX(X){let $=X.querySelector?.("template")?.content;if(!$)return null;for(let Q of Array.from($.children??[]))Q.setAttribute?.(v,"");return O(X)}function fX(X,$){if(typeof X?.querySelectorAll!=="function")return;for(let Q of Array.from(X.querySelectorAll(`[${v}]`)))Q.removeAttribute(v),jX(Q,$)}async function pX(X,$){if(!X?.classList)return;if($.legs){await qX(X,$.legs);return}X.classList.add($.className);let Q=u(X);if(Q<=0){X.classList.remove($.className);return}await m(X,Q),X.classList.remove($.className)}function jX(X,$){if(!X?.classList)return;if($.legs){qX(X,$.legs);return}if(X.classList.contains($.className))X.classList.remove($.className),X.offsetWidth;X.classList.add($.className);let Q=u(X);if(Q<=0){X.classList.remove($.className);return}let j=X.__reactiveFxToken=(X.__reactiveFxToken??0)+1;m(X,Q).then(()=>{if(X.__reactiveFxToken===j)X.classList.remove($.className)})}async function qX(X,$){let[Q,j,q]=$.map(uX),Y=X.__reactiveFxToken=(X.__reactiveFxToken??0)+1;if(X.classList.remove(...Q,...j,...q),X.classList.add(...Q,...j),await mX(),X.__reactiveFxToken!==Y)return;X.classList.remove(...j),X.classList.add(...q);let z=u(X);if(z>0)await m(X,z);if(X.__reactiveFxToken!==Y)return;X.classList.remove(...Q,...q)}function uX(X){return String(X??"").split(/\s+/).filter(Boolean)}function u(X){if(typeof getComputedStyle!=="function")return 0;try{let $=getComputedStyle(X),Q=(Y)=>String(Y??"").split(",").reduce((z,G)=>Math.max(z,parseFloat(G)||0),0),j=Q($.animationDuration)+Q($.animationDelay),q=Q($.transitionDuration)+Q($.transitionDelay);return Math.min(Math.max(j,q)*1000,QX)}catch{return 0}}function m(X,$){return new Promise((Q)=>{let j=!1,q=()=>{if(j)return;j=!0,Q()};X.addEventListener?.("animationend",q,{once:!0}),X.addEventListener?.("transitionend",q,{once:!0}),setTimeout(q,Math.min($+50,QX))})}function mX(){return new Promise((X)=>{if(typeof requestAnimationFrame==="function")requestAnimationFrame(()=>X());else setTimeout(X,16)})}var f=!1;function gX(){if(f)return;if(typeof window>"u"||typeof document>"u")return;if(typeof window.addEventListener!=="function")return;f=!0;let X=()=>{let $=document.documentElement;if(typeof $?.toggleAttribute!=="function")return;$.toggleAttribute("data-reactive-offline",globalThis.navigator?.onLine===!1)};X(),window.addEventListener("online",X),window.addEventListener("offline",X)}function P0(){f=!1}var g="phlex-reactive:latency",D=!1;function cX(X){if(typeof sessionStorage>"u")return;sessionStorage.setItem(g,String(X))}function dX(){if(typeof sessionStorage>"u")return;sessionStorage.removeItem(g),D=!1}function lX(){if(typeof window>"u"||typeof document>"u")return;if(document.querySelector?.('meta[name="phlex-reactive-env"]')?.content!=="development")return;window.PhlexReactive={enableLatencySim:cX,disableLatencySim:dX}}function N0(){D=!1}var YX="data-reactive-active",M=0;function zX(){if(M++,M===1)ZX("reactive:busy")}function GX(){if(M===0)return;if(M--,M===0)ZX("reactive:idle")}function O0(){return M}function D0(){M=0,(typeof document<"u"?document.documentElement:null)?.removeAttribute?.(YX)}function ZX(X){if(typeof document>"u")return;let $=document.documentElement;if(typeof $?.toggleAttribute==="function")$.toggleAttribute(YX,M>0);if(typeof document.dispatchEvent==="function"&&typeof CustomEvent==="function")document.dispatchEvent(new CustomEvent(X,{detail:{count:M}}))}function i(){AX(),xX(),PX(),NX(),EX(),SX(),gX(),lX()}function iX(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}if(typeof window<"u")if(window.Turbo)i();else document.addEventListener("turbo:load",i,{once:!0});var I=!1;function oX(){if(I)return;if(typeof document>"u")return;let X=document.querySelectorAll('[data-controller~="reactive"]');if(!X||X.length===0)return;console.warn("[phlex-reactive] found "+X.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 R0(){I=!1}function F0(){I=!0}if(typeof window<"u"&&typeof document<"u"){let X=()=>setTimeout(oX,0);if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",X,{once:!0});else X()}var sX=new Set(["href","src","srcdoc","action","formaction","xlink:href","style"]);function nX(X){let $=String(X).toLowerCase();return $.startsWith("on")||sX.has($)}function aX(X,$,Q){let[j,q,Y]=$;X.classList.add(j,q),Q(),requestAnimationFrame(()=>{X.classList.remove(q),X.classList.add(Y)});let z=!1,G=()=>{if(z)return;z=!0,X.classList.remove(j,Y)};X.addEventListener("animationend",G,{once:!0}),setTimeout(G,350)}var o=Object.freeze({show:(X,$)=>S(X,!1,$),hide:(X,$)=>S(X,!0,$),toggle:(X,$)=>S(X,!X.hidden,$),add_class:(X,$)=>X.classList.add(...$.classes??[]),remove_class:(X,$)=>X.classList.remove(...$.classes??[]),toggle_class:(X,$)=>($.classes??[]).forEach((Q)=>X.classList.toggle(Q)),set_attr:(X,$)=>{if(w($.name))X.setAttribute($.name,$.value??"")},remove_attr:(X,$)=>{if(w($.name))X.removeAttribute($.name)},toggle_attr:(X,$)=>{if(!w($.name))return;if(X.hasAttribute($.name))X.removeAttribute($.name);else X.setAttribute($.name,"")},focus:(X)=>X.focus?.(),focus_first:(X)=>K0(X)?.focus?.(),text:(X,$)=>{let Q=String($.value??"");if(X.textContent!==Q)X.textContent=Q},dispatch:(X,$)=>{X.dispatchEvent(new CustomEvent($.name,{bubbles:!0,composed:!0,detail:$.detail??{}}))},submit:(X)=>rX(X)?.requestSubmit?.(),paste_into:(X)=>tX(X)});function rX(X){if(X?.tagName==="FORM")return X;return X?.form??X?.closest?.("form")??null}function tX(X){let $=globalThis.navigator?.clipboard;if(typeof $?.readText!=="function")return;$.readText().then((Q)=>{if(!Q)return;if(X.value=Q,typeof X.dispatchEvent==="function")X.dispatchEvent(new Event("input",{bubbles:!0}));X.focus?.()}).catch(()=>{})}function S(X,$,Q){if(Q?.transition)aX(X,Q.transition,()=>X.hidden=$);else X.hidden=$}function w(X){if(!nX(X))return!0;return console.warn(`[phlex-reactive] refused client attr op on ${JSON.stringify(X)} — skipped`),!1}var KX=/^#[A-Za-z_][\w-]*$/;function eX(X){if(typeof X==="string"&&KX.test(X))return!0;return console.warn(`[phlex-reactive] refused cross-root mirror target ${JSON.stringify(X)} — skipped`),!1}function X0(X,$){let Q=X.getAttribute("data-reactive-show-equals");if(Q!==null)return $===Q;let j=X.getAttribute("data-reactive-show-not");if(j!==null)return $!==j;let q=X.getAttribute("data-reactive-show-in");if(q!==null){try{let Y=JSON.parse(q);if(Array.isArray(Y))return Y.includes($)}catch{}return console.warn(`[phlex-reactive] malformed reactive_show in: list ${JSON.stringify(q)} — skipped`),null}for(let Y of HX){let z=X.getAttribute(`data-reactive-show-${Y}`);if(z!==null)return UX(Y,z,$)}return console.warn("[phlex-reactive] a reactive_show binding declares no predicate — skipped"),null}var HX=["gte","gt","lte","lt"],$0=["len_eq","len_gte","len_gt","len_lte","len_lt"];function Q0(X,$,Q){if(!Number.isInteger($))return console.warn(`[phlex-reactive] reactive_show ${X}: needs an integer literal, got ${JSON.stringify($)} — skipped`),null;let j=[...String(Q??"")].length;switch(X){case"len_eq":return j===$;case"len_gte":return j>=$;case"len_gt":return j>$;case"len_lte":return j<=$;case"len_lt":return j<$;default:return null}}function UX(X,$,Q){let j=Number($);if(Number.isNaN(j))return console.warn(`[phlex-reactive] reactive_show ${X}: needs a numeric literal, got ${JSON.stringify($)} — skipped`),null;let q=Q==null?"":String(Q).trim(),Y=q===""?NaN:Number(q);if(Number.isNaN(Y))return!1;switch(X){case"gte":return Y>=j;case"gt":return Y>j;case"lte":return Y<=j;case"lt":return Y<j;default:return null}}function JX(X,$){if(!X||typeof X!=="object")return null;if(typeof X.equals==="string")return $===X.equals;if(typeof X.not==="string")return $!==X.not;if(Array.isArray(X.in))return X.in.includes($);for(let Q of HX)if(Q in X)return UX(Q,X[Q],$);for(let Q of $0)if(Q in X)return Q0(Q,X[Q],$);return null}var s="[data-reactive-show-field], [data-reactive-show]";function j0(X){try{let $=JSON.parse(X);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return console.warn(`[phlex-reactive] malformed compound reactive_show payload ${JSON.stringify(X)} — skipped`),null}function q0(X){try{let $=JSON.parse(X);if(Array.isArray($)&&$.every((Q)=>Q&&typeof Q==="object"&&Array.isArray(Q.any)&&Array.isArray(Q.ops)))return $}catch{}return console.warn(`[phlex-reactive] malformed reactive_on_complete payload ${JSON.stringify(X)} — skipped`),[]}function c(X,$){if(!X||typeof X!=="object"||typeof X.field!=="string")return!1;let Q=$(X.field)??"";return JX(X,Q)===!0}function P(X,$){if(!Array.isArray(X)||X.length===0)return null;return X.some((Q)=>Array.isArray(Q)&&Q.length>0&&Q.every((j)=>c(j,$)))}function Y0(X){if(!Array.isArray(X)||X.length===0)return null;let $=new Set;for(let Q of X){if(!Array.isArray(Q))continue;for(let j of Q)if(j&&typeof j==="object"&&typeof j.field==="string")$.add(j.field)}return $.size>0?[...$]:null}function z0(X,$){if(!X||typeof X!=="object")return null;let Q=X.any;if(Array.isArray(Q)&&(Q.length===0||Array.isArray(Q[0])))return P(Q,$);return G0(X,$)}function G0(X,$){let Q=Array.isArray(X.all)?"all":Array.isArray(X.any)?"any":null;if(!Q)return null;let j=X[Q];if(j.length===0)return null;let q=j.map((Y)=>c(Y,$));return Q==="all"?q.every(Boolean):q.some(Boolean)}function n(X){if(typeof X==="string"&&KX.test(X))return!0;return console.warn(`[phlex-reactive] refused cross-root show target ${JSON.stringify(X)} — skipped`),!1}var Z0='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function K0(X){return X.querySelectorAll?.(Z0)?.[0]??null}function WX(X){if(Array.isArray(X))return X;if(typeof X!=="string")return[];try{let $=JSON.parse(X);return Array.isArray($)?$:[]}catch{return[]}}function H0(X){if(X==null)return null;let $=Array.isArray(X)?X:X.ops;if(Array.isArray($))return $.length>0?$:null;return console.warn("[phlex-reactive] $ops must be an ops chain or a [[op, args], ...] list — skipped"),null}function N(X,$,Q){for(let j of X){if(!Array.isArray(j))continue;let[q,Y={}]=j;if(!Object.hasOwn(o,q)){console.warn(`[phlex-reactive] unknown client op ${JSON.stringify(q)} — skipped`);continue}let z=$(Y);if(z.length===0&&Q)Q(q,Y);for(let G of z)o[q](G,Y)}}var a=new WeakMap;function LX(X){let $=globalThis.document;if(!$)return!0;let Q=a.get($);if(!Q)Q=new Set,a.set($,Q);if(Q.has(X))return!0;return Q.add(X),!1}function p(X,$){try{return X?.querySelectorAll?.($)?.length??0}catch{return 0}}function VX(X,$,Q,j){if(LX(`${X}|${$}|${Q}`))return;console.warn(`[phlex-reactive] ${X} matched zero targets for selector "${$}" (${Q})${j}`)}function U0(X,$,Q){let j=$.to;if(typeof j!=="string"||j===""||j==="@root")return;let q="";if(Q&&!$.global){let Y=p(globalThis.document,j);if(Y>0)q=` — it matches ${Y} element(s) outside the stream's target root; use global: true`}VX(`client op "${X}"`,j,Q?`scoped to #${Q.id||"?"}`:"document-scoped",q)}function J0(X,$){let Q=X.to;if($){if(Q==="@root")return[$];if(typeof Q!=="string"||Q==="")return[];if(X.global)return[...document.querySelectorAll(Q)];return[...$.querySelectorAll(Q)]}if(typeof Q!=="string"||Q===""||Q==="@root")return[];return[...document.querySelectorAll(Q)]}class I0 extends BX{static values={token:String};#a;#P=new Map;#U=new Map;#EX;#S;#r;#w=0;#J=new Map;#b=new WeakMap;#N=new Map;#t=new WeakSet;#e=null;#W;#L;#V;#Q;#Y;#h;#XX;#v;#y;#j;#B;#$X=!1;#f=0;#QX=!1;#q;#_;#M;#O;#A;connect(){if(I=!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.#jX(),this.#O=()=>this.#jX(),this.element.addEventListener?.("turbo:morph-element",this.#O);if(this.#TX()){if(this.#W=()=>this.#c(),this.element.addEventListener?.("turbo:morph-element",this.#W),this.#c(),this.element.getAttribute?.("data-reactive-warn-unsaved")==="true")this.#Q0()}if(this.#q0())this.#Q=()=>this.#MX(),this.element.addEventListener?.("input",this.#Q),this.element.addEventListener?.("change",this.#Q),this.element.addEventListener?.("turbo:morph-element",this.#Q),this.#MX();if(this.#Y0())this.#Y=(X)=>this.#d(X),this.#h=()=>this.#d(null),this.element.addEventListener?.("input",this.#Y),this.element.addEventListener?.("change",this.#Y),this.element.addEventListener?.("turbo:morph-element",this.#h),this.#d(null);if(this.#C())this.#j=(X)=>{if(X?.type==="input"&&!this.#V0(X))return;this.#x()},this.element.addEventListener?.("input",this.#j),this.element.addEventListener?.("turbo:morph-element",this.#j),this.#x();if(this.#E())this.#B=()=>this.#o(),this.element.addEventListener?.("turbo:morph-element",this.#B),this.#o();if(this.#_0())this.#q=(X)=>this.syncNestedJson(X),this.#_=()=>this.#R(),this.element.addEventListener?.("input",this.#q),this.element.addEventListener?.("change",this.#q),this.element.addEventListener?.("turbo:morph-element",this.#_),this.#R();if(this.#L0())this.#M=()=>this.recompute(),this.element.addEventListener?.("turbo:morph-element",this.#M),this.recompute();if(this.#z0())this.#A=()=>this.#_X(),this.element.addEventListener?.("turbo:morph-element",this.#A),this.#_X()}#TX(){if((this.element.getAttribute?.("data-action")??"").includes("reactive#trackDirty"))return!0;let X=this.element.querySelectorAll?.('[data-action*="reactive#trackDirty"]')??[];for(let $ of X)if(this.#$($))return!0;return!1}disconnect(){if(this.#lX(),this.#oX(),this.#j0(),this.#W0(),this.#K0(),this.#B0(),this.#D0(),this.#R0(),this.#F0(),this.#G0(),this.#O)this.element.removeEventListener?.("turbo:morph-element",this.#O)}#jX(){let X=this.element;if(!X?.id)return;let $=X.getAttribute?.("data-reactive-defer-token");if(!$)return;if(X.getAttribute?.("data-reactive-defer-pending")!=="true")return;F(X.id,$)}dispatch(X){let{action:$,params:Q,debounce:j,throttle:q,confirm:Y,confirmWhen:z,outside:G,window:Z,optimistic:K}=X.params;if(!$)return;let U=X.params.busy??this.#y0(X.params.loading);if(G&&this.element.contains(X.target))return;let B=X.currentTarget??X.target;if(!Z&&!this.#T0(K,B))X.preventDefault();let J=this.#g(Y,z);if(!J)return this.#UX(B,$,Q,j,q,K,U);Promise.resolve().then(()=>C(J,{el:B})).catch(()=>!1).then((V)=>{if(V)this.#UX(B,$,Q,j,q,K,U)})}runOps(X){let{ops:$,confirm:Q,confirmWhen:j,outside:q,window:Y}=X.params,z=X.currentTarget??X.target;if(q&&this.element.contains(X.target))return;if(!Y)X.preventDefault();let G=this.#g(Q,j);if(!G)return this.#RX(this.#DX($));Promise.resolve().then(()=>C(G,{el:z})).catch(()=>!1).then((Z)=>{if(Z)this.#RX(this.#DX($))})}trackDirty(){this.#c()}recompute(X){if(X&&this.#t.has(X))return;let $=this.#fX(),Q=$.map(([H])=>H),j=this.element.getAttribute?.("data-reactive-scope")||null,q=(H)=>j&&!H.includes("[")?`${j}[${H}]`:H,Y=this.#X(),z=new Map,G=(H)=>{if(z.has(H))return z.get(H);let W=null;for(let L of this.element.querySelectorAll(`[name="${q(H)}"]`))if(Y(L)){W=L;break}return z.set(H,W),W};for(let H of Q)this.#KX(H,G(H)?.value??"");let Z=this.element.getAttribute("data-reactive-compute-reducer-param"),K=Z?_X(Z):null;if(!K){this.#HX({},G);return}let U=this.#yX("data-reactive-compute-outputs-param"),B={};for(let[H,W]of $){let L=G(H);if(W==="string")B[H]=L?.value??"";else{let A=Number(L?.value);B[H]=Number.isFinite(A)?A:0}}let J=K(B,{changed:this.#pX(X,Q,j)})||{},V=H0(J.$ops),x=[];for(let H of U){if(H==="$ops"||!(H in J))continue;let W=G(H);if(!W)continue;if(String(J[H])===W.value)continue;W.value=J[H],x.push(W)}for(let H of Object.keys(J)){if(H==="$ops")continue;let W=J[H];if(W===void 0||W===null)continue;this.#KX(H,W)}this.#HX(J,G);for(let H of x){let W=new Event("input",{bubbles:!0});this.#t.add(W),H.dispatchEvent(W)}this.#kX(V,Boolean(X))}#kX(X,$){let Q=X===null?null:JSON.stringify(X),j=Q!==null&&Q!==this.#e&&$;if(this.#e=Q,!j)return;N(X,(q)=>this.#k(q.to==null?{...q,to:"@root"}:q),(q,Y)=>this.#T(`client op "${q}"`,Y))}listnavNext(X){this.#qX(X,1)}listnavPrev(X){this.#qX(X,-1)}listnavPick(X){let $=this.#D(X),Q=$.findIndex((j)=>j.hasAttribute("data-reactive-highlighted"));if(Q<0)return;X.preventDefault(),$[Q].click()}listnavClose(X){for(let $ of this.#D(X))$.removeAttribute("data-reactive-highlighted")}#qX(X,$){let Q=this.#D(X);if(!Q.length)return;X.preventDefault();let j=Q.findIndex((z)=>z.hasAttribute("data-reactive-highlighted")),q=j<0?$>0?0:Q.length-1:(j+$+Q.length)%Q.length;for(let z of Q)z.removeAttribute("data-reactive-highlighted");let Y=Q[q];Y.setAttribute("data-reactive-highlighted","true"),Y.scrollIntoView?.({block:"nearest"})}#D(X){let Q=(X?.currentTarget??X?.target??this.element).getAttribute?.("data-reactive-listnav-option-param")??this.element.getAttribute("data-reactive-listnav-option-param");if(!Q)return[];let j=this.#X();return Array.from(this.element.querySelectorAll(Q)).filter((q)=>!q.hidden&&j(q))}tagsAdd(X){if(!this.#E())return;if(X?.defaultPrevented)return;if(this.#D(X).some((j)=>j.hasAttribute?.("data-reactive-highlighted")))return;X?.preventDefault?.();let $=X?.currentTarget??X?.target;if(!$)return;if(!this.#PX(String($.value??"").split(",")))return;if($.value="",this.#C())this.#x()}tagsPick(X){if(!this.#E())return;X?.preventDefault?.();let Q=(X?.currentTarget??X?.target)?.getAttribute?.("data-reactive-tag-param");if(!Q)return;if(!this.#PX([Q]))return;let j=this.#M0();if(!j)return;j.value="",this.#x(),j.focus?.()}tagsRemove(X){if(!this.#E())return;X?.preventDefault?.();let Q=(X?.currentTarget??X?.target)?.getAttribute?.("data-reactive-tag-param");if(!Q)return;let j=this.#l();if(!j)return;let q=this.#i(j),Y=q.filter((z)=>z.toLowerCase()!==Q.toLowerCase());if(Y.length===q.length)return;this.#NX(j,Y)}nestedAdd(X){X?.preventDefault?.();let $=X?.currentTarget??X?.target,Q=$?.getAttribute?.("data-reactive-association-param");if(!Q)return;if(typeof this.element?.querySelectorAll!=="function")return;let j=this.#X(),q=[...this.element.querySelectorAll(`[data-reactive-nested-list="${Q}"]`)].find(j),z=[...this.element.querySelectorAll(`[data-reactive-nested-template="${Q}"]`)].find(j)?.content?.firstElementChild;if(!q||!z){this.#O0(Q);return}let G=z.cloneNode(!0);this.#N0(G,this.#P0()),q.appendChild(G);let Z=$?.getAttribute?.("data-reactive-nested-from-param"),K=$?.getAttribute?.("data-reactive-nested-clear-param")==="true",U=this.#SX(G,Z,K);if(Z)U?.focus?.();else[...G.querySelectorAll?.("input, select, textarea")??[]][0]?.focus?.();if(q.getAttribute?.("data-reactive-nested-json")===Q)this.#zX(Q)}#SX(X,$,Q){if(!$)return null;let j;try{j=JSON.parse($)}catch{return null}if(!j||typeof j!=="object")return null;let q=this.#X(),Y=[...X.querySelectorAll?.("input, select, textarea")??[]],z=[];for(let[G,Z]of Object.entries(j)){let K=[...this.element.querySelectorAll?.(Z)??[]].find(q);if(!K)continue;let U=Y.find((B)=>this.#ZX(B.getAttribute?.("name"))===G);if(!U)continue;this.#wX(U,K),z.push(K)}if(Q)for(let G of z)this.#bX(G);return z[0]??null}#wX(X,$){if(X.type==="checkbox")X.checked=$.type==="checkbox"?!!$.checked:this.#p($)!=="";else X.value=this.#p($);if(typeof X.dispatchEvent==="function")X.dispatchEvent(new Event("input",{bubbles:!0}))}#bX(X){if(X.type==="checkbox")X.checked=!1;else X.value="";if(typeof X.dispatchEvent==="function")X.dispatchEvent(new Event("input",{bubbles:!0}))}nestedRemove(X){X?.preventDefault?.();let $=X?.currentTarget??X?.target,Q=$?.closest?.("[data-reactive-nested-row]");if(!Q)return;if(Q.closest?.('[data-controller~="reactive"]')!==this.element)return;let j=$?.getAttribute?.("data-reactive-confirm-param"),q=$?.getAttribute?.("data-reactive-confirm-when-param"),Y=this.#g(j,q);if(!Y)return this.#YX(Q);let z=this.#GX(Q),G=this.#hX(Y,z);return Promise.resolve().then(()=>C(G,{el:$,row:Q,fields:z})).catch(()=>!1).then((Z)=>{if(Z)this.#YX(Q)})}#hX(X,$){if(!X.includes("%{"))return X;return X.replace(/%\{(\w+)\}/g,(Q,j)=>Object.prototype.hasOwnProperty.call($,j)?$[j]:Q)}#YX(X){let $=[...X.querySelectorAll?.('input[name$="[_destroy]"]')??[]][0];if($){if($.value="1",typeof $.dispatchEvent==="function")$.dispatchEvent(new Event("input",{bubbles:!0}));X.hidden=!0}else X.parentNode?.removeChild?.(X);this.#R()}syncNestedJson(X){let $=X?.target;if(!$||!this.#$($))return;this.#R()}#R(){if(typeof this.element?.querySelectorAll!=="function")return;let X=this.#X();for(let $ of[...this.element.querySelectorAll("[data-reactive-nested-json]")].filter(X))this.#zX($.getAttribute("data-reactive-nested-json"))}#zX(X){let $=this.#X(),Q=[...this.element.querySelectorAll(`[data-reactive-nested-list="${X}"]`)].find($);if(!Q)return;let j=this.#vX(Q);if(!j)return;let q=[];for(let z of[...Q.querySelectorAll?.("[data-reactive-nested-row]")??[]]){if(!$(z)||z.hidden)continue;q.push(this.#GX(z))}let Y=JSON.stringify(q);if(j.value===Y)return;if(j.value=Y,typeof j.dispatchEvent==="function")j.dispatchEvent(new Event("input",{bubbles:!0}))}#vX(X){let $=X.getAttribute?.("data-reactive-nested-json-field");if(!$)return null;let Q=this.#X();return[...this.element.querySelectorAll($)].find(Q)??null}#GX(X){let $={};for(let Q of[...X.querySelectorAll?.("input, select, textarea")??[]]){let j=this.#ZX(Q.getAttribute?.("name"));if(j===null||j==="_destroy")continue;$[j]=this.#p(Q)}return $}#ZX(X){if(!X)return null;let $=X.match(/\[([^\][]+)\]$/);return $?$[1]:X}#p(X){if(X.type==="checkbox")return X.checked?X.value||"on":"";return X.value??""}#yX(X){let $=this.element.getAttribute(X);if(!$)return[];try{let Q=JSON.parse($);return Array.isArray(Q)?Q:[]}catch{return[]}}#fX(){let X=this.element.getAttribute("data-reactive-compute-inputs-param");if(!X)return[];try{let $=JSON.parse(X);if(Array.isArray($))return $.map((Q)=>[Q,"number"]);if($&&typeof $==="object")return Object.entries($);return[]}catch{return[]}}#pX(X,$,Q){let j=X?.target;if(!j?.name||typeof j.closest!=="function")return null;let q=this.#uX(j.name,Q);if(!$.includes(q))return null;return this.#$(j)?q:null}#uX(X,$){if(!$)return X;let Q=`${$}[`;return X.startsWith(Q)&&X.endsWith("]")?X.slice(Q.length,-1):X}#KX(X,$){let Q=String($);for(let j of this.#mX(X)){if(j.textContent===Q)continue;j.textContent=Q}}#mX(X){let $=this.element.querySelectorAll(`[data-reactive-text="${X}"]`);return Array.from($).filter((Q)=>this.#$(Q))}#HX(X,$){let Q=this.#gX();for(let[j,q]of Object.entries(Q)){let Y=j in X?X[j]:$(j)?.value;if(Y===void 0||Y===null)continue;let z=String(Y);for(let G of Array.isArray(q)?q:[q]){if(!eX(G))continue;for(let Z of document.querySelectorAll(G)){if(Z.textContent===z)continue;Z.textContent=z}}}}#gX(){let X=this.element.getAttribute("data-reactive-compute-mirror-param");if(!X)return{};try{let $=JSON.parse(X);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}#UX(X,$,Q,j,q,Y,z){if(this.#I("reactive:before-dispatch",{action:$,params:this.#OX(Q),element:this.element},{cancelable:!0}).defaultPrevented)return;let Z=Number(j)||0;if(Z>0)return this.#dX(X,Z,$,Q,Y,z);let K=Number(q)||0;if(K>0)return this.#iX(X,K,$,Q,Y,z);return this.#F($,Q,Y,X,z)}#F(X,$,Q,j,q){let Y=this.#k0(Q,j),z=this.#S0(X,j,q),G=this.#m()?this.#cX(Q,j):null;return this.queue=(this.queue??Promise.resolve()).then(()=>this.#eX(X,$,Y,z,G)),this.queue}#cX(X,$){if(!X?.hide)return null;let Q=this.#IX(X,$);if(!Q.length)return null;return()=>{let j=Q.filter((q)=>q.isConnected&&!q.hidden);if(!j.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.",j)}}#dX(X,$,Q,j,q,Y){this.#u(X);let z=()=>{this.#u(X),this.#F(Q,j,q,X,Y)},G=setTimeout(z,$);X?.addEventListener?.("blur",z,{once:!0}),this.#P.set(X,{timer:G,flush:z})}#u(X){let $=this.#P.get(X);if(!$)return;clearTimeout($.timer),X?.removeEventListener?.("blur",$.flush),this.#P.delete(X)}#lX(){for(let X of[...this.#P.keys()])this.#u(X)}#iX(X,$,Q,j,q,Y){let z=this.#U.get(X)??new Map;if(z.has(Q))return;let G=setTimeout(()=>{if(z.delete(Q),z.size===0)this.#U.delete(X)},$);return z.set(Q,G),this.#U.set(X,z),this.#F(Q,j,q,X,Y)}#oX(){for(let X of this.#U.values())for(let $ of X.values())clearTimeout($);this.#U.clear()}#I(X,$,{cancelable:Q=!1}={}){let j=new CustomEvent(X,{bubbles:!0,composed:!0,cancelable:Q,detail:$});return(this.element.isConnected?this.element:document).dispatchEvent(j),j}#z(X,$,Q,j){let q=()=>{if(!this.element.isConnected){console.warn("[phlex-reactive] retry() ignored — the reactive root left the DOM");return}return this.#F(X,$)};this.#I("reactive:error",{action:X,params:Q,...j,retry:q})}#G(X){if(this.element?.isConnected===!1)return;this.element?.setAttribute?.("data-reactive-error",X)}#sX(){this.element?.removeAttribute?.("data-reactive-error")}#nX(){let X=document.querySelector("[data-reactive-error-flash]");if(!X?.content)return;let $=X.getAttribute("data-reactive-error-flash")||"flash",Q=document.getElementById($);if(!Q)return;Q.appendChild(X.content.cloneNode(!0))}#aX(){if(typeof sessionStorage>"u")return Promise.resolve();let X=Number(sessionStorage.getItem(g));if(!Number.isFinite(X)||X<=0)return Promise.resolve();if(!D)D=!0,console.warn(`[phlex-reactive] latency simulator ACTIVE — every action is delayed by ${X}ms. Call PhlexReactive.disableLatencySim() (or clear sessionStorage) to turn it off.`);return new Promise(($)=>setTimeout($,X))}#m(){return this.element?.getAttribute?.("data-reactive-debug")==="true"}#JX(){return typeof performance<"u"&&typeof performance.now==="function"?performance.now():Date.now()}#rX(X){if(!X)return[];let $=[],Q=/<turbo-stream\b([^>]*)>/g,j;while((j=Q.exec(X))!==null){let q=j[1],Y=q.match(/\baction="([^"]*)"/)?.[1]??"?",z=q.match(/\btarget="([^"]*)"/)?.[1];$.push(z?`${Y} → #${z}`:Y)}return $}#tX(X){let{action:$,status:Q,ms:j}=X,Y=`reactive ${this.element?.id?`#${this.element.id} `:""}${$} → ${Q??"—"} (${Math.round(j)}ms)`;if(console.groupCollapsed(Y),console.log(`params: [${X.paramNames.join(", ")}] + collected: [${X.fieldNames.join(", ")}]`),console.log(`encoding: ${X.encoding}`),X.streams.length)console.log(`streams: ${X.streams.join(" ")}`);console.log(`token: ${X.tokenRefreshed?"refreshed ✓":"unchanged"}`),console.groupEnd()}async#eX(X,$,Q,j,q){let{fields:Y,files:z}=this.#VX(),G=this.#OX($),Z={...Y,...G},K=this.#Z,U=z.length>0,B=U?this.#I0(K,X,Z,z):JSON.stringify({token:K,act:X,params:Z}),J=this.#m()?{action:X,paramNames:Object.keys(G),fieldNames:Object.keys(Y),encoding:U?"multipart":"json",status:null,streams:[],tokenRefreshed:!1,started:this.#JX()}:null;await this.#aX();try{if(navigator.onLine===!1){this.#K(Q),this.#G("offline"),this.#z(X,$,Z,{kind:"offline"});return}let V;try{let L={Accept:"text/vnd.turbo-stream.html","X-CSRF-Token":this.#u0()};if(!U)L["Content-Type"]="application/json";let A=this.#m0();if(A)L["X-Pgbus-Connection"]=A;V=await fetch(this.#f0(),{method:"POST",headers:L,body:B,credentials:"same-origin",signal:AbortSignal.timeout(this.#p0())})}catch(L){if(console.error("[phlex-reactive] action error",L),this.#K(Q),L?.name==="TimeoutError"||L?.name==="AbortError"){this.#G("timeout"),this.#z(X,$,Z,{kind:"timeout"});return}this.#nX(),this.#G("network"),this.#z(X,$,Z,{kind:"network"});return}if(J)J.status=V.status;if(V.redirected){console.error("[phlex-reactive] action was redirected (auth/CSRF?) — no update applied"),this.#K(Q),this.#G("redirected"),this.#z(X,$,Z,{kind:"redirected",status:V.status});return}if(!V.ok){let L=await V.text();if(console.error(`[phlex-reactive] action failed: HTTP ${V.status}`,L),this.#K(Q),(V.headers.get("Content-Type")||"").includes("turbo-stream")){let A=this.#LX(L);if(this.#Z=A??this.#Z,J)this.#WX(J,L,A);window.Turbo.renderStreamMessage(L)}this.#G("http"),this.#z(X,$,Z,{kind:"http",status:V.status,body:L});return}let x=V.headers.get("Content-Type")||"";if(!x.includes("turbo-stream")){console.error(`[phlex-reactive] expected a turbo-stream, got "${x}" — no update applied`),this.#K(Q),this.#G("content-type"),this.#z(X,$,Z,{kind:"content-type",status:V.status});return}let H=await V.text(),W=this.#LX(H);if(this.#Z=W??this.#Z,J)this.#WX(J,H,W);if(window.Turbo.renderStreamMessage(H),q)queueMicrotask(q);this.#sX(),this.#I("reactive:applied",{action:X,params:Z,html:H})}catch(V){console.error("[phlex-reactive] action error",V),this.#K(Q),this.#I("reactive:error",{action:X,params:Z,kind:"apply"})}finally{if(j?.(),J)this.#tX({...J,ms:this.#JX()-J.started})}}#WX(X,$,Q){X.streams=this.#rX($),X.tokenRefreshed=Q!=null}get#Z(){return this.#a??this.tokenValue}set#Z(X){this.#a=X}#LX(X){let $=this.element.id;if(!$)return X.match(/data-reactive-token-value="([^"]+)"/)?.[1];let{token:Q,self:j}=this.#X0($),q=X.match(Q);if(q)return q[1];let Y=X.match(j);if(Y)return Y[1].match(/data-reactive-token-value="([^"]+)"/)?.[1];return}#X0(X){let $=this.#r;if($&&$.id===X)return $;let Q=iX(X);return this.#r={id:X,token:new RegExp(`<turbo-stream\\b[^>]*\\baction="reactive:token"[^>]*\\btarget="${Q}"[^>]*\\bdata-reactive-token-value="([^"]+)"`),self:new RegExp(`<turbo-stream\\b[^>]*\\baction="(?:replace|update)"[^>]*\\btarget="${Q}"[^>]*>([\\s\\S]*?)</turbo-stream>`)}}#$(X){return X.closest('[data-controller~="reactive"]')===this.element}#X(){if(this.element.querySelectorAll('[data-controller~="reactive"]').length===0)return()=>!0;return($)=>this.#$($)}#g(X,$){if(X)return X;if(!$)return null;let Q=$;if(typeof $==="string")try{Q=JSON.parse($)}catch{return console.warn(`[phlex-reactive] malformed conditional confirm payload ${JSON.stringify($)} — skipped`),null}if(!Q||typeof Q!=="object")return null;let{fields:j}=this.#VX(),q=(z)=>j[z],Y;if(typeof Q.predicate==="string"){let z=MX(Q.predicate);if(!z)return console.warn(`[phlex-reactive] confirm predicate "${Q.predicate}" is not registered — proceeding without a dialog (register it with setConfirmPredicate)`),null;Y=!!z(j)}else Y=P(Q.groups?.any,q)===!0;return Y?Q.message:null}#VX(){let X={},$=[],Q=this.#X();return this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach((j)=>{if(!Q(j))return;if(j.type==="file")for(let q of j.files??[])$.push({name:j.name,file:q,multiple:j.multiple});else if(j.type==="checkbox")X[j.name]=j.checked;else if(j.type==="radio"){if(j.checked)X[j.name]=j.value}else X[j.name]=j.value}),this.element.querySelectorAll("[name]:is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])").forEach((j)=>{if(!Q(j))return;let q=j.getAttribute("name");if(!q)return;let Y=X[q];if(Y==null||Y==="")X[q]=j.value??j.textContent??j.innerHTML??""}),{fields:X,files:$}}#c(){if(typeof this.element?.querySelectorAll!=="function")return;let X=0;if(this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach(($)=>{if(!this.#$($))return;if($.type==="file")return;if(this.#$0($))$.setAttribute("data-reactive-dirty","true"),X++;else $.removeAttribute("data-reactive-dirty")}),X>0)this.element.setAttribute("data-reactive-dirty",String(X));else this.element.removeAttribute("data-reactive-dirty")}#$0(X){if(X.type==="checkbox"||X.type==="radio")return X.checked!==X.defaultChecked;if(X.tag==="select"||X.options)return Array.from(X.options??[]).some(($)=>$.selected!==$.defaultSelected);return X.value!==X.defaultValue}#BX(){let X=this.element.getAttribute?.("data-reactive-dirty"),$=Number(X);return Number.isFinite($)&&$>0?$:0}#Q0(){if(typeof window>"u"||typeof window.addEventListener!=="function")return;this.#L=(X)=>{if(this.#BX()===0)return;return X.preventDefault(),X.returnValue="You have unsaved changes.",X.returnValue},this.#V=(X)=>{if(this.#BX()===0)return;if(!(typeof window.confirm==="function"?window.confirm("You have unsaved changes. Leave anyway?"):!0))X.preventDefault?.()},window.addEventListener("beforeunload",this.#L),window.addEventListener("turbo:before-visit",this.#V)}#j0(){if(this.#W)this.element.removeEventListener?.("turbo:morph-element",this.#W),this.#W=void 0;if(typeof window<"u"&&typeof window.removeEventListener==="function"){if(this.#L)window.removeEventListener("beforeunload",this.#L);if(this.#V)window.removeEventListener("turbo:before-visit",this.#V)}this.#L=void 0,this.#V=void 0}#q0(){if(this.element.getAttribute?.("data-reactive-show-targets"))return!0;let X=this.element.querySelectorAll?.(s)??[];for(let $ of X)if(this.#$($))return!0;return!1}#Y0(){return!!this.element.getAttribute?.("data-reactive-on-complete")}#z0(){if(this.element.getAttribute?.("data-reactive-clipboard"))return!0;let X=this.element.querySelectorAll?.("[data-reactive-clipboard]")??[];for(let $ of X)if(this.#$($))return!0;return!1}#_X(){let X=typeof globalThis.navigator?.clipboard?.readText==="function";if(this.element.getAttribute?.("data-reactive-clipboard"))this.element.hidden=!X;for(let $ of this.element.querySelectorAll?.("[data-reactive-clipboard]")??[])if(this.#$($))$.hidden=!X}#G0(){if(!this.#A)return;this.element.removeEventListener?.("turbo:morph-element",this.#A),this.#A=void 0}#Z0(){let X=this.element.getAttribute?.("data-reactive-on-complete")??null;if(X!==this.#XX)this.#XX=X,this.#v=X==null?[]:q0(X),this.#y=this.#v.map(()=>!1);return this.#v}#d(X){let $=this.#Z0();if(!$.length)return;let Q=this.#X(),j=this.element.getAttribute?.("data-reactive-scope")||null,q=new Map,Y=(z)=>{if(!q.has(z))q.set(z,this.#xX(z,Q,j));return q.get(z)};$.forEach((z,G)=>{let Z=P(z.any,Y);if(Z===null)return;let K=Z&&!this.#y[G]&&Boolean(X);if(this.#y[G]=Z,K)N(z.ops,(U)=>this.#k(U.to==null?{...U,to:"@root"}:U),(U,B)=>this.#T(`client op "${U}"`,B))})}#K0(){if(!this.#Y)return;this.element.removeEventListener?.("input",this.#Y),this.element.removeEventListener?.("change",this.#Y),this.element.removeEventListener?.("turbo:morph-element",this.#h)}#MX(){if(typeof this.element?.querySelectorAll!=="function")return;let X=this.#X(),$=this.element.getAttribute?.("data-reactive-scope")||null,Q=new Map,j=(q)=>{if(!Q.has(q))Q.set(q,this.#xX(q,X,$));return Q.get(q)};for(let q of this.element.querySelectorAll(s)){if(!X(q))continue;let Y=q.getAttribute("data-reactive-show");if(Y!==null){let K=z0(j0(Y),j);if(K!==null)this.#AX(q,K,X,$);continue}let z=q.getAttribute("data-reactive-show-field");if(!z)continue;let G=j(z);if(G===null)continue;let Z=X0(q,G);if(Z===null)continue;this.#AX(q,Z,X,$)}this.#H0(j)}#AX(X,$,Q,j){if(X.hidden=!$,X.getAttribute("data-reactive-show-disable")!=="true")return;if(typeof X.querySelectorAll!=="function")return;for(let q of X.querySelectorAll("input[name], select[name], textarea[name]"))if(Q(q))q.disabled=!$;if(X.name&&Q(X))X.disabled=!$}#H0(X){let $=this.#J0();for(let[Q,j]of Object.entries($)){if(Q.startsWith("#")){this.#U0(Q,j,X);continue}if(!j||typeof j!=="object"||Array.isArray(j))continue;let q=X(Q);if(q===null)continue;let Y=()=>q;for(let[z,G]of Object.entries(j)){if(!n(z))continue;let Z;if(Array.isArray(G)){if(G.length===0){console.warn(`[phlex-reactive] malformed reactive_show_targets group for ${z} — skipped`);continue}Z=G.every((K)=>c(K,Y))}else{let K=JX(G,q);if(K===null){console.warn(`[phlex-reactive] malformed reactive_show_targets predicate for ${z} — skipped`);continue}Z=K}for(let K of document.querySelectorAll(z))K.hidden=!Z}}}#U0(X,$,Q){if(!n(X))return;let j=$&&typeof $==="object"&&!Array.isArray($)?$.any:null,q=Y0(j);if(q===null){console.warn(`[phlex-reactive] malformed reactive_show_targets conditions for ${X} — skipped`);return}if(q.every((z)=>Q(z)===null))return;let Y=P(j,Q);if(Y===null)return;for(let z of document.querySelectorAll(X))z.hidden=!Y}#J0(){let X=this.element.getAttribute?.("data-reactive-show-targets");if(!X)return{};try{let $=JSON.parse(X);if($&&typeof $==="object"&&!Array.isArray($))return $}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: { ... })"),{}}#xX(X,$,Q){let j=Q&&!X.includes("[")?`${Q}[${X}]`:X,q=!1,Y=null;for(let z of this.element.querySelectorAll(`[name="${j}"]`)){if(!$(z))continue;if(z.type==="checkbox")return z.checked?"true":"false";if(z.type==="radio"){if(z.checked)return z.value??"";q=!0;continue}Y??=z}if(Y)return Y.value??"";return q?"":null}#W0(){if(!this.#Q)return;this.element.removeEventListener?.("input",this.#Q),this.element.removeEventListener?.("change",this.#Q),this.element.removeEventListener?.("turbo:morph-element",this.#Q),this.#Q=void 0}#C(){return!!(this.element.getAttribute?.("data-reactive-filter-input")&&this.element.getAttribute?.("data-reactive-filter-option"))}#L0(){return this.element.getAttribute?.("data-reactive-compute-seed")==="true"}#V0(X){let $=this.element.getAttribute("data-reactive-filter-input");return!!$&&typeof X.target?.matches==="function"&&X.target.matches($)}#x(){if(typeof this.element?.querySelectorAll!=="function")return;let X=this.element.getAttribute("data-reactive-filter-input"),$=this.element.getAttribute("data-reactive-filter-option");if(!X||!$)return;let Q=this.#X(),j=[...this.element.querySelectorAll(X)].find(Q);if(!j)return;let q=(j.value??"").trim().toLowerCase(),Y=0;for(let Z of this.element.querySelectorAll($)){if(!Q(Z))continue;let K=(Z.getAttribute("data-reactive-filter-text")??Z.textContent??"").toLowerCase(),U=Z.hasAttribute?.("data-reactive-tags-selected")||q!==""&&!K.includes(q);if(Z.hidden=U,U)Z.removeAttribute("data-reactive-highlighted");else Y++}let z=this.element.getAttribute("data-reactive-filter-group");if(z)for(let Z of this.element.querySelectorAll(z)){if(!Q(Z))continue;let K=[...Z.querySelectorAll($)].filter(Q);if(K.length===0)continue;Z.hidden=K.every((U)=>U.hidden)}let G=this.element.getAttribute("data-reactive-filter-empty");if(G){for(let Z of this.element.querySelectorAll(G))if(Q(Z))Z.hidden=Y>0}}#B0(){if(!this.#j)return;this.element.removeEventListener?.("input",this.#j),this.element.removeEventListener?.("turbo:morph-element",this.#j),this.#j=void 0}#E(){return!!this.element.getAttribute?.("data-reactive-tags-field")}#_0(){if(typeof this.element?.querySelector!=="function")return!1;return!!this.element.querySelector("[data-reactive-nested-json]")}#l(){if(typeof this.element?.querySelectorAll!=="function")return null;let X=this.element.getAttribute("data-reactive-tags-field");if(!X)return null;let $=this.#X();return[...this.element.querySelectorAll(X)].find($)??null}#i(X){let $=new Set,Q=[];for(let j of String(X.value??"").split(",")){let q=j.trim();if(q===""||$.has(q.toLowerCase()))continue;$.add(q.toLowerCase()),Q.push(q)}return Q}#PX(X){let $=this.#l();if(!$)return!1;let Q=this.#i($),j=new Set(Q.map((Y)=>Y.toLowerCase())),q=!1;for(let Y of X){let z=String(Y??"").trim();if(z===""||j.has(z.toLowerCase()))continue;j.add(z.toLowerCase()),Q.push(z),q=!0}if(q)this.#NX($,Q);return q}#NX(X,$){if(X.value=$.join(","),typeof X.dispatchEvent==="function")X.dispatchEvent(new Event("input",{bubbles:!0}));this.#o()}#M0(){if(typeof this.element?.querySelectorAll!=="function")return null;let X=this.element.getAttribute("data-reactive-filter-input");if(!X)return null;let $=this.#X();return[...this.element.querySelectorAll(X)].find($)??null}#o(){let X=this.#l();if(!X)return;let $=this.#i(X),Q=this.#X();this.#A0($,Q),this.#x0($,Q)}#A0(X,$){let Q=[...this.element.querySelectorAll("[data-reactive-tags-list]")].find($);if(!Q)return;let q=[...this.element.querySelectorAll("[data-reactive-tags-template]")].find($)?.content?.firstElementChild;if(!q){if(!this.#$X)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.#$X=!0;return}while(Q.firstChild)Q.removeChild(Q.firstChild);for(let Y of X){let z=q.cloneNode(!0);z.setAttribute?.("data-reactive-tag",Y);let G=z.matches?.("[data-reactive-tag-text]")?z:(z.querySelectorAll?.("[data-reactive-tag-text]")??[])[0];if(G)G.textContent=Y;let Z=[...z.querySelectorAll?.('[data-action*="reactive#tagsRemove"]')??[]];if(z.matches?.('[data-action*="reactive#tagsRemove"]'))Z.push(z);for(let K of Z)K.setAttribute?.("data-reactive-tag-param",Y);Q.appendChild(z)}}#x0(X,$){let Q=new Set(X.map((j)=>j.toLowerCase()));for(let j of this.element.querySelectorAll("[role=option]")){if(!$(j))continue;let q=j.getAttribute?.("data-reactive-tag-param");if(!q)continue;if(Q.has(q.toLowerCase()))j.setAttribute("data-reactive-tags-selected","true"),j.hidden=!0,j.removeAttribute?.("data-reactive-highlighted");else if(j.hasAttribute?.("data-reactive-tags-selected")){if(j.removeAttribute("data-reactive-tags-selected"),!this.#C())j.hidden=!1}}if(this.#C())this.#x()}#P0(){return this.#f=Math.max(this.#f+1,Date.now()),this.#f}#N0(X,$){let Q=[X,...X.querySelectorAll?.("*")??[]];for(let j of Q)for(let q of["name","id","for"]){let Y=j.getAttribute?.(q);if(Y&&Y.includes("NEW_ROW"))j.setAttribute?.(q,Y.replaceAll("NEW_ROW",String($)))}}#O0(X){if(this.#QX)return;console.warn(`[phlex-reactive] nested rows: no owned [data-reactive-nested-list="${X}"] container + <template data-reactive-nested-template="${X}"> pair found in this root — the add `+"trigger did nothing. Render both inside the same reactive root (reactive_nested_list / reactive_nested_template)."),this.#QX=!0}#D0(){if(!this.#B)return;this.element.removeEventListener?.("turbo:morph-element",this.#B),this.#B=void 0}#R0(){if(this.#q)this.element.removeEventListener?.("input",this.#q),this.element.removeEventListener?.("change",this.#q),this.#q=void 0;if(this.#_)this.element.removeEventListener?.("turbo:morph-element",this.#_),this.#_=void 0}#F0(){if(!this.#M)return;this.element.removeEventListener?.("turbo:morph-element",this.#M),this.#M=void 0}#I0(X,$,Q,j){let q=new FormData;q.append("token",X),q.append("act",$);for(let[z,G]of Object.entries(Q))this.#n(q,this.#s(z),G);let Y=this.#C0(j);for(let{name:z,file:G,multiple:Z}of j){let U=Z||Y.has(z)?`${this.#s(z)}[]`:this.#s(z);q.append(U,G,G.name)}return q}#s(X){let $=String(X),Q=$.indexOf("[");if(Q===-1)return`params[${$}]`;return`params${[$.slice(0,Q),...$.slice(Q).match(/[^\[\]]+/g)??[]].map((q)=>`[${q}]`).join("")}`}#n(X,$,Q){if(Q==null)X.append($,"");else if(Array.isArray(Q))Q.forEach((j,q)=>this.#n(X,`${$}[${q}]`,j));else if(typeof Q==="object")for(let[j,q]of Object.entries(Q))this.#n(X,`${$}[${j}]`,q);else X.append($,String(Q))}#C0(X){let $=new Map;for(let{name:Q}of X)$.set(Q,($.get(Q)??0)+1);return new Set([...$].filter(([,Q])=>Q>1).map(([Q])=>Q))}#OX(X){if(!X)return{};try{return typeof X==="string"?JSON.parse(X):X}catch{return{}}}#DX(X){return WX(X)}#RX(X){N(X,($)=>this.#k($),($,Q)=>this.#T(`client op "${$}"`,Q))}#E0(){return this.element?.getAttribute?.("data-reactive-verbose")==="true"||this.#m()}#T(X,$){if(!this.#E0())return;let Q=$.to;if(typeof Q!=="string"||Q===""||Q==="@root")return;let j="";if(!$.global)if(this.element?.matches?.(Q))j=" — the selector matches this component's own root, which root-scoped resolution never includes; use to: :root";else if(p(this.element,Q)>0)j=" — it matches only inside a nested reactive root (excluded by ownership scoping); use global: true";else{let q=p(globalThis.document,Q);if(q>0)j=` — it matches ${q} element(s) outside this scope; use global: true`}VX(X,Q,`scoped to #${this.element?.id||"?"}`,j)}#k(X){let $=X.to;if($==="@root")return[this.element];if(typeof $!=="string"||$==="")return[];if(X.global)return[...document.querySelectorAll($)];return[...this.element.querySelectorAll($)].filter((Q)=>this.#$(Q))}#T0(X,$){if(X?.checked!=="keep")return!1;let Q=$?.type;return Q==="checkbox"||Q==="radio"}#k0(X,$){if(!X)return null;let Q=this.#FX(X,$,!0);return Q.length?Q:null}#K(X){if(!X)return;if(!this.element.isConnected)return;for(let $ of X)$()}#S0(X,$,Q){this.#b0(X,$);let j=Q?this.#FX(Q,$,!1):[];zX();let q=!1;return()=>{if(q)return;q=!0,this.#h0(X,$),GX();for(let Y of j)Y()}}#FX(X,$,Q){let j=[];for(let q of this.#IX(X,$)){if(X.add_class){let Y=X.add_class.filter((z)=>!q.classList.contains(z));if(q.classList.add(...Y),Y.length)j.push(()=>q.classList.remove(...Y))}if(X.remove_class){let Y=X.remove_class.filter((z)=>q.classList.contains(z));if(q.classList.remove(...Y),Y.length)j.push(()=>q.classList.add(...Y))}if(X.toggle_class)X.toggle_class.forEach((Y)=>q.classList.toggle(Y)),j.push(()=>X.toggle_class.forEach((Y)=>q.classList.toggle(Y)));if(X.hide)q.hidden=!0,j.push(()=>q.hidden=!1);if(X.show)q.hidden=!1,j.push(()=>q.hidden=!0)}if($&&(X.disable||X.text!=null))j.push(this.#w0(X,$));if(Q&&X.checked==="keep"&&$&&"checked"in $){let q=$.checked;j.push(()=>$.checked=!q)}return j}#IX(X,$){if(X.to==null)return $?[$]:[];let Q=this.#k({to:X.to});if(Q.length===0)this.#T("busy/optimistic hint",{to:X.to});return Q}#w0(X,$){let Q=this.#N.get($);if(Q)Q.count++;else this.#N.set($,{count:1,disabled:$.disabled,html:$.innerHTML,hadText:X.text!=null,swappedTo:X.text});if(X.disable)$.disabled=!0;if(X.text!=null)$.innerHTML=X.text;return()=>this.#v0($,X)}#b0(X,$){if(this.#H($,X,1),this.#H(this.element,X,1),this.#J.set(X,(this.#J.get(X)??0)+1),this.#w++===0)this.element.setAttribute("aria-busy","true");for(let Q of this.#CX(X))this.#H(Q,X,1)}#h0(X,$){this.#H($,X,-1),this.#H(this.element,X,-1);let Q=(this.#J.get(X)??1)-1;if(Q<=0)this.#J.delete(X);else this.#J.set(X,Q);if(--this.#w<=0)this.#w=0,this.element.removeAttribute("aria-busy");for(let j of this.#CX(X))this.#H(j,X,-1)}#H(X,$,Q){if(!X||typeof X.getAttribute!=="function")return;let j=this.#b.get(X)??new Map,q=(j.get($)??0)+Q;if(q<=0)j.delete($);else j.set($,q);if(j.size===0){this.#b.delete(X),X.removeAttribute("data-reactive-busy");return}this.#b.set(X,j),X.setAttribute("data-reactive-busy",[...j.keys()].join(" "))}#CX(X){return[...this.element.querySelectorAll?.("[data-reactive-busy-on]")??[]].filter((Q)=>Q.getAttribute("data-reactive-busy-on")===X&&this.#$(Q))}#v0(X,$){let Q=this.#N.get(X);if(!Q)return;if(--Q.count>0)return;if(this.#N.delete(X),!X.isConnected)return;if($.disable)X.disabled=Q.disabled;if(Q.hadText&&X.innerHTML===Q.swappedTo)X.innerHTML=Q.html}#y0(X){if(!X||typeof X!=="object")return null;let{class:$,...Q}=X;return $==null?X:{...Q,add_class:$}}#f0(){return this.#EX??=document.querySelector('meta[name="phlex-reactive-action-path"]')?.content||"/reactive/actions"}#p0(){if(this.#S!=null)return this.#S;let X=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,$=Number(X);return this.#S=Number.isFinite($)&&$>0?$:30000}#u0(){return document.querySelector('meta[name="csrf-token"]')?.content??""}#m0(){return document.querySelector("pgbus-stream-source[connection-id]")?.getAttribute("connection-id")||document.querySelector('meta[name="pgbus-connection-id"]')?.content||null}}export{_0 as resetReactiveDefers,D0 as resetReactiveActivity,AX as registerReactiveVisit,xX as registerReactiveToken,gX as registerReactiveOffline,PX as registerReactiveJs,SX as registerReactiveEffects,EX as registerReactiveDismiss,NX as registerReactiveDefer,i as registerReactiveActions,O0 as reactiveActivityCount,M0 as pendingDeferVia,GX as exitReactiveActivity,iX as escapeRegExp,zX as enterReactiveActivity,cX as enableLatencySim,dX as disableLatencySim,I0 as default,oX as checkReactiveRegistration,R0 as __resetReactiveRegistrationForTest,P0 as __resetReactiveOfflineForTest,N0 as __resetReactiveLatencyForTest,x0 as __resetReactiveEffectsForTest,A0 as __resetReactiveDismissForTest,F0 as __markReactiveConnectedForTest,g as LATENCY_KEY,YX as ACTIVE_ATTR};
1
+ import{Controller as k0}from"@hotwired/stimulus";import{confirmResolver as C}from"phlex/reactive/confirm";import{computeReducer as T0}from"phlex/reactive/compute";import{confirmPredicate as S0}from"phlex/reactive/confirm_predicate";function w0(){let $=window.Turbo?.StreamActions;if(!$||$["reactive:visit"])return;$["reactive:visit"]=function(){let Q=this.getAttribute("data-url");if(Q)window.Turbo.visit(Q,{action:"advance"})}}function b0(){let $=window.Turbo?.StreamActions;if(!$||$["reactive:token"])return;$["reactive:token"]=function(){let Q=this.getAttribute("data-reactive-token-value"),X=this.getAttribute("target");if(!Q||!X)return;let j=document.getElementById(X);if(j)j.setAttribute("data-reactive-token-value",Q)}}function h0(){let $=window.Turbo?.StreamActions;if(!$||$["reactive:js"])return;$["reactive:js"]=function(){let Q=I0(this.getAttribute("data-reactive-ops"));if(!Q.length)return;let X=this.getAttribute("target"),j=this.getAttribute("data-reactive-verbose")==="true",q=X?document.getElementById(X):null;if(X&&!q){if(j&&!C0(`missing-root|#${X}`))console.warn(`[phlex-reactive] reactive:js stream target root #${X} is not in the DOM — its ops were dropped`);return}N(Q,(z)=>T1(z,q),j?(z,G)=>k1(z,G,q):void 0)}}var M=new Map;function G0($,Q){let X=!M.has($);if(M.set($,Q),X)B0()}function F($){if(M.delete($))V0()}function v1(){M.clear(),b=!1}function y1($){return M.get($)?.via}var b=!1;function v0(){let $=window.Turbo?.StreamActions;if(!$||$["reactive:defer"])return;if($["reactive:defer"]=function(){let Q=this.getAttribute("target");if(!Q)return;if(this.getAttribute("data-reactive-defer-via")==="stream"){f0(Q,this);return}let X=this.getAttribute("data-reactive-defer-token");if(!X)return;R(Q,X)},!b&&typeof document<"u"&&document.addEventListener)b=!0,document.addEventListener("turbo:before-stream-render",y0)}function y0($){let X=$.target?.getAttribute?.("target");if(!X)return;let j=X.startsWith("reactive-defer-src-")?X.slice(19):X;if(M.get(j)?.via==="stream")F(j)}function R($,Q){let X=document.getElementById($);if(!X){console.warn(`[phlex-reactive] reactive:defer target #${$} is not on the page — skipped`);return}Z0($),H0(X);let j={via:"fetch",abort:new AbortController,timedOut:!1};G0($,j),u0($,j,Q)}function f0($,Q){let X=document.getElementById($);if(!X){console.warn(`[phlex-reactive] reactive:defer target #${$} is not on the page — skipped`);return}let j=Q.getAttribute("data-reactive-defer-src");if(!j)return;if(!globalThis.customElements?.get?.("pgbus-stream-source")){let z=Q.getAttribute("data-reactive-defer-token");if(z){R($,z);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}Z0($),H0(X);let q=document.createElement("pgbus-stream-source");q.id=Y0($),q.setAttribute("src",j),q.setAttribute("since-id",Q.getAttribute("data-reactive-defer-since-id")??"0"),q.setAttribute("hidden",""),document.body.appendChild(q),G0($,{via:"stream"})}function Y0($){return`reactive-defer-src-${$}`}async function u0($,Q,X){let j=setTimeout(()=>{Q.timedOut=!0,Q.abort.abort()},g0()),q;try{q=await fetch(m0(),{method:"POST",headers:{Accept:"text/vnd.turbo-stream.html","Content-Type":"application/json","X-CSRF-Token":p0()},body:JSON.stringify({token:X}),credentials:"same-origin",signal:Q.abort.signal})}catch(G){if(clearTimeout(j),M.get($)!==Q)return;console.error("[phlex-reactive] deferred render failed",G),E($,X);return}if(M.get($)!==Q){clearTimeout(j);return}if(q.status===204){clearTimeout(j),r($);return}if(!q.ok){clearTimeout(j),console.error(`[phlex-reactive] deferred render failed: HTTP ${q.status}`),E($,X,q.status);return}let z;try{z=await q.text()}catch(G){if(clearTimeout(j),M.get($)!==Q)return;console.error("[phlex-reactive] deferred render failed reading the body",G),E($,X);return}if(clearTimeout(j),M.get($)!==Q)return;r($),window.Turbo.renderStreamMessage(z)}function Z0($){let Q=M.get($);if(!Q)return;if(F($),Q.via==="fetch")Q.abort.abort();else document.getElementById(Y0($))?.remove?.()}function H0($){$.setAttribute("data-reactive-defer-pending","true"),$.setAttribute("aria-busy","true")}function U0($){$.removeAttribute("data-reactive-defer-pending"),$.removeAttribute("aria-busy")}function r($){F($);let Q=document.getElementById($);if(!Q)return;U0(Q),Q.removeAttribute("data-reactive-error")}function E($,Q,X){F($);let j=document.getElementById($);if(!j)return;U0(j),j.setAttribute("data-reactive-error","defer");let q=()=>{let z=document.getElementById($);if(!z){console.warn("[phlex-reactive] defer retry() ignored — the target left the DOM");return}z.removeAttribute("data-reactive-error"),R($,Q)};j.dispatchEvent(new CustomEvent("reactive:error",{bubbles:!0,composed:!0,detail:{kind:"defer",target:$,status:X,retry:q}}))}function m0(){return document.querySelector('meta[name="phlex-reactive-defer-path"]')?.content||"/reactive/defer"}function p0(){return document.querySelector('meta[name="csrf-token"]')?.content??""}function g0(){let $=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,Q=Number($);return Number.isFinite(Q)&&Q>0?Q:30000}var h=!1;function c0(){if(h)return;if(typeof document>"u"||!document.addEventListener)return;h=!0,document.addEventListener("turbo:before-stream-render",d0)}function d0($){let Q=$.detail,X=Q?.render;if(typeof X!=="function"||X.__reactiveDismissWrapped){if(typeof requestAnimationFrame==="function")requestAnimationFrame(k);else setTimeout(k,0);return}let j=async(q)=>{await X(q),k()};j.__reactiveDismissWrapped=!0,Q.render=j}function k(){let $=document.querySelectorAll("[data-reactive-dismiss-after]");for(let Q of $){if(Q.hasAttribute("data-reactive-dismiss-scheduled"))continue;let X=Number(Q.getAttribute("data-reactive-dismiss-after"));if(!Number.isFinite(X)||X<=0)continue;Q.setAttribute("data-reactive-dismiss-scheduled",""),setTimeout(()=>Q.remove(),X)}}function f1(){h=!1}var l0=Object.freeze({append:"enter",prepend:"enter",replace:"update",update:"update",remove:"exit"}),T=Object.freeze(["fade","slide","scale","highlight","shake"]),v="data-reactive-fx-pending",K0=1000,y=!1;function i0(){if(y)return;if(typeof document>"u"||typeof document.addEventListener!=="function")return;y=!0,document.addEventListener("turbo:before-stream-render",n0)}function u1(){y=!1}function n0($){let Q=$.detail,X=Q?.render;if(typeof X!=="function"||X.__reactiveEffectsWrapped)return;let j=Q?.newStream??$.target,q=l0[j?.getAttribute?.("action")];if(!q||a0())return;let z=o0(j,q);if(!z)return;let G=q==="exit"?async(Y)=>{await e0(P(j),z),await X(Y)}:async(Y)=>{let Z=q==="enter"?r0(j):null;if(await X(Y),q==="enter")t0(Z,z);else J0(P(j),z)};G.__reactiveEffectsWrapped=!0,Q.render=G}function o0($,Q){let X=$.getAttribute?.("data-reactive-effect");if(X==="off")return null;if(X)return t(X,Q);let q=(Q==="enter"?s0($):P($))?.getAttribute?.(`data-reactive-effect-${Q}`);return q?t(q,Q):null}function P($){let Q=$.getAttribute?.("target");return Q?document.getElementById?.(Q)??null:null}function s0($){return $.querySelector?.("template")?.content?.firstElementChild??null}function t($,Q){if($.startsWith("[")){let j=null;try{let q=JSON.parse($);if(Array.isArray(q)&&q.length===3)j=q.map(String)}catch{}if(j)return{legs:j};return console.warn(`[phlex-reactive] malformed effect legs ${JSON.stringify($)} — skipped`),null}let X=$==="random"?T[Math.floor(Math.random()*T.length)]:$;if(!T.includes(X))return console.warn(`[phlex-reactive] unknown effect ${JSON.stringify($)} — skipped`),null;return{className:`reactive-fx--${X}-${Q}`}}function a0(){try{return typeof matchMedia==="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}}function r0($){let Q=$.querySelector?.("template")?.content;if(!Q)return null;for(let X of Array.from(Q.children??[]))X.setAttribute?.(v,"");return P($)}function t0($,Q){if(typeof $?.querySelectorAll!=="function")return;for(let X of Array.from($.querySelectorAll(`[${v}]`)))X.removeAttribute(v),J0(X,Q)}async function e0($,Q){if(!$?.classList)return;if(Q.legs){await L0($,Q.legs);return}$.classList.add(Q.className);let X=p($);if(X<=0){$.classList.remove(Q.className);return}await g($,X),$.classList.remove(Q.className)}function J0($,Q){if(!$?.classList)return;if(Q.legs){L0($,Q.legs);return}if($.classList.contains(Q.className))$.classList.remove(Q.className),$.offsetWidth;$.classList.add(Q.className);let X=p($);if(X<=0){$.classList.remove(Q.className);return}let j=$.__reactiveFxToken=($.__reactiveFxToken??0)+1;g($,X).then(()=>{if($.__reactiveFxToken===j)$.classList.remove(Q.className)})}async function L0($,Q){let[X,j,q]=Q.map($1),z=$.__reactiveFxToken=($.__reactiveFxToken??0)+1;if($.classList.remove(...X,...j,...q),$.classList.add(...X,...j),await Q1(),$.__reactiveFxToken!==z)return;$.classList.remove(...j),$.classList.add(...q);let G=p($);if(G>0)await g($,G);if($.__reactiveFxToken!==z)return;$.classList.remove(...X,...q)}function $1($){return String($??"").split(/\s+/).filter(Boolean)}function p($){if(typeof getComputedStyle!=="function")return 0;try{let Q=getComputedStyle($),X=(z)=>String(z??"").split(",").reduce((G,Y)=>Math.max(G,parseFloat(Y)||0),0),j=X(Q.animationDuration)+X(Q.animationDelay),q=X(Q.transitionDuration)+X(Q.transitionDelay);return Math.min(Math.max(j,q)*1000,K0)}catch{return 0}}function g($,Q){return new Promise((X)=>{let j=!1,q=()=>{if(j)return;j=!0,X()};$.addEventListener?.("animationend",q,{once:!0}),$.addEventListener?.("transitionend",q,{once:!0}),setTimeout(q,Math.min(Q+50,K0))})}function Q1(){return new Promise(($)=>{if(typeof requestAnimationFrame==="function")requestAnimationFrame(()=>$());else setTimeout($,16)})}var f=!1;function X1(){if(f)return;if(typeof window>"u"||typeof document>"u")return;if(typeof window.addEventListener!=="function")return;f=!0;let $=()=>{let Q=document.documentElement;if(typeof Q?.toggleAttribute!=="function")return;Q.toggleAttribute("data-reactive-offline",globalThis.navigator?.onLine===!1)};$(),window.addEventListener("online",$),window.addEventListener("offline",$)}function m1(){f=!1}var c="phlex-reactive:latency",D=!1;function j1($){if(typeof sessionStorage>"u")return;sessionStorage.setItem(c,String($))}function q1(){if(typeof sessionStorage>"u")return;sessionStorage.removeItem(c),D=!1}function z1(){if(typeof window>"u"||typeof document>"u")return;if(document.querySelector?.('meta[name="phlex-reactive-env"]')?.content!=="development")return;window.PhlexReactive={enableLatencySim:j1,disableLatencySim:q1}}function p1(){D=!1}var W0="data-reactive-active",_=0;function B0(){if(_++,_===1)M0("reactive:busy")}function V0(){if(_===0)return;if(_--,_===0)M0("reactive:idle")}function g1(){return _}function c1(){_=0,(typeof document<"u"?document.documentElement:null)?.removeAttribute?.(W0)}function M0($){if(typeof document>"u")return;let Q=document.documentElement;if(typeof Q?.toggleAttribute==="function")Q.toggleAttribute(W0,_>0);if(typeof document.dispatchEvent==="function"&&typeof CustomEvent==="function")document.dispatchEvent(new CustomEvent($,{detail:{count:_}}))}function e(){w0(),b0(),h0(),v0(),c0(),i0(),X1(),z1()}function G1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}if(typeof window<"u")if(window.Turbo)e();else document.addEventListener("turbo:load",e,{once:!0});var I=!1;function Y1(){if(I)return;if(typeof document>"u")return;let $=document.querySelectorAll('[data-controller~="reactive"]');if(!$||$.length===0)return;console.warn("[phlex-reactive] found "+$.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 d1(){I=!1}function l1(){I=!0}if(typeof window<"u"&&typeof document<"u"){let $=()=>setTimeout(Y1,0);if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",$,{once:!0});else $()}var Z1=new Set(["href","src","srcdoc","action","formaction","xlink:href","style"]);function H1($){let Q=String($).toLowerCase();return Q.startsWith("on")||Z1.has(Q)}function U1($,Q,X){let[j,q,z]=Q;$.classList.add(j,q),X(),requestAnimationFrame(()=>{$.classList.remove(q),$.classList.add(z)});let G=!1,Y=()=>{if(G)return;G=!0,$.classList.remove(j,z)};$.addEventListener("animationend",Y,{once:!0}),setTimeout(Y,350)}var _0=1,K1="phlex-reactive:persist:",J1=new Set(["hidden","file","password","submit","button","reset","image"]),d="data-reactive-persist-state",$0=new WeakSet,Q0=new WeakSet;function l($){let Q=$?.getAttribute?.("data-reactive-persist");if(!Q||Q==="off")return null;try{let X=JSON.parse(Q);if(X&&typeof X==="object"&&typeof X.key==="string"&&X.key!=="")return X}catch{}if(!$0.has($))$0.add($),console.warn(`[phlex-reactive] malformed reactive_persist payload ${JSON.stringify(Q)} — persistence disabled`);return null}function i(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function n($,Q){if($?.getAttribute?.("data-reactive-debug")!=="true"||Q0.has($))return;Q0.add($),console.info(`[phlex-reactive] reactive_persist: storage unavailable — draft skipped (${Q?.name??Q})`)}function o($){return K1+$.key}function u($,Q){let X=i();if(!X)return null;let j;try{j=X.getItem(o(Q))}catch(Z){return n($,Z),null}if(!j)return null;let q;try{q=JSON.parse(j)}catch{return null}if(!q||typeof q!=="object"||q.v!==_0)return null;let z=Number(Q.ttl)*1000;if(!(Number(q.savedAt)+z>Date.now()))return s($,Q),null;let G=q.fields&&typeof q.fields==="object"?q.fields:{},Y=q.state&&typeof q.state==="object"?q.state:null;return{fields:G,state:Y}}function A0($,Q,{fields:X,state:j}){let q=i();if(!q)return!1;let z={v:_0,savedAt:Date.now(),fields:X};if(j)z.state=j;try{return q.setItem(o(Q),JSON.stringify(z)),!0}catch(G){return n($,G),!1}}function s($,Q){$?.removeAttribute?.(d);let X=i();if(!X)return;try{X.removeItem(o(Q))}catch(j){n($,j)}}function x0($,Q){let X=Array.isArray(Q.fields)?new Set(Q.fields):null,j=[];for(let q of $.querySelectorAll("input[name], select[name], textarea[name]")){if(q.closest('[data-controller~="reactive"]')!==$)continue;if(J1.has(q.type))continue;if(q.getAttribute("data-reactive-persist")==="off")continue;if(X&&!X.has(q.name))continue;j.push(q)}return j}function O0($){return $.tagName==="SELECT"&&$.multiple}function N0($,Q){let X={};for(let j of x0($,Q)){let q=j.name;if(j.type==="radio"){if(j.checked)X[q]=j.value;else if(!Object.hasOwn(X,q))X[q]=null}else if(j.type==="checkbox")X[q]=j.checked;else if(O0(j))X[q]=[...j.options].filter((z)=>z.selected).map((z)=>z.value);else X[q]=j.value}return X}function L1($,Q,X){let j=Q.restore==="always",q=x0($,Q);for(let z of q){if(!Object.hasOwn(X,z.name))continue;let G=X[z.name];if(G===null||G===void 0)continue;if(z.type==="radio"){if(!j&&q.some((Y)=>Y.type==="radio"&&Y.name===z.name&&Y.checked))continue;z.checked=z.value===String(G)}else if(z.type==="checkbox"){if(!j&&z.checked)continue;z.checked=Boolean(G)}else if(O0(z)){if(!j&&[...z.options].some((Z)=>Z.selected))continue;let Y=new Set((Array.isArray(G)?G:[G]).map(String));for(let Z of z.options)Z.selected=Y.has(Z.value)}else{if(!j&&z.value!=="")continue;z.value=String(G)}}}function W1($,Q){let X=l($);if(!X){console.warn("[phlex-reactive] persist_state on a root without reactive_persist — skipped");return}if(!Q||typeof Q!=="object")return;let q={...u($,X)?.state??{},...Q};if(A0($,X,{fields:N0($,X),state:q}))$.setAttribute?.(d,JSON.stringify(q))}function B1($){let Q=l($);if(Q)s($,Q)}var X0=Object.freeze({show:($,Q)=>S($,!1,Q),hide:($,Q)=>S($,!0,Q),toggle:($,Q)=>S($,!$.hidden,Q),add_class:($,Q)=>$.classList.add(...Q.classes??[]),remove_class:($,Q)=>$.classList.remove(...Q.classes??[]),toggle_class:($,Q)=>(Q.classes??[]).forEach((X)=>$.classList.toggle(X)),set_attr:($,Q)=>{if(w(Q.name))$.setAttribute(Q.name,Q.value??"")},remove_attr:($,Q)=>{if(w(Q.name))$.removeAttribute(Q.name)},toggle_attr:($,Q)=>{if(!w(Q.name))return;if($.hasAttribute(Q.name))$.removeAttribute(Q.name);else $.setAttribute(Q.name,"")},focus:($)=>$.focus?.(),focus_first:($)=>C1($)?.focus?.(),text:($,Q)=>{let X=String(Q.value??"");if($.textContent!==X)$.textContent=X},dispatch:($,Q)=>{$.dispatchEvent(new CustomEvent(Q.name,{bubbles:!0,composed:!0,detail:Q.detail??{}}))},submit:($)=>V1($)?.requestSubmit?.(),paste_into:($)=>M1($),persist_state:($,Q)=>W1($,Q.state),persist_clear:($)=>B1($)});function V1($){if($?.tagName==="FORM")return $;return $?.form??$?.closest?.("form")??null}function M1($){let Q=globalThis.navigator?.clipboard;if(typeof Q?.readText!=="function")return;Q.readText().then((X)=>{if(!X)return;if($.value=X,typeof $.dispatchEvent==="function")$.dispatchEvent(new Event("input",{bubbles:!0}));$.focus?.()}).catch(()=>{})}function S($,Q,X){if(X?.transition)U1($,X.transition,()=>$.hidden=Q);else $.hidden=Q}function w($){if(!H1($))return!0;return console.warn(`[phlex-reactive] refused client attr op on ${JSON.stringify($)} — skipped`),!1}var P0=/^#[A-Za-z_][\w-]*$/;function _1($){if(typeof $==="string"&&P0.test($))return!0;return console.warn(`[phlex-reactive] refused cross-root mirror target ${JSON.stringify($)} — skipped`),!1}function A1($,Q){let X=$.getAttribute("data-reactive-show-equals");if(X!==null)return Q===X;let j=$.getAttribute("data-reactive-show-not");if(j!==null)return Q!==j;let q=$.getAttribute("data-reactive-show-in");if(q!==null){try{let z=JSON.parse(q);if(Array.isArray(z))return z.includes(Q)}catch{}return console.warn(`[phlex-reactive] malformed reactive_show in: list ${JSON.stringify(q)} — skipped`),null}for(let z of D0){let G=$.getAttribute(`data-reactive-show-${z}`);if(G!==null)return F0(z,G,Q)}return console.warn("[phlex-reactive] a reactive_show binding declares no predicate — skipped"),null}var D0=["gte","gt","lte","lt"],x1=["len_eq","len_gte","len_gt","len_lte","len_lt"];function O1($,Q,X){if(!Number.isInteger(Q))return console.warn(`[phlex-reactive] reactive_show ${$}: needs an integer literal, got ${JSON.stringify(Q)} — skipped`),null;let j=[...String(X??"")].length;switch($){case"len_eq":return j===Q;case"len_gte":return j>=Q;case"len_gt":return j>Q;case"len_lte":return j<=Q;case"len_lt":return j<Q;default:return null}}function F0($,Q,X){let j=Number(Q);if(Number.isNaN(j))return console.warn(`[phlex-reactive] reactive_show ${$}: needs a numeric literal, got ${JSON.stringify(Q)} — skipped`),null;let q=X==null?"":String(X).trim(),z=q===""?NaN:Number(q);if(Number.isNaN(z))return!1;switch($){case"gte":return z>=j;case"gt":return z>j;case"lte":return z<=j;case"lt":return z<j;default:return null}}function R0($,Q){if(!$||typeof $!=="object")return null;if(typeof $.equals==="string")return Q===$.equals;if(typeof $.not==="string")return Q!==$.not;if(Array.isArray($.in))return $.in.includes(Q);for(let X of D0)if(X in $)return F0(X,$[X],Q);for(let X of x1)if(X in $)return O1(X,$[X],Q);return null}var j0="[data-reactive-show-field], [data-reactive-show]";function N1($){try{let Q=JSON.parse($);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return console.warn(`[phlex-reactive] malformed compound reactive_show payload ${JSON.stringify($)} — skipped`),null}function P1($){try{let Q=JSON.parse($);if(Array.isArray(Q)&&Q.every((X)=>X&&typeof X==="object"&&Array.isArray(X.any)&&Array.isArray(X.ops)))return Q}catch{}return console.warn(`[phlex-reactive] malformed reactive_on_complete payload ${JSON.stringify($)} — skipped`),[]}function a($,Q){if(!$||typeof $!=="object"||typeof $.field!=="string")return!1;let X=Q($.field)??"";return R0($,X)===!0}function O($,Q){if(!Array.isArray($)||$.length===0)return null;return $.some((X)=>Array.isArray(X)&&X.length>0&&X.every((j)=>a(j,Q)))}function D1($){if(!Array.isArray($)||$.length===0)return null;let Q=new Set;for(let X of $){if(!Array.isArray(X))continue;for(let j of X)if(j&&typeof j==="object"&&typeof j.field==="string")Q.add(j.field)}return Q.size>0?[...Q]:null}function F1($,Q){if(!$||typeof $!=="object")return null;let X=$.any;if(Array.isArray(X)&&(X.length===0||Array.isArray(X[0])))return O(X,Q);return R1($,Q)}function R1($,Q){let X=Array.isArray($.all)?"all":Array.isArray($.any)?"any":null;if(!X)return null;let j=$[X];if(j.length===0)return null;let q=j.map((z)=>a(z,Q));return X==="all"?q.every(Boolean):q.some(Boolean)}function q0($){if(typeof $==="string"&&P0.test($))return!0;return console.warn(`[phlex-reactive] refused cross-root show target ${JSON.stringify($)} — skipped`),!1}var I1='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function C1($){return $.querySelectorAll?.(I1)?.[0]??null}function I0($){if(Array.isArray($))return $;if(typeof $!=="string")return[];try{let Q=JSON.parse($);return Array.isArray(Q)?Q:[]}catch{return[]}}function E1($){if($==null)return null;let Q=Array.isArray($)?$:$.ops;if(Array.isArray(Q))return Q.length>0?Q:null;return console.warn("[phlex-reactive] $ops must be an ops chain or a [[op, args], ...] list — skipped"),null}function N($,Q,X){for(let j of $){if(!Array.isArray(j))continue;let[q,z={}]=j;if(!Object.hasOwn(X0,q)){console.warn(`[phlex-reactive] unknown client op ${JSON.stringify(q)} — skipped`);continue}let G=Q(z);if(G.length===0&&X)X(q,z);for(let Y of G)X0[q](Y,z)}}var z0=new WeakMap;function C0($){let Q=globalThis.document;if(!Q)return!0;let X=z0.get(Q);if(!X)X=new Set,z0.set(Q,X);if(X.has($))return!0;return X.add($),!1}function m($,Q){try{return $?.querySelectorAll?.(Q)?.length??0}catch{return 0}}function E0($,Q,X,j){if(C0(`${$}|${Q}|${X}`))return;console.warn(`[phlex-reactive] ${$} matched zero targets for selector "${Q}" (${X})${j}`)}function k1($,Q,X){let j=Q.to;if(typeof j!=="string"||j===""||j==="@root")return;let q="";if(X&&!Q.global){let z=m(globalThis.document,j);if(z>0)q=` — it matches ${z} element(s) outside the stream's target root; use global: true`}E0(`client op "${$}"`,j,X?`scoped to #${X.id||"?"}`:"document-scoped",q)}function T1($,Q){let X=$.to;if(Q){if(X==="@root")return[Q];if(typeof X!=="string"||X==="")return[];if($.global)return[...document.querySelectorAll(X)];return[...Q.querySelectorAll(X)]}if(typeof X!=="string"||X===""||X==="@root")return[];return[...document.querySelectorAll(X)]}class i1 extends k0{static values={token:String};#j0;#F=new Map;#L=new Map;#v0;#u;#q0;#m=0;#W=new Map;#p=new WeakMap;#R=new Map;#z0=new WeakSet;#G0=null;#B;#V;#M;#j;#Y;#g;#Y0;#c;#d;#z;#_;#Z0=!1;#l=0;#H0=!1;#G;#A;#x;#I;#O;#q=null;#N=!1;#Q=null;#C;#E;#k;connect(){if(I=!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.#U0(),this.#I=()=>this.#U0(),this.element.addEventListener?.("turbo:morph-element",this.#I);if(this.#q=l(this.element),this.#q)this.#x1();if(this.#y0()){if(this.#B=()=>this.#a(),this.element.addEventListener?.("turbo:morph-element",this.#B),this.#a(),this.element.getAttribute?.("data-reactive-warn-unsaved")==="true")this.#H1()}if(this.#K1())this.#j=()=>this.#F0(),this.element.addEventListener?.("input",this.#j),this.element.addEventListener?.("change",this.#j),this.element.addEventListener?.("turbo:morph-element",this.#j),this.#F0();if(this.#J1())this.#Y=($)=>this.#r($),this.#g=()=>this.#r(null),this.element.addEventListener?.("input",this.#Y),this.element.addEventListener?.("change",this.#Y),this.element.addEventListener?.("turbo:morph-element",this.#g),this.#r(null);if(this.#h())this.#z=($)=>{if($?.type==="input"&&!this.#R1($))return;this.#D()},this.element.addEventListener?.("input",this.#z),this.element.addEventListener?.("turbo:morph-element",this.#z),this.#D();if(this.#v())this.#_=()=>this.#$0(),this.element.addEventListener?.("turbo:morph-element",this.#_),this.#$0();if(this.#C1())this.#G=($)=>this.syncNestedJson($),this.#A=()=>this.#S(),this.element.addEventListener?.("input",this.#G),this.element.addEventListener?.("change",this.#G),this.element.addEventListener?.("turbo:morph-element",this.#A),this.#S();if(this.#F1())this.#x=()=>this.recompute(),this.element.addEventListener?.("turbo:morph-element",this.#x),this.recompute();if(this.#L1())this.#O=()=>this.#D0(),this.element.addEventListener?.("turbo:morph-element",this.#O),this.#D0()}#y0(){if((this.element.getAttribute?.("data-action")??"").includes("reactive#trackDirty"))return!0;let $=this.element.querySelectorAll?.('[data-action*="reactive#trackDirty"]')??[];for(let Q of $)if(this.#X(Q))return!0;return!1}disconnect(){if(this.#P1(),this.#t0(),this.#$1(),this.#U1(),this.#D1(),this.#V1(),this.#I1(),this.#h1(),this.#v1(),this.#y1(),this.#W1(),this.#I)this.element.removeEventListener?.("turbo:morph-element",this.#I)}#U0(){let $=this.element;if(!$?.id)return;let Q=$.getAttribute?.("data-reactive-defer-token");if(!Q)return;if($.getAttribute?.("data-reactive-defer-pending")!=="true")return;R($.id,Q)}dispatch($){let{action:Q,params:X,debounce:j,throttle:q,confirm:z,confirmWhen:G,outside:Y,window:Z,optimistic:H}=$.params;if(!Q)return;let K=$.params.busy??this.#o1($.params.loading);if(Y&&this.element.contains($.target))return;let V=$.currentTarget??$.target;if(!Z&&!this.#p1(H,V))$.preventDefault();let J=this.#s(z,G);if(!J)return this.#_0(V,Q,X,j,q,H,K);Promise.resolve().then(()=>C(J,{el:V})).catch(()=>!1).then((B)=>{if(B)this.#_0(V,Q,X,j,q,H,K)})}runOps($){let{ops:Q,confirm:X,confirmWhen:j,outside:q,window:z}=$.params,G=$.currentTarget??$.target;if(q&&this.element.contains($.target))return;if(!z)$.preventDefault();let Y=this.#s(X,j);if(!Y)return this.#S0(this.#T0(Q));Promise.resolve().then(()=>C(Y,{el:G})).catch(()=>!1).then((Z)=>{if(Z)this.#S0(this.#T0(Q))})}trackDirty(){this.#a()}recompute($){if($&&this.#z0.has($))return;let Q=this.#l0(),X=Q.map(([U])=>U),j=this.element.getAttribute?.("data-reactive-scope")||null,q=(U)=>j&&!U.includes("[")?`${j}[${U}]`:U,z=this.#$(),G=new Map,Y=(U)=>{if(G.has(U))return G.get(U);let L=null;for(let W of this.element.querySelectorAll(`[name="${q(U)}"]`))if(z(W)){L=W;break}return G.set(U,L),L};for(let U of X)this.#V0(U,Y(U)?.value??"");let Z=this.element.getAttribute("data-reactive-compute-reducer-param"),H=Z?T0(Z):null;if(!H){this.#M0({},Y);return}let K=this.#d0("data-reactive-compute-outputs-param"),V={};for(let[U,L]of Q){let W=Y(U);if(L==="string")V[U]=W?.value??"";else{let A=Number(W?.value);V[U]=Number.isFinite(A)?A:0}}let J=H(V,{changed:this.#i0($,X,j)})||{},B=E1(J.$ops),x=[];for(let U of K){if(U==="$ops"||!(U in J))continue;let L=Y(U);if(!L)continue;if(String(J[U])===L.value)continue;L.value=J[U],x.push(L)}for(let U of Object.keys(J)){if(U==="$ops")continue;let L=J[U];if(L===void 0||L===null)continue;this.#V0(U,L)}this.#M0(J,Y);for(let U of x){let L=new Event("input",{bubbles:!0});this.#z0.add(L),U.dispatchEvent(L)}this.#f0(B,Boolean($))}#f0($,Q){let X=$===null?null:JSON.stringify($),j=X!==null&&X!==this.#G0&&Q;if(this.#G0=X,!j)return;N($,(q)=>this.#f(q.to==null?{...q,to:"@root"}:q),(q,z)=>this.#y(`client op "${q}"`,z))}listnavNext($){this.#K0($,1)}listnavPrev($){this.#K0($,-1)}listnavPick($){let Q=this.#T($),X=Q.findIndex((j)=>j.hasAttribute("data-reactive-highlighted"));if(X<0)return;$.preventDefault(),Q[X].click()}listnavClose($){for(let Q of this.#T($))Q.removeAttribute("data-reactive-highlighted")}#K0($,Q){let X=this.#T($);if(!X.length)return;$.preventDefault();let j=X.findIndex((G)=>G.hasAttribute("data-reactive-highlighted")),q=j<0?Q>0?0:X.length-1:(j+Q+X.length)%X.length;for(let G of X)G.removeAttribute("data-reactive-highlighted");let z=X[q];z.setAttribute("data-reactive-highlighted","true"),z.scrollIntoView?.({block:"nearest"})}#T($){let X=($?.currentTarget??$?.target??this.element).getAttribute?.("data-reactive-listnav-option-param")??this.element.getAttribute("data-reactive-listnav-option-param");if(!X)return[];let j=this.#$();return Array.from(this.element.querySelectorAll(X)).filter((q)=>!q.hidden&&j(q))}tagsAdd($){if(!this.#v())return;if($?.defaultPrevented)return;if(this.#T($).some((j)=>j.hasAttribute?.("data-reactive-highlighted")))return;$?.preventDefault?.();let Q=$?.currentTarget??$?.target;if(!Q)return;if(!this.#C0(String(Q.value??"").split(",")))return;if(Q.value="",this.#h())this.#D()}tagsPick($){if(!this.#v())return;$?.preventDefault?.();let X=($?.currentTarget??$?.target)?.getAttribute?.("data-reactive-tag-param");if(!X)return;if(!this.#C0([X]))return;let j=this.#E1();if(!j)return;j.value="",this.#D(),j.focus?.()}tagsRemove($){if(!this.#v())return;$?.preventDefault?.();let X=($?.currentTarget??$?.target)?.getAttribute?.("data-reactive-tag-param");if(!X)return;let j=this.#t();if(!j)return;let q=this.#e(j),z=q.filter((G)=>G.toLowerCase()!==X.toLowerCase());if(z.length===q.length)return;this.#E0(j,z)}nestedAdd($){$?.preventDefault?.();let Q=$?.currentTarget??$?.target,X=Q?.getAttribute?.("data-reactive-association-param");if(!X)return;if(typeof this.element?.querySelectorAll!=="function")return;let j=this.#$(),q=[...this.element.querySelectorAll(`[data-reactive-nested-list="${X}"]`)].find(j),G=[...this.element.querySelectorAll(`[data-reactive-nested-template="${X}"]`)].find(j)?.content?.firstElementChild;if(!q||!G){this.#b1(X);return}let Y=G.cloneNode(!0);this.#w1(Y,this.#S1()),q.appendChild(Y);let Z=Q?.getAttribute?.("data-reactive-nested-from-param"),H=Q?.getAttribute?.("data-reactive-nested-clear-param")==="true",K=this.#u0(Y,Z,H);if(Z)K?.focus?.();else[...Y.querySelectorAll?.("input, select, textarea")??[]][0]?.focus?.();if(q.getAttribute?.("data-reactive-nested-json")===X)this.#L0(X)}#u0($,Q,X){if(!Q)return null;let j;try{j=JSON.parse(Q)}catch{return null}if(!j||typeof j!=="object")return null;let q=this.#$(),z=[...$.querySelectorAll?.("input, select, textarea")??[]],G=[];for(let[Y,Z]of Object.entries(j)){let H=[...this.element.querySelectorAll?.(Z)??[]].find(q);if(!H)continue;let K=z.find((V)=>this.#B0(V.getAttribute?.("name"))===Y);if(!K)continue;this.#m0(K,H),G.push(H)}if(X)for(let Y of G)this.#p0(Y);return G[0]??null}#m0($,Q){if($.type==="checkbox")$.checked=Q.type==="checkbox"?!!Q.checked:this.#i(Q)!=="";else $.value=this.#i(Q);if(typeof $.dispatchEvent==="function")$.dispatchEvent(new Event("input",{bubbles:!0}))}#p0($){if($.type==="checkbox")$.checked=!1;else $.value="";if(typeof $.dispatchEvent==="function")$.dispatchEvent(new Event("input",{bubbles:!0}))}nestedRemove($){$?.preventDefault?.();let Q=$?.currentTarget??$?.target,X=Q?.closest?.("[data-reactive-nested-row]");if(!X)return;if(X.closest?.('[data-controller~="reactive"]')!==this.element)return;let j=Q?.getAttribute?.("data-reactive-confirm-param"),q=Q?.getAttribute?.("data-reactive-confirm-when-param"),z=this.#s(j,q);if(!z)return this.#J0(X);let G=this.#W0(X),Y=this.#g0(z,G);return Promise.resolve().then(()=>C(Y,{el:Q,row:X,fields:G})).catch(()=>!1).then((Z)=>{if(Z)this.#J0(X)})}#g0($,Q){if(!$.includes("%{"))return $;return $.replace(/%\{(\w+)\}/g,(X,j)=>Object.prototype.hasOwnProperty.call(Q,j)?Q[j]:X)}#J0($){let Q=[...$.querySelectorAll?.('input[name$="[_destroy]"]')??[]][0];if(Q){if(Q.value="1",typeof Q.dispatchEvent==="function")Q.dispatchEvent(new Event("input",{bubbles:!0}));$.hidden=!0}else $.parentNode?.removeChild?.($);this.#S()}syncNestedJson($){let Q=$?.target;if(!Q||!this.#X(Q))return;this.#S()}#S(){if(typeof this.element?.querySelectorAll!=="function")return;let $=this.#$();for(let Q of[...this.element.querySelectorAll("[data-reactive-nested-json]")].filter($))this.#L0(Q.getAttribute("data-reactive-nested-json"))}#L0($){let Q=this.#$(),X=[...this.element.querySelectorAll(`[data-reactive-nested-list="${$}"]`)].find(Q);if(!X)return;let j=this.#c0(X);if(!j)return;let q=[];for(let G of[...X.querySelectorAll?.("[data-reactive-nested-row]")??[]]){if(!Q(G)||G.hidden)continue;q.push(this.#W0(G))}let z=JSON.stringify(q);if(j.value===z)return;if(j.value=z,typeof j.dispatchEvent==="function")j.dispatchEvent(new Event("input",{bubbles:!0}))}#c0($){let Q=$.getAttribute?.("data-reactive-nested-json-field");if(!Q)return null;let X=this.#$();return[...this.element.querySelectorAll(Q)].find(X)??null}#W0($){let Q={};for(let X of[...$.querySelectorAll?.("input, select, textarea")??[]]){let j=this.#B0(X.getAttribute?.("name"));if(j===null||j==="_destroy")continue;Q[j]=this.#i(X)}return Q}#B0($){if(!$)return null;let Q=$.match(/\[([^\][]+)\]$/);return Q?Q[1]:$}#i($){if($.type==="checkbox")return $.checked?$.value||"on":"";return $.value??""}#d0($){let Q=this.element.getAttribute($);if(!Q)return[];try{let X=JSON.parse(Q);return Array.isArray(X)?X:[]}catch{return[]}}#l0(){let $=this.element.getAttribute("data-reactive-compute-inputs-param");if(!$)return[];try{let Q=JSON.parse($);if(Array.isArray(Q))return Q.map((X)=>[X,"number"]);if(Q&&typeof Q==="object")return Object.entries(Q);return[]}catch{return[]}}#i0($,Q,X){let j=$?.target;if(!j?.name||typeof j.closest!=="function")return null;let q=this.#n0(j.name,X);if(!Q.includes(q))return null;return this.#X(j)?q:null}#n0($,Q){if(!Q)return $;let X=`${Q}[`;return $.startsWith(X)&&$.endsWith("]")?$.slice(X.length,-1):$}#V0($,Q){let X=String(Q);for(let j of this.#o0($)){if(j.textContent===X)continue;j.textContent=X}}#o0($){let Q=this.element.querySelectorAll(`[data-reactive-text="${$}"]`);return Array.from(Q).filter((X)=>this.#X(X))}#M0($,Q){let X=this.#s0();for(let[j,q]of Object.entries(X)){let z=j in $?$[j]:Q(j)?.value;if(z===void 0||z===null)continue;let G=String(z);for(let Y of Array.isArray(q)?q:[q]){if(!_1(Y))continue;for(let Z of document.querySelectorAll(Y)){if(Z.textContent===G)continue;Z.textContent=G}}}}#s0(){let $=this.element.getAttribute("data-reactive-compute-mirror-param");if(!$)return{};try{let Q=JSON.parse($);return Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{}}catch{return{}}}#_0($,Q,X,j,q,z,G){if(this.#P("reactive:before-dispatch",{action:Q,params:this.#k0(X),element:this.element},{cancelable:!0}).defaultPrevented)return;let Z=Number(j)||0;if(Z>0)return this.#r0($,Z,Q,X,z,G);let H=Number(q)||0;if(H>0)return this.#e0($,H,Q,X,z,G);return this.#w(Q,X,z,$,G)}#w($,Q,X,j,q){let z=this.#g1(X,j),G=this.#c1($,j,q),Y=this.#o()?this.#a0(X,j):null;return this.queue=(this.queue??Promise.resolve()).then(()=>this.#G1($,Q,z,G,Y)),this.queue}#a0($,Q){if(!$?.hide)return null;let X=this.#b0($,Q);if(!X.length)return null;return()=>{let j=X.filter((q)=>q.isConnected&&!q.hidden);if(!j.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.",j)}}#r0($,Q,X,j,q,z){this.#n($);let G=()=>{this.#n($),this.#w(X,j,q,$,z)},Y=setTimeout(G,Q);$?.addEventListener?.("blur",G,{once:!0}),this.#F.set($,{timer:Y,flush:G})}#n($){let Q=this.#F.get($);if(!Q)return;clearTimeout(Q.timer),$?.removeEventListener?.("blur",Q.flush),this.#F.delete($)}#t0(){for(let $ of[...this.#F.keys()])this.#n($)}#e0($,Q,X,j,q,z){let G=this.#L.get($)??new Map;if(G.has(X))return;let Y=setTimeout(()=>{if(G.delete(X),G.size===0)this.#L.delete($)},Q);return G.set(X,Y),this.#L.set($,G),this.#w(X,j,q,$,z)}#$1(){for(let $ of this.#L.values())for(let Q of $.values())clearTimeout(Q);this.#L.clear()}#P($,Q,{cancelable:X=!1}={}){let j=new CustomEvent($,{bubbles:!0,composed:!0,cancelable:X,detail:Q});return(this.element.isConnected?this.element:document).dispatchEvent(j),j}#Z($,Q,X,j){let q=()=>{if(!this.element.isConnected){console.warn("[phlex-reactive] retry() ignored — the reactive root left the DOM");return}return this.#w($,Q)};this.#P("reactive:error",{action:$,params:X,...j,retry:q})}#H($){if(this.element?.isConnected===!1)return;this.element?.setAttribute?.("data-reactive-error",$)}#Q1(){this.element?.removeAttribute?.("data-reactive-error")}#X1(){let $=document.querySelector("[data-reactive-error-flash]");if(!$?.content)return;let Q=$.getAttribute("data-reactive-error-flash")||"flash",X=document.getElementById(Q);if(!X)return;X.appendChild($.content.cloneNode(!0))}#j1(){if(typeof sessionStorage>"u")return Promise.resolve();let $=Number(sessionStorage.getItem(c));if(!Number.isFinite($)||$<=0)return Promise.resolve();if(!D)D=!0,console.warn(`[phlex-reactive] latency simulator ACTIVE — every action is delayed by ${$}ms. Call PhlexReactive.disableLatencySim() (or clear sessionStorage) to turn it off.`);return new Promise((Q)=>setTimeout(Q,$))}#o(){return this.element?.getAttribute?.("data-reactive-debug")==="true"}#A0(){return typeof performance<"u"&&typeof performance.now==="function"?performance.now():Date.now()}#q1($){if(!$)return[];let Q=[],X=/<turbo-stream\b([^>]*)>/g,j;while((j=X.exec($))!==null){let q=j[1],z=q.match(/\baction="([^"]*)"/)?.[1]??"?",G=q.match(/\btarget="([^"]*)"/)?.[1];Q.push(G?`${z} → #${G}`:z)}return Q}#z1($){let{action:Q,status:X,ms:j}=$,z=`reactive ${this.element?.id?`#${this.element.id} `:""}${Q} → ${X??"—"} (${Math.round(j)}ms)`;if(console.groupCollapsed(z),console.log(`params: [${$.paramNames.join(", ")}] + collected: [${$.fieldNames.join(", ")}]`),console.log(`encoding: ${$.encoding}`),$.streams.length)console.log(`streams: ${$.streams.join(" ")}`);console.log(`token: ${$.tokenRefreshed?"refreshed ✓":"unchanged"}`),console.groupEnd()}async#G1($,Q,X,j,q){let{fields:z,files:G}=this.#N0(),Y=this.#k0(Q),Z={...z,...Y},H=this.#U,K=G.length>0,V=K?this.#f1(H,$,Z,G):JSON.stringify({token:H,act:$,params:Z}),J=this.#o()?{action:$,paramNames:Object.keys(Y),fieldNames:Object.keys(z),encoding:K?"multipart":"json",status:null,streams:[],tokenRefreshed:!1,started:this.#A0()}:null;await this.#j1();try{if(navigator.onLine===!1){this.#K(X),this.#H("offline"),this.#Z($,Q,Z,{kind:"offline"});return}let B;try{let W={Accept:"text/vnd.turbo-stream.html","X-CSRF-Token":this.#r1()};if(!K)W["Content-Type"]="application/json";let A=this.#t1();if(A)W["X-Pgbus-Connection"]=A;B=await fetch(this.#s1(),{method:"POST",headers:W,body:V,credentials:"same-origin",signal:AbortSignal.timeout(this.#a1())})}catch(W){if(console.error("[phlex-reactive] action error",W),this.#K(X),W?.name==="TimeoutError"||W?.name==="AbortError"){this.#H("timeout"),this.#Z($,Q,Z,{kind:"timeout"});return}this.#X1(),this.#H("network"),this.#Z($,Q,Z,{kind:"network"});return}if(J)J.status=B.status;if(B.redirected){console.error("[phlex-reactive] action was redirected (auth/CSRF?) — no update applied"),this.#K(X),this.#H("redirected"),this.#Z($,Q,Z,{kind:"redirected",status:B.status});return}if(!B.ok){let W=await B.text();if(console.error(`[phlex-reactive] action failed: HTTP ${B.status}`,W),this.#K(X),(B.headers.get("Content-Type")||"").includes("turbo-stream")){let A=this.#O0(W);if(this.#U=A??this.#U,J)this.#x0(J,W,A);window.Turbo.renderStreamMessage(W)}this.#H("http"),this.#Z($,Q,Z,{kind:"http",status:B.status,body:W});return}let x=B.headers.get("Content-Type")||"";if(!x.includes("turbo-stream")){console.error(`[phlex-reactive] expected a turbo-stream, got "${x}" — no update applied`),this.#K(X),this.#H("content-type"),this.#Z($,Q,Z,{kind:"content-type",status:B.status});return}let U=await B.text(),L=this.#O0(U);if(this.#U=L??this.#U,J)this.#x0(J,U,L);if(window.Turbo.renderStreamMessage(U),q)queueMicrotask(q);this.#Q1(),this.#P("reactive:applied",{action:$,params:Z,html:U})}catch(B){console.error("[phlex-reactive] action error",B),this.#K(X),this.#P("reactive:error",{action:$,params:Z,kind:"apply"})}finally{if(j?.(),J)this.#z1({...J,ms:this.#A0()-J.started})}}#x0($,Q,X){$.streams=this.#q1(Q),$.tokenRefreshed=X!=null}get#U(){return this.#j0??this.tokenValue}set#U($){this.#j0=$}#O0($){let Q=this.element.id;if(!Q)return $.match(/data-reactive-token-value="([^"]+)"/)?.[1];let{token:X,self:j}=this.#Y1(Q),q=$.match(X);if(q)return q[1];let z=$.match(j);if(z)return z[1].match(/data-reactive-token-value="([^"]+)"/)?.[1];return}#Y1($){let Q=this.#q0;if(Q&&Q.id===$)return Q;let X=G1($);return this.#q0={id:$,token:new RegExp(`<turbo-stream\\b[^>]*\\baction="reactive:token"[^>]*\\btarget="${X}"[^>]*\\bdata-reactive-token-value="([^"]+)"`),self:new RegExp(`<turbo-stream\\b[^>]*\\baction="(?:replace|update)"[^>]*\\btarget="${X}"[^>]*>([\\s\\S]*?)</turbo-stream>`)}}#X($){return $.closest('[data-controller~="reactive"]')===this.element}#$(){if(this.element.querySelectorAll('[data-controller~="reactive"]').length===0)return()=>!0;return(Q)=>this.#X(Q)}#s($,Q){if($)return $;if(!Q)return null;let X=Q;if(typeof Q==="string")try{X=JSON.parse(Q)}catch{return console.warn(`[phlex-reactive] malformed conditional confirm payload ${JSON.stringify(Q)} — skipped`),null}if(!X||typeof X!=="object")return null;let{fields:j}=this.#N0(),q=(G)=>j[G],z;if(typeof X.predicate==="string"){let G=S0(X.predicate);if(!G)return console.warn(`[phlex-reactive] confirm predicate "${X.predicate}" is not registered — proceeding without a dialog (register it with setConfirmPredicate)`),null;z=!!G(j)}else z=O(X.groups?.any,q)===!0;return z?X.message:null}#N0(){let $={},Q=[],X=this.#$();return this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach((j)=>{if(!X(j))return;if(j.type==="file")for(let q of j.files??[])Q.push({name:j.name,file:q,multiple:j.multiple});else if(j.type==="checkbox")$[j.name]=j.checked;else if(j.type==="radio"){if(j.checked)$[j.name]=j.value}else $[j.name]=j.value}),this.element.querySelectorAll("[name]:is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])").forEach((j)=>{if(!X(j))return;let q=j.getAttribute("name");if(!q)return;let z=$[q];if(z==null||z==="")$[q]=j.value??j.textContent??j.innerHTML??""}),{fields:$,files:Q}}#a(){if(typeof this.element?.querySelectorAll!=="function")return;let $=0;if(this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach((Q)=>{if(!this.#X(Q))return;if(Q.type==="file")return;if(this.#Z1(Q))Q.setAttribute("data-reactive-dirty","true"),$++;else Q.removeAttribute("data-reactive-dirty")}),$>0)this.element.setAttribute("data-reactive-dirty",String($));else this.element.removeAttribute("data-reactive-dirty")}#Z1($){if($.type==="checkbox"||$.type==="radio")return $.checked!==$.defaultChecked;if($.tag==="select"||$.options)return Array.from($.options??[]).some((Q)=>Q.selected!==Q.defaultSelected);return $.value!==$.defaultValue}#P0(){let $=this.element.getAttribute?.("data-reactive-dirty"),Q=Number($);return Number.isFinite(Q)&&Q>0?Q:0}#H1(){if(typeof window>"u"||typeof window.addEventListener!=="function")return;this.#V=($)=>{if(this.#P0()===0)return;return $.preventDefault(),$.returnValue="You have unsaved changes.",$.returnValue},this.#M=($)=>{if(this.#P0()===0)return;if(!(typeof window.confirm==="function"?window.confirm("You have unsaved changes. Leave anyway?"):!0))$.preventDefault?.()},window.addEventListener("beforeunload",this.#V),window.addEventListener("turbo:before-visit",this.#M)}#U1(){if(this.#B)this.element.removeEventListener?.("turbo:morph-element",this.#B),this.#B=void 0;if(typeof window<"u"&&typeof window.removeEventListener==="function"){if(this.#V)window.removeEventListener("beforeunload",this.#V);if(this.#M)window.removeEventListener("turbo:before-visit",this.#M)}this.#V=void 0,this.#M=void 0}#K1(){if(this.element.getAttribute?.("data-reactive-show-targets"))return!0;let $=this.element.querySelectorAll?.(j0)??[];for(let Q of $)if(this.#X(Q))return!0;return!1}#J1(){return!!this.element.getAttribute?.("data-reactive-on-complete")}#L1(){if(this.element.getAttribute?.("data-reactive-clipboard"))return!0;let $=this.element.querySelectorAll?.("[data-reactive-clipboard]")??[];for(let Q of $)if(this.#X(Q))return!0;return!1}#D0(){let $=typeof globalThis.navigator?.clipboard?.readText==="function";if(this.element.getAttribute?.("data-reactive-clipboard"))this.element.hidden=!$;for(let Q of this.element.querySelectorAll?.("[data-reactive-clipboard]")??[])if(this.#X(Q))Q.hidden=!$}#W1(){if(!this.#O)return;this.element.removeEventListener?.("turbo:morph-element",this.#O),this.#O=void 0}#B1(){let $=this.element.getAttribute?.("data-reactive-on-complete")??null;if($!==this.#Y0)this.#Y0=$,this.#c=$==null?[]:P1($),this.#d=this.#c.map(()=>!1);return this.#c}#r($){let Q=this.#B1();if(!Q.length)return;let X=this.#$(),j=this.element.getAttribute?.("data-reactive-scope")||null,q=new Map,z=(G)=>{if(!q.has(G))q.set(G,this.#I0(G,X,j));return q.get(G)};Q.forEach((G,Y)=>{let Z=O(G.any,z);if(Z===null)return;let H=Z&&!this.#d[Y]&&Boolean($);if(this.#d[Y]=Z,H)N(G.ops,(K)=>this.#f(K.to==null?{...K,to:"@root"}:K),(K,V)=>this.#y(`client op "${K}"`,V))})}#V1(){if(!this.#Y)return;this.element.removeEventListener?.("input",this.#Y),this.element.removeEventListener?.("change",this.#Y),this.element.removeEventListener?.("turbo:morph-element",this.#g)}#F0(){if(typeof this.element?.querySelectorAll!=="function")return;let $=this.#$(),Q=this.element.getAttribute?.("data-reactive-scope")||null,X=new Map,j=(q)=>{if(!X.has(q))X.set(q,this.#I0(q,$,Q));return X.get(q)};for(let q of this.element.querySelectorAll(j0)){if(!$(q))continue;let z=q.getAttribute("data-reactive-show");if(z!==null){let H=F1(N1(z),j);if(H!==null)this.#R0(q,H,$,Q);continue}let G=q.getAttribute("data-reactive-show-field");if(!G)continue;let Y=j(G);if(Y===null)continue;let Z=A1(q,Y);if(Z===null)continue;this.#R0(q,Z,$,Q)}this.#M1(j)}#R0($,Q,X,j){if($.hidden=!Q,$.getAttribute("data-reactive-show-disable")!=="true")return;if(typeof $.querySelectorAll!=="function")return;for(let q of $.querySelectorAll("input[name], select[name], textarea[name]"))if(X(q))q.disabled=!Q;if($.name&&X($))$.disabled=!Q}#M1($){let Q=this.#A1();for(let[X,j]of Object.entries(Q)){if(X.startsWith("#")){this.#_1(X,j,$);continue}if(!j||typeof j!=="object"||Array.isArray(j))continue;let q=$(X);if(q===null)continue;let z=()=>q;for(let[G,Y]of Object.entries(j)){if(!q0(G))continue;let Z;if(Array.isArray(Y)){if(Y.length===0){console.warn(`[phlex-reactive] malformed reactive_show_targets group for ${G} — skipped`);continue}Z=Y.every((H)=>a(H,z))}else{let H=R0(Y,q);if(H===null){console.warn(`[phlex-reactive] malformed reactive_show_targets predicate for ${G} — skipped`);continue}Z=H}for(let H of document.querySelectorAll(G))H.hidden=!Z}}}#_1($,Q,X){if(!q0($))return;let j=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.any:null,q=D1(j);if(q===null){console.warn(`[phlex-reactive] malformed reactive_show_targets conditions for ${$} — skipped`);return}if(q.every((G)=>X(G)===null))return;let z=O(j,X);if(z===null)return;for(let G of document.querySelectorAll($))G.hidden=!z}#A1(){let $=this.element.getAttribute?.("data-reactive-show-targets");if(!$)return{};try{let Q=JSON.parse($);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}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: { ... })"),{}}#I0($,Q,X){let j=X&&!$.includes("[")?`${X}[${$}]`:$,q=!1,z=null;for(let G of this.element.querySelectorAll(`[name="${j}"]`)){if(!Q(G))continue;if(G.type==="checkbox")return G.checked?"true":"false";if(G.type==="radio"){if(G.checked)return G.value??"";q=!0;continue}z??=G}if(z)return z.value??"";return q?"":null}#x1(){let $=this.#q;this.#N=!1;let Q=u(this.element,$);if(Q){if(L1(this.element,$,Q.fields),Q.state)this.element.setAttribute?.(d,JSON.stringify(Q.state));this.#P("reactive:persist-restored",{key:$.key,fields:Q.fields,state:Q.state??{}})}this.#N=!0,this.#C=()=>this.#O1(),this.#E=()=>this.#b(),this.#k=(X)=>this.#N1(X),this.element.addEventListener?.("input",this.#C),this.element.addEventListener?.("change",this.#E),document.addEventListener?.("turbo:submit-end",this.#k)}#O1(){if(!this.#N)return;let $=Number(this.#q?.debounce)||0;if($<=0)return this.#b();if(this.#Q!==null)clearTimeout(this.#Q);this.#Q=setTimeout(()=>{this.#Q=null,this.#b()},$)}#b(){if(!this.#N||!this.#q)return;if(this.#Q!==null)clearTimeout(this.#Q),this.#Q=null;let $=this.#q,Q=u(this.element,$);A0(this.element,$,{fields:N0(this.element,$),state:Q?.state??null})}#N1($){if(!$?.detail?.success)return;let Q=$.target;if(Q?.tagName!=="FORM"||typeof Q.contains!=="function")return;if(!Q.contains(this.element))return;if(this.#Q!==null)clearTimeout(this.#Q),this.#Q=null;s(this.element,this.#q)}#P1(){if(!this.#q)return;if(this.#Q!==null)this.#b();this.element.removeEventListener?.("input",this.#C),this.element.removeEventListener?.("change",this.#E),document.removeEventListener?.("turbo:submit-end",this.#k),this.#C=this.#E=this.#k=void 0,this.#q=null,this.#N=!1}#D1(){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}#h(){return!!(this.element.getAttribute?.("data-reactive-filter-input")&&this.element.getAttribute?.("data-reactive-filter-option"))}#F1(){return this.element.getAttribute?.("data-reactive-compute-seed")==="true"}#R1($){let Q=this.element.getAttribute("data-reactive-filter-input");return!!Q&&typeof $.target?.matches==="function"&&$.target.matches(Q)}#D(){if(typeof this.element?.querySelectorAll!=="function")return;let $=this.element.getAttribute("data-reactive-filter-input"),Q=this.element.getAttribute("data-reactive-filter-option");if(!$||!Q)return;let X=this.#$(),j=[...this.element.querySelectorAll($)].find(X);if(!j)return;let q=(j.value??"").trim().toLowerCase(),z=0;for(let Z of this.element.querySelectorAll(Q)){if(!X(Z))continue;let H=(Z.getAttribute("data-reactive-filter-text")??Z.textContent??"").toLowerCase(),K=Z.hasAttribute?.("data-reactive-tags-selected")||q!==""&&!H.includes(q);if(Z.hidden=K,K)Z.removeAttribute("data-reactive-highlighted");else z++}let G=this.element.getAttribute("data-reactive-filter-group");if(G)for(let Z of this.element.querySelectorAll(G)){if(!X(Z))continue;let H=[...Z.querySelectorAll(Q)].filter(X);if(H.length===0)continue;Z.hidden=H.every((K)=>K.hidden)}let Y=this.element.getAttribute("data-reactive-filter-empty");if(Y){for(let Z of this.element.querySelectorAll(Y))if(X(Z))Z.hidden=z>0}}#I1(){if(!this.#z)return;this.element.removeEventListener?.("input",this.#z),this.element.removeEventListener?.("turbo:morph-element",this.#z),this.#z=void 0}#v(){return!!this.element.getAttribute?.("data-reactive-tags-field")}#C1(){if(typeof this.element?.querySelector!=="function")return!1;return!!this.element.querySelector("[data-reactive-nested-json]")}#t(){if(typeof this.element?.querySelectorAll!=="function")return null;let $=this.element.getAttribute("data-reactive-tags-field");if(!$)return null;let Q=this.#$();return[...this.element.querySelectorAll($)].find(Q)??null}#e($){let Q=new Set,X=[];for(let j of String($.value??"").split(",")){let q=j.trim();if(q===""||Q.has(q.toLowerCase()))continue;Q.add(q.toLowerCase()),X.push(q)}return X}#C0($){let Q=this.#t();if(!Q)return!1;let X=this.#e(Q),j=new Set(X.map((z)=>z.toLowerCase())),q=!1;for(let z of $){let G=String(z??"").trim();if(G===""||j.has(G.toLowerCase()))continue;j.add(G.toLowerCase()),X.push(G),q=!0}if(q)this.#E0(Q,X);return q}#E0($,Q){if($.value=Q.join(","),typeof $.dispatchEvent==="function")$.dispatchEvent(new Event("input",{bubbles:!0}));this.#$0()}#E1(){if(typeof this.element?.querySelectorAll!=="function")return null;let $=this.element.getAttribute("data-reactive-filter-input");if(!$)return null;let Q=this.#$();return[...this.element.querySelectorAll($)].find(Q)??null}#$0(){let $=this.#t();if(!$)return;let Q=this.#e($),X=this.#$();this.#k1(Q,X),this.#T1(Q,X)}#k1($,Q){let X=[...this.element.querySelectorAll("[data-reactive-tags-list]")].find(Q);if(!X)return;let q=[...this.element.querySelectorAll("[data-reactive-tags-template]")].find(Q)?.content?.firstElementChild;if(!q){if(!this.#Z0)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.#Z0=!0;return}while(X.firstChild)X.removeChild(X.firstChild);for(let z of $){let G=q.cloneNode(!0);G.setAttribute?.("data-reactive-tag",z);let Y=G.matches?.("[data-reactive-tag-text]")?G:(G.querySelectorAll?.("[data-reactive-tag-text]")??[])[0];if(Y)Y.textContent=z;let Z=[...G.querySelectorAll?.('[data-action*="reactive#tagsRemove"]')??[]];if(G.matches?.('[data-action*="reactive#tagsRemove"]'))Z.push(G);for(let H of Z)H.setAttribute?.("data-reactive-tag-param",z);X.appendChild(G)}}#T1($,Q){let X=new Set($.map((j)=>j.toLowerCase()));for(let j of this.element.querySelectorAll("[role=option]")){if(!Q(j))continue;let q=j.getAttribute?.("data-reactive-tag-param");if(!q)continue;if(X.has(q.toLowerCase()))j.setAttribute("data-reactive-tags-selected","true"),j.hidden=!0,j.removeAttribute?.("data-reactive-highlighted");else if(j.hasAttribute?.("data-reactive-tags-selected")){if(j.removeAttribute("data-reactive-tags-selected"),!this.#h())j.hidden=!1}}if(this.#h())this.#D()}#S1(){return this.#l=Math.max(this.#l+1,Date.now()),this.#l}#w1($,Q){let X=[$,...$.querySelectorAll?.("*")??[]];for(let j of X)for(let q of["name","id","for"]){let z=j.getAttribute?.(q);if(z&&z.includes("NEW_ROW"))j.setAttribute?.(q,z.replaceAll("NEW_ROW",String(Q)))}}#b1($){if(this.#H0)return;console.warn(`[phlex-reactive] nested rows: no owned [data-reactive-nested-list="${$}"] container + <template data-reactive-nested-template="${$}"> pair found in this root — the add `+"trigger did nothing. Render both inside the same reactive root (reactive_nested_list / reactive_nested_template)."),this.#H0=!0}#h1(){if(!this.#_)return;this.element.removeEventListener?.("turbo:morph-element",this.#_),this.#_=void 0}#v1(){if(this.#G)this.element.removeEventListener?.("input",this.#G),this.element.removeEventListener?.("change",this.#G),this.#G=void 0;if(this.#A)this.element.removeEventListener?.("turbo:morph-element",this.#A),this.#A=void 0}#y1(){if(!this.#x)return;this.element.removeEventListener?.("turbo:morph-element",this.#x),this.#x=void 0}#f1($,Q,X,j){let q=new FormData;q.append("token",$),q.append("act",Q);for(let[G,Y]of Object.entries(X))this.#X0(q,this.#Q0(G),Y);let z=this.#u1(j);for(let{name:G,file:Y,multiple:Z}of j){let K=Z||z.has(G)?`${this.#Q0(G)}[]`:this.#Q0(G);q.append(K,Y,Y.name)}return q}#Q0($){let Q=String($),X=Q.indexOf("[");if(X===-1)return`params[${Q}]`;return`params${[Q.slice(0,X),...Q.slice(X).match(/[^\[\]]+/g)??[]].map((q)=>`[${q}]`).join("")}`}#X0($,Q,X){if(X==null)$.append(Q,"");else if(Array.isArray(X))X.forEach((j,q)=>this.#X0($,`${Q}[${q}]`,j));else if(typeof X==="object")for(let[j,q]of Object.entries(X))this.#X0($,`${Q}[${j}]`,q);else $.append(Q,String(X))}#u1($){let Q=new Map;for(let{name:X}of $)Q.set(X,(Q.get(X)??0)+1);return new Set([...Q].filter(([,X])=>X>1).map(([X])=>X))}#k0($){if(!$)return{};try{return typeof $==="string"?JSON.parse($):$}catch{return{}}}#T0($){return I0($)}#S0($){N($,(Q)=>this.#f(Q),(Q,X)=>this.#y(`client op "${Q}"`,X))}#m1(){return this.element?.getAttribute?.("data-reactive-verbose")==="true"||this.#o()}#y($,Q){if(!this.#m1())return;let X=Q.to;if(typeof X!=="string"||X===""||X==="@root")return;let j="";if(!Q.global)if(this.element?.matches?.(X))j=" — the selector matches this component's own root, which root-scoped resolution never includes; use to: :root";else if(m(this.element,X)>0)j=" — it matches only inside a nested reactive root (excluded by ownership scoping); use global: true";else{let q=m(globalThis.document,X);if(q>0)j=` — it matches ${q} element(s) outside this scope; use global: true`}E0($,X,`scoped to #${this.element?.id||"?"}`,j)}#f($){let Q=$.to;if(Q==="@root")return[this.element];if(typeof Q!=="string"||Q==="")return[];if($.global)return[...document.querySelectorAll(Q)];return[...this.element.querySelectorAll(Q)].filter((X)=>this.#X(X))}#p1($,Q){if($?.checked!=="keep")return!1;let X=Q?.type;return X==="checkbox"||X==="radio"}#g1($,Q){if(!$)return null;let X=this.#w0($,Q,!0);return X.length?X:null}#K($){if(!$)return;if(!this.element.isConnected)return;for(let Q of $)Q()}#c1($,Q,X){this.#l1($,Q);let j=X?this.#w0(X,Q,!1):[];B0();let q=!1;return()=>{if(q)return;q=!0,this.#i1($,Q),V0();for(let z of j)z()}}#w0($,Q,X){let j=[];for(let q of this.#b0($,Q)){if($.add_class){let z=$.add_class.filter((G)=>!q.classList.contains(G));if(q.classList.add(...z),z.length)j.push(()=>q.classList.remove(...z))}if($.remove_class){let z=$.remove_class.filter((G)=>q.classList.contains(G));if(q.classList.remove(...z),z.length)j.push(()=>q.classList.add(...z))}if($.toggle_class)$.toggle_class.forEach((z)=>q.classList.toggle(z)),j.push(()=>$.toggle_class.forEach((z)=>q.classList.toggle(z)));if($.hide)q.hidden=!0,j.push(()=>q.hidden=!1);if($.show)q.hidden=!1,j.push(()=>q.hidden=!0)}if(Q&&($.disable||$.text!=null))j.push(this.#d1($,Q));if(X&&$.checked==="keep"&&Q&&"checked"in Q){let q=Q.checked;j.push(()=>Q.checked=!q)}return j}#b0($,Q){if($.to==null)return Q?[Q]:[];let X=this.#f({to:$.to});if(X.length===0)this.#y("busy/optimistic hint",{to:$.to});return X}#d1($,Q){let X=this.#R.get(Q);if(X)X.count++;else this.#R.set(Q,{count:1,disabled:Q.disabled,html:Q.innerHTML,hadText:$.text!=null,swappedTo:$.text});if($.disable)Q.disabled=!0;if($.text!=null)Q.innerHTML=$.text;return()=>this.#n1(Q,$)}#l1($,Q){if(this.#J(Q,$,1),this.#J(this.element,$,1),this.#W.set($,(this.#W.get($)??0)+1),this.#m++===0)this.element.setAttribute("aria-busy","true");for(let X of this.#h0($))this.#J(X,$,1)}#i1($,Q){this.#J(Q,$,-1),this.#J(this.element,$,-1);let X=(this.#W.get($)??1)-1;if(X<=0)this.#W.delete($);else this.#W.set($,X);if(--this.#m<=0)this.#m=0,this.element.removeAttribute("aria-busy");for(let j of this.#h0($))this.#J(j,$,-1)}#J($,Q,X){if(!$||typeof $.getAttribute!=="function")return;let j=this.#p.get($)??new Map,q=(j.get(Q)??0)+X;if(q<=0)j.delete(Q);else j.set(Q,q);if(j.size===0){this.#p.delete($),$.removeAttribute("data-reactive-busy");return}this.#p.set($,j),$.setAttribute("data-reactive-busy",[...j.keys()].join(" "))}#h0($){return[...this.element.querySelectorAll?.("[data-reactive-busy-on]")??[]].filter((X)=>X.getAttribute("data-reactive-busy-on")===$&&this.#X(X))}#n1($,Q){let X=this.#R.get($);if(!X)return;if(--X.count>0)return;if(this.#R.delete($),!$.isConnected)return;if(Q.disable)$.disabled=X.disabled;if(X.hadText&&$.innerHTML===X.swappedTo)$.innerHTML=X.html}#o1($){if(!$||typeof $!=="object")return null;let{class:Q,...X}=$;return Q==null?$:{...X,add_class:Q}}#s1(){return this.#v0??=document.querySelector('meta[name="phlex-reactive-action-path"]')?.content||"/reactive/actions"}#a1(){if(this.#u!=null)return this.#u;let $=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,Q=Number($);return this.#u=Number.isFinite(Q)&&Q>0?Q:30000}#r1(){return document.querySelector('meta[name="csrf-token"]')?.content??""}#t1(){return document.querySelector("pgbus-stream-source[connection-id]")?.getAttribute("connection-id")||document.querySelector('meta[name="pgbus-connection-id"]')?.content||null}}export{v1 as resetReactiveDefers,c1 as resetReactiveActivity,w0 as registerReactiveVisit,b0 as registerReactiveToken,X1 as registerReactiveOffline,h0 as registerReactiveJs,i0 as registerReactiveEffects,c0 as registerReactiveDismiss,v0 as registerReactiveDefer,e as registerReactiveActions,g1 as reactiveActivityCount,y1 as pendingDeferVia,V0 as exitReactiveActivity,G1 as escapeRegExp,B0 as enterReactiveActivity,j1 as enableLatencySim,q1 as disableLatencySim,i1 as default,Y1 as checkReactiveRegistration,d1 as __resetReactiveRegistrationForTest,m1 as __resetReactiveOfflineForTest,p1 as __resetReactiveLatencyForTest,u1 as __resetReactiveEffectsForTest,f1 as __resetReactiveDismissForTest,l1 as __markReactiveConnectedForTest,c as LATENCY_KEY,W0 as ACTIVE_ATTR};
2
2
 
3
- //# debugId=48A0C1884C683EB564756E2164756E21
3
+ //# debugId=699F61A8BB96642764756E2164756E21
4
4
  //# sourceMappingURL=reactive_controller.min.js.map