phlex-reactive 0.12.5 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 De}from"@hotwired/stimulus";import{confirmResolver as _}from"phlex/reactive/confirm";import{computeReducer as Fe}from"phlex/reactive/compute";import{confirmPredicate as Me}from"phlex/reactive/confirm_predicate";function Pe(){let e=window.Turbo?.StreamActions;if(!e||e["reactive:visit"])return;e["reactive:visit"]=function(){let t=this.getAttribute("data-url");if(t)window.Turbo.visit(t,{action:"advance"})}}function je(){let e=window.Turbo?.StreamActions;if(!e||e["reactive:token"])return;e["reactive:token"]=function(){let t=this.getAttribute("data-reactive-token-value"),n=this.getAttribute("target");if(!t||!n)return;let r=document.getElementById(n);if(r)r.setAttribute("data-reactive-token-value",t)}}function Je(){let e=window.Turbo?.StreamActions;if(!e||e["reactive:js"])return;e["reactive:js"]=function(){let t=Re(this.getAttribute("data-reactive-ops"));if(!t.length)return;let n=this.getAttribute("target"),r=this.getAttribute("data-reactive-verbose")==="true",i=n?document.getElementById(n):null;if(n&&!i){if(r&&!qe(`missing-root|#${n}`))console.warn(`[phlex-reactive] reactive:js stream target root #${n} is not in the DOM — its ops were dropped`);return}S(t,(s)=>Ht(s,i),r?(s,o)=>Wt(s,o,i):void 0)}}var g=new Map;function fe(e,t){let n=!g.has(e);if(g.set(e,t),n)Ae()}function k(e){if(g.delete(e))we()}function Ut(){g.clear(),D=!1}function Yt(e){return g.get(e)?.via}var D=!1;function Ie(){let e=window.Turbo?.StreamActions;if(!e||e["reactive:defer"])return;if(e["reactive:defer"]=function(){let t=this.getAttribute("target");if(!t)return;if(this.getAttribute("data-reactive-defer-via")==="stream"){We(t,this);return}let n=this.getAttribute("data-reactive-defer-token");if(!n)return;T(t,n)},!D&&typeof document<"u"&&document.addEventListener)D=!0,document.addEventListener("turbo:before-stream-render",Be)}function Be(e){let n=e.target?.getAttribute?.("target");if(!n)return;let r=n.startsWith("reactive-defer-src-")?n.slice(19):n;if(g.get(r)?.via==="stream")k(r)}function T(e,t){let n=document.getElementById(e);if(!n){console.warn(`[phlex-reactive] reactive:defer target #${e} is not on the page — skipped`);return}he(e),me(n);let r={via:"fetch",abort:new AbortController,timedOut:!1};fe(e,r),He(e,r,t)}function We(e,t){let n=document.getElementById(e);if(!n){console.warn(`[phlex-reactive] reactive:defer target #${e} is not on the page — skipped`);return}let r=t.getAttribute("data-reactive-defer-src");if(!r)return;if(!globalThis.customElements?.get?.("pgbus-stream-source")){let s=t.getAttribute("data-reactive-defer-token");if(s){T(e,s);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}he(e),me(n);let i=document.createElement("pgbus-stream-source");i.id=de(e),i.setAttribute("src",r),i.setAttribute("since-id",t.getAttribute("data-reactive-defer-since-id")??"0"),i.setAttribute("hidden",""),document.body.appendChild(i),fe(e,{via:"stream"})}function de(e){return`reactive-defer-src-${e}`}async function He(e,t,n){let r=setTimeout(()=>{t.timedOut=!0,t.abort.abort()},Ge()),i;try{i=await fetch(Ve(),{method:"POST",headers:{Accept:"text/vnd.turbo-stream.html","Content-Type":"application/json","X-CSRF-Token":ze()},body:JSON.stringify({token:n}),credentials:"same-origin",signal:t.abort.signal})}catch(o){if(clearTimeout(r),g.get(e)!==t)return;console.error("[phlex-reactive] deferred render failed",o),N(e,n);return}if(g.get(e)!==t){clearTimeout(r);return}if(i.status===204){clearTimeout(r),ee(e);return}if(!i.ok){clearTimeout(r),console.error(`[phlex-reactive] deferred render failed: HTTP ${i.status}`),N(e,n,i.status);return}let s;try{s=await i.text()}catch(o){if(clearTimeout(r),g.get(e)!==t)return;console.error("[phlex-reactive] deferred render failed reading the body",o),N(e,n);return}if(clearTimeout(r),g.get(e)!==t)return;ee(e),window.Turbo.renderStreamMessage(s)}function he(e){let t=g.get(e);if(!t)return;if(k(e),t.via==="fetch")t.abort.abort();else document.getElementById(de(e))?.remove?.()}function me(e){e.setAttribute("data-reactive-defer-pending","true"),e.setAttribute("aria-busy","true")}function pe(e){e.removeAttribute("data-reactive-defer-pending"),e.removeAttribute("aria-busy")}function ee(e){k(e);let t=document.getElementById(e);if(!t)return;pe(t),t.removeAttribute("data-reactive-error")}function N(e,t,n){k(e);let r=document.getElementById(e);if(!r)return;pe(r),r.setAttribute("data-reactive-error","defer");let i=()=>{let s=document.getElementById(e);if(!s){console.warn("[phlex-reactive] defer retry() ignored — the target left the DOM");return}s.removeAttribute("data-reactive-error"),T(e,t)};r.dispatchEvent(new CustomEvent("reactive:error",{bubbles:!0,composed:!0,detail:{kind:"defer",target:e,status:n,retry:i}}))}function Ve(){return document.querySelector('meta[name="phlex-reactive-defer-path"]')?.content||"/reactive/defer"}function ze(){return document.querySelector('meta[name="csrf-token"]')?.content??""}function Ge(){let e=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,t=Number(e);return Number.isFinite(t)&&t>0?t:30000}var F=!1;function Ke(){if(F)return;if(typeof document>"u"||!document.addEventListener)return;F=!0,document.addEventListener("turbo:before-stream-render",Ue)}function Ue(e){let t=e.detail,n=t?.render;if(typeof n!=="function"||n.__reactiveDismissWrapped){if(typeof requestAnimationFrame==="function")requestAnimationFrame(C);else setTimeout(C,0);return}let r=async(i)=>{await n(i),C()};r.__reactiveDismissWrapped=!0,t.render=r}function C(){let e=document.querySelectorAll("[data-reactive-dismiss-after]");for(let t of e){if(t.hasAttribute("data-reactive-dismiss-scheduled"))continue;let n=Number(t.getAttribute("data-reactive-dismiss-after"));if(!Number.isFinite(n)||n<=0)continue;t.setAttribute("data-reactive-dismiss-scheduled",""),setTimeout(()=>t.remove(),n)}}function Xt(){F=!1}var Ye=Object.freeze({append:"enter",prepend:"enter",replace:"update",update:"update",remove:"exit"}),O=Object.freeze(["fade","slide","scale","highlight","shake"]),M="data-reactive-fx-pending",ve=1000,P=!1;function Xe(){if(P)return;if(typeof document>"u"||typeof document.addEventListener!=="function")return;P=!0,document.addEventListener("turbo:before-stream-render",Ze)}function Zt(){P=!1}function Ze(e){let t=e.detail,n=t?.render;if(typeof n!=="function"||n.__reactiveEffectsWrapped)return;let r=t?.newStream??e.target,i=Ye[r?.getAttribute?.("action")];if(!i||tt())return;let s=Qe(r,i);if(!s)return;let o=i==="exit"?async(c)=>{await it(E(r),s),await n(c)}:async(c)=>{let a=i==="enter"?nt(r):null;if(await n(c),i==="enter")rt(a,s);else ge(E(r),s)};o.__reactiveEffectsWrapped=!0,t.render=o}function Qe(e,t){let n=e.getAttribute?.("data-reactive-effect");if(n==="off")return null;if(n)return te(n,t);let i=(t==="enter"?et(e):E(e))?.getAttribute?.(`data-reactive-effect-${t}`);return i?te(i,t):null}function E(e){let t=e.getAttribute?.("target");return t?document.getElementById?.(t)??null:null}function et(e){return e.querySelector?.("template")?.content?.firstElementChild??null}function te(e,t){if(e.startsWith("[")){let r=null;try{let i=JSON.parse(e);if(Array.isArray(i)&&i.length===3)r=i.map(String)}catch{}if(r)return{legs:r};return console.warn(`[phlex-reactive] malformed effect legs ${JSON.stringify(e)} — skipped`),null}let n=e==="random"?O[Math.floor(Math.random()*O.length)]:e;if(!O.includes(n))return console.warn(`[phlex-reactive] unknown effect ${JSON.stringify(e)} — skipped`),null;return{className:`reactive-fx--${n}-${t}`}}function tt(){try{return typeof matchMedia==="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}}function nt(e){let t=e.querySelector?.("template")?.content;if(!t)return null;for(let n of Array.from(t.children??[]))n.setAttribute?.(M,"");return E(e)}function rt(e,t){if(typeof e?.querySelectorAll!=="function")return;for(let n of Array.from(e.querySelectorAll(`[${M}]`)))n.removeAttribute(M),ge(n,t)}async function it(e,t){if(!e?.classList)return;if(t.legs){await ye(e,t.legs);return}e.classList.add(t.className);let n=B(e);if(n<=0){e.classList.remove(t.className);return}await W(e,n),e.classList.remove(t.className)}function ge(e,t){if(!e?.classList)return;if(t.legs){ye(e,t.legs);return}if(e.classList.contains(t.className))e.classList.remove(t.className),e.offsetWidth;e.classList.add(t.className);let n=B(e);if(n<=0){e.classList.remove(t.className);return}let r=e.__reactiveFxToken=(e.__reactiveFxToken??0)+1;W(e,n).then(()=>{if(e.__reactiveFxToken===r)e.classList.remove(t.className)})}async function ye(e,t){let[n,r,i]=t.map(st),s=e.__reactiveFxToken=(e.__reactiveFxToken??0)+1;if(e.classList.remove(...n,...r,...i),e.classList.add(...n,...r),await ot(),e.__reactiveFxToken!==s)return;e.classList.remove(...r),e.classList.add(...i);let o=B(e);if(o>0)await W(e,o);if(e.__reactiveFxToken!==s)return;e.classList.remove(...n,...i)}function st(e){return String(e??"").split(/\s+/).filter(Boolean)}function B(e){if(typeof getComputedStyle!=="function")return 0;try{let t=getComputedStyle(e),n=(s)=>String(s??"").split(",").reduce((o,c)=>Math.max(o,parseFloat(c)||0),0),r=n(t.animationDuration)+n(t.animationDelay),i=n(t.transitionDuration)+n(t.transitionDelay);return Math.min(Math.max(r,i)*1000,ve)}catch{return 0}}function W(e,t){return new Promise((n)=>{let r=!1,i=()=>{if(r)return;r=!0,n()};e.addEventListener?.("animationend",i,{once:!0}),e.addEventListener?.("transitionend",i,{once:!0}),setTimeout(i,Math.min(t+50,ve))})}function ot(){return new Promise((e)=>{if(typeof requestAnimationFrame==="function")requestAnimationFrame(()=>e());else setTimeout(e,16)})}var j=!1;function at(){if(j)return;if(typeof window>"u"||typeof document>"u")return;if(typeof window.addEventListener!=="function")return;j=!0;let e=()=>{let t=document.documentElement;if(typeof t?.toggleAttribute!=="function")return;t.toggleAttribute("data-reactive-offline",globalThis.navigator?.onLine===!1)};e(),window.addEventListener("online",e),window.addEventListener("offline",e)}function Qt(){j=!1}var H="phlex-reactive:latency",x=!1;function ct(e){if(typeof sessionStorage>"u")return;sessionStorage.setItem(H,String(e))}function ut(){if(typeof sessionStorage>"u")return;sessionStorage.removeItem(H),x=!1}function lt(){if(typeof window>"u"||typeof document>"u")return;if(document.querySelector?.('meta[name="phlex-reactive-env"]')?.content!=="development")return;window.PhlexReactive={enableLatencySim:ct,disableLatencySim:ut}}function en(){x=!1}var be="data-reactive-active",y=0;function Ae(){if(y++,y===1)Se("reactive:busy")}function we(){if(y===0)return;if(y--,y===0)Se("reactive:idle")}function tn(){return y}function nn(){y=0,(typeof document<"u"?document.documentElement:null)?.removeAttribute?.(be)}function Se(e){if(typeof document>"u")return;let t=document.documentElement;if(typeof t?.toggleAttribute==="function")t.toggleAttribute(be,y>0);if(typeof document.dispatchEvent==="function"&&typeof CustomEvent==="function")document.dispatchEvent(new CustomEvent(e,{detail:{count:y}}))}function ne(){Pe(),je(),Je(),Ie(),Ke(),Xe(),at(),lt()}function ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}if(typeof window<"u")if(window.Turbo)ne();else document.addEventListener("turbo:load",ne,{once:!0});var L=!1;function dt(){if(L)return;if(typeof document>"u")return;let e=document.querySelectorAll('[data-controller~="reactive"]');if(!e||e.length===0)return;console.warn("[phlex-reactive] found "+e.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 rn(){L=!1}function sn(){L=!0}if(typeof window<"u"&&typeof document<"u"){let e=()=>setTimeout(dt,0);if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",e,{once:!0});else e()}var ht=new Set(["href","src","srcdoc","action","formaction","xlink:href","style"]);function mt(e){let t=String(e).toLowerCase();return t.startsWith("on")||ht.has(t)}function pt(e,t,n){let[r,i,s]=t;e.classList.add(r,i),n(),requestAnimationFrame(()=>{e.classList.remove(i),e.classList.add(s)});let o=!1,c=()=>{if(o)return;o=!0,e.classList.remove(r,s)};e.addEventListener("animationend",c,{once:!0}),setTimeout(c,350)}var Ee=1,vt="phlex-reactive:persist:",gt=new Set(["hidden","file","password","submit","button","reset","image"]),V="data-reactive-persist-state",yt=":is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])",bt=new Set(["lexxy-editor","trix-editor"]),At="lexxy-editor, trix-editor, trix-toolbar",re=["lexxy:change","trix-change"],wt=new Set(["","<p></p>","<p><br></p>","<div><br></div>"]),ie=new WeakSet,se=new WeakSet,oe=new WeakSet;function z(e){let t=e?.getAttribute?.("data-reactive-persist");if(!t||t==="off")return null;try{let n=JSON.parse(t);if(n&&typeof n==="object"&&typeof n.key==="string"&&n.key!=="")return n}catch{}if(!ie.has(e))ie.add(e),console.warn(`[phlex-reactive] malformed reactive_persist payload ${JSON.stringify(t)} — persistence disabled`);return null}function G(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function K(e,t){if(e?.getAttribute?.("data-reactive-debug")!=="true"||se.has(e))return;se.add(e),console.info(`[phlex-reactive] reactive_persist: storage unavailable — draft skipped (${t?.name??t})`)}function U(e){return vt+e.key}function J(e,t){let n=G();if(!n)return null;let r;try{r=n.getItem(U(t))}catch(a){return K(e,a),null}if(!r)return null;let i;try{i=JSON.parse(r)}catch{return null}if(!i||typeof i!=="object"||i.v!==Ee)return null;let s=Number(t.ttl)*1000;if(!(Number(i.savedAt)+s>Date.now()))return Y(e,t),null;let o=i.fields&&typeof i.fields==="object"?i.fields:{},c=i.state&&typeof i.state==="object"?i.state:null;return{fields:o,state:c}}function xe(e,t,{fields:n,state:r}){let i=G();if(!i)return!1;let s={v:Ee,savedAt:Date.now(),fields:n};if(r)s.state=r;try{return i.setItem(U(t),JSON.stringify(s)),!0}catch(o){return K(e,o),!1}}function Y(e,t){e?.removeAttribute?.(V);let n=G();if(!n)return;try{n.removeItem(U(t))}catch(r){K(e,r)}}function X(e,t){let n=Array.isArray(t.fields)?new Set(t.fields):null,r=[],i=(s)=>s.closest('[data-controller~="reactive"]')===e&&s.getAttribute("data-reactive-persist")!=="off";for(let s of e.querySelectorAll("input[name], select[name], textarea[name]")){if(!i(s)||gt.has(s.type)||s.closest(At))continue;if(n&&!n.has(s.name))continue;r.push({el:s,name:s.name,kind:"native"})}for(let s of e.querySelectorAll(yt)){if(!i(s))continue;let o=St(s);if(!o||n&&!n.has(o))continue;r.push({el:s,name:o,kind:bt.has(s.localName)?"editor":"contenteditable"})}return r}function St(e){return e.getAttribute("name")||typeof e.name==="string"&&e.name||null}function Z(e){return typeof e.value==="string"}function Et(e){if(typeof e.isEmpty==="boolean")return e.isEmpty;let t=e.editor?.getDocument?.();if(typeof t?.isEmpty==="function")return t.isEmpty();return wt.has(e.value.trim())}function xt(e,t,n){if(e?.getAttribute?.("data-reactive-debug")!=="true"||oe.has(e))return;oe.add(e),console.info(`[phlex-reactive] reactive_persist: could not restore editor ${JSON.stringify(t)} — ${n?.message??n}`)}function ke(e){return e.tagName==="SELECT"&&e.multiple}function Te(e,t){let n={};for(let{el:r,name:i,kind:s}of X(e,t))if(s==="editor"){if(Z(r))n[i]=r.value}else if(s==="contenteditable")n[i]=r.textContent??"";else if(r.type==="radio"){if(r.checked)n[i]=r.value;else if(!Object.hasOwn(n,i))n[i]=null}else if(r.type==="checkbox")n[i]=r.checked;else if(ke(r))n[i]=[...r.options].filter((o)=>o.selected).map((o)=>o.value);else n[i]=r.value;return n}function kt(e,t,n){let r=t.restore==="always",i=X(e,t);for(let{el:s,name:o,kind:c}of i){if(!Object.hasOwn(n,o))continue;let a=n[o];if(a===null||a===void 0)continue;if(c==="editor")Le(e,s,o,a,r);else if(c==="contenteditable"){if(!r&&(s.textContent??"").trim()!=="")continue;s.textContent=String(a)}else if(s.type==="radio"){if(!r&&i.some((u)=>u.kind==="native"&&u.el.type==="radio"&&u.name===o&&u.el.checked))continue;s.checked=s.value===String(a)}else if(s.type==="checkbox"){if(!r&&s.checked)continue;s.checked=Boolean(a)}else if(ke(s)){if(!r&&[...s.options].some((l)=>l.selected))continue;let u=new Set((Array.isArray(a)?a:[a]).map(String));for(let l of s.options)l.selected=u.has(l.value)}else{if(!r&&s.value!=="")continue;s.value=String(a)}}Tt(e,t,n)}function Le(e,t,n,r,i){if(!Z(t))return;if(!i&&!Et(t))return;try{t.value=String(r)}catch(s){xt(e,n,s)}}function Tt(e,t,n){let r=globalThis.customElements;if(typeof r?.whenDefined!=="function")return;let i=new Set;for(let o of e.querySelectorAll("lexxy-editor, trix-editor"))if(!Z(o)&&!r.get?.(o.localName))i.add(o.localName);let s=t.restore==="always";for(let o of i)r.whenDefined(o).then(()=>{if(!e.isConnected)return;for(let{el:c,name:a,kind:u}of X(e,t)){if(u!=="editor"||c.localName!==o||!Object.hasOwn(n,a))continue;let l=n[a];if(l===null||l===void 0)continue;Le(e,c,a,l,s)}})}function Lt(e,t){let n=z(e);if(!n){console.warn("[phlex-reactive] persist_state on a root without reactive_persist — skipped");return}if(!t||typeof t!=="object")return;let i={...J(e,n)?.state??{},...t};if(xe(e,n,{fields:Te(e,n),state:i}))e.setAttribute?.(V,JSON.stringify(i))}function _t(e){let t=z(e);if(t)Y(e,t)}var ae=Object.freeze({show:(e,t)=>R(e,!1,t),hide:(e,t)=>R(e,!0,t),toggle:(e,t)=>R(e,!e.hidden,t),add_class:(e,t)=>e.classList.add(...t.classes??[]),remove_class:(e,t)=>e.classList.remove(...t.classes??[]),toggle_class:(e,t)=>(t.classes??[]).forEach((n)=>e.classList.toggle(n)),set_attr:(e,t)=>{if(q(t.name))e.setAttribute(t.name,t.value??"")},remove_attr:(e,t)=>{if(q(t.name))e.removeAttribute(t.name)},toggle_attr:(e,t)=>{if(!q(t.name))return;if(e.hasAttribute(t.name))e.removeAttribute(t.name);else e.setAttribute(t.name,"")},focus:(e)=>e.focus?.(),focus_first:(e)=>It(e)?.focus?.(),text:(e,t)=>{let n=String(t.value??"");if(e.textContent!==n)e.textContent=n},dispatch:(e,t)=>{e.dispatchEvent(new CustomEvent(t.name,{bubbles:!0,composed:!0,detail:t.detail??{}}))},submit:(e)=>Nt(e)?.requestSubmit?.(),paste_into:(e)=>Ct(e),persist_state:(e,t)=>Lt(e,t.state),persist_clear:(e)=>_t(e)});function Nt(e){if(e?.tagName==="FORM")return e;return e?.form??e?.closest?.("form")??null}function Ct(e){let t=globalThis.navigator?.clipboard;if(typeof t?.readText!=="function")return;t.readText().then((n)=>{if(!n)return;if(e.value=n,typeof e.dispatchEvent==="function")e.dispatchEvent(new Event("input",{bubbles:!0}));e.focus?.()}).catch(()=>{})}function R(e,t,n){if(n?.transition)pt(e,n.transition,()=>e.hidden=t);else e.hidden=t}function q(e){if(!mt(e))return!0;return console.warn(`[phlex-reactive] refused client attr op on ${JSON.stringify(e)} — skipped`),!1}var _e=/^#[A-Za-z_][\w-]*$/;function Ot(e){if(typeof e==="string"&&_e.test(e))return!0;return console.warn(`[phlex-reactive] refused cross-root mirror target ${JSON.stringify(e)} — skipped`),!1}function Rt(e,t){let n=e.getAttribute("data-reactive-show-equals");if(n!==null)return t===n;let r=e.getAttribute("data-reactive-show-not");if(r!==null)return t!==r;let i=e.getAttribute("data-reactive-show-in");if(i!==null){try{let s=JSON.parse(i);if(Array.isArray(s))return s.includes(t)}catch{}return console.warn(`[phlex-reactive] malformed reactive_show in: list ${JSON.stringify(i)} — skipped`),null}for(let s of Ne){let o=e.getAttribute(`data-reactive-show-${s}`);if(o!==null)return Ce(s,o,t)}return console.warn("[phlex-reactive] a reactive_show binding declares no predicate — skipped"),null}var Ne=["gte","gt","lte","lt"],qt=["len_eq","len_gte","len_gt","len_lte","len_lt"];function $t(e,t,n){if(!Number.isInteger(t))return console.warn(`[phlex-reactive] reactive_show ${e}: needs an integer literal, got ${JSON.stringify(t)} — skipped`),null;let r=[...String(n??"")].length;switch(e){case"len_eq":return r===t;case"len_gte":return r>=t;case"len_gt":return r>t;case"len_lte":return r<=t;case"len_lt":return r<t;default:return null}}function Ce(e,t,n){let r=Number(t);if(Number.isNaN(r))return console.warn(`[phlex-reactive] reactive_show ${e}: needs a numeric literal, got ${JSON.stringify(t)} — skipped`),null;let i=n==null?"":String(n).trim(),s=i===""?NaN:Number(i);if(Number.isNaN(s))return!1;switch(e){case"gte":return s>=r;case"gt":return s>r;case"lte":return s<=r;case"lt":return s<r;default:return null}}function Oe(e,t){if(!e||typeof e!=="object")return null;if(typeof e.equals==="string")return t===e.equals;if(typeof e.not==="string")return t!==e.not;if(Array.isArray(e.in))return e.in.includes(t);for(let n of Ne)if(n in e)return Ce(n,e[n],t);for(let n of qt)if(n in e)return $t(n,e[n],t);return null}var ce="[data-reactive-show-field], [data-reactive-show]";function Dt(e){try{let t=JSON.parse(e);if(t&&typeof t==="object"&&!Array.isArray(t))return t}catch{}return console.warn(`[phlex-reactive] malformed compound reactive_show payload ${JSON.stringify(e)} — skipped`),null}function Ft(e){try{let t=JSON.parse(e);if(Array.isArray(t)&&t.every((n)=>n&&typeof n==="object"&&Array.isArray(n.any)&&Array.isArray(n.ops)))return t}catch{}return console.warn(`[phlex-reactive] malformed reactive_on_complete payload ${JSON.stringify(e)} — skipped`),[]}function Q(e,t){if(!e||typeof e!=="object"||typeof e.field!=="string")return!1;let n=t(e.field)??"";return Oe(e,n)===!0}function w(e,t){if(!Array.isArray(e)||e.length===0)return null;return e.some((n)=>Array.isArray(n)&&n.length>0&&n.every((r)=>Q(r,t)))}function Mt(e){if(!Array.isArray(e)||e.length===0)return null;let t=new Set;for(let n of e){if(!Array.isArray(n))continue;for(let r of n)if(r&&typeof r==="object"&&typeof r.field==="string")t.add(r.field)}return t.size>0?[...t]:null}function Pt(e,t){if(!e||typeof e!=="object")return null;let n=e.any;if(Array.isArray(n)&&(n.length===0||Array.isArray(n[0])))return w(n,t);return jt(e,t)}function jt(e,t){let n=Array.isArray(e.all)?"all":Array.isArray(e.any)?"any":null;if(!n)return null;let r=e[n];if(r.length===0)return null;let i=r.map((s)=>Q(s,t));return n==="all"?i.every(Boolean):i.some(Boolean)}function ue(e){if(typeof e==="string"&&_e.test(e))return!0;return console.warn(`[phlex-reactive] refused cross-root show target ${JSON.stringify(e)} — skipped`),!1}var Jt='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function It(e){return e.querySelectorAll?.(Jt)?.[0]??null}function Re(e){if(Array.isArray(e))return e;if(typeof e!=="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Bt(e){if(e==null)return null;let t=Array.isArray(e)?e:e.ops;if(Array.isArray(t))return t.length>0?t:null;return console.warn("[phlex-reactive] $ops must be an ops chain or a [[op, args], ...] list — skipped"),null}function S(e,t,n){for(let r of e){if(!Array.isArray(r))continue;let[i,s={}]=r;if(!Object.hasOwn(ae,i)){console.warn(`[phlex-reactive] unknown client op ${JSON.stringify(i)} — skipped`);continue}let o=t(s);if(o.length===0&&n)n(i,s);for(let c of o)ae[i](c,s)}}var le=new WeakMap;function qe(e){let t=globalThis.document;if(!t)return!0;let n=le.get(t);if(!n)n=new Set,le.set(t,n);if(n.has(e))return!0;return n.add(e),!1}function I(e,t){try{return e?.querySelectorAll?.(t)?.length??0}catch{return 0}}function $e(e,t,n,r){if(qe(`${e}|${t}|${n}`))return;console.warn(`[phlex-reactive] ${e} matched zero targets for selector "${t}" (${n})${r}`)}function Wt(e,t,n){let r=t.to;if(typeof r!=="string"||r===""||r==="@root")return;let i="";if(n&&!t.global){let s=I(globalThis.document,r);if(s>0)i=` — it matches ${s} element(s) outside the stream's target root; use global: true`}$e(`client op "${e}"`,r,n?`scoped to #${n.id||"?"}`:"document-scoped",i)}function Ht(e,t){let n=e.to;if(t){if(n==="@root")return[t];if(typeof n!=="string"||n==="")return[];if(e.global)return[...document.querySelectorAll(n)];return[...t.querySelectorAll(n)]}if(typeof n!=="string"||n===""||n==="@root")return[];return[...document.querySelectorAll(n)]}class on extends De{static values={token:String};#re;#T=new Map;#m=new Map;#Fe;#j;#ie;#J=0;#p=new Map;#I=new WeakMap;#L=new Map;#se=new WeakSet;#oe=null;#v;#g;#y;#r;#a;#B;#ae;#W;#H;#s;#b;#ce=!1;#V=0;#ue=!1;#o;#A;#w;#_;#S;#i=null;#E=!1;#t=null;#c;#N;#C;connect(){if(L=!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.#le(),this.#_=()=>this.#le(),this.element.addEventListener?.("turbo:morph-element",this.#_);if(this.#i=z(this.element),this.#i)this.#At();if(this.#Me()){if(this.#v=()=>this.#Y(),this.element.addEventListener?.("turbo:morph-element",this.#v),this.#Y(),this.element.getAttribute?.("data-reactive-warn-unsaved")==="true")this.#ut()}if(this.#ft())this.#r=()=>this.#ke(),this.element.addEventListener?.("input",this.#r),this.element.addEventListener?.("change",this.#r),this.element.addEventListener?.("turbo:morph-element",this.#r),this.#ke();if(this.#dt())this.#a=(e)=>this.#X(e),this.#B=()=>this.#X(null),this.element.addEventListener?.("input",this.#a),this.element.addEventListener?.("change",this.#a),this.element.addEventListener?.("turbo:morph-element",this.#B),this.#X(null);if(this.#D())this.#s=(e)=>{if(e?.type==="input"&&!this.#Tt(e))return;this.#k()},this.element.addEventListener?.("input",this.#s),this.element.addEventListener?.("turbo:morph-element",this.#s),this.#k();if(this.#F())this.#b=()=>this.#ee(),this.element.addEventListener?.("turbo:morph-element",this.#b),this.#ee();if(this.#_t())this.#o=(e)=>this.syncNestedJson(e),this.#A=()=>this.#R(),this.element.addEventListener?.("input",this.#o),this.element.addEventListener?.("change",this.#o),this.element.addEventListener?.("turbo:morph-element",this.#A),this.#R();if(this.#kt())this.#w=()=>this.recompute(),this.element.addEventListener?.("turbo:morph-element",this.#w),this.recompute();if(this.#ht())this.#S=()=>this.#xe(),this.element.addEventListener?.("turbo:morph-element",this.#S),this.#xe()}#Me(){if((this.element.getAttribute?.("data-action")??"").includes("reactive#trackDirty"))return!0;let e=this.element.querySelectorAll?.('[data-action*="reactive#trackDirty"]')??[];for(let t of e)if(this.#n(t))return!0;return!1}disconnect(){if(this.#Et(),this.#Ze(),this.#et(),this.#lt(),this.#xt(),this.#vt(),this.#Lt(),this.#Dt(),this.#Ft(),this.#Mt(),this.#mt(),this.#_)this.element.removeEventListener?.("turbo:morph-element",this.#_)}#le(){let e=this.element;if(!e?.id)return;let t=e.getAttribute?.("data-reactive-defer-token");if(!t)return;if(e.getAttribute?.("data-reactive-defer-pending")!=="true")return;T(e.id,t)}dispatch(e){let{action:t,params:n,debounce:r,throttle:i,confirm:s,confirmWhen:o,outside:c,window:a,optimistic:u}=e.params;if(!t)return;let l=e.params.busy??this.#Kt(e.params.loading);if(c&&this.element.contains(e.target))return;let v=e.currentTarget??e.target;if(!a&&!this.#It(u,v))e.preventDefault();let d=this.#U(s,o);if(!d)return this.#ye(v,t,n,r,i,u,l);Promise.resolve().then(()=>_(d,{el:v})).catch(()=>!1).then((p)=>{if(p)this.#ye(v,t,n,r,i,u,l)})}runOps(e){let{ops:t,confirm:n,confirmWhen:r,outside:i,window:s}=e.params,o=e.currentTarget??e.target;if(i&&this.element.contains(e.target))return;if(!s)e.preventDefault();let c=this.#U(n,r);if(!c)return this.#Re(this.#Oe(t));Promise.resolve().then(()=>_(c,{el:o})).catch(()=>!1).then((a)=>{if(a)this.#Re(this.#Oe(t))})}trackDirty(){this.#Y()}recompute(e){if(e&&this.#se.has(e))return;let t=this.#Ve(),n=t.map(([f])=>f),r=this.element.getAttribute?.("data-reactive-scope")||null,i=(f)=>r&&!f.includes("[")?`${r}[${f}]`:f,s=this.#e(),o=new Map,c=(f)=>{if(o.has(f))return o.get(f);let h=null;for(let m of this.element.querySelectorAll(`[name="${i(f)}"]`))if(s(m)){h=m;break}return o.set(f,h),h};for(let f of n)this.#ve(f,c(f)?.value??"");let a=this.element.getAttribute("data-reactive-compute-reducer-param"),u=a?Fe(a):null;if(!u){this.#ge({},c);return}let l=this.#He("data-reactive-compute-outputs-param"),v={};for(let[f,h]of t){let m=c(f);if(h==="string")v[f]=m?.value??"";else{let b=Number(m?.value);v[f]=Number.isFinite(b)?b:0}}let d=u(v,{changed:this.#ze(e,n,r)})||{},p=Bt(d.$ops),A=[];for(let f of l){if(f==="$ops"||!(f in d))continue;let h=c(f);if(!h)continue;if(String(d[f])===h.value)continue;h.value=d[f],A.push(h)}for(let f of Object.keys(d)){if(f==="$ops")continue;let h=d[f];if(h===void 0||h===null)continue;this.#ve(f,h)}this.#ge(d,c);for(let f of A){let h=new Event("input",{bubbles:!0});this.#se.add(h),f.dispatchEvent(h)}this.#Pe(p,Boolean(e))}#Pe(e,t){let n=e===null?null:JSON.stringify(e),r=n!==null&&n!==this.#oe&&t;if(this.#oe=n,!r)return;S(e,(i)=>this.#P(i.to==null?{...i,to:"@root"}:i),(i,s)=>this.#M(`client op "${i}"`,s))}listnavNext(e){this.#fe(e,1)}listnavPrev(e){this.#fe(e,-1)}listnavPick(e){let t=this.#O(e),n=t.findIndex((r)=>r.hasAttribute("data-reactive-highlighted"));if(n<0)return;e.preventDefault(),t[n].click()}listnavClose(e){for(let t of this.#O(e))t.removeAttribute("data-reactive-highlighted")}#fe(e,t){let n=this.#O(e);if(!n.length)return;e.preventDefault();let r=n.findIndex((o)=>o.hasAttribute("data-reactive-highlighted")),i=r<0?t>0?0:n.length-1:(r+t+n.length)%n.length;for(let o of n)o.removeAttribute("data-reactive-highlighted");let s=n[i];s.setAttribute("data-reactive-highlighted","true"),s.scrollIntoView?.({block:"nearest"})}#O(e){let n=(e?.currentTarget??e?.target??this.element).getAttribute?.("data-reactive-listnav-option-param")??this.element.getAttribute("data-reactive-listnav-option-param");if(!n)return[];let r=this.#e();return Array.from(this.element.querySelectorAll(n)).filter((i)=>!i.hidden&&r(i))}tagsAdd(e){if(!this.#F())return;if(e?.defaultPrevented)return;if(this.#O(e).some((r)=>r.hasAttribute?.("data-reactive-highlighted")))return;e?.preventDefault?.();let t=e?.currentTarget??e?.target;if(!t)return;if(!this.#_e(String(t.value??"").split(",")))return;if(t.value="",this.#D())this.#k()}tagsPick(e){if(!this.#F())return;e?.preventDefault?.();let n=(e?.currentTarget??e?.target)?.getAttribute?.("data-reactive-tag-param");if(!n)return;if(!this.#_e([n]))return;let r=this.#Nt();if(!r)return;r.value="",this.#k(),r.focus?.()}tagsRemove(e){if(!this.#F())return;e?.preventDefault?.();let n=(e?.currentTarget??e?.target)?.getAttribute?.("data-reactive-tag-param");if(!n)return;let r=this.#Z();if(!r)return;let i=this.#Q(r),s=i.filter((o)=>o.toLowerCase()!==n.toLowerCase());if(s.length===i.length)return;this.#Ne(r,s)}nestedAdd(e){e?.preventDefault?.();let t=e?.currentTarget??e?.target,n=t?.getAttribute?.("data-reactive-association-param");if(!n)return;if(typeof this.element?.querySelectorAll!=="function")return;let r=this.#e(),i=[...this.element.querySelectorAll(`[data-reactive-nested-list="${n}"]`)].find(r),o=[...this.element.querySelectorAll(`[data-reactive-nested-template="${n}"]`)].find(r)?.content?.firstElementChild;if(!i||!o){this.#$t(n);return}let c=o.cloneNode(!0);this.#qt(c,this.#Rt()),i.appendChild(c);let a=t?.getAttribute?.("data-reactive-nested-from-param"),u=t?.getAttribute?.("data-reactive-nested-clear-param")==="true",l=this.#je(c,a,u);if(a)l?.focus?.();else[...c.querySelectorAll?.("input, select, textarea")??[]][0]?.focus?.();if(i.getAttribute?.("data-reactive-nested-json")===n)this.#he(n)}#je(e,t,n){if(!t)return null;let r;try{r=JSON.parse(t)}catch{return null}if(!r||typeof r!=="object")return null;let i=this.#e(),s=[...e.querySelectorAll?.("input, select, textarea")??[]],o=[];for(let[c,a]of Object.entries(r)){let u=[...this.element.querySelectorAll?.(a)??[]].find(i);if(!u)continue;let l=s.find((v)=>this.#pe(v.getAttribute?.("name"))===c);if(!l)continue;this.#Je(l,u),o.push(u)}if(n)for(let c of o)this.#Ie(c);return o[0]??null}#Je(e,t){if(e.type==="checkbox")e.checked=t.type==="checkbox"?!!t.checked:this.#z(t)!=="";else e.value=this.#z(t);if(typeof e.dispatchEvent==="function")e.dispatchEvent(new Event("input",{bubbles:!0}))}#Ie(e){if(e.type==="checkbox")e.checked=!1;else e.value="";if(typeof e.dispatchEvent==="function")e.dispatchEvent(new Event("input",{bubbles:!0}))}nestedRemove(e){e?.preventDefault?.();let t=e?.currentTarget??e?.target,n=t?.closest?.("[data-reactive-nested-row]");if(!n)return;if(n.closest?.('[data-controller~="reactive"]')!==this.element)return;let r=t?.getAttribute?.("data-reactive-confirm-param"),i=t?.getAttribute?.("data-reactive-confirm-when-param"),s=this.#U(r,i);if(!s)return this.#de(n);let o=this.#me(n),c=this.#Be(s,o);return Promise.resolve().then(()=>_(c,{el:t,row:n,fields:o})).catch(()=>!1).then((a)=>{if(a)this.#de(n)})}#Be(e,t){if(!e.includes("%{"))return e;return e.replace(/%\{(\w+)\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(t,r)?t[r]:n)}#de(e){let t=[...e.querySelectorAll?.('input[name$="[_destroy]"]')??[]][0];if(t){if(t.value="1",typeof t.dispatchEvent==="function")t.dispatchEvent(new Event("input",{bubbles:!0}));e.hidden=!0}else e.parentNode?.removeChild?.(e);this.#R()}syncNestedJson(e){let t=e?.target;if(!t||!this.#n(t))return;this.#R()}#R(){if(typeof this.element?.querySelectorAll!=="function")return;let e=this.#e();for(let t of[...this.element.querySelectorAll("[data-reactive-nested-json]")].filter(e))this.#he(t.getAttribute("data-reactive-nested-json"))}#he(e){let t=this.#e(),n=[...this.element.querySelectorAll(`[data-reactive-nested-list="${e}"]`)].find(t);if(!n)return;let r=this.#We(n);if(!r)return;let i=[];for(let o of[...n.querySelectorAll?.("[data-reactive-nested-row]")??[]]){if(!t(o)||o.hidden)continue;i.push(this.#me(o))}let s=JSON.stringify(i);if(r.value===s)return;if(r.value=s,typeof r.dispatchEvent==="function")r.dispatchEvent(new Event("input",{bubbles:!0}))}#We(e){let t=e.getAttribute?.("data-reactive-nested-json-field");if(!t)return null;let n=this.#e();return[...this.element.querySelectorAll(t)].find(n)??null}#me(e){let t={};for(let n of[...e.querySelectorAll?.("input, select, textarea")??[]]){let r=this.#pe(n.getAttribute?.("name"));if(r===null||r==="_destroy")continue;t[r]=this.#z(n)}return t}#pe(e){if(!e)return null;let t=e.match(/\[([^\][]+)\]$/);return t?t[1]:e}#z(e){if(e.type==="checkbox")return e.checked?e.value||"on":"";return e.value??""}#He(e){let t=this.element.getAttribute(e);if(!t)return[];try{let n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return[]}}#Ve(){let e=this.element.getAttribute("data-reactive-compute-inputs-param");if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return t.map((n)=>[n,"number"]);if(t&&typeof t==="object")return Object.entries(t);return[]}catch{return[]}}#ze(e,t,n){let r=e?.target;if(!r?.name||typeof r.closest!=="function")return null;let i=this.#Ge(r.name,n);if(!t.includes(i))return null;return this.#n(r)?i:null}#Ge(e,t){if(!t)return e;let n=`${t}[`;return e.startsWith(n)&&e.endsWith("]")?e.slice(n.length,-1):e}#ve(e,t){let n=String(t);for(let r of this.#Ke(e)){if(r.textContent===n)continue;r.textContent=n}}#Ke(e){let t=this.element.querySelectorAll(`[data-reactive-text="${e}"]`);return Array.from(t).filter((n)=>this.#n(n))}#ge(e,t){let n=this.#Ue();for(let[r,i]of Object.entries(n)){let s=r in e?e[r]:t(r)?.value;if(s===void 0||s===null)continue;let o=String(s);for(let c of Array.isArray(i)?i:[i]){if(!Ot(c))continue;for(let a of document.querySelectorAll(c)){if(a.textContent===o)continue;a.textContent=o}}}}#Ue(){let e=this.element.getAttribute("data-reactive-compute-mirror-param");if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return{}}}#ye(e,t,n,r,i,s,o){if(this.#x("reactive:before-dispatch",{action:t,params:this.#Ce(n),element:this.element},{cancelable:!0}).defaultPrevented)return;let a=Number(r)||0;if(a>0)return this.#Xe(e,a,t,n,s,o);let u=Number(i)||0;if(u>0)return this.#Qe(e,u,t,n,s,o);return this.#q(t,n,s,e,o)}#q(e,t,n,r,i){let s=this.#Bt(n,r),o=this.#Wt(e,r,i),c=this.#K()?this.#Ye(n,r):null;return this.queue=(this.queue??Promise.resolve()).then(()=>this.#ot(e,t,s,o,c)),this.queue}#Ye(e,t){if(!e?.hide)return null;let n=this.#$e(e,t);if(!n.length)return null;return()=>{let r=n.filter((i)=>i.isConnected&&!i.hidden);if(!r.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.",r)}}#Xe(e,t,n,r,i,s){this.#G(e);let o=()=>{this.#G(e),this.#q(n,r,i,e,s)},c=setTimeout(o,t);e?.addEventListener?.("blur",o,{once:!0}),this.#T.set(e,{timer:c,flush:o})}#G(e){let t=this.#T.get(e);if(!t)return;clearTimeout(t.timer),e?.removeEventListener?.("blur",t.flush),this.#T.delete(e)}#Ze(){for(let e of[...this.#T.keys()])this.#G(e)}#Qe(e,t,n,r,i,s){let o=this.#m.get(e)??new Map;if(o.has(n))return;let c=setTimeout(()=>{if(o.delete(n),o.size===0)this.#m.delete(e)},t);return o.set(n,c),this.#m.set(e,o),this.#q(n,r,i,e,s)}#et(){for(let e of this.#m.values())for(let t of e.values())clearTimeout(t);this.#m.clear()}#x(e,t,{cancelable:n=!1}={}){let r=new CustomEvent(e,{bubbles:!0,composed:!0,cancelable:n,detail:t});return(this.element.isConnected?this.element:document).dispatchEvent(r),r}#u(e,t,n,r){let i=()=>{if(!this.element.isConnected){console.warn("[phlex-reactive] retry() ignored — the reactive root left the DOM");return}return this.#q(e,t)};this.#x("reactive:error",{action:e,params:n,...r,retry:i})}#l(e){if(this.element?.isConnected===!1)return;this.element?.setAttribute?.("data-reactive-error",e)}#tt(){this.element?.removeAttribute?.("data-reactive-error")}#nt(){let e=document.querySelector("[data-reactive-error-flash]");if(!e?.content)return;let t=e.getAttribute("data-reactive-error-flash")||"flash",n=document.getElementById(t);if(!n)return;n.appendChild(e.content.cloneNode(!0))}#rt(){if(typeof sessionStorage>"u")return Promise.resolve();let e=Number(sessionStorage.getItem(H));if(!Number.isFinite(e)||e<=0)return Promise.resolve();if(!x)x=!0,console.warn(`[phlex-reactive] latency simulator ACTIVE — every action is delayed by ${e}ms. Call PhlexReactive.disableLatencySim() (or clear sessionStorage) to turn it off.`);return new Promise((t)=>setTimeout(t,e))}#K(){return this.element?.getAttribute?.("data-reactive-debug")==="true"}#be(){return typeof performance<"u"&&typeof performance.now==="function"?performance.now():Date.now()}#it(e){if(!e)return[];let t=[],n=/<turbo-stream\b([^>]*)>/g,r;while((r=n.exec(e))!==null){let i=r[1],s=i.match(/\baction="([^"]*)"/)?.[1]??"?",o=i.match(/\btarget="([^"]*)"/)?.[1];t.push(o?`${s} → #${o}`:s)}return t}#st(e){let{action:t,status:n,ms:r}=e,s=`reactive ${this.element?.id?`#${this.element.id} `:""}${t} → ${n??"—"} (${Math.round(r)}ms)`;if(console.groupCollapsed(s),console.log(`params: [${e.paramNames.join(", ")}] + collected: [${e.fieldNames.join(", ")}]`),console.log(`encoding: ${e.encoding}`),e.streams.length)console.log(`streams: ${e.streams.join(" ")}`);console.log(`token: ${e.tokenRefreshed?"refreshed ✓":"unchanged"}`),console.groupEnd()}async#ot(e,t,n,r,i){let{fields:s,files:o}=this.#Se(),c=this.#Ce(t),a={...s,...c},u=this.#f,l=o.length>0,v=l?this.#Pt(u,e,a,o):JSON.stringify({token:u,act:e,params:a}),d=this.#K()?{action:e,paramNames:Object.keys(c),fieldNames:Object.keys(s),encoding:l?"multipart":"json",status:null,streams:[],tokenRefreshed:!1,started:this.#be()}:null;await this.#rt();try{if(navigator.onLine===!1){this.#d(n),this.#l("offline"),this.#u(e,t,a,{kind:"offline"});return}let p;try{let m={Accept:"text/vnd.turbo-stream.html","X-CSRF-Token":this.#Xt()};if(!l)m["Content-Type"]="application/json";let b=this.#Zt();if(b)m["X-Pgbus-Connection"]=b;p=await fetch(this.#Ut(),{method:"POST",headers:m,body:v,credentials:"same-origin",signal:AbortSignal.timeout(this.#Yt())})}catch(m){if(console.error("[phlex-reactive] action error",m),this.#d(n),m?.name==="TimeoutError"||m?.name==="AbortError"){this.#l("timeout"),this.#u(e,t,a,{kind:"timeout"});return}this.#nt(),this.#l("network"),this.#u(e,t,a,{kind:"network"});return}if(d)d.status=p.status;if(p.redirected){console.error("[phlex-reactive] action was redirected (auth/CSRF?) — no update applied"),this.#d(n),this.#l("redirected"),this.#u(e,t,a,{kind:"redirected",status:p.status});return}if(!p.ok){let m=await p.text();if(console.error(`[phlex-reactive] action failed: HTTP ${p.status}`,m),this.#d(n),(p.headers.get("Content-Type")||"").includes("turbo-stream")){let b=this.#we(m);if(this.#f=b??this.#f,d)this.#Ae(d,m,b);window.Turbo.renderStreamMessage(m)}this.#l("http"),this.#u(e,t,a,{kind:"http",status:p.status,body:m});return}let A=p.headers.get("Content-Type")||"";if(!A.includes("turbo-stream")){console.error(`[phlex-reactive] expected a turbo-stream, got "${A}" — no update applied`),this.#d(n),this.#l("content-type"),this.#u(e,t,a,{kind:"content-type",status:p.status});return}let f=await p.text(),h=this.#we(f);if(this.#f=h??this.#f,d)this.#Ae(d,f,h);if(window.Turbo.renderStreamMessage(f),i)queueMicrotask(i);this.#tt(),this.#x("reactive:applied",{action:e,params:a,html:f})}catch(p){console.error("[phlex-reactive] action error",p),this.#d(n),this.#x("reactive:error",{action:e,params:a,kind:"apply"})}finally{if(r?.(),d)this.#st({...d,ms:this.#be()-d.started})}}#Ae(e,t,n){e.streams=this.#it(t),e.tokenRefreshed=n!=null}get#f(){return this.#re??this.tokenValue}set#f(e){this.#re=e}#we(e){let t=this.element.id;if(!t)return e.match(/data-reactive-token-value="([^"]+)"/)?.[1];let{token:n,self:r}=this.#at(t),i=e.match(n);if(i)return i[1];let s=e.match(r);if(s)return s[1].match(/data-reactive-token-value="([^"]+)"/)?.[1];return}#at(e){let t=this.#ie;if(t&&t.id===e)return t;let n=ft(e);return this.#ie={id:e,token:new RegExp(`<turbo-stream\\b[^>]*\\baction="reactive:token"[^>]*\\btarget="${n}"[^>]*\\bdata-reactive-token-value="([^"]+)"`),self:new RegExp(`<turbo-stream\\b[^>]*\\baction="(?:replace|update)"[^>]*\\btarget="${n}"[^>]*>([\\s\\S]*?)</turbo-stream>`)}}#n(e){return e.closest('[data-controller~="reactive"]')===this.element}#e(){if(this.element.querySelectorAll('[data-controller~="reactive"]').length===0)return()=>!0;return(t)=>this.#n(t)}#U(e,t){if(e)return e;if(!t)return null;let n=t;if(typeof t==="string")try{n=JSON.parse(t)}catch{return console.warn(`[phlex-reactive] malformed conditional confirm payload ${JSON.stringify(t)} — skipped`),null}if(!n||typeof n!=="object")return null;let{fields:r}=this.#Se(),i=(o)=>r[o],s;if(typeof n.predicate==="string"){let o=Me(n.predicate);if(!o)return console.warn(`[phlex-reactive] confirm predicate "${n.predicate}" is not registered — proceeding without a dialog (register it with setConfirmPredicate)`),null;s=!!o(r)}else s=w(n.groups?.any,i)===!0;return s?n.message:null}#Se(){let e={},t=[],n=this.#e();return this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach((r)=>{if(!n(r))return;if(r.type==="file")for(let i of r.files??[])t.push({name:r.name,file:i,multiple:r.multiple});else if(r.type==="checkbox")e[r.name]=r.checked;else if(r.type==="radio"){if(r.checked)e[r.name]=r.value}else e[r.name]=r.value}),this.element.querySelectorAll("[name]:is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])").forEach((r)=>{if(!n(r))return;let i=r.getAttribute("name");if(!i)return;let s=e[i];if(s==null||s==="")e[i]=r.value??r.textContent??r.innerHTML??""}),{fields:e,files:t}}#Y(){if(typeof this.element?.querySelectorAll!=="function")return;let e=0;if(this.element.querySelectorAll("input[name], select[name], textarea[name]").forEach((t)=>{if(!this.#n(t))return;if(t.type==="file")return;if(this.#ct(t))t.setAttribute("data-reactive-dirty","true"),e++;else t.removeAttribute("data-reactive-dirty")}),e>0)this.element.setAttribute("data-reactive-dirty",String(e));else this.element.removeAttribute("data-reactive-dirty")}#ct(e){if(e.type==="checkbox"||e.type==="radio")return e.checked!==e.defaultChecked;if(e.tag==="select"||e.options)return Array.from(e.options??[]).some((t)=>t.selected!==t.defaultSelected);return e.value!==e.defaultValue}#Ee(){let e=this.element.getAttribute?.("data-reactive-dirty"),t=Number(e);return Number.isFinite(t)&&t>0?t:0}#ut(){if(typeof window>"u"||typeof window.addEventListener!=="function")return;this.#g=(e)=>{if(this.#Ee()===0)return;return e.preventDefault(),e.returnValue="You have unsaved changes.",e.returnValue},this.#y=(e)=>{if(this.#Ee()===0)return;if(!(typeof window.confirm==="function"?window.confirm("You have unsaved changes. Leave anyway?"):!0))e.preventDefault?.()},window.addEventListener("beforeunload",this.#g),window.addEventListener("turbo:before-visit",this.#y)}#lt(){if(this.#v)this.element.removeEventListener?.("turbo:morph-element",this.#v),this.#v=void 0;if(typeof window<"u"&&typeof window.removeEventListener==="function"){if(this.#g)window.removeEventListener("beforeunload",this.#g);if(this.#y)window.removeEventListener("turbo:before-visit",this.#y)}this.#g=void 0,this.#y=void 0}#ft(){if(this.element.getAttribute?.("data-reactive-show-targets"))return!0;let e=this.element.querySelectorAll?.(ce)??[];for(let t of e)if(this.#n(t))return!0;return!1}#dt(){return!!this.element.getAttribute?.("data-reactive-on-complete")}#ht(){if(this.element.getAttribute?.("data-reactive-clipboard"))return!0;let e=this.element.querySelectorAll?.("[data-reactive-clipboard]")??[];for(let t of e)if(this.#n(t))return!0;return!1}#xe(){let e=typeof globalThis.navigator?.clipboard?.readText==="function";if(this.element.getAttribute?.("data-reactive-clipboard"))this.element.hidden=!e;for(let t of this.element.querySelectorAll?.("[data-reactive-clipboard]")??[])if(this.#n(t))t.hidden=!e}#mt(){if(!this.#S)return;this.element.removeEventListener?.("turbo:morph-element",this.#S),this.#S=void 0}#pt(){let e=this.element.getAttribute?.("data-reactive-on-complete")??null;if(e!==this.#ae)this.#ae=e,this.#W=e==null?[]:Ft(e),this.#H=this.#W.map(()=>!1);return this.#W}#X(e){let t=this.#pt();if(!t.length)return;let n=this.#e(),r=this.element.getAttribute?.("data-reactive-scope")||null,i=new Map,s=(o)=>{if(!i.has(o))i.set(o,this.#Le(o,n,r));return i.get(o)};t.forEach((o,c)=>{let a=w(o.any,s);if(a===null)return;let u=a&&!this.#H[c]&&Boolean(e);if(this.#H[c]=a,u)S(o.ops,(l)=>this.#P(l.to==null?{...l,to:"@root"}:l),(l,v)=>this.#M(`client op "${l}"`,v))})}#vt(){if(!this.#a)return;this.element.removeEventListener?.("input",this.#a),this.element.removeEventListener?.("change",this.#a),this.element.removeEventListener?.("turbo:morph-element",this.#B)}#ke(){if(typeof this.element?.querySelectorAll!=="function")return;let e=this.#e(),t=this.element.getAttribute?.("data-reactive-scope")||null,n=new Map,r=(i)=>{if(!n.has(i))n.set(i,this.#Le(i,e,t));return n.get(i)};for(let i of this.element.querySelectorAll(ce)){if(!e(i))continue;let s=i.getAttribute("data-reactive-show");if(s!==null){let u=Pt(Dt(s),r);if(u!==null)this.#Te(i,u,e,t);continue}let o=i.getAttribute("data-reactive-show-field");if(!o)continue;let c=r(o);if(c===null)continue;let a=Rt(i,c);if(a===null)continue;this.#Te(i,a,e,t)}this.#gt(r)}#Te(e,t,n,r){if(e.hidden=!t,e.getAttribute("data-reactive-show-disable")!=="true")return;if(typeof e.querySelectorAll!=="function")return;for(let i of e.querySelectorAll("input[name], select[name], textarea[name]"))if(n(i))i.disabled=!t;if(e.name&&n(e))e.disabled=!t}#gt(e){let t=this.#bt();for(let[n,r]of Object.entries(t)){if(n.startsWith("#")){this.#yt(n,r,e);continue}if(!r||typeof r!=="object"||Array.isArray(r))continue;let i=e(n);if(i===null)continue;let s=()=>i;for(let[o,c]of Object.entries(r)){if(!ue(o))continue;let a;if(Array.isArray(c)){if(c.length===0){console.warn(`[phlex-reactive] malformed reactive_show_targets group for ${o} — skipped`);continue}a=c.every((u)=>Q(u,s))}else{let u=Oe(c,i);if(u===null){console.warn(`[phlex-reactive] malformed reactive_show_targets predicate for ${o} — skipped`);continue}a=u}for(let u of document.querySelectorAll(o))u.hidden=!a}}}#yt(e,t,n){if(!ue(e))return;let r=t&&typeof t==="object"&&!Array.isArray(t)?t.any:null,i=Mt(r);if(i===null){console.warn(`[phlex-reactive] malformed reactive_show_targets conditions for ${e} — skipped`);return}if(i.every((o)=>n(o)===null))return;let s=w(r,n);if(s===null)return;for(let o of document.querySelectorAll(e))o.hidden=!s}#bt(){let e=this.element.getAttribute?.("data-reactive-show-targets");if(!e)return{};try{let t=JSON.parse(e);if(t&&typeof t==="object"&&!Array.isArray(t))return t}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: { ... })"),{}}#Le(e,t,n){let r=n&&!e.includes("[")?`${n}[${e}]`:e,i=!1,s=null;for(let o of this.element.querySelectorAll(`[name="${r}"]`)){if(!t(o))continue;if(o.type==="checkbox")return o.checked?"true":"false";if(o.type==="radio"){if(o.checked)return o.value??"";i=!0;continue}s??=o}if(s)return s.value??"";return i?"":null}#At(){let e=this.#i;this.#E=!1;let t=J(this.element,e);if(t){if(kt(this.element,e,t.fields),t.state)this.element.setAttribute?.(V,JSON.stringify(t.state));this.#x("reactive:persist-restored",{key:e.key,fields:t.fields,state:t.state??{}})}this.#E=!0,this.#c=()=>this.#wt(),this.#N=()=>this.#$(),this.#C=(n)=>this.#St(n),this.element.addEventListener?.("input",this.#c),this.element.addEventListener?.("change",this.#N);for(let n of re)this.element.addEventListener?.(n,this.#c);document.addEventListener?.("turbo:submit-end",this.#C)}#wt(){if(!this.#E)return;let e=Number(this.#i?.debounce)||0;if(e<=0)return this.#$();if(this.#t!==null)clearTimeout(this.#t);this.#t=setTimeout(()=>{this.#t=null,this.#$()},e)}#$(){if(!this.#E||!this.#i)return;if(this.#t!==null)clearTimeout(this.#t),this.#t=null;let e=this.#i,t=J(this.element,e);xe(this.element,e,{fields:Te(this.element,e),state:t?.state??null})}#St(e){if(!e?.detail?.success)return;let t=e.target;if(t?.tagName!=="FORM"||typeof t.contains!=="function")return;if(!t.contains(this.element))return;if(this.#t!==null)clearTimeout(this.#t),this.#t=null;Y(this.element,this.#i)}#Et(){if(!this.#i)return;if(this.#t!==null)this.#$();this.element.removeEventListener?.("input",this.#c),this.element.removeEventListener?.("change",this.#N);for(let e of re)this.element.removeEventListener?.(e,this.#c);document.removeEventListener?.("turbo:submit-end",this.#C),this.#c=this.#N=this.#C=void 0,this.#i=null,this.#E=!1}#xt(){if(!this.#r)return;this.element.removeEventListener?.("input",this.#r),this.element.removeEventListener?.("change",this.#r),this.element.removeEventListener?.("turbo:morph-element",this.#r),this.#r=void 0}#D(){return!!(this.element.getAttribute?.("data-reactive-filter-input")&&this.element.getAttribute?.("data-reactive-filter-option"))}#kt(){return this.element.getAttribute?.("data-reactive-compute-seed")==="true"}#Tt(e){let t=this.element.getAttribute("data-reactive-filter-input");return!!t&&typeof e.target?.matches==="function"&&e.target.matches(t)}#k(){if(typeof this.element?.querySelectorAll!=="function")return;let e=this.element.getAttribute("data-reactive-filter-input"),t=this.element.getAttribute("data-reactive-filter-option");if(!e||!t)return;let n=this.#e(),r=[...this.element.querySelectorAll(e)].find(n);if(!r)return;let i=(r.value??"").trim().toLowerCase(),s=0;for(let a of this.element.querySelectorAll(t)){if(!n(a))continue;let u=(a.getAttribute("data-reactive-filter-text")??a.textContent??"").toLowerCase(),l=a.hasAttribute?.("data-reactive-tags-selected")||i!==""&&!u.includes(i);if(a.hidden=l,l)a.removeAttribute("data-reactive-highlighted");else s++}let o=this.element.getAttribute("data-reactive-filter-group");if(o)for(let a of this.element.querySelectorAll(o)){if(!n(a))continue;let u=[...a.querySelectorAll(t)].filter(n);if(u.length===0)continue;a.hidden=u.every((l)=>l.hidden)}let c=this.element.getAttribute("data-reactive-filter-empty");if(c){for(let a of this.element.querySelectorAll(c))if(n(a))a.hidden=s>0}}#Lt(){if(!this.#s)return;this.element.removeEventListener?.("input",this.#s),this.element.removeEventListener?.("turbo:morph-element",this.#s),this.#s=void 0}#F(){return!!this.element.getAttribute?.("data-reactive-tags-field")}#_t(){if(typeof this.element?.querySelector!=="function")return!1;return!!this.element.querySelector("[data-reactive-nested-json]")}#Z(){if(typeof this.element?.querySelectorAll!=="function")return null;let e=this.element.getAttribute("data-reactive-tags-field");if(!e)return null;let t=this.#e();return[...this.element.querySelectorAll(e)].find(t)??null}#Q(e){let t=new Set,n=[];for(let r of String(e.value??"").split(",")){let i=r.trim();if(i===""||t.has(i.toLowerCase()))continue;t.add(i.toLowerCase()),n.push(i)}return n}#_e(e){let t=this.#Z();if(!t)return!1;let n=this.#Q(t),r=new Set(n.map((s)=>s.toLowerCase())),i=!1;for(let s of e){let o=String(s??"").trim();if(o===""||r.has(o.toLowerCase()))continue;r.add(o.toLowerCase()),n.push(o),i=!0}if(i)this.#Ne(t,n);return i}#Ne(e,t){if(e.value=t.join(","),typeof e.dispatchEvent==="function")e.dispatchEvent(new Event("input",{bubbles:!0}));this.#ee()}#Nt(){if(typeof this.element?.querySelectorAll!=="function")return null;let e=this.element.getAttribute("data-reactive-filter-input");if(!e)return null;let t=this.#e();return[...this.element.querySelectorAll(e)].find(t)??null}#ee(){let e=this.#Z();if(!e)return;let t=this.#Q(e),n=this.#e();this.#Ct(t,n),this.#Ot(t,n)}#Ct(e,t){let n=[...this.element.querySelectorAll("[data-reactive-tags-list]")].find(t);if(!n)return;let i=[...this.element.querySelectorAll("[data-reactive-tags-template]")].find(t)?.content?.firstElementChild;if(!i){if(!this.#ce)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.#ce=!0;return}while(n.firstChild)n.removeChild(n.firstChild);for(let s of e){let o=i.cloneNode(!0);o.setAttribute?.("data-reactive-tag",s);let c=o.matches?.("[data-reactive-tag-text]")?o:(o.querySelectorAll?.("[data-reactive-tag-text]")??[])[0];if(c)c.textContent=s;let a=[...o.querySelectorAll?.('[data-action*="reactive#tagsRemove"]')??[]];if(o.matches?.('[data-action*="reactive#tagsRemove"]'))a.push(o);for(let u of a)u.setAttribute?.("data-reactive-tag-param",s);n.appendChild(o)}}#Ot(e,t){let n=new Set(e.map((r)=>r.toLowerCase()));for(let r of this.element.querySelectorAll("[role=option]")){if(!t(r))continue;let i=r.getAttribute?.("data-reactive-tag-param");if(!i)continue;if(n.has(i.toLowerCase()))r.setAttribute("data-reactive-tags-selected","true"),r.hidden=!0,r.removeAttribute?.("data-reactive-highlighted");else if(r.hasAttribute?.("data-reactive-tags-selected")){if(r.removeAttribute("data-reactive-tags-selected"),!this.#D())r.hidden=!1}}if(this.#D())this.#k()}#Rt(){return this.#V=Math.max(this.#V+1,Date.now()),this.#V}#qt(e,t){let n=[e,...e.querySelectorAll?.("*")??[]];for(let r of n)for(let i of["name","id","for"]){let s=r.getAttribute?.(i);if(s&&s.includes("NEW_ROW"))r.setAttribute?.(i,s.replaceAll("NEW_ROW",String(t)))}}#$t(e){if(this.#ue)return;console.warn(`[phlex-reactive] nested rows: no owned [data-reactive-nested-list="${e}"] container + <template data-reactive-nested-template="${e}"> pair found in this root — the add `+"trigger did nothing. Render both inside the same reactive root (reactive_nested_list / reactive_nested_template)."),this.#ue=!0}#Dt(){if(!this.#b)return;this.element.removeEventListener?.("turbo:morph-element",this.#b),this.#b=void 0}#Ft(){if(this.#o)this.element.removeEventListener?.("input",this.#o),this.element.removeEventListener?.("change",this.#o),this.#o=void 0;if(this.#A)this.element.removeEventListener?.("turbo:morph-element",this.#A),this.#A=void 0}#Mt(){if(!this.#w)return;this.element.removeEventListener?.("turbo:morph-element",this.#w),this.#w=void 0}#Pt(e,t,n,r){let i=new FormData;i.append("token",e),i.append("act",t);for(let[o,c]of Object.entries(n))this.#ne(i,this.#te(o),c);let s=this.#jt(r);for(let{name:o,file:c,multiple:a}of r){let l=a||s.has(o)?`${this.#te(o)}[]`:this.#te(o);i.append(l,c,c.name)}return i}#te(e){let t=String(e),n=t.indexOf("[");if(n===-1)return`params[${t}]`;return`params${[t.slice(0,n),...t.slice(n).match(/[^\[\]]+/g)??[]].map((i)=>`[${i}]`).join("")}`}#ne(e,t,n){if(n==null)e.append(t,"");else if(Array.isArray(n))n.forEach((r,i)=>this.#ne(e,`${t}[${i}]`,r));else if(typeof n==="object")for(let[r,i]of Object.entries(n))this.#ne(e,`${t}[${r}]`,i);else e.append(t,String(n))}#jt(e){let t=new Map;for(let{name:n}of e)t.set(n,(t.get(n)??0)+1);return new Set([...t].filter(([,n])=>n>1).map(([n])=>n))}#Ce(e){if(!e)return{};try{return typeof e==="string"?JSON.parse(e):e}catch{return{}}}#Oe(e){return Re(e)}#Re(e){S(e,(t)=>this.#P(t),(t,n)=>this.#M(`client op "${t}"`,n))}#Jt(){return this.element?.getAttribute?.("data-reactive-verbose")==="true"||this.#K()}#M(e,t){if(!this.#Jt())return;let n=t.to;if(typeof n!=="string"||n===""||n==="@root")return;let r="";if(!t.global)if(this.element?.matches?.(n))r=" — the selector matches this component's own root, which root-scoped resolution never includes; use to: :root";else if(I(this.element,n)>0)r=" — it matches only inside a nested reactive root (excluded by ownership scoping); use global: true";else{let i=I(globalThis.document,n);if(i>0)r=` — it matches ${i} element(s) outside this scope; use global: true`}$e(e,n,`scoped to #${this.element?.id||"?"}`,r)}#P(e){let t=e.to;if(t==="@root")return[this.element];if(typeof t!=="string"||t==="")return[];if(e.global)return[...document.querySelectorAll(t)];return[...this.element.querySelectorAll(t)].filter((n)=>this.#n(n))}#It(e,t){if(e?.checked!=="keep")return!1;let n=t?.type;return n==="checkbox"||n==="radio"}#Bt(e,t){if(!e)return null;let n=this.#qe(e,t,!0);return n.length?n:null}#d(e){if(!e)return;if(!this.element.isConnected)return;for(let t of e)t()}#Wt(e,t,n){this.#Vt(e,t);let r=n?this.#qe(n,t,!1):[];Ae();let i=!1;return()=>{if(i)return;i=!0,this.#zt(e,t),we();for(let s of r)s()}}#qe(e,t,n){let r=[];for(let i of this.#$e(e,t)){if(e.add_class){let s=e.add_class.filter((o)=>!i.classList.contains(o));if(i.classList.add(...s),s.length)r.push(()=>i.classList.remove(...s))}if(e.remove_class){let s=e.remove_class.filter((o)=>i.classList.contains(o));if(i.classList.remove(...s),s.length)r.push(()=>i.classList.add(...s))}if(e.toggle_class)e.toggle_class.forEach((s)=>i.classList.toggle(s)),r.push(()=>e.toggle_class.forEach((s)=>i.classList.toggle(s)));if(e.hide)i.hidden=!0,r.push(()=>i.hidden=!1);if(e.show)i.hidden=!1,r.push(()=>i.hidden=!0)}if(t&&(e.disable||e.text!=null))r.push(this.#Ht(e,t));if(n&&e.checked==="keep"&&t&&"checked"in t){let i=t.checked;r.push(()=>t.checked=!i)}return r}#$e(e,t){if(e.to==null)return t?[t]:[];let n=this.#P({to:e.to});if(n.length===0)this.#M("busy/optimistic hint",{to:e.to});return n}#Ht(e,t){let n=this.#L.get(t);if(n)n.count++;else this.#L.set(t,{count:1,disabled:t.disabled,html:t.innerHTML,hadText:e.text!=null,swappedTo:e.text});if(e.disable)t.disabled=!0;if(e.text!=null)t.innerHTML=e.text;return()=>this.#Gt(t,e)}#Vt(e,t){if(this.#h(t,e,1),this.#h(this.element,e,1),this.#p.set(e,(this.#p.get(e)??0)+1),this.#J++===0)this.element.setAttribute("aria-busy","true");for(let n of this.#De(e))this.#h(n,e,1)}#zt(e,t){this.#h(t,e,-1),this.#h(this.element,e,-1);let n=(this.#p.get(e)??1)-1;if(n<=0)this.#p.delete(e);else this.#p.set(e,n);if(--this.#J<=0)this.#J=0,this.element.removeAttribute("aria-busy");for(let r of this.#De(e))this.#h(r,e,-1)}#h(e,t,n){if(!e||typeof e.getAttribute!=="function")return;let r=this.#I.get(e)??new Map,i=(r.get(t)??0)+n;if(i<=0)r.delete(t);else r.set(t,i);if(r.size===0){this.#I.delete(e),e.removeAttribute("data-reactive-busy");return}this.#I.set(e,r),e.setAttribute("data-reactive-busy",[...r.keys()].join(" "))}#De(e){return[...this.element.querySelectorAll?.("[data-reactive-busy-on]")??[]].filter((n)=>n.getAttribute("data-reactive-busy-on")===e&&this.#n(n))}#Gt(e,t){let n=this.#L.get(e);if(!n)return;if(--n.count>0)return;if(this.#L.delete(e),!e.isConnected)return;if(t.disable)e.disabled=n.disabled;if(n.hadText&&e.innerHTML===n.swappedTo)e.innerHTML=n.html}#Kt(e){if(!e||typeof e!=="object")return null;let{class:t,...n}=e;return t==null?e:{...n,add_class:t}}#Ut(){return this.#Fe??=document.querySelector('meta[name="phlex-reactive-action-path"]')?.content||"/reactive/actions"}#Yt(){if(this.#j!=null)return this.#j;let e=document.querySelector('meta[name="phlex-reactive-timeout"]')?.content,t=Number(e);return this.#j=Number.isFinite(t)&&t>0?t:30000}#Xt(){return document.querySelector('meta[name="csrf-token"]')?.content??""}#Zt(){return document.querySelector("pgbus-stream-source[connection-id]")?.getAttribute("connection-id")||document.querySelector('meta[name="pgbus-connection-id"]')?.content||null}}export{be as ACTIVE_ATTR,H as LATENCY_KEY,sn as __markReactiveConnectedForTest,Xt as __resetReactiveDismissForTest,Zt as __resetReactiveEffectsForTest,en as __resetReactiveLatencyForTest,Qt as __resetReactiveOfflineForTest,rn as __resetReactiveRegistrationForTest,dt as checkReactiveRegistration,on as default,ut as disableLatencySim,ct as enableLatencySim,Ae as enterReactiveActivity,ft as escapeRegExp,we as exitReactiveActivity,Yt as pendingDeferVia,tn as reactiveActivityCount,ne as registerReactiveActions,Ie as registerReactiveDefer,Ke as registerReactiveDismiss,Xe as registerReactiveEffects,Je as registerReactiveJs,at as registerReactiveOffline,je as registerReactiveToken,Pe as registerReactiveVisit,nn as resetReactiveActivity,Ut as resetReactiveDefers};
2
2
 
3
- //# debugId=48A0C1884C683EB564756E2164756E21
3
+ //# debugId=F00902BE4CBCB94A64756E2164756E21
4
4
  //# sourceMappingURL=reactive_controller.min.js.map