phlex-reactive 0.16.2 → 0.16.3

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.
@@ -3,7 +3,7 @@
3
3
  "sources": ["runtime.js", "features/bindings.js", "features/compute.js", "features/persist.js", "features/form.js", "features/effects.js", "features/devtools.js", "features/hints.js", "features/defer.js", "features/sortable.js", "features/drag.js", "features/presence.js", "features/countdown.js", "reactive_controller.js"],
4
4
  "sourcesContent": [
5
5
  "import { Controller } from \"@hotwired/stimulus\"\n// Import the BARE specifier the engine already pins (phlex/reactive/confirm),\n// NOT a relative \"./confirm.js\" (issue #57). Under importmap-rails + Propshaft\n// the controller is served at its DIGESTED url; a relative sibling import is\n// left untouched (Propshaft rewrites only RAILS_ASSET_URL(...), and the import\n// map resolves ONLY bare specifiers), so \"./confirm.js\" resolves against the\n// digested controller url → an undigested /assets/.../confirm.js that 404s, and\n// the throwing import takes down every Stimulus controller on the page. The\n// bare specifier resolves to the digested asset through the import map, and\n// bundlers/bun resolve it the same way they already resolve\n// \"phlex/reactive/reactive_controller\" (see tsconfig.json paths for the tests).\nimport { confirmResolver } from \"phlex/reactive/confirm\"\n// The feature modules, imported STATICALLY (issue #305). Only the default\n// entry uses these: there `__SPLIT__` is false (scripts/build_client.js\n// defines it), every reference below sits in a `__SPLIT__ ? … : …` branch the\n// minifier keeps, and the features end up in the same file as the runtime,\n// called directly. The opt-in entry (core) is built with `__SPLIT__` true:\n// those branches fold away, and its build resolves these five imports to an\n// empty module, so core.min.js imports no feature until a root needs one.\n//\n// THE ORDER BELOW IS THE DEFAULT BUNDLE'S LAYOUT, not the connect order (that\n// is #connectFeaturesNow's, persist first). The bundler lays the features out\n// in import order, ahead of this file's own code, and gzip only matches text\n// within 32 KB: a feature that repeats what the runtime also says (defer's\n// fetch headers and meta reads, persist's editor selector, form's dirty\n// marker) compresses against it only when it sits close to the runtime. This\n// order was the smallest of a swap search over all of them (issue #310):\n// ~450 B gzipped less than the table order. None of the features runs\n// anything at import time, so the order changes bytes, never behaviour.\nimport * as bindingsFeature from \"phlex/reactive/features/bindings\"\nimport * as computeFeature from \"phlex/reactive/features/compute\"\nimport * as persistFeature from \"phlex/reactive/features/persist\"\nimport * as formFeature from \"phlex/reactive/features/form\"\nimport * as effectsFeature from \"phlex/reactive/features/effects\"\nimport * as devtoolsFeature from \"phlex/reactive/features/devtools\"\nimport * as hintsFeature from \"phlex/reactive/features/hints\"\nimport * as deferFeature from \"phlex/reactive/features/defer\"\nimport * as sortableFeature from \"phlex/reactive/features/sortable\"\nimport * as dragFeature from \"phlex/reactive/features/drag\"\nimport * as presenceFeature from \"phlex/reactive/features/presence\"\nimport * as countdownFeature from \"phlex/reactive/features/countdown\"\n\n// phlex/reactive/runtime — the reactive controller WITHOUT its feature\n// modules (issue #275): the code both client entries share. It is not an\n// entry itself and is never pinned; each entry is built with this file inside\n// it. An app reaches it one of two ways, never both:\n//\n// phlex/reactive/reactive_controller the default: this runtime bundled with\n// every feature in one file, built with\n// __SPLIT__ false (issue #305): the\n// features are imported statically and\n// called directly, and connect inside\n// connect(). It has no table and NO way\n// to import one.\n// phlex/reactive/core opt-in: this runtime plus the table of\n// import() calls (core.js). A feature is\n// imported the first time a root on the\n// page needs it (see \"Feature modules\").\n//\n// The ONE generic controller behind every reactive Phlex component. It\n// replaces the per-feature Stimulus controllers you'd otherwise hand-write\n// for interactive components. A component declares its actions in Ruby (via\n// Phlex::Reactive::Component); this controller binds DOM events to a single\n// HTTP round trip and lets Turbo apply the re-rendered component back in\n// (replace by default; method=\"morph\" — Response.morph — preserves focus).\n//\n// Wire format (client -> server), POST <action path>, turbo-stream Accept:\n// { token: \"<signed identity>\", act: \"<action>\", params: {...} } (JSON)\n// (`act`, not `action`: `action` is a reserved Rails routing param.)\n// The token is a MessageVerifier-signed { component, gid } — NO state is sent.\n// When the root holds a chosen <input type=\"file\">, the SAME payload is sent as\n// multipart FormData instead (token/act flat, params bracketed, files appended)\n// so an upload reaches the action (issue #34) — only the encoding differs.\n// The response is a <turbo-stream> that replaces the component by its id.\n//\n// Server -> client live updates use the SAME element id, pushed over the\n// stream transport (pgbus SSE / Action Cable) via the Streamable\n// .broadcast_* methods — so a click and a background broadcast converge on\n// one re-render unit.\n//\n// Custom turbo-stream action: the server tells the actor to full-navigate\n// (e.g. the record's slug changed and the current URL is now dead). It rides a\n// 200 turbo-stream — NOT an HTTP 3xx — so it never trips the response.redirected\n// bail below (which still correctly catches real auth/CSRF redirects). Registered\n// once on the Turbo global (no @hotwired/turbo import — the gem uses window.Turbo\n// everywhere, and a named import is unreliable under importmap/esbuild).\nexport function registerReactiveVisit() {\n const actions = window.Turbo?.StreamActions\n if (!actions || actions[\"reactive:visit\"]) return\n actions[\"reactive:visit\"] = function () {\n const url = this.getAttribute(\"data-url\")\n if (url) window.Turbo.visit(url, { action: \"advance\" })\n }\n}\n\n// Custom turbo-stream action: a TOKEN-ONLY refresh (issue #30). A partial\n// update (Response.streams / reply.streams) re-renders only PART of a component\n// — so there's no full-self replace to carry the next signed token. The server\n// instead emits `<turbo-stream action=\"reactive:token\" target=\"<id>\"\n// data-reactive-token-value=\"<fresh>\">`. #perform's #extractToken already reads\n// the token out of the response body for the NEXT queued request; this handler\n// keeps the DOM in sync too, writing the attribute onto the root element so the\n// `tokenValue` fallback stays fresh. It's a pure attribute set — no node is\n// replaced — so a focused <input> + caret survive (the whole point: update a\n// total cell without tearing down the field the user is typing in).\nexport function registerReactiveToken() {\n const actions = window.Turbo?.StreamActions\n if (!actions || actions[\"reactive:token\"]) return\n actions[\"reactive:token\"] = function () {\n const token = this.getAttribute(\"data-reactive-token-value\")\n const target = this.getAttribute(\"target\")\n if (!token || !target) return\n const el = document.getElementById(target)\n // Stimulus reads the token via the `token` value -> data-reactive-token-value.\n if (el) el.setAttribute(\"data-reactive-token-value\", token)\n }\n}\n\n// Custom turbo-stream action: SERVER-PUSHED client DOM ops (issue #97). The\n// server-side sibling of on_client's runOps — a reply (reply.<verb>.js(ops)) or\n// a broadcast (Streamable.broadcast_js_to) emits\n//\n// <turbo-stream action=\"reactive:js\" target=\"<optional root id>\"\n// data-reactive-ops=\"[[op, args], ...]\"></turbo-stream>\n//\n// and Turbo invokes this handler with `this` bound to that <turbo-stream>\n// element. It runs the ops through the SAME frozen CLIENT_OPS whitelist as\n// runOps (client-side default-deny — an unknown op warns + is skipped), so a\n// forged/stale ops attr can never break the page or execute anything off the\n// vocabulary. NO token, NO fetch — a pure local DOM mutation.\n//\n// `target` (optional, an element id) scopes op resolution to that root: \"@root\"\n// resolves to the target element itself and a selector resolves WITHIN it.\n// Without a target, ops resolve document-wide (a broadcast op like\n// add_class(\"#bell\", ...) that isn't anchored to one component). The op stream\n// is emitted AFTER all render streams in the reply (the endpoint appends it\n// last), so focus(\"[name=next]\") sees the freshly morphed DOM — Turbo applies\n// streams in document order.\nexport function registerReactiveJs() {\n const actions = window.Turbo?.StreamActions\n if (!actions || actions[\"reactive:js\"]) return\n actions[\"reactive:js\"] = function () {\n const list = parseOps(this.getAttribute(\"data-reactive-ops\"))\n if (!list.length) return\n const targetId = this.getAttribute(\"target\")\n // Issue #237: the server stamps the verbose gate on the stream element\n // itself (verbose_errors), so document-scoped ops are diagnosable too.\n const verbose = this.getAttribute(\"data-reactive-verbose\") === \"true\"\n // With a target: scope to that element (missing → no-op). Without: document.\n const root = targetId ? document.getElementById(targetId) : null\n if (targetId && !root) {\n if (verbose) {\n if (__SPLIT__) withFeature(\"devtools\", (devtools) => devtools.missingRoot(targetId))\n else devtoolsFeature.missingRoot(targetId)\n }\n return\n }\n applyOps(\n list,\n (args) => streamOpTargets(args, root),\n verbose\n ? (name, args) =>\n __SPLIT__\n ? withFeature(\"devtools\", (devtools) => devtools.diagnoseStream(name, args, root))\n : devtoolsFeature.diagnoseStream(name, args, root)\n : undefined,\n )\n }\n}\n\n// --- Deferred and lazy renders (issues #165, #276, #277) ---------------------\n// reply.defer, reactive_lazy and reactive_lazy(on:/cache:) live in the defer\n// feature module (issue #275, features/defer.js). The core keeps only the\n// `reactive:defer` stream action's REGISTRATION: such a stream can reach a\n// page that has not loaded the module yet (the first reply.defer on a page\n// with no lazy root), and it must not be lost. The <turbo-stream> element is\n// handed over once the module is here — at once when it already is.\nexport function registerReactiveDefer() {\n const actions = window.Turbo?.StreamActions\n if (!actions || actions[\"reactive:defer\"]) return\n actions[\"reactive:defer\"] = function () {\n if (__SPLIT__) withFeature(\"defer\", (defer) => defer.streamAction(this))\n else deferFeature.streamAction(this)\n }\n}\n\n// --- Around a stream render: effects and dismissing flashes (issues #100, #215) ---\n// Both live in the effects feature module (issue #275, features/effects.js).\n// The runtime keeps the ONE document-level turbo:before-stream-render listener\n// (it fires for every <turbo-stream>: a reply AND a broadcast) and hands each\n// event to the module, which wraps event.detail.render.\n//\n// In the default client the module is always here. The opt-in client may not\n// have imported it yet when a stream first needs it; what happens then is that\n// entry's business (core.js installs it: the stream's render waits for the\n// import). The runtime only offers the event.\nlet streamRenderRegistered = false\nlet streamWithoutEffects = null\n\nexport function registerReactiveStreamRender() {\n if (streamRenderRegistered) return\n if (typeof document === \"undefined\" || typeof document.addEventListener !== \"function\") return\n streamRenderRegistered = true\n document.addEventListener(\"turbo:before-stream-render\", (event) => {\n streamOwnReply(event)\n streamIntoRoots(event)\n streamModals(event)\n // The opt-in entry sees every stream (it may hold one for a module the\n // incoming content needs); with no entry hook, a loaded effects module\n // wraps the stream directly — in the default entry, always.\n if (!__SPLIT__) effectsFeature.wrap(event)\n else if (streamWithoutEffects) streamWithoutEffects(event, featureModules.get(\"effects\"))\n else featureModules.get(\"effects\")?.wrap(event)\n })\n}\n// The names this registration had while it was two listeners.\nexport { registerReactiveStreamRender as registerReactiveDismiss, registerReactiveStreamRender as registerReactiveEffects }\n\n// --- A stream into a connected root (issue #356) ---\n// A morph of a root makes it re-read its feature markers (#boundRootMorph); a\n// stream that renders INTO it — append, prepend or update of the root or a\n// child, before, after or replace of a child — fires neither a lifecycle nor\n// a morph of the root, so a marker it brings was never connected. The roots\n// a stream renders into are resolved here, before anything (effects, the opt-in\n// entry's hold) wraps Turbo's render; once that render has run, each one still\n// connected is told (STREAMED, not bubbling: an outer root's content is not\n// its own). The root re-runs its connected features' seeds and connects what\n// the new content needs, in both entries.\nconst STREAMED = \"reactive:streamed\"\n\nfunction streamIntoRoots(event) {\n const detail = event.detail\n const render = detail?.render\n const stream = detail?.newStream ?? event.target\n const action = stream?.getAttribute?.(\"action\")\n const into = /^(append|prepend|update)$/.test(action)\n if (typeof render !== \"function\" || !(into || /^(before|after|replace)$/.test(action))) return\n const id = stream.getAttribute(\"target\")\n const selector = stream.getAttribute(\"targets\")\n const roots = new Set()\n for (const target of id ? [document.getElementById(id)] : selector ? document.querySelectorAll(selector) : []) {\n const root = (into ? target : target?.parentElement)?.closest?.('[data-controller~=\"reactive\"]')\n if (root) roots.add(root)\n }\n if (roots.size === 0) return\n detail.render = async (el) => {\n await render(el)\n for (const root of roots) if (root.isConnected) root.dispatchEvent(new Event(STREAMED))\n }\n}\n\n// --- Modal dialogs (issue #365) ---\n// show_modal / close_dialog reach the browser's own modal dialog: the top\n// layer, the focus trap, ::backdrop, Escape and focus restored to the opener.\n// A dialog the SERVER renders open with data-reactive-modal becomes modal as\n// soon as the client sees it: at a root's connect (a full page, a replaced\n// root), after a morph of a root or of the page, and after a stream whose\n// content holds a dialog. Duck-typed on tagName (the submitFormFor precedent:\n// fake-node and test friendly).\nfunction isDialog(el) {\n return el?.tagName === \"DIALOG\" && typeof el.showModal === \"function\"\n}\n\n// `:modal` is the only way to tell a modal dialog from one opened with the\n// `open` attribute. An engine that does not know the pseudo-class throws a\n// SyntaxError; it then counts as not modal (show_modal reopens it modally).\nfunction isModal(dialog) {\n try {\n return dialog.matches(\":modal\")\n } catch {\n return false\n }\n}\n\nfunction showModal(el) {\n if (!isDialog(el)) {\n // Said where a zero-target op is (issue #237): under verbose_errors or debug.\n if (el?.closest?.('[data-reactive-verbose=\"true\"], [data-reactive-debug=\"true\"]')) {\n console.warn(`[phlex-reactive] show_modal targets a <dialog>, not <${el.localName}> — skipped`)\n }\n return\n }\n if (!el.isConnected || isModal(el)) return\n // showModal() throws on a dialog already open non-modally: close it first,\n // in the same task, so nothing paints in between.\n if (el.open) el.close()\n el.showModal()\n}\n\nfunction closeDialog(el) {\n if (isDialog(el) && el.open) el.close()\n}\n\n// Make every open dialog[data-reactive-modal] in `scope` modal — `scope` itself\n// too, for a root that is the dialog.\nfunction upgradeModals(scope) {\n const sel = \"dialog[data-reactive-modal]\"\n const dialogs = [...(scope?.querySelectorAll?.(sel) ?? [])]\n if (scope?.matches?.(sel)) dialogs.push(scope)\n for (const dialog of dialogs) {\n if (dialog.open && !isModal(dialog)) showModal(dialog)\n }\n}\n\n// After a stream whose content holds a dialog has rendered, upgrade the page's\n// marked dialogs. Document-wide: a replace's target is gone by then.\nfunction streamModals(event) {\n const detail = event.detail\n const render = detail?.render\n const stream = detail?.newStream ?? event.target\n if (typeof render !== \"function\" || !stream?.querySelector?.(\"template\")?.content?.querySelector?.(\"dialog\")) return\n detail.render = async (el) => {\n await render(el)\n upgradeModals(document)\n }\n}\n\nlet modalsRegistered = false\n\nexport function registerReactiveModals() {\n if (modalsRegistered) return\n if (typeof document === \"undefined\" || typeof document.addEventListener !== \"function\") return\n modalsRegistered = true\n // A morph of a root (a reply or broadcast morph, a page refresh) may have\n // inserted an open marked dialog or opened one; a page morph covers dialogs\n // outside any root.\n document.addEventListener(\"turbo:morph-element\", (event) => {\n if (event.target?.matches?.('[data-controller~=\"reactive\"]')) upgradeModals(event.target)\n })\n document.addEventListener(\"turbo:morph\", () => upgradeModals(document))\n // A morph that removes `open` from a modal dialog (the server now renders it\n // closed): close() it instead, which leaves the top layer, ends the page's\n // inertness and restores focus. Removing the attribute alone left all that\n // in place under the older spec text, and close() is a no-op once `open` is\n // gone — so the removal is cancelled and close() removes it. Idiomorph asks\n // \"remove\" for EVERY attribute of the old element, kept or not, and that ask\n // carries no new element: whether `open` is really leaving is read from the\n // element morph's new render, which comes first.\n const closing = new WeakSet()\n document.addEventListener(\"turbo:before-morph-element\", (event) => {\n const el = event.target\n const next = event.detail?.newElement\n if (!isDialog(el) || !next) return\n if (next.hasAttribute?.(\"open\")) closing.delete(el)\n else closing.add(el)\n })\n document.addEventListener(\"turbo:before-morph-attribute\", (event) => {\n const el = event.target\n const detail = event.detail\n if (detail?.attributeName !== \"open\" || detail.mutationType !== \"remove\") return\n if (!closing.has(el) || !el.open || !isModal(el)) return\n closing.delete(el)\n event.preventDefault()\n el.close()\n })\n}\n\n\n// --- keep: a morph re-applies what a kept client op did (issue #369) ---------\n// A morph rewrites `class`, `hidden` and every attribute from the server\n// render, so a selection made with on_client ops was lost to the next reply or\n// broadcast morph. An op with keep: records its RESULT on each target — each\n// class on or off, `hidden`, an attribute's value (null: absent) — and the one\n// document listener below puts that back after Turbo morphs the element in\n// place. The result, not the op: a toggle must not flip again on every morph.\n// The latest kept op on an element and a class or attribute wins, so \"clear\n// all, then select one\" leaves one. Classes and attributes no kept op touched\n// follow the render. Weak: an element a stream replaces is a new element.\n//\n// One Map per element: \".name\" → whether that class is on; an attribute name →\n// its value, null when absent. show/hide/toggle keep the `hidden` attribute,\n// so the morph puts back the visibility without running a transition again.\n// (No attribute name starts with \".\", so the two kinds of key never meet.)\n// An entry is re-inserted on every kept op, so the Map replays in op order:\n// a kept add_class after a kept set_attr(\"class\", …) still wins.\nconst kept = new WeakMap()\n\nfunction keepResult(el, name, args, resolveTargets) {\n const state = kept.get(el) ?? new Map()\n kept.set(el, state)\n const put = (key, value) => {\n state.delete(key)\n state.set(key, value)\n }\n if (name.endsWith(\"_class\")) for (const c of args.classes ?? []) put(`.${c}`, el.classList.contains(c))\n else if (name.endsWith(\"_attr\")) attrRefused(args.name) || put(args.name, el.getAttribute(args.name))\n else if (name === \"show\" || name === \"hide\" || name === \"toggle\") {\n put(\"hidden\", el.getAttribute(\"hidden\"))\n // The expanded: trigger's aria-expanded is kept on the trigger: a document\n // listener has no op scope to resolve it from later.\n if (args.expanded != null) {\n for (const trigger of resolveTargets({ ...args, to: args.expanded })) {\n keepResult(trigger, \"set_attr\", { name: \"aria-expanded\" })\n }\n }\n }\n}\n\nlet keepRegistered = false\n\nexport function registerReactiveKeep() {\n if (keepRegistered) return\n if (typeof document === \"undefined\" || typeof document.addEventListener !== \"function\") return\n keepRegistered = true\n // turbo:morph-element fires for every element Idiomorph morphed in place,\n // after its attributes were synced from the new render.\n document.addEventListener(\"turbo:morph-element\", (event) => {\n const el = event.target\n for (const [key, value] of kept.get(el) ?? []) {\n if (key[0] === \".\") el.classList.toggle(key.slice(1), value)\n else if (value == null) el.removeAttribute(key)\n else if (el.getAttribute(key) !== value) el.setAttribute(key, value)\n }\n })\n}\n\n\n// --- An image fallback that recovers (issue #383) ---------------------------\n// data-reactive-image-fallback='{\"hide\":true,\"alt\":\"#name\"}' on an <img>. On\n// `error` it gets data-reactive-image-state=\"error\" (plus `hidden` with hide,\n// and its alt shown in the `alt` node of its own reactive root); on `load`,\n// \"loaded\". A later src clears the error: copy_media and preview_file reset\n// it as they write (resetImage), any src that loads clears it on `load`, and\n// a morph that changes the src lets the browser try again. A morph that keeps\n// the src puts the state back. An error with no src is not an error (a\n// removed or emptied src). One document listener, capture phase (neither\n// event bubbles); nothing per root at connect.\nconst IMAGE_FALLBACK = \"data-reactive-image-fallback\"\nconst IMAGE_STATE = \"data-reactive-image-state\"\n// Marks the `hidden` the fallback set, so a reset removes only that one. On\n// the element, not in a WeakSet: a Turbo snapshot restores a NEW node.\nconst IMAGE_HIDDEN = \"data-reactive-image-hidden\"\nlet imageFallbackListeners = null\n\n// --- A wrapper an op hides (issues #391, #392) -------------------------------\n// preview_file's wrap: and reactive_image_fallback's wrap: hide the box around\n// an img. The mark says the runtime set that `hidden`, so a show removes only\n// a hide of its own, never one the author wrote. On the element, for the\n// IMAGE_HIDDEN reason. Visibility only: a wrapper usually holds the img, so\n// nothing here writes its text.\nconst WRAP_HIDDEN = \"data-reactive-wrap-hidden\"\n\nfunction hideWrap(el) {\n if (el.hasAttribute(\"hidden\")) return\n el.setAttribute(\"hidden\", \"\")\n el.setAttribute(WRAP_HIDDEN, \"\")\n}\n\nfunction showWrap(el) {\n if (!el.hasAttribute(WRAP_HIDDEN)) return\n el.removeAttribute(\"hidden\")\n el.removeAttribute(WRAP_HIDDEN)\n}\n\nfunction imageFallback(img) {\n if (img?.localName !== \"img\") return null\n const raw = img.getAttribute(IMAGE_FALLBACK)\n if (raw == null) return null\n try {\n return JSON.parse(raw) || {}\n } catch {\n return {}\n }\n}\n\nconst hasImageSrc = (img) => img.getAttribute(\"src\") || img.getAttribute(\"srcset\")\n\n// The node that shows the alt text: a selector resolved inside the img's own\n// root only (a document listener has no op scope).\nfunction imageRootNode(img, selector) {\n if (typeof selector !== \"string\" || !selector) return null\n try {\n return img.closest('[data-controller~=\"reactive\"]')?.querySelector(selector) ?? null\n } catch {\n return null\n }\n}\n\nfunction imageAltNode(img, wire) {\n const node = imageRootNode(img, wire.alt)\n // Never a node that holds the img: its textContent would wipe the img.\n return node && !node.contains(img) ? node : null\n}\n\nfunction setImageState(img, wire, value) {\n if (value === \"error\") {\n if (wire.hide && !img.hasAttribute(\"hidden\")) {\n img.setAttribute(\"hidden\", \"\")\n img.setAttribute(IMAGE_HIDDEN, \"\")\n }\n // wrap: (issue #392) may hold the img: only its visibility changes.\n if (wire.wrap) {\n const wrap = imageRootNode(img, wire.wrap)\n if (wrap) hideWrap(wrap)\n else console.warn(`[phlex-reactive] reactive_image_fallback wrap: ${JSON.stringify(wire.wrap)} is not in the root — skipped`)\n }\n const node = imageAltNode(img, wire)\n if (node) {\n node.textContent = img.getAttribute(\"alt\") ?? \"\"\n node.hidden = false\n }\n } else resetImage(img, wire)\n img.setAttribute(IMAGE_STATE, value)\n}\n\n// Undo what an error did — only what it did: `hidden` stays when the author\n// set it. Called by copy_media and preview_file when they change the src.\nfunction resetImage(img, wire = imageFallback(img)) {\n if (!wire || img.getAttribute(IMAGE_STATE) == null) return\n if (img.getAttribute(IMAGE_STATE) === \"error\") {\n if (img.hasAttribute(IMAGE_HIDDEN)) img.removeAttribute(\"hidden\")\n const wrap = imageRootNode(img, wire.wrap)\n if (wrap) showWrap(wrap)\n const node = imageAltNode(img, wire)\n if (node) node.hidden = true\n }\n img.removeAttribute(IMAGE_STATE)\n img.removeAttribute(IMAGE_HIDDEN)\n}\n\nfunction onImageEvent(event) {\n const img = event.target\n const wire = imageFallback(img)\n if (!wire) return\n if (event.type === \"load\") setImageState(img, wire, \"loaded\")\n else if (hasImageSrc(img)) setImageState(img, wire, \"error\")\n else resetImage(img, wire)\n}\n\nexport function registerReactiveImageFallback() {\n if (imageFallbackListeners) return\n if (typeof document === \"undefined\" || typeof document.addEventListener !== \"function\") return\n // A morph that keeps the src keeps the state: the render carries none, and\n // the browser loads nothing new to tell us again. Put it back once the\n // whole morph is done, so a later-morphed alt node is shown again too.\n const kept = new WeakMap()\n imageFallbackListeners = {\n error: onImageEvent,\n load: onImageEvent,\n \"turbo:before-morph-element\": (event) => {\n const img = event.target\n const next = event.detail?.newElement\n const value = img?.getAttribute?.(IMAGE_STATE)\n if (value == null || !next || !imageFallback(img)) return\n const same = (name) => img.getAttribute(name) === next.getAttribute?.(name)\n if (same(\"src\") && same(\"srcset\")) kept.set(img, value)\n },\n \"turbo:morph-element\": (event) => {\n const img = event.target\n const value = kept.get(img)\n if (value === undefined) return\n kept.delete(img)\n queueMicrotask(() => {\n const wire = imageFallback(img)\n if (wire) setImageState(img, wire, value)\n })\n },\n }\n for (const [name, fn] of Object.entries(imageFallbackListeners)) document.addEventListener(name, fn, true)\n // An image that finished before this ran (a cached 404) fired its event\n // unheard: read it off the element once. naturalWidth 0 is also a loaded\n // SVG with only a viewBox, so decode() decides (it rejects a broken image).\n for (const img of document.querySelectorAll?.(`img[${IMAGE_FALLBACK}]`) ?? []) {\n if (!img.complete || !hasImageSrc(img)) continue\n // A decode() that settles after the src changed decoded the OLD one: ignore it.\n const was = `${img.getAttribute(\"src\")} ${img.getAttribute(\"srcset\")}`\n const mark = (value) => `${img.getAttribute(\"src\")} ${img.getAttribute(\"srcset\")}` === was && setImageState(img, imageFallback(img) ?? {}, value)\n if (img.naturalWidth > 0) mark(\"loaded\")\n else if (typeof img.decode === \"function\") img.decode().then(() => mark(\"loaded\"), () => mark(\"error\"))\n else mark(\"error\")\n }\n}\n\n\n// For the opt-in entry: what to do with a stream before its render — hold it\n// for a module the incoming content needs. `handle(event, effects)` gets the\n// loaded effects module (or undefined) and wraps the stream with it itself.\nexport function onReactiveStreamWithoutEffects(handle) {\n streamWithoutEffects = handle\n}\n\n\n// --- A morph keeps the focused field's value (issue #338) ---\n// Turbo's stream morph (reply.morph, a broadcast morph) runs Idiomorph without\n// ignoreActiveValue, so a field being typed in took the render's value: a\n// normalised \"Hello\" over \"Hello \", or the value as the request left. Two\n// document listeners give a focused input/textarea inside a reactive root\n// Idiomorph's own ignoreActiveValue behaviour, minus the stale default:\n// before-morph-element — write the field's DEFAULT (its value attribute)\n// from the new render ourselves; with the user's\n// edit on it (the dirty-value flag) that never\n// touches .value, so dirty tracking still re-scans\n// against the saved value. A textarea's default is\n// its text child, which Idiomorph still morphs.\n// before-morph-attribute — cancel `value` on that field: Idiomorph honours it\n// for the attribute AND the property. Nothing else\n// (a root's token, a field's class) is held.\n// data-reactive-morph-value on a field lets the morph write it while focused.\n// --- An engine without contenteditable=\"plaintext-only\" (issue #355) ---\n// reactive_editable renders contenteditable=\"plaintext-only\": the browser\n// itself then pastes plain text and inserts \"\\n\" for Enter. An engine without\n// it reads the value as INVALID — the element is not editable, cannot even be\n// focused — so there every reactive editable is switched to \"true\" (and the\n// bindings feature does the plain-text paste itself). However it reaches the\n// page: present at load, appended by a stream into a root that is already\n// connected, loaded in a frame, written back by a morph of an unfocused\n// editable, or made reactive by a morph. One observer, only in such an engine; elsewhere the probe is all\n// that runs. Detected once per page.\nlet plaintextOnly\nlet plaintextObserver = null\nconst PLAINTEXT_EDITABLE = \"[data-reactive-editable][contenteditable=plaintext-only]\"\n\nfunction plaintextSupported() {\n if (plaintextOnly === undefined) {\n try {\n const probe = document.createElement(\"div\")\n probe.contentEditable = \"plaintext-only\"\n plaintextOnly = probe.contentEditable === \"plaintext-only\"\n } catch {\n plaintextOnly = false\n }\n }\n return plaintextOnly\n}\n\nfunction makeEditable(el) {\n if (el.matches?.(PLAINTEXT_EDITABLE)) el.setAttribute(\"contenteditable\", \"true\")\n el.querySelectorAll?.(PLAINTEXT_EDITABLE).forEach(makeEditable)\n}\n\nexport function registerReactivePlaintext() {\n // (No element factory, no page to observe: never probe a stub document.)\n if (plaintextObserver || typeof document === \"undefined\" || typeof document.createElement !== \"function\") return\n if (plaintextSupported()) return\n makeEditable(document)\n plaintextObserver = new MutationObserver((records) => {\n for (const record of records) {\n if (record.type === \"attributes\") makeEditable(record.target)\n else record.addedNodes.forEach(makeEditable)\n }\n })\n plaintextObserver.observe(document.documentElement, {\n childList: true,\n subtree: true,\n attributes: true,\n // (a morph can also make an existing plaintext-only element reactive)\n attributeFilter: [\"contenteditable\", \"data-reactive-editable\"],\n })\n}\n\n// For tests: what the probe answers (undefined probes again), with no\n// observer installed.\n\nlet morphFocusRegistered = false\n\n//\n// A reactive_editable (issue #351) is held the same way, but its \"value\" is its\n// CHILDREN: a focused one keeps them (text and caret) while every attribute\n// still morphs — copied here from the render, then the element's morph is\n// cancelled (cancelling is all-or-nothing in Idiomorph). Its contenteditable\n// stays as it is: the runtime switches it to \"true\" in an engine without\n// plaintext-only (registerReactivePlaintext, #355). Every morph of an editable, held or not, records the\n// render's text as its SERVER TEXT (the Escape revert, the dirty baseline).\nfunction holdsTypedValue(el) {\n return (\n el === document.activeElement &&\n (el.localName === \"input\" || el.localName === \"textarea\" || el.hasAttribute(\"data-reactive-editable\")) &&\n !el.hasAttribute(\"data-reactive-morph-value\") &&\n !!el.closest('[data-controller~=\"reactive\"]')\n )\n}\n\nexport function registerReactiveMorphFocus() {\n if (morphFocusRegistered) return\n if (typeof document === \"undefined\" || typeof document.addEventListener !== \"function\") return\n morphFocusRegistered = true\n document.addEventListener(\"turbo:before-morph-element\", (event) => {\n const el = event.target\n const next = event.detail?.newElement // absent when Turbo asks before a removal\n if (!next || event.defaultPrevented) return\n const holds = holdsTypedValue(el)\n // Before the default below is overwritten (issue #370).\n if (holds) noteHeld(el, next)\n if (el.hasAttribute?.(\"data-reactive-editable\")) {\n serverTexts.set(el, editableValue(next))\n if (!holds) return\n for (const { name } of [...el.attributes]) {\n if (!next.hasAttribute(name) && name !== \"contenteditable\" && name !== HELD) el.removeAttribute(name)\n }\n for (const { name, value } of next.attributes) {\n if (name !== \"contenteditable\" && el.getAttribute(name) !== value) el.setAttribute(name, value)\n }\n return event.preventDefault()\n }\n if (el.localName !== \"input\" || !holds) return\n const value = next.getAttribute(\"value\")\n if (value == null) el.removeAttribute(\"value\")\n else if (el.getAttribute(\"value\") !== value) el.setAttribute(\"value\", value)\n })\n // An editable a morph never reached (a stream append) records its server\n // text when first focused — before anything can be typed into it.\n document.addEventListener(\"focusin\", (event) => seedServerText(event.target))\n document.addEventListener(\"turbo:before-morph-attribute\", (event) => {\n const name = event.detail?.attributeName\n if ((name === \"value\" || name === HELD) && holdsTypedValue(event.target)) event.preventDefault()\n })\n // The user took theirs: the field reads its default again.\n document.addEventListener(\"input\", (event) => {\n const el = event.target\n if (el?.hasAttribute?.(HELD) && typedValue(el) === serverValue(el)) el.removeAttribute(HELD)\n })\n}\n\n// --- Knowing what was held (issue #370) ---\n// A morph that holds a focused field (above) over a render whose value differs\n// from the field's default — its last server value — means someone else changed\n// the field while the user typed. The field is marked data-reactive-held (kept\n// through later morphs while focused, like `value`), a bubbling reactive:held\n// { name, theirs } is dispatched, and the root's next action sends the names as\n// X-Reactive-Held. The root's own reply never marks (it answers exactly those\n// values), and once applied the root holds nothing — unless it refused them\n// (X-Reactive-Refused, issue #413): then the marks it names stay. A morph of\n// the field while unfocused writes the server's value and drops the mark with it.\nconst HELD = \"data-reactive-held\"\nconst ROOT = '[data-controller~=\"reactive\"]'\nlet replyRoot = null\nconst replying = new Map()\n\nfunction typedValue(el) {\n return el.hasAttribute(\"data-reactive-editable\") ? editableValue(el) : el.value\n}\n\nfunction serverValue(el) {\n return el.hasAttribute(\"data-reactive-editable\") ? serverText(el) : el.defaultValue\n}\n\nfunction renderedValue(next) {\n if (next.hasAttribute(\"data-reactive-editable\")) return editableValue(next)\n return next.localName === \"textarea\" ? next.textContent : (next.getAttribute(\"value\") ?? \"\")\n}\n\nfunction noteHeld(el, next) {\n const name = el.getAttribute(\"name\")\n // A checkbox's or radio's value is the option, not what the user typed.\n if (!name || /^(checkbox|radio)$/.test(el.type) || replying.has(el.closest(ROOT))) return\n const theirs = renderedValue(next)\n if (theirs === typedValue(el)) return el.removeAttribute(HELD)\n if (theirs === serverValue(el)) return\n el.setAttribute(HELD, \"\")\n el.dispatchEvent(new CustomEvent(\"reactive:held\", { bubbles: true, detail: { name, theirs } }))\n}\n\n// The names a root's next request reports: its own marked fields (not a nested\n// root's), still different from their default. As a header value: JSON with\n// every non-ASCII character escaped (fetch refuses a code point above 0xFF).\nfunction heldHeader(root) {\n const names = []\n for (const el of root.querySelectorAll(`[${HELD}]`)) {\n if (el.closest(ROOT) !== root) continue\n const name = el.getAttribute(\"name\")\n if (typedValue(el) === serverValue(el)) el.removeAttribute(HELD)\n else if (name && !names.includes(name)) names.push(name)\n }\n if (names.length === 0) return null\n return JSON.stringify(names).replace(/[\\u007f-￿]/g, (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`)\n}\n\n// `keep`: true keeps every mark, a list keeps the marks of those names.\nfunction releaseHeld(root, keep) {\n if (keep === true) return\n for (const el of root.querySelectorAll(`[${HELD}]`)) {\n if (el.closest(ROOT) === root && !keep?.includes(el.getAttribute(\"name\"))) el.removeAttribute(HELD)\n }\n}\n\n// What a reply refused (issue #413): \"*\" keeps every mark, a JSON list the\n// marks of those names. Anything else reads as a plain reply.\nfunction refusedHeader(response) {\n const raw = response.headers.get(\"X-Reactive-Refused\")\n if (raw === \"*\") return true\n try {\n const names = JSON.parse(raw)\n return Array.isArray(names) ? names : null\n } catch {\n return null\n }\n}\n\n// Hand a root's own reply to Turbo: while its streams render nothing in the\n// root is marked, and once they have the root holds nothing but what `keep`\n// names. Turbo announces each stream synchronously inside renderStreamMessage\n// (streamOwnReply wraps its render, innermost); a reply none of whose streams\n// rendered releases now. An error reply (keep true) never marks either, but\n// releases nothing: the server refused those values rather than answering them.\nfunction renderOwnReply(root, html, keep = null) {\n const own = { root, streams: 0, keep }\n const previous = replyRoot\n replyRoot = own\n try {\n window.Turbo.renderStreamMessage(html)\n } finally {\n replyRoot = previous\n }\n if (own.streams === 0) releaseHeld(root, keep)\n}\n\nfunction streamOwnReply(event) {\n const own = replyRoot\n const detail = event.detail\n const render = detail?.render\n if (!own || typeof render !== \"function\") return\n own.streams++\n detail.render = async (el) => {\n replying.set(own.root, (replying.get(own.root) || 0) + 1)\n try {\n return await render(el)\n } finally {\n const left = replying.get(own.root) - 1\n if (left) replying.set(own.root, left)\n else replying.delete(own.root)\n releaseHeld(own.root, own.keep)\n }\n }\n}\n\n\n// The framework-owned act a reactive_lazy(on:) shell sends (issue #276).\n// Lockstep with Phlex::Reactive::Component::Lazy::MATERIALIZE_ACTION.\nconst LAZY_MATERIALIZE_ACTION = \"__materialize\"\n\n// Offline CSS hook (issue #101). Mirror data-reactive-offline on\n// document.documentElement from navigator.onLine, kept in sync by the window\n// online/offline events — so an app can dim a save button or show a banner with\n// PURE CSS and zero JS ([data-reactive-offline] .save { pointer-events: none }).\n// Guarded on window (needed for addEventListener AND navigator) so importing the\n// module in a non-browser (bun test) context is a no-op, and registered once\n// (the online/offline listeners are NOT {once}, so a second registerReactiveActions\n// call must not stack duplicates) — mirroring the dismiss guard + reset seam.\nlet offlineRegistered = false\nexport function registerReactiveOffline() {\n if (offlineRegistered) return\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return\n if (typeof window.addEventListener !== \"function\") return\n offlineRegistered = true\n // toggleAttribute(name, force) writes data-reactive-offline=\"\" (a bare boolean\n // attr the [data-reactive-offline] selector matches) or removes it — never the\n // \"true\" string. navigator.onLine === false is the reliable direction (a false\n // \"online\" is spec-permitted but rare, and this is only a presentational hook —\n // the authoritative offline signal is the #perform gate, not this attribute).\n // Fully defensive: a missing documentElement/toggleAttribute/navigator degrades\n // to a no-op — a presentational hook must NEVER throw during bootstrap.\n const sync = () => {\n const root = document.documentElement\n if (typeof root?.toggleAttribute !== \"function\") return\n root.toggleAttribute(\"data-reactive-offline\", globalThis.navigator?.onLine === false)\n }\n sync() // seed synchronously so first paint is correct\n window.addEventListener(\"online\", sync)\n window.addEventListener(\"offline\", sync)\n}\n\n\n// Latency simulator dev aid (issue #102): features/devtools.js (issue #275). The\n// core keeps the two places that decide whether the module is needed at all:\n// the page opted into the console handle (the phlex-reactive-env meta), or a\n// delay is stored for this tab. Read live per request, like the CSRF token.\nconst LATENCY_KEY = \"phlex-reactive:latency\"\n\nfunction latencyStored() {\n return typeof sessionStorage !== \"undefined\" && Boolean(sessionStorage.getItem(LATENCY_KEY))\n}\n\n// At registration: a page that can use the simulator gets the module now —\n// effectively eager, in development only. No meta and no stored delay: no\n// module, no global handle, nothing on the page.\n//\n// This runtime registers with Turbo while it is being evaluated, BEFORE the\n// entry that imports it has run — before the default entry has handed the\n// module over, before the opt-in entry has said where to import it from. So\n// with neither in place this does nothing, and each entry calls it again\n// once it has done its part (see reactive_controller.js and core.js).\nexport function registerReactiveDev() {\n if (typeof document === \"undefined\") return\n if (__SPLIT__ && !featureModules.has(\"devtools\") && !FEATURES.get(\"devtools\")[1]) return\n const development = document.querySelector?.('meta[name=\"phlex-reactive-env\"]')?.content === \"development\"\n // (The default entry has the module in it: there is nothing to load, and\n // attach() is idempotent, so the second call is harmless.)\n if (!__SPLIT__) {\n if (development) devtoolsFeature.attach()\n } else if (development || latencyStored()) withFeature(\"devtools\", (devtools) => development && devtools.attach())\n}\n\n// --- Global reactive-activity signal (issue #201) --------------------------\n// A DOCUMENT-LEVEL count of in-flight reactive operations — the direct analogue\n// of Turbo's progress bar, but for reactive round trips and deferred renders\n// instead of navigations. Anything that starts an async reactive operation calls\n// enterReactiveActivity(); when it settles (success OR failure, on every path) it\n// calls exitReactiveActivity(). The count is exposed two ways so an app — or a\n// system test — can key off \"is the reactive layer settling?\" without knowing\n// about any individual root:\n//\n// * a marker on <html>: data-reactive-active present while count > 0 (CSS can\n// drive a global spinner; code/tests can read it). A DISTINCT name from the\n// per-root data-reactive-busy so a [data-reactive-busy] selector never also\n// matches the document element.\n// * events on document: reactive:busy on the 0 -> >0 edge, reactive:idle on the\n// >0 -> 0 edge — EDGES ONLY (not once per op), each carrying { count }.\n//\n// It sums ACROSS all reactive roots (module-level, not per-controller) and across\n// the two async lifecycles wired below:\n// * dispatch — entered in #applyBusy (at ENQUEUE, so the queue wait counts too),\n// exited in the settle closure #perform runs in its finally.\n// * defer — entered/exited with the pendingDefers registry (set/delete), the\n// ONE registry both the fetch (pull) and the stream (push) lane maintain — so\n// the push lane stays balanced even though it clears its pending markers by a\n// node swap, not clearDeferPending. A supersede is delete-then-set (net zero),\n// which is correct: a fast typist's replaced defer is still \"layer busy\".\n//\n// compute-seed is deliberately NOT counted: recompute() is synchronous, so a seed\n// is fully applied by the time the call returns — there is no async window to await\n// (the \"value settles a beat after a morph/seed\" case the issue describes is\n// covered by the System test helpers' re-resolve-by-id polling, not this counter).\nexport const ACTIVE_ATTR = \"data-reactive-active\"\n\nlet activityCount = 0\n\n// Increment the global in-flight count; on the 0 -> 1 edge, mark <html> and fire\n// reactive:busy. Fully defensive — a non-browser/test document with no\n// documentElement/dispatchEvent still tracks the count and simply skips the DOM\n// side effects (a global signal must never throw during bootstrap or a round trip).\nexport function enterReactiveActivity() {\n activityCount++\n if (activityCount === 1) syncReactiveActivity(\"reactive:busy\")\n}\n\n// Decrement the global in-flight count, clamped at 0 so an unbalanced exit can\n// never drive it negative (which would wedge the marker on forever). On the\n// 1 -> 0 edge, clear the <html> marker and fire reactive:idle.\nexport function exitReactiveActivity() {\n if (activityCount === 0) return\n activityCount--\n if (activityCount === 0) syncReactiveActivity(\"reactive:idle\")\n}\n\n// The current in-flight count — a test seam and a runtime read (an app can gate an\n// \"unsaved changes\" prompt on `reactiveActivityCount() > 0`).\nexport function reactiveActivityCount() {\n return activityCount\n}\n\n// Test seam: reset the module-level counter (and clear the marker) between tests,\n// since the module is imported once per bun run.\nexport function resetReactiveActivity() {\n activityCount = 0\n const root = typeof document !== \"undefined\" ? document.documentElement : null\n root?.removeAttribute?.(ACTIVE_ATTR)\n}\n\n// Write the <html> marker from the current count and fire the edge event on\n// document. Both sides are independently guarded so a partial document stub (a\n// documentElement without toggleAttribute, or a document without dispatchEvent)\n// degrades to a no-op rather than throwing.\nfunction syncReactiveActivity(eventName) {\n if (typeof document === \"undefined\") return\n const root = document.documentElement\n if (typeof root?.toggleAttribute === \"function\") {\n root.toggleAttribute(ACTIVE_ATTR, activityCount > 0)\n }\n if (typeof document.dispatchEvent === \"function\" && typeof CustomEvent === \"function\") {\n document.dispatchEvent(new CustomEvent(eventName, { detail: { count: activityCount } }))\n }\n}\n\n// --- Reactive request totals (issue #279) ----------------------------------\n// A running total of the reactive REQUESTS made, per kind — \"action\" (one per\n// #perform fetch) and \"defer\" (one per performDeferFetch) — so a system test can\n// assert \"one request on first open, none after\". The in-flight count above says\n// whether the layer is settling; this says how much it did.\n//\n// The JSON on <html data-reactive-requests> IS the store (read-modify-write per\n// request): a test reads it, and re-baselines by writing zeros, with no window\n// hook and no module state to drift from it. Written ONLY under the verbose gate\n// — data-reactive-verbose on <html> or on any reactive root (stamped in dev/test\n// by default) — so production writes nothing. The gate is checked once per\n// network request, never per event.\nexport const REQUESTS_ATTR = \"data-reactive-requests\"\n\nexport function countReactiveRequest(kind) {\n if (typeof document === \"undefined\") return\n const root = document.documentElement\n if (typeof root?.setAttribute !== \"function\" || !reactiveRequestsCounted(root)) return\n const totals = readReactiveRequests(root)\n totals[kind] = (Number(totals[kind]) || 0) + 1\n root.setAttribute(REQUESTS_ATTR, JSON.stringify(totals))\n}\n\nfunction reactiveRequestsCounted(root) {\n return root.hasAttribute?.(\"data-reactive-verbose\") || !!document.querySelector?.('[data-reactive-verbose=\"true\"]')\n}\n\n// The current totals, or zeros when the attribute is absent or not an object\n// (a hand-edited / garbled value restarts the count rather than throwing).\nfunction readReactiveRequests(root) {\n try {\n const parsed = JSON.parse(root.getAttribute(REQUESTS_ATTR))\n if (parsed && typeof parsed === \"object\") return { action: 0, defer: 0, ...parsed }\n } catch {}\n return { action: 0, defer: 0 }\n}\n\nexport function registerReactiveActions() {\n registerReactiveVisit()\n registerReactiveToken()\n registerReactiveJs()\n registerReactiveDefer()\n registerReactiveStreamRender()\n registerReactiveMorphFocus()\n registerReactiveModals()\n registerReactiveKeep()\n registerReactiveImageFallback()\n registerReactivePlaintext()\n registerReactiveOffline()\n registerReactiveDev()\n}\n\n// Escape a DOM id for safe interpolation into a RegExp (an id can legally contain\n// regex metacharacters like `.`/`:` — e.g. an `escape:`-namespaced or dotted id).\n// Used by #extractToken to match the stream that re-renders THIS element by id.\nexport function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n// --- Loaded-twice guard (issue #275) ------------------------------------------\n// Each shipped entry carries its own copy of this file. An app that imports\n// BOTH phlex/reactive/reactive_controller and phlex/reactive/core (or bundles\n// one and pins the other) gets two runtimes: two request queues' worth of\n// module state, two activity counters, two feature tables. Say so, loudly.\nconst CORE_LOADED = Symbol.for(\"phlex-reactive.core\")\nif (globalThis[CORE_LOADED]) {\n console.error(\n \"[phlex-reactive] the client was loaded twice. Import EITHER phlex/reactive/reactive_controller (the default, \" +\n \"everything in one file) OR phlex/reactive/core (features on demand), not both — each carries its own state.\",\n )\n}\nglobalThis[CORE_LOADED] = true\n\n// --- Registration guard (issue #26 part 2) -------------------------------\n// In a `lazyLoadControllersFrom(\"controllers\", application)` app, only\n// controllers under app/javascript/controllers/ are registered. This module\n// lives outside that dir, so importing it isn't enough — `data-controller=\n// \"reactive\"` does NOTHING until the host runs application.register(\"reactive\",\n// ...). The failure is silent: components render, but no action ever fires.\n//\n// We can't warn from connect() in that case (connect never runs). Instead, once\n// the page is ready, if reactive elements exist but no controller has connected,\n// the controller wasn't registered — so we warn, pointing at the fix.\nlet reactiveConnected = false\n\nexport function checkReactiveRegistration() {\n if (reactiveConnected) return\n if (typeof document === \"undefined\") return\n const els = document.querySelectorAll('[data-controller~=\"reactive\"]')\n if (!els || els.length === 0) return\n console.warn(\n \"[phlex-reactive] found \" + els.length + ' element(s) with data-controller=\"reactive\" ' +\n \"but the reactive controller never connected. It is loaded but not registered — \" +\n 'add `application.register(\"reactive\", ReactiveController)` (importmap) or import it ' +\n \"into app/javascript/controllers/ for lazyLoadControllersFrom apps. See the README.\"\n )\n}\n\n// Test seams (no-ops in production usage).\n\nif (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n // Defer past initial controller connection (a microtask/tick after ready).\n const scheduleCheck = () => setTimeout(checkReactiveRegistration, 0)\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", scheduleCheck, { once: true })\n } else {\n scheduleCheck()\n }\n}\n\n// The interpret-time attribute-name allowlist (issue #96) — the SECOND half of\n// the two-sided default-deny. The Ruby builder already refuses these at build\n// time; this guards a hand-built / forged ops attr from bypassing it. Refused:\n// event handlers (on*, XSS), URL-bearing names (a javascript: navigation\n// surface), and style (CSS injection). Case-insensitive, mirroring js.rb.\n// srcset (issue #373) too: a URL list that picks what an <img> loads.\nconst REFUSED_ATTR_URL = new Set([\"href\", \"src\", \"srcset\", \"srcdoc\", \"action\", \"formaction\", \"xlink:href\", \"style\"])\nfunction attrRefused(name) {\n const lower = String(name).toLowerCase()\n return lower.startsWith(\"on\") || REFUSED_ATTR_URL.has(lower)\n}\n\n// Run an animated visibility change (issue #96 `transition:`). `flip` performs\n// the actual hidden-flag change; `[during, from, to]` are class lists applied\n// AROUND it. Cleanup is awaited via the element's OWN animationend/transitionend\n// OR a setTimeout fallback — whichever comes first — so an element with NO\n// animation never leaves the helper classes stuck (the op chain itself is not\n// blocked: cleanup is fire-and-forget, later ops run immediately). Both end\n// events bubble, so a descendant's is ignored, and settling drops both\n// listeners (the effects.js fix, #296). The fallback is armed synchronously,\n// not behind the frame, so a hidden tab (no rAF) still cleans up; cleanup then\n// cancels the pending frame and clears `from` too, so a late frame can't leave\n// `to` (or `from`) stuck. A one-shot `done` guard runs cleanup exactly once.\n// One run per element: a new run first settles the live one (its classes,\n// timer, listeners and frame), so a superseded run's late wakeups can't strip\n// the new run's classes. The fallback follows the element's computed\n// durations (transitionFallbackMs), so a 600 ms transition isn't cut at 350.\nconst transitionRuns = new WeakMap()\nfunction runTransition(el, transition, flip) {\n const [during, from, to] = transition\n transitionRuns.get(el)?.()\n el.classList.add(during, from)\n flip()\n let done = false\n const frame = requestAnimationFrame(() => {\n if (done) return\n el.classList.remove(from)\n el.classList.add(to)\n })\n\n const cleanup = (event) => {\n if (done || (event && event.target !== el)) return\n done = true\n transitionRuns.delete(el)\n clearTimeout(timer)\n globalThis.cancelAnimationFrame?.(frame)\n el.removeEventListener(\"animationend\", cleanup)\n el.removeEventListener(\"transitionend\", cleanup)\n el.classList.remove(during, from, to)\n }\n transitionRuns.set(el, cleanup)\n el.addEventListener(\"animationend\", cleanup)\n el.addEventListener(\"transitionend\", cleanup)\n // Also the ONLY path for a non-animated element (no end event fires there),\n // so it must always be scheduled — and never behind the frame.\n const timer = setTimeout(cleanup, transitionFallbackMs(el))\n}\n\n// The longest computed duration × iteration-count + delay over the transition\n// and animation lists (CSS repeats the shorter list; a transition runs once,\n// `infinite` hits the cap), plus 50 ms; 350 ms when nothing is declared (or\n// there is no computed style), capped at 5 s so a bogus value can't wedge the\n// classes on. Read once `during` is on the element.\nfunction transitionFallbackMs(el) {\n let longest = 0\n try {\n const style = getComputedStyle(el)\n for (const kind of [\"transition\", \"animation\"]) {\n const [durations, delays] = [\"Duration\", \"Delay\"].map((name) =>\n String(style[kind + name])\n .split(\",\")\n .map((v) => parseFloat(v) * (/ms/.test(v) ? 1 : 1000) || 0),\n )\n const counts = String(style[kind + \"IterationCount\"])\n .split(\",\")\n .map((v) => (/inf/.test(v) ? Infinity : parseFloat(v) >= 0 ? parseFloat(v) : 1))\n for (let i = 0; i < durations.length || i < delays.length || i < counts.length; i++) {\n const runs = durations[i % durations.length] * counts[i % counts.length] || 0\n longest = Math.max(longest, runs + delays[i % delays.length])\n }\n }\n } catch {}\n return Math.min(Math.max(longest + 50, 350), 5000)\n}\n\n// Rich-text and contenteditable fields, as #collectFields reads them (minus\n// the [name] guard — an editor's name may live on its IDL `name` getter:\n// Trix's `input=`-paired hidden input). The persist feature keeps its own copy\n// of these two constants (features never import the core); a test pins that\n// they stay equal.\nexport const EDITOR_SELECTOR =\n \":is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])\"\nexport const EDITOR_TAGS = new Set([\"lexxy-editor\", \"trix-editor\"])\n\n// A reactive_editable's value (issue #351): its text with line breaks — a\n// <br> is one, a block element (the <div> a contenteditable=true Enter\n// inserts) starts and ends a line — \"\\r\\n\" normalised, ONE trailing newline\n// dropped (the <br> browsers keep at the end), and folded to spaces when the\n// field is single-line. Read from the DOM, not innerText: no layout, the same\n// on a detached render and under any white-space.\nexport function editableValue(el) {\n let text = \"\"\n // A block's edge asks for a line break; the next text or <br> pays it,\n // once, unless the text already ends in one.\n let line = false\n const add = (s) => {\n if (line && text && !text.endsWith(\"\\n\")) text += \"\\n\"\n line = false\n text += s\n }\n const walk = (node) => {\n for (const child of node.childNodes) {\n const block = /^(div|p|li)$/.test(child.localName)\n if (block) line = true\n if (child.nodeType === 3) child.data && add(child.data)\n else if (child.localName === \"br\") add(\"\\n\")\n else if (child.nodeType === 1) walk(child)\n if (block) line = true\n }\n }\n walk(el)\n text = text.replace(/\\r\\n?/g, \"\\n\").replace(/\\n$/, \"\")\n return el.getAttribute(\"data-reactive-editable\") === \"multi\" ? text : text.replace(/\\n/g, \" \")\n}\n\n// element -> the text of its last server render (issue #351): what Escape\n// reverts to and what dirty tracking diffs against. Seeded when the root\n// connects (or on first focus) and advanced by every morph of the element.\nconst serverTexts = new WeakMap()\n\nfunction seedServerText(el) {\n if (el?.hasAttribute?.(\"data-reactive-editable\") && !serverTexts.has(el)) serverTexts.set(el, editableValue(el))\n}\n\nexport function serverText(el) {\n seedServerText(el)\n return serverTexts.get(el)\n}\n\n// A RICH editor (lexxy/trix) is only ready once its custom element upgraded —\n// Trix defines its elements in a setTimeout after load — and exposes the\n// string `value` accessor; reading it before that yields \"\", which is issue\n// #8. A bare [contenteditable] is plain DOM and always ready.\nfunction collectorEditorReady(el) {\n return EDITOR_TAGS.has(el.localName) ? typeof el.value === \"string\" : true\n}\n\n// The client-op whitelist behind on_client (issue #95, extended in #96). Mirrors\n// Phlex::Reactive::JS's vocabulary; an op name not in this map is\n// warn-and-skipped by #applyOps (client-side default-deny — a stale or newer\n// ops attr must never break the page). Each op is a pure, local DOM mutation:\n// nothing is sent anywhere, and nothing is read back — with ONE deliberate\n// exception, paste_into (issue #228), which reads the clipboard behind the\n// browser's own gesture + permission gates and still only writes locally.\n// Frozen so nothing can be registered into it at runtime — extending the\n// vocabulary is a gem change, not an app hook.\nconst CLIENT_OPS = Object.freeze({\n show: (el, args, resolveTargets) => setVisibility(el, false, args, resolveTargets),\n hide: (el, args, resolveTargets) => setVisibility(el, true, args, resolveTargets),\n toggle: (el, args, resolveTargets) => setVisibility(el, !el.hidden, args, resolveTargets),\n add_class: (el, args) => el.classList.add(...(args.classes ?? [])),\n remove_class: (el, args) => el.classList.remove(...(args.classes ?? [])),\n toggle_class: (el, args) => (args.classes ?? []).forEach((c) => el.classList.toggle(c)),\n\n // Attribute ops (issue #96), interpret-time allowlisted. set_attr writes the\n // (already-stringified) value; toggle_attr adds a missing attr (value \"\") or\n // removes a present one — or, given values [on, off] (issue #271), flips\n // between them (an absent attr becomes `on`); remove_attr removes it. A\n // refused name warns + skips.\n set_attr: (el, args) => {\n if (guardAttr(args.name)) el.setAttribute(args.name, args.value ?? \"\")\n },\n remove_attr: (el, args) => {\n if (guardAttr(args.name)) el.removeAttribute(args.name)\n },\n toggle_attr: (el, args) => {\n if (!guardAttr(args.name)) return\n if (Array.isArray(args.values)) {\n const [on, off] = args.values\n el.setAttribute(args.name, el.getAttribute(args.name) === on ? off : on)\n } else if (el.hasAttribute(args.name)) el.removeAttribute(args.name)\n else el.setAttribute(args.name, \"\")\n },\n\n // Focus ops (issue #96). focus targets the match itself; focus_first targets\n // its first focusable descendant (opened-menu → first menuitem).\n focus: (el) => el.focus?.(),\n focus_first: (el) => firstFocusable(el)?.focus?.(),\n // Issue #399: blur the focused element when it is the target or inside it\n // (Escape ends a menu's :focus-within); focus elsewhere is left alone.\n // ACTOR-ONLY like focus (BROADCAST_REFUSED_OPS server-side).\n blur: (el) => {\n const active = el.ownerDocument?.activeElement ?? globalThis.document?.activeElement\n if (active && (active === el || el.contains?.(active))) active.blur?.()\n },\n\n // Modal dialog ops (issue #365): HTMLDialogElement#showModal / #close.\n // ACTOR-ONLY like focus (BROADCAST_REFUSED_OPS server-side).\n show_modal: (el) => showModal(el),\n close_dialog: (el) => closeDialog(el),\n\n // Text op (issue #159): set textContent — XSS-safe by construction (never\n // innerHTML), strictly less powerful than set_attr. Change-guarded like\n // #mirrorText. With global: true it is the cross-root text escape: paint a\n // value into a recap node OUTSIDE the component's root.\n text: (el, args) => {\n const text = String(args.value ?? \"\")\n if (el.textContent !== text) el.textContent = text\n },\n\n // Copy a server-rendered image (issue #373): src, srcset and alt from the\n // `from` <img>, resolved with the op's own scoping (the `submitter:`\n // precedent). The URL is read off that element, never from an argument —\n // the src refusal above stays. A selector that does not parse (a URL\n // string) is a miss, like one that matches nothing.\n copy_media: (el, args, resolveTargets) => {\n let source = null\n try {\n source = resolveTargets({ ...args, to: args.from })[0] ?? null\n } catch {}\n copyMedia(el, source)\n },\n\n // Tick or untick a whole checkbox group (issue #342) — \"clear selection\".\n // The bindings feature flips the root's OWNED boxes the way its select-all\n // header does (every box set, then input + change on each flipped one) and\n // re-syncs the group bindings once. global: true ignores the op's own root\n // and asks every reactive root on the page; each flips only the boxes it\n // owns (nested roots included), so every root holding the group answers.\n check_group: (el, args) => {\n const roots = args.global ? document.querySelectorAll('[data-controller~=\"reactive\"]') : [el]\n for (const root of roots) {\n __SPLIT__\n ? withFeature(\"bindings\", (bindings) => bindings.checkGroup(root, args.group, args.checked))\n : bindingsFeature.checkGroup(root, args.group, args.checked)\n }\n },\n\n // Write this tab's presence state (issue #358) through the root's\n // presence_set action. The feature warns outside a reactive_presence root.\n presence: (el, args) =>\n __SPLIT__\n ? withFeature(\"presence\", (presence) => presence.set(el, args.state))\n : presenceFeature.set(el, args.state),\n\n // Dispatch a bubbling CustomEvent (issue #96). RAW element.dispatchEvent — the\n // controller SHADOWS Stimulus's this.dispatch helper, so it must not be used.\n dispatch: (el, args) => {\n el.dispatchEvent(new CustomEvent(args.name, { bubbles: true, composed: true, detail: args.detail ?? {} }))\n },\n\n // Submit the target's OWN form (issue #226) via requestSubmit() — constraint\n // validation runs and a REAL cancelable `submit` event fires, so an\n // on(:action, event: \"submit\") interception or a native/Turbo form handles it\n // exactly like a user submit. No form → no-op. ACTOR-ONLY like focus: the\n // broadcast builder refuses it server-side (BROADCAST_REFUSED_OPS).\n // `submitter:` (issue #319) resolves with the op's own scoping (the\n // `expanded:` precedent) and submits THROUGH it, so its name=value posts. It\n // must be a submit control of that form — requestSubmit(x) throws otherwise —\n // so anything else warns and falls back to a plain requestSubmit().\n submit: (el, args, resolveTargets) => {\n const form = submitFormFor(el)\n if (!form) return\n let submitter = null\n if (args?.submitter != null && typeof resolveTargets === \"function\") {\n submitter = resolveTargets({ ...args, to: args.submitter })[0] ?? null\n if (!(submitter?.form === form && (submitter.type === \"submit\" || submitter.type === \"image\"))) {\n console.warn(`[phlex-reactive] submitter ${args.submitter} is not a submit control of the form — ignored`)\n submitter = null\n }\n }\n submitter ? form.requestSubmit?.(submitter) : form.requestSubmit?.()\n },\n\n // Clipboard-source paste (issue #228): on a user gesture, read\n // navigator.clipboard.readText() and feed the text into the target field\n // through the normal input pipeline — exactly what a native Cmd/Ctrl+V does.\n // The ONE op that reads a browser API and is async: fire-and-forget, so\n // applyOps stays sync and chain siblings never wait (the runTransition\n // posture). A rejected/dismissed read, empty text, or a missing API is a\n // SILENT no-op — page state must not change. ACTOR-ONLY like focus/submit:\n // the broadcast builder refuses it server-side (BROADCAST_REFUSED_OPS) —\n // and that server gate is the REAL one. The browser only partially backs it\n // up: Safari gates every read on a fresh gesture and Firefox shows its\n // paste picker per read, but Chromium's clipboard-read is a PERSISTENT\n // per-origin permission — once granted (the legit paste button itself\n // induces that), readText() succeeds with no gesture. No client-side\n // refusal is possible here: the reactive:js interpreter cannot distinguish\n // an actor reply's stream from a broadcast's, and reply.js legitimately\n // carries this op.\n paste_into: (el) => pasteClipboardInto(el),\n\n // Preview a chosen file (issue #375): paint the input's first image file\n // onto the `into` <img> through an object URL made HERE from the input's\n // own File. The op carries no URL and `args.url` is never read, so the src\n // refusal of set_attr (issue #96) stays whole. ACTOR-ONLY like paste_into\n // (BROADCAST_REFUSED_OPS server-side).\n preview_file: (el, args, resolveTargets) => previewFile(el, args, resolveTargets),\n\n // A field's live value (issue #374): the paste_into write without the\n // clipboard or the focus. ACTOR-ONLY (BROADCAST_REFUSED_OPS server-side).\n set_value: (el, args) => setFieldValue(el, String(args.value ?? \"\")),\n\n // Client-only drafts (issue #239): merge a flat state bag into the root's\n // reactive_persist draft / forget the draft. ACTOR-ONLY like focus/submit\n // (BROADCAST_REFUSED_OPS server-side) — rewriting or wiping every\n // subscriber's draft from a broadcast would be hostile.\n // The draft code lives in the persist feature module (issue #275), so both\n // ops run once it has loaded — at once on a root that restored a draft.\n persist_state: (el, args) =>\n __SPLIT__\n ? withFeature(\"persist\", (persist) => persist.writeState(el, args.state))\n : persistFeature.writeState(el, args.state),\n persist_clear: (el) =>\n __SPLIT__ ? withFeature(\"persist\", (persist) => persist.clearRoot(el)) : persistFeature.clearRoot(el),\n})\n\n// The form a submit op commits (issue #226), in order: the target itself when\n// it IS a form (tagName, not instanceof — fake-node/test friendly), its form\n// owner for a control (input.form — honors a form= attribute), else the nearest\n// ancestor form. closest() may cross the component root by design — the\n// FIELD'S OWN form is the submit scope, not the reactive boundary.\nfunction submitFormFor(el) {\n if (el?.tagName === \"FORM\") return el\n return el?.form ?? el?.closest?.(\"form\") ?? null\n}\n\n// Read the clipboard into a field (issue #228) — the body of the paste_into\n// op. The write mirrors a native paste: set .value, dispatch a bubbling\n// `input` event (the set-value + dispatch contract, issue #183 — compute\n// reducers, show bindings, and on_complete all run exactly as if the user\n// had typed), then focus (the caret lands where the user continues typing on\n// a partial paste). Availability-guarded: insecure contexts and some\n// webviews have no navigator.clipboard — the connect()-time gate hides\n// marked triggers there, so this guard is belt-and-braces. Empty text is a\n// no-op: \"paste nothing\" must not clear a half-typed field.\nfunction pasteClipboardInto(field) {\n const clipboard = globalThis.navigator?.clipboard\n if (typeof clipboard?.readText !== \"function\") return\n clipboard\n .readText()\n .then((text) => {\n if (!text) return\n field.value = text\n dispatchInput(field)\n field.focus?.()\n })\n .catch(() => {\n // Permission denied or the prompt dismissed — the browser's own UX said\n // no. The issue-#228 contract: a silent no-op, never an error.\n })\n}\n\n// --- Preview a chosen file (issue #375) ---\n// img -> the object URL preview_file last made for it. The runtime owns it:\n// never an op argument, never an attribute a caller sets. An entry lives\n// while the img is on the page AND still shows that URL; a re-pick, a clear,\n// a non-image file, the img leaving the page or a morph that strips its src\n// in place revokes it. One MutationObserver notices the last two, and only\n// while some preview is live: it then wakes on every DOM mutation of the page\n// (a live feed, a drag), and each wake is a walk over the few live previews.\nconst previews = new Map()\nlet previewObserver = null\n\nfunction previewFile(input, args, resolveTargets) {\n if (input?.tagName !== \"INPUT\" || input.type !== \"file\") {\n return warnPreview(`reads an input[type=file], not <${input?.localName}>`)\n }\n const img = typeof resolveTargets === \"function\" ? resolveTargets({ ...args, to: args.into })[0] : null\n // Duck-typed on tagName (the isDialog precedent): only an <img> ever gets a\n // src here — never an iframe, a script, a frame or anything else.\n if (img?.tagName !== \"IMG\") {\n return warnPreview(`paints an <img>, and ${JSON.stringify(args.into)} is ${img ? `a <${img.localName}>` : \"not on the page\"}`)\n }\n // valid: true (issue #382): an input the app marked invalid (setCustomValidity,\n // required) previews as empty. validity.valid, not checkValidity(): no\n // `invalid` event fired into the app's own listeners.\n const files = [...(args.valid === true && input.validity?.valid === false ? [] : (input.files ?? []))]\n const accepts = previewAccepts(input, args.accept)\n const listed = files.filter((f) => typeof f?.type === \"string\" && accepts(f))\n // Only an image is painted: a listed PDF clears the preview, unrefused.\n let file = listed.find((f) => f.type.startsWith(\"image/\"))\n // A refused file (issue #391) clears like an empty pick and says why. The\n // input keeps its files and its validity: the page owns the reset. Size is\n // read BEFORE an object URL exists, so an over-size file never gets one.\n let reason = files.length > 0 && listed.length === 0 ? \"type\" : null\n if (file && Number.isInteger(args.max_bytes) && file.size > args.max_bytes) reason = \"size\"\n const refused = reason === \"size\" ? file : files[0]\n if (reason) file = null\n forgetPreview(img)\n if (file) {\n const url = URL.createObjectURL(file)\n previews.set(img, url)\n img.setAttribute(\"src\", url)\n watchPreviews()\n } else img.removeAttribute(\"src\")\n resetImage(img)\n if (args.wrap != null) {\n const wraps = resolveTargets({ ...args, to: args.wrap })\n if (wraps.length === 0) warnPreview(`wrap: ${JSON.stringify(args.wrap)} is not on the page`)\n for (const wrap of wraps) file ? showWrap(wrap) : hideWrap(wrap)\n }\n if (args.name != null) {\n for (const node of resolveTargets({ ...args, to: args.name })) node.textContent = file ? file.name : \"\"\n }\n if (reason) {\n input.dispatchEvent(new CustomEvent(\"reactive:file-rejected\", { bubbles: true, detail: { reason, file: refused } }))\n }\n}\n\n// Which files the page takes: an image by default. accept: true reads the\n// input's own accept attribute; a string is that list for this op. A token is\n// an extension (\".png\"), a MIME type or a type/* wildcard, the browser's own\n// accept grammar. An absent or empty list keeps the image rule.\nfunction previewAccepts(input, accept) {\n const tokens = String((accept === true ? input.getAttribute(\"accept\") : typeof accept === \"string\" && accept) || \"\")\n .toLowerCase()\n .split(\",\")\n .map((token) => token.trim())\n .filter(Boolean)\n if (tokens.length === 0) return (f) => f.type.startsWith(\"image/\")\n return (f) => {\n const type = f.type.toLowerCase()\n return tokens.some((token) =>\n token[0] === \".\"\n ? String(f.name).toLowerCase().endsWith(token)\n : token.endsWith(\"/*\")\n ? type.startsWith(token.slice(0, -1))\n : type === token,\n )\n }\n}\n\nfunction warnPreview(why) {\n console.warn(`[phlex-reactive] preview_file ${why} — skipped`)\n}\n\n// Revoke the URL preview_file made for `img`, if it made one.\nfunction forgetPreview(img) {\n const url = previews.get(img)\n if (url === undefined) return\n previews.delete(img)\n URL.revokeObjectURL(url)\n if (previews.size === 0) {\n previewObserver?.disconnect()\n previewObserver = null\n }\n}\n\nfunction watchPreviews() {\n if (previewObserver || typeof MutationObserver !== \"function\" || !document?.documentElement) return\n previewObserver = new MutationObserver(() => {\n for (const [img, url] of previews) if (!img.isConnected || img.getAttribute(\"src\") !== url) forgetPreview(img)\n })\n previewObserver.observe(document.documentElement, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"src\"],\n })\n}\n\n\n// The set-value contract's dispatch (issue #183): a bubbling `input`, so\n// compute reducers, show bindings and on_complete run as if the user typed.\nfunction dispatchInput(field) {\n if (typeof field.dispatchEvent === \"function\") field.dispatchEvent(new Event(\"input\", { bubbles: true }))\n}\n\n// The body of the set_value op (issue #374). Writes the IDL .value — never the\n// attribute, never HTML — and dispatches `input` only when the field's value\n// actually moved (compared after the write: a textarea normalizes CRLF, a\n// select ends at \"\" for a value no option has). No `change`, no focus. Only an\n// input, textarea or select is a target, so a contenteditable (reactive_editable's\n// to write) warns and skips like any other node. A file input takes \"\" alone —\n// the browser throws on anything else.\nfunction setFieldValue(field, value) {\n if (!/^(input|textarea|select)$/.test(field.localName) || (field.type === \"file\" && value !== \"\")) {\n console.warn(\"[phlex-reactive] set_value skipped: not a field it can write\", field)\n return\n }\n const before = fieldState(field)\n field.value = value\n if (fieldState(field) !== before) dispatchInput(field)\n}\n\n// What set_value compares: .value, or for a <select multiple> its whole\n// selection — assigning .value deselects every other option, which .value\n// (the first selected) alone would not show.\nfunction fieldState(field) {\n return field.type === \"select-multiple\" ? [...field.selectedOptions].map((o) => o.value).join(\"\\n\") : field.value\n}\n\n// Apply a hidden-flag change, optionally animated by a [during, from, to]\n// transition (issue #96). Split out so show/hide/toggle share it.\nfunction setHidden(el, hidden, args) {\n if (args?.transition) runTransition(el, args.transition, () => (el.hidden = hidden))\n else el.hidden = hidden\n}\n\n// show/hide/toggle (issue #271): flip visibility, then mirror the INTENDED\n// state into the `expanded:` target's aria-expanded — computed before the flip,\n// so a transition never delays or races it. The expanded target resolves with\n// the op's own scoping (root-scoped, or document-wide under global: true).\nfunction setVisibility(el, hidden, args, resolveTargets) {\n setHidden(el, hidden, args)\n if (args?.expanded == null || typeof resolveTargets !== \"function\") return\n for (const target of resolveTargets({ ...args, to: args.expanded })) {\n target.setAttribute?.(\"aria-expanded\", String(!hidden))\n }\n}\n\n// The interpret-time attribute guard: refuse (warn + skip) a name off the\n// allowlist. Returns true when the op may proceed.\nfunction guardAttr(name) {\n if (!attrRefused(name)) return true\n console.warn(`[phlex-reactive] refused client attr op on ${JSON.stringify(name)} — skipped`)\n return false\n}\n\n// Copy src, srcset and alt from one <img> onto another (issue #373) — the\n// copy_media op and the reactive_media binding (the bindings feature reaches it\n// through the core handle). Only an <img> target is written, so an iframe,\n// script, object, embed or frame never receives a src from here. A source that\n// is missing or not an <img> clears the target. An <img> source without src is\n// a hit with no image (issue #381): the target loses src and srcset but takes\n// the alt, so a known entry without a logo keeps its name. Each attribute is\n// written only when it changes, so the same URL twice does not reload. Returns\n// the alt copied, false when it cleared, or null when the target was skipped.\nfunction copyMedia(target, source) {\n if (target?.localName !== \"img\") {\n console.warn(`[phlex-reactive] copy_media targets an <img>, not <${target?.localName}> — skipped`)\n return null\n }\n const img = source?.localName === \"img\" ? source : null\n const src = img?.getAttribute(\"src\")\n let changed = false\n for (const name of [\"srcset\", \"src\"]) {\n const value = src ? img.getAttribute(name) : null\n if (value == null) {\n if (target.hasAttribute(name)) changed = target.removeAttribute(name) ?? true\n } else if (target.getAttribute(name) !== value) changed = target.setAttribute(name, value) ?? true\n }\n if (changed) resetImage(target)\n const alt = img?.getAttribute(\"alt\") ?? \"\"\n if (target.getAttribute(\"alt\") !== alt) target.setAttribute(\"alt\", alt)\n return img ? alt : false\n}\n\n// The first focusable descendant of `el`, in document order — the natural\n// keyboard target inside an opened menu/dialog. Covers the standard focusable\n// set; :not([tabindex=\"-1\"]) drops explicitly-removed nodes. Returns null when\n// nothing inside is focusable (focus_first then no-ops).\nconst FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\nfunction firstFocusable(el) {\n return el.querySelectorAll?.(FOCUSABLE)?.[0] ?? null\n}\n\n// Parse a [[name, args], ...] op list from a raw attr/param. An array passes\n// through; a JSON string is parsed; anything malformed degrades to [] — a bad\n// ops attr must NEVER break the page (client-side default-deny). Shared by the\n// controller's runOps and the reactive:js stream action (issue #97).\nfunction parseOps(raw) {\n if (Array.isArray(raw)) return raw\n if (typeof raw !== \"string\") return []\n try {\n const list = JSON.parse(raw)\n return Array.isArray(list) ? list : []\n } catch {\n return []\n }\n}\n\n// --- on_client binding records (issue #271) -----------------------------------\n// Each on_client call emits ONE record ({on, ops, window?, outside?, once?,\n// detail?, confirm?, confirmWhen?}); mix space-joins several onto one element (spaces inside a\n// record ride as \\u0020, so the join is unambiguous). Stimulus hands every\n// runOps descriptor on an element the SAME event.params, so runOps selects the\n// record(s) whose descriptor matches the firing event: event.type, the key\n// filter, and window-boundness.\n\n// Stimulus's default keyMappings (letters and digits map to themselves), plus\n// delete and backspace (issue #366): Stimulus lacks those two, so a shortcut\n// naming one binds a bare keydown and only shortcutApplies matches it. A\n// custom Stimulus schema is not mirrored — an unknown filter never matches.\nconst KEY_FILTER_MAP = Object.freeze({\n backspace: \"Backspace\",\n delete: \"Delete\",\n enter: \"Enter\",\n tab: \"Tab\",\n esc: \"Escape\",\n space: \" \",\n up: \"ArrowUp\",\n down: \"ArrowDown\",\n left: \"ArrowLeft\",\n right: \"ArrowRight\",\n home: \"Home\",\n end: \"End\",\n page_up: \"PageUp\",\n page_down: \"PageDown\",\n})\nconst KEY_FILTER_MODIFIERS = Object.freeze([\"meta\", \"ctrl\", \"alt\", \"shift\"])\n\n// Stimulus's rule: the four modifiers must match EXACTLY (ctrl+k is not k);\n// the remaining token is compared to event.key case-insensitively. A\n// non-keyboard event (no event.key) checks the modifiers only. `keyMappings`\n// is the app's Stimulus schema table (custom keys included) when the\n// controller has one; the default table is the fallback.\nfunction keyFilterMatches(filter, event, keyMappings) {\n const parts = filter.split(\"+\")\n for (const mod of KEY_FILTER_MODIFIERS) {\n if (parts.includes(mod) !== Boolean(event[`${mod}Key`])) return false\n }\n const token = parts.find((part) => !KEY_FILTER_MODIFIERS.includes(part))\n if (token === undefined || typeof event.key !== \"string\") return true\n const key =\n keyMappings && Object.hasOwn(keyMappings, token)\n ? keyMappings[token]\n : Object.hasOwn(KEY_FILTER_MAP, token)\n ? KEY_FILTER_MAP[token]\n : /^[a-z0-9]$/.test(token)\n ? token\n : null\n return typeof key === \"string\" && key.toLowerCase() === event.key.toLowerCase()\n}\n\n// Issue #357: a shortcut: (\"mod+z\", or { keys, inEditable }) is a window\n// keydown whose `mod` is meta on Apple platforms and ctrl elsewhere. Ruby\n// renders a meta twin and a ctrl twin; Stimulus filters the key, and this\n// decides whether the twin that fired is this platform's and whether the\n// target is one the user is typing in. Either miss is a complete no-op. A\n// delete/backspace chord (issue #366) has no twins and no Stimulus filter:\n// its bare keydown hears every key, and this check alone picks the chord.\n// (Stimulus typecasts a digit shortcut, \"1\", to a number: hence String().)\nconst shortcutKeys = (spec) => (spec && typeof spec === \"object\" ? spec.keys : String(spec))\n// A shortcut record keeps a bare `on: \"keydown\"`, so bindingMatches lets every\n// keydown through and this check, per record, picks the chord that fired.\nfunction shortcutApplies(spec, event, keyMappings) {\n const target = event.target\n if (spec?.inEditable !== true && (target?.isContentEditable || /^(input|textarea|select)$/.test(target?.localName)))\n return false\n const mod = /[Mm]ac|iP/.test(navigator.userAgentData?.platform ?? navigator.platform) ? \"meta\" : \"ctrl\"\n return keyFilterMatches(shortcutKeys(spec).replace(/^mod\\+/, `${mod}+`), event, keyMappings)\n}\n\n// Parse data-reactive-ops-param into binding records. Stimulus typecasts a\n// lone record to an object; several records stay a string (JSON.parse fails on\n// the join) and are split here. A LEGACY [[op, args]] list (array or JSON\n// string — a hand-built attr) becomes one record flagged `legacy`: it has no\n// `on`, so it always matches, and runOps reads its flags from event.params. A\n// malformed piece warns and is skipped; its siblings still run (default-deny).\nfunction parseBindingRecords(raw) {\n if (Array.isArray(raw)) return [{ ops: raw, legacy: true }]\n if (raw && typeof raw === \"object\") return [raw]\n if (typeof raw !== \"string\") return []\n const text = raw.trim()\n if (text.startsWith(\"[\")) return [{ ops: parseOps(text), legacy: true }]\n const records = []\n for (const piece of text.split(\" \")) {\n if (piece === \"\") continue\n let record = null\n try {\n record = JSON.parse(piece)\n } catch {\n record = null\n }\n if (record && typeof record === \"object\" && !Array.isArray(record)) records.push(record)\n else console.warn(`[phlex-reactive] malformed on_client binding record ${JSON.stringify(piece)} — skipped`)\n }\n return records\n}\n\n// Does this record's descriptor match the firing event? The window check\n// matters for an element carrying both `click` and `click@window`: one inside\n// click reaches both listeners, and only currentTarget tells them apart. It is\n// recognised structurally (isWindow), so an undefined currentTarget is never\n// window-bound and a replay built for another document's window still counts\n// (issue #303). Only a LEGACY record (no `on` by\n// construction) matches everything; any other record without a descriptor is\n// malformed and never matches (default-deny). `keyMappings === null` skips the\n// key filter (the caller's single-candidate shortcut).\nfunction bindingMatches(record, event, keyMappings) {\n if (record.legacy) return true\n const on = record.on\n if (typeof on !== \"string\" || on === \"\") return false\n const dot = on.indexOf(\".\")\n if (event.type !== (dot < 0 ? on : on.slice(0, dot))) return false\n if (Boolean(record.window) !== isWindow(event.currentTarget)) return false\n return dot < 0 || keyMappings === null || keyFilterMatches(on.slice(dot + 1), event, keyMappings)\n}\n\n// Issue #346: a record's `detail` lists top-level keys of event.detail and the\n// JSON scalar each must strictly equal — on_client(\"turbo:submit-end\", ops,\n// detail: { success: true }) runs only after a successful submit. A missing or\n// non-object event.detail, or a missing key, never matches (default-deny); a\n// record without `detail` matches whatever the event carries.\nfunction detailMatches(record, event) {\n const expected = record.detail\n if (expected === undefined) return true\n if (expected === null || typeof expected !== \"object\" || Array.isArray(expected)) return false\n const detail = event.detail\n if (detail === null || typeof detail !== \"object\") return false\n // A missing key reads undefined, which no JSON scalar (null included) equals.\n return Object.keys(expected).every((key) => detail[key] === expected[key])\n}\n\n// A `once: true` record (PR #272) is spent after its first run. Stimulus\n// removes only that binding's own listener; a regular same-event sibling on\n// the element keeps calling runOps with BOTH records, so the spent one is\n// skipped here. Spent state belongs to the TRIGGER element (a WeakMap, so it\n// is collected with it): a morph/stream that swaps in a fresh element starts\n// fresh, and a byte-identical sibling trigger has its own. A window-bound\n// binding's currentTarget is the window, so there the element's ops attr joins\n// the key (a re-rendered window-bound once trigger with the same markup stays\n// spent — a known limit; spentEarlyOnce below has the same one for a replayed\n// `:once` hotkey).\nconst spentOnceBindings = new WeakMap()\nfunction onceBindingSpent(controller, event, record) {\n if (!record.once) return false\n const owner = event.currentTarget ?? controller.element\n let byOwner = spentOnceBindings.get(controller)\n if (!byOwner) {\n byOwner = new WeakMap()\n spentOnceBindings.set(controller, byOwner)\n }\n let spent = byOwner.get(owner)\n if (!spent) {\n spent = new Set()\n byOwner.set(owner, spent)\n }\n const raw = event.params?.ops\n const attr = owner === globalThis.window ? `${typeof raw === \"string\" ? raw : JSON.stringify(raw ?? null)}|` : \"\"\n const key = attr + JSON.stringify(record)\n if (spent.has(key)) return true\n spent.add(key)\n return false\n}\n\n// Two identical descriptors on one element (two mix-ed on_client calls with\n// the same event) are two Stimulus bindings, so runOps runs twice for ONE\n// event. The first call runs every matching record; a repeat is a no-op.\n// \"Repeat\" is (controller, listener target, the element's ops attr): Stimulus\n// walks EVERY binding of one window listener with the SAME event object, so\n// keying on currentTarget alone (= window) would drop every other root's\n// window-bound binding — and a sibling element's within one root. The ops attr\n// is the per-element key (a lone record is typecast to a fresh object per\n// binding, so it is compared by its JSON). Two elements in one root carrying\n// byte-identical window-bound records run once — the same ops, applied once.\nconst ranBindings = new WeakMap()\nfunction bindingsAlreadyRan(event, controller) {\n if (event === null || typeof event !== \"object\") return false\n const raw = event.params?.ops\n const key = typeof raw === \"string\" ? raw : JSON.stringify(raw ?? null)\n let byController = ranBindings.get(event)\n if (!byController) {\n byController = new WeakMap()\n ranBindings.set(event, byController)\n }\n let byTarget = byController.get(controller)\n if (!byTarget) {\n byTarget = new Map()\n byController.set(controller, byTarget)\n }\n let keys = byTarget.get(event.currentTarget)\n if (!keys) {\n keys = new Set()\n byTarget.set(event.currentTarget, keys)\n }\n if (keys.has(key)) return true\n keys.add(key)\n return false\n}\n\n// Interpret a [[name, args], ...] op list against the frozen CLIENT_OPS\n// whitelist (issues #95/#96/#97). `resolveTargets(args)` returns the element(s)\n// an op applies to — the controller scopes to its root (excluding nested\n// reactive roots); the reactive:js stream action scopes to its target root (or\n// the document). An unknown name warns and is SKIPPED while the rest of the\n// chain still applies — client-side default-deny, one bad op never takes down\n// its siblings. Object.hasOwn (not a bare read) so inherited Object members\n// (\"constructor\") can't masquerade as ops.\nfunction applyOps(list, resolveTargets, onZeroTargets) {\n for (const entry of list) {\n if (!Array.isArray(entry)) continue\n const [name, args = {}] = entry\n if (!Object.hasOwn(CLIENT_OPS, name)) {\n console.warn(`[phlex-reactive] unknown client op ${JSON.stringify(name)} — skipped`)\n continue\n }\n const targets = resolveTargets(args)\n if (targets.length === 0 && onZeroTargets) onZeroTargets(name, args)\n for (const el of targets) {\n CLIENT_OPS[name](el, args, resolveTargets)\n if (args?.keep === true) keepResult(el, name, args, resolveTargets)\n }\n }\n}\n\n// Resolve a reactive:js op's targets against its `target` root (issue #97).\n// \"@root\" is the root element itself; a selector resolves WITHIN it; a bare\n// selector with no root (no `target` attr on the stream) resolves document-wide\n// — a broadcast op anchored by a global selector (#bell) rather than a\n// component. Unlike the controller path there is no nested-reactive-root\n// ownership filter: a server-pushed op names its own scope explicitly —\n// including `global: true`, which opts a single op out of the target-root\n// scope to document-wide resolution (issue #159; the same escape the builder\n// documents for the controller path).\nfunction streamOpTargets(args, root) {\n const to = args.to\n if (root) {\n if (to === \"@root\") return [root]\n if (typeof to !== \"string\" || to === \"\") return []\n if (args.global) return [...document.querySelectorAll(to)]\n return [...root.querySelectorAll(to)]\n }\n // No target root: document-scoped. \"@root\" is meaningless here (nothing to\n // anchor to) → no-op; a selector matches document-wide.\n if (typeof to !== \"string\" || to === \"\" || to === \"@root\") return []\n return [...document.querySelectorAll(to)]\n}\n\n// --- Feature modules (issue #275) ---------------------------------------------\n// The client is a small core plus feature modules a page loads only when one\n// of its roots asks for them. Each entry is [needs, load, waiting?, gates?]:\n//\n// needs(root) a cheap marker read — does this root use the feature?\n// null for a feature no root asks for (it is loaded by\n// something page-level instead).\n// load() how to import the module — NOT written here. core.js,\n// the opt-in entry, supplies one per feature\n// (registerReactiveFeatureLoader): a LITERAL\n// import(\"phlex/reactive/features/<name>\"), so a bundler can\n// see the specifier and the import map resolves it to its\n// own digested file. The default entry supplies none: its\n// features are part of the file.\n// waiting(root, pending)\n// optional, and like load() supplied by core.js (only the\n// opt-in client ever waits): what must not be missed WHILE\n// the import is on its way. Runs when a root starts waiting, RECORDS into\n// `pending` (a plain object the feature receives later) and\n// returns its own undo. Core bytes — record, never act.\n// gates optional, true when the feature's connect changes what a\n// REQUEST reads (the draft restore writes the fields a\n// request collects). A root's action requests wait for its\n// features only while one that gates is still loading; a\n// feature that does not gate never delays a request.\n//\n// TABLE ORDER IS CONNECT ORDER (and disconnect order): persist is first\n// because its restore writes the values every other connect-time seed reads.\n//\n// A feature module exports\n//\n// install(shared) optional; once, when it has loaded\n// connect(controller, core, morphed, pending)\n// once per root connection; `pending` is what\n// its `waiting` hook recorded (undefined when\n// the root never had to wait)\n// disconnect(controller, core)\n// FIRST in the controller's disconnect()\n// abandon(root, pending) optional; the root left BEFORE the feature\n// could connect — last chance to act on\n// what was recorded\n//\n// and never imports this file (two copies of the core would split its state).\n// `shared` is FEATURE_SHARED below: the core's single-instance counters.\n// Everything a feature needs from one controller arrives as `core`, the\n// handle #featureCore builds — the ONE door into its private state:\n//\n// core.emit(name, detail, options) raw-dispatch a lifecycle event\n// core.reseed() re-run the connect-time seeds that\n// read field values\n// core.proceed(target, action, params) send an action down the ordinary\n// pipeline (veto, queue, request)\n// core.forgetToken() drop the token cached from a reply\n// core.owns(el) is this control this root's own, not\n// a nested reactive root's (issue #15)\n// core.ownership() the hoisted per-pass form of owns\n// core.opTargets(args) the elements an op's `to:` names\n// core.applyOps(list, defaultTo) run an op list root-scoped\n// core.diagnose(label, args) the zero-target warning\n// core.listnavOptions(event) the keyboard-navigable options\n// core.collectFields() this root's fields, as a request\n// would send them\n// core.confirm(message, context) the confirm gate (resolves a boolean)\n//\n// Later features add to that handle; nothing else of the controller is theirs\n// to touch beyond its public surface (element, application, …).\n//\n// WHEN A FEATURE CONNECTS. A module that is already here connects inside\n// connect() itself, in the same task, before the early-queue drain. In the\n// default bundle (phlex/reactive/reactive_controller) that is every feature,\n// always: they are handed over before anything connects, and nothing below\n// about imports, waiting, gates or timeouts ever applies.\n//\n// With phlex/reactive/core alone, the first root on a page that needs a\n// feature waits for its import: connect() only starts it, and the feature\n// connects when the module has arrived — after every feature EARLIER in the\n// table that this root is also waiting for (table order), never after a later\n// one: a slow defer import does not hold the draft restore back. Once the\n// module is loaded (a later root, the next Turbo visit, a reconnect) it too\n// connects inside connect().\n//\n// THE DEFAULT ENTRY HAS NONE OF THIS (issue #305). It is built with\n// `__SPLIT__` false: the runtime imports every feature statically and calls\n// it directly — connect() connects what the root's markers ask for, in this\n// order, by name in the source and by nothing at all in the minified file.\n// No table, no loader, no import(): what is below is the opt-in entry's.\n\n// The marker checks of the features that connect per root. The default entry\n// calls them directly (#connectFeaturesNow); the table below hands them to\n// the loader.\nfunction persistNeeded(root) {\n const declared = root.getAttribute?.(\"data-reactive-persist\")\n return Boolean(declared) && declared !== \"off\"\n}\n\n// reply.defer, reactive_lazy, reactive_lazy(on:/cache:). A root is a lazy\n// shell when it carries any of these; real content carries none.\nfunction deferNeeded(root) {\n return [\"defer-token\", \"defer-src\", \"lazy-on\", \"lazy-visible\"].some(\n (marker) => root.getAttribute?.(`data-reactive-${marker}`) != null,\n )\n}\n\n// Issue #410: a tokenless CLIENT-ONLY root (a ClientBindings component: filter,\n// show, on_client) has no action of its own. It is transparent to server round\n// trips: a server trigger inside it dispatches on the nearest token-bearing root\n// above, and that root's #collectFields looks through it. A lazy or deferred\n// shell is tokenless by design and is NOT client-only.\nconst AWAKE_ROOT = '[data-controller~=\"reactive\"]'\nconst ANY_ROOT = '[data-controller~=\"reactive\"],[data-reactive-dormant~=\"reactive\"]'\n\nconst clientOnlyRoot = (root) => root.getAttribute?.(\"data-reactive-token-value\") == null && !deferNeeded(root)\n\n// The first `selector` root at or above `from` that is not client-only, or\n// `stop` when the walk reaches it first, or null.\nfunction serverRoot(from, selector, stop) {\n let root = from?.closest?.(selector)\n while (root && root !== stop && clientOnlyRoot(root)) root = root.parentElement?.closest?.(selector)\n return root ?? null\n}\n\n// Connected controllers by root element, so a client-only root can hand a\n// dispatch to the server root above it. A dispatch for a root that has not\n// connected yet (a dormant root being woken) waits here until it does.\nconst rootControllers = new WeakMap()\nconst heldForwards = new WeakMap()\n\n// Dirty tracking with its navigate-away guard, and the paste-trigger gate:\n// the root or anything inside it carries one of the two markers. (A nested\n// root's marker loads the module for its parent too; the module then checks\n// ownership before it wires anything.)\nfunction formNeeded(root) {\n return (\n (root.getAttribute?.(\"data-action\") ?? \"\").includes(\"reactive#trackDirty\") ||\n root.getAttribute?.(\"data-reactive-clipboard\") != null ||\n root.querySelector?.('[data-action*=\"reactive#trackDirty\"],[data-reactive-clipboard]') != null\n )\n}\n\n// Show bindings and cross-root show targets, completion bindings, option\n// filtering, the bulk-selection group bindings (enable, select-all, count —\n// issue #319) and their cross-root targets (#343), the tag-chip input, draft\n// nested rows, editable text's keys and paste (#351), media previews\n// (#373) and fields fed into CSS custom properties (#417): a form's\n// client-only bindings. The root declares one, or owns an element that does.\n// (The probes the connect-time gates ran before the split, unchanged.)\nfunction bindingsNeeded(root) {\n return (\n [\"show-targets\", \"group-targets\", \"on-complete\", \"filter-input\", \"tags-field\", \"css-vars\"].some(\n (marker) => root.getAttribute?.(`data-reactive-${marker}`) != null,\n ) ||\n (root.querySelectorAll?.(\"[data-reactive-show-field], [data-reactive-show]\") ?? []).length > 0 ||\n root.querySelector?.(\n \"[data-reactive-nested-json], [data-reactive-nested-list], [data-reactive-confirm-when-param], [data-reactive-enable], [data-reactive-select-all], [data-reactive-count], [data-reactive-editable], [data-reactive-media], [data-reactive-css-vars]\",\n ) != null\n )\n}\n\n// Client-side computes: the root carries a reactive_compute binding.\nfunction computeNeeded(root) {\n return root.getAttribute?.(\"data-reactive-compute-inputs-param\") != null\n}\n\n// Sortable lists (issue #350): the root is, or holds, a sortable list or a\n// source list. (A nested root's list loads the module for its parent too; the\n// module then checks ownership before it picks a row up.)\nfunction sortableNeeded(root) {\n const lists = \"[data-reactive-sortable],[data-reactive-sortable-source]\"\n return Boolean(root.matches?.(lists) || root.querySelector?.(lists))\n}\n\n// Draggable regions (issue #416): the root is, or holds, a frame, a box or a\n// point. (A nested root's frame loads the module for its parent too; the\n// module then checks ownership before it drags anything.)\nfunction dragNeeded(root) {\n const marks = \"[data-reactive-frame],[data-reactive-box],[data-reactive-point]\"\n return Boolean(root.matches?.(marks) || root.querySelector?.(marks))\n}\n\n// Presence (issue #358): the root is a reactive_presence roster.\nfunction presenceNeeded(root) {\n return root.getAttribute?.(\"data-reactive-presence\") != null\n}\n\n// Countdowns (issue #400): the root is, or holds, a reactive_countdown.\nfunction countdownNeeded(root) {\n return Boolean(root.matches?.(\"[data-reactive-countdown]\") || root.querySelector?.(\"[data-reactive-countdown]\"))\n}\n\nconst PRODUCTION_FEATURES = [\n // (Its `waiting` hook is the opt-in entry's: core.js.) The draft restore\n // writes what a request reads, so it gates.\n [\"persist\", [persistNeeded, null, null, true]],\n [\"defer\", [deferNeeded, null]],\n [\"form\", [formNeeded, null]],\n // Its seeds write what a request reads (the JSON-mode rows), so it gates.\n [\"bindings\", [bindingsNeeded, null, null, true]],\n // The seed writes output fields a request collects, so it gates.\n [\"compute\", [computeNeeded, null, null, true]],\n // Nothing it does at connect is read by a request: it never gates.\n [\"sortable\", [sortableNeeded, null]],\n // A drag writes fields only when the user drags: it never gates.\n [\"drag\", [dragNeeded, null]],\n // Its announce is a request of its own; nothing it does at connect is read\n // by another request: it never gates.\n [\"presence\", [presenceNeeded, null]],\n // A countdown writes only its own text and visibility: it never gates.\n [\"countdown\", [countdownNeeded, null]],\n [\n // Stream effects and dismissing flashes are document-level: the module\n // has no connect. A root that DECLARES an effect only gets it fetched\n // early, so the first stream need not wait for it (see streamHold).\n \"effects\",\n [\n (root) => [\"enter\", \"update\", \"exit\"].some((hook) => root.getAttribute?.(`data-reactive-effect-${hook}`) != null),\n null,\n ],\n ],\n [\n // The optimistic/busy hint engine: a trigger in the root declares a hint.\n // No connect — the module acts at enqueue — so the marker is only read\n // while it is not loaded, and a root that declares one preloads it.\n \"hints\",\n [\n (root) =>\n root.querySelector?.(\n \"[data-reactive-optimistic-param], [data-reactive-busy-param], [data-reactive-loading-param]\",\n ) != null,\n null,\n ],\n ],\n [\n // Development aids: the latency simulator (page-level, see\n // registerReactiveDev), the zero-target diagnostics and the debug trace.\n // A root in debug mode preloads it; a verbose root asks for it the first\n // time it has something to warn about.\n \"devtools\",\n [(root) => root.getAttribute?.(\"data-reactive-debug\") === \"true\", null],\n ],\n]\n// (Only the opt-in entry has a table: `new Map` would keep it in the default.)\nconst FEATURES = __SPLIT__ ? new Map(PRODUCTION_FEATURES) : null\n\n// name -> the one import promise every root shares, kept even when it\n// rejected: a browser caches a module that failed to load, so importing it\n// again only re-rejects. A failed feature stays failed until the page is\n// reloaded; every root it costs is told (reactive:error).\nconst featureLoads = __SPLIT__ ? new Map() : null\n// name -> the loaded module: what lets a later root connect a feature inside\n// connect(), and a stream action or client op use it in the same tick.\nconst featureModules = __SPLIT__ ? new Map() : null\n// The modules the default bundle handed over (registerReactiveFeature); only\n// the test seam below reads it back.\nconst featuresGiven = __SPLIT__ ? new Map() : null\n\n// How the opt-in entry (core.js) tells the runtime where a feature module is\n// — `load`, a function returning its import() — and, optionally, what to\n// record while that import is on its way (`waiting`, see above).\nexport function registerReactiveFeatureLoader(name, load, waiting) {\n if (__SPLIT__) {\n featureLoaders.set(name, [load, waiting])\n applyFeatureLoader(name)\n }\n}\n\n// name -> [load, waiting] the opt-in entry registered: kept apart from the\n// table so a test's reset of the table puts them back.\nconst featureLoaders = __SPLIT__ ? new Map() : null\n\nfunction applyFeatureLoader(name) {\n const entry = FEATURES.get(name)\n const [load, waiting] = featureLoaders.get(name)\n entry[1] = load\n entry[2] = waiting\n}\n\n// Hand the runtime a feature that is ALREADY loaded — what\n// phlex/reactive/reactive_controller does for every feature before anything\n// can connect. Such a feature is never imported: it connects inside connect().\nexport function registerReactiveFeature(name, feature) {\n if (__SPLIT__) {\n feature.install?.(FEATURE_SHARED)\n featureModules.set(name, feature)\n featuresGiven.set(name, feature)\n }\n}\n\n// For the opt-in entry: the features some of `elements` (reactive roots a\n// stream is about to render) need and that are not loaded — read off the\n// table, so a new feature is covered by its own marker check.\nexport function unloadedFeaturesFor(elements) {\n const names = []\n if (__SPLIT__) {\n for (const [name, [needs]] of FEATURES) {\n if (!needs || featureModules.has(name)) continue\n try {\n if (elements.some((el) => needs(el))) names.push(name)\n } catch {\n // a marker check that throws is that root's problem at connect, not the stream's\n }\n }\n }\n return names\n}\n\n// For the opt-in entry: import a feature now. Resolves with the module, or\n// with undefined once the failure has been logged.\nexport function loadReactiveFeature(name) {\n return __SPLIT__\n ? loadFeature(name).catch((error) => logFeatureFailure(name, \"load\", error))\n : Promise.resolve()\n}\n\nfunction loadFeature(name) {\n let loading = featureLoads.get(name)\n if (!loading) {\n const load = FEATURES.get(name)[1] ?? (() => Promise.reject(new Error(\"this entry has no way to import it\")))\n loading = load().then((feature) => {\n feature.install?.(FEATURE_SHARED)\n featureModules.set(name, feature)\n return feature\n })\n featureLoads.set(name, loading)\n }\n return loading\n}\n\n// Logged once per feature and phase per page (a failed import would otherwise\n// log again for every root that connects). `phase` says what went wrong:\n// \"detect\" (its marker check threw), \"load\" (the import failed — and stays\n// failed until the page is reloaded), \"timeout\" (slow; the root carried on\n// without it) or \"connect\" (it threw while wiring a root).\nconst featureFailuresLogged = new Set()\n\nfunction logFeatureFailure(name, phase, error) {\n const logged = name + phase\n if (featureFailuresLogged.has(logged)) return\n featureFailuresLogged.add(logged)\n console.error(\n `[phlex-reactive] the \"${name}\" feature module (phlex/reactive/features/${name}) is unavailable: ${phase}. ` +\n \"If you bundle or vendor the client, alias or pin phlex/reactive/features/* (README: esbuild / webpack / bun).\",\n error,\n )\n}\n\n// Run `use(feature)` with a feature — for code with no root connection to\n// wait on (a client op, a stream action): in this tick when the module is\n// loaded, else once it has arrived. A feature that cannot load is logged.\nfunction withFeature(name, use) {\n const feature = featureModules.get(name)\n if (feature) return use(feature)\n loadFeature(name).then(use, (error) => logFeatureFailure(name, \"load\", error))\n}\n\n// How long a root waits for a feature import before it carries on without it\n// (<meta name=\"phlex-reactive-feature-timeout\" content=\"ms\"> in <head>).\n// 10 s: the modules are a few KB, so even a slow 3G fetch (seconds, not tens\n// of seconds) finishes well inside it, and it matches the early-event TTL —\n// the other \"how long may the client be late\" window. A feature that arrives\n// AFTER the timeout still connects; the timeout only stops it holding back\n// the root's other features and its action requests.\nconst DEFAULT_FEATURE_TIMEOUT_MS = 10000\n\nfunction featureTimeoutMs() {\n const ms = Number(globalThis.document?.head?.querySelector?.('meta[name=\"phlex-reactive-feature-timeout\"]')?.content)\n return Number.isFinite(ms) && ms > 0 ? ms : DEFAULT_FEATURE_TIMEOUT_MS\n}\n\nexport function reactiveFeatureNames() {\n return __SPLIT__\n ? [...FEATURES.keys()]\n : [\"persist\", \"defer\", \"form\", \"bindings\", \"compute\", \"sortable\", \"drag\", \"presence\", \"countdown\", \"effects\", \"hints\", \"devtools\"]\n}\n\n\n// Test-only: a feature's table entry, to wrap one part of it.\n\n// Test-only: import a feature now (a later connect is then synchronous).\n\n// Test-only: back to the shipped table, with nothing logged and only the\n// modules the default bundle handed over still loaded — or, `cold`, with none\n// loaded at all: the state of a page that imported phlex/reactive/core.\n\nconst FEATURES_READY = Promise.resolve()\n\n// The single-instance module state a feature may add to (install()): ONE\n// in-flight activity count and one request total per page, whoever counts.\n// `waiting` maps a root to { <feature name>: pending } while it waits for that\n// feature's import (see the `waiting` hook above).\nfunction forgetWaiting(root, name, pending) {\n const waiting = FEATURE_SHARED.waiting.get(root)\n // (A root that reconnected meanwhile has a NEW record under the same name.)\n if (waiting && waiting[name] === pending) delete waiting[name]\n}\n\nconst FEATURE_SHARED = {\n enter: enterReactiveActivity,\n exit: exitReactiveActivity,\n count: countReactiveRequest,\n // The editable collector and server text (issue #351), for the draft.\n text: editableValue,\n served: serverText,\n waiting: new WeakMap(),\n}\n\n// The default entry's per-root features, one bit each (#connectFeaturesNow).\nconst PERSIST = 1\nconst DEFER = 2\nconst FORM = 4\nconst BINDINGS = 8\nconst COMPUTE = 16\nconst SORTABLE = 32\nconst PRESENCE = 64\nconst COUNTDOWN = 128\nconst DRAG = 256\n\n// The default entry's features are part of this file: install them now, as\n// the opt-in entry does when one arrives.\nif (!__SPLIT__) {\n persistFeature.install(FEATURE_SHARED)\n deferFeature.install(FEATURE_SHARED)\n}\n\n// --- Early triggers (issue #273) ----------------------------------------------\n// phlex/reactive/early (imported eagerly by the app) queues trigger events that\n// reach a root before its controller connects. The queue is shared through a\n// Symbol.for key on window — no import edge either way, so either module may\n// load first, and an app that never imports early gets an empty queue.\nconst EARLY_KEY = Symbol.for(\"phlex-reactive.early\")\nconst DEFAULT_EARLY_TTL_MS = 10000\n// A window-bound trigger (a hotkey, issue #303) is replayed only this soon\n// after the keypress: later, the user has moved on. A shorter configured TTL\n// still wins.\nconst WINDOW_EARLY_TTL_MS = 1500\n\n// Is this event's currentTarget a Window (a Stimulus `@window` listener)? The\n// page's window, or any Window recognised structurally (another document's,\n// which a replay built from its trigger element's document carries).\nconst isWindow = (target) => target != null && (target === globalThis.window || target.window === target)\n\n// Issue #393: the key on()'s dispatch debounce uses in #debounceTimers. An\n// on_client record keys on its JSON, which starts with \"{\", so never this.\nconst DISPATCH_WAIT_KEY = \"dispatch\"\n\nfunction earlyState() {\n globalThis[EARLY_KEY] ??= { queue: [], connected: new WeakSet() }\n return globalThis[EARLY_KEY]\n}\n\n// <meta name=\"phlex-reactive-early-ttl\" content=\"ms\"> (Phlex::Reactive.\n// early_event_ttl_ms), parsed defensively like the timeout meta.\nfunction earlyTtlMs() {\n const ms = Number(globalThis.document?.querySelector?.('meta[name=\"phlex-reactive-early-ttl\"]')?.content)\n return Number.isFinite(ms) && ms > 0 ? ms : DEFAULT_EARLY_TTL_MS\n}\n\n// Stimulus's param reader (data-reactive-<name>-param, JSON-typecast,\n// camelized) — a replayed trigger carries the same event.params a live one does.\nfunction stimulusParams(el) {\n const params = {}\n for (const { name, value } of Array.from(el.attributes ?? [])) {\n const match = /^data-reactive-(.+)-param$/i.exec(name)\n if (!match) continue\n let typed\n try {\n typed = JSON.parse(value)\n } catch {\n typed = value\n }\n params[match[1].replace(/[-_]([a-z0-9])/g, (_, char) => char.toUpperCase())] = typed\n }\n return params\n}\n\n// The event a replay hands to dispatch()/runOps(). It is called DIRECTLY, not\n// re-dispatched on the element: a real event would also re-run every OTHER\n// listener on the trigger (a lazily connected sibling controller that already\n// handled the original click would toggle twice). The original's default was\n// already prevented (or deliberately kept) by early.js, so preventDefault here\n// is a no-op. A window-bound entry (issue #303) is replayed as Stimulus's\n// window listener sees it: currentTarget is the window, params come from `el`.\nfunction earlyReplayEvent(event, el, win) {\n return {\n [EARLY_KEY]: true,\n type: event.type,\n detail: event.detail,\n target: event.target,\n currentTarget: win ? el.ownerDocument.defaultView : el,\n params: stimulusParams(el),\n key: event.key,\n code: event.code,\n metaKey: event.metaKey,\n ctrlKey: event.ctrlKey,\n altKey: event.altKey,\n shiftKey: event.shiftKey,\n button: event.button,\n submitter: event.submitter,\n bubbles: event.bubbles,\n timeStamp: event.timeStamp,\n defaultPrevented: event.defaultPrevented,\n preventDefault() {},\n stopPropagation() {},\n stopImmediatePropagation() {},\n }\n}\n\n// A :once trigger that was REPLAYED is spent, but Stimulus's own `once`\n// listener for it is still armed (the replay calls the method directly). The\n// markup is left alone — rewriting data-action would let a morph, which writes\n// the server's attribute back, re-arm it — so the spent descriptor is tracked\n// per trigger element (a WeakMap: a replaced element starts fresh, like a live\n// `once`), and the armed listener's single firing is swallowed. A window-bound\n// descriptor's live call carries the window as currentTarget, not its\n// element, so it is tracked under the ROOT instead (issue #303), flagged\n// `win` (apart from the root's own element-bound descriptors) and told apart\n// from its siblings by the params Stimulus reads off its element.\n//\n// Known limit of the root-keyed entry (the same class as onceBindingSpent's\n// window-bound limit above): a reply that MORPHS the root but swaps the\n// trigger element gives Stimulus a fresh `once` listener for the new element\n// while this entry stays armed, so the next live press is swallowed here and\n// that fresh listener is consumed — the hotkey is dead until the root\n// disconnects. Keep a `:once` hotkey's trigger element stable across replies,\n// or bind the hotkey without `once:`.\nconst spentEarlyOnce = new WeakMap()\n\nfunction spendEarlyOnce(owner, { token, type, method, filter, win }, params) {\n let spent = spentEarlyOnce.get(owner)\n if (!spent) spentEarlyOnce.set(owner, (spent = new Map()))\n const key = win ? `${token} ${params}` : token\n if (spent.has(key)) return false\n spent.set(key, { type, method, filter, win, params, armed: true })\n return true\n}\n\n// True (once) for the live call that comes from a spent descriptor's listener:\n// same element, method, event type AND key filter — a sibling descriptor with\n// another filter (keydown.esc beside a spent keydown.enter:once) is not it.\n//\n// Also true for the ORIGINAL of a replayed event arriving live at the same\n// element (issue #274): waking a dormant root can connect its controller while\n// the waking event is still propagating (an eagerly registered controller\n// connects in the microtask checkpoint after early.js's capture listener), so\n// the event reaches the listener Stimulus just bound after it was replayed.\n// Only as many live calls as the replay RAN for that element and method are\n// dropped — a binding the replay skipped (a key filter only the app's own\n// mapping matches) still runs.\nfunction earlyOnceSwallows(event, method, keyMappings, root) {\n if (event?.[EARLY_KEY]) return false\n const win = isWindow(event?.currentTarget)\n // A window-bound replay is owned by its ROOT: another root's binding on the\n // same window event is not it (issue #303).\n const owner = win ? root : event?.currentTarget\n const replayed = takeEarlyReplay(event, owner, win ? `@${method}` : method)\n const spent = spentEarlyOnce.get(owner)\n const params = win && JSON.stringify(event.params)\n for (const entry of spent?.values() ?? []) {\n if (!entry.armed || entry.method !== method || entry.type !== event.type || Boolean(entry.win) !== win) continue\n if (win && entry.params !== params) continue\n if (entry.filter && !keyFilterMatches(entry.filter, event, keyMappings)) continue\n entry.armed = false\n return true\n }\n return replayed\n}\n\n// event → (element → { dispatch: n, runOps: n }): how many bindings a replay\n// ran while its original may still be propagating. The entry lasts for that\n// propagation only — a new task starts after the whole dispatch is over — so\n// the same event OBJECT dispatched again later is live.\nconst replayedEarly = new WeakMap()\n\nfunction markEarlyReplay(event, el, method) {\n let byElement = replayedEarly.get(event)\n if (!byElement) {\n replayedEarly.set(event, (byElement = new Map()))\n setTimeout(() => replayedEarly.delete(event))\n }\n const counts = byElement.get(el) ?? {}\n byElement.set(el, counts)\n counts[method] = (counts[method] ?? 0) + 1\n}\n\nfunction takeEarlyReplay(event, owner, method) {\n const counts = event && replayedEarly.get(event)?.get(owner)\n if (!counts?.[method]) return false\n counts[method] -= 1\n return true\n}\n\n// Register this controller eagerly OR lazily: with phlex/reactive/early\n// imported, a trigger that fires before connect is replayed on connect (issue\n// #273). The engine auto-pins it with preload: true for importmap apps; see\n// the README for esbuild/webpack.\nexport default class extends Controller {\n static values = {\n token: String, // signed identity token (component + record gid/state)\n }\n\n #tokenCache // freshest token, threaded synchronously across queued requests\n #debounceTimers = new Map() // trigger element -> Map(key -> { timer, flush }) pending run\n #throttleTimers = new Map() // trigger element -> Map(action or record key -> suppression timer)\n #actionPathCache // page-stable action path, resolved once per controller\n #timeoutMsCache // page-stable request timeout (ms), resolved once per controller (issue #101)\n #tokenRegexCache // { id, token, self } — #extractToken's two per-id RegExps, rebuilt on id change (issue #118)\n // Loading-state bookkeeping (issue #99). All keyed so overlapping enqueues\n // refcount correctly and never clobber each other:\n #busyPending = 0 // root aria-busy pending counter (remove only at zero)\n #busyActions = new Map() // action -> in-flight count (root's space-separated busy set + busy_on)\n #busyTokenCounts = new WeakMap() // element -> Map(action -> count): its data-reactive-busy token set\n // Dirty tracking (issue #103): the bound re-scan (turbo:morph-element) and the\n // navigate-away guard handlers, held so disconnect() can remove exactly them.\n // The root-only morph listener of a token root or lazy shell (#275, #312): a morph\n // can add a feature's marker to a connected root. Held for teardown.\n #boundRootMorph\n // Clipboard-trigger availability gate (issue #228): the bound morph re-sync,\n // held for teardown.\n // Client-only drafts (issue #239): the parsed root payload (null when\n // undeclared), the restore-complete latch (no write may run before the\n // connect restore — a connect must never overwrite a draft with server\n // blanks), the ONE per-root trailing-edge write timer, and the bound\n // input/change/turbo:submit-end handlers held for teardown.\n // Feature modules (issue #275). `featuresReady` resolves once the features\n // this root needs have connected (or been given up on: failed, or slower\n // than the timeout) — it never rejects, and is already resolved for a root\n // that needs none. connect() only STARTS the imports. The name is long on\n // purpose: it is a public field, and a short `ready` would shadow a method\n // an app's own subclass may well define.\n // #featureEpoch changes on every connect and disconnect, so an import that\n // resolves for a connection that has since ended connects nothing.\n featuresReady = FEATURES_READY\n #features = new Map() // name -> module connected on this connection\n #featuresWanted = new Set() // names this connection has asked for\n #featuresSettling = false // true while featuresReady is still pending\n #featureGate = null // settles when the last feature that `gates` has connected\n #featureWaits = new Map() // pending import-timeout timer -> its wait's resolve\n #featureHooks = new Map() // name -> [undo, pending] of a feature still on its way\n #featureTurns = new Map() // name -> settles once that feature has had its turn to connect\n #featureEpoch = 0\n #featureHandle // the `core` handle features receive, built on first use\n // The default entry (issue #305): one bit per feature, PERSIST … COUNTDOWN —\n // asked for (its marker read true) and connected on this connection.\n #featuresAsked = 0\n #featuresOn = 0\n\n // Mark that a reactive controller actually connected, so the registration\n // guard above knows the controller was registered (issue #26 part 2).\n connect() {\n reactiveConnected = true\n // Early triggers (issue #273): from here on Stimulus delivers this root's\n // events live (its bindings are already wired), so early.js must stop\n // queueing them NOW — a connect-time seed below (a compute output write)\n // dispatches real input events. The queue itself drains at the very end.\n earlyState().connected.add(this.element)\n rootControllers.set(this.element, this)\n\n // Root-id guard (issue #48). The token round trip assumes the reactive root\n // element's id == component.id: the server targets component.id and the client\n // self-matches its NEXT token by this.element.id (#extractToken, issue #46).\n // If `id:` landed on a CHILD instead of the `**reactive_attrs` root, this id is\n // \"\" — #extractToken falls back to the FIRST token in the response (a child's),\n // so the next action POSTs a foreign token → endpoint default-deny → silent 403.\n // Warn NOW (on connect) so the failure surfaces on page load, not on click 2.\n if (this.element.id === \"\") {\n console.warn(\n \"[phlex-reactive] a reactive root has no id; its next-action token can't self-match \" +\n \"and may fall back to the first token in the response → a silent HTTP 403 on the NEXT action. \" +\n \"Put id: on the SAME element as reactive_attrs — use div(**reactive_root) (emits id + token together), \" +\n \"or div(id:, **reactive_attrs). The id: must NOT be on a child. See the README.\"\n )\n }\n\n // Lazy shells (reactive_lazy, on:, cache:) are wired by the defer feature\n // module (issue #275), which #loadFeatures below starts importing when the\n // root carries one of its markers. What stays here is the root-only morph\n // listener of a TOKEN-BEARING root or a LAZY SHELL: a Turbo morph can turn\n // a root that connected on REAL content (no marker, so no feature) into a\n // shell while it stays connected — no Stimulus lifecycle fires — and only\n // a listener that is already there can notice and load the feature. A\n // shell carries no identity token (a `cache:` one has its URL, issue #306;\n // a plain one its defer token), and a morph can turn it, still connected,\n // into a root that needs another feature (issue #312). It costs a root\n // without any marker, before and after the morph, a few attribute reads and\n // never an import. (turbo:morph-element BUBBLES: only a morph of the root\n // itself counts.) A tokenless, client-only root has no such listener.\n // The same listener hears an editable being focused (issue #351): a stream\n // can append a root's first reactive_editable without morphing the root,\n // and its keys and paste need the bindings feature before anything is\n // typed into it. And it hears a stream that rendered into the root\n // (STREAMED, issue #356): the features already connected re-run their\n // seeds first (a morph's own listeners do that for a morph), then what the\n // new content needs connects.\n if (this.element.getAttribute?.(\"data-reactive-token-value\") != null || deferNeeded(this.element)) {\n this.#boundRootMorph = (event) => {\n if (event.type === \"focusin\" ? !event.target.hasAttribute?.(\"data-reactive-editable\") : event.target !== this.element) return\n if (event.type === STREAMED) this.#reseed()\n if (__SPLIT__) this.#loadFeatures(true)\n else this.#connectFeaturesNow(true)\n }\n this.element.addEventListener?.(\"turbo:morph-element\", this.#boundRootMorph)\n this.element.addEventListener?.(\"focusin\", this.#boundRootMorph)\n this.element.addEventListener?.(STREAMED, this.#boundRootMorph)\n }\n\n // Feature modules (issue #275): connect the ones that are here and START\n // the import of any that is not. HERE, before the seeds below, because\n // this is where their work used to sit: the draft restore (persist) writes\n // the values those seeds read, the dirty baseline (form) comes before\n // them. A module that is still on its way connects when it arrives and\n // re-runs the seeds itself (#reseed). Never awaited — connect() must reach\n // the drain at the end in the same task (issue #274: an await before it\n // runs a waking click twice).\n // The editables' server texts (issue #351), before a draft restore\n // writes into them.\n this.element.querySelectorAll?.(\"[data-reactive-editable]\").forEach(seedServerText)\n\n this.#featureEpoch++\n this.featuresReady = FEATURES_READY\n if (__SPLIT__) this.#loadFeatures()\n else this.#connectFeaturesNow()\n\n // A dialog the server rendered open with data-reactive-modal (issue #365).\n upgradeModals(this.element)\n\n // LAST, after every feature above is wired: a replayed trigger must find\n // the controller exactly as a live event after connect would.\n this.#announceConnected()\n }\n\n // The default entry (issue #305): every feature is in this file, so each\n // one this root's markers ask for connects now, by a direct call, in the\n // order the opt-in entry's table gives (persist first: its restore writes\n // the values the later seeds read). Again after a morph of the root, for a\n // marker the morph added. The features with no per-root connect (effects,\n // hints, devtools) act when called.\n #connectFeaturesNow(morphed) {\n if (!__SPLIT__) {\n this.#connectFeatureNow(PERSIST, \"persist\", persistNeeded, (core) => persistFeature.connect(this, core, morphed))\n this.#connectFeatureNow(DEFER, \"defer\", deferNeeded, (core) => deferFeature.connect(this, core, morphed))\n this.#connectFeatureNow(FORM, \"form\", formNeeded, (core) => formFeature.connect(this, core, morphed))\n this.#connectFeatureNow(BINDINGS, \"bindings\", bindingsNeeded, (core) => bindingsFeature.connect(this, core, morphed))\n this.#connectFeatureNow(COMPUTE, \"compute\", computeNeeded, (core) => computeFeature.connect(this, core, morphed))\n this.#connectFeatureNow(SORTABLE, \"sortable\", sortableNeeded, (core) => sortableFeature.connect(this, core))\n this.#connectFeatureNow(DRAG, \"drag\", dragNeeded, (core) => dragFeature.connect(this, core))\n this.#connectFeatureNow(PRESENCE, \"presence\", presenceNeeded, (core) => presenceFeature.connect(this, core))\n this.#connectFeatureNow(COUNTDOWN, \"countdown\", countdownNeeded, (core) => countdownFeature.connect(this, core))\n }\n }\n\n // Once per connection: a marker check that throws loses that feature (and\n // is read again after a morph), a connect that throws loses it until the\n // root reconnects — never the rest of connect().\n #connectFeatureNow(bit, name, needs, connect) {\n if (!__SPLIT__) {\n if (this.#featuresAsked & bit) return\n try {\n if (!needs(this.element)) return\n } catch (error) {\n return this.#featureFailed(name, \"detect\", error)\n }\n this.#featuresAsked |= bit\n try {\n connect(this.#featureCore())\n this.#featuresOn |= bit\n } catch (error) {\n this.#featureFailed(name, \"connect\", error)\n }\n }\n }\n\n // FIRST in disconnect(), in connect order, while the root is still intact\n // (the draft flush reads its fields).\n #disconnectFeaturesNow() {\n if (!__SPLIT__) {\n const on = this.#featuresOn\n this.#featuresAsked = this.#featuresOn = 0\n const core = this.#featureCore()\n if (on & PERSIST) this.#disconnectFeatureNow(\"persist\", () => persistFeature.disconnect(this, core))\n if (on & DEFER) this.#disconnectFeatureNow(\"defer\", () => deferFeature.disconnect(this, core))\n if (on & FORM) this.#disconnectFeatureNow(\"form\", () => formFeature.disconnect(this, core))\n if (on & BINDINGS) this.#disconnectFeatureNow(\"bindings\", () => bindingsFeature.disconnect(this, core))\n if (on & COMPUTE) this.#disconnectFeatureNow(\"compute\", () => computeFeature.disconnect(this, core))\n if (on & SORTABLE) this.#disconnectFeatureNow(\"sortable\", () => sortableFeature.disconnect(this, core))\n if (on & DRAG) this.#disconnectFeatureNow(\"drag\", () => dragFeature.disconnect(this, core))\n if (on & PRESENCE) this.#disconnectFeatureNow(\"presence\", () => presenceFeature.disconnect(this, core))\n if (on & COUNTDOWN) this.#disconnectFeatureNow(\"countdown\", () => countdownFeature.disconnect(this, core))\n }\n }\n\n #disconnectFeatureNow(name, disconnect) {\n if (!__SPLIT__) {\n try {\n disconnect()\n } catch (error) {\n console.error(`[phlex-reactive] the \"${name}\" feature module failed to disconnect`, error)\n }\n }\n }\n\n // Starts the import of every feature this root needs and has not asked for\n // yet — at connect, and again after a morph of the root (which may have\n // added a marker; `morphed`). Every import starts now; each feature connects\n // when its own module has arrived (or is given up on) AND the features\n // before it in the table have had their turn — the order their connect-time\n // seeds depend on, never the order the network delivered them in — unless\n // this connection ended meanwhile.\n #loadFeatures(morphed) {\n if (__SPLIT__) {\n const epoch = this.#featureEpoch\n const names = []\n for (const [name, [needs]] of FEATURES) {\n if (!needs || this.#featuresWanted.has(name)) continue\n // Loaded, and with nothing to do per root: its marker need not be read.\n const loaded = featureModules.get(name)\n if (loaded && !loaded.connect) continue\n // A marker check that throws loses that feature, never the rest of\n // connect() — above all not the early drain that follows it.\n try {\n if (needs(this.element)) names.push(name)\n } catch (error) {\n this.#featureFailed(name, \"detect\", error)\n }\n }\n if (names.length === 0) return\n for (const name of names) this.#featuresWanted.add(name)\n // Every module already here (a later root, the next Turbo visit): connect\n // now, in this task — nothing to wait for, so nothing to gate or time out.\n if (!this.#featuresSettling && names.every((name) => featureModules.has(name))) {\n for (const name of names) this.#connectFeature(epoch, name, featureModules.get(name), morphed)\n return\n }\n for (const name of names) {\n const arrival = this.#awaitFeature(epoch, name)\n // Its turn comes after the features BEFORE it in the table that this\n // root is still waiting for — never after a later one, even one whose\n // import started earlier (a morph can add an earlier feature's marker).\n const earlier = []\n for (const key of FEATURES.keys()) {\n if (key === name) break\n if (this.#featureTurns.has(key)) earlier.push(this.#featureTurns.get(key))\n }\n const turn = Promise.all(earlier)\n .then(() => arrival)\n .then((feature) => feature && this.#connectFeature(epoch, name, feature, morphed))\n this.#featureTurns.set(name, turn)\n if (FEATURES.get(name)[3]) this.#featureGate = turn\n }\n // Requests stop waiting the moment the last gating feature has connected.\n const gate = this.#featureGate\n gate?.then(() => {\n if (this.#featureGate === gate) this.#featureGate = null\n })\n this.#featuresSettling = true\n const ready = Promise.all(this.#featureTurns.values()).then(() => {\n if (this.featuresReady === ready) this.#featuresSettling = false\n })\n this.featuresReady = ready\n }\n }\n\n // One feature's import, for one scan: resolves with the module, or with\n // null once the import failed or outlasted the timeout — so one slow or\n // broken feature never holds back the others. A module that arrives after\n // its timeout still connects (late, and so out of table order).\n #awaitFeature(epoch, name) {\n if (__SPLIT__) {\n const current = () => epoch === this.#featureEpoch\n this.#startWaitingFor(name)\n return new Promise((resolve) => {\n let timedOut = false\n const timer = setTimeout(() => {\n this.#featureWaits.delete(timer)\n timedOut = true\n if (current()) this.#featureFailed(name, \"timeout\", new Error(`not loaded after ${featureTimeoutMs()} ms`))\n resolve(null)\n }, featureTimeoutMs())\n // Kept with its resolve: a disconnect ends the wait (#disconnectFeatures),\n // or whatever is queued behind featuresReady would hang on a stuck import.\n this.#featureWaits.set(timer, resolve)\n const settled = () => {\n clearTimeout(timer)\n this.#featureWaits.delete(timer)\n }\n loadFeature(name).then(\n (feature) => {\n settled()\n // Late: connect one microtask on, after whatever else was queued on\n // this import while the root waited.\n if (timedOut) queueMicrotask(() => this.#connectFeature(epoch, name, feature))\n else resolve(feature)\n },\n (error) => {\n settled()\n if (current()) this.#featureFailed(name, \"load\", error)\n resolve(null)\n },\n )\n })\n }\n }\n\n // Run the feature's `waiting` hook (if it has one) and remember its undo and\n // what it records, for #connectFeature or #disconnectFeatures to hand on.\n #startWaitingFor(name) {\n if (__SPLIT__) {\n const hook = FEATURES.get(name)[2]\n if (!hook) return\n const pending = {}\n try {\n this.#featureHooks.set(name, [hook(this.element, pending), pending])\n FEATURE_SHARED.waiting.set(this.element, { ...FEATURE_SHARED.waiting.get(this.element), [name]: pending })\n } catch (error) {\n this.#featureFailed(name, \"detect\", error)\n }\n }\n }\n\n // The wait is over (the feature is here, or the root is leaving): undo the\n // hook and return what it recorded. The shared record goes with it unless\n // `abandoning`: a root that leaves keeps its record until abandon() has run,\n // so anything else queued on the same import still finds it.\n #stopWaitingFor(name, abandoning) {\n if (__SPLIT__) {\n const [undo, pending] = this.#featureHooks.get(name) ?? []\n this.#featureHooks.delete(name)\n if (!abandoning) forgetWaiting(this.element, name, pending)\n try {\n undo?.()\n } catch (error) {\n console.error(`[phlex-reactive] the \"${name}\" feature module failed to stop waiting`, error)\n }\n return pending\n }\n }\n\n #connectFeature(epoch, name, feature, morphed) {\n if (__SPLIT__) {\n if (epoch !== this.#featureEpoch) return\n const pending = this.#stopWaitingFor(name)\n try {\n feature.connect?.(this, this.#featureCore(), morphed, pending)\n this.#features.set(name, feature)\n } catch (error) {\n this.#featureFailed(name, \"connect\", error)\n }\n }\n }\n\n // The `core` handle a feature receives (see \"Feature modules\" above).\n #featureCore() {\n this.#featureHandle ??= {\n emit: (name, detail, options) => this.#emit(name, detail, options),\n reseed: () => this.#reseed(),\n // Resolves with the reply's HTML once the request has applied, or with\n // nothing when it failed or was vetoed. `busy` is on(busy:)'s hint.\n proceed: (target, action, params, busy) => this.#proceed(target, action, params, 0, 0, null, busy),\n forgetToken: () => {\n this.#tokenCache = undefined\n },\n owns: (el) => this.#ownsField(el),\n ownership: () => this.#ownershipFilter(),\n opTargets: (args) => this.#opTargets(args),\n diagnose: (label, args) => this.#diagnoseZeroTargets(label, args),\n // Apply an op list root-scoped, with the zero-target diagnostics; a\n // missing to: defaults to `defaultTo` (the reducer / completion-binding\n // convention is \"@root\").\n applyOps: (list, defaultTo) =>\n applyOps(\n list,\n (args) => this.#opTargets(defaultTo != null && args.to == null ? { ...args, to: defaultTo } : args),\n (name, args) => this.#diagnoseZeroTargets(`client op \"${name}\"`, args),\n ),\n listnavOptions: (event) => this.#listnavOptions(event),\n collectFields: () => this.#collectFields(),\n // A reactive_editable's value and its last server-rendered text (#351),\n // and whether the engine has contenteditable=\"plaintext-only\" (#355).\n plain: plaintextSupported,\n text: editableValue,\n served: serverText,\n // Copy one <img> onto another (issue #373): the reactive_media binding.\n copyMedia,\n // set_value's write (issue #374): reactive_show clear: (issue #394).\n setValue: setFieldValue,\n // The confirm gate, as dispatch() runs it: the resolver inside the chain\n // (a synchronous throw is a cancel), never a rejection out.\n confirm: (message, context) =>\n Promise.resolve()\n .then(() => confirmResolver(message, context))\n .catch(() => false),\n }\n return this.#featureHandle\n }\n\n // Re-run the connect-time seeds that read field values, in connect() order\n // — for a feature that changed those values after connect() ran (the draft\n // restore), or content a stream rendered into the root (issue #356). Each is\n // the same re-sync its feature runs after a morph; a root that did not opt\n // into one skips it. on-complete re-ARMS without firing. Form and bindings\n // also wire a binding whose gate reads true only now (a stream's content).\n #reseed() {\n if (!__SPLIT__) {\n if (this.#featuresOn & FORM) formFeature.reseed(this)\n if (this.#featuresOn & BINDINGS) bindingsFeature.reseed(this)\n if (this.#featuresOn & COMPUTE) computeFeature.seed(this)\n } else {\n this.#features.get(\"form\")?.reseed(this)\n this.#features.get(\"bindings\")?.reseed(this)\n this.#features.get(\"compute\")?.seed(this)\n }\n }\n\n // A feature that is missing leaves its part of the root dead: say so on\n // every root it costs (reactive:error, the error marker), and once in the\n // console. `phase` is \"detect\", \"load\", \"timeout\" or \"connect\".\n #featureFailed(name, phase, error) {\n logFeatureFailure(name, phase, error)\n this.#markError(\"feature\")\n // A lazy shell whose module will never come (a failed import stays failed\n // until the page is reloaded) must not go on shimmering as if it loaded.\n if (phase === \"load\" && this.element.getAttribute?.(\"data-reactive-defer-pending\")) {\n this.element.removeAttribute(\"data-reactive-defer-pending\")\n this.element.removeAttribute(\"aria-busy\")\n }\n this.#emit(\"reactive:error\", { kind: \"feature\", feature: name, phase, error })\n }\n\n // Runs FIRST in disconnect(), in table order, while the root is still\n // intact (the draft flush reads its fields). A feature whose disconnect\n // throws must not keep the others, or the rest of disconnect(), from running.\n #disconnectFeatures() {\n if (__SPLIT__) {\n this.#featureEpoch++\n // End every wait still open: nothing will connect on this connection, and\n // a request queued behind featuresReady must not hang on a stuck import.\n for (const [timer, resolve] of this.#featureWaits) {\n clearTimeout(timer)\n resolve(null)\n }\n this.#featureWaits.clear()\n // A feature this root was still waiting for never connected here: hand it\n // what its hook recorded, once (and if) the module arrives.\n for (const name of [...this.#featureHooks.keys()]) {\n const pending = this.#stopWaitingFor(name, true)\n const root = this.element\n withFeature(name, (feature) => {\n feature.abandon?.(root, pending)\n forgetWaiting(root, name, pending)\n })\n }\n this.#featuresWanted.clear()\n this.#featureTurns.clear()\n this.#featuresSettling = false\n this.#featureGate = null\n const connected = [...this.#features]\n this.#features.clear()\n for (const [name, feature] of connected) {\n try {\n feature.disconnect?.(this, this.#featureCore())\n } catch (error) {\n console.error(`[phlex-reactive] the \"${name}\" feature module failed to disconnect`, error)\n }\n }\n }\n }\n\n // Early triggers (issue #273): mark the root (the attribute is for CSS and\n // tests; early.js trusts the WeakSet joined at the top of connect()),\n // announce it with a bubbling reactive:connect, then replay its queued triggers.\n #announceConnected() {\n // The attribute is a connect-time marker only: an in-place morph writes\n // the server's attributes back and strips it (re-marking would cost every\n // root a morph listener — the \"a root that never opted in pays nothing\"\n // contract). The connected WeakSet is the truth; reactive:connect the signal.\n this.element.setAttribute?.(\"data-reactive-connected\", \"\")\n // Raw dispatch (as #emit), on the root only: connect() runs on an attached\n // element, so there is no detached-node fallback to make.\n if (this.element.isConnected) {\n this.element.dispatchEvent?.(\n new CustomEvent(\"reactive:connect\", { bubbles: true, composed: true, detail: { id: this.element.id } }),\n )\n }\n this.#drainEarly()\n // Issue #410: dispatches a client-only root inside handed over before this\n // root connected (a dormant root woken by that very trigger).\n // currentTarget is null once propagation ended: pin the trigger back on.\n for (const [event, target] of heldForwards.get(this.element) ?? []) {\n if (event.currentTarget !== target) Object.defineProperty(event, \"currentTarget\", { value: target, configurable: true })\n this.dispatch(event)\n }\n heldForwards.delete(this.element)\n }\n\n // The trigger elements whose :once descriptor THIS connection replayed —\n // forgotten on disconnect (see disconnect()).\n #earlySpentOn = new Set()\n\n // Takes this root's entries — and those of any root that left the page\n // before connecting (replaced by a stream), which no controller would ever\n // claim.\n #drainEarly() {\n const { queue } = earlyState()\n if (queue.length === 0) return\n const mine = []\n for (let i = queue.length - 1; i >= 0; i--) {\n const { root } = queue[i]\n if (root === this.element || !root.isConnected) mine.unshift(...queue.splice(i, 1))\n }\n const ttl = earlyTtlMs()\n // Two module instances of early.js (a bundled copy beside the pinned one)\n // each queue the same event: replay an (event, element) pair once. (One\n // event OBJECT dispatched twice on one element before connect also counts\n // once — indistinguishable here.) An element bound to both `click` and\n // `click@window` is heard by both listeners live, so its window-bound\n // entry (issue #303) is a separate pair.\n const replayed = new Map()\n for (const entry of mine) {\n const pair = replayed.get(entry.event) ?? [new Set(), new Set()]\n replayed.set(entry.event, pair)\n const seen = pair[+!!entry.win]\n if (seen.has(entry.el)) continue\n seen.add(entry.el)\n const limit = entry.win ? Math.min(WINDOW_EARLY_TTL_MS, ttl) : ttl\n const reason =\n entry.root !== this.element\n ? \"its root left the page before a controller connected\"\n : performance.now() - entry.at > limit\n ? `it is older than the ${limit} ms ${entry.win ? \"window-trigger\" : \"early-event\"} TTL`\n : entry.el.isConnected && this.element.contains(entry.el)\n ? null\n : \"its element left the root before the controller connected\"\n if (reason) {\n if (this.#verboseEnabled()) console.warn(`[phlex-reactive] dropped an early \"${entry.event.type}\" trigger: ${reason}`)\n continue\n }\n this.#replayEarly(entry)\n }\n }\n\n // One queued event, replayed once per matching descriptor — Stimulus calls\n // each binding with the SAME event object, so runOps' duplicate-binding\n // guard behaves as it does live. Each descriptor is re-checked here, where\n // Stimulus would check it: it must still be on the element (a morph may\n // have removed it), its key filter must match under the app's own key\n // mappings (early.js knows only Stimulus's defaults), and a :once one runs a single time however often it\n // was queued (spendEarlyOnce).\n #replayEarly({ event, el, descs, win }) {\n const replay = earlyReplayEvent(event, el, win)\n const keyMappings = this.application?.schema?.keyMappings\n const tokens = (el.getAttribute(\"data-action\") ?? \"\").split(/\\s+/)\n // A window-bound entry belongs to this root, not to `el` (issue #303).\n const owner = win ? this.element : el\n for (const desc of descs) {\n if (!tokens.includes(desc.token)) continue\n if (desc.filter && !keyFilterMatches(desc.filter, event, keyMappings)) continue\n // (`:once` is read off the token: early.js keeps its records minimal.)\n if (/#\\w+.*:once\\b/.test(desc.token)) {\n if (!spendEarlyOnce(owner, desc, win && JSON.stringify(replay.params))) continue\n this.#earlySpentOn.add(owner)\n }\n // The original may still be propagating (issue #274): its live arrival at\n // `el` — or at the window, for a window-bound entry — must not run this\n // binding again (earlyOnceSwallows).\n markEarlyReplay(event, owner, win ? `@${desc.method}` : desc.method)\n if (desc.method === \"runOps\") this.runOps(replay)\n else this.dispatch(replay)\n }\n }\n\n // Tear down any pending debounce timers when the controller leaves the DOM\n // (Turbo morph/navigation removes the element). Otherwise a timer that hasn't\n // fired yet would later call #enqueue on a disconnected controller — a round\n // trip against a detached element / stale token (issue #17 follow-up).\n // Throttle suppression timers (issue #80) are torn down the same way — a\n // leading-edge timer holds no pending POST, but leaving it running would leak\n // it past the element's life.\n disconnect() {\n // Features FIRST (issue #275): the persist feature flushes a pending draft\n // write while the fields are still readable (Turbo disconnects before\n // leaving the page — a fast visit otherwise loses the last keystrokes).\n if (__SPLIT__) this.#disconnectFeatures()\n else this.#disconnectFeaturesNow()\n this.#clearAllDebounces()\n this.#clearAllThrottles()\n if (this.#boundRootMorph) {\n this.element.removeEventListener?.(\"turbo:morph-element\", this.#boundRootMorph)\n this.element.removeEventListener?.(\"focusin\", this.#boundRootMorph)\n this.element.removeEventListener?.(STREAMED, this.#boundRootMorph)\n }\n // Early triggers (issue #273): a disconnected root records again.\n earlyState().connected.delete(this.element)\n if (rootControllers.get(this.element) === this) rootControllers.delete(this.element)\n this.element.removeAttribute?.(\"data-reactive-connected\")\n // A spent :once replay is remembered per element so a morph REPLY (root\n // still connected) cannot re-arm it. A disconnect drops Stimulus's own\n // `once` listeners and the next connect binds fresh ones, so the memory\n // goes too (issue #274: a dormant morph-back disconnects a root in place —\n // its :once trigger must work again after the re-wake).\n for (const el of this.#earlySpentOn) spentEarlyOnce.delete(el)\n this.#earlySpentOn.clear()\n }\n\n // Serialize requests per component. Each round trip rewrites the signed\n // token in the DOM (state lives in the token, not the client). If events\n // fire faster than round trips complete, concurrent requests would all read\n // the SAME stale token and clobber each other (last-write-wins). Chaining on\n // a per-controller promise makes each dispatch wait for the previous one, so\n // it always uses the freshest token.\n dispatch(event) {\n // Issue #410: a client-only root has no action of its own — a server\n // trigger inside it belongs to the token-bearing root above. FIRST, so that\n // root runs every check below with its own element.\n if (event.params?.action && event.params.action !== LAZY_MATERIALIZE_ACTION && this.#clientOnly()) {\n return this.#forwardToServerRoot(event)\n }\n // A shortcut (issue #357) that is the other platform's twin, or pressed\n // in a field the user is typing in, is a complete no-op: the native\n // default (text undo) proceeds and nothing is announced. Checked FIRST: a\n // delete/backspace shortcut (issue #366) binds a bare window keydown, so\n // every key the user presses lands here.\n const shortcut = event.params?.shortcut\n if (shortcut != null && !shortcutApplies(shortcut, event, this.application?.schema?.keyMappings)) return\n // A :once trigger already replayed on connect (issue #273) is spent.\n if (earlyOnceSwallows(event, \"dispatch\", this.application?.schema?.keyMappings, this.element)) return\n // `window` (renamed: never shadow the global) and `outside` are the event-\n // modifier params (issue #80). The client decides preventDefault behavior\n // from event.params — set by the Ruby on() — never by sniffing the\n // Stimulus descriptor.\n const { action, params, debounce, throttle, confirm, confirmWhen, outside, window: windowBound, optimistic } =\n event.params\n if (!action) return\n\n // The pending-state hint (issue #181): data-reactive-busy-param. During a\n // deploy overlap a page rendered by the PREVIOUS gem still emits the old\n // data-reactive-loading-param — read it as a fallback so an in-flight page\n // keeps its pending affordance until the next full render (the hints\n // feature remaps its `class:` key).\n const busy = event.params.busy ?? event.params.loading\n\n // Outside guard FIRST (issue #80): an outside: trigger only fires for\n // events whose target is OUTSIDE this component's ROOT (containment against\n // this.element — .contains includes the root itself). An event inside the\n // root must be a COMPLETE no-op — before preventDefault (the page's native\n // click behavior is untouched) and before the reactive:before-dispatch\n // lifecycle event (nothing to announce, nothing to veto).\n if (outside && this.element.contains(event.target)) return\n\n // The trigger is event.currentTarget — the element on(...) was spread onto —\n // NOT event.target (issue #99). A `<button><span>Save</span></button>` click\n // has target === the span, which carries no params and is the wrong element\n // to disable / swap text on. currentTarget is the bound element; fall back to\n // target for a directly-invoked/synthetic event. Captured now because\n // #proceed runs in a later microtask (after the confirm resolver), by which\n // point currentTarget is reset to null.\n const target = event.currentTarget ?? event.target\n\n // Stop native behavior (button submit / FORM NAVIGATION) HERE, synchronously\n // within the event dispatch — BEFORE the (possibly async) confirm gate below.\n // preventDefault() only works while the event is still being handled; once we\n // await the confirm resolver it's too late, and a `submit` trigger would\n // natively POST the form and navigate before the reactive round trip runs\n // (issue #11). For a `click` trigger there's no default to miss. This holds\n // for debounced triggers too — the round trip is deferred, but the native\n // default must still be prevented now. (Moved ahead of the confirm branch in\n // issue #55: an async resolver means we can't preventDefault after awaiting.)\n //\n // ONLY for element-bound triggers: a window-bound trigger (window:/outside:,\n // issue #80) hears EVERY matching event on the page — preventDefault-ing\n // those would kill every link click while a dropdown is mounted. The page's\n // native behavior proceeds alongside the reactive round trip.\n //\n // The `checked: :keep` optimistic hint (issue #98) OPTS OUT: for a click-bound\n // checkbox/radio the unconditional preventDefault is exactly what stops the\n // native flip from happening before the morph — so a bare checkbox click\n // (which has no form-navigation default to lose) skips it and flips now, and\n // the failure revert snaps it back. A `change`-bound trigger is unaffected —\n // `change` isn't cancelable, so preventDefault was already a no-op there.\n //\n // A shortcut (issue #357) IS prevented: its key filter has already narrowed\n // the window binding to one chord the page claims (mod+s must not also open\n // the browser's save dialog).\n if ((shortcut != null || !windowBound) && !this.#keepsNativeToggle(optimistic, target)) event.preventDefault()\n\n // A reactive_lazy(on:) shell's trigger (issue #276) goes through the one\n // materialize entry point, which dedupes it against the observer, the\n // re-armed listener and a morph-back. That entry point lives in the defer\n // feature (issue #275): the synchronous part of this dispatch is done, and\n // the load itself waits for the feature while it is still on its way.\n if (action === LAZY_MATERIALIZE_ACTION) {\n // Without the feature (it failed to load) a shell can still load the\n // plain way: the signed __materialize POST. A `cache:` shell carries no\n // token (issue #306) and has no such way: the feature's reactive:error\n // already said so, and nothing is sent.\n const materialize = () => {\n // (A shell whose defer connect threw has nothing wired: the plain POST.)\n if (!__SPLIT__) {\n if (this.#featuresOn & DEFER) return deferFeature.materialize(this)\n } else {\n const defer = this.#features.get(\"defer\")\n if (defer) return defer.materialize(this)\n }\n if (this.tokenValue) return this.#proceed(target, action, \"{}\")\n }\n return this.#featuresSettling ? this.featuresReady.then(materialize) : materialize()\n }\n\n // Resolve the EFFECTIVE confirm message (issue #179): a plain string confirm:\n // is that string (static, #52); a Hash confirm: (confirmWhen) evaluates its\n // condition/predicate over the collected fields and returns the message ONLY\n // when it fires, else null → no dialog. No confirm at all → also null. The\n // conditional form is the bindings feature's: on the opt-in client its\n // answer may come a moment later (a promise), once the module is here.\n const message = this.#effectiveConfirmMessage(confirm, confirmWhen)\n const proceed = () => this.#proceed(target, action, params, debounce, throttle, optimistic, busy)\n\n // No message → proceed straight away (unchanged fast path).\n if (!message) return proceed()\n if (message instanceof Promise) {\n return message.then((resolved) => (resolved ? this.#confirmThen(resolved, target, proceed) : proceed()))\n }\n this.#confirmThen(message, target, proceed)\n }\n\n // The confirmation gate (issue #52, made overridable + async in #55). A\n // reactive trigger can't use Hotwire's data-turbo-confirm — this controller\n // preempts the event — so a `confirm:` message routes through\n // confirmResolver (default window.confirm; an app can override it to reuse\n // Turbo.config.forms.confirm). The resolver may be sync or async; call it\n // INSIDE the chain (via the leading .then) so even a SYNCHRONOUS override\n // throw rejects this promise instead of escaping dispatch — a throwing\n // dialog is treated as a cancel, like the user dismissing it. The .catch is\n // scoped to the resolver step (→ false = cancel), so a dismissed/erroring\n // dialog never surfaces as an unhandled rejection AND a genuine bug inside\n // #proceed is NOT silently swallowed. Enqueue ONLY on a truthy resolution —\n // nothing is enqueued, no timer scheduled, otherwise. The resolver's\n // optional 2nd arg (issue #222) carries the trigger element, so an override\n // has the same ctx shape here as on nestedRemove ({ el, … }).\n #confirmThen(message, target, proceed) {\n return Promise.resolve()\n .then(() => confirmResolver(message, { el: target }))\n .catch(() => false)\n .then((ok) => {\n if (ok) proceed()\n })\n }\n\n // The effective confirm message (issue #179): the static string; or, for a\n // conditional confirm, what the bindings feature says — now when the module\n // is here, else a promise of it (the opt-in client's import window); or\n // null when neither applies. A module that cannot load, or is slower than\n // the feature timeout, answers null: no dialog, the endpoint's\n // authorize/default-deny is the real gate.\n #effectiveConfirmMessage(confirm, confirmWhen) {\n if (confirm) return confirm\n if (!confirmWhen) return null\n if (!__SPLIT__) return bindingsFeature.confirmMessage(this, this.#featureCore(), confirmWhen)\n else {\n const loaded = featureModules.get(\"bindings\")\n if (loaded) return loaded.confirmMessage(this, this.#featureCore(), confirmWhen)\n return this.#awaitFeatureOrNull(\"bindings\").then(\n (bindings) => bindings && bindings.confirmMessage(this, this.#featureCore(), confirmWhen),\n )\n }\n }\n\n // A feature's module, or null once its import failed (logged) or outlasted\n // the feature timeout — for the two places a REQUEST waits on an import\n // without a root connection to wait with (a hint, a conditional confirm).\n #awaitFeatureOrNull(name) {\n if (__SPLIT__) {\n let timer\n return Promise.race([\n loadFeature(name).catch((error) => (logFeatureFailure(name, \"load\", error), null)),\n new Promise((resolve) => (timer = setTimeout(() => resolve(null), featureTimeoutMs()))),\n ]).finally(() => clearTimeout(timer))\n }\n }\n\n\n // A tokenless client-only root (issue #410). tokenValue is the Stimulus view\n // of data-reactive-token-value; the attribute check also rules out a shell.\n #clientOnly() {\n return !this.tokenValue && clientOnlyRoot(this.element)\n }\n\n // Hand a server trigger to the nearest token-bearing root above (issue #410).\n // A dormant one is woken (as early.js wakes a root on its own trigger) and\n // runs the dispatch when it connects. With no such root nothing is sent.\n #forwardToServerRoot(event) {\n const root = serverRoot(this.element.parentElement, ANY_ROOT)\n if (!root) {\n if (this.element.closest?.('[data-reactive-verbose=\"true\"], [data-reactive-debug=\"true\"]'))\n console.warn(`[phlex-reactive] \"${event.params.action}\": no token on this root or above, nothing sent`)\n return\n }\n const controller = rootControllers.get(root)\n if (controller) return controller.dispatch(event)\n // Held past this event's dispatch: cancel its native default NOW, by\n // dispatch()'s own rule, or a submit/link would act before the request.\n const { shortcut, window: windowBound, optimistic } = event.params\n const target = event.currentTarget ?? event.target\n if ((shortcut != null || !windowBound) && !this.#keepsNativeToggle(optimistic, target)) event.preventDefault()\n heldForwards.set(root, [...(heldForwards.get(root) ?? []), [event, target]])\n const data = root.dataset\n if (data.reactiveDormant) {\n data.controller = `${data.controller ?? \"\"} ${data.reactiveDormant}`.trim()\n delete data.reactiveDormant\n }\n }\n\n // CLIENT-ONLY trigger entry point (issue #95) — the zero-round-trip sibling\n // of dispatch(). Wired by on_client: applies the declared op chain\n // (data-reactive-ops-param, built by Phlex::Reactive::JS) locally. NO token,\n // NO params, NO fetch, ever. Ops are ephemeral UI: any server re-render of\n // the component resets whatever they toggled (by design — a signed action\n // owns state that must survive re-renders).\n runOps(event) {\n // A lone shortcut record (Stimulus typecasts it to an object) whose chord\n // did not fire bails before any bookkeeping: a delete/backspace shortcut\n // (issue #366) binds a bare window keydown that hears every key. Several\n // records are checked one by one below.\n const lone = event.params?.ops\n if (lone?.shortcut != null && !shortcutApplies(lone.shortcut, event, this.application?.schema?.keyMappings)) return\n if (earlyOnceSwallows(event, \"runOps\", this.application?.schema?.keyMappings, this.element)) return\n if (bindingsAlreadyRan(event, this)) return\n const params = event.params ?? {}\n // The trigger element on_client was spread onto (issue #222 ctx: { el }),\n // captured now — currentTarget resets before the confirm resolver's microtask.\n const trigger = event.currentTarget ?? event.target\n // Issue #271: run only the binding record(s) whose descriptor fired. A\n // legacy [[op, args]] attr reads its flags from the element-wide params.\n const records = parseBindingRecords(params.ops)\n // Stimulus already applied the firing descriptor's key filter (custom\n // schema keys included), so a lone candidate on type + window-boundness\n // runs without a second key check; several same-type candidates are told\n // apart by their key filters, read through the app's Stimulus schema.\n const candidates = records.filter((record) => bindingMatches(record, event, null))\n const matching =\n candidates.length <= 1\n ? candidates\n : candidates.filter((record) => bindingMatches(record, event, this.application?.schema?.keyMappings))\n if (matching.length === 0 && records.length > 0) {\n // Issue #271: a hand-edited attr or a descriptor the matcher doesn't\n // know. Verbose gate only (the devtools feature dedupes).\n if (this.#verboseEnabled()) {\n if (__SPLIT__) this.#devtools((devtools) => devtools.noBinding(this, event))\n else devtoolsFeature.noBinding(this, event)\n }\n return\n }\n for (const record of matching) {\n // An early replay never runs an outside: record (issue #303: an outside\n // click before connect had nothing to close).\n if (record.outside && event[EARLY_KEY]) continue\n // A detail miss (issue #346) is a complete no-op — checked before the\n // once record is spent, preventDefault and the confirm gate.\n if (!detailMatches(record, event)) continue\n // So is a shortcut that is not this platform's twin or fired in an\n // editable target (issue #357).\n if (record.shortcut != null && !shortcutApplies(record.shortcut, event, this.application?.schema?.keyMappings))\n continue\n if (onceBindingSpent(this, event, record)) continue\n // A legacy attr reads its flags element-wide — but never a mix-ed on()'s\n // debounce/throttle params (issue #393): those belong to the dispatch.\n this.#runBinding(\n record.legacy ? { ...params, ops: record.ops, debounce: undefined, throttle: undefined } : record,\n event,\n trigger,\n records.indexOf(record),\n )\n }\n }\n\n // One on_client binding (issue #95): its outside guard, preventDefault rule,\n // confirm gate, then its ops — every flag read from the binding itself.\n #runBinding(record, event, trigger, ordinal) {\n const { ops, confirm, confirmWhen, outside, window: windowBound, shortcut } = record\n // Outside guard FIRST — identical semantics to dispatch() (issue #80): an\n // outside: trigger is a COMPLETE no-op for events inside this root, before\n // preventDefault and before any op runs.\n if (outside && this.element.contains(event.target)) return\n\n // Element-bound triggers preventDefault (a bare button inside a <form>\n // must not submit it); window-bound triggers (window:/outside:) never do —\n // they hear every matching event on the page, and preventDefault-ing those\n // would kill native clicks site-wide (issue #80 rationale). Runs BEFORE the\n // (possibly async) confirm gate below — a native default can't wait for a\n // pending dialog (same ordering as dispatch()).\n // A shortcut (issue #357) is prevented: it is one chord the page claims.\n if (shortcut != null || !windowBound) event.preventDefault()\n\n // Resolve the effective confirm message — static string, or the conditional\n // Hash form (issue #179) evaluated over collected fields (a promise of it\n // on the opt-in client while the bindings module is on its way). Null →\n // no dialog. The gate is here (the user gesture), NOT in #applyOps: that\n // applier is shared with the server-pushed reactive:js stream action,\n // which must NEVER prompt. The same confirmResolver gate on(:action,\n // confirm:) uses (issues #52/#55/#178), so a themed dialog covers both.\n const message = this.#effectiveConfirmMessage(confirm, confirmWhen)\n const apply = this.#waitedOps(record, ordinal, trigger, () => this.#applyOps(this.#parseOps(ops)))\n if (!message) return apply()\n if (message instanceof Promise) {\n return message.then((resolved) => (resolved ? this.#confirmThen(resolved, trigger, apply) : apply()))\n }\n this.#confirmThen(message, trigger, apply)\n }\n\n // Issue #393: an on_client record's debounce:/throttle: — on()'s timers\n // (#debounce trailing, #throttle leading), keyed on the trigger + the\n // record's ordinal + JSON (two identical mix-ed records keep their own\n // timers), so disconnect clears them with the dispatch ones. The wait sits\n // after the outside guard, preventDefault and confirm, as on()'s does.\n #waitedOps(record, ordinal, trigger, run) {\n const debounce = Number(record.debounce) || 0\n const throttle = Number(record.throttle) || 0\n if (debounce <= 0 && throttle <= 0) return run\n const key = JSON.stringify([ordinal, record])\n if (debounce > 0) return () => this.#debounce(trigger, key, debounce, run)\n return () => this.#throttle(trigger, key, throttle, run)\n }\n\n // Client-side compute (issue #104) is the compute feature's (issue #275,\n // features/compute.js). This is the method its descriptor names\n // (input->reactive#recompute), so it stays. While the module is on its way\n // (the opt-in client) the entry records the edit, and the module runs one\n // recompute when it connects.\n recompute(event) {\n return __SPLIT__\n ? featureModules.get(\"compute\")?.recompute(this, this.#featureCore(), event)\n : computeFeature.recompute(this, this.#featureCore(), event)\n }\n\n // Tag-chip input (issue #203) and draft nested rows (issue #208) are the\n // bindings feature's (issue #275, features/bindings.js). These are the\n // methods their descriptors name, so they stay: each hands the event to the\n // module — now, or, with the opt-in client, once it has arrived. The event\n // is dead by then, so what the module reads of it (the trigger, the target)\n // is captured here; the native default is prevented now, as the module\n // would have. tagsAdd keeps its two composition guards (an Enter that\n // listnav already took, or is about to take) in the same tick.\n tagsAdd(event) {\n if (event?.defaultPrevented) return\n if (this.#listnavOptions(event).some((el) => el.hasAttribute?.(\"data-reactive-highlighted\"))) return\n return __SPLIT__\n ? this.#bindingsAction(\"tagsAdd\", event)\n : bindingsFeature.tagsAdd(this, this.#featureCore(), event)\n }\n\n tagsPick(event) {\n return __SPLIT__\n ? this.#bindingsAction(\"tagsPick\", event)\n : bindingsFeature.tagsPick(this, this.#featureCore(), event)\n }\n\n tagsRemove(event) {\n return __SPLIT__\n ? this.#bindingsAction(\"tagsRemove\", event)\n : bindingsFeature.tagsRemove(this, this.#featureCore(), event)\n }\n\n nestedAdd(event) {\n return __SPLIT__\n ? this.#bindingsAction(\"nestedAdd\", event)\n : bindingsFeature.nestedAdd(this, this.#featureCore(), event)\n }\n\n nestedRemove(event) {\n return __SPLIT__\n ? this.#bindingsAction(\"nestedRemove\", event)\n : bindingsFeature.nestedRemove(this, this.#featureCore(), event)\n }\n\n syncNestedJson(event) {\n return __SPLIT__\n ? featureModules.get(\"bindings\")?.syncNestedJson(this, this.#featureCore(), event)\n : bindingsFeature.syncNestedJson(this, this.#featureCore(), event)\n }\n\n #bindingsAction(name, event) {\n if (__SPLIT__) {\n const loaded = featureModules.get(\"bindings\")\n if (loaded) return loaded[name](this, this.#featureCore(), event)\n event?.preventDefault?.()\n const snapshot = { currentTarget: event?.currentTarget ?? null, target: event?.target ?? null, preventDefault() {} }\n return withFeature(\"bindings\", (bindings) => bindings[name](this, this.#featureCore(), snapshot))\n }\n }\n\n // Dirty tracking (issue #103) is the form feature's (issue #275,\n // features/form.js). This is the method its descriptor names\n // (input->reactive#trackDirty), so it stays: a full re-scan, by the module\n // when it is here. While it is still on its way nothing is lost — it scans\n // the whole root when it connects.\n trackDirty() {\n if (!__SPLIT__) formFeature.scan(this, this.#featureCore())\n else (this.#features.get(\"form\") ?? featureModules.get(\"form\"))?.scan(this, this.#featureCore())\n }\n\n // Client-side list navigation (combobox keyboard nav, issue #72). Wired by\n // on(:search, …, listnav: \"[role=option]\"), which appends keyboard filters to\n // the input's data-action (keydown.down/up/enter/esc->reactive#listnav*) and\n // sets data-reactive-listnav-option-param. Arrow keys move a highlight among\n // the options WITH NO ROUND TRIP; Enter picks the highlighted option by\n // CLICKING IT (so its own on(:select) reactive trigger fires — selection stays\n // a signed action); Escape clears. Ephemeral highlight state lives on the DOM\n // (data-reactive-highlighted), never shipped to the client as trusted state.\n //\n // Issue #271: a container spread with reactive_listnav(focus: true) carries\n // data-reactive-listnav-focus-param=\"true\" — ROVING-FOCUS mode for a\n // role=menu: the same moves shift real focus among the items instead of a\n // highlight, and Home/End (listnavFirst/listnavLast) jump to the edges.\n listnavNext(event) {\n this.#listnavMove(event, (current, length) => (current < 0 ? 0 : (current + 1) % length))\n }\n\n listnavPrev(event) {\n this.#listnavMove(event, (current, length) => (current < 0 ? length - 1 : (current - 1 + length) % length))\n }\n\n listnavFirst(event) {\n this.#listnavMove(event, () => 0)\n }\n\n listnavLast(event) {\n this.#listnavMove(event, (_current, length) => length - 1)\n }\n\n // Enter: activate the highlighted option (fires its reactive select). No-op if\n // nothing is highlighted, and in that case DON'T preventDefault — Enter falls\n // through (there's no selection to make).\n listnavPick(event) {\n const options = this.#listnavOptions(event)\n const current = options.findIndex((el) => el.hasAttribute(\"data-reactive-highlighted\"))\n if (current < 0) return\n event.preventDefault()\n options[current].click()\n }\n\n listnavClose(event) {\n for (const el of this.#listnavOptions(event)) el.removeAttribute(\"data-reactive-highlighted\")\n }\n\n // Move among THIS root's options: `pick(current, length)` returns the next\n // index (current is -1 when nothing is highlighted/focused). preventDefault\n // stops Arrow keys moving the caret in a search input, and the page scrolling\n // under a menu. Highlight mode writes data-reactive-highlighted; focus mode\n // (issue #271) focuses the chosen item, current being the item that is or\n // contains document.activeElement.\n #listnavMove(event, pick) {\n const options = this.#listnavOptions(event)\n if (!options.length) return\n event.preventDefault()\n\n const focusMode = this.#listnavFocusMode(event)\n const active = globalThis.document?.activeElement\n const current = focusMode\n ? options.findIndex((el) => el === active || (active != null && el.contains?.(active)))\n : options.findIndex((el) => el.hasAttribute(\"data-reactive-highlighted\"))\n const chosen = options[pick(current, options.length)]\n\n if (focusMode) {\n chosen.focus?.()\n } else {\n for (const el of options) el.removeAttribute(\"data-reactive-highlighted\")\n chosen.setAttribute(\"data-reactive-highlighted\", \"true\")\n }\n chosen.scrollIntoView?.({ block: \"nearest\" })\n }\n\n // Focus mode is read off the TRIGGER like the option selector (issue #271).\n #listnavFocusMode(event) {\n const trigger = event?.currentTarget ?? event?.target ?? this.element\n return trigger.getAttribute?.(\"data-reactive-listnav-focus-param\") === \"true\"\n }\n\n // The option elements this root owns (skips nested reactive roots, issue #15),\n // per the selector on data-reactive-listnav-option-param. The attr rides on the\n // TRIGGER element (the search input on(...) is spread onto), read from the\n // event; the options are still scoped to this controller's root. Empty when\n // unset. Falls back to the root for a directly-invoked call (unit tests). The\n // ownership predicate is hoisted ONCE per keypress (issue #117) — in the common\n // no-nested-root case it is a constant true, skipping a closest() walk per\n // option. Hidden options are excluded (issue #163): a reactive_filter (or any\n // `hidden` toggle) removes a row from the keyboard path too, so an Arrow can't\n // highlight — and Enter can't pick — an invisible option.\n #listnavOptions(event) {\n const trigger = event?.currentTarget ?? event?.target ?? this.element\n const selector =\n trigger.getAttribute?.(\"data-reactive-listnav-option-param\") ??\n this.element.getAttribute(\"data-reactive-listnav-option-param\")\n if (!selector) return []\n const owns = this.#ownershipFilter()\n return Array.from(this.element.querySelectorAll(selector)).filter((el) => !el.hidden && owns(el))\n }\n\n // Enqueue the action — debounced if a debounce window is set, else immediately.\n // Split out of dispatch so both the no-confirm fast path and the post-confirm\n // microtask share one place (issue #55). `target` is captured up front because\n // this can run in a later microtask, after event.target has been reset.\n #proceed(target, action, params, debounce, throttle, optimistic, busy) {\n // Lifecycle veto point (issue #79): one cancelable reactive:before-dispatch\n // per user gesture — post-preventDefault, post-confirm, PRE-debounce (and\n // PRE-throttle, the same timing). event.preventDefault() skips the\n // debounce/throttle AND the enqueue entirely (nothing is scheduled).\n // retry() re-enters the queue directly, so this does NOT refire on a retry.\n // detail.params are the trigger's explicit params; sibling fields are\n // collected later, at send time.\n const before = this.#emit(\"reactive:before-dispatch\", {\n action,\n params: this.#parseParams(params),\n element: this.element,\n }, { cancelable: true })\n if (before.defaultPrevented) return\n\n // Debounced trigger (e.g. on(:update, event: \"input\", debounce: 300)):\n // coalesce rapid events into ONE round trip after a quiet period, instead of\n // one POST per keystroke (issue #17). A blur flushes a pending dispatch.\n // The optimistic hint (issue #98) and the busy state (issue #181) ride to\n // the flush too, so they apply ONCE per enqueue — a debounced input must not\n // flap toggle_class per keystroke, and its element must NOT be disabled\n // during the quiet period (that would break typing). Both apply at ENQUEUE.\n const ms = Number(debounce) || 0\n if (ms > 0) return this.#debounceDispatch(target, ms, action, params, optimistic, busy)\n\n // Throttled trigger (e.g. on(:track, event: \"scroll\", window: true,\n // throttle: 250), issue #80): LEADING-EDGE rate limit — fire the first\n // event immediately, drop the rest until the window elapses. debounce and\n // throttle are mutually exclusive (the Ruby on() raises on both).\n const throttleMs = Number(throttle) || 0\n if (throttleMs > 0) return this.#throttleDispatch(target, throttleMs, action, params, optimistic, busy)\n\n return this.#enqueue(action, params, optimistic, target, busy)\n }\n\n // Apply the optimistic hint ONCE (recording its inverse) and chain the round\n // trip, threading that inverse onto THIS queued request so the serialized\n // per-controller queue reverts the RIGHT request's hint on failure (issue\n // #98). Applying here — the single flush/enqueue point every path funnels\n // through — is what makes a hint apply once per enqueue, not per raw dispatch.\n //\n // The busy state (issue #181) applies here too, for the same reason: enqueue\n // is the moment the request is committed to the queue, so the always-on busy\n // vocabulary (data-reactive-busy on the trigger + root, aria-busy via a pending\n // counter, busy_on scoping) and the busy hint (disable + class + text swap)\n // cover the WHOLE pending window — queue wait included — not just the fetch. It\n // returns a `settle` closure that #perform runs in its finally (success OR\n // failure), guarded so a morph-replaced trigger is never clobbered.\n #enqueue(action, params, optimistic, target, busy) {\n // The always-on busy state and the activity signal, now: they cover the\n // whole pending window, a wait for the hints module included. `pending`\n // is what this request's hint engine recorded — filled in by the apply\n // below, which may run a moment later than this call.\n const pending = { inverse: null, undo: [], resurrect: null }\n const settle = this.#applyBusy(action, target, pending)\n const wanted = Boolean(optimistic || busy)\n const apply = (hints) => {\n if (!wanted || !hints) return\n const core = this.#featureCore()\n pending.inverse = __SPLIT__\n ? hints.optimistic(this, core, optimistic, target)\n : hintsFeature.optimistic(this, core, optimistic, target)\n pending.undo.push(...(__SPLIT__ ? hints.busy(this, core, busy, target) : hintsFeature.busy(this, core, busy, target)))\n // Debug-only teaching aid (issue #181): if optimistic: { hide: true } is\n // used for instant-delete but the reply RE-RENDERS the element (bringing\n // it back), that hint was pointless — the developer likely wanted\n // reply.remove. Capture the hidden nodes now; the success path re-checks\n // the OBSERVED DOM after the morph (never inferred from the verb).\n if (this.#debugEnabled()) {\n pending.resurrect = __SPLIT__\n ? hints.resurrection(this, core, optimistic, target)\n : hintsFeature.resurrection(this, core, optimistic, target)\n }\n }\n // A hint applies ONCE per enqueue — the single flush point every path\n // funnels through — never per raw dispatch. With the module here (the\n // default client, always) that is now, synchronously.\n const loaded = __SPLIT__ ? featureModules.get(\"hints\") : true\n if (!wanted || loaded) apply(loaded)\n // A feature still loading may be about to change what this request reads\n // (issue #275: the draft restore writes the fields #perform collects). Only\n // such a feature — one that `gates` — holds a request back, until it has\n // connected: at most the feature timeout, and on a root that never waited\n // for one, not at all. A feature that does not gate (the defer module)\n // never delays a request, however slow its import. A request WITH a hint\n // on a page that has not loaded the hints module waits for that import\n // the same way (at most the feature timeout), then applies the hint and\n // goes out — once.\n const perform = () => this.#perform(action, params, pending, settle)\n const ready = () => (this.#featureGate ? this.#featureGate.then(perform) : perform())\n this.queue = (this.queue ?? Promise.resolve()).then(() =>\n wanted && !loaded ? this.#awaitHints().then(apply).then(ready) : ready(),\n )\n return this.queue\n }\n\n // The hints module, or null once its import failed or outlasted the feature\n // timeout (the request then goes out without its hint).\n #awaitHints() {\n return this.#awaitFeatureOrNull(\"hints\")\n }\n\n // Reset a per-element timer; only enqueue the round trip after `ms` of quiet.\n // Also flush immediately on blur so leaving the field never drops the last\n // edit (a long debounce shouldn't swallow a value the user tabbed away from).\n #debounceDispatch(target, ms, action, params, optimistic, busy) {\n this.#debounce(target, DISPATCH_WAIT_KEY, ms, () => this.#enqueue(action, params, optimistic, target, busy))\n }\n\n // The one trailing-edge timer on() and on_client (issue #393) share. Timers\n // are keyed on target + key: on()'s dispatch uses DISPATCH_WAIT_KEY, an\n // on_client record its ordinal + JSON (it starts with \"[\"), so an on() debounce and an\n // on_client debounce on one input never cancel each other. A window-bound\n // trigger gets no blur flush: a window blur is a tab switch, not an edit.\n #debounce(target, key, ms, run) {\n this.#clearDebounce(target, key)\n\n const flush = () => {\n this.#clearDebounce(target, key)\n run()\n }\n const timer = setTimeout(flush, ms)\n if (!isWindow(target)) target?.addEventListener?.(\"blur\", flush, { once: true })\n let pending = this.#debounceTimers.get(target)\n if (!pending) this.#debounceTimers.set(target, (pending = new Map()))\n pending.set(key, { timer, flush })\n }\n\n #clearDebounce(target, key) {\n const byKey = this.#debounceTimers.get(target)\n const pending = byKey?.get(key)\n if (!pending) return\n clearTimeout(pending.timer)\n target?.removeEventListener?.(\"blur\", pending.flush)\n byKey.delete(key)\n if (byKey.size === 0) this.#debounceTimers.delete(target)\n }\n\n // Clear every pending debounce timer (used on disconnect). Reuses\n // #clearDebounce so all timer/listener teardown stays in one place. Snapshot\n // the entries first — #clearDebounce mutates the maps as it goes.\n #clearAllDebounces() {\n for (const [target, byKey] of [...this.#debounceTimers]) {\n for (const key of [...byKey.keys()]) this.#clearDebounce(target, key)\n }\n }\n\n // Leading-edge throttle (issue #80), mirroring #debounceDispatch: the FIRST\n // event fires immediately; a suppression timer then drops further events\n // until the window elapses (no trailing fire — dropped, not queued). Timers\n // are keyed on action + target, NOT target alone: window-bound scroll/resize\n // events all share event.target === document, so two window-bound triggers\n // on one component would otherwise collide on one timer.\n #throttleDispatch(target, ms, action, params, optimistic, busy) {\n return this.#throttle(target, action, ms, () => this.#enqueue(action, params, optimistic, target, busy))\n }\n\n // The leading-edge window on() and on_client (issue #393) share; an\n // on_client record keys on its ordinal + JSON, which no action name can equal.\n #throttle(target, key, ms, run) {\n const timers = this.#throttleTimers.get(target) ?? new Map()\n if (timers.has(key)) return // inside the window — suppress\n\n const timer = setTimeout(() => {\n timers.delete(key)\n if (timers.size === 0) this.#throttleTimers.delete(target)\n }, ms)\n timers.set(key, timer)\n this.#throttleTimers.set(target, timers)\n return run() // leading edge: fire NOW\n }\n\n // Clear every throttle suppression timer (used on disconnect, alongside\n // #clearAllDebounces) so nothing outlives the element.\n #clearAllThrottles() {\n for (const timers of this.#throttleTimers.values()) {\n for (const timer of timers.values()) clearTimeout(timer)\n }\n this.#throttleTimers.clear()\n }\n\n // Raw-dispatch a lifecycle CustomEvent (issue #79). Deliberately NOT\n // Stimulus's this.dispatch() helper — that name is SHADOWED by this\n // controller's own dispatch(event) action method. Bubbling + composed so a\n // page-level listener (or `data-action=\"reactive:error->toast#show\"` on an\n // ancestor) hears it. After a plain (non-morph) replace this.element is a\n // DETACHED node — a bubbling event on it never reaches document listeners —\n // so fall back to dispatching on document itself.\n #emit(name, detail, { cancelable = false } = {}) {\n const event = new CustomEvent(name, { bubbles: true, composed: true, cancelable, detail })\n const root = this.element.isConnected ? this.element : document\n root.dispatchEvent(event)\n return event\n }\n\n // reactive:error detail: { action, params, kind, status?, body?, retry }.\n // `params` are the FULL params that were sent (collected fields + explicit\n // trigger params). retry() re-enters the request queue with the ORIGINAL raw\n // trigger params, so #perform re-reads the freshest token and RE-COLLECTS the\n // sibling fields — nothing stale is replayed. It does not refire\n // reactive:before-dispatch (one veto per user gesture), and it no-ops with a\n // warning once the root has left the DOM (retrying against a detached\n // element would post a stale token into nowhere).\n #emitError(action, rawParams, sentParams, extra) {\n const retry = () => {\n if (!this.element.isConnected) {\n console.warn(\"[phlex-reactive] retry() ignored — the reactive root left the DOM\")\n return\n }\n return this.#enqueue(action, rawParams)\n }\n this.#emit(\"reactive:error\", { action, params: sentParams, ...extra, retry })\n }\n\n // Mark the reactive root as errored (issue #100) with the failure kind, so an\n // app can style it purely in CSS ([data-reactive-error] { … }) with zero JS.\n // Guarded — a plain replace may have detached the root before the failure lands.\n #markError(kind) {\n if (this.element?.isConnected === false) return\n this.element?.setAttribute?.(\"data-reactive-error\", kind)\n }\n\n // Clear the failure marker on the next successful apply (issue #100).\n #clearError() {\n this.element?.removeAttribute?.(\"data-reactive-error\")\n }\n\n // Offline fallback (issue #100): a network failure reached no server, so there\n // is no body to render. Clone the content of a server-rendered\n // <template data-reactive-error-flash> into the flash region so the user still\n // sees SOMETHING. The template is app-authored (trusted) — this is a pure\n // deep clone, never client templating of untrusted data. No template, or no\n // flash container, is a silent no-op (a page without the opt-in is unchanged).\n #renderNetworkFallback() {\n const template = document.querySelector(\"[data-reactive-error-flash]\")\n if (!template?.content) return\n // The flash region is the host-app container Response#flash targets. Its id\n // defaults to \"flash\" (Phlex::Reactive.flash_target); an app that customized\n // it can point the fallback at the same node by putting the template's\n // data-reactive-error-flash value there — but the common case is #flash.\n const targetId = template.getAttribute(\"data-reactive-error-flash\") || \"flash\"\n const region = document.getElementById(targetId)\n if (!region) return\n region.appendChild(template.content.cloneNode(true))\n }\n\n // Latency simulator (issue #102): the delay itself is the dev feature's.\n // A request waits for the module only while a delay is stored (so the very\n // first delayed request is delayed too); with none stored this is two reads.\n #maybeSimulateLatency() {\n if (!__SPLIT__) return devtoolsFeature.delay()\n else {\n const devtools = featureModules.get(\"devtools\")\n if (devtools) return devtools.delay()\n if (latencyStored()) return loadFeature(\"devtools\").then((loaded) => loaded.delay(), () => {})\n }\n }\n\n // Client debug mode (issue #108) — the \"devtools-lite\" lens. On when the Ruby\n // reactive_attrs stamped data-reactive-debug=\"true\" (Phlex::Reactive.debug).\n // Read live (a single getAttribute) so the whole feature is inert for any app\n // that never opts in: OFF → this returns false and #perform builds no debug\n // object, parses no response, and logs nothing (the \"zero cost when off\"\n // invariant — one nil-check per dispatch). Guarded for a stub root with no\n // getAttribute (unit harnesses) so it degrades to off, never throwing.\n #debugEnabled() {\n return this.element?.getAttribute?.(\"data-reactive-debug\") === \"true\"\n }\n\n // A monotonic timestamp for the round-trip duration (ms). performance.now is\n // monotonic (immune to a wall-clock adjustment mid-request); Date.now is the\n // fallback for an exotic environment without it. ONLY called on the debug path,\n // so it costs nothing when debug is off.\n #debugNow() {\n return typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now()\n }\n\n async #perform(action, params, pending, settle) {\n // Auto-collect named field values inside this component so a button-\n // triggered action still receives sibling inputs (Livewire-style), plus any\n // chosen file inputs in the SAME walk. Explicit params\n // (data-reactive-params-param) win over collected fields.\n const { fields, files } = this.#collectFields()\n // Parse the explicit trigger params ONCE — reused below for allParams and, on\n // the debug path, for the params-only name list (so the trace can show\n // `params: [...]` distinct from the collected `+ collected: [...]`). #parseParams\n // is pure (a fresh object from a JSON string, or the same object by reference\n // when already parsed); allParams spreads a COPY and nothing mutates parsedParams\n // downstream (JSON.stringify / #buildFormData read allParams, a new object).\n const parsedParams = this.#parseParams(params)\n const allParams = { ...fields, ...parsedParams }\n const token = this.#currentToken\n\n // File/multipart path (issue #34): if THIS root has a populated\n // <input type=\"file\">, the action can't be JSON (JSON.stringify drops the\n // File). Send FormData instead — token + act + scalar params as fields, each\n // chosen file appended. The morph/token machinery downstream is identical;\n // only the request ENCODING differs when files are present.\n const multipart = files.length > 0\n const body = multipart\n ? this.#buildFormData(token, action, allParams, files)\n : JSON.stringify({ token, act: action, params: allParams })\n\n // Client debug mode (issue #108): build the trace object ONLY when debug is on\n // (one nil-check otherwise — zero cost off). It carries NAMES only: the\n // explicit trigger param names and the collected sibling field names, split so\n // the group shows `params: [...] + collected: [...]`. status/streams/\n // tokenRefreshed are filled in at the branch that knows them; the group is\n // emitted once in the finally so EVERY exit (success or any failure) logs.\n const debug = this.#debugEnabled()\n ? {\n action,\n paramNames: Object.keys(parsedParams),\n fieldNames: Object.keys(fields),\n encoding: multipart ? \"multipart\" : \"json\",\n status: null,\n streams: [],\n tokenRefreshed: false,\n started: this.#debugNow(),\n }\n : null\n\n // aria-busy on the root is now driven by the loading pending counter\n // (#applyLoading, applied at ENQUEUE so it covers the queue wait too), not\n // set here. #settleLoading in the finally clears it — see #enqueue.\n\n // Latency simulator (issue #102): the busy window (aria-busy + loading state)\n // is already applied at enqueue, so awaiting the configured delay HERE — after\n // that window opened and before the fetch — is what makes it visible on\n // localhost. A null/absent/non-positive sessionStorage key is a no-op (zero\n // production surface), so this line vanishes for any app that never opts in.\n await this.#maybeSimulateLatency()\n\n try {\n // Offline gate (issue #101), authoritative at the NETWORK BOUNDARY (send\n // time), not at enqueue. A click can enqueue while online and reach here\n // after going offline (a debounced/queued request, a rapid transition) —\n // gating in #perform makes the kind consistently \"offline\" for that whole\n // condition instead of leaking through as a \"network\" fetch throw. The\n // fetch never fires, so the edit is not half-sent; the finally still runs\n // (settle clears loading), the optimistic hint reverts, and retry() (which\n // re-enters #perform) re-checks and sends once back online.\n if (navigator.onLine === false) {\n this.#revertOptimistic(pending.inverse)\n this.#markError(\"offline\")\n this.#emitError(action, params, allParams, { kind: \"offline\" })\n return\n }\n\n let response\n try {\n const headers = {\n Accept: \"text/vnd.turbo-stream.html\",\n \"X-CSRF-Token\": this.#csrfToken(),\n }\n // For JSON we declare the content type; for multipart we must NOT — the\n // browser sets `multipart/form-data; boundary=…` itself, and overriding it\n // would strip the boundary and corrupt the body server-side.\n if (!multipart) headers[\"Content-Type\"] = \"application/json\"\n // Send the pgbus SSE connection id (if subscribed) so the server can\n // exclude this connection from its own broadcast echo — the actor\n // already gets the action's HTTP response. Harmless without pgbus.\n const connectionId = this.#connectionId()\n if (connectionId) headers[\"X-Pgbus-Connection\"] = connectionId\n // A presence root's own connection (issue #358): the row its presence\n // writes land on, whatever source comes first on the page.\n const presence =\n presenceNeeded(this.element) &&\n document.getElementById(`reactive-presence-src-${this.element.id}`)?.getAttribute(\"connection-id\")\n if (presence) headers[\"X-Reactive-Presence\"] = presence\n // The fields a morph held over a changed server value (issue #370).\n const held = heldHeader(this.element)\n if (held) headers[\"X-Reactive-Held\"] = held\n\n // ONLY `fetch` itself is the network boundary — offline, DNS, a reset\n // connection. Everything below this inner try (reading the body,\n // extracting the token, handing streams to Turbo) runs AFTER the\n // server already processed the mutation, so none of it belongs in the\n // `kind: \"network\"` / retriable bucket (CodeRabbit review on #89): if\n // renderStreamMessage throws, retry()ing would re-POST an action the\n // server already completed — see the outer catch below. (NOT a\n // reactive:applied LISTENER throwing — per the DOM spec, dispatchEvent\n // never propagates a listener's exception back to its caller, so that\n // case can't reach this catch at all; verified in the JS test suite.)\n countReactiveRequest(\"action\")\n response = await fetch(this.#actionPath(), {\n method: \"POST\",\n headers,\n body,\n credentials: \"same-origin\",\n // Bound the request (issue #101): a server that never answers used to\n // wedge this.queue forever (the finally that clears aria-busy/loading\n // never ran). AbortSignal.timeout(ms) aborts the fetch after the\n // configured window; the abort surfaces in this catch as a\n // DOMException named \"TimeoutError\" (see the branch below).\n signal: AbortSignal.timeout(this.#timeoutMs()),\n })\n } catch (error) {\n console.error(\"[phlex-reactive] action error\", error)\n this.#revertOptimistic(pending.inverse)\n // AbortSignal.timeout() rejects with a DOMException named \"TimeoutError\"\n // (a manual AbortController.abort() would be \"AbortError\" — we don't use\n // one, but accept it too for robustness). A timeout is NOT \"offline\":\n // the request left and the server didn't answer in time; connectivity is\n // unknown. So do NOT clone the offline-fallback template or mark network\n // — just fire kind:\"timeout\" (retriable). The queue still advances\n // (#perform returns, never rejects), so the hung request un-wedges it.\n if (error?.name === \"TimeoutError\" || error?.name === \"AbortError\") {\n this.#markError(\"timeout\")\n this.#emitError(action, params, allParams, { kind: \"timeout\" })\n return\n }\n // No server reached — nothing to render (issue #100). Clone a\n // server-rendered <template data-reactive-error-flash> into the flash\n // region as an offline fallback. The template is rendered by the app\n // (trusted), so this is a pure clone — no client templating of data.\n this.#renderNetworkFallback()\n this.#markError(\"network\")\n this.#emitError(action, params, allParams, { kind: \"network\" })\n return\n }\n\n // Debug (issue #108): the server answered — record the status for the trace\n // now, so every response branch below (redirected/http/content-type/ok) logs\n // it. The transport-failure branches above return before here (they have no\n // status); their group still fires from the finally with status null → \"—\".\n if (debug) debug.status = response.status\n\n if (response.redirected) {\n console.error(\"[phlex-reactive] action was redirected (auth/CSRF?) — no update applied\")\n this.#revertOptimistic(pending.inverse)\n this.#markError(\"redirected\")\n this.#emitError(action, params, allParams, { kind: \"redirected\", status: response.status })\n return\n }\n if (!response.ok) {\n const errorBody = await response.text()\n console.error(`[phlex-reactive] action failed: HTTP ${response.status}`, errorBody)\n this.#revertOptimistic(pending.inverse)\n // Render a non-OK turbo-stream body so a server-rendered error flash\n // (an error_flash rescue, or a status: :unprocessable_entity validation\n // reply from a plain controller) is actually SHOWN — instead of being\n // read only for the console (issue #100). #extractToken is run as usual;\n // it NO-OPS when no stream re-renders our id, so a 400 InvalidToken body\n // never refreshes the held identity token (which is not a nonce and stays\n // retry-valid — do not \"fix\" that). A non-turbo-stream body is left to the\n // console.error above (an HTML error page must not be handed to Turbo).\n if ((response.headers.get(\"Content-Type\") || \"\").includes(\"turbo-stream\")) {\n const fresh = this.#extractToken(errorBody)\n this.#currentToken = fresh ?? this.#currentToken\n if (debug) {\n if (__SPLIT__) this.#devtools((devtools) => devtools.recordBody(debug, errorBody, fresh))\n else devtoolsFeature.recordBody(debug, errorBody, fresh)\n }\n renderOwnReply(this.element, errorBody, true)\n }\n this.#markError(\"http\")\n this.#emitError(action, params, allParams, { kind: \"http\", status: response.status, body: errorBody })\n return\n }\n\n const contentType = response.headers.get(\"Content-Type\") || \"\"\n if (!contentType.includes(\"turbo-stream\")) {\n console.error(`[phlex-reactive] expected a turbo-stream, got \"${contentType}\" — no update applied`)\n this.#revertOptimistic(pending.inverse)\n this.#markError(\"content-type\")\n this.#emitError(action, params, allParams, { kind: \"content-type\", status: response.status })\n return\n }\n\n const html = await response.text()\n // Capture the new token from the response synchronously, so the next\n // queued request uses it without waiting for the async DOM morph.\n const fresh = this.#extractToken(html)\n this.#currentToken = fresh ?? this.#currentToken\n // Debug (issue #108): record the stream actions/targets + whether a refresh\n // arrived, from the body we JUST read (reuse — no second text() read). Never\n // the token or template contents.\n if (debug) {\n if (__SPLIT__) this.#devtools((devtools) => devtools.recordBody(debug, html, fresh))\n else devtoolsFeature.recordBody(debug, html, fresh)\n }\n // Turbo applies the <turbo-stream> ops by id. A plain replace is an\n // outerHTML swap (focus on the replaced subtree is lost); a method=\"morph\"\n // replace (Response.morph) or an update morphs in place, preserving the\n // focused input + caret on unchanged nodes — see issue #28. As the root's\n // own reply, it clears what the root held (issue #370), but what it\n // refused (issue #413).\n renderOwnReply(this.element, html, refusedHeader(response))\n // Debug-only (issue #181): the morph may apply a microtask later, so check\n // the resurrected-hide case AFTER it lands. Off the debug path, resurrect is\n // null — zero cost.\n if (pending.resurrect) queueMicrotask(pending.resurrect)\n // A successful apply CLEARS any prior failure marker (issue #100), so\n // error-driven CSS on the root (a red border, a shake) resets on recovery.\n this.#clearError()\n // Lifecycle hook (issue #79): the streams were HANDED TO Turbo — a\n // renderStreamMessage applies asynchronously, so the DOM mutation may\n // complete a tick later. Apps needing post-morph timing listen to Turbo's\n // own events; this one is for \"the action round trip succeeded\".\n this.#emit(\"reactive:applied\", { action, params: allParams, html })\n // What core.proceed resolves with: a feature can tell a reply that\n // applied from a failure (every other exit returns nothing).\n return html\n } catch (error) {\n // The server already processed this action successfully (we're past the\n // fetch) — a throw here is a CLIENT-side apply failure (a malformed\n // response, a broken Turbo render — NOT a reactive:applied listener\n // throw, which dispatchEvent never propagates here), not a transport\n // failure. kind: \"apply\" carries NO retry() — retrying would re-POST an\n // action the server already completed.\n console.error(\"[phlex-reactive] action error\", error)\n this.#revertOptimistic(pending.inverse)\n this.#emit(\"reactive:error\", { action, params: allParams, kind: \"apply\" })\n } finally {\n // Settle the loading state (issue #99): decrement the pending counter,\n // drop the trigger's/root's busy tokens, restore disabled/text/class —\n // guarded so a morph-replaced trigger is never clobbered. Runs on EVERY\n // exit (success, every failure branch, or an apply throw).\n settle?.()\n // Debug (issue #108): emit the group here so EVERY exit path logs exactly\n // once — success, any transport/response failure, or an apply throw. Null\n // when debug is off (zero cost). The round-trip ms is measured now, at the\n // finally, so it spans the whole #perform (fetch + apply) regardless of exit.\n if (debug) {\n if (__SPLIT__) this.#devtools((devtools) => devtools.trace(this, { ...debug, ms: this.#debugNow() - debug.started }))\n else devtoolsFeature.trace(this, { ...debug, ms: this.#debugNow() - debug.started })\n }\n }\n }\n\n get #currentToken() {\n return this.#tokenCache ?? this.tokenValue\n }\n\n set #currentToken(value) {\n this.#tokenCache = value\n }\n\n // A token written into the DOM wins over the cached one (issue #301): an\n // outside morph (a broadcast, a page refresh, a dormant morph-back) rewrites\n // the attribute while this controller survives, and Stimulus calls this on\n // that change and on a reconnect after it. Our own reply's morph writes the\n // token #extractToken already cached, so dropping the cache changes nothing —\n // unless a later reply was already extracted: then the attribute holds the\n // older token until that reply's morph lands, the same frame (Turbo renders\n // streams after nextRepaint), before any queued dispatch reads it.\n tokenValueChanged() {\n this.#tokenCache = undefined\n }\n\n // Read the next token for THIS controller — the one that re-renders THIS\n // element's id, never just the first token in the body (issue #46). On a\n // collection of REACTIVE rows the prepended/appended ROW carries its OWN\n // data-reactive-token-value and it sorts FIRST in the response; the list's own\n // fresh token rides a trailing `reactive:token` stream targeting the container.\n // Grabbing the first match stored the ROW's token, so the list's SECOND\n // dispatch sent a row token → failed verification → add-once-only. This mirrors\n // the server's carries_token_for? (#44): a stream carries OUR token only when it\n // RE-RENDERS our id (reactive:token / replace / update of `this.element.id`) —\n // append/prepend insert children and never count. Returns undefined when no\n // stream re-renders our id, so #currentToken keeps its existing value.\n #extractToken(html) {\n const id = this.element.id\n if (!id) {\n // No id to self-match (shouldn't happen for a reactive root). Fall back to\n // the legacy first-token behavior so a single-component response still works.\n return html.match(/data-reactive-token-value=\"([^\"]+)\"/)?.[1]\n }\n\n const { token, self } = this.#tokenRegexes(id)\n\n // The dedicated token-only refresh for THIS element (partial updates / the\n // collection container) — an attribute on the <turbo-stream> itself.\n const tokenStream = html.match(token)\n if (tokenStream) return tokenStream[1]\n\n // A full self re-render: a replace/update of THIS element whose template root\n // carries the fresh token. Scope the token search to that one stream so a\n // sibling/child token elsewhere in the body can't leak in.\n const selfStream = html.match(self)\n if (selfStream) return selfStream[1].match(/data-reactive-token-value=\"([^\"]+)\"/)?.[1]\n\n // Nothing re-rendered our id — keep the current token.\n return undefined\n }\n\n // The two per-id RegExps #extractToken uses to self-match this element's next\n // token (issue #118). `this.element.id` is page-stable, so these are compiled\n // ONCE and reused across every response — instead of allocating two fresh\n // RegExps per round trip. The memo is KEYED ON THE ID and rebuilt when it\n // changes: a re-render that re-identifies the root must scan for the NEW target,\n // never the stale one (or the token would freeze — see the id-change bun test).\n // The PATTERNS are byte-identical to the pre-memo inline literals; only their\n // allocation moved.\n #tokenRegexes(id) {\n const cache = this.#tokenRegexCache\n if (cache && cache.id === id) return cache\n const escaped = escapeRegExp(id)\n return (this.#tokenRegexCache = {\n id,\n token: new RegExp(\n `<turbo-stream\\\\b[^>]*\\\\baction=\"reactive:token\"[^>]*\\\\btarget=\"${escaped}\"[^>]*\\\\bdata-reactive-token-value=\"([^\"]+)\"`,\n ),\n self: new RegExp(\n `<turbo-stream\\\\b[^>]*\\\\baction=\"(?:replace|update)\"[^>]*\\\\btarget=\"${escaped}\"[^>]*>([\\\\s\\\\S]*?)</turbo-stream>`,\n ),\n })\n }\n\n // True when `el` is collected by THIS reactive root and not by a nested one.\n // A reactive component can be rendered inside another (both are\n // data-controller=\"reactive\" roots). querySelectorAll() descends into nested\n // roots, so without this guard an outer action would sweep the inner roots'\n // inputs into its own params (issue #15). An element belongs to this root iff\n // its nearest [data-controller~=\"reactive\"] ancestor is this.element.\n #ownsField(el) {\n return el.closest('[data-controller~=\"reactive\"]') === this.element\n }\n\n // A per-op ownership PREDICATE — the issue #117 fast path over issue #15\n // scoping. #ownsField answers \"is this element mine, not a nested reactive\n // root's\" with a per-element closest() walk; on a wide form or every keystroke\n // that walk runs per matched field. This hoists the DECISION to once per op.\n //\n // HYBRID GATE — closest() stays the source of truth; the nested-root query only\n // decides whether the fast path is SAFE:\n // * Fast path (overwhelmingly common): this root contains NO nested reactive\n // roots, so every element the caller's querySelectorAll returned is already\n // a direct descendant of this.element with no intervening reactive root —\n // it is ours. Return a constant-true predicate and skip the per-field\n // closest() walk entirely. That is the whole win.\n // * Nested case: fall back to the UNCHANGED #ownsField closest() check, so\n // scoping is byte-identical to before. We deliberately do NOT use\n // contains() here — the closest() form needs no node to implement\n // contains(), and on a real DOM the two agree for a descendant of\n // this.element (el.closest('[data-controller~=\"reactive\"]') === this.element\n // iff no nested reactive-root descendant contains el).\n //\n // Computed ONCE per dispatch-scoped op (per #collectFields call, per recompute,\n // per #listnavOptions) and NEVER stored on the instance — a morph replaces\n // nodes, so a cached predicate would close over stale roots.\n #ownershipFilter() {\n const nested = this.element.querySelectorAll('[data-controller~=\"reactive\"]')\n if (nested.length === 0) return () => true\n return (el) => this.#ownsField(el)\n }\n\n // #ownershipFilter for SERVER params (issue #410): nested client-only roots\n // are transparent, so a control under one is this root's when the first\n // token-bearing root above it is this.element. A nested token-bearing root\n // keeps its own fields (issue #15). Bindings, computes and listnav keep the\n // strict nearest-root #ownershipFilter.\n #serverFieldFilter() {\n const nested = this.element.querySelectorAll(AWAKE_ROOT)\n if (nested.length === 0 || [...nested].every(clientOnlyRoot)) return () => true\n return (el) => serverRoot(el, AWAKE_ROOT, this.element) === this.element\n }\n\n // One walk over THIS root's named controls (not a nested reactive root's),\n // returning both the scalar `fields` and any chosen `files`. The ownership\n // predicate is hoisted ONCE (issue #117) via #ownershipFilter — in the common\n // no-nested-root case it is a constant true, so we skip a closest() walk per\n // field. A file input's `.value` is the useless \"C:\\fakepath\\…\" string, never a\n // scalar — so its chosen files are collected separately (honoring `multiple`)\n // and it adds no phantom blank value (issue #34). An empty `files` keeps the\n // JSON path.\n #collectFields() {\n const fields = {}\n const files = []\n const owns = this.#serverFieldFilter() // compute ONCE per dispatch (issue #117)\n const controls = []\n this.element.querySelectorAll(\"input[name], select[name], textarea[name]\").forEach((field) => {\n if (!owns(field)) return\n if (field.type === \"file\") {\n // Carry the input's `multiple` flag so #buildFormData keeps the array\n // shape (params[name][]) even when the user picked exactly one file —\n // otherwise a [:file] schema would see a lone scalar upload and drop it.\n for (const file of field.files ?? []) files.push({ name: field.name, file, multiple: field.multiple })\n } else {\n // Held for a second pass: a hidden input is only a companion if a\n // checkbox somewhere in the root shares its name, which the first\n // occurrence cannot know yet.\n controls.push(field)\n }\n })\n // Collected before the first pass so the editor DOM is walked once.\n const editors = []\n this.element.querySelectorAll(`[name]${EDITOR_SELECTOR}`).forEach((el) => {\n if (owns(el)) editors.push(el) // the SAME hoisted predicate (nested reactive root, issue #15)\n })\n const arrayNames = this.#arrayFieldNames(controls)\n const companionNames = this.#companionNames(controls)\n for (const field of controls) {\n if (arrayNames.has(field.name)) {\n const slot = fields[field.name] ?? (fields[field.name] = [])\n if (field.type === \"checkbox\" || field.type === \"radio\") {\n // An unchecked box contributes NOTHING, the way a native submission\n // leaves it out. The group's value is the list of checked values, and\n // with none checked that list stays an EMPTY ARRAY rather than\n // vanishing: the action can tell \"the operator cleared them\" from\n // \"the group never rendered\", and an [:string] schema coerces [] to\n // []. A form body cannot carry the empty array, so #buildFormData\n // announces the group there instead.\n if (field.checked) slot.push(field.value)\n } else if (field.type === \"hidden\") {\n if (!companionNames.has(field.name)) slot.push(field.value)\n } else if (field.multiple && field.options) {\n for (const option of field.options) if (option.selected) slot.push(option.value)\n } else {\n slot.push(field.value)\n }\n } else if (field.type === \"checkbox\") {\n fields[field.name] = field.checked\n } else if (field.type === \"radio\") {\n if (field.checked) fields[field.name] = field.value\n } else {\n fields[field.name] = field.value\n }\n }\n // Named rich-text / custom editors (lexxy-editor, trix-editor) and bare\n // [contenteditable]. These aren't input/select/textarea, so the query above\n // skips them — without this, a reactive save posts an empty value and\n // silently wipes the field (issue #8). Read whatever the element exposes:\n // a custom editor's serialized `.value`, else its contenteditable text.\n // Under a plain name: only fill what the standard controls left absent or\n // empty, so a synced hidden input (e.g. Trix mirrors into one) still wins\n // when populated. Under a `[]` name the editor APPENDS to the group slot\n // instead, and a same-named hidden keeps its own say: nothing here can\n // tell a hidden that mirrors this editor from one that is a list JS\n // maintains.\n editors\n .forEach((el) => {\n // A plain element (e.g. a <div contenteditable>) has no `name` IDL\n // property — only the attribute — so read getAttribute, not el.name.\n const name = el.getAttribute(\"name\")\n if (!name) return\n const own = el.getAttribute(\"data-reactive-editable\") != null\n ? editableValue(el)\n : (el.value ?? el.textContent ?? el.innerHTML ?? \"\")\n // A `[]` name is a group here too: the editor APPENDS its value\n // instead of replacing the slot. Assigning a scalar posted\n // `{\"notes[]\": \"<p>x</p>\"}` while the draft snapshot pushed the same\n // control into an array — the wire and the draft disagreeing about one\n // field, and a declared array type seeing a string. A same-named hidden\n // is NOT read as this editor's twin: nothing here can tell a mirror\n // from a list JS maintains, and a value posted twice is visible while a\n // suppressed one is not.\n const existing = fields[name]\n // An editor that has not upgraded yet contributes NOTHING to a group.\n // Trix defines its elements in a setTimeout after load, and its \"\" is\n // not an empty value but an absent one: persistSnapshot omits such an\n // editor for the same reason, so this keeps the wire and the draft\n // saying the same thing.\n if (String(name).endsWith(\"[]\") && !collectorEditorReady(el)) return\n if (String(name).endsWith(\"[]\") && (existing === undefined || Array.isArray(existing))) {\n const slot = Array.isArray(existing) ? existing : (fields[name] = [])\n slot.push(own)\n return\n }\n // A scalar already under a `[]` name can only be a RADIO's: a radio\n // means \"pick one\" and keeps its single value with or without the\n // suffix, which is why #arrayFieldNames excepts it. Converting that to\n // a group here would discard the chosen value — measured, the post lost\n // it — so the editor stands down and the rule below applies, which\n // never overwrites a populated name.\n // Only fill what the standard controls left absent or empty, so a\n // synced hidden input still wins when populated.\n if (existing == null || existing === \"\") {\n fields[name] = own\n }\n })\n return { fields, files }\n }\n\n // Names collected as an ARRAY rather than a single value: a name carrying the\n // `[]` suffix, the HTML convention for a group. That suffix is the ONLY\n // trigger — a group says so, it is not inferred from two controls happening\n // to share a name. Radios are excluded BY DESIGN: a radio group shares one\n // name to mean \"pick one\", and it keeps posting the single checked value,\n // suffix or not.\n //\n // Issue #258: without this, `fields[name] = field.checked` wrote a boolean per\n // checkbox and same-named boxes overwrote each other, so three boxes with two\n // ticked left the browser as the LAST box's checked state — the chosen values\n // never reached the wire, whatever the action's schema declared.\n #arrayFieldNames(controls) {\n const names = new Set()\n for (const field of controls) {\n // A radio group shares one name BY DESIGN to mean \"pick one\" and keeps\n // its single checked value, `[]` suffix or not.\n if (field.type === \"radio\") continue\n if (String(field.name).endsWith(\"[]\")) names.add(field.name)\n }\n return names\n }\n\n // Names whose group carries a hidden COMPANION: a hidden input is Rails' way\n // of giving a checkbox a value for the unchecked case, and it is never a\n // chosen value. Measured from the helpers, the three shapes are:\n //\n // check_box(:u, :sub)\n // <input name=\"u[sub]\" type=\"hidden\" value=\"0\"><input type=\"checkbox\" value=\"1\" name=\"u[sub]\">\n // check_box(:u, :ids, {multiple: true}, \"3\")\n // <input name=\"u[ids][]\" type=\"hidden\" value=\"0\"><input type=\"checkbox\" value=\"3\" name=\"u[ids][]\">\n // collection_check_boxes(...) / an unchecked_value of nil\n // <input type=\"hidden\" name=\"u[ids][]\" value=\"\"> — or no hidden at all\n //\n // The value differs (unchecked_value, blank, absent), so the value cannot be\n // the test. What identifies a companion is that a checkbox shares its name.\n // A hidden WITHOUT a same-named checkbox is a list JS maintains, and its\n // value is a chosen value like any other.\n #companionNames(controls) {\n const names = new Set()\n for (const field of controls) if (field.type === \"checkbox\") names.add(field.name)\n return names\n }\n\n // Build the multipart body (issue #34). `token`/`act` are flat fields the\n // endpoint reads from params[:token]/params[:act]; scalar params nest under\n // params[<key>] (Rails parses the bracket into params[:params]); each file is\n // appended under params[<name>] (single) — a second file with the same name\n // (a `multiple` picker, several inputs sharing a name) is sent as\n // params[<name>][] so Rails coerces it to an array for a [:file] schema.\n #buildFormData(token, action, params, files) {\n const fd = new FormData()\n fd.append(\"token\", token)\n fd.append(\"act\", action)\n const emptyGroups = []\n for (const [key, value] of Object.entries(params)) {\n // A `[]` name carrying an array is the group shape (issue #258): every\n // element goes to params[name][], which Rack parses as an array. The\n // indexed form #appendField writes for a plain array (params[name][0],\n // params[name][1]) arrives as a hash of index keys — ParamSchema's array\n // type normalizes that back, but only an array type does, so the two\n // bodies would stop coercing identically for the same fields.\n //\n // An EMPTY group cannot be an empty array in a form body, so it is\n // ANNOUNCED instead: its key stays absent from params and its name goes\n // into `empty_groups[]`, a field of its own beside token/act/params. A\n // blank entry was the obvious alternative and is ambiguous — Rails leaves\n // `[\"\"]` to the caller, and a `[:date]` or `[:file]` element reads it as\n // \"did not come in\", so treating it as \"cleared\" would change what those\n // params mean. The field is additive: a server that ignores it behaves\n // exactly as it does today, and so does a client that never sends it.\n if (Array.isArray(value) && String(key).endsWith(\"[]\")) {\n if (value.length === 0) {\n emptyGroups.push(String(key).slice(0, -2))\n } else {\n const wire = `${this.#wireKey(key)}[]`\n for (const element of value) fd.append(wire, String(element))\n }\n } else {\n this.#appendField(fd, this.#wireKey(key), value)\n }\n }\n for (const name of emptyGroups) fd.append(\"empty_groups[]\", name)\n const multiNames = this.#multiFileNames(files)\n for (const { name, file, multiple } of files) {\n // params[name][] when the input is `multiple` (array shape even for one\n // file) OR the name repeats across inputs; otherwise a lone scalar file.\n const asArray = multiple || multiNames.has(name)\n const key = asArray ? `${this.#wireKey(name)}[]` : this.#wireKey(name)\n fd.append(key, file, file.name)\n }\n return fd\n }\n\n // The multipart wire key for a collected field/file name: params[...] with\n // the name's OWN brackets expanded into nesting segments (issue #231). The\n // old verbatim wrap of a Rails-bracketed name — params[blog_post[summary]] —\n // is unparseable by Rack: a scalar arrived as {\"blog_post[summary\" => {\"]\" =>\n // value}} (data corruption written through `update!` with a 200) and a file\n // never reached its schema key (silent drop). Expanding blog_post[summary]\n // into params[blog_post][summary] mirrors the server's bracket_path exactly —\n // split at the first \"[\", then each non-empty bracket segment; an empty\n // trailing segment (tags[]) drops, matching how the JSON path's\n // expand_bracket_keys coerces the same name — so a multipart body and a JSON\n // body coerce identically for the same fields (the documented contract).\n // A flat name stays a single params[name] wrap, byte-identical to before.\n #wireKey(name) {\n const raw = String(name)\n const head = raw.indexOf(\"[\")\n if (head === -1) return `params[${raw}]`\n const segments = [raw.slice(0, head), ...(raw.slice(head).match(/[^\\[\\]]+/g) ?? [])]\n return `params${segments.map((segment) => `[${segment}]`).join(\"\")}`\n }\n\n // Append a param leaf to FormData under its bracketed key. FormData carries\n // only strings, so a NON-scalar param (a nested object or an array) is\n // bracket-EXPANDED into params[key][sub] / params[key][index][...] fields —\n // the SAME Rails-form shape the server's expand_bracket_keys / array_values\n // already parse, so a JSON body and a multipart body coerce identically\n // (issue #39). Previously a non-scalar was JSON.stringify'd into one\n // params[key]='<json>' field, which the server received as an un-decodable\n // String leaf and DROPPED (nested hash -> {}, array -> key removed).\n //\n // Arrays use NUMERIC indices (params[key][0], params[key][1]) — required for\n // an array-of-hash so each element's sub-keys stay grouped and the server's\n // index-hash sort rebuilds order; params[key][] would collapse them. A scalar\n // (string/number/boolean) is one string field, mirroring the JSON wire shape\n // (the server's :boolean/:integer casts read \"true\"/\"42\"). null/undefined is\n // an empty field. An EMPTY array/object emits NOTHING — FormData can't carry\n // []/{}, so the key is omitted and the action's keyword default applies (this\n // differs from the JSON path, where an explicit [] coerces to an empty array).\n #appendField(fd, key, value) {\n if (value == null) {\n fd.append(key, \"\")\n } else if (Array.isArray(value)) {\n value.forEach((element, index) => this.#appendField(fd, `${key}[${index}]`, element))\n } else if (typeof value === \"object\") {\n for (const [subKey, subValue] of Object.entries(value)) {\n this.#appendField(fd, `${key}[${subKey}]`, subValue)\n }\n } else {\n fd.append(key, String(value))\n }\n }\n\n // Names that appear more than once across the chosen files (a `multiple`\n // picker, or several file inputs sharing a name) — those go to params[name][]\n // so the server sees an array; a lone file stays params[name].\n #multiFileNames(files) {\n const counts = new Map()\n for (const { name } of files) counts.set(name, (counts.get(name) ?? 0) + 1)\n return new Set([...counts].filter(([, n]) => n > 1).map(([name]) => name))\n }\n\n #parseParams(raw) {\n if (!raw) return {}\n try {\n return typeof raw === \"string\" ? JSON.parse(raw) : raw\n } catch {\n return {}\n }\n }\n\n // Stimulus typecasts a JSON param to the parsed array already; a raw string\n // (hand-built attr, non-typecasting harness) is parsed here. Delegates to the\n // shared parseOps so the controller and the reactive:js stream action (issue\n // #97) treat a malformed ops attr identically (→ [], never a throw).\n #parseOps(raw) {\n return parseOps(raw)\n }\n\n // Interpret a [[name, args], ...] op list against this root (issue #95),\n // scoping each op's targets to this controller's own root via #opTargets (the\n // nested-reactive-root ownership filter, issue #15). The whitelist + skip\n // logic lives in the shared applyOps so runOps and the reactive:js stream\n // action interpret the SAME vocabulary the SAME way (client-side default-deny).\n #applyOps(list) {\n applyOps(\n list,\n (args) => this.#opTargets(args),\n (name, args) => this.#diagnoseZeroTargets(`client op \"${name}\"`, args),\n )\n }\n\n // Issue #237: the verbose gate for zero-target diagnostics — the\n // verbose_errors stamp (ON by default in dev/test) or full debug mode (a\n // debug user must never see less). Read live off the root like #debugEnabled.\n #verboseEnabled() {\n return this.element?.getAttribute?.(\"data-reactive-verbose\") === \"true\" || this.#debugEnabled()\n }\n\n // Issue #237: called when a selector-form target resolved to ZERO elements on\n // this root. Past the verbose gate the devtools feature (issue #275) does the\n // work: the DOM probes, the dedupe, the trap-specific hint.\n #diagnoseZeroTargets(label, args) {\n if (!this.#verboseEnabled()) return\n if (__SPLIT__) this.#devtools((devtools) => devtools.diagnose(this, label, args))\n else devtoolsFeature.diagnose(this, label, args)\n }\n\n // Run `use` with the devtools feature: now when it is loaded (the default\n // client, always), else once it has arrived — a warning or a trace a tick\n // late is still a warning. Called only past a debug/verbose gate, so a page\n // with neither never asks for the module.\n #devtools(use) {\n if (__SPLIT__) withFeature(\"devtools\", use)\n }\n\n // Resolve an op's targets: \"@root\" is this element; a selector resolves\n // WITHIN this root and excludes nested reactive roots' subtrees (issue #15\n // semantics — the same nearest-root ownership check the field walk uses);\n // global: true opts a single op out to document-wide.\n #opTargets(args) {\n const to = args.to\n if (to === \"@root\") return [this.element]\n if (typeof to !== \"string\" || to === \"\") return []\n if (args.global) return [...document.querySelectorAll(to)]\n return [...this.element.querySelectorAll(to)].filter((el) => this.#ownsField(el))\n }\n\n // Whether a click-bound checkbox/radio trigger should keep its NATIVE flip\n // (issue #98). `checked: :keep` means \"let the control flip now\": the\n // unconditional preventDefault is exactly what suppresses that flip until the\n // morph, so we skip it — but ONLY for a checkbox/radio (a bare toggle click\n // has no form-navigation default to lose). Any other element (a button) keeps\n // preventDefault so an in-form submit can't navigate.\n #keepsNativeToggle(optimistic, target) {\n if (optimistic?.checked !== \"keep\") return false\n const type = target?.type\n return type === \"checkbox\" || type === \"radio\"\n }\n\n // Replay the recorded undo ops on failure (issue #98), guarded by isConnected:\n // a plain (non-morph) replace can detach this subtree before the failure lands,\n // and reverting a stale/detached node is pointless (it's gone) — so a\n // disconnected root skips the revert entirely. On success NOTHING calls this:\n // the server re-render overwrites the hint, or (reply.remove / streams-only)\n // the hint is deliberately left standing.\n #revertOptimistic(inverse) {\n if (!inverse) return\n if (!this.element.isConnected) return\n for (const undo of inverse) undo()\n }\n\n // Apply the BUSY state for THIS enqueue (issue #181) and return a `settle`\n // closure that undoes exactly this enqueue's contribution when the round trip\n // finishes (success OR any failure). Everything is refcounted so overlapping\n // enqueues never clobber: A's settle can't clear busy while B is still pending.\n //\n // Two layers:\n // 1. The ALWAYS-ON busy vocabulary (fires for every action, no hint needed):\n // data-reactive-busy=\"<action>\" on the trigger and the root (a\n // space-separated, per-action refcounted set), aria-busy on the root (a\n // pending counter), and data-reactive-busy on any busy_on element scoped\n // to this action. Apps style a spinner with pure CSS and zero Ruby.\n // 2. The busy HINT (only when busy: was declared): the SAME cosmetic op set\n // as optimistic: (class ops, hide/show, disable, text), applied by the\n // hints feature (features/hints.js) and reverted on SETTLE (not on\n // failure) — its undo ops land in `pending.undo`, which the settle\n // closure replays. They apply at ENQUEUE — never during a debounce quiet\n // period — so a debounced input is not disabled mid-typing.\n #applyBusy(action, trigger, pending) {\n this.#markBusy(action, trigger)\n // Global activity signal (issue #201): this enqueue is one in-flight reactive\n // operation. Entered HERE (at enqueue, via #applyBusy) so the document marker\n // covers the whole pending window — queue wait included — exactly like the\n // per-root busy vocabulary. Exited once in the settle closure below, which\n // #perform runs in its finally on EVERY exit path (success or any failure).\n enterReactiveActivity()\n\n let settled = false\n return () => {\n if (settled) return // one settle per enqueue, even if called twice\n settled = true\n this.#unmarkBusy(action, trigger)\n exitReactiveActivity()\n // Busy reverts on SETTLE regardless of outcome, guarded per element.\n for (const op of pending.undo) op()\n }\n }\n\n // Layer 1 — the always-on busy markers. Trigger + root carry the action token;\n // the root's counter drives aria-busy; busy_on elements scoped to this action\n // light up. Refcounts (#busyActions, #busyPending) so overlapping requests\n // don't clear each other.\n #markBusy(action, trigger) {\n this.#setBusyToken(trigger, action, +1)\n this.#setBusyToken(this.element, action, +1)\n\n this.#busyActions.set(action, (this.#busyActions.get(action) ?? 0) + 1)\n if (this.#busyPending++ === 0) this.element.setAttribute(\"aria-busy\", \"true\")\n\n for (const el of this.#busyOnTargets(action)) this.#setBusyToken(el, action, +1)\n }\n\n #unmarkBusy(action, trigger) {\n this.#setBusyToken(trigger, action, -1)\n this.#setBusyToken(this.element, action, -1)\n\n const count = (this.#busyActions.get(action) ?? 1) - 1\n if (count <= 0) this.#busyActions.delete(action)\n else this.#busyActions.set(action, count)\n\n if (--this.#busyPending <= 0) {\n this.#busyPending = 0\n this.element.removeAttribute(\"aria-busy\")\n }\n\n for (const el of this.#busyOnTargets(action)) this.#setBusyToken(el, action, -1)\n }\n\n // Add (+1) or remove (-1) `action` from an element's space-separated\n // data-reactive-busy token set, refcounted PER ELEMENT+ACTION so two queued\n // requests of the same action on the same element don't drop the token early\n // (and two DIFFERENT actions both keep their token — the set never clobbers).\n // The attribute is removed only when the set empties. No-op on a nullish/\n // detached element (a morph may have replaced the trigger before settle).\n #setBusyToken(el, action, delta) {\n if (!el || typeof el.getAttribute !== \"function\") return\n\n const counts = (this.#busyTokenCounts.get(el) ?? new Map())\n const next = (counts.get(action) ?? 0) + delta\n if (next <= 0) counts.delete(action)\n else counts.set(action, next)\n\n if (counts.size === 0) {\n this.#busyTokenCounts.delete(el)\n el.removeAttribute(\"data-reactive-busy\")\n return\n }\n this.#busyTokenCounts.set(el, counts)\n el.setAttribute(\"data-reactive-busy\", [...counts.keys()].join(\" \"))\n }\n\n // busy_on elements scoped to THIS action, owned by this root (not a nested\n // reactive root's, issue #15). data-reactive-busy-on=\"<action>\" is the marker\n // busy_on(:action) emits.\n #busyOnTargets(action) {\n const nodes = this.element.querySelectorAll?.(\"[data-reactive-busy-on]\") ?? []\n return [...nodes].filter(\n (el) => el.getAttribute(\"data-reactive-busy-on\") === action && this.#ownsField(el),\n )\n }\n\n // The action path comes from a <meta> tag that is fixed for the page's life,\n // so resolve it once per controller and cache it — avoids a querySelector on\n // every dispatch (this runs on the request hot path, once per click/keystroke\n // round trip). Cached on the instance, so a fresh connect() (after a Turbo\n // navigation swaps the element) re-reads it.\n #actionPath() {\n return (this.#actionPathCache ??=\n document.querySelector('meta[name=\"phlex-reactive-action-path\"]')?.content ||\n \"/reactive/actions\")\n }\n\n // The per-request timeout in ms (issue #101), from a page-stable\n // <meta name=\"phlex-reactive-timeout\"> (default 30000). Cached per-controller\n // like the action path. Parsed defensively: a missing/blank/non-positive/NaN\n // value falls back to the default, so a typo'd meta can never disable the\n // timeout (which would reintroduce the wedged-queue bug) or set a zero/negative\n // window that aborts instantly.\n #timeoutMs() {\n if (this.#timeoutMsCache != null) return this.#timeoutMsCache\n const raw = document.querySelector('meta[name=\"phlex-reactive-timeout\"]')?.content\n const ms = Number(raw)\n return (this.#timeoutMsCache = Number.isFinite(ms) && ms > 0 ? ms : 30000)\n }\n\n // CSRF token and connection id are read LIVE (not cached) on purpose: Rails\n // can rotate the CSRF token, and the pgbus connection id changes on an SSE\n // reconnect — caching either would send a stale value. A single querySelector\n // per request is cheap next to the round trip itself.\n #csrfToken() {\n return document.querySelector('meta[name=\"csrf-token\"]')?.content ?? \"\"\n }\n\n // The pgbus SSE connection id, if the page is subscribed to a stream. pgbus\n // reflects it onto the <pgbus-stream-source connection-id=\"…\"> element (and\n // apps may mirror it to <meta name=\"pgbus-connection-id\">). Returns null\n // when not present (e.g. no pgbus, or no active subscription) — the header\n // is then simply omitted.\n #connectionId() {\n return (\n document.querySelector(\"pgbus-stream-source[connection-id]\")?.getAttribute(\"connection-id\") ||\n document.querySelector('meta[name=\"pgbus-connection-id\"]')?.content ||\n null\n )\n }\n}\n\n// Register with Turbo as soon as it is there. LAST in the file: registration\n// reads the feature table (the dev module is loaded from it), which must\n// exist by then.\nif (typeof window !== \"undefined\") {\n if (window.Turbo) registerReactiveActions()\n else document.addEventListener(\"turbo:load\", registerReactiveActions, { once: true })\n}\n",
6
- "// phlex/reactive/features/bindings — what a form root wires at connect and\n// re-syncs after a morph, all of it client-only and all of it reading the\n// root's own controls: show bindings and cross-root show targets (issues\n// #161, #164, #176, #180, #209), completion bindings (#226), option filtering\n// (#163), the tag-chip input (#203), draft nested-attribute rows with their\n// JSON mode (#208) and fields fed into CSS custom properties (#417). One of the feature modules the opt-in client imports on\n// demand (issue #275); in the default client it is part of the one file.\n//\n// Grouped because they share a shape — a marker check at connect, one\n// delegated listener pair on the root, a seed, the same pass again on\n// turbo:morph-element — and a page: a form with a show binding is the form\n// that filters options and adds rows. The seeds here write visible state\n// (and the JSON mode writes a hidden field a request collects), so with the\n// opt-in client the feature `gates`: a root's requests wait for it.\n//\n// The conditional confirm (issue #179) lives here too: its condition is the\n// same DNF fold a show binding uses, and its `predicate:` form reads the\n// confirm_predicate seam — imported here by its bare name, so the runtime no\n// longer imports it. A plain string confirm: never comes here; a conditional\n// one on the opt-in client waits for this module before its dialog (a root\n// with one preloads it).\n//\n// This module never imports the runtime: it reaches a controller through the\n// `core` handle.\nimport { confirmPredicate } from \"phlex/reactive/confirm_predicate\"\n\n// controller -> its context: the root, the core handle, and what used to be\n// the controller's own fields for these features. Every field it does not\n// set here starts undefined (falsy); a property name is one thing the\n// minifier never renames, so the record carries no more of them than it\n// must (issue #310).\nconst contexts = new WeakMap()\n// root element -> the same context, for the check_group op (issue #342),\n// which names a root, not a controller.\nconst rootContexts = new WeakMap()\n\nfunction ctx(controller, core) {\n let c = contexts.get(controller)\n if (!c) {\n contexts.set(controller, (c = { root: controller.element, core, nestedIndex: 0 }))\n if (c.root) rootContexts.set(c.root, c)\n }\n return c\n}\n\n// Add a delegated listener on the root for each of the space-separated\n// `types`, and keep its removal for disconnect().\nfunction listen(c, types, handler) {\n for (const type of types.split(\" \")) {\n c.root.addEventListener?.(type, handler)\n c.offs.push(() => c.root.removeEventListener?.(type, handler))\n }\n}\n\n// What connect() wires is one seed per binding: it runs now, again on\n// turbo:morph-element, and again from reseed().\nfunction seed(c, run) {\n listen(c, \"turbo:morph-element\", run)\n c.seeds.push(run)\n run()\n}\n\nexport function connect(controller, core) {\n const c = ctx(controller, core)\n c.offs = []\n c.seeds = []\n // Each binding below is wired once, the first time its gate reads true:\n // here, and again from reseed() — a stream can render a root's first show\n // target, filter or nested list into it after connect (issue #356).\n let resetting\n let filtering\n let tagging\n let serializing\n ;(c.wire = () => {\n // Show bindings (issue #161) — ONLY when this root owns one, so a component\n // without any pays a single probe (the dirty-tracking gate precedent). ONE\n // delegated listener pair on the root (input + change bubble from every\n // owned field — no per-field wiring, and a reactive_compute output write\n // dispatches a real input event, so computed values drive visibility too).\n // The connect sync seeds the initial state — a plain replace re-connects —\n // and turbo:morph-element re-syncs after an in-place morph (which keeps the\n // element connected, fires no Stimulus lifecycle, and may preserve a\n // user-edited field value the server's hidden attrs don't reflect).\n if (!c.show && showSyncEnabled(c)) {\n // A select-all header's edit flips its group first (issue #319) — on\n // `input`, which a click fires BEFORE `change`, or the pass below would\n // reset the header to its group's state first (the flip is idempotent, so\n // the `change` that follows flips nothing). The change events it\n // dispatches re-enter here and are skipped while it flips, so the pass\n // after the loop runs once, not once per box.\n c.show = (event) => {\n if (c.flipping) return\n // Only a user edit pushes the header onto its group; a morph (whose\n // turbo:morph-element bubbles from the header too) derives it instead.\n if (event?.type === \"input\" || event?.type === \"change\") flipGroup(c, event.target)\n // Whether this root has group bindings is read at connect and again on\n // a morph (which may add one, and so need the observer) — never per\n // keystroke.\n else {\n c.groups = hasGroups(c)\n observeGroups(c)\n }\n syncShow(c)\n }\n listen(c, \"input change\", c.show)\n // The after: gate (issue #396): an owned field's first blur marks its\n // name touched for this controller (a morph keeps it, a new one starts\n // without), and re-syncs once if a binding waits on a blur.\n listen(c, \"focusout\", (event) => {\n const name = event.target?.getAttribute?.(\"name\")\n if (!name || c.touched?.has(name) || !c.core.owns(event.target)) return\n ;(c.touched ??= new Set()).add(name)\n if (c.root.querySelector?.(\"[data-reactive-show-after]\")) syncShow(c)\n })\n seed(c, c.show)\n }\n\n // Completion bindings (issue #226) — ONLY when the root declares\n // data-reactive-on-complete (the show/filter gate precedent). ONE\n // delegated input+change listener evaluates every binding's DNF over the\n // owned fields and runs its ops on the RISING EDGE — the event-driven\n // flip to true. The connect pass ARMS without firing (a fresh render with\n // already-satisfied conditions must never self-fire — the $ops seed\n // precedent), and turbo:morph-element re-arms the same way after an\n // in-place morph. Listeners added HERE run after the Stimulus-wired\n // recompute delegation for the same event, so the evaluation reads\n // compute-NORMALIZED values (and a compute output write dispatches a real\n // input event that re-evaluates anyway).\n if (!c.arm && onCompleteEnabled(c)) {\n listen(c, \"input change\", (event) => syncOnComplete(c, event))\n seed(\n c,\n (c.arm = () => {\n syncOnComplete(c, null)\n observeGroups(c)\n }),\n )\n }\n\n // A form reset (issue #342) restores its fields AFTER the `reset` event\n // dispatches (and only if nothing cancelled it), so this waits a task, then\n // re-syncs the bindings and re-arms the completion latches without firing\n // (a reset fires no input/change, so a checked-count latch would stay high).\n if (!resetting && (resetting = c.show || c.arm)) {\n listen(c, \"reset\", () =>\n setTimeout(() => {\n if (contexts.get(controller) !== c) return\n c.show?.()\n c.arm?.()\n }, 0),\n )\n }\n\n // Option filtering (issue #163) — ONLY when the root declares the binding\n // (reactive_filter emits both attrs together), so a component without one\n // pays two attribute reads. ONE delegated input listener on the root — the\n // handler re-filters only for events from the NAMED input, so keystrokes in\n // unrelated fields on a wide form never pay a filter pass. The connect sync\n // seeds from the input's current value (a plain replace re-connects; back\n // navigation may restore typed text), and turbo:morph-element re-applies\n // after an in-place morph (which keeps the element connected, fires no\n // Stimulus lifecycle, and may preserve the user's typed query while the\n // server re-rendered every option visible).\n if (!filtering && (filtering = filterEnabled(c))) {\n listen(c, \"input\", (event) => filterInputEvent(c, event) && syncFilter(c))\n seed(c, () => syncFilter(c))\n }\n\n // Tag-chip input (issue #203) — ONLY when the root names the hidden value\n // field (reactive_tags), so a component without one pays one attribute\n // read. The chip list is a CLIENT PROJECTION of the hidden field's\n // comma-joined value: connect seeds it (a plain replace re-connects with\n // the server-rendered value), and turbo:morph-element re-projects after an\n // in-place morph (the morph wrote server truth into the hidden field while\n // the chips DOM kept the pre-morph projection). Registered AFTER the\n // filter's listeners so a morph re-filters first and the tags pass then\n // re-marks selected options on the fresh visibility state.\n if (!tagging && (tagging = tagsEnabled(c))) seed(c, () => syncTags(c))\n\n // JSON-mode nested rows (issue #208) — ONLY when the root owns a list with\n // `as: :json`, so a form without one pays a single probe (the show/filter/\n // tags gate precedent). ONE delegated input + change listener re-serializes\n // the rows into the hidden field on every owned edit (nestedAdd/Remove call\n // the sync directly; this covers typing into a row's fields). The connect\n // seed writes the initial array (a plain replace re-connects), and\n // turbo:morph-element re-seeds after an in-place morph (which keeps the\n // element connected, fires no Stimulus lifecycle, and may have rewritten\n // the rows to server truth while the hidden field kept its pre-morph value).\n if (!serializing && (serializing = nestedJsonEnabled(c))) {\n listen(c, \"input change\", (event) => syncNestedJson(c, event))\n seed(c, () => syncAllNestedJson(c))\n }\n })()\n\n // Editable text (issue #351). Delegated keys, paste and drop on the root,\n // whether or not it owns an editable yet: a stream can append the first one\n // into a root whose bindings connected for another marker (each handler\n // returns at once for an event that is not an owned editable's).\n listen(c, \"keydown\", (event) => editableKey(c, event))\n listen(c, \"paste drop\", (event) => editablePaste(c, event))\n listen(c, \"input\", (event) => editableEmptied(c, event))\n}\n\n// Remove every listener connect() added, so a stray event after a Turbo\n// morph/navigation never re-evaluates against a detached root.\nexport function disconnect(controller) {\n const c = contexts.get(controller)\n if (!c) return\n contexts.delete(controller)\n rootContexts.delete(c.root)\n for (const off of c.offs ?? []) off()\n c.groupObserver?.disconnect()\n}\n\n// Re-run the seeds that read field values, in connect() order — for a\n// feature that changed those values after connect() ran (the draft restore),\n// or content a stream rendered into the root (issue #356) — then wire any\n// binding whose gate reads true only now. Each seed is the same re-sync a\n// morph runs; on-complete re-ARMS without firing.\nexport function reseed(controller) {\n const c = contexts.get(controller)\n if (!c) return\n for (const run of c.seeds) run()\n c.wire()\n}\n\n// A value this module wrote is announced the way a user's edit is: a bubbling\n// `input` (the set-value + dispatch contract, issue #183), so dirty tracking,\n// reactive_show and compute all see it.\nfunction fireInput(el) {\n if (typeof el.dispatchEvent === \"function\") el.dispatchEvent(new Event(\"input\", { bubbles: true }))\n}\n\n// The Stimulus actions this module answers (the controller's own methods of\n// the same names hand the event here). tagsAdd, tagsPick, tagsRemove,\n// nestedAdd and nestedRemove take the controller themselves; the JSON sync is\n// also the root's own listener, so it keeps its context form inside.\nfunction publicSyncNestedJson(controller, core, event) {\n return syncNestedJson(ctx(controller, core), event)\n}\nexport { publicSyncNestedJson as syncNestedJson }\n\n// The runtime's call-in for a conditional confirm: the message when its\n// condition fires over this root's fields, else null.\nexport function confirmMessage(controller, core, confirmWhen) {\n return conditionalConfirmMessage(ctx(controller, core), confirmWhen)\n}\n\n// An id-only selector (the issue #159/#164 allowlist for anything that\n// escapes the root).\nconst ID_SELECTOR = /^#[A-Za-z_][\\w-]*$/\n\n// The selector matching every OWNED-element show binding: single-field\n// (data-reactive-show-field, issue #161) OR compound all:/any:\n// (data-reactive-show, issue #176). Both the connect() gate and the sync walk\n// use it so a compound-only root still enables the sync.\nconst SHOW_BINDING_SELECTOR = \"[data-reactive-show-field], [data-reactive-show]\"\n\n// Evaluate a show binding's declared literal predicate (issue #161) against\n// the controlling field's current value. Exactly one of the three predicate\n// attrs decides: equals (value === literal), not (value !== literal), in\n// (value ∈ a JSON string list). The vocabulary is fixed and literal-only —\n// never an expression, so there is no eval surface (the reactive_show helper\n// enforces the same shape loudly at render; this is the client half of the\n// two-sided posture). Returns true/false for a decidable binding, or null for\n// a malformed/missing predicate — the caller SKIPS a null so a hand-built or\n// stale binding never flips visibility it doesn't understand (default-deny,\n// like the op whitelist).\nfunction showBindingMatches(el, value) {\n const equals = el.getAttribute(\"data-reactive-show-equals\")\n if (equals !== null) return value === equals\n const not = el.getAttribute(\"data-reactive-show-not\")\n if (not !== null) return value !== not\n const inRaw = el.getAttribute(\"data-reactive-show-in\")\n if (inRaw !== null) {\n try {\n const list = JSON.parse(inRaw)\n if (Array.isArray(list)) return list.includes(value)\n } catch {\n // fall through to the warn below — malformed JSON and a non-array both skip\n }\n console.warn(`[phlex-reactive] malformed reactive_show in: list ${JSON.stringify(inRaw)} — skipped`)\n return null\n }\n // Numeric threshold predicates (issue #176 part B): gte/gt/lte/lt read the\n // literal off its own flat attr and compare Number(value) against it. Any\n // present numeric attr decides the binding — a non-numeric field value (NaN)\n // is false (hidden), and a non-numeric LITERAL warn-skips (null).\n for (const key of SHOW_NUMERIC_KEYS) {\n const raw = el.getAttribute(`data-reactive-show-${key}`)\n if (raw !== null) return numericPredicateMatches(key, raw, value)\n }\n console.warn(\"[phlex-reactive] a reactive_show binding declares no predicate — skipped\")\n return null\n}\n\n// Parse a compound show binding's JSON payload (issue #176 part A). Malformed\n// JSON degrades to null WITH a warn — a bad binding must never throw or blank\n// the page (client-side default-deny), but a collision (two bindings' JSON\n// mix-joined) is worth surfacing.\nfunction parseShowCompound(raw) {\n try {\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed\n } catch {\n // fall through to the warn\n }\n console.warn(`[phlex-reactive] malformed compound reactive_show payload ${JSON.stringify(raw)} — skipped`)\n return null\n}\n\n// Parse a data-reactive-on-complete payload (issue #226): a JSON array of\n// { any: [[term, …], …], ops: [[op, args], …] } bindings. Malformed JSON, a\n// non-array, or a binding missing either half degrades to [] WITH a warn — a\n// bad payload must never throw or fire an op (client-side default-deny, the\n// parseShowCompound posture).\nfunction parseOnComplete(raw) {\n try {\n const list = JSON.parse(raw)\n if (\n Array.isArray(list) &&\n list.every((b) => b && typeof b === \"object\" && Array.isArray(b.any) && Array.isArray(b.ops))\n ) {\n return list\n }\n } catch {\n // fall through to the warn\n }\n console.warn(`[phlex-reactive] malformed reactive_on_complete payload ${JSON.stringify(raw)} — skipped`)\n return []\n}\n\n// Route a parsed data-reactive-show payload to the right evaluator. The 0.10\n// wire is { any: [ [term,…], … ] } (DNF — groups are ARRAYS). For a stale tab\n// still serving pre-0.10 HTML (deploy overlap), fall back to the 0.9.5 compound\n// shape { all: [term,…] } / { any: [term,…] } where the values are flat TERM\n// OBJECTS, not arrays. The nesting distinguishes them: DNF's any[0] is an Array.\n// DELETE the legacy arm in 0.11.\nfunction showPayloadMatches(payload, fieldValue) {\n if (!payload || typeof payload !== \"object\") return null\n const any = payload.any\n if (Array.isArray(any) && (any.length === 0 || Array.isArray(any[0]))) {\n return anyOfAllsMatches(any, fieldValue)\n }\n return legacyCompoundShowMatches(payload, fieldValue)\n}\n\n// LEGACY (0.9.5, deploy-overlap only — DELETE in 0.11): the flat all:/any:\n// compound fold, where terms are objects (not groups). Preserved so a morph of\n// stale pre-0.10 HTML doesn't go dead.\nfunction legacyCompoundShowMatches(payload, fieldValue) {\n const connective = Array.isArray(payload.all) ? \"all\" : Array.isArray(payload.any) ? \"any\" : null\n if (!connective) return null\n const terms = payload[connective]\n if (terms.length === 0) return null\n const results = terms.map((term) => dnfTermMatches(term, fieldValue))\n return connective === \"all\" ? results.every(Boolean) : results.some(Boolean)\n}\n\n// A cross-root show target must be a single ID selector (issue #164) — the\n// SAME shape the #159 mirror enforces (one shared regex), with its own warn so\n// a refused show target is distinguishable in the console. The client half of\n// the two-sided default-deny: reactive_show_targets raises at declare time; a\n// hand-built wire attr must not widen the escape to class/compound selectors.\n// A refused selector warns + skips — its siblings still apply. The group\n// targets (issue #343) share it, naming their own kind in the warn.\nfunction guardShowTargetSelector(selector, kind = \"show\") {\n if (typeof selector === \"string\" && ID_SELECTOR.test(selector)) return true\n console.warn(`[phlex-reactive] refused cross-root ${kind} target ${JSON.stringify(selector)} — skipped`)\n return false\n}\n\n\n// Whether this root owns a show binding (issue #161) or declares cross-root\n// show targets (issue #164) — the connect() gate, so a component with\n// neither pays only this probe (the #dirtyTrackingEnabled precedent). A\n// NESTED root's bindings don't count: its own controller instance syncs them\n// (issue #15 ownership). The targets attr is checked FIRST — one\n// getAttribute, cheaper than the binding walk.\nfunction showSyncEnabled(c) {\n if (c.root.getAttribute?.(\"data-reactive-show-targets\")) return true\n if (c.root.getAttribute?.(\"data-reactive-group-targets\")) return true\n // Single-field bindings carry -field; compound all:/any: bindings (issue\n // #176) carry data-reactive-show and have NO single controlling field, so\n // both selectors gate the sync.\n const nodes = c.root.querySelectorAll?.(SHOW_BINDING_SELECTOR) ?? []\n for (const el of nodes) if (c.core.owns(el)) return true\n for (const el of c.root.querySelectorAll?.(GROUP_BINDING_SELECTOR) ?? []) if (c.core.owns(el)) return true\n for (const el of c.root.querySelectorAll?.(`${MEDIA_BINDING_SELECTOR}, ${CSS_VARS_SELECTOR}`) ?? []) {\n if (c.core.owns(el)) return true\n }\n return c.root.hasAttribute?.(\"data-reactive-css-vars\") ?? false\n}\n\n// The connect() gate for completion bindings (issue #226) — one attribute read.\nfunction onCompleteEnabled(c) {\n return !!c.root.getAttribute?.(\"data-reactive-on-complete\")\n}\n\n// Parse-and-memoize the completion bindings, keyed on the RAW attr string:\n// a morph that rewrote the payload re-parses and RESETS the latches (the\n// morph listener's own arm pass then re-arms without firing). A removed\n// attr yields [] silently; malformed JSON warns (in parseOnComplete).\nfunction onCompleteBindings(c) {\n const raw = c.root.getAttribute?.(\"data-reactive-on-complete\") ?? null\n if (raw !== c.onCompleteRaw) {\n c.onCompleteRaw = raw\n c.onCompleteParsed = raw == null ? [] : parseOnComplete(raw)\n c.onCompleteStates = c.onCompleteParsed.map(() => false)\n }\n return c.onCompleteParsed\n}\n\n// Evaluate every completion binding (issue #226) over the owned fields —\n// the SAME memoized, scope-aware field resolver and DNF fold the show sync\n// uses — and run each binding's ops on ITS OWN rising edge. `event` null\n// (the connect/morph arm pass) updates the latches WITHOUT firing, so ops\n// only ever run from a real user gesture. An undecidable payload (no\n// groups) leaves its latch alone — default-deny, like every malformed-wire\n// arm. Ops resolve through runOps's root-scoped targets; a missing to:\n// defaults to \"@root\" (the $ops convention).\nfunction syncOnComplete(c, event) {\n const bindings = onCompleteBindings(c)\n if (!bindings.length) return\n\n const fieldValue = fieldResolver(c, c.core.ownership())\n bindings.forEach((binding, i) => {\n const matches = anyOfAllsMatches(binding.any, fieldValue)\n if (matches === null) return\n const fire = matches && !c.onCompleteStates[i] && Boolean(event)\n c.onCompleteStates[i] = matches\n if (fire) {\n c.core.applyOps(binding.ops, \"@root\")\n }\n })\n}\n\n// Re-evaluate every OWNED show binding in one pass (issue #161): read the\n// controlling field's current value, evaluate the declared literal predicate,\n// toggle `hidden`. A full pass (not per-target) for the same reason as\n// #scanDirty — a radio group's deselected radio fires no event — and because\n// several bindings can hang off one field (the value read is memoized per\n// pass). A binding whose field can't be resolved, or whose predicate is\n// malformed, leaves visibility ALONE — a bad binding must never break or\n// blank the page (client-side default-deny).\nfunction syncShow(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return\n\n const owns = c.core.ownership()\n const scope = c.root.getAttribute?.(\"data-reactive-scope\") || null\n // A memoized resolver shared by every binding in this pass — a field driving\n // several bindings (and several DNF terms) reads exactly once. Scope-aware:\n // a bare field `director` resolves as `[name=\"scope[director]\"]` (issue #180).\n const fieldValue = fieldResolver(c, owns)\n // Bindings whose visibility flipped this pass and that declare transition\n // work (issue #394) — run after the pass, so the `input` a clear dispatches\n // re-syncs from fresh values instead of this pass's memo.\n const moved = []\n for (const el of c.root.querySelectorAll(SHOW_BINDING_SELECTOR)) {\n if (!owns(el)) continue // a nested root's binding is its own controller's job\n\n // The 0.10 DNF payload (issue #180): data-reactive-show carries\n // { any: [ [term,…], … ] }. The legacy flat-attr and 0.9.5-compound read\n // arms live in showPayloadMatches/showBindingMatches for deploy overlap.\n const payloadRaw = el.getAttribute(\"data-reactive-show\")\n if (payloadRaw !== null) {\n const match = showPayloadMatches(parseShowCompound(payloadRaw), fieldValue)\n if (match === null) continue\n // after: (issue #396) keeps it hidden until its field has blurred once.\n const after = el.getAttribute(\"data-reactive-show-after\")\n const visible = match && (after == null || !!c.touched?.has(wireName(after, scope)))\n applyShowVisibility(el, visible, owns, scope)\n // The previous visibility lives on this controller (absent on connect,\n // kept by a morph), so first paint never counts as a change.\n // Tracked for every binding, so a morph that drops the transition attrs\n // and later restores them never compares against a stale value.\n const was = (c.shown ??= new WeakMap()).get(el)\n c.shown.set(el, visible)\n const moves = SHOW_MOVES.some((name) => el.hasAttribute(`data-reactive-show-${name}`))\n if (moves && was !== undefined && was !== visible) moved.push(el)\n continue\n }\n\n // LEGACY flat-attr binding (pre-0.10, deploy overlap — removed in 0.11).\n const name = el.getAttribute(\"data-reactive-show-field\")\n if (!name) continue\n const value = fieldValue(name)\n if (value === null) continue // no owned field with that name — leave it be\n const match = showBindingMatches(el, value)\n if (match === null) continue // malformed predicate — warned + skipped\n applyShowVisibility(el, match, owns, scope)\n }\n\n // The group bindings (issue #319) and the cross-root pass (issue #164)\n // share the same owned-field memo, so a field driving several reads once.\n if (c.groups) syncGroups(c, fieldValue, owns, scope)\n syncMedia(c, fieldValue, owns)\n syncCssVars(c, fieldValue, owns, scope)\n syncShowTargets(c, fieldValue)\n syncGroupTargets(c, fieldValue)\n for (const el of moved) showMoved(c, el, owns, scope)\n}\n\n// The transition attrs a show binding may declare (issue #394).\nconst SHOW_MOVES = [\"clear\", \"focus\", \"scroll\"]\n\n// A binding just changed visibility (issue #394). Hidden: empty each clear:\n// field with set_value's write (which announces only a real change), uncheck a\n// checkbox or radio, skip a file input. Visible: scroll the section into view,\n// then focus the first match of focus: inside the root.\nfunction showMoved(c, el, owns, scope) {\n if (el.hidden) {\n let names = []\n try {\n names = JSON.parse(el.getAttribute(\"data-reactive-show-clear\") ?? \"[]\")\n } catch {}\n // Compared by attribute, not a [name=\"…\"] selector, so a name holding a\n // `\"` or `\\` clears its field instead of throwing.\n const wires = new Set((Array.isArray(names) ? names : []).map((name) => wireName(String(name), scope)))\n for (const field of wires.size ? c.root.querySelectorAll(\"[name]\") : []) {\n if (!wires.has(field.getAttribute(\"name\")) || !owns(field) || field.type === \"file\") continue\n if (field.type === \"checkbox\" || field.type === \"radio\") {\n if (field.checked) {\n field.checked = false\n fireInput(field)\n }\n } else c.core.setValue(field, \"\")\n }\n return\n }\n const scroll = el.getAttribute(\"data-reactive-show-scroll\") === \"true\"\n if (scroll) el.scrollIntoView?.({ block: \"nearest\" })\n const focus = el.getAttribute(\"data-reactive-show-focus\")\n let target = null\n try {\n target = focus ? c.root.querySelector(focus) : null\n } catch {}\n target?.focus?.(scroll ? { preventScroll: true } : undefined)\n}\n\n// Toggle `hidden` (and, when the binding declares data-reactive-show-disable,\n// the `disabled` of every owned named control inside it) from a match result\n// (issue #180). Disabling a hidden section's controls stops them submitting —\n// the stale-value fix. A visible section re-enables them. Controls a nested\n// reactive root owns are left alone (#15 ownership).\nfunction applyShowVisibility(el, match, owns, scope) {\n el.hidden = !match\n if (el.getAttribute(\"data-reactive-show-disable\") !== \"true\") return\n if (typeof el.querySelectorAll !== \"function\") return\n for (const control of el.querySelectorAll(\"input[name], select[name], textarea[name]\")) {\n if (owns(control)) control.disabled = !match\n }\n // The element itself may be a named control (a bare field with a binding).\n if (el.name && owns(el)) el.disabled = !match\n}\n\n// Apply the declared cross-root show targets (issue #164) — the visibility\n// parallel of #applyComputeMirrors. For each declared field: read the OWNED\n// field's current value (never a nested root's — you can only drive outside\n// visibility from a field this root owns), then for each \"#id\" → predicate\n// entry: guard the selector id-only (warn-and-skip; the Ruby helper raised\n// at declare time — two-sided default-deny), resolve it DOCUMENT-WIDE, and\n// toggle `hidden`. A target id not on the page is silently skipped (an\n// unrendered tab pane is normal); a malformed predicate warn-skips its one\n// target while siblings still apply. With no map declared this is one\n// getAttribute and out.\n//\n// A \"#id\" KEY (issue #209) is a TARGET-KEYED entry instead: its value is the\n// same DNF payload data-reactive-show holds, folded with per-term owned-field\n// reads — the multi-field cross-root case. The \"#\" prefix routes unambiguously\n// (a field name may never start with \"#\"; the Ruby helper raises).\nfunction syncShowTargets(c, fieldValue) {\n const map = parseShowTargets(c)\n for (const [name, targets] of Object.entries(map)) {\n if (name.startsWith(\"#\")) {\n applyConditionsTarget(name, targets, fieldValue)\n continue\n }\n if (!targets || typeof targets !== \"object\" || Array.isArray(targets)) continue\n const value = fieldValue(name)\n if (value === null) continue // no owned field with that name — leave them be\n // Every target's terms share this one field, so a constant resolver folds\n // the group (issue #180): a target's value is a DNF GROUP (terms ANDed).\n // (A checked_* term asks for the group's count instead, issue #319.)\n const resolve = (_, count) => (count ? fieldValue(name, true) : value)\n for (const [selector, group] of Object.entries(targets)) {\n if (!guardShowTargetSelector(selector)) continue\n // 0.10 wire: the value is a DNF GROUP (an array of terms, ANDed).\n // LEGACY (0.9.5, deploy overlap — DELETE in 0.11): a flat predicate\n // OBJECT ({ equals/not/in/gte… }) routed through showPredicateMatches.\n let match\n if (Array.isArray(group)) {\n if (group.length === 0) {\n console.warn(`[phlex-reactive] malformed reactive_show_targets group for ${selector} — skipped`)\n continue\n }\n match = group.every((term) => dnfTermMatches(term, resolve))\n } else {\n const legacy = showPredicateMatches(group, value)\n if (legacy === null) {\n console.warn(`[phlex-reactive] malformed reactive_show_targets predicate for ${selector} — skipped`)\n continue\n }\n match = legacy\n }\n for (const node of document.querySelectorAll(selector)) node.hidden = !match\n }\n }\n}\n\n// Apply ONE target-keyed conditions entry (issue #209): \"#id\" → the DNF\n// payload { any: [[term,…],…] }, folded by the SAME anyOfAllsMatches as an\n// in-root reactive_show — each term reads its OWN owned field, a missing\n// owned field reads as blank (fail-closed, the shared-fixture contract). A\n// target whose referenced fields are ALL unowned is left alone — the\n// single-field skip generalized (this root has nothing to evaluate with) —\n// unless every term is a checked_* count (issue #348): a group with no owned\n// boxes counts 0, so that target is always decidable, as in-root. A\n// malformed payload warn-skips its one target while siblings still apply;\n// the selector guard is the same id-only allowlist as every cross-root arm.\nfunction applyConditionsTarget(selector, payload, fieldValue) {\n if (!guardShowTargetSelector(selector)) return\n const groups = payload && typeof payload === \"object\" && !Array.isArray(payload) ? payload.any : null\n const fields = dnfGroupFields(groups)\n if (fields === null) {\n console.warn(`[phlex-reactive] malformed reactive_show_targets conditions for ${selector} — skipped`)\n return\n }\n if (fields.every((name) => fieldValue(name) === null) && !countsOnly(groups)) return // no owned field — leave it be\n const match = anyOfAllsMatches(groups, fieldValue)\n if (match === null) return // unreachable after dnfGroupFields, kept fail-closed\n for (const node of document.querySelectorAll(selector)) node.hidden = !match\n}\n\n// The declared cross-root show-target map (issue #164): a JSON object of\n// { field: { \"#id\": predicate } } from data-reactive-show-targets (emitted\n// by reactive_show_targets on the root). Absent degrades to {}; malformed\n// degrades to {} WITH a warn — never a throw (the #parseComputeMirror\n// contract), but never silent either: the likeliest cause is TWO\n// reactive_show_targets calls on one root, whose JSON strings Phlex `mix`\n// space-joined into an unparseable attr. The warn names the fix.\nfunction parseShowTargets(c, kind = \"show\", fix = \"mode: { ... }, kind: { ... }\") {\n const raw = c.root.getAttribute?.(`data-reactive-${kind}-targets`)\n if (!raw) return {}\n try {\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed\n } catch {\n // fall through to the shared warn below\n }\n console.warn(\n `[phlex-reactive] malformed data-reactive-${kind}-targets — ignored. ` +\n `Did two reactive_${kind}_targets calls collide on one root? Declare every entry in ONE call: ` +\n `reactive_${kind}_targets(${fix})`\n )\n return {}\n}\n\n// The current value of the OWNED field controlling a show binding, as the\n// string the literal predicate compares against. Mirrors #collectFields'\n// per-kind reads: a checkbox reports its checked state (\"true\"/\"false\" — its\n// .value is the constant \"on\", and the checkbox wins over the hidden input\n// Rails pairs with it); a radio group reports the CHECKED radio's value (\"\"\n// when none is); anything else reports .value first-wins. Returns null when\n// no owned field carries the name — the caller then leaves visibility alone.\nfunction showFieldValue(c, name, owns, scope) {\n let sawRadio = false\n let first = null\n for (const el of c.root.querySelectorAll(namedSelector(name, scope))) {\n if (!owns(el)) continue\n if (el.type === \"checkbox\") return el.checked ? \"true\" : \"false\"\n if (el.type === \"radio\") {\n if (el.checked) return el.value ?? \"\"\n sawRadio = true\n continue\n }\n first ??= el\n }\n if (first) return first.value ?? \"\"\n return sawRadio ? \"\" : null\n}\n\n// Scope (issue #180): a bare field `director` under `data-reactive-scope=\n// \"form\"` resolves as `[name=\"form[director]\"]`. A name already carrying a\n// bracket (a raw wire name the author passed, like \"ids[]\") is used verbatim.\nfunction namedSelector(name, scope) {\n return `[name=\"${wireName(name, scope)}\"]`\n}\n\nfunction wireName(name, scope) {\n return scope && !name.includes(\"[\") ? `${scope}[${name}]` : name\n}\n\n// The per-pass field resolver every DNF fold reads (show, enable, on-complete).\n// fieldValue(name) is the field's string value; fieldValue(name, true) is how\n// many owned boxes of that checkbox group are ticked (the checked_* terms,\n// issue #319). Memoized, so a field driving several bindings reads once.\nfunction fieldResolver(c, owns) {\n const scope = c.root.getAttribute?.(\"data-reactive-scope\") || null\n const values = new Map()\n return (name, count) => {\n const key = count ? `#${name}` : name\n if (!values.has(key)) {\n values.set(key, count ? groupBoxes(c, name, owns, scope).filter((box) => box.checked).length : showFieldValue(c, name, owns, scope))\n }\n return values.get(key)\n }\n}\n\n// --- Media bindings (issue #373) ---------------------------------------------\n// data-reactive-media='{\"field\",\"take\"?,\"match\"?,\"when\"?,\"pending\"?,\"pool\",\"label\"?,\"blank\"?}'\n// on a preview <img>: the owned field's value (its first `take` characters, or\n// all of it) is a key into `pool`, whose value is a SELECTOR for an <img>\n// inside the root. The core's copyMedia copies that element's src, srcset and\n// alt — a pool value is never assigned to anything. A key, selector or element\n// that misses clears the preview; `label` gets the alt (or `blank`) via\n// textContent. A key shorter than `take`, a key the anchored `match` source\n// rejects, or a WHOLE field value the anchored `when` source rejects (issue\n// #390 — tested before the pool lookup; the key stays the prefix) is PENDING\n// (issue #380) and never gets `blank`: \"keep\" leaves the preview and label\n// alone, the default clears both. The preview's\n// data-reactive-media-state names the outcome (pending | hit | miss). An\n// unowned field leaves the preview alone (the show default-deny); a malformed\n// attr warns and is skipped.\nconst MEDIA_BINDING_SELECTOR = \"[data-reactive-media]\"\n\nfunction syncMedia(c, fieldValue, owns) {\n for (const el of c.root.querySelectorAll(MEDIA_BINDING_SELECTOR)) {\n if (!owns(el)) continue\n let wire, pattern, whole\n try {\n wire = JSON.parse(el.getAttribute(\"data-reactive-media\"))\n if (wire?.match != null) pattern = new RegExp(`^(?:${wire.match})$`)\n if (wire?.when != null) whole = new RegExp(`^(?:${wire.when})$`)\n } catch {}\n if (\n typeof wire?.field !== \"string\" ||\n !wire.pool ||\n typeof wire.pool !== \"object\" ||\n (wire.match != null && !pattern) ||\n (wire.when != null && !whole)\n ) {\n console.warn(\"[phlex-reactive] malformed data-reactive-media — skipped\")\n continue\n }\n const value = fieldValue(wire.field)\n if (value === null) continue\n // Characters (code points), as Ruby counts them — not UTF-16 code units.\n const chars = wire.take > 0 ? [...value] : null\n const key = chars ? chars.slice(0, wire.take).join(\"\") : value\n const pending = chars?.length < wire.take || pattern?.test(key) === false || whole?.test(value) === false\n if (pending && wire.pending === \"keep\") {\n mediaState(el, \"pending\")\n continue\n }\n const source = !pending && Object.hasOwn(wire.pool, key) ? mediaMatches(c, wire.pool[key])[0] : null\n const alt = c.core.copyMedia(el, source ?? null)\n if (alt === null) continue\n mediaState(el, pending ? \"pending\" : alt === false ? \"miss\" : \"hit\")\n if (typeof wire.label !== \"string\") continue\n const text = pending ? \"\" : alt === false ? String(wire.blank ?? \"\") : alt\n for (const node of mediaMatches(c, wire.label)) if (node.textContent !== text) node.textContent = text\n }\n}\n\n// The outcome a stylesheet (or :has()) can hide a row on, written only when\n// it changes.\nfunction mediaState(el, state) {\n if (el.getAttribute(\"data-reactive-media-state\") !== state) el.setAttribute(\"data-reactive-media-state\", state)\n}\n\n// The owned elements a pool or label selector names — none when it does not\n// parse (a URL string is not a selector), and none for the \"@root\" sentinel:\n// a label naming the root would rewrite the whole root's text.\nfunction mediaMatches(c, selector) {\n try {\n return selector === \"@root\" ? [] : c.core.opTargets({ to: selector })\n } catch {\n return []\n }\n}\n\n// --- CSS custom properties (issue #417) --------------------------------------\n// data-reactive-css-vars='{\"to\":[selector|\"@root\",…],\"global\"?:true,\n// \"vars\":{\"--name\":{\"field\",\"unit\"?}}}' on the root or an element it owns.\n// Each property reads its owned field (a checkbox is 1 or 0, a radio group its\n// checked value) as a finite number and writes number + unit on every `to:`\n// target, resolved from the root like a client op's. Anything else removes the\n// property, so the author's var() fallback applies: no string from a field ever\n// reaches CSS. A name or unit off the Ruby allowlist is refused here too (a\n// hand-built attr must not widen it); a field no owned control carries leaves\n// the property alone (the show default-deny). A value is written only when it\n// changes, since the pass runs on every owned field's edit.\nconst CSS_VARS_SELECTOR = \"[data-reactive-css-vars]\"\nconst CSS_VAR_NAME = /^--[a-z0-9-]+$/i\nconst CSS_VAR_UNITS = [\"\", \"px\", \"%\", \"deg\", \"turn\", \"ms\", \"s\", \"em\", \"rem\", \"fr\"]\n\nfunction syncCssVars(c, fieldValue, owns, scope) {\n const nodes = [...c.root.querySelectorAll(CSS_VARS_SELECTOR)].filter(owns)\n if (c.root.hasAttribute(\"data-reactive-css-vars\")) nodes.unshift(c.root)\n for (const el of nodes) {\n let wire\n try {\n wire = JSON.parse(el.getAttribute(\"data-reactive-css-vars\"))\n } catch {}\n if (!Array.isArray(wire?.to) || !wire.vars || typeof wire.vars !== \"object\") {\n // Most likely two calls mixed onto one element: their JSON space-joins.\n console.warn(\"[phlex-reactive] malformed data-reactive-css-vars — skipped (two reactive_css_vars on one element?)\")\n continue\n }\n // A selector that does not parse matches nothing: it must not throw out\n // of the show pass and stop the root's other bindings.\n const targets = wire.to.flatMap((to) => {\n const args = { to, global: wire.global === true }\n let found = []\n try {\n found = c.core.opTargets(args)\n } catch {}\n if (!found.length) c.core.diagnose(\"reactive_css_vars\", args)\n return found\n })\n for (const [name, spec] of Object.entries(wire.vars)) {\n const unit = spec?.unit ?? \"\"\n if (!CSS_VAR_NAME.test(name) || !CSS_VAR_UNITS.includes(unit) || typeof spec?.field !== \"string\") {\n console.warn(`[phlex-reactive] refused reactive_css_vars entry ${JSON.stringify(name)} — skipped`)\n continue\n }\n const number = cssVarNumber(c, fieldValue, spec.field, owns, scope)\n if (number === undefined) continue\n const value = number === null ? \"\" : `${number}${unit}`\n for (const target of targets) {\n if (target.style.getPropertyValue(name) === value) continue\n if (value) target.style.setProperty(name, value)\n else target.style.removeProperty(name)\n }\n }\n }\n}\n\n// The number an owned field holds: 1 or 0 for a checkbox (decided by its\n// type, so a text field reading \"true\" is no number), else its value through\n// Number() — null when that is not finite or the value is blank (Number(\"\")\n// is 0), undefined when no owned field has the name.\nfunction cssVarNumber(c, fieldValue, name, owns, scope) {\n const value = fieldValue(name)\n if (value === null) return undefined\n if (\n (value === \"true\" || value === \"false\") &&\n [...c.root.querySelectorAll(namedSelector(name, scope))].some((el) => owns(el) && el.type === \"checkbox\")\n ) {\n return value === \"true\" ? 1 : 0\n }\n const number = value.trim() ? Number(value) : NaN\n return Number.isFinite(number) ? number : null\n}\n\n// --- Bulk selection (issue #319) ---------------------------------------------\n// A checkbox GROUP is the owned boxes sharing one name. Three bindings read it:\n// the select-all header (data-reactive-select-all), the ticked count\n// (data-reactive-count), and the checked_* terms any condition can use —\n// reactive_enable (data-reactive-enable) flips the element's own `disabled`\n// from one. They re-sync with the show pass: on every input/change, on a\n// morph, and when boxes are added or removed (observeGroups). A header with\n// data-reactive-select-all-under (issue #398) is one branch of a tree: it owns\n// the boxes of the name whose data-reactive-group is in its path.\nconst GROUP_BINDING_SELECTOR = \"[data-reactive-enable], [data-reactive-select-all], [data-reactive-count]\"\n\n// Whether the root holds any group binding (owned or not — a stray nested\n// one only costs the walk, which still skips it).\nfunction hasGroups(c) {\n return !!c.root.querySelector?.(GROUP_BINDING_SELECTOR)\n}\n\n// The owned checkboxes of a group (a nested root's boxes are its own, #15).\n// With `under` (a nested header, issue #398) only the boxes whose\n// data-reactive-group is that path or below it, on whole segments.\nfunction groupBoxes(c, name, owns, scope, under) {\n return [...c.root.querySelectorAll(namedSelector(name, scope))].filter(\n (el) => el.type === \"checkbox\" && owns(el) && (!under || inGroupPath(el.getAttribute(\"data-reactive-group\"), under)),\n )\n}\n\nfunction inGroupPath(path, under) {\n return path === under || !!path?.startsWith(`${under}.`)\n}\n\n// A header's edit ticks or unticks every owned box of its group (the header\n// itself is never a member). The show listener syncs once afterwards.\nfunction flipGroup(c, header) {\n const group = header?.getAttribute?.(\"data-reactive-select-all\")\n if (group && c.core.owns(header)) {\n setGroup(c, group, header.checked, header, header.getAttribute(\"data-reactive-select-all-under\"))\n }\n}\n\n// The check_group op (issue #342): set a root's group the way its header\n// would, then sync its bindings once. A root this module never connected (no\n// group binding, only the boxes) still flips, with the #15 ownership check.\nexport function checkGroup(root, group, checked) {\n if (!group) return\n const c = rootContexts.get(root) ?? {\n root,\n core: { ownership: () => (el) => el.closest('[data-controller~=\"reactive\"]') === root },\n }\n setGroup(c, group, checked !== false)\n c.show?.()\n}\n\n// Tick or untick every owned box of a group, and dispatch `input` + `change`\n// on each one it flips so computes, shows and on-complete bindings see a real\n// edit. The re-entrant events are skipped by the show listener while this\n// runs (c.flipping); the caller syncs once afterwards.\nfunction setGroup(c, group, checked, except, under) {\n const scope = c.root.getAttribute?.(\"data-reactive-scope\") || null\n const flipped = groupBoxes(c, group, c.core.ownership(), scope, under).filter((box) => box !== except && box.checked !== checked)\n // Every box first, then the events: a listener (a checked-count\n // on_complete) must see the group's final count, never a half-flipped one.\n for (const box of flipped) box.checked = checked\n c.flipping = true\n try {\n for (const box of flipped) {\n // input then change, as a click does: computes listen on input.\n for (const type of [\"input\", \"change\"]) box.dispatchEvent?.(new Event(type, { bubbles: true }))\n }\n } finally {\n c.flipping = false\n }\n}\n\n// One pass over the owned group bindings: enable from its conditions, the\n// count as text (change-guarded, like #mirrorText), and each header's\n// checked/indeterminate from its group (the header itself never counts).\nfunction syncGroups(c, fieldValue, owns, scope) {\n for (const el of c.root.querySelectorAll(GROUP_BINDING_SELECTOR)) {\n if (!owns(el)) continue\n const enable = el.getAttribute(\"data-reactive-enable\")\n if (enable !== null) {\n const match = showPayloadMatches(parseShowCompound(enable), fieldValue)\n if (match !== null) el.disabled = !match\n }\n const counted = el.getAttribute(\"data-reactive-count\")\n if (counted) {\n const text = String(fieldValue(counted, true))\n if (el.textContent !== text) el.textContent = text\n }\n const group = el.getAttribute(\"data-reactive-select-all\")\n if (group) {\n const under = el.getAttribute(\"data-reactive-select-all-under\")\n const boxes = groupBoxes(c, group, owns, scope, under).filter((box) => box !== el)\n const ticked = boxes.filter((box) => box.checked).length\n el.checked = ticked > 0 && ticked === boxes.length\n el.indeterminate = ticked > 0 && ticked < boxes.length\n }\n }\n}\n\n// The declared cross-root group targets (issue #343) — the count and enable\n// parallel of syncShowTargets, declared on the root that OWNS the group:\n// { group: { count: [\"#id\", …], enable: { \"#id\": { any: … } } } }. The count\n// is this root's owned ticked boxes (a nested root's are its own, #15), the\n// enable folds its DNF payload with the same owned-field memo as every other\n// binding. Targets are id-only (warn-skip — the Ruby helper raised at\n// declare time) and resolved document-wide; a missing one is skipped.\nfunction syncGroupTargets(c, fieldValue) {\n for (const [group, targets] of Object.entries(parseShowTargets(c, \"group\", '\"ids[]\" => { ... }, \"tags[]\" => { ... }'))) {\n if (!targets || typeof targets !== \"object\" || Array.isArray(targets)) continue\n const text = String(fieldValue(group, true))\n for (const selector of Array.isArray(targets.count) ? targets.count : []) {\n if (!guardShowTargetSelector(selector, \"group\")) continue\n for (const node of document.querySelectorAll(selector)) if (node.textContent !== text) node.textContent = text\n }\n const enable = targets.enable && typeof targets.enable === \"object\" ? targets.enable : {}\n for (const [selector, payload] of Object.entries(enable)) {\n if (!guardShowTargetSelector(selector, \"group\")) continue\n const match = anyOfAllsMatches(payload?.any, fieldValue)\n if (match === null) {\n console.warn(`[phlex-reactive] malformed reactive_group_targets enable for ${selector} — skipped`)\n continue\n }\n for (const node of document.querySelectorAll(selector)) node.disabled = !match\n }\n }\n}\n\n// Boxes added or removed later — a stream append, a removal — fire no event,\n// so a root with a group binding (a header, a count, an enable, or a show,\n// show target or on_complete with a checked_* term) watches its subtree and\n// re-syncs when a mutation adds or removes a checkbox: the show pass, and the\n// on_complete latches re-armed without firing. Text writes (the count itself)\n// never qualify, so it cannot loop. Installed once — at connect, or by the\n// first morph that adds such a binding.\nfunction observeGroups(c) {\n if (c.groupObserver || typeof MutationObserver !== \"function\") return\n const onRoot = (name) => c.root.getAttribute?.(`data-reactive-${name}`)?.includes(\"checked_\")\n const targeted = !!c.root.getAttribute?.(\"data-reactive-group-targets\")\n if (!targeted && !c.root.querySelector?.(`${GROUP_BINDING_SELECTOR}, [data-reactive-show*=checked_]`) && !onRoot(\"show-targets\") && !onRoot(\"on-complete\")) return\n const boxIn = (node) => node.nodeType === 1 && (node.matches('input[type=\"checkbox\"]') || !!node.querySelector('input[type=\"checkbox\"]'))\n c.groupObserver = new MutationObserver((records) => {\n if (!records.some((r) => [...r.addedNodes, ...r.removedNodes].some(boxIn))) return\n c.show?.()\n c.arm?.()\n })\n c.groupObserver.observe(c.root, { childList: true, subtree: true })\n}\n\n// Whether this root declares an option filter (issue #163) — the connect()\n// gate. reactive_filter always emits input + option together, so requiring\n// BOTH also default-denies a half-built hand-authored binding.\nfunction filterEnabled(c) {\n return !!(\n c.root.getAttribute?.(\"data-reactive-filter-input\") &&\n c.root.getAttribute?.(\"data-reactive-filter-option\")\n )\n}\n\n// Whether a delegated input event came from the NAMED filter input (issue\n// #163). Anything else — another field's keystroke, a target without\n// matches() — skips the filter pass (the morph re-sync path bypasses this).\nfunction filterInputEvent(c, event) {\n const selector = c.root.getAttribute(\"data-reactive-filter-input\")\n return !!selector && typeof event.target?.matches === \"function\" && event.target.matches(selector)\n}\n\n// Re-apply the filter in one pass (issue #163): lowercase the named input's\n// current value, toggle `hidden` on every OWNED option by a substring match\n// against its haystack (data-reactive-filter-text, falling back to the\n// option's own text), collapse any group whose every contained option is\n// hidden, and reveal the empty target at 0 visible. A filtered-out option\n// also loses its listnav highlight so Enter can never pick an invisible row.\n// No owned input → leave visibility ALONE — a binding that can't resolve\n// must never break or blank the page (client-side default-deny). All\n// selectors resolve within this root, skipping nested reactive roots'\n// elements (issue #15 ownership; the predicate is hoisted once per pass).\nfunction syncFilter(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return\n const inputSelector = c.root.getAttribute(\"data-reactive-filter-input\")\n const optionSelector = c.root.getAttribute(\"data-reactive-filter-option\")\n if (!inputSelector || !optionSelector) return\n\n const owns = c.core.ownership()\n const input = [...c.root.querySelectorAll(inputSelector)].find(owns)\n if (!input) return\n\n const query = (input.value ?? \"\").trim().toLowerCase()\n let visible = 0\n for (const el of c.root.querySelectorAll(optionSelector)) {\n if (!owns(el)) continue // a nested root's option is its own controller's job\n const haystack = (el.getAttribute(\"data-reactive-filter-text\") ?? el.textContent ?? \"\").toLowerCase()\n // An option whose tag is already selected (reactive_tags, issue #203)\n // stays hidden through every re-filter — clearing the query must not\n // resurface an already-added tag.\n const hidden =\n el.hasAttribute?.(\"data-reactive-tags-selected\") || (query !== \"\" && !haystack.includes(query))\n el.hidden = hidden\n if (hidden) el.removeAttribute(\"data-reactive-highlighted\")\n else visible++\n }\n\n const groupSelector = c.root.getAttribute(\"data-reactive-filter-group\")\n if (groupSelector) {\n for (const group of c.root.querySelectorAll(groupSelector)) {\n if (!owns(group)) continue\n const contained = [...group.querySelectorAll(optionSelector)].filter(owns)\n // A group with no options isn't this filter's to decide — server state\n // stands (it may be a header the app toggles by other means).\n if (contained.length === 0) continue\n group.hidden = contained.every((el) => el.hidden)\n }\n }\n\n const emptySelector = c.root.getAttribute(\"data-reactive-filter-empty\")\n if (emptySelector) {\n for (const el of c.root.querySelectorAll(emptySelector)) {\n if (owns(el)) el.hidden = visible > 0\n }\n }\n}\n\n// Whether this root declares a tag-chip binding (issue #203) — the connect()\n// gate and every tags action's first check (an action bound without the root\n// binding is default-denied, the filter posture).\nfunction tagsEnabled(c) {\n return !!c.root.getAttribute?.(\"data-reactive-tags-field\")\n}\n\n// Whether this root owns at least one JSON-mode nested list (issue #208) —\n// the connect() gate. A cheap descendant probe: a form without one wires no\n// input/change listeners. Ownership is re-checked per sync, so a stray match\n// in a nested reactive root here is harmless (it just arms the listeners).\nfunction nestedJsonEnabled(c) {\n if (typeof c.root?.querySelector !== \"function\") return false\n return !!c.root.querySelector(\"[data-reactive-nested-json]\")\n}\n\n// The hidden input storing the comma-joined value, resolved fresh per use\n// (a morph replaces nodes — never cache it) and OWNED by this root (issue\n// #15). null when the selector resolves nothing — every caller then no-ops:\n// a binding that can't resolve must never break the page.\nfunction tagsField(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return null\n const selector = c.root.getAttribute(\"data-reactive-tags-field\")\n if (!selector) return null\n const owns = c.core.ownership()\n return [...c.root.querySelectorAll(selector)].find(owns) ?? null\n}\n\n// Parse the field's comma-joined value into the canonical tag list: split,\n// trim, drop blanks, dedupe case-insensitively KEEPING the first casing (the\n// server may have stored a ragged value — the projection normalizes without\n// rewriting the field, so we never fight server truth).\nfunction tagsRead(field) {\n const seen = new Set()\n const tags = []\n for (const part of String(field.value ?? \"\").split(\",\")) {\n const tag = part.trim()\n if (tag === \"\" || seen.has(tag.toLowerCase())) continue\n seen.add(tag.toLowerCase())\n tags.push(tag)\n }\n return tags\n}\n\n// Append any NEW tags (trimmed, non-blank, not already present under the\n// case-insensitive dedupe) and write the field once. Returns whether\n// anything was actually added — callers only clear the query input then.\nfunction tagsAddValues(c, values) {\n const field = tagsField(c)\n if (!field) return false\n\n const tags = tagsRead(field)\n const seen = new Set(tags.map((tag) => tag.toLowerCase()))\n let added = false\n for (const value of values) {\n const tag = String(value ?? \"\").trim()\n if (tag === \"\" || seen.has(tag.toLowerCase())) continue\n seen.add(tag.toLowerCase())\n tags.push(tag)\n added = true\n }\n if (added) tagsWrite(c, field, tags)\n return added\n}\n\n// The ONE writer: join, store, dispatch a real bubbling `input` on the field\n// (the set-value + dispatch contract, issue #183 — dirty tracking,\n// reactive_show, and compute all see the change), then re-project.\nfunction tagsWrite(c, field, tags) {\n field.value = tags.join(\",\")\n fireInput(field)\n syncTags(c)\n}\n\n// The query input the tags widget resets after a pick — the SAME input that\n// drives reactive_filter (a tags widget without filtering has none; the\n// caller then skips the reset).\nfunction tagsQueryInput(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return null\n const selector = c.root.getAttribute(\"data-reactive-filter-input\")\n if (!selector) return null\n const owns = c.core.ownership()\n return [...c.root.querySelectorAll(selector)].find(owns) ?? null\n}\n\n// Re-project the hidden field into the DOM (issue #203): rebuild the chip\n// list from the <template> and mark/hide the options whose tag is already\n// selected. The field is the single source of truth — this never writes it.\nfunction syncTags(c) {\n const field = tagsField(c)\n if (!field) return\n const tags = tagsRead(field)\n const owns = c.core.ownership()\n tagsRenderChips(c, tags, owns)\n tagsMarkOptions(c, tags, owns)\n}\n\n// Rebuild the chip list: clear the container and clone one chip per tag from\n// the server-owned template. The tag lands in the clone's\n// [data-reactive-tag-text] node via textContent (XSS-safe by construction —\n// never innerHTML, the reactive_text posture), and every tagsRemove trigger\n// in the clone gets the tag as its param. A missing list is a chip-less\n// widget (fine — the value still maintains); a missing/empty template warns\n// ONCE (a half-built binding should be loud, but never per-keystroke).\nfunction tagsRenderChips(c, tags, owns) {\n const list = [...c.root.querySelectorAll(\"[data-reactive-tags-list]\")].find(owns)\n if (!list) return\n\n const template = [...c.root.querySelectorAll(\"[data-reactive-tags-template]\")].find(owns)\n const chipProto = template?.content?.firstElementChild\n if (!chipProto) {\n if (!c.tagsWarnedTemplate) {\n console.warn(\n \"[phlex-reactive] reactive_tags: no chip <template data-reactive-tags-template> found in this root — \" +\n \"chips will not render (the hidden field still updates). Add a template with a \" +\n \"[data-reactive-tag-text] node and a reactive_tags_remove button.\"\n )\n c.tagsWarnedTemplate = true\n }\n return\n }\n\n while (list.firstChild) list.removeChild(list.firstChild)\n for (const tag of tags) {\n const chip = chipProto.cloneNode(true)\n chip.setAttribute?.(\"data-reactive-tag\", tag)\n const sink = chip.matches?.(\"[data-reactive-tag-text]\")\n ? chip\n : (chip.querySelectorAll?.(\"[data-reactive-tag-text]\") ?? [])[0]\n if (sink) sink.textContent = tag\n const removers = [...(chip.querySelectorAll?.('[data-action*=\"reactive#tagsRemove\"]') ?? [])]\n if (chip.matches?.('[data-action*=\"reactive#tagsRemove\"]')) removers.push(chip)\n for (const remover of removers) remover.setAttribute?.(\"data-reactive-tag-param\", tag)\n list.appendChild(chip)\n }\n}\n\n// Hide + mark every owned option whose DECLARED tag is already selected\n// (data-reactive-tags-selected — #syncFilter keeps it hidden through\n// re-filters), and resurface an option WE hid when its tag is removed. Only\n// marker-carrying options are un-hidden — an option hidden by the filter or\n// the server stays as-is. With a filter bound, one final #syncFilter re-folds\n// groups/empty against the new selected set.\nfunction tagsMarkOptions(c, tags, owns) {\n const selected = new Set(tags.map((tag) => tag.toLowerCase()))\n for (const el of c.root.querySelectorAll(\"[role=option]\")) {\n if (!owns(el)) continue\n const tag = el.getAttribute?.(\"data-reactive-tag-param\")\n if (!tag) continue\n if (selected.has(tag.toLowerCase())) {\n el.setAttribute(\"data-reactive-tags-selected\", \"true\")\n el.hidden = true\n el.removeAttribute?.(\"data-reactive-highlighted\")\n } else if (el.hasAttribute?.(\"data-reactive-tags-selected\")) {\n el.removeAttribute(\"data-reactive-tags-selected\")\n if (!filterEnabled(c)) el.hidden = false\n }\n }\n if (filterEnabled(c)) syncFilter(c)\n}\n\n// A fresh index per nested-row add (issue #208) — strictly monotonic and\n// clock-seeded, so it can never collide with server-rendered integer indexes\n// (0..n) NOR with a rapid same-millisecond double add.\nfunction nextNestedIndex(c) {\n c.nestedIndex = Math.max(c.nestedIndex + 1, Date.now())\n return c.nestedIndex\n}\n\n// Swap every NEW_ROW in the clone's name/id/for for the fresh index, so the\n// row posts as its own `…_attributes[<index>][field]` group and labels keep\n// pointing at their (renumbered) inputs.\nfunction renumberNestedRow(row, index) {\n const nodes = [row, ...(row.querySelectorAll?.(\"*\") ?? [])]\n for (const el of nodes) {\n for (const attr of [\"name\", \"id\", \"for\"]) {\n const value = el.getAttribute?.(attr)\n if (value && value.includes(\"NEW_ROW\")) el.setAttribute?.(attr, value.replaceAll(\"NEW_ROW\", String(index)))\n }\n }\n}\n\n// A half-built nested-rows binding should be loud, but never per-click.\nfunction warnNestedOnce(c, assoc) {\n if (c.nestedWarned) return\n console.warn(\n `[phlex-reactive] nested rows: no owned [data-reactive-nested-list=\"${assoc}\"] container + ` +\n `<template data-reactive-nested-template=\"${assoc}\"> pair found in this root — the add ` +\n \"trigger did nothing. Render both inside the same reactive root (reactive_nested_list / \" +\n \"reactive_nested_template).\"\n )\n c.nestedWarned = true\n}\n\n// Fill-then-add (issue #208): copy each source control's value into the\n// matching cloned-row field, keyed by the trailing bracket segment of the\n// field's name (#nestedJsonKey — the SAME inference JSON mode uses, so the\n// two features can't drift). Sources resolve root-scoped and owned (#15); an\n// unresolved source or an unmatched key is silently skipped (the row still\n// adds — a half-mapped binding must never throw on click). Returns the FIRST\n// source control read (for focus), or null. With `clear`, resets every source\n// it read via the set-value + dispatch contract (#183) so dirty/show/compute\n// observe the reset.\nfunction seedNestedRow(c, row, fromJson, clear) {\n if (!fromJson) return null\n let map\n try {\n map = JSON.parse(fromJson)\n } catch {\n return null\n }\n if (!map || typeof map !== \"object\") return null\n\n const owns = c.core.ownership()\n const rowFields = [...(row.querySelectorAll?.(\"input, select, textarea\") ?? [])]\n const sources = []\n for (const [key, selector] of Object.entries(map)) {\n const source = [...(c.root.querySelectorAll?.(selector) ?? [])].find(owns)\n if (!source) continue\n const target = rowFields.find((field) => nestedJsonKey(field.getAttribute?.(\"name\")) === key)\n if (!target) continue\n seedNestedField(target, source)\n sources.push(source)\n }\n if (clear) for (const source of sources) clearNestedSource(source)\n return sources[0] ?? null\n}\n\n// Copy a source control's value into a cloned-row field, then dispatch a\n// bubbling `input` (the set-value + dispatch contract, #183). Checkbox ↔\n// checkbox copies the checked state; every other target takes the source's\n// submit-shaped value (#nestedFieldValue), so a checkbox source feeding a\n// text field lands \"on\"/\"\" exactly as a submit would.\nfunction seedNestedField(target, source) {\n if (target.type === \"checkbox\") {\n target.checked = source.type === \"checkbox\" ? !!source.checked : nestedFieldValue(source) !== \"\"\n } else {\n target.value = nestedFieldValue(source)\n }\n fireInput(target)\n}\n\n// Reset a source control after a fill-then-add (issue #208), dispatching a\n// bubbling `input` so dirty tracking / reactive_show / compute see the reset.\nfunction clearNestedSource(source) {\n if (source.type === \"checkbox\") source.checked = false\n else source.value = \"\"\n fireInput(source)\n}\n\n// Resolve %{field} placeholders in a confirm message from a row's field map\n// (issue #222). Ruby-style %{name} tokens; an unresolved key is left verbatim\n// (a visible, debuggable placeholder — never an empty hole or a throw). A\n// message with no placeholders returns unchanged, so this is inert for every\n// server-rendered (already-interpolated) confirm string.\nfunction interpolateConfirm(message, fields) {\n if (!message.includes(\"%{\")) return message\n return message.replace(/%\\{(\\w+)\\}/g, (whole, key) =>\n Object.prototype.hasOwnProperty.call(fields, key) ? fields[key] : whole,\n )\n}\n\n// The remove itself, shared by the confirmed and no-confirm paths. Draft rows\n// leave the DOM; a persisted row (a hidden [_destroy] input present) is marked\n// \"1\" + hidden instead (set-value + dispatch contract, #183), so Rails destroys\n// it on save. Then re-sync every owned JSON-mode list (#208) — an absent row\n// IS the removal; a form without a JSON list iterates an empty set and exits.\nfunction removeNestedRow(c, row) {\n const destroy = [...(row.querySelectorAll?.('input[name$=\"[_destroy]\"]') ?? [])][0]\n if (destroy) {\n destroy.value = \"1\"\n fireInput(destroy)\n row.hidden = true\n } else {\n row.parentNode?.removeChild?.(row)\n }\n\n syncAllNestedJson(c)\n}\n\n// Serialize every owned JSON-mode list into its hidden field. The connect\n// seed and the input/remove re-syncs funnel through here so one place owns\n// the \"DOM rows → JSON field\" projection.\nfunction syncAllNestedJson(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return\n const owns = c.core.ownership()\n for (const list of [...c.root.querySelectorAll(\"[data-reactive-nested-json]\")].filter(owns)) {\n syncNestedJsonList(c, list.getAttribute(\"data-reactive-nested-json\"))\n }\n}\n\n// The hidden field a JSON-mode list mirrors into — resolved fresh (a morph\n// replaces nodes, never cache it) and OWNED by this root (#15). null when\n// the selector resolves nothing, so the caller no-ops (a half-built binding\n// must never break the page).\nfunction nestedJsonField(c, list) {\n const selector = list.getAttribute?.(\"data-reactive-nested-json-field\")\n if (!selector) return null\n const owns = c.core.ownership()\n return [...c.root.querySelectorAll(selector)].find(owns) ?? null\n}\n\n// One row → { key: value } over its named form controls. The JSON key is the\n// trailing bracket segment of each control's name (order[todos_attributes]\n// [3][title] → \"title\"; a bare `title` → \"title\"), the \"infer from input\n// names\" contract. The [_destroy] control is dropped (JSON has no destroy\n// marker). Later inputs with the same key win (last-wins, the DOM order).\n// Like a real submit (#299): an unchecked radio, a disabled control (its own\n// flag or a <fieldset disabled> ancestor: :disabled) and a nested reactive\n// root's control are skipped.\nfunction nestedRowObject(c, row) {\n const obj = {}\n const owns = c.core.ownership()\n for (const el of [...(row.querySelectorAll?.(\"input, select, textarea\") ?? [])]) {\n if (el.matches(\":disabled\") || (el.type === \"radio\" && !el.checked) || !owns(el)) continue\n const key = nestedJsonKey(el.getAttribute?.(\"name\"))\n if (key === null || key === \"_destroy\") continue\n obj[key] = nestedFieldValue(el)\n }\n return obj\n}\n\n// The trailing bracket segment of a field name (the inferred JSON key), or\n// the bare name when it carries no brackets. null for a nameless control\n// (a bare button, an unnamed helper input) — skipped by the caller.\nfunction nestedJsonKey(name) {\n if (!name) return null\n const match = name.match(/\\[([^\\][]+)\\]$/)\n return match ? match[1] : name\n}\n\n// A form control's submitted value: an unchecked checkbox contributes \"\" (it\n// wouldn't post at all), a checked one its value (default \"on\"); everything\n// else its .value. Keeps the JSON shape close to what a real form submit\n// would carry for the same control.\nfunction nestedFieldValue(el) {\n if (el.type === \"checkbox\") return el.checked ? (el.value || \"on\") : \"\"\n return el.value ?? \"\"\n}\n\n// Project ONE JSON-mode list's surviving rows into its hidden field. Each\n// row becomes an object keyed by the trailing bracket segment of its inputs'\n// names (…[title] → \"title\"); a hidden/_destroy-marked row is skipped (an\n// absent row IS the removal — JSON carries no destroy marker). The write\n// uses the set-value + dispatch contract (issue #183) so dirty tracking,\n// reactive_show, and compute see the change — but only when the value\n// actually changed, so a connect seed on an already-correct field is silent.\nfunction syncNestedJsonList(c, assoc) {\n const owns = c.core.ownership()\n const list = [...c.root.querySelectorAll(`[data-reactive-nested-list=\"${assoc}\"]`)].find(owns)\n if (!list) return\n const field = nestedJsonField(c, list)\n if (!field) return\n\n const rows = []\n for (const row of [...(list.querySelectorAll?.(\"[data-reactive-nested-row]\") ?? [])]) {\n if (!owns(row) || row.hidden) continue\n rows.push(nestedRowObject(c, row))\n }\n\n const next = JSON.stringify(rows)\n if (field.value === next) return\n field.value = next\n fireInput(field)\n}\n\n// Tag-chip input (issue #203) — the composed combobox/tags primitive. The\n// root's data-reactive-tags-field names the hidden input that stores the\n// COMMA-JOINED value; these three actions are its only writers. All of it is\n// FORM state (like text in an input) — no token, no POST: the surrounding\n// form submit carries the joined value. The chip list is re-projected from\n// the field on every write (#syncTags), so the field stays the single source\n// of truth.\n//\n// Enter on the query input: add the TYPED text — unless this Enter belongs\n// to listnav (reactive_tags_add composes after reactive_listnav on the same\n// keydown.enter). Two guards make the composition order-independent:\n// defaultPrevented means listnavPick ALREADY picked the highlighted option\n// (adding the typed text too would double-add); a still-visible highlighted\n// option means listnavPick is ABOUT to pick it (when tagsAdd is bound\n// first). Past the guards, Enter is OURS — preventDefault unconditionally so\n// it can never submit the enclosing form (blank input included). A\n// comma-separated paste splits into individual tags (the value is\n// comma-joined, so a comma can never be part of one tag). The input clears\n// only when something was actually added — a duplicate keeps the typed text\n// for correction.\nexport function tagsAdd(controller, core, event) {\n const c = ctx(controller, core)\n if (!tagsEnabled(c)) return\n if (event?.defaultPrevented) return\n if (c.core.listnavOptions(event).some((el) => el.hasAttribute?.(\"data-reactive-highlighted\"))) return\n event?.preventDefault?.()\n\n const input = event?.currentTarget ?? event?.target\n if (!input) return\n const added = tagsAddValues(c, String(input.value ?? \"\").split(\",\"))\n if (!added) return\n input.value = \"\"\n if (filterEnabled(c)) syncFilter(c)\n}\n\n// Click (or listnav Enter, which CLICKS the highlighted option) on a\n// preloaded option: add its DECLARED tag (data-reactive-tag-param — set by\n// reactive_tags_option, never free text). After a successful add, reset the\n// query so the next tag starts from the full list: clear the filter input,\n// re-narrow, and hand focus back for continued typing.\nexport function tagsPick(controller, core, event) {\n const c = ctx(controller, core)\n if (!tagsEnabled(c)) return\n event?.preventDefault?.()\n\n const trigger = event?.currentTarget ?? event?.target\n const tag = trigger?.getAttribute?.(\"data-reactive-tag-param\")\n if (!tag) return\n if (!tagsAddValues(c, [tag])) return\n\n const input = tagsQueryInput(c)\n if (!input) return\n input.value = \"\"\n syncFilter(c)\n input.focus?.()\n}\n\n// Click on a chip's remove button: drop its tag (case-insensitive match, the\n// dedupe convention) from the hidden value. The re-projection removes the\n// chip and resurfaces the option. Removing an absent tag is a no-op.\nexport function tagsRemove(controller, core, event) {\n const c = ctx(controller, core)\n if (!tagsEnabled(c)) return\n event?.preventDefault?.()\n\n const trigger = event?.currentTarget ?? event?.target\n const tag = trigger?.getAttribute?.(\"data-reactive-tag-param\")\n if (!tag) return\n const field = tagsField(c)\n if (!field) return\n\n const tags = tagsRead(field)\n const next = tags.filter((t) => t.toLowerCase() !== tag.toLowerCase())\n if (next.length === tags.length) return\n tagsWrite(c, field, next)\n}\n\n// Draft nested-attribute rows (issue #208) — the \"new parent + child rows\"\n// window. The rows are FORM state (the reactive_tags posture): no token, no\n// POST, ever — the surrounding REAL form submit carries Rails'\n// accepts_nested_attributes_for names and the server reconciles parent +\n// rows in ONE create. Add clones the association's server-owned\n// <template data-reactive-nested-template=\"assoc\"> row, swaps every NEW_ROW\n// in the clone's name/id/for for a fresh unique index (each row posts as its\n// own `…_attributes[<index>][field]` group), appends it to the owned\n// [data-reactive-nested-list=\"assoc\"] container, and focuses the new row's\n// first field. Several collections can share one root — everything is keyed\n// by the association name the trigger carries.\nexport function nestedAdd(controller, core, event) {\n const c = ctx(controller, core)\n event?.preventDefault?.()\n const trigger = event?.currentTarget ?? event?.target\n const assoc = trigger?.getAttribute?.(\"data-reactive-association-param\")\n if (!assoc) return\n if (typeof c.root?.querySelectorAll !== \"function\") return\n\n const owns = c.core.ownership()\n const list = [...c.root.querySelectorAll(`[data-reactive-nested-list=\"${assoc}\"]`)].find(owns)\n const template = [...c.root.querySelectorAll(`[data-reactive-nested-template=\"${assoc}\"]`)].find(owns)\n const proto = template?.content?.firstElementChild\n if (!list || !proto) {\n warnNestedOnce(c, assoc)\n return\n }\n\n const row = proto.cloneNode(true)\n renumberNestedRow(row, nextNestedIndex(c))\n list.appendChild(row)\n\n // Fill-then-add (issue #208 Scenario A): seed the cloned row from named\n // source controls OUTSIDE the row, then (optionally) clear the sources.\n // Runs AFTER renumber+append so a seeded field's name already carries its\n // final `[<index>][field]` form — the key match agrees with what JSON mode\n // reads. `seeded` is the FIRST source we cleared/read, so fill-then-add can\n // return focus to the sources instead of stealing it into the new row.\n const fromJson = trigger?.getAttribute?.(\"data-reactive-nested-from-param\")\n const clear = trigger?.getAttribute?.(\"data-reactive-nested-clear-param\") === \"true\"\n const firstSource = seedNestedRow(c, row, fromJson, clear)\n\n // Focus: inline-edit (no from:) focuses the new row's first field so you\n // type INTO it; fill-then-add keeps focus on the sources (the first one) so\n // you keep entering the next item — stealing focus would break that loop.\n if (fromJson) firstSource?.focus?.()\n else [...(row.querySelectorAll?.(\"input, select, textarea\") ?? [])][0]?.focus?.()\n\n // JSON mode (issue #208): a freshly-added row must land in the hidden field\n // immediately (seeded values included), so the serialized array reflects the\n // DOM even before the first keystroke. A no-op when not `as: :json`.\n if (list.getAttribute?.(\"data-reactive-nested-json\") === assoc) syncNestedJsonList(c, assoc)\n}\n\n// Remove the trigger's closest row wrapper. A DRAFT row (no [_destroy]\n// input) leaves the DOM — it was never persisted, so removing its fields IS\n// the removal. A PERSISTED row (an edit form rendered a hidden [_destroy]\n// input via nested_field_name) is marked \"1\" and hidden instead — Rails\n// destroys it on save. The mark dispatches a real bubbling `input` (the\n// set-value + dispatch contract, issue #183) so dirty tracking/compute see it.\nexport function nestedRemove(controller, core, event) {\n const c = ctx(controller, core)\n event?.preventDefault?.()\n const trigger = event?.currentTarget ?? event?.target\n const row = trigger?.closest?.(\"[data-reactive-nested-row]\")\n if (!row) return\n // The closest() walk must not escape this root — a root can itself sit\n // inside ANOTHER collection's row (the issue #15 closest-form posture).\n if (row.closest?.('[data-controller~=\"reactive\"]') !== c.root) return\n\n // Confirm gate (issue #218): reactive_nested_remove(confirm:) emits the SAME\n // data-reactive-confirm[-when]-param the other triggers do (nestedRemove reads\n // params via getAttribute, not event.params, so pull them off the trigger),\n // routed through the SAME #effectiveConfirmMessage + confirmResolver seam. A\n // static string always shows; a conditional Hash fires only when it matches,\n // else null. No confirm attr → null → the immediate-remove fast path.\n const confirm = trigger?.getAttribute?.(\"data-reactive-confirm-param\")\n const confirmWhen = trigger?.getAttribute?.(\"data-reactive-confirm-when-param\")\n const rawMessage = confirm || (confirmWhen ? conditionalConfirmMessage(c, confirmWhen) : null)\n if (!rawMessage) return removeNestedRow(c, row)\n\n // Per-row confirm interpolation (issue #222). A row added client-side is a\n // cloneNode of the <template>, and the clone carries the TEMPLATE's confirm\n // string verbatim — the renumber/seed steps never rewrite the confirm attr.\n // So resolve %{field} placeholders here, from THIS row's live field values\n // (read now, not at clone time, so a later edit is reflected). An unresolved\n // key is left as its literal %{key} (debuggable, never throws). Server-\n // rendered rows already interpolate server-side, so their finished strings\n // carry no %{}; this is a no-op for them.\n const fields = nestedRowObject(c, row)\n const message = interpolateConfirm(rawMessage, fields)\n\n // Gate through the overridable confirmResolver (issues #52/#55/#178) — a\n // themed dialog set with setConfirmResolver covers this trigger too. Pass the\n // row context (issue #222, superset of proposal 3) as an optional 2nd arg so\n // a power-user override can build the string itself; the message is already\n // interpolated for the default window.confirm path. Call the resolver INSIDE\n // the chain so even a SYNCHRONOUS override throw is a cancel (like a dismissed\n // dialog), and remove ONLY on a truthy resolution.\n return c.core.confirm(message, { el: trigger, row, fields }).then((ok) => {\n if (ok) removeNestedRow(c, row)\n })\n}\n\n// JSON-mode nested rows (issue #208) — the delegated input/change handler.\n// An app whose controller parses a serialized JSON param instead of Rails'\n// accepts_nested_attributes_for opts a list into `as: :json`; the client\n// then mirrors that list's rows into ONE hidden field as a JSON array on\n// every owned edit. Public so Stimulus can bind it; a no-op unless the\n// edited field belongs to a JSON-mode list this root owns.\nfunction syncNestedJson(c, event) {\n const target = event?.target\n if (!target || !c.core.owns(target)) return\n // Re-serialize every JSON-mode list (an edit could touch any of them; the\n // per-list owned-row scan is cheap and keeps this handler association-free).\n syncAllNestedJson(c)\n}\n\n// The numeric threshold keys (issue #176 part B) — the client half of the Ruby\n// SHOW_NUMERIC_KEYS. Order-independent; the evaluator reads the one that's\n// present. Each coerces BOTH sides to Number and compares.\nconst SHOW_NUMERIC_KEYS = [\"gte\", \"gt\", \"lte\", \"lt\"]\n\n// The length predicate keys (issue #226) — the client half of Ruby's\n// ShowConditions::LENGTH_KEYS. Length is counted in CODEPOINTS\n// ([...str].length), NOT UTF-16 code units (str.length), so Ruby's\n// String#length and this evaluator agree on multibyte values — the shared\n// fixture's emoji vector proves it.\nconst SHOW_LENGTH_KEYS = [\"len_eq\", \"len_gte\", \"len_gt\", \"len_lte\", \"len_lt\"]\n\n// The checked-count keys (issue #319) — the client half of Ruby's\n// ShowConditions::CHECKED_KEYS: how many owned boxes of a group are ticked.\nconst SHOW_CHECKED_KEYS = [\"checked_eq\", \"checked_gte\", \"checked_gt\", \"checked_lte\", \"checked_lt\"]\n\n// The digit-count keys (issue #396) — Ruby's CompareTerms::DIGITS_KEYS.\nconst SHOW_DIGITS_KEYS = [\"digits_eq\", \"digits_gte\", \"digits_lt\", \"digits_lte\"]\n\n// Evaluate one count predicate (len_* or checked_*). A count is a TOTAL\n// function (blank/absent → 0), so every field value is decidable — no\n// fail-closed special case like the numeric thresholds ({ length: 0 }\n// legitimately matches a blank field). A non-Integer LITERAL is a malformed\n// binding — warn-skip (null), default-deny.\nfunction countPredicateMatches(key, literal, count) {\n if (!Number.isInteger(literal)) {\n console.warn(`[phlex-reactive] reactive_show ${key}: needs an integer literal, got ${JSON.stringify(literal)} — skipped`)\n return null\n }\n switch (key.slice(key.indexOf(\"_\") + 1)) {\n case \"eq\":\n return count === literal\n case \"gte\":\n return count >= literal\n case \"gt\":\n return count > literal\n case \"lte\":\n return count <= literal\n case \"lt\":\n return count < literal\n default:\n return null\n }\n}\n\n// Evaluate one numeric threshold predicate against a field value. Returns\n// true/false for a decidable comparison, or null when the LITERAL itself is\n// non-numeric (a malformed binding — warn-skip, default-deny). A non-numeric\n// FIELD value (empty/blank/garbage) is treated as NaN → false: the\n// reveal-on-threshold notice stays hidden, the safe default. Shared by the\n// owned-binding evaluator (raw string literal off an attr) and the\n// cross-root/compound evaluator (a literal that arrived as a JSON number or\n// string).\nfunction numericPredicateMatches(key, literal, value) {\n const rhs = Number(literal)\n if (Number.isNaN(rhs)) {\n console.warn(`[phlex-reactive] reactive_show ${key}: needs a numeric literal, got ${JSON.stringify(literal)} — skipped`)\n return null\n }\n // A blank/whitespace field value must fail closed. Number(\"\") and\n // Number(\" \") are 0 (NOT NaN), so a bare Number()+isNaN check would wrongly\n // reveal a `lte:`/`lt:`/`gte: 0` binding on an EMPTY field. Force the\n // empty/blank case to NaN so the \"blank → hidden\" contract holds for every\n // operator, not just the ones where 0 happens to fail the comparison.\n const trimmed = value == null ? \"\" : String(value).trim()\n const n = trimmed === \"\" ? NaN : Number(trimmed)\n if (Number.isNaN(n)) return false\n switch (key) {\n case \"gte\":\n return n >= rhs\n case \"gt\":\n return n > rhs\n case \"lte\":\n return n <= rhs\n case \"lt\":\n return n < rhs\n default:\n return null\n }\n}\n\n// Evaluate an ALREADY-PARSED show predicate object (issue #164) — the\n// reactive_show_targets map embeds { equals/not/in } directly in its JSON, so\n// unlike showBindingMatches there are no attrs to read or re-parse. The same\n// literal-only vocabulary; anything else (empty, unknown keys, a non-array\n// in:) returns null and the caller warn-skips that target (default-deny — a\n// hand-built map entry must never flip visibility it doesn't declare).\nfunction showPredicateMatches(pred, value) {\n if (!pred || typeof pred !== \"object\") return null\n if (typeof pred.equals === \"string\") return value === pred.equals\n if (typeof pred.not === \"string\") return value !== pred.not\n if (Array.isArray(pred.in)) return pred.in.includes(value)\n // Numeric threshold predicates (issue #176 part B): the literal arrives as a\n // JSON number (or a numeric string) embedded in the predicate object — one\n // shared numericPredicateMatches with the owned-binding evaluator.\n for (const key of SHOW_NUMERIC_KEYS) {\n if (key in pred) return numericPredicateMatches(key, pred[key], value)\n }\n // Length predicates (issue #226): codepoint count vs an Integer literal.\n for (const key of SHOW_LENGTH_KEYS) {\n if (key in pred) return countPredicateMatches(key, pred[key], [...String(value ?? \"\")].length)\n }\n return null\n}\n\n// Evaluate one DNF TERM against a resolved field value (issue #180). A missing\n// field (null) or a malformed/unknown predicate folds to FALSE — fail-closed\n// (default-deny): a broken AND term can't pass, a broken OR term can't reveal.\nfunction dnfTermMatches(term, fieldValue) {\n if (!term || typeof term !== \"object\" || typeof term.field !== \"string\") return false\n // A checked_* term (issue #319) counts the group's ticked boxes: the\n // resolver's count form, or — from collected fields (a conditional confirm)\n // — the group's array of checked values (a lone box's true/false is 1/0).\n const checked = SHOW_CHECKED_KEYS.find((key) => key in term)\n if (checked) {\n const n = fieldValue(term.field, true)\n return countPredicateMatches(checked, term[checked], Array.isArray(n) ? n.length : Number(n) || 0) === true\n }\n // A same: term (issue #395) compares this field with ANOTHER owned field,\n // both as strings (an absent one is \"\"); fold lowercases ASCII A-Z only, the\n // exact replace Ruby's tr(\"A-Z\", \"a-z\") does. negate is unless:'s flip.\n if (typeof term.same === \"string\") {\n const read = (name) => {\n const v = String(fieldValue(name) ?? \"\")\n return term.fold === true ? v.replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32)) : v\n }\n return (read(term.field) === read(term.same)) !== (term.negate === true)\n }\n // A digits: term (issue #396): ASCII digits only, the count within every\n // digits_* bound, and the optional prefix; negate flips it. A malformed\n // literal is false either way (fail-closed, like Ruby).\n const digits = SHOW_DIGITS_KEYS.filter((key) => key in term)\n if (digits.length) {\n const v = String(fieldValue(term.field) ?? \"\")\n if (!digits.every((key) => Number.isInteger(term[key])) || (term.prefix != null && typeof term.prefix !== \"string\")) return false\n const ok = /^[0-9]*$/.test(v) && digits.every((key) => countPredicateMatches(key, term[key], v.length)) && v.startsWith(term.prefix ?? \"\")\n return ok !== (term.negate === true)\n }\n // An absent owned field reads as \"\" — identical to the server evaluator\n // (ShowConditions.match? treats a missing field as blank). This keeps the\n // Ruby first-paint and the client live-toggle in exact agreement (the shared\n // fixture proves it). A malformed predicate still folds to false.\n const value = fieldValue(term.field) ?? \"\"\n return showPredicateMatches(term, value) === true\n}\n\n// Evaluate a DNF show payload (issue #180): { any: [group, …] } where each\n// GROUP is an array of terms (terms AND within a group, groups OR). Returns\n// true/false for a decidable payload, or null for a malformed one (no groups)\n// so the caller warn-skips and leaves visibility alone. This is the ONE shape\n// the 0.10 wire emits; showPayloadMatches routes the legacy shapes here or to\n// the compatibility arm below.\nfunction anyOfAllsMatches(groups, fieldValue) {\n if (!Array.isArray(groups) || groups.length === 0) return null\n // groups OR; within a group, terms AND (an empty group can't decide → false).\n return groups.some((group) => Array.isArray(group) && group.length > 0 &&\n group.every((term) => dnfTermMatches(term, fieldValue)))\n}\n\n// Every field a DNF payload's groups reference (issue #209) — drives the\n// \"leave the target alone when NO referenced field is owned\" skip, the\n// single-field-target skip generalized. Returns null for a malformed payload\n// (no groups, or no term names a field) so the caller warn-skips instead of\n// toggling on garbage (default-deny, like every other malformed-wire arm).\nfunction dnfGroupFields(groups) {\n if (!Array.isArray(groups) || groups.length === 0) return null\n const fields = new Set()\n for (const group of groups) {\n if (!Array.isArray(group)) continue\n for (const term of group) {\n if (term && typeof term === \"object\" && typeof term.field === \"string\") fields.add(term.field)\n if (typeof term?.same === \"string\") fields.add(term.same)\n }\n }\n return fields.size > 0 ? [...fields] : null\n}\n\n// Whether every term of a DNF payload is a checked_* count (issue #348) —\n// the payload a group with zero owned boxes still decides (count 0).\nfunction countsOnly(groups) {\n return groups.flat().every((term) => SHOW_CHECKED_KEYS.some((key) => key in Object(term)))\n}\n\n// Resolve the effective confirm message (issue #179). A plain string is the\n// static #52 form (always shown). A confirmWhen JSON payload is the CONDITIONAL\n// form — evaluated over the SAME collected fields reactive_compute reads — and\n// returns the message ONLY when it fires, else null (proceed, no dialog):\n// { groups, message } — the reactive_show conditions fold (anyOfAllsMatches)\n// { predicate, message } — a registered fn (setConfirmPredicate) over the fields\n// A missing predicate warns and returns null (PROCEED without a dialog) — the\n// compute unknown-reducer posture. This is soft-validation UX; the endpoint's\n// authorize/default-deny is the real gate, so failing OPEN here never grants\n// anything the server wouldn't already allow.\nfunction conditionalConfirmMessage(c, confirmWhen) {\n\n // Stimulus auto-parses a JSON-object -param value, so confirmWhen usually\n // arrives ALREADY parsed. Accept an object as-is; parse a string defensively\n // (a hand-built attr, or a non-Stimulus caller). A malformed string warns and\n // proceeds without a dialog (default-deny UX — the server is the real gate).\n let payload = confirmWhen\n if (typeof confirmWhen === \"string\") {\n try {\n payload = JSON.parse(confirmWhen)\n } catch {\n console.warn(`[phlex-reactive] malformed conditional confirm payload ${JSON.stringify(confirmWhen)} — skipped`)\n return null\n }\n }\n if (!payload || typeof payload !== \"object\") return null\n\n const { fields } = c.core.collectFields()\n const fieldValue = (name) => fields[name]\n\n let fires\n if (typeof payload.predicate === \"string\") {\n const fn = confirmPredicate(payload.predicate)\n if (!fn) {\n console.warn(`[phlex-reactive] confirm predicate \"${payload.predicate}\" is not registered — proceeding without a dialog (register it with setConfirmPredicate)`)\n return null\n }\n fires = !!fn(fields)\n } else {\n // Declarative: the DNF groups fold, identical to reactive_show — matches → fire.\n fires = anyOfAllsMatches(payload.groups?.any, fieldValue) === true\n }\n\n return fires ? payload.message : null\n}\n\n// --- Editable text (issue #351) ----------------------------------------------\n// reactive_editable renders contenteditable=\"plaintext-only\": the browser\n// itself then pastes plain text and inserts \"\\n\" for Enter. An engine without\n// it reads the value as invalid; the runtime switches every reactive editable\n// to \"true\" there (issue #355), and the paste handler below does the\n// plain-text part.\n\n// The owned editable an event came from, or null — a nested reactive root's\n// editables are its own (#15).\nfunction ownedEditable(c, event) {\n const el = event.target?.closest?.(\"[data-reactive-editable]\")\n return el && c.core.owns(el) ? el : null\n}\n\n// Enter: a single-line field swallows it; on_enter runs its ops (root-scoped,\n// as on_client) or submits the field's form — in a multiline field only a\n// plain Enter, so Shift+Enter still breaks the line. Never while an IME is\n// composing (its Enter commits the composition). Escape with on_escape:\n// :revert restores the last server-rendered text, announces it as an edit\n// (dirty, show, an input-bound save) and blurs.\nfunction editableKey(c, event) {\n const el = ownedEditable(c, event)\n if (!el || event.isComposing || event.keyCode === 229) return\n if (event.key === \"Enter\") {\n const enter = el.getAttribute(\"data-reactive-editable-enter\")\n const multi = el.getAttribute(\"data-reactive-editable\") === \"multi\"\n if (multi && (enter == null || event.shiftKey)) return\n event.preventDefault()\n if (enter === \"submit\") el.closest(\"form\")?.requestSubmit()\n else if (enter) c.core.applyOps(JSON.parse(enter), \"@root\")\n } else if (event.key === \"Escape\" && el.hasAttribute(\"data-reactive-editable-escape\")) {\n event.preventDefault()\n el.textContent = c.core.served(el)\n fireInput(el)\n el.blur()\n }\n}\n\n// Paste and drop insert the clipboard's PLAIN text — handled here where the\n// engine has no plaintext-only, and for a single-line field everywhere (its\n// line breaks fold to spaces). insertText keeps the browser's undo stack. A\n// drop lands at the caret, not under the pointer.\nfunction editablePaste(c, event) {\n const el = ownedEditable(c, event)\n const single = el?.getAttribute(\"data-reactive-editable\") !== \"multi\"\n let text = (event.clipboardData ?? event.dataTransfer)?.getData(\"text/plain\")\n if (!el || text == null || (c.core.plain() && !(single && /[\\r\\n]/.test(text)))) return\n event.preventDefault()\n if (single) text = text.replace(/\\r?\\n|\\r/g, \" \")\n el.focus()\n document.execCommand(\"insertText\", false, text)\n}\n\n// A field the user emptied keeps the <br> browsers leave behind, so\n// :empty::before (the placeholder) would never match: drop it.\nfunction editableEmptied(c, event) {\n const el = ownedEditable(c, event)\n if (el?.firstChild && c.core.text(el) === \"\") el.replaceChildren()\n}\n",
6
+ "// phlex/reactive/features/bindings — what a form root wires at connect and\n// re-syncs after a morph, all of it client-only and all of it reading the\n// root's own controls: show bindings and cross-root show targets (issues\n// #161, #164, #176, #180, #209), completion bindings (#226), option filtering\n// (#163), the tag-chip input (#203), draft nested-attribute rows with their\n// JSON mode (#208) and fields fed into CSS custom properties (#417). One of the feature modules the opt-in client imports on\n// demand (issue #275); in the default client it is part of the one file.\n//\n// Grouped because they share a shape — a marker check at connect, one\n// delegated listener pair on the root, a seed, the same pass again on\n// turbo:morph-element — and a page: a form with a show binding is the form\n// that filters options and adds rows. The seeds here write visible state\n// (and the JSON mode writes a hidden field a request collects), so with the\n// opt-in client the feature `gates`: a root's requests wait for it.\n//\n// The conditional confirm (issue #179) lives here too: its condition is the\n// same DNF fold a show binding uses, and its `predicate:` form reads the\n// confirm_predicate seam — imported here by its bare name, so the runtime no\n// longer imports it. A plain string confirm: never comes here; a conditional\n// one on the opt-in client waits for this module before its dialog (a root\n// with one preloads it).\n//\n// This module never imports the runtime: it reaches a controller through the\n// `core` handle.\nimport { confirmPredicate } from \"phlex/reactive/confirm_predicate\"\n\n// controller -> its context: the root, the core handle, and what used to be\n// the controller's own fields for these features. Every field it does not\n// set here starts undefined (falsy); a property name is one thing the\n// minifier never renames, so the record carries no more of them than it\n// must (issue #310).\nconst contexts = new WeakMap()\n// root element -> the same context, for the check_group op (issue #342),\n// which names a root, not a controller.\nconst rootContexts = new WeakMap()\n\nfunction ctx(controller, core) {\n let c = contexts.get(controller)\n if (!c) {\n contexts.set(controller, (c = { root: controller.element, core, nestedIndex: 0 }))\n if (c.root) rootContexts.set(c.root, c)\n }\n return c\n}\n\n// Add a delegated listener on the root for each of the space-separated\n// `types`, and keep its removal for disconnect().\nfunction listen(c, types, handler) {\n for (const type of types.split(\" \")) {\n c.root.addEventListener?.(type, handler)\n c.offs.push(() => c.root.removeEventListener?.(type, handler))\n }\n}\n\n// What connect() wires is one seed per binding: it runs now, again on\n// turbo:morph-element, and again from reseed().\nfunction seed(c, run) {\n listen(c, \"turbo:morph-element\", run)\n c.seeds.push(run)\n run()\n}\n\nexport function connect(controller, core) {\n const c = ctx(controller, core)\n c.offs = []\n c.seeds = []\n // Each binding below is wired once, the first time its gate reads true:\n // here, and again from reseed() — a stream can render a root's first show\n // target, filter or nested list into it after connect (issue #356).\n let resetting\n let filtering\n let tagging\n let serializing\n ;(c.wire = () => {\n // Show bindings (issue #161) — ONLY when this root owns one, so a component\n // without any pays a single probe (the dirty-tracking gate precedent). ONE\n // delegated listener pair on the root (input + change bubble from every\n // owned field — no per-field wiring, and a reactive_compute output write\n // dispatches a real input event, so computed values drive visibility too).\n // The connect sync seeds the initial state — a plain replace re-connects —\n // and turbo:morph-element re-syncs after an in-place morph (which keeps the\n // element connected, fires no Stimulus lifecycle, and may preserve a\n // user-edited field value the server's hidden attrs don't reflect).\n if (!c.show && showSyncEnabled(c)) {\n // A select-all header's edit flips its group first (issue #319) — on\n // `input`, which a click fires BEFORE `change`, or the pass below would\n // reset the header to its group's state first (the flip is idempotent, so\n // the `change` that follows flips nothing). The change events it\n // dispatches re-enter here and are skipped while it flips, so the pass\n // after the loop runs once, not once per box.\n c.show = (event) => {\n if (c.flipping) return\n // Only a user edit pushes the header onto its group; a morph (whose\n // turbo:morph-element bubbles from the header too) derives it instead.\n if (event?.type === \"input\" || event?.type === \"change\") flipGroup(c, event.target)\n // Whether this root has group bindings is read at connect and again on\n // a morph (which may add one, and so need the observer) — never per\n // keystroke.\n else {\n c.groups = hasGroups(c)\n observeGroups(c)\n }\n syncShow(c)\n }\n listen(c, \"input change\", c.show)\n // The after: gate (issue #396): an owned field's first blur marks its\n // name touched for this controller (a morph keeps it, a new one starts\n // without), and re-syncs once if a binding waits on a blur.\n listen(c, \"focusout\", (event) => {\n const name = event.target?.getAttribute?.(\"name\")\n if (!name || c.touched?.has(name) || !c.core.owns(event.target)) return\n ;(c.touched ??= new Set()).add(name)\n if (c.root.querySelector?.(\"[data-reactive-show-after]\")) syncShow(c)\n })\n seed(c, c.show)\n }\n\n // Completion bindings (issue #226) — ONLY when the root declares\n // data-reactive-on-complete (the show/filter gate precedent). ONE\n // delegated input+change listener evaluates every binding's DNF over the\n // owned fields and runs its ops on the RISING EDGE — the event-driven\n // flip to true. The connect pass ARMS without firing (a fresh render with\n // already-satisfied conditions must never self-fire — the $ops seed\n // precedent), and turbo:morph-element re-arms the same way after an\n // in-place morph. Listeners added HERE run after the Stimulus-wired\n // recompute delegation for the same event, so the evaluation reads\n // compute-NORMALIZED values (and a compute output write dispatches a real\n // input event that re-evaluates anyway).\n if (!c.arm && onCompleteEnabled(c)) {\n listen(c, \"input change\", (event) => syncOnComplete(c, event))\n seed(\n c,\n (c.arm = () => {\n syncOnComplete(c, null)\n observeGroups(c)\n }),\n )\n }\n\n // A form reset (issue #342) restores its fields AFTER the `reset` event\n // dispatches (and only if nothing cancelled it), so this waits a task, then\n // re-syncs the bindings and re-arms the completion latches without firing\n // (a reset fires no input/change, so a checked-count latch would stay high).\n if (!resetting && (resetting = c.show || c.arm)) {\n listen(c, \"reset\", () =>\n setTimeout(() => {\n if (contexts.get(controller) !== c) return\n c.show?.()\n c.arm?.()\n }, 0),\n )\n }\n\n // Option filtering (issue #163) — ONLY when the root declares the binding\n // (reactive_filter emits both attrs together), so a component without one\n // pays two attribute reads. ONE delegated input listener on the root — the\n // handler re-filters only for events from the NAMED input, so keystrokes in\n // unrelated fields on a wide form never pay a filter pass. The connect sync\n // seeds from the input's current value (a plain replace re-connects; back\n // navigation may restore typed text), and turbo:morph-element re-applies\n // after an in-place morph (which keeps the element connected, fires no\n // Stimulus lifecycle, and may preserve the user's typed query while the\n // server re-rendered every option visible).\n if (!filtering && (filtering = filterEnabled(c))) {\n listen(c, \"input\", (event) => filterInputEvent(c, event) && syncFilter(c))\n seed(c, () => syncFilter(c))\n }\n\n // Tag-chip input (issue #203) — ONLY when the root names the hidden value\n // field (reactive_tags), so a component without one pays one attribute\n // read. The chip list is a CLIENT PROJECTION of the hidden field's\n // comma-joined value: connect seeds it (a plain replace re-connects with\n // the server-rendered value), and turbo:morph-element re-projects after an\n // in-place morph (the morph wrote server truth into the hidden field while\n // the chips DOM kept the pre-morph projection). Registered AFTER the\n // filter's listeners so a morph re-filters first and the tags pass then\n // re-marks selected options on the fresh visibility state.\n if (!tagging && (tagging = tagsEnabled(c))) seed(c, () => syncTags(c))\n\n // JSON-mode nested rows (issue #208) — ONLY when the root owns a list with\n // `as: :json`, so a form without one pays a single probe (the show/filter/\n // tags gate precedent). ONE delegated input + change listener re-serializes\n // the rows into the hidden field on every owned edit (nestedAdd/Remove call\n // the sync directly; this covers typing into a row's fields). The connect\n // seed writes the initial array (a plain replace re-connects), and\n // turbo:morph-element re-seeds after an in-place morph (which keeps the\n // element connected, fires no Stimulus lifecycle, and may have rewritten\n // the rows to server truth while the hidden field kept its pre-morph value).\n if (!serializing && (serializing = nestedJsonEnabled(c))) {\n listen(c, \"input change\", (event) => syncNestedJson(c, event))\n seed(c, () => syncAllNestedJson(c))\n }\n })()\n\n // Editable text (issue #351). Delegated keys, paste and drop on the root,\n // whether or not it owns an editable yet: a stream can append the first one\n // into a root whose bindings connected for another marker (each handler\n // returns at once for an event that is not an owned editable's).\n listen(c, \"keydown\", (event) => editableKey(c, event))\n listen(c, \"paste drop\", (event) => editablePaste(c, event))\n listen(c, \"input\", (event) => editableEmptied(c, event))\n}\n\n// Remove every listener connect() added, so a stray event after a Turbo\n// morph/navigation never re-evaluates against a detached root.\nexport function disconnect(controller) {\n const c = contexts.get(controller)\n if (!c) return\n contexts.delete(controller)\n rootContexts.delete(c.root)\n for (const off of c.offs ?? []) off()\n c.groupObserver?.disconnect()\n}\n\n// Re-run the seeds that read field values, in connect() order — for a\n// feature that changed those values after connect() ran (the draft restore),\n// or content a stream rendered into the root (issue #356) — then wire any\n// binding whose gate reads true only now. Each seed is the same re-sync a\n// morph runs; on-complete re-ARMS without firing.\nexport function reseed(controller) {\n const c = contexts.get(controller)\n if (!c) return\n for (const run of c.seeds) run()\n c.wire()\n}\n\n// A value this module wrote is announced the way a user's edit is: a bubbling\n// `input` (the set-value + dispatch contract, issue #183), so dirty tracking,\n// reactive_show and compute all see it.\nfunction fireInput(el) {\n if (typeof el.dispatchEvent === \"function\") el.dispatchEvent(new Event(\"input\", { bubbles: true }))\n}\n\n// The Stimulus actions this module answers (the controller's own methods of\n// the same names hand the event here). tagsAdd, tagsPick, tagsRemove,\n// nestedAdd and nestedRemove take the controller themselves; the JSON sync is\n// also the root's own listener, so it keeps its context form inside.\nfunction publicSyncNestedJson(controller, core, event) {\n return syncNestedJson(ctx(controller, core), event)\n}\nexport { publicSyncNestedJson as syncNestedJson }\n\n// The runtime's call-in for a conditional confirm: the message when its\n// condition fires over this root's fields, else null.\nexport function confirmMessage(controller, core, confirmWhen) {\n return conditionalConfirmMessage(ctx(controller, core), confirmWhen)\n}\n\n// An id-only selector (the issue #159/#164 allowlist for anything that\n// escapes the root).\nconst ID_SELECTOR = /^#[A-Za-z_][\\w-]*$/\n\n// The selector matching every OWNED-element show binding: single-field\n// (data-reactive-show-field, issue #161) OR compound all:/any:\n// (data-reactive-show, issue #176). Both the connect() gate and the sync walk\n// use it so a compound-only root still enables the sync.\nconst SHOW_BINDING_SELECTOR = \"[data-reactive-show-field], [data-reactive-show]\"\n\n// Evaluate a show binding's declared literal predicate (issue #161) against\n// the controlling field's current value. Exactly one of the three predicate\n// attrs decides: equals (value === literal), not (value !== literal), in\n// (value ∈ a JSON string list). The vocabulary is fixed and literal-only —\n// never an expression, so there is no eval surface (the reactive_show helper\n// enforces the same shape loudly at render; this is the client half of the\n// two-sided posture). Returns true/false for a decidable binding, or null for\n// a malformed/missing predicate — the caller SKIPS a null so a hand-built or\n// stale binding never flips visibility it doesn't understand (default-deny,\n// like the op whitelist).\nfunction showBindingMatches(el, value) {\n const equals = el.getAttribute(\"data-reactive-show-equals\")\n if (equals !== null) return value === equals\n const not = el.getAttribute(\"data-reactive-show-not\")\n if (not !== null) return value !== not\n const inRaw = el.getAttribute(\"data-reactive-show-in\")\n if (inRaw !== null) {\n try {\n const list = JSON.parse(inRaw)\n if (Array.isArray(list)) return list.includes(value)\n } catch {\n // fall through to the warn below — malformed JSON and a non-array both skip\n }\n console.warn(`[phlex-reactive] malformed reactive_show in: list ${JSON.stringify(inRaw)} — skipped`)\n return null\n }\n // Numeric threshold predicates (issue #176 part B): gte/gt/lte/lt read the\n // literal off its own flat attr and compare Number(value) against it. Any\n // present numeric attr decides the binding — a non-numeric field value (NaN)\n // is false (hidden), and a non-numeric LITERAL warn-skips (null).\n for (const key of SHOW_NUMERIC_KEYS) {\n const raw = el.getAttribute(`data-reactive-show-${key}`)\n if (raw !== null) return numericPredicateMatches(key, raw, value)\n }\n console.warn(\"[phlex-reactive] a reactive_show binding declares no predicate — skipped\")\n return null\n}\n\n// Parse a compound show binding's JSON payload (issue #176 part A). Malformed\n// JSON degrades to null WITH a warn — a bad binding must never throw or blank\n// the page (client-side default-deny), but a collision (two bindings' JSON\n// mix-joined) is worth surfacing.\nfunction parseShowCompound(raw) {\n try {\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed\n } catch {\n // fall through to the warn\n }\n console.warn(`[phlex-reactive] malformed compound reactive_show payload ${JSON.stringify(raw)} — skipped`)\n return null\n}\n\n// Parse a data-reactive-on-complete payload (issue #226): a JSON array of\n// { any: [[term, …], …], ops: [[op, args], …] } bindings. Malformed JSON, a\n// non-array, or a binding missing either half degrades to [] WITH a warn — a\n// bad payload must never throw or fire an op (client-side default-deny, the\n// parseShowCompound posture).\nfunction parseOnComplete(raw) {\n try {\n const list = JSON.parse(raw)\n if (\n Array.isArray(list) &&\n list.every((b) => b && typeof b === \"object\" && Array.isArray(b.any) && Array.isArray(b.ops))\n ) {\n return list\n }\n } catch {\n // fall through to the warn\n }\n console.warn(`[phlex-reactive] malformed reactive_on_complete payload ${JSON.stringify(raw)} — skipped`)\n return []\n}\n\n// Route a parsed data-reactive-show payload to the right evaluator. The 0.10\n// wire is { any: [ [term,…], … ] } (DNF — groups are ARRAYS). For a stale tab\n// still serving pre-0.10 HTML (deploy overlap), fall back to the 0.9.5 compound\n// shape { all: [term,…] } / { any: [term,…] } where the values are flat TERM\n// OBJECTS, not arrays. The nesting distinguishes them: DNF's any[0] is an Array.\n// DELETE the legacy arm in 0.11.\nfunction showPayloadMatches(payload, fieldValue) {\n if (!payload || typeof payload !== \"object\") return null\n const any = payload.any\n if (Array.isArray(any) && (any.length === 0 || Array.isArray(any[0]))) {\n return anyOfAllsMatches(any, fieldValue)\n }\n return legacyCompoundShowMatches(payload, fieldValue)\n}\n\n// LEGACY (0.9.5, deploy-overlap only — DELETE in 0.11): the flat all:/any:\n// compound fold, where terms are objects (not groups). Preserved so a morph of\n// stale pre-0.10 HTML doesn't go dead.\nfunction legacyCompoundShowMatches(payload, fieldValue) {\n const connective = Array.isArray(payload.all) ? \"all\" : Array.isArray(payload.any) ? \"any\" : null\n if (!connective) return null\n const terms = payload[connective]\n if (terms.length === 0) return null\n const results = terms.map((term) => dnfTermMatches(term, fieldValue))\n return connective === \"all\" ? results.every(Boolean) : results.some(Boolean)\n}\n\n// A cross-root show target must be a single ID selector (issue #164) — the\n// SAME shape the #159 mirror enforces (one shared regex), with its own warn so\n// a refused show target is distinguishable in the console. The client half of\n// the two-sided default-deny: reactive_show_targets raises at declare time; a\n// hand-built wire attr must not widen the escape to class/compound selectors.\n// A refused selector warns + skips — its siblings still apply. The group\n// targets (issue #343) share it, naming their own kind in the warn.\nfunction guardShowTargetSelector(selector, kind = \"show\") {\n if (typeof selector === \"string\" && ID_SELECTOR.test(selector)) return true\n console.warn(`[phlex-reactive] refused cross-root ${kind} target ${JSON.stringify(selector)} — skipped`)\n return false\n}\n\n\n// Whether this root owns a show binding (issue #161) or declares cross-root\n// show targets (issue #164) — the connect() gate, so a component with\n// neither pays only this probe (the #dirtyTrackingEnabled precedent). A\n// NESTED root's bindings don't count: its own controller instance syncs them\n// (issue #15 ownership). The targets attr is checked FIRST — one\n// getAttribute, cheaper than the binding walk.\nfunction showSyncEnabled(c) {\n if (c.root.getAttribute?.(\"data-reactive-show-targets\")) return true\n if (c.root.getAttribute?.(\"data-reactive-group-targets\")) return true\n // Single-field bindings carry -field; compound all:/any: bindings (issue\n // #176) carry data-reactive-show and have NO single controlling field, so\n // both selectors gate the sync.\n const nodes = c.root.querySelectorAll?.(SHOW_BINDING_SELECTOR) ?? []\n for (const el of nodes) if (c.core.owns(el)) return true\n for (const el of c.root.querySelectorAll?.(GROUP_BINDING_SELECTOR) ?? []) if (c.core.owns(el)) return true\n for (const el of c.root.querySelectorAll?.(`${MEDIA_BINDING_SELECTOR}, ${CSS_VARS_SELECTOR}`) ?? []) {\n if (c.core.owns(el)) return true\n }\n return c.root.hasAttribute?.(\"data-reactive-css-vars\") ?? false\n}\n\n// The connect() gate for completion bindings (issue #226) — one attribute read.\nfunction onCompleteEnabled(c) {\n return !!c.root.getAttribute?.(\"data-reactive-on-complete\")\n}\n\n// Parse-and-memoize the completion bindings, keyed on the RAW attr string:\n// a morph that rewrote the payload re-parses and RESETS the latches (the\n// morph listener's own arm pass then re-arms without firing). A removed\n// attr yields [] silently; malformed JSON warns (in parseOnComplete).\nfunction onCompleteBindings(c) {\n const raw = c.root.getAttribute?.(\"data-reactive-on-complete\") ?? null\n if (raw !== c.onCompleteRaw) {\n c.onCompleteRaw = raw\n c.onCompleteParsed = raw == null ? [] : parseOnComplete(raw)\n c.onCompleteStates = c.onCompleteParsed.map(() => false)\n }\n return c.onCompleteParsed\n}\n\n// Evaluate every completion binding (issue #226) over the owned fields —\n// the SAME memoized, scope-aware field resolver and DNF fold the show sync\n// uses — and run each binding's ops on ITS OWN rising edge. `event` null\n// (the connect/morph arm pass) updates the latches WITHOUT firing, so ops\n// only ever run from a real user gesture. An undecidable payload (no\n// groups) leaves its latch alone — default-deny, like every malformed-wire\n// arm. Ops resolve through runOps's root-scoped targets; a missing to:\n// defaults to \"@root\" (the $ops convention).\nfunction syncOnComplete(c, event) {\n const bindings = onCompleteBindings(c)\n if (!bindings.length) return\n\n const fieldValue = fieldResolver(c, c.core.ownership())\n bindings.forEach((binding, i) => {\n const matches = anyOfAllsMatches(binding.any, fieldValue)\n if (matches === null) return\n const fire = matches && !c.onCompleteStates[i] && Boolean(event)\n c.onCompleteStates[i] = matches\n if (fire) {\n c.core.applyOps(binding.ops, \"@root\")\n }\n })\n}\n\n// Re-evaluate every OWNED show binding in one pass (issue #161): read the\n// controlling field's current value, evaluate the declared literal predicate,\n// toggle `hidden`. A full pass (not per-target) for the same reason as\n// #scanDirty — a radio group's deselected radio fires no event — and because\n// several bindings can hang off one field (the value read is memoized per\n// pass). A binding whose field can't be resolved, or whose predicate is\n// malformed, leaves visibility ALONE — a bad binding must never break or\n// blank the page (client-side default-deny).\nfunction syncShow(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return\n\n const owns = c.core.ownership()\n const scope = c.root.getAttribute?.(\"data-reactive-scope\") || null\n // A memoized resolver shared by every binding in this pass — a field driving\n // several bindings (and several DNF terms) reads exactly once. Scope-aware:\n // a bare field `director` resolves as `[name=\"scope[director]\"]` (issue #180).\n const fieldValue = fieldResolver(c, owns)\n // Bindings whose visibility flipped this pass and that declare transition\n // work (issue #394) — run after the pass, so the `input` a clear dispatches\n // re-syncs from fresh values instead of this pass's memo.\n const moved = []\n for (const el of c.root.querySelectorAll(SHOW_BINDING_SELECTOR)) {\n if (!owns(el)) continue // a nested root's binding is its own controller's job\n\n // The 0.10 DNF payload (issue #180): data-reactive-show carries\n // { any: [ [term,…], … ] }. The legacy flat-attr and 0.9.5-compound read\n // arms live in showPayloadMatches/showBindingMatches for deploy overlap.\n const payloadRaw = el.getAttribute(\"data-reactive-show\")\n if (payloadRaw !== null) {\n const match = showPayloadMatches(parseShowCompound(payloadRaw), fieldValue)\n if (match === null) continue\n // after: (issue #396) keeps it hidden until its field has blurred once.\n const after = el.getAttribute(\"data-reactive-show-after\")\n const visible = match && (after == null || !!c.touched?.has(wireName(after, scope)))\n applyShowVisibility(el, visible, owns, scope)\n // The previous visibility lives on this controller (absent on connect,\n // kept by a morph), so first paint never counts as a change.\n // Tracked for every binding, so a morph that drops the transition attrs\n // and later restores them never compares against a stale value.\n const was = (c.shown ??= new WeakMap()).get(el)\n c.shown.set(el, visible)\n const moves = SHOW_MOVES.some((name) => el.hasAttribute(`data-reactive-show-${name}`))\n if (moves && was !== undefined && was !== visible) moved.push(el)\n continue\n }\n\n // LEGACY flat-attr binding (pre-0.10, deploy overlap — removed in 0.11).\n const name = el.getAttribute(\"data-reactive-show-field\")\n if (!name) continue\n const value = fieldValue(name)\n if (value === null) continue // no owned field with that name — leave it be\n const match = showBindingMatches(el, value)\n if (match === null) continue // malformed predicate — warned + skipped\n applyShowVisibility(el, match, owns, scope)\n }\n\n // The group bindings (issue #319) and the cross-root pass (issue #164)\n // share the same owned-field memo, so a field driving several reads once.\n if (c.groups) syncGroups(c, fieldValue, owns, scope)\n syncMedia(c, fieldValue, owns)\n syncCssVars(c, fieldValue, owns, scope)\n syncShowTargets(c, fieldValue)\n syncGroupTargets(c, fieldValue)\n for (const el of moved) showMoved(c, el, owns, scope)\n}\n\n// The transition attrs a show binding may declare (issue #394).\nconst SHOW_MOVES = [\"clear\", \"focus\", \"scroll\"]\n\n// A binding just changed visibility (issue #394). Hidden: empty each clear:\n// field with set_value's write (which announces only a real change), uncheck a\n// checkbox or radio, skip a file input. Visible: scroll the section into view,\n// then focus the first match of focus: inside the root.\nfunction showMoved(c, el, owns, scope) {\n if (el.hidden) {\n let names = []\n try {\n names = JSON.parse(el.getAttribute(\"data-reactive-show-clear\") ?? \"[]\")\n } catch {}\n // Compared by attribute, not a [name=\"…\"] selector, so a name holding a\n // `\"` or `\\` clears its field instead of throwing.\n const wires = new Set((Array.isArray(names) ? names : []).map((name) => wireName(String(name), scope)))\n for (const field of wires.size ? c.root.querySelectorAll(\"[name]\") : []) {\n if (!wires.has(field.getAttribute(\"name\")) || !owns(field) || field.type === \"file\") continue\n if (field.type === \"checkbox\" || field.type === \"radio\") {\n if (field.checked) {\n field.checked = false\n fireInput(field)\n }\n } else c.core.setValue(field, \"\")\n }\n return\n }\n const scroll = el.getAttribute(\"data-reactive-show-scroll\") === \"true\"\n if (scroll) el.scrollIntoView?.({ block: \"nearest\" })\n const focus = el.getAttribute(\"data-reactive-show-focus\")\n let target = null\n try {\n target = focus ? c.root.querySelector(focus) : null\n } catch {}\n target?.focus?.(scroll ? { preventScroll: true } : undefined)\n}\n\n// Toggle `hidden` (and, when the binding declares data-reactive-show-disable,\n// the `disabled` of every owned named control inside it) from a match result\n// (issue #180). Disabling a hidden section's controls stops them submitting —\n// the stale-value fix. A visible section re-enables them. Controls a nested\n// reactive root owns are left alone (#15 ownership).\nfunction applyShowVisibility(el, match, owns, scope) {\n el.hidden = !match\n if (el.getAttribute(\"data-reactive-show-disable\") !== \"true\") return\n if (typeof el.querySelectorAll !== \"function\") return\n for (const control of el.querySelectorAll(\"input[name], select[name], textarea[name]\")) {\n if (owns(control)) control.disabled = !match\n }\n // The element itself may be a named control (a bare field with a binding).\n if (el.name && owns(el)) el.disabled = !match\n}\n\n// Apply the declared cross-root show targets (issue #164) — the visibility\n// parallel of #applyComputeMirrors. For each declared field: read the OWNED\n// field's current value (never a nested root's — you can only drive outside\n// visibility from a field this root owns), then for each \"#id\" → predicate\n// entry: guard the selector id-only (warn-and-skip; the Ruby helper raised\n// at declare time — two-sided default-deny), resolve it DOCUMENT-WIDE, and\n// toggle `hidden`. A target id not on the page is silently skipped (an\n// unrendered tab pane is normal); a malformed predicate warn-skips its one\n// target while siblings still apply. With no map declared this is one\n// getAttribute and out.\n//\n// A \"#id\" KEY (issue #209) is a TARGET-KEYED entry instead: its value is the\n// same DNF payload data-reactive-show holds, folded with per-term owned-field\n// reads — the multi-field cross-root case. The \"#\" prefix routes unambiguously\n// (a field name may never start with \"#\"; the Ruby helper raises).\nfunction syncShowTargets(c, fieldValue) {\n const map = parseShowTargets(c)\n for (const [name, targets] of Object.entries(map)) {\n if (name.startsWith(\"#\")) {\n applyConditionsTarget(name, targets, fieldValue)\n continue\n }\n if (!targets || typeof targets !== \"object\" || Array.isArray(targets)) continue\n const value = fieldValue(name)\n if (value === null) continue // no owned field with that name — leave them be\n // Every target's terms share this one field, so a constant resolver folds\n // the group (issue #180): a target's value is a DNF GROUP (terms ANDed).\n // (A checked_* term asks for the group's count instead, issue #319.)\n const resolve = (_, count) => (count ? fieldValue(name, true) : value)\n for (const [selector, group] of Object.entries(targets)) {\n if (!guardShowTargetSelector(selector)) continue\n // 0.10 wire: the value is a DNF GROUP (an array of terms, ANDed).\n // LEGACY (0.9.5, deploy overlap — DELETE in 0.11): a flat predicate\n // OBJECT ({ equals/not/in/gte… }) routed through showPredicateMatches.\n let match\n if (Array.isArray(group)) {\n if (group.length === 0) {\n console.warn(`[phlex-reactive] malformed reactive_show_targets group for ${selector} — skipped`)\n continue\n }\n match = group.every((term) => dnfTermMatches(term, resolve))\n } else {\n const legacy = showPredicateMatches(group, value)\n if (legacy === null) {\n console.warn(`[phlex-reactive] malformed reactive_show_targets predicate for ${selector} — skipped`)\n continue\n }\n match = legacy\n }\n for (const node of document.querySelectorAll(selector)) node.hidden = !match\n }\n }\n}\n\n// Apply ONE target-keyed conditions entry (issue #209): \"#id\" → the DNF\n// payload { any: [[term,…],…] }, folded by the SAME anyOfAllsMatches as an\n// in-root reactive_show — each term reads its OWN owned field, a missing\n// owned field reads as blank (fail-closed, the shared-fixture contract). A\n// target whose referenced fields are ALL unowned is left alone — the\n// single-field skip generalized (this root has nothing to evaluate with) —\n// unless every term is a checked_* count (issue #348): a group with no owned\n// boxes counts 0, so that target is always decidable, as in-root. A\n// malformed payload warn-skips its one target while siblings still apply;\n// the selector guard is the same id-only allowlist as every cross-root arm.\nfunction applyConditionsTarget(selector, payload, fieldValue) {\n if (!guardShowTargetSelector(selector)) return\n const groups = payload && typeof payload === \"object\" && !Array.isArray(payload) ? payload.any : null\n const fields = dnfGroupFields(groups)\n if (fields === null) {\n console.warn(`[phlex-reactive] malformed reactive_show_targets conditions for ${selector} — skipped`)\n return\n }\n if (fields.every((name) => fieldValue(name) === null) && !countsOnly(groups)) return // no owned field — leave it be\n const match = anyOfAllsMatches(groups, fieldValue)\n if (match === null) return // unreachable after dnfGroupFields, kept fail-closed\n for (const node of document.querySelectorAll(selector)) node.hidden = !match\n}\n\n// The declared cross-root show-target map (issue #164): a JSON object of\n// { field: { \"#id\": predicate } } from data-reactive-show-targets (emitted\n// by reactive_show_targets on the root). Absent degrades to {}; malformed\n// degrades to {} WITH a warn — never a throw (the #parseComputeMirror\n// contract), but never silent either: the likeliest cause is TWO\n// reactive_show_targets calls on one root, whose JSON strings Phlex `mix`\n// space-joined into an unparseable attr. The warn names the fix.\nfunction parseShowTargets(c, kind = \"show\", fix = \"mode: { ... }, kind: { ... }\") {\n const raw = c.root.getAttribute?.(`data-reactive-${kind}-targets`)\n if (!raw) return {}\n try {\n const parsed = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed\n } catch {\n // fall through to the shared warn below\n }\n console.warn(\n `[phlex-reactive] malformed data-reactive-${kind}-targets — ignored. ` +\n `Did two reactive_${kind}_targets calls collide on one root? Declare every entry in ONE call: ` +\n `reactive_${kind}_targets(${fix})`\n )\n return {}\n}\n\n// The current value of the OWNED field controlling a show binding, as the\n// string the literal predicate compares against. Mirrors #collectFields'\n// per-kind reads: a checkbox reports its checked state (\"true\"/\"false\" — its\n// .value is the constant \"on\", and the checkbox wins over the hidden input\n// Rails pairs with it); a radio group reports the CHECKED radio's value (\"\"\n// when none is); anything else reports .value first-wins. Returns null when\n// no owned field carries the name — the caller then leaves visibility alone.\nfunction showFieldValue(c, name, owns, scope) {\n let sawRadio = false\n let first = null\n for (const el of c.root.querySelectorAll(namedSelector(name, scope))) {\n if (!owns(el)) continue\n if (el.type === \"checkbox\") return el.checked ? \"true\" : \"false\"\n if (el.type === \"radio\") {\n if (el.checked) return el.value ?? \"\"\n sawRadio = true\n continue\n }\n first ??= el\n }\n if (first) return first.value ?? \"\"\n return sawRadio ? \"\" : null\n}\n\n// Scope (issue #180): a bare field `director` under `data-reactive-scope=\n// \"form\"` resolves as `[name=\"form[director]\"]`. A name already carrying a\n// bracket (a raw wire name the author passed, like \"ids[]\") is used verbatim.\nfunction namedSelector(name, scope) {\n return `[name=\"${wireName(name, scope)}\"]`\n}\n\nfunction wireName(name, scope) {\n return scope && !name.includes(\"[\") ? `${scope}[${name}]` : name\n}\n\n// The per-pass field resolver every DNF fold reads (show, enable, on-complete).\n// fieldValue(name) is the field's string value; fieldValue(name, true) is how\n// many owned boxes of that checkbox group are ticked (the checked_* terms,\n// issue #319). Memoized, so a field driving several bindings reads once.\nfunction fieldResolver(c, owns) {\n const scope = c.root.getAttribute?.(\"data-reactive-scope\") || null\n const values = new Map()\n return (name, count) => {\n const key = count ? `#${name}` : name\n if (!values.has(key)) {\n values.set(key, count ? groupBoxes(c, name, owns, scope).filter((box) => box.checked).length : showFieldValue(c, name, owns, scope))\n }\n return values.get(key)\n }\n}\n\n// --- Media bindings (issue #373) ---------------------------------------------\n// data-reactive-media='{\"field\",\"take\"?,\"match\"?,\"when\"?,\"pending\"?,\"pool\",\"label\"?,\"blank\"?}'\n// on a preview <img>: the owned field's value (its first `take` characters, or\n// all of it) is a key into `pool`, whose value is a SELECTOR for an <img>\n// inside the root. The core's copyMedia copies that element's src, srcset and\n// alt — a pool value is never assigned to anything. A key, selector or element\n// that misses clears the preview; `label` gets the alt (or `blank`) via\n// textContent. A key shorter than `take`, a key the anchored `match` source\n// rejects, or a WHOLE field value the anchored `when` source rejects (issue\n// #390 — tested before the pool lookup; the key stays the prefix) is PENDING\n// (issue #380) and never gets `blank`: \"keep\" leaves the preview and label\n// alone, the default clears both. The preview's\n// data-reactive-media-state names the outcome (pending | hit | miss). An\n// unowned field leaves the preview alone (the show default-deny); a malformed\n// attr warns and is skipped.\nconst MEDIA_BINDING_SELECTOR = \"[data-reactive-media]\"\n\nfunction syncMedia(c, fieldValue, owns) {\n for (const el of c.root.querySelectorAll(MEDIA_BINDING_SELECTOR)) {\n if (!owns(el)) continue\n let wire, pattern, whole\n try {\n wire = JSON.parse(el.getAttribute(\"data-reactive-media\"))\n if (wire?.match != null) pattern = new RegExp(`^(?:${wire.match})$`)\n if (wire?.when != null) whole = new RegExp(`^(?:${wire.when})$`)\n } catch {}\n if (\n typeof wire?.field !== \"string\" ||\n !wire.pool ||\n typeof wire.pool !== \"object\" ||\n (wire.match != null && !pattern) ||\n (wire.when != null && !whole)\n ) {\n console.warn(\"[phlex-reactive] malformed data-reactive-media — skipped\")\n continue\n }\n const value = fieldValue(wire.field)\n if (value === null) continue\n // Characters (code points), as Ruby counts them — not UTF-16 code units.\n const chars = wire.take > 0 ? [...value] : null\n const key = chars ? chars.slice(0, wire.take).join(\"\") : value\n const pending = chars?.length < wire.take || pattern?.test(key) === false || whole?.test(value) === false\n if (pending && wire.pending === \"keep\") {\n mediaState(el, \"pending\")\n continue\n }\n const source = !pending && Object.hasOwn(wire.pool, key) ? mediaMatches(c, wire.pool[key])[0] : null\n const alt = c.core.copyMedia(el, source ?? null)\n if (alt === null) continue\n mediaState(el, pending ? \"pending\" : alt === false ? \"miss\" : \"hit\")\n if (typeof wire.label !== \"string\") continue\n const text = pending ? \"\" : alt === false ? String(wire.blank ?? \"\") : alt\n for (const node of mediaMatches(c, wire.label)) if (node.textContent !== text) node.textContent = text\n }\n}\n\n// The outcome a stylesheet (or :has()) can hide a row on, written only when\n// it changes.\nfunction mediaState(el, state) {\n if (el.getAttribute(\"data-reactive-media-state\") !== state) el.setAttribute(\"data-reactive-media-state\", state)\n}\n\n// The owned elements a pool or label selector names — none when it does not\n// parse (a URL string is not a selector), and none for the \"@root\" sentinel:\n// a label naming the root would rewrite the whole root's text.\nfunction mediaMatches(c, selector) {\n try {\n return selector === \"@root\" ? [] : c.core.opTargets({ to: selector })\n } catch {\n return []\n }\n}\n\n// --- CSS custom properties (issue #417) --------------------------------------\n// data-reactive-css-vars='{\"to\":[selector|\"@root\",…],\"global\"?:true,\n// \"vars\":{\"--name\":{\"field\",\"unit\"?}}}' on the root or an element it owns.\n// Each property reads its owned field (a checkbox is 1 or 0, a radio group its\n// checked value) as a finite number and writes number + unit on every `to:`\n// target, resolved from the root like a client op's. Anything else removes the\n// property, so the author's var() fallback applies: no string from a field ever\n// reaches CSS. A name or unit off the Ruby allowlist is refused here too (a\n// hand-built attr must not widen it); a field no owned control carries leaves\n// the property alone (the show default-deny). A value is written only when it\n// changes, since the pass runs on every owned field's edit.\nconst CSS_VARS_SELECTOR = \"[data-reactive-css-vars]\"\nconst CSS_VAR_NAME = /^--[a-z0-9-]+$/i\nconst CSS_VAR_UNITS = [\"\", \"px\", \"%\", \"deg\", \"turn\", \"ms\", \"s\", \"em\", \"rem\", \"fr\"]\n\nfunction syncCssVars(c, fieldValue, owns, scope) {\n const nodes = [...c.root.querySelectorAll(CSS_VARS_SELECTOR)].filter(owns)\n if (c.root.hasAttribute(\"data-reactive-css-vars\")) nodes.unshift(c.root)\n for (const el of nodes) {\n let wire\n try {\n wire = JSON.parse(el.getAttribute(\"data-reactive-css-vars\"))\n } catch {}\n if (!Array.isArray(wire?.to) || !wire.vars || typeof wire.vars !== \"object\") {\n // Most likely two calls mixed onto one element: their JSON space-joins.\n console.warn(\"[phlex-reactive] malformed data-reactive-css-vars — skipped (two reactive_css_vars on one element?)\")\n continue\n }\n // A selector that does not parse matches nothing: it must not throw out\n // of the show pass and stop the root's other bindings.\n const targets = wire.to.flatMap((to) => {\n const args = { to, global: wire.global === true }\n let found = []\n try {\n found = c.core.opTargets(args)\n } catch {}\n if (!found.length) c.core.diagnose(\"reactive_css_vars\", args)\n return found\n })\n for (const [name, spec] of Object.entries(wire.vars)) {\n const unit = spec?.unit ?? \"\"\n if (!CSS_VAR_NAME.test(name) || !CSS_VAR_UNITS.includes(unit) || typeof spec?.field !== \"string\") {\n console.warn(`[phlex-reactive] refused reactive_css_vars entry ${JSON.stringify(name)} — skipped`)\n continue\n }\n const number = cssVarNumber(c, fieldValue, spec.field, owns, scope)\n if (number === undefined) continue\n const value = number === null ? \"\" : `${number}${unit}`\n for (const target of targets) {\n if (target.style.getPropertyValue(name) === value) continue\n if (value) target.style.setProperty(name, value)\n else target.style.removeProperty(name)\n }\n }\n }\n}\n\n// The number an owned field holds: 1 or 0 for a checkbox (decided by its\n// type, so a text field reading \"true\" is no number), else its value through\n// Number() — null when that is not finite or the value is blank (Number(\"\")\n// is 0), undefined when no owned field has the name.\nfunction cssVarNumber(c, fieldValue, name, owns, scope) {\n const value = fieldValue(name)\n if (value === null) return undefined\n if (\n (value === \"true\" || value === \"false\") &&\n [...c.root.querySelectorAll(namedSelector(name, scope))].some((el) => owns(el) && el.type === \"checkbox\")\n ) {\n return value === \"true\" ? 1 : 0\n }\n const number = value.trim() ? Number(value) : NaN\n return Number.isFinite(number) ? number : null\n}\n\n// --- Bulk selection (issue #319) ---------------------------------------------\n// A checkbox GROUP is the owned boxes sharing one name. Three bindings read it:\n// the select-all header (data-reactive-select-all), the ticked count\n// (data-reactive-count), and the checked_* terms any condition can use —\n// reactive_enable (data-reactive-enable) flips the element's own `disabled`\n// from one. They re-sync with the show pass: on every input/change, on a\n// morph, and when boxes are added or removed (observeGroups). A header with\n// data-reactive-select-all-under (issue #398) is one branch of a tree: it owns\n// the boxes of the name whose data-reactive-group is in its path.\nconst GROUP_BINDING_SELECTOR = \"[data-reactive-enable], [data-reactive-select-all], [data-reactive-count]\"\n\n// Whether the root holds any group binding (owned or not — a stray nested\n// one only costs the walk, which still skips it).\nfunction hasGroups(c) {\n return !!c.root.querySelector?.(GROUP_BINDING_SELECTOR)\n}\n\n// The owned checkboxes of a group (a nested root's boxes are its own, #15).\n// With `under` (a nested header, issue #398) only the boxes whose\n// data-reactive-group is that path or below it, on whole segments.\nfunction groupBoxes(c, name, owns, scope, under) {\n return [...c.root.querySelectorAll(namedSelector(name, scope))].filter(\n (el) => el.type === \"checkbox\" && owns(el) && (!under || inGroupPath(el.getAttribute(\"data-reactive-group\"), under)),\n )\n}\n\nfunction inGroupPath(path, under) {\n return path === under || !!path?.startsWith(`${under}.`)\n}\n\n// A header's edit ticks or unticks every owned box of its group (the header\n// itself is never a member). The show listener syncs once afterwards.\nfunction flipGroup(c, header) {\n const group = header?.getAttribute?.(\"data-reactive-select-all\")\n if (group && c.core.owns(header)) {\n setGroup(c, group, header.checked, header, header.getAttribute(\"data-reactive-select-all-under\"))\n }\n}\n\n// The check_group op (issue #342): set a root's group the way its header\n// would, then sync its bindings once. A root this module never connected (no\n// group binding, only the boxes) still flips, with the #15 ownership check.\nexport function checkGroup(root, group, checked) {\n if (!group) return\n const c = rootContexts.get(root) ?? {\n root,\n core: { ownership: () => (el) => el.closest('[data-controller~=\"reactive\"]') === root },\n }\n setGroup(c, group, checked !== false)\n c.show?.()\n}\n\n// Tick or untick every owned box of a group, and dispatch `input` + `change`\n// on each one it flips so computes, shows and on-complete bindings see a real\n// edit. The re-entrant events are skipped by the show listener while this\n// runs (c.flipping); the caller syncs once afterwards.\nfunction setGroup(c, group, checked, except, under) {\n const scope = c.root.getAttribute?.(\"data-reactive-scope\") || null\n const flipped = groupBoxes(c, group, c.core.ownership(), scope, under).filter((box) => box !== except && box.checked !== checked)\n // Every box first, then the events: a listener (a checked-count\n // on_complete) must see the group's final count, never a half-flipped one.\n for (const box of flipped) box.checked = checked\n c.flipping = true\n try {\n for (const box of flipped) {\n // input then change, as a click does: computes listen on input.\n for (const type of [\"input\", \"change\"]) box.dispatchEvent?.(new Event(type, { bubbles: true }))\n }\n } finally {\n c.flipping = false\n }\n}\n\n// One pass over the owned group bindings: enable from its conditions, the\n// count as text (change-guarded, like #mirrorText), and each header's\n// checked/indeterminate from its group (the header itself never counts).\nfunction syncGroups(c, fieldValue, owns, scope) {\n for (const el of c.root.querySelectorAll(GROUP_BINDING_SELECTOR)) {\n if (!owns(el)) continue\n const enable = el.getAttribute(\"data-reactive-enable\")\n if (enable !== null) {\n const match = showPayloadMatches(parseShowCompound(enable), fieldValue)\n if (match !== null) el.disabled = !match\n }\n const counted = el.getAttribute(\"data-reactive-count\")\n if (counted) {\n const text = String(fieldValue(counted, true))\n if (el.textContent !== text) el.textContent = text\n }\n const group = el.getAttribute(\"data-reactive-select-all\")\n if (group) {\n const under = el.getAttribute(\"data-reactive-select-all-under\")\n const boxes = groupBoxes(c, group, owns, scope, under).filter((box) => box !== el)\n const ticked = boxes.filter((box) => box.checked).length\n el.checked = ticked > 0 && ticked === boxes.length\n el.indeterminate = ticked > 0 && ticked < boxes.length\n }\n }\n}\n\n// The declared cross-root group targets (issue #343) — the count and enable\n// parallel of syncShowTargets, declared on the root that OWNS the group:\n// { group: { count: [\"#id\", …], enable: { \"#id\": { any: … } } } }. The count\n// is this root's owned ticked boxes (a nested root's are its own, #15), the\n// enable folds its DNF payload with the same owned-field memo as every other\n// binding. Targets are id-only (warn-skip — the Ruby helper raised at\n// declare time) and resolved document-wide; a missing one is skipped.\nfunction syncGroupTargets(c, fieldValue) {\n for (const [group, targets] of Object.entries(parseShowTargets(c, \"group\", '\"ids[]\" => { ... }, \"tags[]\" => { ... }'))) {\n if (!targets || typeof targets !== \"object\" || Array.isArray(targets)) continue\n const text = String(fieldValue(group, true))\n for (const selector of Array.isArray(targets.count) ? targets.count : []) {\n if (!guardShowTargetSelector(selector, \"group\")) continue\n for (const node of document.querySelectorAll(selector)) if (node.textContent !== text) node.textContent = text\n }\n const enable = targets.enable && typeof targets.enable === \"object\" ? targets.enable : {}\n for (const [selector, payload] of Object.entries(enable)) {\n if (!guardShowTargetSelector(selector, \"group\")) continue\n const match = anyOfAllsMatches(payload?.any, fieldValue)\n if (match === null) {\n console.warn(`[phlex-reactive] malformed reactive_group_targets enable for ${selector} — skipped`)\n continue\n }\n for (const node of document.querySelectorAll(selector)) node.disabled = !match\n }\n }\n}\n\n// Boxes added or removed later — a stream append, a removal — fire no event,\n// so a root with a group binding (a header, a count, an enable, or a show,\n// show target or on_complete with a checked_* term) watches its subtree and\n// re-syncs when a mutation adds or removes a checkbox: the show pass, and the\n// on_complete latches re-armed without firing. Text writes (the count itself)\n// never qualify, so it cannot loop. Installed once — at connect, or by the\n// first morph that adds such a binding.\nfunction observeGroups(c) {\n if (c.groupObserver || typeof MutationObserver !== \"function\") return\n const onRoot = (name) => c.root.getAttribute?.(`data-reactive-${name}`)?.includes(\"checked_\")\n const targeted = !!c.root.getAttribute?.(\"data-reactive-group-targets\")\n if (!targeted && !c.root.querySelector?.(`${GROUP_BINDING_SELECTOR}, [data-reactive-show*=checked_]`) && !onRoot(\"show-targets\") && !onRoot(\"on-complete\")) return\n const boxIn = (node) => node.nodeType === 1 && (node.matches('input[type=\"checkbox\"]') || !!node.querySelector('input[type=\"checkbox\"]'))\n c.groupObserver = new MutationObserver((records) => {\n if (!records.some((r) => [...r.addedNodes, ...r.removedNodes].some(boxIn))) return\n c.show?.()\n c.arm?.()\n })\n c.groupObserver.observe(c.root, { childList: true, subtree: true })\n}\n\n// Whether this root declares an option filter (issue #163) — the connect()\n// gate. reactive_filter always emits input + option together, so requiring\n// BOTH also default-denies a half-built hand-authored binding.\nfunction filterEnabled(c) {\n return !!(\n c.root.getAttribute?.(\"data-reactive-filter-input\") &&\n c.root.getAttribute?.(\"data-reactive-filter-option\")\n )\n}\n\n// Whether a delegated input event came from the NAMED filter input (issue\n// #163). Anything else — another field's keystroke, a target without\n// matches() — skips the filter pass (the morph re-sync path bypasses this).\nfunction filterInputEvent(c, event) {\n const selector = c.root.getAttribute(\"data-reactive-filter-input\")\n return !!selector && typeof event.target?.matches === \"function\" && event.target.matches(selector)\n}\n\n// The characters a word_start query may follow (issue #425): whitespace and\n// - ' ( ) , . /, so \"ivo\" finds Côte d'Ivoire and \"bis\" Guinea-Bissau.\nconst FILTER_WORD_BREAK = /[\\s\\-'(),./]/\n\n// Whether a normalized haystack keeps its option for a normalized, non-empty\n// query (issue #425): \"prefix\" at its start, \"word_start\" at its start or\n// right after a FILTER_WORD_BREAK, anything else (the default \"substring\", or\n// a mode this client does not know) anywhere in it.\nfunction filterMatches(mode, haystack, query) {\n if (mode === \"prefix\") return haystack.startsWith(query)\n if (mode !== \"word_start\") return haystack.includes(query)\n for (let i = haystack.indexOf(query); i !== -1; i = haystack.indexOf(query, i + 1)) {\n if (i === 0 || FILTER_WORD_BREAK.test(haystack[i - 1])) return true\n }\n return false\n}\n\n// Re-apply the filter in one pass (issue #163): lowercase the named input's\n// current value, toggle `hidden` on every OWNED option by matching it against\n// its haystack (data-reactive-filter-text, falling back to the option's own\n// text) in the root's data-reactive-filter-match mode (issue #425; substring\n// when absent), with diacritics folded on both sides under\n// data-reactive-filter-fold, collapse any group whose every contained option\n// is hidden, and reveal the empty target at 0 visible. A filtered-out option\n// also loses its listnav highlight so Enter can never pick an invisible row.\n// No owned input → leave visibility ALONE — a binding that can't resolve\n// must never break or blank the page (client-side default-deny). All\n// selectors resolve within this root, skipping nested reactive roots'\n// elements (issue #15 ownership; the predicate is hoisted once per pass).\nfunction syncFilter(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return\n const inputSelector = c.root.getAttribute(\"data-reactive-filter-input\")\n const optionSelector = c.root.getAttribute(\"data-reactive-filter-option\")\n if (!inputSelector || !optionSelector) return\n\n const owns = c.core.ownership()\n const input = [...c.root.querySelectorAll(inputSelector)].find(owns)\n if (!input) return\n\n const mode = c.root.getAttribute(\"data-reactive-filter-match\")\n const fold = c.root.hasAttribute?.(\"data-reactive-filter-fold\")\n // Both sides go through the same normalization: lowercased and trimmed\n // (markup indentation in a textContent haystack must not defeat a prefix),\n // then, under fold, decomposed with the combining marks stripped — so\n // \"zur\" and \"zür\" both find Zürich.\n const norm = (s) => {\n const text = (s ?? \"\").toLowerCase().trim()\n return fold ? text.normalize(\"NFD\").replace(/\\p{M}/gu, \"\") : text\n }\n const query = norm(input.value)\n let visible = 0\n for (const el of c.root.querySelectorAll(optionSelector)) {\n if (!owns(el)) continue // a nested root's option is its own controller's job\n // An option whose tag is already selected (reactive_tags, issue #203)\n // stays hidden through every re-filter — clearing the query must not\n // resurface an already-added tag.\n const hidden =\n el.hasAttribute?.(\"data-reactive-tags-selected\") ||\n (query !== \"\" &&\n !filterMatches(mode, norm(el.getAttribute(\"data-reactive-filter-text\") ?? el.textContent), query))\n el.hidden = hidden\n if (hidden) el.removeAttribute(\"data-reactive-highlighted\")\n else visible++\n }\n\n const groupSelector = c.root.getAttribute(\"data-reactive-filter-group\")\n if (groupSelector) {\n for (const group of c.root.querySelectorAll(groupSelector)) {\n if (!owns(group)) continue\n const contained = [...group.querySelectorAll(optionSelector)].filter(owns)\n // A group with no options isn't this filter's to decide — server state\n // stands (it may be a header the app toggles by other means).\n if (contained.length === 0) continue\n group.hidden = contained.every((el) => el.hidden)\n }\n }\n\n const emptySelector = c.root.getAttribute(\"data-reactive-filter-empty\")\n if (emptySelector) {\n for (const el of c.root.querySelectorAll(emptySelector)) {\n if (owns(el)) el.hidden = visible > 0\n }\n }\n}\n\n// Whether this root declares a tag-chip binding (issue #203) — the connect()\n// gate and every tags action's first check (an action bound without the root\n// binding is default-denied, the filter posture).\nfunction tagsEnabled(c) {\n return !!c.root.getAttribute?.(\"data-reactive-tags-field\")\n}\n\n// Whether this root owns at least one JSON-mode nested list (issue #208) —\n// the connect() gate. A cheap descendant probe: a form without one wires no\n// input/change listeners. Ownership is re-checked per sync, so a stray match\n// in a nested reactive root here is harmless (it just arms the listeners).\nfunction nestedJsonEnabled(c) {\n if (typeof c.root?.querySelector !== \"function\") return false\n return !!c.root.querySelector(\"[data-reactive-nested-json]\")\n}\n\n// The hidden input storing the comma-joined value, resolved fresh per use\n// (a morph replaces nodes — never cache it) and OWNED by this root (issue\n// #15). null when the selector resolves nothing — every caller then no-ops:\n// a binding that can't resolve must never break the page.\nfunction tagsField(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return null\n const selector = c.root.getAttribute(\"data-reactive-tags-field\")\n if (!selector) return null\n const owns = c.core.ownership()\n return [...c.root.querySelectorAll(selector)].find(owns) ?? null\n}\n\n// Parse the field's comma-joined value into the canonical tag list: split,\n// trim, drop blanks, dedupe case-insensitively KEEPING the first casing (the\n// server may have stored a ragged value — the projection normalizes without\n// rewriting the field, so we never fight server truth).\nfunction tagsRead(field) {\n const seen = new Set()\n const tags = []\n for (const part of String(field.value ?? \"\").split(\",\")) {\n const tag = part.trim()\n if (tag === \"\" || seen.has(tag.toLowerCase())) continue\n seen.add(tag.toLowerCase())\n tags.push(tag)\n }\n return tags\n}\n\n// Append any NEW tags (trimmed, non-blank, not already present under the\n// case-insensitive dedupe) and write the field once. Returns whether\n// anything was actually added — callers only clear the query input then.\nfunction tagsAddValues(c, values) {\n const field = tagsField(c)\n if (!field) return false\n\n const tags = tagsRead(field)\n const seen = new Set(tags.map((tag) => tag.toLowerCase()))\n let added = false\n for (const value of values) {\n const tag = String(value ?? \"\").trim()\n if (tag === \"\" || seen.has(tag.toLowerCase())) continue\n seen.add(tag.toLowerCase())\n tags.push(tag)\n added = true\n }\n if (added) tagsWrite(c, field, tags)\n return added\n}\n\n// The ONE writer: join, store, dispatch a real bubbling `input` on the field\n// (the set-value + dispatch contract, issue #183 — dirty tracking,\n// reactive_show, and compute all see the change), then re-project.\nfunction tagsWrite(c, field, tags) {\n field.value = tags.join(\",\")\n fireInput(field)\n syncTags(c)\n}\n\n// The query input the tags widget resets after a pick — the SAME input that\n// drives reactive_filter (a tags widget without filtering has none; the\n// caller then skips the reset).\nfunction tagsQueryInput(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return null\n const selector = c.root.getAttribute(\"data-reactive-filter-input\")\n if (!selector) return null\n const owns = c.core.ownership()\n return [...c.root.querySelectorAll(selector)].find(owns) ?? null\n}\n\n// Re-project the hidden field into the DOM (issue #203): rebuild the chip\n// list from the <template> and mark/hide the options whose tag is already\n// selected. The field is the single source of truth — this never writes it.\nfunction syncTags(c) {\n const field = tagsField(c)\n if (!field) return\n const tags = tagsRead(field)\n const owns = c.core.ownership()\n tagsRenderChips(c, tags, owns)\n tagsMarkOptions(c, tags, owns)\n}\n\n// Rebuild the chip list: clear the container and clone one chip per tag from\n// the server-owned template. The tag lands in the clone's\n// [data-reactive-tag-text] node via textContent (XSS-safe by construction —\n// never innerHTML, the reactive_text posture), and every tagsRemove trigger\n// in the clone gets the tag as its param. A missing list is a chip-less\n// widget (fine — the value still maintains); a missing/empty template warns\n// ONCE (a half-built binding should be loud, but never per-keystroke).\nfunction tagsRenderChips(c, tags, owns) {\n const list = [...c.root.querySelectorAll(\"[data-reactive-tags-list]\")].find(owns)\n if (!list) return\n\n const template = [...c.root.querySelectorAll(\"[data-reactive-tags-template]\")].find(owns)\n const chipProto = template?.content?.firstElementChild\n if (!chipProto) {\n if (!c.tagsWarnedTemplate) {\n console.warn(\n \"[phlex-reactive] reactive_tags: no chip <template data-reactive-tags-template> found in this root — \" +\n \"chips will not render (the hidden field still updates). Add a template with a \" +\n \"[data-reactive-tag-text] node and a reactive_tags_remove button.\"\n )\n c.tagsWarnedTemplate = true\n }\n return\n }\n\n while (list.firstChild) list.removeChild(list.firstChild)\n for (const tag of tags) {\n const chip = chipProto.cloneNode(true)\n chip.setAttribute?.(\"data-reactive-tag\", tag)\n const sink = chip.matches?.(\"[data-reactive-tag-text]\")\n ? chip\n : (chip.querySelectorAll?.(\"[data-reactive-tag-text]\") ?? [])[0]\n if (sink) sink.textContent = tag\n const removers = [...(chip.querySelectorAll?.('[data-action*=\"reactive#tagsRemove\"]') ?? [])]\n if (chip.matches?.('[data-action*=\"reactive#tagsRemove\"]')) removers.push(chip)\n for (const remover of removers) remover.setAttribute?.(\"data-reactive-tag-param\", tag)\n list.appendChild(chip)\n }\n}\n\n// Hide + mark every owned option whose DECLARED tag is already selected\n// (data-reactive-tags-selected — #syncFilter keeps it hidden through\n// re-filters), and resurface an option WE hid when its tag is removed. Only\n// marker-carrying options are un-hidden — an option hidden by the filter or\n// the server stays as-is. With a filter bound, one final #syncFilter re-folds\n// groups/empty against the new selected set.\nfunction tagsMarkOptions(c, tags, owns) {\n const selected = new Set(tags.map((tag) => tag.toLowerCase()))\n for (const el of c.root.querySelectorAll(\"[role=option]\")) {\n if (!owns(el)) continue\n const tag = el.getAttribute?.(\"data-reactive-tag-param\")\n if (!tag) continue\n if (selected.has(tag.toLowerCase())) {\n el.setAttribute(\"data-reactive-tags-selected\", \"true\")\n el.hidden = true\n el.removeAttribute?.(\"data-reactive-highlighted\")\n } else if (el.hasAttribute?.(\"data-reactive-tags-selected\")) {\n el.removeAttribute(\"data-reactive-tags-selected\")\n if (!filterEnabled(c)) el.hidden = false\n }\n }\n if (filterEnabled(c)) syncFilter(c)\n}\n\n// A fresh index per nested-row add (issue #208) — strictly monotonic and\n// clock-seeded, so it can never collide with server-rendered integer indexes\n// (0..n) NOR with a rapid same-millisecond double add.\nfunction nextNestedIndex(c) {\n c.nestedIndex = Math.max(c.nestedIndex + 1, Date.now())\n return c.nestedIndex\n}\n\n// Swap every NEW_ROW in the clone's name/id/for for the fresh index, so the\n// row posts as its own `…_attributes[<index>][field]` group and labels keep\n// pointing at their (renumbered) inputs.\nfunction renumberNestedRow(row, index) {\n const nodes = [row, ...(row.querySelectorAll?.(\"*\") ?? [])]\n for (const el of nodes) {\n for (const attr of [\"name\", \"id\", \"for\"]) {\n const value = el.getAttribute?.(attr)\n if (value && value.includes(\"NEW_ROW\")) el.setAttribute?.(attr, value.replaceAll(\"NEW_ROW\", String(index)))\n }\n }\n}\n\n// A half-built nested-rows binding should be loud, but never per-click.\nfunction warnNestedOnce(c, assoc) {\n if (c.nestedWarned) return\n console.warn(\n `[phlex-reactive] nested rows: no owned [data-reactive-nested-list=\"${assoc}\"] container + ` +\n `<template data-reactive-nested-template=\"${assoc}\"> pair found in this root — the add ` +\n \"trigger did nothing. Render both inside the same reactive root (reactive_nested_list / \" +\n \"reactive_nested_template).\"\n )\n c.nestedWarned = true\n}\n\n// Fill-then-add (issue #208): copy each source control's value into the\n// matching cloned-row field, keyed by the trailing bracket segment of the\n// field's name (#nestedJsonKey — the SAME inference JSON mode uses, so the\n// two features can't drift). Sources resolve root-scoped and owned (#15); an\n// unresolved source or an unmatched key is silently skipped (the row still\n// adds — a half-mapped binding must never throw on click). Returns the FIRST\n// source control read (for focus), or null. With `clear`, resets every source\n// it read via the set-value + dispatch contract (#183) so dirty/show/compute\n// observe the reset.\nfunction seedNestedRow(c, row, fromJson, clear) {\n if (!fromJson) return null\n let map\n try {\n map = JSON.parse(fromJson)\n } catch {\n return null\n }\n if (!map || typeof map !== \"object\") return null\n\n const owns = c.core.ownership()\n const rowFields = [...(row.querySelectorAll?.(\"input, select, textarea\") ?? [])]\n const sources = []\n for (const [key, selector] of Object.entries(map)) {\n const source = [...(c.root.querySelectorAll?.(selector) ?? [])].find(owns)\n if (!source) continue\n const target = rowFields.find((field) => nestedJsonKey(field.getAttribute?.(\"name\")) === key)\n if (!target) continue\n seedNestedField(target, source)\n sources.push(source)\n }\n if (clear) for (const source of sources) clearNestedSource(source)\n return sources[0] ?? null\n}\n\n// Copy a source control's value into a cloned-row field, then dispatch a\n// bubbling `input` (the set-value + dispatch contract, #183). Checkbox ↔\n// checkbox copies the checked state; every other target takes the source's\n// submit-shaped value (#nestedFieldValue), so a checkbox source feeding a\n// text field lands \"on\"/\"\" exactly as a submit would.\nfunction seedNestedField(target, source) {\n if (target.type === \"checkbox\") {\n target.checked = source.type === \"checkbox\" ? !!source.checked : nestedFieldValue(source) !== \"\"\n } else {\n target.value = nestedFieldValue(source)\n }\n fireInput(target)\n}\n\n// Reset a source control after a fill-then-add (issue #208), dispatching a\n// bubbling `input` so dirty tracking / reactive_show / compute see the reset.\nfunction clearNestedSource(source) {\n if (source.type === \"checkbox\") source.checked = false\n else source.value = \"\"\n fireInput(source)\n}\n\n// Resolve %{field} placeholders in a confirm message from a row's field map\n// (issue #222). Ruby-style %{name} tokens; an unresolved key is left verbatim\n// (a visible, debuggable placeholder — never an empty hole or a throw). A\n// message with no placeholders returns unchanged, so this is inert for every\n// server-rendered (already-interpolated) confirm string.\nfunction interpolateConfirm(message, fields) {\n if (!message.includes(\"%{\")) return message\n return message.replace(/%\\{(\\w+)\\}/g, (whole, key) =>\n Object.prototype.hasOwnProperty.call(fields, key) ? fields[key] : whole,\n )\n}\n\n// The remove itself, shared by the confirmed and no-confirm paths. Draft rows\n// leave the DOM; a persisted row (a hidden [_destroy] input present) is marked\n// \"1\" + hidden instead (set-value + dispatch contract, #183), so Rails destroys\n// it on save. Then re-sync every owned JSON-mode list (#208) — an absent row\n// IS the removal; a form without a JSON list iterates an empty set and exits.\nfunction removeNestedRow(c, row) {\n const destroy = [...(row.querySelectorAll?.('input[name$=\"[_destroy]\"]') ?? [])][0]\n if (destroy) {\n destroy.value = \"1\"\n fireInput(destroy)\n row.hidden = true\n } else {\n row.parentNode?.removeChild?.(row)\n }\n\n syncAllNestedJson(c)\n}\n\n// Serialize every owned JSON-mode list into its hidden field. The connect\n// seed and the input/remove re-syncs funnel through here so one place owns\n// the \"DOM rows → JSON field\" projection.\nfunction syncAllNestedJson(c) {\n if (typeof c.root?.querySelectorAll !== \"function\") return\n const owns = c.core.ownership()\n for (const list of [...c.root.querySelectorAll(\"[data-reactive-nested-json]\")].filter(owns)) {\n syncNestedJsonList(c, list.getAttribute(\"data-reactive-nested-json\"))\n }\n}\n\n// The hidden field a JSON-mode list mirrors into — resolved fresh (a morph\n// replaces nodes, never cache it) and OWNED by this root (#15). null when\n// the selector resolves nothing, so the caller no-ops (a half-built binding\n// must never break the page).\nfunction nestedJsonField(c, list) {\n const selector = list.getAttribute?.(\"data-reactive-nested-json-field\")\n if (!selector) return null\n const owns = c.core.ownership()\n return [...c.root.querySelectorAll(selector)].find(owns) ?? null\n}\n\n// One row → { key: value } over its named form controls. The JSON key is the\n// trailing bracket segment of each control's name (order[todos_attributes]\n// [3][title] → \"title\"; a bare `title` → \"title\"), the \"infer from input\n// names\" contract. The [_destroy] control is dropped (JSON has no destroy\n// marker). Later inputs with the same key win (last-wins, the DOM order).\n// Like a real submit (#299): an unchecked radio, a disabled control (its own\n// flag or a <fieldset disabled> ancestor: :disabled) and a nested reactive\n// root's control are skipped.\nfunction nestedRowObject(c, row) {\n const obj = {}\n const owns = c.core.ownership()\n for (const el of [...(row.querySelectorAll?.(\"input, select, textarea\") ?? [])]) {\n if (el.matches(\":disabled\") || (el.type === \"radio\" && !el.checked) || !owns(el)) continue\n const key = nestedJsonKey(el.getAttribute?.(\"name\"))\n if (key === null || key === \"_destroy\") continue\n obj[key] = nestedFieldValue(el)\n }\n return obj\n}\n\n// The trailing bracket segment of a field name (the inferred JSON key), or\n// the bare name when it carries no brackets. null for a nameless control\n// (a bare button, an unnamed helper input) — skipped by the caller.\nfunction nestedJsonKey(name) {\n if (!name) return null\n const match = name.match(/\\[([^\\][]+)\\]$/)\n return match ? match[1] : name\n}\n\n// A form control's submitted value: an unchecked checkbox contributes \"\" (it\n// wouldn't post at all), a checked one its value (default \"on\"); everything\n// else its .value. Keeps the JSON shape close to what a real form submit\n// would carry for the same control.\nfunction nestedFieldValue(el) {\n if (el.type === \"checkbox\") return el.checked ? (el.value || \"on\") : \"\"\n return el.value ?? \"\"\n}\n\n// Project ONE JSON-mode list's surviving rows into its hidden field. Each\n// row becomes an object keyed by the trailing bracket segment of its inputs'\n// names (…[title] → \"title\"); a hidden/_destroy-marked row is skipped (an\n// absent row IS the removal — JSON carries no destroy marker). The write\n// uses the set-value + dispatch contract (issue #183) so dirty tracking,\n// reactive_show, and compute see the change — but only when the value\n// actually changed, so a connect seed on an already-correct field is silent.\nfunction syncNestedJsonList(c, assoc) {\n const owns = c.core.ownership()\n const list = [...c.root.querySelectorAll(`[data-reactive-nested-list=\"${assoc}\"]`)].find(owns)\n if (!list) return\n const field = nestedJsonField(c, list)\n if (!field) return\n\n const rows = []\n for (const row of [...(list.querySelectorAll?.(\"[data-reactive-nested-row]\") ?? [])]) {\n if (!owns(row) || row.hidden) continue\n rows.push(nestedRowObject(c, row))\n }\n\n const next = JSON.stringify(rows)\n if (field.value === next) return\n field.value = next\n fireInput(field)\n}\n\n// Tag-chip input (issue #203) — the composed combobox/tags primitive. The\n// root's data-reactive-tags-field names the hidden input that stores the\n// COMMA-JOINED value; these three actions are its only writers. All of it is\n// FORM state (like text in an input) — no token, no POST: the surrounding\n// form submit carries the joined value. The chip list is re-projected from\n// the field on every write (#syncTags), so the field stays the single source\n// of truth.\n//\n// Enter on the query input: add the TYPED text — unless this Enter belongs\n// to listnav (reactive_tags_add composes after reactive_listnav on the same\n// keydown.enter). Two guards make the composition order-independent:\n// defaultPrevented means listnavPick ALREADY picked the highlighted option\n// (adding the typed text too would double-add); a still-visible highlighted\n// option means listnavPick is ABOUT to pick it (when tagsAdd is bound\n// first). Past the guards, Enter is OURS — preventDefault unconditionally so\n// it can never submit the enclosing form (blank input included). A\n// comma-separated paste splits into individual tags (the value is\n// comma-joined, so a comma can never be part of one tag). The input clears\n// only when something was actually added — a duplicate keeps the typed text\n// for correction.\nexport function tagsAdd(controller, core, event) {\n const c = ctx(controller, core)\n if (!tagsEnabled(c)) return\n if (event?.defaultPrevented) return\n if (c.core.listnavOptions(event).some((el) => el.hasAttribute?.(\"data-reactive-highlighted\"))) return\n event?.preventDefault?.()\n\n const input = event?.currentTarget ?? event?.target\n if (!input) return\n const added = tagsAddValues(c, String(input.value ?? \"\").split(\",\"))\n if (!added) return\n input.value = \"\"\n if (filterEnabled(c)) syncFilter(c)\n}\n\n// Click (or listnav Enter, which CLICKS the highlighted option) on a\n// preloaded option: add its DECLARED tag (data-reactive-tag-param — set by\n// reactive_tags_option, never free text). After a successful add, reset the\n// query so the next tag starts from the full list: clear the filter input,\n// re-narrow, and hand focus back for continued typing.\nexport function tagsPick(controller, core, event) {\n const c = ctx(controller, core)\n if (!tagsEnabled(c)) return\n event?.preventDefault?.()\n\n const trigger = event?.currentTarget ?? event?.target\n const tag = trigger?.getAttribute?.(\"data-reactive-tag-param\")\n if (!tag) return\n if (!tagsAddValues(c, [tag])) return\n\n const input = tagsQueryInput(c)\n if (!input) return\n input.value = \"\"\n syncFilter(c)\n input.focus?.()\n}\n\n// Click on a chip's remove button: drop its tag (case-insensitive match, the\n// dedupe convention) from the hidden value. The re-projection removes the\n// chip and resurfaces the option. Removing an absent tag is a no-op.\nexport function tagsRemove(controller, core, event) {\n const c = ctx(controller, core)\n if (!tagsEnabled(c)) return\n event?.preventDefault?.()\n\n const trigger = event?.currentTarget ?? event?.target\n const tag = trigger?.getAttribute?.(\"data-reactive-tag-param\")\n if (!tag) return\n const field = tagsField(c)\n if (!field) return\n\n const tags = tagsRead(field)\n const next = tags.filter((t) => t.toLowerCase() !== tag.toLowerCase())\n if (next.length === tags.length) return\n tagsWrite(c, field, next)\n}\n\n// Draft nested-attribute rows (issue #208) — the \"new parent + child rows\"\n// window. The rows are FORM state (the reactive_tags posture): no token, no\n// POST, ever — the surrounding REAL form submit carries Rails'\n// accepts_nested_attributes_for names and the server reconciles parent +\n// rows in ONE create. Add clones the association's server-owned\n// <template data-reactive-nested-template=\"assoc\"> row, swaps every NEW_ROW\n// in the clone's name/id/for for a fresh unique index (each row posts as its\n// own `…_attributes[<index>][field]` group), appends it to the owned\n// [data-reactive-nested-list=\"assoc\"] container, and focuses the new row's\n// first field. Several collections can share one root — everything is keyed\n// by the association name the trigger carries.\nexport function nestedAdd(controller, core, event) {\n const c = ctx(controller, core)\n event?.preventDefault?.()\n const trigger = event?.currentTarget ?? event?.target\n const assoc = trigger?.getAttribute?.(\"data-reactive-association-param\")\n if (!assoc) return\n if (typeof c.root?.querySelectorAll !== \"function\") return\n\n const owns = c.core.ownership()\n const list = [...c.root.querySelectorAll(`[data-reactive-nested-list=\"${assoc}\"]`)].find(owns)\n const template = [...c.root.querySelectorAll(`[data-reactive-nested-template=\"${assoc}\"]`)].find(owns)\n const proto = template?.content?.firstElementChild\n if (!list || !proto) {\n warnNestedOnce(c, assoc)\n return\n }\n\n const row = proto.cloneNode(true)\n renumberNestedRow(row, nextNestedIndex(c))\n list.appendChild(row)\n\n // Fill-then-add (issue #208 Scenario A): seed the cloned row from named\n // source controls OUTSIDE the row, then (optionally) clear the sources.\n // Runs AFTER renumber+append so a seeded field's name already carries its\n // final `[<index>][field]` form — the key match agrees with what JSON mode\n // reads. `seeded` is the FIRST source we cleared/read, so fill-then-add can\n // return focus to the sources instead of stealing it into the new row.\n const fromJson = trigger?.getAttribute?.(\"data-reactive-nested-from-param\")\n const clear = trigger?.getAttribute?.(\"data-reactive-nested-clear-param\") === \"true\"\n const firstSource = seedNestedRow(c, row, fromJson, clear)\n\n // Focus: inline-edit (no from:) focuses the new row's first field so you\n // type INTO it; fill-then-add keeps focus on the sources (the first one) so\n // you keep entering the next item — stealing focus would break that loop.\n if (fromJson) firstSource?.focus?.()\n else [...(row.querySelectorAll?.(\"input, select, textarea\") ?? [])][0]?.focus?.()\n\n // JSON mode (issue #208): a freshly-added row must land in the hidden field\n // immediately (seeded values included), so the serialized array reflects the\n // DOM even before the first keystroke. A no-op when not `as: :json`.\n if (list.getAttribute?.(\"data-reactive-nested-json\") === assoc) syncNestedJsonList(c, assoc)\n}\n\n// Remove the trigger's closest row wrapper. A DRAFT row (no [_destroy]\n// input) leaves the DOM — it was never persisted, so removing its fields IS\n// the removal. A PERSISTED row (an edit form rendered a hidden [_destroy]\n// input via nested_field_name) is marked \"1\" and hidden instead — Rails\n// destroys it on save. The mark dispatches a real bubbling `input` (the\n// set-value + dispatch contract, issue #183) so dirty tracking/compute see it.\nexport function nestedRemove(controller, core, event) {\n const c = ctx(controller, core)\n event?.preventDefault?.()\n const trigger = event?.currentTarget ?? event?.target\n const row = trigger?.closest?.(\"[data-reactive-nested-row]\")\n if (!row) return\n // The closest() walk must not escape this root — a root can itself sit\n // inside ANOTHER collection's row (the issue #15 closest-form posture).\n if (row.closest?.('[data-controller~=\"reactive\"]') !== c.root) return\n\n // Confirm gate (issue #218): reactive_nested_remove(confirm:) emits the SAME\n // data-reactive-confirm[-when]-param the other triggers do (nestedRemove reads\n // params via getAttribute, not event.params, so pull them off the trigger),\n // routed through the SAME #effectiveConfirmMessage + confirmResolver seam. A\n // static string always shows; a conditional Hash fires only when it matches,\n // else null. No confirm attr → null → the immediate-remove fast path.\n const confirm = trigger?.getAttribute?.(\"data-reactive-confirm-param\")\n const confirmWhen = trigger?.getAttribute?.(\"data-reactive-confirm-when-param\")\n const rawMessage = confirm || (confirmWhen ? conditionalConfirmMessage(c, confirmWhen) : null)\n if (!rawMessage) return removeNestedRow(c, row)\n\n // Per-row confirm interpolation (issue #222). A row added client-side is a\n // cloneNode of the <template>, and the clone carries the TEMPLATE's confirm\n // string verbatim — the renumber/seed steps never rewrite the confirm attr.\n // So resolve %{field} placeholders here, from THIS row's live field values\n // (read now, not at clone time, so a later edit is reflected). An unresolved\n // key is left as its literal %{key} (debuggable, never throws). Server-\n // rendered rows already interpolate server-side, so their finished strings\n // carry no %{}; this is a no-op for them.\n const fields = nestedRowObject(c, row)\n const message = interpolateConfirm(rawMessage, fields)\n\n // Gate through the overridable confirmResolver (issues #52/#55/#178) — a\n // themed dialog set with setConfirmResolver covers this trigger too. Pass the\n // row context (issue #222, superset of proposal 3) as an optional 2nd arg so\n // a power-user override can build the string itself; the message is already\n // interpolated for the default window.confirm path. Call the resolver INSIDE\n // the chain so even a SYNCHRONOUS override throw is a cancel (like a dismissed\n // dialog), and remove ONLY on a truthy resolution.\n return c.core.confirm(message, { el: trigger, row, fields }).then((ok) => {\n if (ok) removeNestedRow(c, row)\n })\n}\n\n// JSON-mode nested rows (issue #208) — the delegated input/change handler.\n// An app whose controller parses a serialized JSON param instead of Rails'\n// accepts_nested_attributes_for opts a list into `as: :json`; the client\n// then mirrors that list's rows into ONE hidden field as a JSON array on\n// every owned edit. Public so Stimulus can bind it; a no-op unless the\n// edited field belongs to a JSON-mode list this root owns.\nfunction syncNestedJson(c, event) {\n const target = event?.target\n if (!target || !c.core.owns(target)) return\n // Re-serialize every JSON-mode list (an edit could touch any of them; the\n // per-list owned-row scan is cheap and keeps this handler association-free).\n syncAllNestedJson(c)\n}\n\n// The numeric threshold keys (issue #176 part B) — the client half of the Ruby\n// SHOW_NUMERIC_KEYS. Order-independent; the evaluator reads the one that's\n// present. Each coerces BOTH sides to Number and compares.\nconst SHOW_NUMERIC_KEYS = [\"gte\", \"gt\", \"lte\", \"lt\"]\n\n// The length predicate keys (issue #226) — the client half of Ruby's\n// ShowConditions::LENGTH_KEYS. Length is counted in CODEPOINTS\n// ([...str].length), NOT UTF-16 code units (str.length), so Ruby's\n// String#length and this evaluator agree on multibyte values — the shared\n// fixture's emoji vector proves it.\nconst SHOW_LENGTH_KEYS = [\"len_eq\", \"len_gte\", \"len_gt\", \"len_lte\", \"len_lt\"]\n\n// The checked-count keys (issue #319) — the client half of Ruby's\n// ShowConditions::CHECKED_KEYS: how many owned boxes of a group are ticked.\nconst SHOW_CHECKED_KEYS = [\"checked_eq\", \"checked_gte\", \"checked_gt\", \"checked_lte\", \"checked_lt\"]\n\n// The digit-count keys (issue #396) — Ruby's CompareTerms::DIGITS_KEYS.\nconst SHOW_DIGITS_KEYS = [\"digits_eq\", \"digits_gte\", \"digits_lt\", \"digits_lte\"]\n\n// Evaluate one count predicate (len_* or checked_*). A count is a TOTAL\n// function (blank/absent → 0), so every field value is decidable — no\n// fail-closed special case like the numeric thresholds ({ length: 0 }\n// legitimately matches a blank field). A non-Integer LITERAL is a malformed\n// binding — warn-skip (null), default-deny.\nfunction countPredicateMatches(key, literal, count) {\n if (!Number.isInteger(literal)) {\n console.warn(`[phlex-reactive] reactive_show ${key}: needs an integer literal, got ${JSON.stringify(literal)} — skipped`)\n return null\n }\n switch (key.slice(key.indexOf(\"_\") + 1)) {\n case \"eq\":\n return count === literal\n case \"gte\":\n return count >= literal\n case \"gt\":\n return count > literal\n case \"lte\":\n return count <= literal\n case \"lt\":\n return count < literal\n default:\n return null\n }\n}\n\n// Evaluate one numeric threshold predicate against a field value. Returns\n// true/false for a decidable comparison, or null when the LITERAL itself is\n// non-numeric (a malformed binding — warn-skip, default-deny). A non-numeric\n// FIELD value (empty/blank/garbage) is treated as NaN → false: the\n// reveal-on-threshold notice stays hidden, the safe default. Shared by the\n// owned-binding evaluator (raw string literal off an attr) and the\n// cross-root/compound evaluator (a literal that arrived as a JSON number or\n// string).\nfunction numericPredicateMatches(key, literal, value) {\n const rhs = Number(literal)\n if (Number.isNaN(rhs)) {\n console.warn(`[phlex-reactive] reactive_show ${key}: needs a numeric literal, got ${JSON.stringify(literal)} — skipped`)\n return null\n }\n // A blank/whitespace field value must fail closed. Number(\"\") and\n // Number(\" \") are 0 (NOT NaN), so a bare Number()+isNaN check would wrongly\n // reveal a `lte:`/`lt:`/`gte: 0` binding on an EMPTY field. Force the\n // empty/blank case to NaN so the \"blank → hidden\" contract holds for every\n // operator, not just the ones where 0 happens to fail the comparison.\n const trimmed = value == null ? \"\" : String(value).trim()\n const n = trimmed === \"\" ? NaN : Number(trimmed)\n if (Number.isNaN(n)) return false\n switch (key) {\n case \"gte\":\n return n >= rhs\n case \"gt\":\n return n > rhs\n case \"lte\":\n return n <= rhs\n case \"lt\":\n return n < rhs\n default:\n return null\n }\n}\n\n// Evaluate an ALREADY-PARSED show predicate object (issue #164) — the\n// reactive_show_targets map embeds { equals/not/in } directly in its JSON, so\n// unlike showBindingMatches there are no attrs to read or re-parse. The same\n// literal-only vocabulary; anything else (empty, unknown keys, a non-array\n// in:) returns null and the caller warn-skips that target (default-deny — a\n// hand-built map entry must never flip visibility it doesn't declare).\nfunction showPredicateMatches(pred, value) {\n if (!pred || typeof pred !== \"object\") return null\n if (typeof pred.equals === \"string\") return value === pred.equals\n if (typeof pred.not === \"string\") return value !== pred.not\n if (Array.isArray(pred.in)) return pred.in.includes(value)\n // Numeric threshold predicates (issue #176 part B): the literal arrives as a\n // JSON number (or a numeric string) embedded in the predicate object — one\n // shared numericPredicateMatches with the owned-binding evaluator.\n for (const key of SHOW_NUMERIC_KEYS) {\n if (key in pred) return numericPredicateMatches(key, pred[key], value)\n }\n // Length predicates (issue #226): codepoint count vs an Integer literal.\n for (const key of SHOW_LENGTH_KEYS) {\n if (key in pred) return countPredicateMatches(key, pred[key], [...String(value ?? \"\")].length)\n }\n return null\n}\n\n// Evaluate one DNF TERM against a resolved field value (issue #180). A missing\n// field (null) or a malformed/unknown predicate folds to FALSE — fail-closed\n// (default-deny): a broken AND term can't pass, a broken OR term can't reveal.\nfunction dnfTermMatches(term, fieldValue) {\n if (!term || typeof term !== \"object\" || typeof term.field !== \"string\") return false\n // A checked_* term (issue #319) counts the group's ticked boxes: the\n // resolver's count form, or — from collected fields (a conditional confirm)\n // — the group's array of checked values (a lone box's true/false is 1/0).\n const checked = SHOW_CHECKED_KEYS.find((key) => key in term)\n if (checked) {\n const n = fieldValue(term.field, true)\n return countPredicateMatches(checked, term[checked], Array.isArray(n) ? n.length : Number(n) || 0) === true\n }\n // A same: term (issue #395) compares this field with ANOTHER owned field,\n // both as strings (an absent one is \"\"); fold lowercases ASCII A-Z only, the\n // exact replace Ruby's tr(\"A-Z\", \"a-z\") does. negate is unless:'s flip.\n if (typeof term.same === \"string\") {\n const read = (name) => {\n const v = String(fieldValue(name) ?? \"\")\n return term.fold === true ? v.replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32)) : v\n }\n return (read(term.field) === read(term.same)) !== (term.negate === true)\n }\n // A digits: term (issue #396): ASCII digits only, the count within every\n // digits_* bound, and the optional prefix; negate flips it. A malformed\n // literal is false either way (fail-closed, like Ruby).\n const digits = SHOW_DIGITS_KEYS.filter((key) => key in term)\n if (digits.length) {\n const v = String(fieldValue(term.field) ?? \"\")\n if (!digits.every((key) => Number.isInteger(term[key])) || (term.prefix != null && typeof term.prefix !== \"string\")) return false\n const ok = /^[0-9]*$/.test(v) && digits.every((key) => countPredicateMatches(key, term[key], v.length)) && v.startsWith(term.prefix ?? \"\")\n return ok !== (term.negate === true)\n }\n // An absent owned field reads as \"\" — identical to the server evaluator\n // (ShowConditions.match? treats a missing field as blank). This keeps the\n // Ruby first-paint and the client live-toggle in exact agreement (the shared\n // fixture proves it). A malformed predicate still folds to false.\n const value = fieldValue(term.field) ?? \"\"\n return showPredicateMatches(term, value) === true\n}\n\n// Evaluate a DNF show payload (issue #180): { any: [group, …] } where each\n// GROUP is an array of terms (terms AND within a group, groups OR). Returns\n// true/false for a decidable payload, or null for a malformed one (no groups)\n// so the caller warn-skips and leaves visibility alone. This is the ONE shape\n// the 0.10 wire emits; showPayloadMatches routes the legacy shapes here or to\n// the compatibility arm below.\nfunction anyOfAllsMatches(groups, fieldValue) {\n if (!Array.isArray(groups) || groups.length === 0) return null\n // groups OR; within a group, terms AND (an empty group can't decide → false).\n return groups.some((group) => Array.isArray(group) && group.length > 0 &&\n group.every((term) => dnfTermMatches(term, fieldValue)))\n}\n\n// Every field a DNF payload's groups reference (issue #209) — drives the\n// \"leave the target alone when NO referenced field is owned\" skip, the\n// single-field-target skip generalized. Returns null for a malformed payload\n// (no groups, or no term names a field) so the caller warn-skips instead of\n// toggling on garbage (default-deny, like every other malformed-wire arm).\nfunction dnfGroupFields(groups) {\n if (!Array.isArray(groups) || groups.length === 0) return null\n const fields = new Set()\n for (const group of groups) {\n if (!Array.isArray(group)) continue\n for (const term of group) {\n if (term && typeof term === \"object\" && typeof term.field === \"string\") fields.add(term.field)\n if (typeof term?.same === \"string\") fields.add(term.same)\n }\n }\n return fields.size > 0 ? [...fields] : null\n}\n\n// Whether every term of a DNF payload is a checked_* count (issue #348) —\n// the payload a group with zero owned boxes still decides (count 0).\nfunction countsOnly(groups) {\n return groups.flat().every((term) => SHOW_CHECKED_KEYS.some((key) => key in Object(term)))\n}\n\n// Resolve the effective confirm message (issue #179). A plain string is the\n// static #52 form (always shown). A confirmWhen JSON payload is the CONDITIONAL\n// form — evaluated over the SAME collected fields reactive_compute reads — and\n// returns the message ONLY when it fires, else null (proceed, no dialog):\n// { groups, message } — the reactive_show conditions fold (anyOfAllsMatches)\n// { predicate, message } — a registered fn (setConfirmPredicate) over the fields\n// A missing predicate warns and returns null (PROCEED without a dialog) — the\n// compute unknown-reducer posture. This is soft-validation UX; the endpoint's\n// authorize/default-deny is the real gate, so failing OPEN here never grants\n// anything the server wouldn't already allow.\nfunction conditionalConfirmMessage(c, confirmWhen) {\n\n // Stimulus auto-parses a JSON-object -param value, so confirmWhen usually\n // arrives ALREADY parsed. Accept an object as-is; parse a string defensively\n // (a hand-built attr, or a non-Stimulus caller). A malformed string warns and\n // proceeds without a dialog (default-deny UX — the server is the real gate).\n let payload = confirmWhen\n if (typeof confirmWhen === \"string\") {\n try {\n payload = JSON.parse(confirmWhen)\n } catch {\n console.warn(`[phlex-reactive] malformed conditional confirm payload ${JSON.stringify(confirmWhen)} — skipped`)\n return null\n }\n }\n if (!payload || typeof payload !== \"object\") return null\n\n const { fields } = c.core.collectFields()\n const fieldValue = (name) => fields[name]\n\n let fires\n if (typeof payload.predicate === \"string\") {\n const fn = confirmPredicate(payload.predicate)\n if (!fn) {\n console.warn(`[phlex-reactive] confirm predicate \"${payload.predicate}\" is not registered — proceeding without a dialog (register it with setConfirmPredicate)`)\n return null\n }\n fires = !!fn(fields)\n } else {\n // Declarative: the DNF groups fold, identical to reactive_show — matches → fire.\n fires = anyOfAllsMatches(payload.groups?.any, fieldValue) === true\n }\n\n return fires ? payload.message : null\n}\n\n// --- Editable text (issue #351) ----------------------------------------------\n// reactive_editable renders contenteditable=\"plaintext-only\": the browser\n// itself then pastes plain text and inserts \"\\n\" for Enter. An engine without\n// it reads the value as invalid; the runtime switches every reactive editable\n// to \"true\" there (issue #355), and the paste handler below does the\n// plain-text part.\n\n// The owned editable an event came from, or null — a nested reactive root's\n// editables are its own (#15).\nfunction ownedEditable(c, event) {\n const el = event.target?.closest?.(\"[data-reactive-editable]\")\n return el && c.core.owns(el) ? el : null\n}\n\n// Enter: a single-line field swallows it; on_enter runs its ops (root-scoped,\n// as on_client) or submits the field's form — in a multiline field only a\n// plain Enter, so Shift+Enter still breaks the line. Never while an IME is\n// composing (its Enter commits the composition). Escape with on_escape:\n// :revert restores the last server-rendered text, announces it as an edit\n// (dirty, show, an input-bound save) and blurs.\nfunction editableKey(c, event) {\n const el = ownedEditable(c, event)\n if (!el || event.isComposing || event.keyCode === 229) return\n if (event.key === \"Enter\") {\n const enter = el.getAttribute(\"data-reactive-editable-enter\")\n const multi = el.getAttribute(\"data-reactive-editable\") === \"multi\"\n if (multi && (enter == null || event.shiftKey)) return\n event.preventDefault()\n if (enter === \"submit\") el.closest(\"form\")?.requestSubmit()\n else if (enter) c.core.applyOps(JSON.parse(enter), \"@root\")\n } else if (event.key === \"Escape\" && el.hasAttribute(\"data-reactive-editable-escape\")) {\n event.preventDefault()\n el.textContent = c.core.served(el)\n fireInput(el)\n el.blur()\n }\n}\n\n// Paste and drop insert the clipboard's PLAIN text — handled here where the\n// engine has no plaintext-only, and for a single-line field everywhere (its\n// line breaks fold to spaces). insertText keeps the browser's undo stack. A\n// drop lands at the caret, not under the pointer.\nfunction editablePaste(c, event) {\n const el = ownedEditable(c, event)\n const single = el?.getAttribute(\"data-reactive-editable\") !== \"multi\"\n let text = (event.clipboardData ?? event.dataTransfer)?.getData(\"text/plain\")\n if (!el || text == null || (c.core.plain() && !(single && /[\\r\\n]/.test(text)))) return\n event.preventDefault()\n if (single) text = text.replace(/\\r?\\n|\\r/g, \" \")\n el.focus()\n document.execCommand(\"insertText\", false, text)\n}\n\n// A field the user emptied keeps the <br> browsers leave behind, so\n// :empty::before (the placeholder) would never match: drop it.\nfunction editableEmptied(c, event) {\n const el = ownedEditable(c, event)\n if (el?.firstChild && c.core.text(el) === \"\") el.replaceChildren()\n}\n",
7
7
  "// phlex/reactive/features/compute — client-side computes (data binding,\n// issues #104, #159, #183, #199, #262): `recompute`, the connect-time seed,\n// text mirrors and the reducer's $ops. One of the feature modules the opt-in\n// client imports on demand (issue #275); in the default client it is part of\n// the one file.\n//\n// The reducer registry is the compute seam (phlex/reactive/compute), imported\n// here by its bare name — so the runtime no longer imports it, and a page\n// with no compute binding never resolves it. The seed writes output fields a\n// request collects, so with the opt-in client the feature `gates`: a root's\n// requests wait for it. While the module is on its way, the opt-in entry\n// records that the user edited a field (`pending.edited`), and connect() runs\n// ONE recompute then: the reducer reads the inputs as the user left them, so\n// nothing they typed is overwritten, and a `recompute` the window dispatched\n// has run exactly once when it is over.\n//\n// This module never imports the runtime: it reaches a controller through the\n// `core` handle.\nimport { computeReducer } from \"phlex/reactive/compute\"\n\n// controller -> its context: the root, the core handle, and what used to be\n// the controller's own fields for this feature. Short field names: the\n// minifier never renames a property (issue #310).\n// ours the `input` events recompute dispatched for its OWN output\n// writes (issue #183), so re-entering from one skips the reducer\n// (and ONLY one of ours)\n// opsSig the reducer's last $ops chain (issue #226), the rising-edge latch\n// seed the connect-time seed, when the root opts in\nconst contexts = new WeakMap()\n\nfunction ctx(controller, core) {\n let c = contexts.get(controller)\n if (!c) contexts.set(controller, (c = { root: controller.element, core, ours: new WeakSet(), opsSig: null }))\n return c\n}\n\nexport function connect(controller, core, _morphed, pending) {\n const c = ctx(controller, core)\n // Connect-time compute seed (issue #199) — ONLY when the root carries a\n // reactive_compute binding that opts in (data-reactive-compute-seed). A\n // freshly-rendered compute root (a first paint, or a server validation-error\n // re-render that replaced the body) computed NOTHING until the first user\n // `input`; apps worked around it by dispatching a synthetic seed `input` on\n // connect, but the compute root is a distinct Stimulus controller that may\n // connect a frame later, so the seed raced its own wiring. Running ONE\n // recompute() HERE — after Stimulus has fully connected the controller and\n // wired the input->recompute delegation — runs the whole single-pass write\n // set (issue #183) synchronously, so every declared output, text sink, and\n // cross-root mirror paints from one reducer result. It is client-only\n // (recompute never enqueues a round trip) and idempotent (change-guarded\n // writes make a re-seed a no-op). A plain replace re-connects and re-seeds;\n // an in-place morph keeps the element CONNECTED and fires no Stimulus\n // lifecycle, so ALSO re-seed on turbo:morph-element. No event is passed, so\n // meta.changed is null — the correct \"no field edited yet\" seed semantics; a\n // convergent reducer's default branch computes the full settled set (see\n // compute.js CONVERGENCE REQUIREMENT).\n const seeds = computeSeedEnabled(c)\n if (seeds) {\n c.seed = () => recompute(c)\n c.root.addEventListener?.(\"turbo:morph-element\", c.seed)\n }\n // The one pass a root that waited for this module owes: its seed, or the\n // recompute an edit in the window asked for.\n if (seeds || pending?.edited) recompute(c)\n}\n\nexport function disconnect(controller) {\n const c = contexts.get(controller)\n if (!c) return\n contexts.delete(controller)\n if (c.seed) c.root.removeEventListener?.(\"turbo:morph-element\", c.seed)\n}\n\n// Re-run the seed (for a feature that changed field values after connect:\n// the draft restore).\nexport function seed(controller) {\n contexts.get(controller)?.seed?.()\n}\n\n// The Stimulus action (input->reactive#recompute); the controller's method of\n// the same name hands the event here.\nfunction publicRecompute(controller, core, event) {\n return recompute(ctx(controller, core), event)\n}\nexport { publicRecompute as recompute }\n\n// The control for a name nothing owned resolves to.\nconst COMPUTE_NO_CONTROL = Object.freeze({ el: null, kind: \"\" })\n\n// A cross-root mirror target must be a single ID selector (issue #159) — \"#\" +\n// a CSS identifier, nothing else. The client half of the two-sided default-deny\n// (reactive_compute's `mirror:` validates the SAME shape loudly at declare\n// time): a hand-built mirror attr must not widen a declared text mirror into a\n// page-wide selector write. A refused selector warns + skips (its siblings\n// still apply), matching the attr-allowlist posture.\nconst MIRROR_ID_SELECTOR = /^#[A-Za-z_][\\w-]*$/\n\n// The TEXT reading of a compute control (issue #262) — what a :string input\n// hands the reducer and what the identity/cross-root mirrors paint. A checkbox\n// reads its CHECKED STATE (\"true\"/\"false\", the strings reactive_show compares\n// against): its .value is a constant — \"1\", \"on\", whatever the markup says —\n// so reading it told the reducer nothing. A radio reads its value only while\n// checked (\"\" otherwise; the resolver hands over the checked radio of a group).\n// Anything else reads .value, as it always has.\n//\n// Every compute helper takes a CONTROL — the { el, kind } record #recompute's\n// resolver builds, kind being \"checkbox\", \"radio\" or \"\" — and never re-reads\n// el.type: the resolver reads it ONCE per name. Re-reading it in each helper\n// cost the 30-input calculator bench ~60% (16.8 → 27 µs/iter, measured).\nfunction computeText({ el, kind }) {\n if (!el) return \"\"\n if (kind === \"checkbox\") return el.checked ? \"true\" : \"false\"\n if (kind === \"radio\") return el.checked ? (el.value ?? \"\") : \"\"\n return el.value ?? \"\"\n}\n\n// Whether a value counts as \"on\" — for a :boolean input read off a control that\n// is not a checkbox, and for an output written INTO a checkbox. A boolean is\n// itself; otherwise \"\", \"0\" and \"false\" are off (what a hidden flag field or a\n// reducer returning 0 means) and anything else is on.\nfunction computeTruthy(value) {\n if (typeof value === \"boolean\") return value\n if (value == null) return false\n const text = String(value)\n return text !== \"\" && text !== \"0\" && text !== \"false\"\n}\n\n// One declared input's value for the reducer, coerced by its declared type\n// (issue #104; checked-state controls issue #262):\n//\n// \"string\" → the text reading, raw (blank/absent → \"\")\n// \"boolean\" → a checkbox's checked state; any other control by computeTruthy\n// \"number\" → a checkbox is 1/0; anything else through Number (blank/NaN → 0,\n// the nanToZero the hand-written calculators use)\n//\n// A checkbox is 1/0 and never Number(its value): a box is a yes/no, and a\n// reducer that wants an amount writes `gift ? 25 : 0`.\nfunction computeValue(control, type) {\n if (type === \"string\") return computeText(control)\n const box = control.kind === \"checkbox\"\n if (type === \"boolean\") return box ? Boolean(control.el.checked) : computeTruthy(computeText(control))\n if (box) return control.el.checked ? 1 : 0\n const n = Number(computeText(control))\n return Number.isFinite(n) ? n : 0\n}\n\n// Write one reducer output into the control its name resolved to (issue #262),\n// change-guarded. Returns the element to announce with an `input` event, or\n// null when nothing changed. A checkbox takes the result as its checked state\n// and a radio group checks the radio carrying it — neither ever has its value\n// attribute rewritten, which would change what the control SUBMITS. Anything\n// else takes the result as its .value (issue #76).\nfunction computeWrite(root, owns, { el, kind }, domName, value) {\n if (kind === \"checkbox\") {\n const checked = computeTruthy(value)\n if (Boolean(el.checked) === checked) return null\n el.checked = checked\n return el\n }\n if (kind === \"radio\") return computeCheckRadio(root, owns, domName, String(value))\n if (String(value) === el.value) return null\n el.value = value\n return el\n}\n\n// Check the owned radio of a group whose value is `wanted`, unchecking the\n// rest — the same per-radio rule a restored draft applies. A value no radio\n// carries clears the group. Returns the radio that GAINED the check, or, for a\n// cleared group, the one that lost it; null when the selection already matched.\nfunction computeCheckRadio(root, owns, domName, wanted) {\n let announced = null\n for (const el of root.querySelectorAll(`[name=\"${domName}\"]`)) {\n if (el.type !== \"radio\" || !owns(el)) continue\n const checked = el.value === wanted\n if (Boolean(el.checked) === checked) continue\n el.checked = checked\n if (checked) announced = el\n else announced ??= el\n }\n return announced\n}\n\n// Normalize a reducer's reserved $ops output (issue #226): the compute `ops`\n// builder (its .ops list), a raw [[name, args], ...] array, or null/undefined\n// (no effect this pass). An EMPTY list is the same as null — \"nothing to run\"\n// must not latch the rising edge. Anything else warns + is dropped\n// (default-deny, like every other malformed op source). Reducers are trusted\n// app code, but their ops still run through the frozen CLIENT_OPS whitelist.\nfunction computeOpsList(raw) {\n if (raw == null) return null\n const list = Array.isArray(raw) ? raw : raw.ops\n if (Array.isArray(list)) return list.length > 0 ? list : null\n console.warn(\"[phlex-reactive] $ops must be an ops chain or a [[op, args], ...] list — skipped\")\n return null\n}\n\nfunction guardMirrorSelector(selector) {\n if (typeof selector === \"string\" && MIRROR_ID_SELECTOR.test(selector)) return true\n console.warn(`[phlex-reactive] refused cross-root mirror target ${JSON.stringify(selector)} — skipped`)\n return false\n}\n\n// Apply a reducer-emitted $ops chain (issue #226) on its RISING EDGE, keyed\n// on CONTENT: fire only when THIS pass's chain differs from the LAST pass's\n// (including from \"absent\"), and only on an event-driven pass. An unchanged\n// chain never re-fires — \"still complete, same submit\" is settled, exactly\n// like the change-guarded field writes. A pass with no $ops re-arms; a pass\n// whose chain CHANGED fires again (per-keystroke focus advance across OTP\n// boxes is a different focus target each time — a deliberately new intent).\n// Ops run through the shared CLIENT_OPS interpreter with runOps's\n// root-scoped target resolution; a missing to: defaults to \"@root\"\n// (hand-written reducer ergonomics).\nfunction applyComputeOps(c, list, eventDriven) {\n const signature = list === null ? null : JSON.stringify(list)\n const fire = signature !== null && signature !== c.opsSig && eventDriven\n c.opsSig = signature\n if (!fire) return\n c.core.applyOps(list, \"@root\")\n}\n\n// Parse a JSON string list from a root data attr; [] on absence/parse error so\n// a malformed binding degrades to \"no fields\" rather than throwing on input.\nfunction parseComputeList(c, attr) {\n const raw = c.root.getAttribute(attr)\n if (!raw) return []\n try {\n const list = JSON.parse(raw)\n return Array.isArray(list) ? list : []\n } catch {\n return []\n }\n}\n\n// Parse the inputs param into [name, type] pairs (issue #104). The wire is a\n// JSON ARRAY of names (array form → every input typed \"number\", the shipped\n// numeric coercion) OR a JSON OBJECT of name→type (hash form → \":string\" read\n// raw, \":number\" coerced). Malformed/absent degrades to [] — a bad binding\n// must never throw on input.\nfunction parseComputeInputs(c) {\n const raw = c.root.getAttribute(\"data-reactive-compute-inputs-param\")\n if (!raw) return []\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) return parsed.map((name) => [name, \"number\"])\n if (parsed && typeof parsed === \"object\") return Object.entries(parsed)\n return []\n } catch {\n return []\n }\n}\n\n// The declared compute input the event just edited — the reducer's\n// meta.changed (issue #75). The triggering field counts only when it is a\n// named form control OWNED by this root (not a nested reactive root's, issue\n// #15) AND its name is among the declared compute inputs; anything else\n// (a direct call, an unowned/undeclared target) yields null.\n//\n// Scope-aware (issue #184): under data-reactive-scope, the edited field's DOM\n// name is scoped (order[allowance]) while the declared inputs are BARE\n// (allowance). Strip the scope prefix off the DOM name before comparing, and\n// return the BARE name — so a reducer branching on `changed` sees the same\n// names it declared, scoped or not.\nfunction changedComputeField(c, event, inputs, scope) {\n const target = event?.target\n if (!target?.name || typeof target.closest !== \"function\") return null\n const bare = unscopeName(target.name, scope)\n if (!inputs.includes(bare)) return null\n return c.core.owns(target) ? bare : null\n}\n\n// Strip a leading `scope[…]` wrapper off a DOM field name, returning the bare\n// inner name; a name that isn't wrapped in this scope passes through unchanged.\nfunction unscopeName(name, scope) {\n if (!scope) return name\n const prefix = `${scope}[`\n return name.startsWith(prefix) && name.endsWith(\"]\") ? name.slice(prefix.length, -1) : name\n}\n\n// Write `value` into every owned [data-reactive-text=\"<name>\"] node via\n// textContent (issue #104) — XSS-safe by construction (never innerHTML). Drives\n// both the identity mirror (an input's raw value) and a text-node output (a\n// reducer result with no matching field). Change-guarded (skip an unchanged\n// node) and NO input dispatch — a text node has no listener contract. String()\n// so a numeric result renders like the DOM would.\nfunction mirrorText(c, name, value) {\n const text = String(value)\n for (const node of ownedTextNodes(c, name)) {\n if (node.textContent === text) continue\n node.textContent = text\n }\n}\n\n// Every [data-reactive-text=\"<name>\"] mirror OWNED by this root (skips nested\n// reactive roots, issue #15). Empty when none — reactive_text is optional.\nfunction ownedTextNodes(c, name) {\n const nodes = c.root.querySelectorAll(`[data-reactive-text=\"${name}\"]`)\n return Array.from(nodes).filter((el) => c.core.owns(el))\n}\n\n// Cross-root text mirrors (issue #159): paint every DECLARED mirror name into\n// its allowlisted document-wide id targets via textContent — the opt-in escape\n// from root isolation (issue #15) for a recap OUTSIDE the computing root. The\n// value is the reducer's result when it produced one, else the owned field's\n// CURRENT value (an input identity mirror / a just-written output) — one\n// declaration covers all three shapes. A name with NO value this pass is\n// SKIPPED (a mirror never blanks a recap the reducer didn't feed). textContent\n// only (never innerHTML), change-guarded, and NO input dispatch — same\n// contract as #mirrorText. With no mirror declared this is one getAttribute\n// and out — the shipped compute path never touches the document.\nfunction applyComputeMirrors(c, result, ownedControl) {\n const mirror = parseComputeMirror(c)\n for (const [name, selectors] of Object.entries(mirror)) {\n const control = name in result ? null : ownedControl(name)\n const value = name in result ? result[name] : control.el ? computeText(control) : undefined\n if (value === undefined || value === null) continue\n const text = String(value)\n for (const sel of Array.isArray(selectors) ? selectors : [selectors]) {\n if (!guardMirrorSelector(sel)) continue\n for (const node of document.querySelectorAll(sel)) {\n if (node.textContent === text) continue\n node.textContent = text\n }\n }\n }\n}\n\n// The declared cross-root mirror map (issue #159): a JSON object of\n// { name: [id selectors] } from data-reactive-compute-mirror-param (emitted by\n// reactive_compute's `mirror:`). Absent/malformed degrades to {} — a bad\n// binding must never throw on input.\nfunction parseComputeMirror(c) {\n const raw = c.root.getAttribute(\"data-reactive-compute-mirror-param\")\n if (!raw) return {}\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : {}\n } catch {\n return {}\n }\n}\n\n// Whether this root opts into the connect-time compute seed (issue #199).\n// reactive_compute's root binding emits data-reactive-compute-seed=\"true\"; a\n// root without a compute binding (or with the seed opted out) pays one\n// attribute read and never seeds. A quick read, evaluated once per connect.\nfunction computeSeedEnabled(c) {\n return c.root.getAttribute?.(\"data-reactive-compute-seed\") === \"true\"\n}\n\n// Client-side compute (data binding). Wired by reactive_compute: an `input`\n// trigger (input->reactive#recompute) runs a REGISTERED JS reducer over the\n// named input fields and writes the named output fields WITH NO ROUND TRIP —\n// the \"instant\" half of the new/unpersisted-record UX. If the field ALSO\n// carries on(...) (a persisted record, or a synced draft), that debounced POST\n// still fires and the server reply reconciles; recompute just paints first.\n//\n// Reads inputs/outputs/reducer from the root's data-reactive-compute-* attrs\n// (set once by reactive_compute_attrs). A missing/unregistered reducer is a\n// no-op — a page must never break because a binding wasn't wired up.\n//\n// The reducer gets a second argument, meta = { changed } (issue #75): the\n// name of the declared input the triggering event edited, or null for a\n// direct call / an unowned or undeclared target. A multi-way rebalance\n// branches on it (edit c → derive a; else → derive c). Note that a #76\n// output write dispatches a real input event, so recompute RE-ENTERS with\n// changed = that output's name — the reducer must be convergent (see\n// compute.js) so the change guard settles the chain.\nfunction recompute(c, event) {\n // Issue #183 — single-pass write set: an `input` event this method dispatched\n // for its OWN output writes is self-marked. Re-running the reducer on it would\n // re-enter from a partially-written DOM (the old mid-loop-dispatch corruption\n // class). Skip the reducer for our own event — but ONLY ours: the marker lives\n // in a per-instance WeakSet, so a genuinely different root's compute event (or\n // a real user edit) is never swallowed. The event still bubbled and fired every\n // OTHER listener (dirty tracking, show bindings, sibling roots) before reaching\n // here; we simply don't recompute a second time from our own write.\n if (event && c.ours.has(event)) return\n\n // Inputs may be a JSON ARRAY of names (array form — every input coerced\n // through Number, the shipped behavior) or a JSON OBJECT of name→type (hash\n // form, issue #104 — :number coerced, :string read raw). #parseComputeInputs\n // returns [name, type] pairs either way (array form defaults type \"number\").\n const inputPairs = parseComputeInputs(c)\n const inputs = inputPairs.map(([name]) => name)\n\n // Resolve every declared input AND output through ONE per-call resolver whose\n // ownership probe is computed ONCE (issue #117), replacing the per-name\n // closest() walk #ownedField did on every read — a 30-field calculator paid\n // ~60 closest() sweeps per keystroke. #ownershipFilter returns a constant-true\n // predicate in the common no-nested-root case (skipping closest() entirely)\n // and the exact #ownsField check when a nested reactive root is present\n // (issue #15 scoping, byte-identical to before). Resolution is memoized in a\n // per-CALL Map, so a name read as an input AND written as an output\n // resolves to the SAME element and is queried once.\n //\n // Which element a name resolves to (issue #262, mirroring #showFieldValue): a\n // CHECKBOX wins over the hidden companion Rails renders before it; a radio\n // group resolves to its CHECKED radio (any radio of the group when none is);\n // anything else is first-wins. Resolving first-wins across the board handed\n // the reducer the companion's constant \"0\" and the first radio's value.\n //\n // Why per-name `[name=\"X\"]` queries and not one bare `[name]` sweep: a single\n // sweep is the natural \"one walk\", but the resolver must issue the SAME\n // per-name query shape the field walk always has (the issue-#15 unit fakes\n // answer only `[name=\"X\"]`). It is O(distinct declared names) queries, not the\n // old O(inputs + outputs) — the ownership decision is hoisted out of the loop.\n // The memo is per-CALL only: an output write dispatches `input` (issue #76),\n // re-entering recompute, which correctly rebuilds a fresh map (a morph may\n // have replaced the nodes) — it is NEVER stored on the instance.\n // Scope (issue #183, mirroring #showFieldValue): a bare compute name `cash`\n // under `data-reactive-scope=\"order\"` resolves as `[name=\"order[cash]\"]`. A\n // name already carrying a bracket (a raw wire name the author passed) is used\n // verbatim — so bracketed literals pass through unscoped.\n const scope = c.root.getAttribute?.(\"data-reactive-scope\") || null\n const scoped = (name) => (scope && !name.includes(\"[\") ? `${scope}[${name}]` : name)\n\n const owns = c.core.ownership()\n const byName = new Map()\n const ownedControl = (name) => {\n const known = byName.get(name)\n if (known) return known\n let radio = null\n let first = null\n let control = null\n for (const el of c.root.querySelectorAll(`[name=\"${scoped(name)}\"]`)) {\n if (!owns(el)) continue\n const kind = el.type // read ONCE per element — see computeText\n if (kind === \"checkbox\" || (kind === \"radio\" && el.checked)) {\n control = { el, kind }\n break\n }\n if (kind === \"radio\") radio ??= el\n else first ??= el\n }\n if (!control) {\n if (radio) control = { el: radio, kind: \"radio\" }\n else control = first ? { el: first, kind: \"\" } : COMPUTE_NO_CONTROL\n }\n byName.set(name, control)\n return control\n }\n\n // Identity-mirror pass (issue #104), ALWAYS run — even with NO registered\n // reducer, so reactive_text(:title) mirrors a field into its text node with\n // zero reducer wiring. Each declared input's RAW text reading (computeText —\n // a checkbox paints \"true\"/\"false\", issue #262) is written to its owned\n // [data-reactive-text=\"<name>\"] node(s). It runs BEFORE the reducer\n // early-return below so a reducer-less binding still mirrors.\n for (const name of inputs) mirrorText(c, name, computeText(ownedControl(name)))\n\n const key = c.root.getAttribute(\"data-reactive-compute-reducer-param\")\n const reduce = key ? computeReducer(key) : null\n if (!reduce) {\n // No reducer registered: the identity pass above still ran, so declared\n // cross-root mirrors of the INPUT names still paint (issue #159) — a\n // reducer-less binding mirrors, exactly like the owned-text-node case.\n applyComputeMirrors(c, {}, ownedControl)\n return\n }\n\n const outputs = parseComputeList(c, \"data-reactive-compute-outputs-param\")\n\n // Coerce each input per its declared type (computeValue): \"string\" raw,\n // \"boolean\" a real boolean, else (\"number\", the array-form default) the\n // numeric coercion. A checkbox contributes its CHECKED STATE under every\n // type (issue #262). Reads from the memoized resolver — no re-query.\n const values = {}\n for (const [name, type] of inputPairs) values[name] = computeValue(ownedControl(name), type)\n\n // meta.changed stays on #changedComputeField (its own #ownsField check over\n // the raw event target) — NOT this resolver. The issue-#15 nested-rejection\n // test depends on that path being unchanged. ONE run, from the ONE pre-write\n // snapshot above (issue #183): its result drives the whole single-pass write.\n const result = reduce(values, { changed: changedComputeField(c, event, inputs, scope) }) || {}\n\n // The reserved $ops output (issue #226) is CONSUMED here — normalized once,\n // then excluded from every write phase below (it is an op chain, never a\n // field value, text sink, or mirror), and applied as phase 4.\n const reducerOps = computeOpsList(result.$ops)\n\n // Issue #183 — SINGLE-PASS WRITE SET. Ordered phases, so declared output\n // order stops being semantics and a wrong order can no longer corrupt values:\n //\n // 1. BATCH the field writes from the ONE result. Each output name in the\n // allowlist (outputs:) whose owned field's value actually changes is\n // written now (change-guarded) and remembered — but NO `input` event is\n // dispatched yet, so nothing re-enters mid-batch. A checkbox or radio\n // output is written as its CHECKED state (computeWrite, issue #262).\n // 2. PAINT the sinks from the SETTLED values: any owned reactive_text node by\n // presence (issue #183 change #4 — a text node no longer needs its name in\n // outputs:), then the cross-root mirror: ids (issue #159).\n // 3. DISPATCH a self-marked `input` on each changed field. The marker (a\n // per-instance WeakSet) makes recompute skip re-running the reducer for our\n // own write, while the event still fires every OTHER listener (chained\n // repaint, dirty tracking, show bindings, sibling roots).\n // 4. RUN the reducer's $ops chain (issue #226) — rising-edge, event-gated —\n // so its ops (dispatch a completion event, submit the form) always see\n // the fully settled DOM and every chained listener has already run.\n const changedFields = []\n for (const name of outputs) {\n if (name === \"$ops\" || !(name in result)) continue\n const control = ownedControl(name)\n if (!control.el) continue // a non-field output paints as a text sink in phase 2\n const written = computeWrite(c.root, owns, control, scoped(name), result[name])\n if (written) changedFields.push(written) // null = change-guard, unchanged\n }\n\n // Phase 2 — text sinks declare themselves (issue #183 change #4): every result\n // key paints into any owned [data-reactive-text=\"<name>\"] node by PRESENCE,\n // regardless of outputs: membership. Runs from settled field values. A null/\n // undefined result value is SKIPPED (never stringified to \"null\"/\"undefined\") —\n // the same \"no value this pass, don't paint\" filter #applyComputeMirrors uses.\n for (const name of Object.keys(result)) {\n if (name === \"$ops\") continue\n const value = result[name]\n if (value === undefined || value === null) continue\n mirrorText(c, name, value)\n }\n\n // Cross-root text mirrors (issue #159) — AFTER the batch + text sinks, so a\n // mirror keyed on a just-written output paints the settled value.\n applyComputeMirrors(c, result, ownedControl)\n\n // Phase 3 — dispatch the deferred `input` events (issue #183). Real browsers\n // do NOT fire `input` on a programmatic .value write (issue #76), so we do it\n // ourselves, matching the server's set_value + dispatch(\"input\") contract.\n // Each event is SELF-MARKED so our own re-entry skips the reducer (guard at the\n // top of recompute) — but the event still bubbles and fires every other\n // listener. Dispatched AFTER all writes + paints, so a chained listener reads\n // SETTLED values, never a half-written DOM.\n for (const field of changedFields) {\n const inputEvent = new Event(\"input\", { bubbles: true })\n c.ours.add(inputEvent)\n field.dispatchEvent(inputEvent)\n }\n\n // Phase 4 — the reducer's $ops chain (issue #226), after everything settled.\n // Event-gated: a seed/direct recompute() pass (no event) arms the latch but\n // never fires, so a restored/re-rendered complete value can't auto-fire.\n applyComputeOps(c, reducerOps, Boolean(event))\n}\n",
8
8
  "// Client-only drafts (issue #239) — reactive_persist. A FEATURE MODULE of the\n// reactive controller (issue #275): the core imports it only when a root on\n// the page declares data-reactive-persist, or when a persist_state /\n// persist_clear client op runs.\n//\n// A root that declares\n// data-reactive-persist='{\"key\",\"ttl\",\"debounce\"[,\"fields\"][,\"restore\"][,\"storage\"]}'\n// keeps a localStorage (or, with \"storage\":\"session\", sessionStorage) draft of every persistable OWNED control (write on\n// input/change, restore on connect, clear on a successful submit / TTL / the\n// persist_clear op). The storage layer is MODULE-LEVEL and keyed on the root\n// element — the per-root connect/write path and the persist_state /\n// persist_clear client ops (which receive only the element) share it. Every\n// storage access is try/catch'd: a private window, a quota error or blocked\n// storage degrades to \"no draft\", never a thrown bootstrap. Nothing here\n// leaves the browser: no token, no POST, and phlex-reactive never writes\n// markup into the DOM: native controls are replayed via\n// .value/.checked/.selected, a bare [contenteditable] via textContent, and a\n// rich editor (lexxy-editor, trix-editor — issue #241) through its OWN\n// `value` setter, the same sanitizing import path a paste takes. Never\n// innerHTML.\n//\n// The feature contract (reactive_controller.js \"Feature modules\"):\n// install(shared) once, when the module loads\n// connect(controller, core, morphed, pending) per root connection\n// disconnect(controller, core) before the core's teardown\n// abandon(root, pending) the root left before connect\n// `core` is the controller's handle for features: core.emit(name, detail)\n// raw-dispatches a lifecycle event from the root; core.reseed() re-runs the\n// connect-time seeds that read field values (dirty baseline, show bindings,\n// on-complete arming, filter, tags, nested JSON, compute).\n//\n// TIMING. On the first root of a page that needs it, this module is still on\n// its way when the controller connects, so the restore runs a moment AFTER\n// connect() — and the connect-time seeds, which ran on the server's values,\n// are re-run (core.reseed()). On any later root the module is loaded and the\n// restore runs inside connect() as it always did.\n//\n// While a root waits for this module:\n// * it writes no draft, and its action requests are held back (they would\n// post the server's blanks) — the core's side of it;\n// * the core records, in `pending`, that the user edited a field and that\n// the form was submitted successfully; connect() drafts the edit, or\n// forgets the draft instead of restoring it;\n// * a persist_state / persist_clear op waits in pending.ops — its snapshot\n// would overwrite the draft with those blanks.\n// A root that leaves before the module arrives is handed to abandon().\n\n// The core's shared state (install()): shared.waiting maps a root to\n// { persist: pending } while that root waits for this module.\nlet shared\n\nexport function install(given) {\n shared = given\n}\n\nconst PERSIST_VERSION = 1\nconst PERSIST_PREFIX = \"phlex-reactive:persist:\"\n// Never persisted regardless of author intent: no server default to restore\n// into (hidden, file), secrets (password), and non-value controls.\nconst PERSIST_EXCLUDED_TYPES = new Set([\"hidden\", \"file\", \"password\", \"submit\", \"button\", \"reset\", \"image\"])\nconst PERSIST_NO_VALUE = Symbol(\"persist-no-value\")\nconst PERSIST_STATE_ATTR = \"data-reactive-persist-state\"\n// The editor query the core's #collectFields reads (minus the [name] guard —\n// an editor's name may live on its IDL `name` getter: Trix's `input=`-paired\n// hidden input). The core holds the same two constants (EDITOR_SELECTOR,\n// EDITOR_TAGS); a feature never imports the core, so they are repeated here\n// and spec/javascript/reactive_persist.test.js pins that they stay equal.\nexport const PERSIST_EDITOR_SELECTOR =\n \":is(lexxy-editor, trix-editor, [contenteditable=''], [contenteditable=true], [contenteditable=plaintext-only])\"\nexport const PERSIST_EDITOR_TAGS = new Set([\"lexxy-editor\", \"trix-editor\"])\n// An editor's own chrome: Lexxy renders its toolbar (a `lexxy-code-language`\n// select, the link dialog's `href` input) INSIDE <lexxy-editor>, Trix as a\n// sibling <trix-toolbar>. Those are named native controls that are not the\n// user's fields — never drafted, never restored into.\nconst PERSIST_EDITOR_CHROME = \"lexxy-editor, trix-editor, trix-toolbar\"\n// The editors' own bubbling change events — the keystroke signal for the\n// draft write, since neither lets its contenteditable's native `input` bubble.\nconst PERSIST_EDITOR_CHANGE_EVENTS = [\"lexxy:change\", \"trix-change\"]\n// \"Is this editor empty\" when it exposes no predicate of its own (Lexxy's\n// `isEmpty`, Trix's `editor.getDocument().isEmpty()`): Lexxy's own empty\n// list plus the Trix / contenteditable empties. Exact strings, no HTML\n// parsing — an attachment-only body stays non-blank.\nconst PERSIST_EMPTY_HTML = new Set([\"\", \"<p></p>\", \"<p><br></p>\", \"<div><br></div>\"])\n// Once-per-root guards: a malformed payload warns once; the storage-failure\n// and editor-restore dev notes (debug mode only) print once each.\nconst persistPayloadWarned = new WeakSet()\nconst persistFailureNoted = new WeakSet()\nconst persistEditorNoted = new WeakSet()\n\n// The root's parsed payload, or null (undeclared / malformed → warned once).\n// A control-level \"off\" (reactive_persist_skip) is never a root payload.\nfunction persistPayload(root) {\n const raw = root?.getAttribute?.(\"data-reactive-persist\")\n if (!raw || raw === \"off\") return null\n try {\n const payload = JSON.parse(raw)\n if (payload && typeof payload === \"object\" && typeof payload.key === \"string\" && payload.key !== \"\") return payload\n } catch {\n // fall through to the warn\n }\n if (!persistPayloadWarned.has(root)) {\n persistPayloadWarned.add(root)\n console.warn(`[phlex-reactive] malformed reactive_persist payload ${JSON.stringify(raw)} — persistence disabled`)\n }\n return null\n}\n\n// The store the root selected: sessionStorage for {\"storage\":\"session\"}\n// (issue #397 — this tab only), else localStorage. Never the other one: a\n// missing sessionStorage is \"no draft\", not a fallback that outlives the tab.\nfunction persistStorage(payload) {\n try {\n if (payload.storage === \"session\") return typeof sessionStorage === \"undefined\" ? null : sessionStorage\n return typeof localStorage === \"undefined\" ? null : localStorage\n } catch {\n return null // the accessor itself can throw (blocked site data)\n }\n}\n\n// The dev lens for \"why did nothing come back\": ONLY under data-reactive-debug\n// (Phlex::Reactive.debug), once per root — production stays silent.\nfunction persistNoteFailure(root, error) {\n if (root?.getAttribute?.(\"data-reactive-debug\") !== \"true\" || persistFailureNoted.has(root)) return\n persistFailureNoted.add(root)\n console.info(`[phlex-reactive] reactive_persist: storage unavailable — draft skipped (${error?.name ?? error})`)\n}\n\nfunction persistKeyFor(payload) {\n return PERSIST_PREFIX + payload.key\n}\n\n// Read + validate the draft: null when absent, unparsable, another schema\n// version, or expired (an expired draft is REMOVED on read). Returns\n// { fields, state } with state null when the draft carries none.\nfunction persistRead(root, payload) {\n const store = persistStorage(payload)\n if (!store) return null\n let raw\n try {\n raw = store.getItem(persistKeyFor(payload))\n } catch (error) {\n persistNoteFailure(root, error)\n return null\n }\n if (!raw) return null\n let draft\n try {\n draft = JSON.parse(raw)\n } catch {\n return null\n }\n if (!draft || typeof draft !== \"object\" || draft.v !== PERSIST_VERSION) return null\n const ttlMs = Number(payload.ttl) * 1000\n if (!(Number(draft.savedAt) + ttlMs > Date.now())) {\n persistRemove(root, payload)\n return null\n }\n const fields = draft.fields && typeof draft.fields === \"object\" ? draft.fields : {}\n const state = draft.state && typeof draft.state === \"object\" ? draft.state : null\n return { fields, state }\n}\n\nfunction persistWrite(root, payload, { fields, state }) {\n const store = persistStorage(payload)\n if (!store) return false\n const draft = { v: PERSIST_VERSION, savedAt: Date.now(), fields }\n if (state) draft.state = state\n try {\n store.setItem(persistKeyFor(payload), JSON.stringify(draft))\n return true\n } catch (error) {\n persistNoteFailure(root, error)\n return false\n }\n}\n\nfunction persistRemove(root, payload) {\n root?.removeAttribute?.(PERSIST_STATE_ATTR)\n const store = persistStorage(payload)\n if (!store) return\n try {\n store.removeItem(persistKeyFor(payload))\n } catch (error) {\n persistNoteFailure(root, error)\n }\n}\n\n// The persistable controls this root OWNS (#15: a nested reactive root's\n// controls are its own), minus the excluded types, the reactive_persist_skip\n// marker, and — when `fields` narrows the set — any undeclared name. Each\n// entry is { el, name, kind } with kind \"native\" (input/select/textarea),\n// \"editor\" (lexxy-editor / trix-editor) or \"contenteditable\" (a bare named\n// editable element) — issue #241.\nfunction persistControls(root, payload) {\n const allow = Array.isArray(payload.fields) ? new Set(payload.fields) : null\n const out = []\n const owned = (el) =>\n el.closest('[data-controller~=\"reactive\"]') === root && el.getAttribute(\"data-reactive-persist\") !== \"off\"\n for (const el of root.querySelectorAll(\"input[name], select[name], textarea[name]\")) {\n if (!owned(el) || PERSIST_EXCLUDED_TYPES.has(el.type) || el.closest(PERSIST_EDITOR_CHROME)) continue\n if (allow && !allow.has(el.name)) continue\n out.push({ el, name: el.name, kind: \"native\" })\n }\n for (const el of root.querySelectorAll(PERSIST_EDITOR_SELECTOR)) {\n if (!owned(el)) continue\n const name = persistEditorName(el)\n if (!name || (allow && !allow.has(name))) continue\n out.push({ el, name, kind: PERSIST_EDITOR_TAGS.has(el.localName) ? \"editor\" : \"contenteditable\" })\n }\n return out\n}\n\n// A contenteditable's text: a reactive_editable through the core's collector\n// (issue #351 — line breaks kept, as the request sends it), a bare one as its\n// textContent (#241).\nfunction persistText(el) {\n return el.hasAttribute(\"data-reactive-editable\") ? shared.text(el) : (el.textContent ?? \"\")\n}\n\n// The attribute first (Lexxy, a bare contenteditable — which has no `name`\n// IDL property at all), then the IDL getter (Trix resolves it through its\n// `input=`-paired hidden input, which is itself excluded as type=hidden).\nfunction persistEditorName(el) {\n return el.getAttribute(\"name\") || (typeof el.name === \"string\" && el.name) || null\n}\n\n// An editor is READY once its custom element has upgraded and connected: only\n// then does it expose the string `value` accessor (Lexxy's setter throws\n// before connectedCallback created its editor; Trix's discards the value).\nfunction persistEditorReady(el) {\n return typeof el.value === \"string\"\n}\n\n// Ask the editor whether it is empty (Lexxy `isEmpty`; Trix\n// `editor.getDocument().isEmpty()`), else the exact-string fallback. An\n// attachment-only server body is therefore NON-blank and never overwritten.\nfunction persistEditorBlank(el) {\n if (typeof el.isEmpty === \"boolean\") return el.isEmpty\n const doc = el.editor?.getDocument?.()\n if (typeof doc?.isEmpty === \"function\") return doc.isEmpty()\n return PERSIST_EMPTY_HTML.has(el.value.trim())\n}\n\n// The editor-restore dev lens: ONLY under data-reactive-debug, once per root.\nfunction persistNoteEditorFailure(root, name, error) {\n if (root?.getAttribute?.(\"data-reactive-debug\") !== \"true\" || persistEditorNoted.has(root)) return\n persistEditorNoted.add(root)\n console.info(\n `[phlex-reactive] reactive_persist: could not restore editor ${JSON.stringify(name)} — ${error?.message ?? error}`,\n )\n}\n\nfunction persistSelectMultiple(el) {\n return el.tagName === \"SELECT\" && el.multiple\n}\n\n// How many controls can contribute a value under each `[]` name, counted the\n// way persistSnapshot fills the slot — a radio is the exception there and here.\n// A group of ONE is unambiguous: its single entry can only have come from that\n// control.\nfunction persistGroupSizes(controls) {\n const sizes = new Map()\n for (const { el, name } of controls) {\n if (el.type === \"radio\" || !String(name).endsWith(\"[]\")) continue\n sizes.set(name, (sizes.get(name) ?? 0) + 1)\n }\n return sizes\n}\n\n// The value a control that cannot pick its own entry out of a list may take.\n// A list belongs to a `[]` group, and in a group of two or more nothing says\n// which entry came from which control — restoring it would paste\n// \"freeform,news\" into a text field. A group of ONE has no such ambiguity, and\n// refusing it would silently drop the draft of a plain field whose name merely\n// ends in `[]` (a list JS maintains), which worked before groups existed.\n// Returns PERSIST_NO_VALUE when the control must keep what the server rendered.\nfunction persistGenericValue(value, name, sizes) {\n if (!Array.isArray(value)) return value\n if (sizes.get(name) !== 1 || value.length !== 1) return PERSIST_NO_VALUE\n\n return value[0]\n}\n\n// Snapshot the owned controls: radio → the checked value (null when the group\n// has none, so a restore leaves it alone), checkbox → checked, multi-select →\n// the selected values, a rich editor → its serialized `value` (omitted while\n// the element hasn't upgraded — never a phantom \"\"), a bare contenteditable →\n// its textContent, else .value. Mirrors the core's #collectFields reads.\nfunction persistSnapshot(root, payload) {\n const fields = {}\n // A `[]` name is a group for every control that can contribute a value —\n // checkboxes, selects, text inputs, editors and contenteditables all append\n // to one array, mirroring #collectFields. The one exception is a RADIO group,\n // which means \"pick one\" and keeps its single value with or without the\n // suffix, exactly as the collector treats it.\n //\n // Reading the slot without this (fields[name] ?? []) breaks as soon as a\n // non-checkbox shares the group's name: a text input or an editor leaves a\n // string there, `.push` on it throws inside the draft write, and that write\n // is swallowed — the root then persists nothing at all, silently. Editors\n // are collected AFTER the native controls, so they always land last.\n const groupSlot = (name) => {\n const existing = fields[name]\n return Array.isArray(existing) ? existing : (fields[name] = [])\n }\n for (const { el, name, kind } of persistControls(root, payload)) {\n const group = String(name).endsWith(\"[]\")\n if (kind === \"editor\") {\n if (persistEditorReady(el)) {\n if (group) groupSlot(name).push(el.value)\n else fields[name] = el.value\n }\n } else if (kind === \"contenteditable\") {\n const text = persistText(el)\n if (group) groupSlot(name).push(text)\n else fields[name] = text\n } else if (el.type === \"radio\") {\n if (el.checked) fields[name] = el.value\n else if (!Object.hasOwn(fields, name)) fields[name] = null\n } else if (el.type === \"checkbox\") {\n // A `[]` group drafts the list of ticked values, mirroring #collectFields\n // (issue #258). Without this the boxes overwrote each other and the draft\n // held one boolean, which the restore then applied to every box of the\n // group. A lone checkbox keeps the boolean it has always been.\n if (group) {\n const slot = groupSlot(name)\n if (el.checked) slot.push(el.value)\n } else {\n fields[name] = el.checked\n }\n } else if (persistSelectMultiple(el)) {\n const selected = [...el.options].filter((o) => o.selected).map((o) => o.value)\n if (group) groupSlot(name).push(...selected)\n else fields[name] = selected\n } else if (group) {\n groupSlot(name).push(el.value)\n } else {\n fields[name] = el.value\n }\n }\n return fields\n}\n\n// Replay the draft into the owned controls. Default (restore: blank): a\n// control the server rendered NON-BLANK keeps its value — a 422 re-render's\n// submitted values beat an older draft. restore: \"always\" lets the draft win.\n// Values land via .value/.checked/.selected, textContent, or the editor's own\n// `value` setter — never HTML written by us.\nfunction persistApply(root, payload, fields) {\n const always = payload.restore === \"always\"\n const controls = persistControls(root, payload)\n // Which group names the SERVER rendered with a box already ticked. Computed\n // BEFORE the loop on purpose: the loop writes `checked`, so asking this\n // question from inside it would read THIS restore's own work — the first box\n // it ticks makes every later box of the same group look server-rendered, and\n // a draft of two values comes back as one. The radio branch below asks the\n // same question inline and stays correct only because a radio group holds a\n // single value.\n const groupSizes = persistGroupSizes(controls)\n const serverTicked = new Set()\n for (const control of controls) {\n if (control.kind === \"native\" && control.el.type === \"checkbox\" && control.el.checked) {\n serverTicked.add(control.name)\n }\n }\n for (const { el, name, kind } of controls) {\n if (!Object.hasOwn(fields, name)) continue\n let value = fields[name]\n if (value === null || value === undefined) continue\n // A multi-select reads a list by matching option values, which is only\n // sound when the list is ITS list. In a group with another contributor the\n // entries are mixed, and a text value that happens to equal an option\n // would select it — measured, a draft of [\"blue\",\"freitext\"] from a select\n // plus a text field selected both options. `?? 0` because a name without\n // the suffix is not in the map at all, and a plain `<select multiple\n // name=\"colors\">` must keep restoring.\n if (Array.isArray(value) && persistSelectMultiple(el) && (groupSizes.get(name) ?? 0) > 1) continue\n\n // An array belongs to a `[]` group, and only a control that can pick ITS\n // entry out of the list may read it: a checkbox matches by value, a\n // multi-select by option. Everything else — editors, contenteditables,\n // text inputs — keeps what the server rendered, because the list does not\n // record which entry came from which control. This sits ABOVE the branch\n // chain on purpose: below the editor branch it would never fire for the\n // very controls that land last in the snapshot.\n if (Array.isArray(value) && !(el.type === \"checkbox\" || persistSelectMultiple(el))) {\n value = persistGenericValue(value, name, groupSizes)\n if (value === PERSIST_NO_VALUE) continue\n }\n // The mirror, for a draft written BEFORE a group was drafted as a list\n // (#258): there `features[]` held ONE boolean, and applying it here ticks\n // every box of the group — precisely the state this fix removes, for as\n // long as the draft lives (default ttl 7 days). A group key that is not a\n // list is stale by definition, so the control keeps what the server\n // rendered and the next snapshot overwrites the key. It reads for a\n // multi-select too: 0.13.2 wrote last-writer-wins per name, so a checkbox\n // in a mixed group could leave its boolean under the select's name, and\n // under `restore: \"always\"` the select would then deselect everything —\n // `wanted` being Set{\"true\"} matches no option. Asking for the `[]` suffix\n // is what leaves a lone `gift` checkbox on the boolean it has always held —\n // and scoping the rule to the one key whose meaning changed is why\n // PERSIST_VERSION stays at 1: bumping it would also throw away the drafted\n // prose of every form that has no checkbox group at all.\n if ((el.type === \"checkbox\" || persistSelectMultiple(el)) && String(name).endsWith(\"[]\") && !Array.isArray(value)) {\n continue\n }\n if (kind === \"editor\") {\n persistApplyEditor(root, el, name, value, always)\n } else if (kind === \"contenteditable\") {\n if (!always && persistText(el).trim() !== \"\") continue\n el.textContent = String(value)\n } else if (el.type === \"radio\") {\n if (!always && controls.some((c) => c.kind === \"native\" && c.el.type === \"radio\" && c.name === name && c.el.checked)) continue\n el.checked = el.value === String(value)\n } else if (el.type === \"checkbox\" && Array.isArray(value)) {\n // A drafted group ticks exactly the boxes it held. One box the SERVER\n // rendered ticked means it had a say, and the draft yields for the whole\n // group.\n if (!always && serverTicked.has(name)) continue\n el.checked = value.map(String).includes(el.value)\n } else if (el.type === \"checkbox\") {\n if (!always && el.checked) continue\n el.checked = Boolean(value)\n } else if (persistSelectMultiple(el)) {\n if (!always && [...el.options].some((o) => o.selected)) continue\n const wanted = new Set((Array.isArray(value) ? value : [value]).map(String))\n for (const o of el.options) o.selected = wanted.has(o.value)\n } else {\n if (!always && el.value !== \"\") continue\n el.value = String(value)\n }\n }\n persistDeferEditors(root, payload, fields)\n}\n\n// A ready editor takes the value through its own setter; the setter is the\n// editor's sanitizing import (Trix HTMLParser, Lexxy $generateNodesFromDOM +\n// sanitizer). A throw (Lexxy before its editor exists) never escapes connect.\nfunction persistApplyEditor(root, el, name, value, always) {\n // A list never reaches here: both callers resolve it through\n // persistGenericValue first — the group of two or more has no mapping back to\n // this editor, the group of one does. Belt and braces, because this is the\n // one apply path with a second entry point.\n if (Array.isArray(value)) return\n if (!persistEditorReady(el)) return // not upgraded yet — persistDeferEditors re-applies after define\n if (!always && !persistEditorBlank(el)) return\n try {\n el.value = String(value)\n } catch (error) {\n persistNoteEditorFailure(root, name, error)\n }\n}\n\n// An editor whose custom element is not defined yet (Trix defines its elements\n// in a setTimeout after load; a lazily imported Lexxy) cannot take a value now.\n// Re-apply per TAG once it is defined — re-querying the controls (the upgrade\n// may replace the node) and re-checking restore: blank at that moment — unless\n// the root has left the document meanwhile.\nfunction persistDeferEditors(root, payload, fields) {\n const registry = globalThis.customElements\n if (typeof registry?.whenDefined !== \"function\") return\n const pending = new Set()\n for (const el of root.querySelectorAll(\"lexxy-editor, trix-editor\")) {\n if (!persistEditorReady(el) && !registry.get?.(el.localName)) pending.add(el.localName)\n }\n const always = payload.restore === \"always\"\n for (const tag of pending) {\n registry.whenDefined(tag).then(() => {\n if (!root.isConnected) return\n const deferred = persistControls(root, payload)\n const sizes = persistGroupSizes(deferred)\n for (const { el, name, kind } of deferred) {\n if (kind !== \"editor\" || el.localName !== tag || !Object.hasOwn(fields, name)) continue\n const value = persistGenericValue(fields[name], name, sizes)\n if (value === null || value === undefined || value === PERSIST_NO_VALUE) continue\n persistApplyEditor(root, el, name, value, always)\n }\n })\n }\n}\n\n// The persist_state op body: merge a FLAT bag into the root's draft (re-\n// snapshotting the fields so the write is whole) and mirror it on the root.\n// A root without reactive_persist is a call-site bug — warn and skip.\n// `restored` false: the root never restored (it left before this module\n// arrived), so its controls hold the server's blanks — keep the drafted\n// fields and merge the bag only.\nfunction persistWriteState(root, state, restored = true) {\n const payload = persistPayload(root)\n if (!payload) {\n console.warn(\"[phlex-reactive] persist_state on a root without reactive_persist — skipped\")\n return\n }\n if (!state || typeof state !== \"object\") return\n const current = persistRead(root, payload)\n const merged = { ...(current?.state ?? {}), ...state }\n const fields = restored ? persistSnapshot(root, payload) : (current?.fields ?? {})\n if (persistWrite(root, payload, { fields, state: merged })) {\n root.setAttribute?.(PERSIST_STATE_ATTR, JSON.stringify(merged))\n }\n}\n\nfunction persistClearRoot(root) {\n const payload = persistPayload(root)\n if (payload) persistRemove(root, payload)\n}\n\n// --- Per-root wiring -------------------------------------------------------\n\n// controller -> the closure that flushes and unwires the connection this\n// feature is wired to. Its timer and handlers are locals of connect(), not a\n// record's fields: the minifier renames a local, never a property (#310).\nconst wired = new WeakMap()\n\n// document -> the submit-end handlers of its persisted roots. One document\n// listener serves them all: a listener per root made connecting and\n// disconnecting N persisted roots quadratic (the browser scans a target's\n// listeners on each add and remove). Added with the first root, removed with\n// the last. Returns the handler's removal.\nconst submitEnds = new WeakMap()\n\nfunction onSubmitEndOf(doc, handler) {\n if (typeof doc?.addEventListener !== \"function\") return () => {}\n let shared = submitEnds.get(doc)\n if (!shared) {\n const handlers = new Set()\n const listener = (event) => {\n for (const run of handlers) run(event)\n }\n doc.addEventListener(\"turbo:submit-end\", listener)\n shared = [handlers, listener]\n submitEnds.set(doc, shared)\n }\n const [handlers, listener] = shared\n handlers.add(handler)\n return () => {\n handlers.delete(handler)\n if (handlers.size > 0) return\n doc.removeEventListener?.(\"turbo:submit-end\", listener)\n submitEnds.delete(doc)\n }\n}\n\n// Restore the draft into the owned controls, expose the state bag, announce,\n// then arm the write listeners. The restore reads ONCE and never writes back:\n// nothing is wired until it has completed, so no listener can clobber the\n// draft with the server's blanks. The submit-end listener is DOCUMENT-level\n// (the event fires on the form, which is usually an ANCESTOR of this root)\n// and gated on the form containing this root.\n//\n// `pending` is what the core recorded while this root waited for the module\n// (undefined when it never had to): see TIMING at the top.\nexport function connect(controller, core, _morphed, pending) {\n const root = controller.element\n const payload = persistPayload(root)\n if (!payload) return\n // Submitted successfully while we were on our way: the draft is done with.\n if (pending?.submitted) persistRemove(root, payload)\n const draft = persistRead(root, payload)\n if (draft) {\n persistApply(root, payload, draft.fields)\n if (draft.state) root.setAttribute?.(PERSIST_STATE_ATTR, JSON.stringify(draft.state))\n core.emit(\"reactive:persist-restored\", { key: payload.key, fields: draft.fields, state: draft.state ?? {} })\n // If the connect-time seeds ran before this restore, they ran on the\n // server's values; they read fields.\n core.reseed()\n }\n\n // ONE pending keystroke write per root (a snapshot is a full pass, so\n // per-field timers would only multiply writes).\n let timer = null\n const cancel = () => {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n // Snapshot every persistable owned control and write. Re-reads the current\n // draft first so a state bag written by persist_state survives the write\n // (the bag lives in storage, not on the connection — the op has none).\n const writeNow = () => {\n cancel()\n const current = persistRead(root, payload)\n persistWrite(root, payload, { fields: persistSnapshot(root, payload), state: current?.state ?? null })\n }\n // Trailing-edge debounce for keystrokes.\n const onInput = () => {\n const ms = Number(payload.debounce) || 0\n if (ms <= 0) return writeNow()\n if (timer !== null) clearTimeout(timer)\n timer = setTimeout(() => {\n timer = null\n writeNow()\n }, ms)\n }\n // A SUCCESSFUL Turbo form submission of the form that owns this root\n // forgets the draft. tagName (not instanceof) so a cross-realm form counts.\n const onSubmitEnd = (event) => {\n if (!event?.detail?.success) return\n const form = event.target\n if (form?.tagName !== \"FORM\" || typeof form.contains !== \"function\") return\n if (!form.contains(root)) return\n // Drop a pending keystroke write too — the disconnect flush that follows\n // Turbo's redirect visit would otherwise resurrect the just-cleared draft.\n cancel()\n persistRemove(root, payload)\n }\n // Rich editors (#241): Lexical and Trix swallow the native `input` of\n // their contenteditable, so their own bubbling change events are the\n // keystroke signal — same trailing-edge debounce as `input`.\n const inputs = [\"input\", ...PERSIST_EDITOR_CHANGE_EVENTS]\n for (const event of inputs) root.addEventListener?.(event, onInput)\n root.addEventListener?.(\"change\", writeNow)\n const offSubmitEnd = onSubmitEndOf(globalThis.document, onSubmitEnd)\n wired.set(controller, () => {\n if (timer !== null) writeNow()\n for (const event of inputs) root.removeEventListener?.(event, onInput)\n root.removeEventListener?.(\"change\", writeNow)\n offSubmitEnd()\n })\n\n // An edit made while we were on our way had no listener to draft it: draft\n // it now, with everything the restore just filled in around it.\n if (pending?.edited && !pending.submitted) writeNow()\n for (const op of pending?.ops ?? []) op(true)\n}\n\n// The root left before this module could connect to it. Nothing was restored\n// into it, so its controls hold what the server rendered plus whatever the\n// user did: forget the draft if the form was submitted; otherwise keep the\n// drafted fields, add the ones the user CHANGED, and run the ops that waited.\nexport function abandon(root, pending) {\n if (!pending) return\n const payload = persistPayload(root)\n if (!payload) return\n if (pending.submitted) return persistRemove(root, payload)\n if (pending.edited) {\n const current = persistRead(root, payload)\n const fields = { ...current?.fields }\n const snapshot = persistSnapshot(root, payload)\n for (const name of changedNames(root, payload)) {\n if (Object.hasOwn(snapshot, name)) fields[name] = snapshot[name]\n }\n persistWrite(root, payload, { fields, state: current?.state ?? null })\n }\n for (const op of pending.ops ?? []) op(false)\n}\n\n// The names of the owned controls the user changed on a root that never\n// restored: those whose live state differs from what the SERVER rendered (the\n// DOM keeps that as defaultValue / defaultChecked / the `selected` attribute), so a\n// server-prefilled value is never mistaken for an edit, and an emptied field\n// or an unticked box counts as one. An editor has no such default: it counts\n// once it holds anything.\nfunction changedNames(root, payload) {\n const names = new Set()\n for (const { el, name, kind } of persistControls(root, payload)) {\n const changed =\n kind === \"editor\"\n ? persistEditorReady(el) && !persistEditorBlank(el)\n : kind === \"contenteditable\"\n ? el.hasAttribute(\"data-reactive-editable\")\n ? shared.text(el) !== shared.served(el)\n : (el.textContent ?? \"\").trim() !== \"\"\n : el.type === \"checkbox\" || el.type === \"radio\"\n ? el.checked !== el.defaultChecked\n : el.tagName === \"SELECT\"\n ? [...el.options].some((option) => option.selected !== option.hasAttribute(\"selected\"))\n : el.value !== el.defaultValue\n if (changed) names.add(name)\n }\n return names\n}\n\n// Flush a pending write while the fields are still readable (Turbo\n// disconnects before leaving the page — a fast visit otherwise loses the last\n// keystrokes), then drop every listener: the closure connect() stored does both.\nexport function disconnect(controller) {\n const off = wired.get(controller)\n wired.delete(controller)\n off?.()\n}\n\n// --- The persist_state / persist_clear client ops --------------------------\n\n// A root that is still waiting for this module shows the server's blanks: an\n// op that snapshots or clears it now would destroy the draft the restore is\n// about to read. Such an op waits in the root's pending record and runs after\n// the restore (connect) — or, if the root leaves first, without one (abandon).\n// Any other root runs it at once.\nfunction whenRestored(root, op) {\n const pending = shared?.waiting.get(root)?.persist\n // (No payload: connect() will not restore this root, so nothing would ever\n // run a queued op — a morph can take the marker away while we load.)\n if (!pending || !persistPayload(root)) return op(true)\n ;(pending.ops ??= []).push(op)\n}\n\nexport function writeState(root, state) {\n whenRestored(root, (restored) => persistWriteState(root, state, restored))\n}\n\nexport function clearRoot(root) {\n whenRestored(root, () => persistClearRoot(root))\n}\n",
9
9
  "// phlex/reactive/features/form — what a form root sets up when it connects\n// and re-syncs after a morph, with no round trip: dirty tracking and the\n// navigate-away guard (issue #103), and the paste-trigger availability gate\n// (issue #228). One of the feature modules the core imports on demand (issue\n// #275); in the default client it is part of the one file.\n//\n// The two share a module because they share a shape, not a page: a marker\n// check at connect, one pass over the root's own controls, the same pass\n// again on turbo:morph-element. The gate alone is smaller than what a module\n// of its own costs the core.\n//\n// This module never imports the core: it reaches a controller through the\n// `core` handle (core.owns — is this control this root's own, issue #15).\n\n// controller -> [the removals of what connect() added, its reseed].\nconst wired = new WeakMap()\n// The turbo:before-visit events a warn_unsaved root already prompted for: one\n// prompt per visit, however many dirty roots guard the page (issue #298).\nconst askedVisits = new WeakSet()\n// window -> its guarded roots and the removal of its one listener pair.\nconst guards = new WeakMap()\n\nexport function connect(controller, core) {\n const root = controller.element\n const offs = []\n const seeds = []\n // Add a listener and keep its removal. Closures, not a record of named\n // handlers: the minifier renames a local, never a property (issue #310).\n const listen = (target, type, handler) => {\n target.addEventListener?.(type, handler)\n offs.push(() => target.removeEventListener?.(type, handler))\n }\n // Each pass below is wired once, the first time its gate reads true: here,\n // and again from reseed() — a stream can render the root's first dirty field\n // or paste trigger into it after connect (issue #356).\n let tracking\n let gating\n const wire = () => {\n // Dirty tracking (issue #103) — ONLY when this root opts in (track_dirty: or a\n // reactive_field(dirty:)), so a component that never uses it pays nothing (no\n // baseline scan, no morph listener on every broadcast). A plain (outerHTML)\n // replace re-connects the controller, so seed the baseline scan here — the root\n // reflects current-vs-default WITHOUT waiting for the first input. An in-place\n // morph / broadcast morph keeps the element CONNECTED and fires no Stimulus\n // lifecycle, so ALSO listen for turbo:morph-element on the root to re-scan\n // after the morph writes fresh default* attributes (reactive:applied is NOT a\n // valid hook — it fires when streams are handed to Turbo, BEFORE the DOM\n // mutation). Both listeners are torn down in disconnect().\n if (!tracking && (tracking = dirtyTrackingEnabled(root, core))) {\n const rescan = () => scan(controller, core)\n listen(root, \"turbo:morph-element\", rescan)\n seeds.push(rescan)\n rescan()\n\n // warn_unsaved: arm a navigate-away guard gated on a LIVE dirty-count read\n // (never a cached snapshot — the count is re-derived from the DOM each time).\n // beforeunload covers a real browser unload; turbo:before-visit covers a\n // Turbo in-app navigation (it does NOT fire on restoration visits — the\n // documented gap). Registered on window only when the marker is present.\n if (root.getAttribute?.(\"data-reactive-warn-unsaved\") === \"true\") armUnsavedGuard(root, offs)\n }\n\n // Clipboard-trigger availability gate (issue #228) — ONLY when this root\n // owns a paste trigger (on_client marks one with data-reactive-clipboard).\n // The Async Clipboard API is absent in insecure contexts and some webviews;\n // a paste button that can never work must not show. The gate OWNS a marked\n // trigger's `hidden` flag: author the trigger `hidden` and this pass reveals\n // it where the API exists (a dead button never paints); turbo:morph-element\n // re-syncs because a morph rewrites the trigger back to its authored hidden\n // state. A trigger first INTRODUCED by a later morph of a root that already\n // tracks dirtiness stays ungated (hidden) until a full replace re-connects\n // the controller; one a stream renders into the root is gated then.\n if (!gating && (gating = clipboardGateEnabled(root, core))) {\n const sync = () => syncClipboardTriggers(root, core)\n listen(root, \"turbo:morph-element\", sync)\n seeds.push(sync)\n sync()\n }\n }\n wired.set(controller, [\n offs,\n () => {\n for (const run of seeds) run()\n wire()\n },\n ])\n wire()\n}\n\n// Remove the listeners on disconnect (Turbo morph/navigation) so a morph\n// re-scan or a navigate-away guard never runs against a detached root.\nexport function disconnect(controller) {\n for (const off of wired.get(controller)?.[0] ?? []) off()\n wired.delete(controller)\n}\n\n// Re-run the passes wired at connect, then wire any whose gate reads true only\n// now — for content that changed after connect() ran (the draft restore, a\n// stream rendered into the root, issue #356).\nexport function reseed(controller) {\n wired.get(controller)?.[1]()\n}\n\n// Whether this root opts into dirty tracking (issue #103): track_dirty: puts the\n// trackDirty descriptor on the ROOT's data-action; a per-field reactive_field(\n// dirty:) puts it on a descendant field. Either turns tracking on. A quick\n// attribute read + one scoped query, evaluated once per connect (a cold path).\nfunction dirtyTrackingEnabled(root, core) {\n if ((root.getAttribute?.(\"data-action\") ?? \"\").includes(\"reactive#trackDirty\")) return true\n const nodes = root.querySelectorAll?.('[data-action*=\"reactive#trackDirty\"]') ?? []\n for (const el of nodes) if (core.owns(el)) return true\n return false\n}\n\n// Dirty tracking (issue #103). Wired by reactive_field(dirty: true) /\n// reactive_root(track_dirty: true): an `input` on an owned field runs a FULL\n// re-scan of every field this root owns (the controller's trackDirty action\n// calls this). NO round trip, NO shipped state.\n//\n// Re-compute the dirty flag for EVERY field this root owns in one pass, then\n// reflect the total onto the root. Called on an owned field's input, on\n// connect (baseline seed), and after a turbo:morph-element re-render (fresh\n// default* attrs). dirty = current ≠ the DOM's own default:\n// checkbox/radio → checked !== defaultChecked\n// select → some option.selected !== its reset state (issue #297)\n// else → value !== defaultValue\n// A full pass (not per-target) is REQUIRED: a radio group's previously-checked\n// radio flips to checked=false with NO input event, so per-target toggling\n// would leave its flag stale. File inputs are skipped — a file has no server\n// default baseline. Per-dirty-field data-reactive-dirty=\"true\" (\"true\" STRING,\n// not a valueless boolean attr — mirrors the on() flag convention); the root\n// carries data-reactive-dirty=\"<count>\" and DROPS the attr at zero, so\n// `[data-reactive-dirty]` styles the whole form and `[data-reactive-dirty]`\n// on a field styles just the changed control — both pure CSS, zero JS.\nexport function scan(controller, core) {\n const root = controller.element\n // Runs at bootstrap (the connect baseline seed) as well as on input/morph, so\n // it must never throw — degrade to a no-op if the root can't be queried (a real\n // reactive root always can; this guards minimal/test element stubs).\n if (typeof root?.querySelectorAll !== \"function\") return\n\n let count = 0\n const mark = (field, dirty) => {\n if (dirty) {\n field.setAttribute(\"data-reactive-dirty\", \"true\")\n count++\n } else {\n field.removeAttribute(\"data-reactive-dirty\")\n }\n }\n root.querySelectorAll(\"input[name], select[name], textarea[name]\").forEach((field) => {\n if (!core.owns(field)) return // skip a nested reactive root's fields (issue #15)\n if (field.type === \"file\") return // no server default baseline to diff against\n mark(field, fieldDirty(field))\n })\n // A reactive_editable (issue #351) diffs its text against the text of its\n // last server render, which the core keeps.\n root.querySelectorAll(\"[data-reactive-editable][name]\").forEach((field) => {\n if (core.owns(field)) mark(field, core.text(field) !== core.served(field))\n })\n\n if (count > 0) root.setAttribute(\"data-reactive-dirty\", String(count))\n else root.removeAttribute(\"data-reactive-dirty\")\n}\n\n// Whether a single owned control differs from its server-rendered default.\nfunction fieldDirty(field) {\n if (field.type === \"checkbox\" || field.type === \"radio\") {\n return field.checked !== field.defaultChecked\n }\n if (field.tag === \"select\" || field.options) {\n // Any option whose selected state diverges from the select's RESET state.\n // Guard for a stub/absent options list (degrade to clean). A one-row single\n // select resets to its last defaultSelected option or, with none, to its\n // first enabled one — the browser selects it while its defaultSelected stays\n // false, so a pristine form must not read as dirty (issue #297). A multiple\n // (or size > 1) select resets to exactly its defaultSelected options. An\n // option inside a disabled <optgroup> is disabled too (the browser skips it).\n const options = Array.from(field.options ?? [])\n const single = !field.multiple && !(field.size > 1)\n const reset = options.filter((o) => o.defaultSelected).pop() ?? options.find((o) => !o.closest?.(\"optgroup\")?.disabled && !o.disabled)\n return options.some((o) => o.selected !== (single ? o === reset : o.defaultSelected))\n }\n return field.value !== field.defaultValue\n}\n\n// The live dirty-field count, re-derived from the DOM (never a cached snapshot)\n// — the source of truth for the warn_unsaved guard's gate.\nfunction dirtyCount(root) {\n const raw = root.getAttribute?.(\"data-reactive-dirty\")\n const n = Number(raw)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n// Arm the navigate-away guard (warn_unsaved: true, issue #103). beforeunload\n// blocks a real browser unload; turbo:before-visit blocks a Turbo in-app\n// navigation (it does NOT fire on restoration visits — the documented gap).\n// Both read the LIVE dirty count, so a clean form never blocks.\n//\n// One listener pair per window serves every guarded root on it: a pair per\n// root made connecting and disconnecting N guarded forms quadratic (the\n// browser scans a target's listeners on each add and remove). The pair is\n// added with the first guarded root and removed with the last, so a page\n// without one carries no beforeunload listener. The root leaves the set\n// through `offs`, which disconnect() runs.\nfunction armUnsavedGuard(root, offs) {\n if (typeof window === \"undefined\" || typeof window.addEventListener !== \"function\") return\n\n const win = window\n let guard = guards.get(win)\n if (!guard) {\n const roots = new Set()\n const dirtyRoot = () => {\n for (const guarded of roots) if (dirtyCount(guarded) > 0) return guarded\n return null\n }\n const beforeunload = (event) => {\n if (!dirtyRoot()) return undefined\n // The spec dance: preventDefault + a truthy returnValue triggers the native\n // \"leave site?\" prompt. The string is legacy (modern browsers show their own\n // copy) but must be non-empty/truthy to arm the dialog.\n event.preventDefault()\n event.returnValue = \"You have unsaved changes.\"\n return event.returnValue\n }\n // One visit asks once (issue #298), and only when a guarded root is dirty.\n // askedVisits still matters when two copies of this module (a bundled one\n // beside the pinned one) each hold a pair.\n const beforeVisit = (event) => {\n if (askedVisits.has(event) || !dirtyRoot()) return\n askedVisits.add(event)\n const ok = typeof win.confirm === \"function\" ? win.confirm(\"You have unsaved changes. Leave anyway?\") : true\n if (!ok) event.preventDefault?.()\n }\n win.addEventListener(\"beforeunload\", beforeunload)\n win.addEventListener(\"turbo:before-visit\", beforeVisit)\n guard = {\n roots,\n remove: () => {\n win.removeEventListener?.(\"beforeunload\", beforeunload)\n win.removeEventListener?.(\"turbo:before-visit\", beforeVisit)\n guards.delete(win)\n },\n }\n guards.set(win, guard)\n }\n guard.roots.add(root)\n offs.push(() => {\n guard.roots.delete(root)\n if (guard.roots.size === 0) guard.remove()\n })\n}\n\n// Whether this root owns a clipboard-marked paste trigger (issue #228). The\n// ROOT itself counts (a button-only component that mixes on_client(paste_into)\n// onto reactive_root), then one scoped query; a NESTED root's triggers are\n// its own controller's to gate (issue #15 ownership).\nfunction clipboardGateEnabled(root, core) {\n if (root.getAttribute?.(\"data-reactive-clipboard\")) return true\n const nodes = root.querySelectorAll?.(\"[data-reactive-clipboard]\") ?? []\n for (const el of nodes) if (core.owns(el)) return true\n return false\n}\n\n// Set every owned paste trigger's `hidden` from clipboard availability\n// (issue #228): available → revealed (the authored `hidden` was only the\n// no-dead-button first paint), missing → hidden (insecure context /\n// webview). The gate owns the flag on MARKED elements only — nothing else\n// is ever touched. A marked ROOT is gated too: when the component IS the\n// paste button, hiding the root is exactly \"the dead button never shows\".\nfunction syncClipboardTriggers(root, core) {\n const available = typeof globalThis.navigator?.clipboard?.readText === \"function\"\n if (root.getAttribute?.(\"data-reactive-clipboard\")) root.hidden = !available\n for (const el of root.querySelectorAll?.(\"[data-reactive-clipboard]\") ?? []) {\n if (core.owns(el)) el.hidden = !available\n }\n}\n",
@@ -17,7 +17,7 @@
17
17
  "// phlex/reactive/features/countdown — a deadline counted down on the client\n// (issue #400). One of the feature modules the core imports on demand (issue\n// #275); in the default client it is part of the one file.\n//\n// The markup is the Ruby side's (reactive_countdown):\n//\n// data-reactive-countdown='{\"until\":\"<ISO8601>\",\"format\":\"ms\",\"waiting\":\"#wait\",\"done\":\"#done\"}'\n//\n// Every tick reads Date.now against the deadline, so a late tick (a throttled\n// background tab, a slept laptop) paints the real remaining time, never a\n// count of missed ticks; a tab that becomes visible again re-reads at once.\n// The text is unpadded minutes, a colon and zero-padded seconds (\"1:30\"),\n// written as textContent only. The next tick is set for the moment the shown\n// second changes.\n//\n// At zero (or with the deadline already past on connect, which starts no\n// timer) the text is \"0:00\", data-reactive-countdown-state is \"done\", the\n// waiting: node hides, the done: node shows, and the element dispatches\n// reactive:countdown-done (bubbling) once. \"Once\" is per root id (a root\n// without one is its own element), countdown (its id, else its place in the\n// root) and deadline, kept for the life of the document: a morph or a replace\n// that keeps the deadline, or brings back one that already fired, paints the\n// done state again without a second event; a new deadline counts down afresh.\n// The countdown's content is its text: waiting: and done: are nodes beside it,\n// so a root that is itself the countdown has none.\n// No request, no frame reload: the page decides what the event does.\n//\n// This module never imports the core: it reaches a controller through the\n// `core` handle (core.owns).\n\nconst MARK = \"data-reactive-countdown\"\nconst STATE = \"data-reactive-countdown-state\"\n\n// \"<root id>|<countdown key>\" -> every deadline it already dispatched for.\nconst finished = new Map()\n// A root without an id: a number of its own, so two never share a key.\nconst anonymous = new WeakMap()\nlet anonymousSeq = 0\n// controller -> the removal of what connect() added.\nconst wired = new WeakMap()\n\nexport function connect(controller, core) {\n const root = controller.element\n if (!root.id && !anonymous.has(root)) anonymous.set(root, `#${++anonymousSeq}`)\n const rootKey = root.id || anonymous.get(root)\n // countdown element -> its pending timer.\n const timers = new Map()\n let queued = false\n\n const clear = (el) => {\n clearTimeout(timers.get(el))\n timers.delete(el)\n }\n\n const tick = (el, wire, key) => {\n clear(el)\n const left = Date.parse(wire.until) - Date.now()\n if (!(left > 0)) return finish(el, wire, key)\n const seconds = Math.ceil(left / 1000)\n paint(el, `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`, \"running\")\n show(wire.waiting, true)\n show(wire.done, false)\n timers.set(\n el,\n setTimeout(() => tick(el, wire, key), ((left - 1) % 1000) + 1),\n )\n }\n\n const finish = (el, wire, key) => {\n paint(el, \"0:00\", \"done\")\n show(wire.waiting, false)\n show(wire.done, true)\n const fired = finished.get(key) ?? new Set()\n if (fired.has(wire.until)) return\n finished.set(key, fired.add(wire.until))\n el.dispatchEvent(new CustomEvent(\"reactive:countdown-done\", { bubbles: true, detail: { until: wire.until } }))\n }\n\n // A selector that is not valid CSS is ignored, never a stopped clock.\n const show = (selector, visible) => {\n let node\n try {\n node = selector && root.querySelector(selector)\n } catch {}\n if (node && node.hidden === visible) node.hidden = !visible\n }\n\n // Every countdown this root owns, from scratch: a morph may have changed a\n // deadline, written the server's text back, or removed a countdown.\n const sync = () => {\n queued = false\n // A morph that also removed the root: disconnect ran first.\n if (!wired.has(controller)) return\n const seen = new Set()\n const els = [...(root.matches(`[${MARK}]`) ? [root] : []), ...root.querySelectorAll(`[${MARK}]`)]\n els.forEach((el, index) => {\n if (!core.owns(el)) return\n let wire\n try {\n wire = JSON.parse(el.getAttribute(MARK))\n } catch {\n return\n }\n if (Number.isNaN(Date.parse(wire?.until))) return\n seen.add(el)\n tick(el, wire, `${rootKey}|${el.id || index}`)\n })\n for (const el of timers.keys()) if (!seen.has(el)) clear(el)\n }\n\n // A morph of the root or of anything in it (turbo:morph-element bubbles,\n // once per morphed element), a stream rendered into it, a tab woken up:\n // one sync for all of them, after the morph is done.\n const later = () => {\n if (queued) return\n queued = true\n queueMicrotask(sync)\n }\n const woke = () => document.visibilityState === \"visible\" && sync()\n root.addEventListener(\"turbo:morph-element\", later)\n root.addEventListener(\"reactive:streamed\", later)\n document.addEventListener(\"visibilitychange\", woke)\n wired.set(controller, () => {\n root.removeEventListener(\"turbo:morph-element\", later)\n root.removeEventListener(\"reactive:streamed\", later)\n document.removeEventListener(\"visibilitychange\", woke)\n for (const el of [...timers.keys()]) clear(el)\n })\n sync()\n}\n\nexport function disconnect(controller) {\n wired.get(controller)?.()\n wired.delete(controller)\n}\n\nfunction paint(el, text, state) {\n if (el.textContent !== text) el.textContent = text\n if (el.getAttribute(STATE) !== state) el.setAttribute(STATE, state)\n}\n",
18
18
  "// phlex/reactive/reactive_controller — the DEFAULT client: ONE file with the\n// whole runtime in it. This is what `import ReactiveController from\n// \"phlex/reactive/reactive_controller\"` has always given an app, and what the\n// install generator wires up.\n//\n// The client's source is a shared runtime (runtime.js: the controller) plus\n// feature modules (features/*.js, issue #275). In this entry every feature is\n// there before the controller can connect anything — the shipped file is\n// built with __SPLIT__ false, and the runtime imports each one statically and\n// calls it directly (issue #305) — so:\n//\n// * nothing is imported on demand — no request for a feature, ever;\n// * every feature a root needs connects inside connect(), in the same task,\n// in table order — a draft is restored there, a lazy shell armed there;\n// * `featuresReady` is already resolved, no request waits for a feature,\n// and the import timeout can never fire.\n//\n// In short: it behaves as the client did before it was split. The shipped\n// reactive_controller.min.js is this module BUNDLED with the runtime and the\n// features (scripts/build_client.js). It contains no import() and no feature\n// table at all: those belong to the other entry. The seams an app may override stay\n// separate modules, imported by their bare names exactly as before:\n// phlex/reactive/confirm, phlex/reactive/confirm_predicate, phlex/reactive/compute.\n//\n// The opt-in alternative is phlex/reactive/core (core.js): the same runtime\n// without the features, which it then imports when a root on the page needs one. An\n// app imports ONE of the two, never both — each carries its own copy of the\n// runtime's state, and the second to load says so in the console.\nimport ReactiveController, { registerReactiveDev, registerReactiveFeature } from \"phlex/reactive/runtime\"\nimport * as persist from \"phlex/reactive/features/persist\"\nimport * as defer from \"phlex/reactive/features/defer\"\nimport * as form from \"phlex/reactive/features/form\"\nimport * as bindings from \"phlex/reactive/features/bindings\"\nimport * as compute from \"phlex/reactive/features/compute\"\nimport * as sortable from \"phlex/reactive/features/sortable\"\nimport * as drag from \"phlex/reactive/features/drag\"\nimport * as presence from \"phlex/reactive/features/presence\"\nimport * as countdown from \"phlex/reactive/features/countdown\"\nimport * as effects from \"phlex/reactive/features/effects\"\nimport * as hints from \"phlex/reactive/features/hints\"\nimport * as devtools from \"phlex/reactive/features/devtools\"\n\n// The shipped file is built with __SPLIT__ false (scripts/build_client.js):\n// the runtime then imports every feature itself and calls it directly, and\n// this hand-over folds away with the table it would fill (issue #305). With\n// __SPLIT__ true — the JS suite's default, where this entry and core.js share\n// one runtime — it hands each feature over, as below.\nif (__SPLIT__) {\n // Table order is the runtime's (persist first); this only supplies the\n // features — for each, a plain object of exactly what the runtime calls, so\n // the bundler can drop the rest of the module's exports (and the module\n // namespace object itself).\n registerReactiveFeature(\"persist\", { install: persist.install, connect: persist.connect, disconnect: persist.disconnect, abandon: persist.abandon, writeState: persist.writeState, clearRoot: persist.clearRoot })\n registerReactiveFeature(\"defer\", { install: defer.install, connect: defer.connect, disconnect: defer.disconnect, streamAction: defer.streamAction, materialize: defer.materialize })\n registerReactiveFeature(\"form\", { connect: form.connect, disconnect: form.disconnect, scan: form.scan, reseed: form.reseed })\n registerReactiveFeature(\"bindings\", {\n connect: bindings.connect,\n disconnect: bindings.disconnect,\n reseed: bindings.reseed,\n tagsAdd: bindings.tagsAdd,\n tagsPick: bindings.tagsPick,\n tagsRemove: bindings.tagsRemove,\n nestedAdd: bindings.nestedAdd,\n nestedRemove: bindings.nestedRemove,\n syncNestedJson: bindings.syncNestedJson,\n confirmMessage: bindings.confirmMessage,\n checkGroup: bindings.checkGroup,\n })\n registerReactiveFeature(\"compute\", { connect: compute.connect, disconnect: compute.disconnect, seed: compute.seed, recompute: compute.recompute })\n registerReactiveFeature(\"sortable\", { connect: sortable.connect, disconnect: sortable.disconnect })\n registerReactiveFeature(\"drag\", { connect: drag.connect, disconnect: drag.disconnect })\n registerReactiveFeature(\"presence\", { connect: presence.connect, disconnect: presence.disconnect, set: presence.set })\n registerReactiveFeature(\"countdown\", { connect: countdown.connect, disconnect: countdown.disconnect })\n registerReactiveFeature(\"effects\", { wrap: effects.wrap, sweep: effects.sweep })\n registerReactiveFeature(\"hints\", { optimistic: hints.optimistic, busy: hints.busy, resurrection: hints.resurrection })\n registerReactiveFeature(\"devtools\", {\n attach: devtools.attach,\n delay: devtools.delay,\n diagnose: devtools.diagnose,\n noBinding: devtools.noBinding,\n diagnoseStream: devtools.diagnoseStream,\n missingRoot: devtools.missingRoot,\n recordBody: devtools.recordBody,\n trace: devtools.trace,\n })\n}\n// The runtime registered with Turbo while it was being evaluated, before the\n// dev module was handed over: give a development page its console handle now, in\n// this task, as it always was.\nregisterReactiveDev()\n\nexport * from \"phlex/reactive/runtime\"\n// The latency simulator's named exports (issue #102), where they have always\n// been importable from. With phlex/reactive/core, import them from\n// phlex/reactive/features/devtools.\nexport { enableLatencySim, disableLatencySim, LATENCY_KEY } from \"phlex/reactive/features/devtools\"\nexport default ReactiveController\n"
19
19
  ],
20
- "mappings": "AAAA,qBAAS,4BAWT,0BAAS,gCCaT,2BAAS,0CAOT,IAAM,EAAW,IAAI,QAGf,GAAe,IAAI,QAEzB,SAAS,CAAG,CAAC,EAAY,EAAM,CAC7B,IAAI,EAAI,EAAS,IAAI,CAAU,EAC/B,GAAI,CAAC,GAEH,GADA,EAAS,IAAI,EAAa,EAAI,CAAE,KAAM,EAAW,QAAS,OAAM,YAAa,CAAE,CAAE,EAC7E,EAAE,KAAM,GAAa,IAAI,EAAE,KAAM,CAAC,EAExC,OAAO,EAKT,SAAS,CAAM,CAAC,EAAG,EAAO,EAAS,CACjC,QAAW,KAAQ,EAAM,MAAM,GAAG,EAChC,EAAE,KAAK,mBAAmB,EAAM,CAAO,EACvC,EAAE,KAAK,KAAK,IAAM,EAAE,KAAK,sBAAsB,EAAM,CAAO,CAAC,EAMjE,SAAS,CAAI,CAAC,EAAG,EAAK,CACpB,EAAO,EAAG,sBAAuB,CAAG,EACpC,EAAE,MAAM,KAAK,CAAG,EAChB,EAAI,EAGC,SAAS,EAAO,CAAC,EAAY,EAAM,CACxC,IAAM,EAAI,EAAI,EAAY,CAAI,EAC9B,EAAE,KAAO,CAAC,EACV,EAAE,MAAQ,CAAC,EAIX,IAAI,EACA,EACA,EACA,GACF,EAAE,KAAO,IAAM,CAUf,GAAI,CAAC,EAAE,MAAQ,GAAgB,CAAC,EAO9B,EAAE,KAAO,CAAC,IAAU,CAClB,GAAI,EAAE,SAAU,OAGhB,GAAI,GAAO,OAAS,SAAW,GAAO,OAAS,SAAU,GAAU,EAAG,EAAM,MAAM,EAKhF,OAAE,OA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