phlex-reactive 0.14.3 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +107 -0
- data/README.md +258 -5
- data/app/controllers/phlex/reactive/actions_controller.rb +28 -18
- data/app/javascript/phlex/reactive/core.js +7 -1
- data/app/javascript/phlex/reactive/core.min.js +6 -2
- data/app/javascript/phlex/reactive/core.min.js.map +4 -4
- data/app/javascript/phlex/reactive/early.js +28 -9
- data/app/javascript/phlex/reactive/early.min.js +2 -2
- data/app/javascript/phlex/reactive/early.min.js.map +3 -3
- data/app/javascript/phlex/reactive/features/bindings.js +188 -107
- data/app/javascript/phlex/reactive/features/bindings.min.js +2 -2
- data/app/javascript/phlex/reactive/features/bindings.min.js.map +3 -3
- data/app/javascript/phlex/reactive/features/form.js +75 -46
- data/app/javascript/phlex/reactive/features/form.min.js +2 -2
- data/app/javascript/phlex/reactive/features/form.min.js.map +3 -3
- data/app/javascript/phlex/reactive/features/persist.js +12 -3
- data/app/javascript/phlex/reactive/features/persist.min.js +2 -2
- data/app/javascript/phlex/reactive/features/persist.min.js.map +3 -3
- data/app/javascript/phlex/reactive/features/presence.js +205 -0
- data/app/javascript/phlex/reactive/features/presence.min.js +4 -0
- data/app/javascript/phlex/reactive/features/presence.min.js.map +10 -0
- data/app/javascript/phlex/reactive/features/sortable.js +463 -0
- data/app/javascript/phlex/reactive/features/sortable.min.js +4 -0
- data/app/javascript/phlex/reactive/features/sortable.min.js.map +10 -0
- data/app/javascript/phlex/reactive/inspect.js +5 -1
- data/app/javascript/phlex/reactive/inspect.min.js +2 -2
- data/app/javascript/phlex/reactive/inspect.min.js.map +3 -3
- data/app/javascript/phlex/reactive/reactive_controller.js +5 -1
- data/app/javascript/phlex/reactive/reactive_controller.min.js +6 -2
- data/app/javascript/phlex/reactive/reactive_controller.min.js.map +10 -8
- data/app/javascript/phlex/reactive/runtime.js +286 -18
- data/lib/phlex/reactive/component/dsl.rb +5 -0
- data/lib/phlex/reactive/component/editable.rb +78 -0
- data/lib/phlex/reactive/component/helpers.rb +81 -8
- data/lib/phlex/reactive/component/presence_declaration.rb +118 -0
- data/lib/phlex/reactive/component/registry.rb +3 -1
- data/lib/phlex/reactive/component/sortable.rb +212 -0
- data/lib/phlex/reactive/component.rb +1 -0
- data/lib/phlex/reactive/defer.rb +5 -0
- data/lib/phlex/reactive/engine.rb +9 -4
- data/lib/phlex/reactive/js.rb +24 -0
- data/lib/phlex/reactive/presence/component_methods.rb +130 -0
- data/lib/phlex/reactive/presence/roster.rb +90 -0
- data/lib/phlex/reactive/presence/transport.rb +154 -0
- data/lib/phlex/reactive/presence.rb +162 -0
- data/lib/phlex/reactive/presence_render_job.rb +26 -0
- data/lib/phlex/reactive/shortcut.rb +105 -0
- data/lib/phlex/reactive/streamable.rb +7 -3
- data/lib/phlex/reactive/version.rb +1 -1
- data/lib/phlex/reactive.rb +10 -0
- metadata +16 -1
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["features/persist.js"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"// 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\"]}'\n// keeps a localStorage 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\nfunction persistStorage() {\n try {\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()\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()\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()\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// 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 = el.textContent ?? \"\"\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 && (el.textContent ?? \"\").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// 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 document.addEventListener?.(\"turbo:submit-end\", 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 document.removeEventListener?.(\"turbo:submit-end\", onSubmitEnd)\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.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"
|
|
5
|
+
"// 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\"]}'\n// keeps a localStorage 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\nfunction persistStorage() {\n try {\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()\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()\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()\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// 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 document.addEventListener?.(\"turbo:submit-end\", 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 document.removeEventListener?.(\"turbo:submit-end\", onSubmitEnd)\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"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "AAiDA,IAAI,EAEG,SAAS,EAAO,CAAC,EAAO,CAC7B,EAAS,EAGX,I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,EAUR,SAAS,CAAY,CAAC,EAAM,EAAI,CAC9B,IAAM,EAAU,GAAQ,QAAQ,IAAI,CAAI,GAAG,QAG3C,GAAI,CAAC,GAAW,CAAC,EAAe,CAAI,EAAG,OAAO,EAAG,EAAI,GACnD,EAAQ,MAAQ,CAAC,GAAG,KAAK,CAAE,EAGxB,SAAS,EAAU,CAAC,EAAM,EAAO,CACtC,EAAa,EAAM,CAAC,IAAa,EAAkB,EAAM,EAAO,CAAQ,CAAC,EAGpE,SAAS,EAAS,CAAC,EAAM,CAC9B,EAAa,EAAM,IAAM,EAAiB,CAAI,CAAC",
|
|
8
|
+
"debugId": "C200972FABEC142364756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// phlex/reactive/features/presence — who is viewing a stream, one seat per
|
|
2
|
+
// tab (issue #358). One of the feature modules the core imports on demand
|
|
3
|
+
// (issue #275); in the default client it is part of the one file.
|
|
4
|
+
//
|
|
5
|
+
// The markup is the Ruby side's (reactive_presence and its helpers):
|
|
6
|
+
//
|
|
7
|
+
// data-reactive-presence="<signed src>" the roster root; its stream
|
|
8
|
+
// data-reactive-presence-roster="<seats>" on the root: the seats rendered
|
|
9
|
+
// data-reactive-presence-peer="<seat>" a tab's element
|
|
10
|
+
// data-reactive-presence-member="<id>" a person's (or a tab's) element
|
|
11
|
+
//
|
|
12
|
+
// and what this module sets, for the app's CSS, after the first paint and
|
|
13
|
+
// after every morph of the root:
|
|
14
|
+
//
|
|
15
|
+
// data-reactive-presence-me this tab's own peer element
|
|
16
|
+
// data-reactive-presence-same-member this person's other elements
|
|
17
|
+
//
|
|
18
|
+
// The roster is rendered ONCE for every viewer (one broadcast), so the server
|
|
19
|
+
// cannot say which row is "me": the module does, from the tab's seat.
|
|
20
|
+
//
|
|
21
|
+
// The subscription. The root carries its presence stream's signed src; the
|
|
22
|
+
// module mints a <pgbus-stream-source presence> for it in <body>, with a
|
|
23
|
+
// deterministic id (reactive-presence-src-<root id>), as the defer push lane
|
|
24
|
+
// mints its one-shot source. pgbus's element mints the tab's seat (one per
|
|
25
|
+
// document), sends it as ?seat= and exposes it as element.pgbusSeat: the
|
|
26
|
+
// transport stores it on the tab's presence row, a reconnect (a new
|
|
27
|
+
// connection id) keeps it, and this module reads it to find "me". A plain
|
|
28
|
+
// replace of the root disconnects and
|
|
29
|
+
// reconnects the controller: the source is removed only a microtask after a
|
|
30
|
+
// disconnect, and kept when the same root id comes back.
|
|
31
|
+
//
|
|
32
|
+
// Announcing. On every pgbus:connected (the first one and each reconnect) the
|
|
33
|
+
// module sends presence_set with the tab's last state ({} at first), through
|
|
34
|
+
// the root's own pipeline (core.proceed): the signed token, the typed state,
|
|
35
|
+
// the request queue. That write puts the tab on the roster for everyone (and
|
|
36
|
+
// the actor's own reply shows it), and a reconnect, which is a fresh row with
|
|
37
|
+
// no state, gets its state back. The runtime sends the source's connection id
|
|
38
|
+
// as X-Reactive-Presence, so the write lands on this tab's row.
|
|
39
|
+
//
|
|
40
|
+
// Events. The module keeps the seats it last saw in the root (the root's
|
|
41
|
+
// data-reactive-presence-roster list); when a morph changes them it dispatches
|
|
42
|
+
// reactive:presence on the root with { joined, left, me } — from the DOM, so a
|
|
43
|
+
// replayed frame that changes nothing fires nothing.
|
|
44
|
+
//
|
|
45
|
+
// This module never imports the core: it reaches a controller through the
|
|
46
|
+
// `core` handle (core.proceed, core.emit).
|
|
47
|
+
|
|
48
|
+
const SOURCE = "reactive-presence-src-"
|
|
49
|
+
const PEER = "data-reactive-presence-peer"
|
|
50
|
+
const MEMBER = "data-reactive-presence-member"
|
|
51
|
+
const ROSTER = "data-reactive-presence-roster"
|
|
52
|
+
|
|
53
|
+
// root id -> { root, core, state, seats, removing, off }: what a root's
|
|
54
|
+
// connection left behind, kept across a replace of the root.
|
|
55
|
+
const roots = new Map()
|
|
56
|
+
// The sources this module minted and listens to (a Turbo cache restore brings
|
|
57
|
+
// back a clone without the listener).
|
|
58
|
+
const minted = new WeakSet()
|
|
59
|
+
|
|
60
|
+
export function connect(controller, core) {
|
|
61
|
+
const root = controller.element
|
|
62
|
+
let entry = roots.get(root.id)
|
|
63
|
+
if (!entry) roots.set(root.id, (entry = { state: null, seats: null }))
|
|
64
|
+
entry.root = root
|
|
65
|
+
entry.core = core
|
|
66
|
+
entry.removing = false
|
|
67
|
+
subscribe(root)
|
|
68
|
+
const morphed = (event) => event.target === root && queueMicrotask(() => paint(entry))
|
|
69
|
+
// A failed announce (a network error, a 5xx) leaves the tab's row without
|
|
70
|
+
// its note and state until the next js.presence or reconnect: say so.
|
|
71
|
+
const failed = (event) =>
|
|
72
|
+
event.target === root &&
|
|
73
|
+
event.detail?.action === "presence_set" &&
|
|
74
|
+
console.error(`[phlex-reactive] #${root.id}: its presence_set request failed`, event.detail)
|
|
75
|
+
root.addEventListener("turbo:morph-element", morphed)
|
|
76
|
+
root.addEventListener("reactive:error", failed)
|
|
77
|
+
entry.off = () => {
|
|
78
|
+
root.removeEventListener("turbo:morph-element", morphed)
|
|
79
|
+
root.removeEventListener("reactive:error", failed)
|
|
80
|
+
}
|
|
81
|
+
paint(entry)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function disconnect(controller) {
|
|
85
|
+
const root = controller.element
|
|
86
|
+
const entry = roots.get(root.id)
|
|
87
|
+
if (!entry || entry.root !== root) return
|
|
88
|
+
entry.off()
|
|
89
|
+
entry.removing = true
|
|
90
|
+
queueMicrotask(() => {
|
|
91
|
+
if (!entry.removing) return
|
|
92
|
+
roots.delete(root.id)
|
|
93
|
+
root.ownerDocument.getElementById(SOURCE + root.id)?.remove()
|
|
94
|
+
})
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// js.presence(**state): merge into the tab's state and send it. Before the
|
|
98
|
+
// tab has a connection the state waits for the announce on connect.
|
|
99
|
+
export function set(root, state) {
|
|
100
|
+
if (!root?.hasAttribute?.("data-reactive-presence")) {
|
|
101
|
+
console.warn("[phlex-reactive] js.presence ran outside a reactive_presence root — ignored")
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
let entry = roots.get(root.id)
|
|
105
|
+
if (!entry) roots.set(root.id, (entry = { root, state: null, seats: null }))
|
|
106
|
+
entry.state = { ...entry.state, ...state }
|
|
107
|
+
send(entry)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function subscribe(root) {
|
|
111
|
+
const id = SOURCE + root.id
|
|
112
|
+
const found = document.getElementById(id)
|
|
113
|
+
if (found && minted.has(found)) return
|
|
114
|
+
found?.remove()
|
|
115
|
+
// pgbus's client is an async module script, so this controller can connect
|
|
116
|
+
// before <pgbus-stream-source> is defined: mint the element anyway (it
|
|
117
|
+
// upgrades when pgbus defines it), and call a still-missing client a
|
|
118
|
+
// misconfiguration only after a grace period.
|
|
119
|
+
if (!defined()) {
|
|
120
|
+
setTimeout(() => {
|
|
121
|
+
if (!defined()) {
|
|
122
|
+
console.error(
|
|
123
|
+
"[phlex-reactive] reactive_presence needs the pgbus client (<pgbus-stream-source>) on this page — " +
|
|
124
|
+
`#${root.id} is not subscribed to its presence stream`,
|
|
125
|
+
)
|
|
126
|
+
}
|
|
127
|
+
}, 5000)
|
|
128
|
+
}
|
|
129
|
+
const source = document.createElement("pgbus-stream-source")
|
|
130
|
+
source.id = id
|
|
131
|
+
source.setAttribute("src", root.getAttribute("data-reactive-presence"))
|
|
132
|
+
source.setAttribute("presence", "")
|
|
133
|
+
source.hidden = true
|
|
134
|
+
source.addEventListener("pgbus:connected", () => {
|
|
135
|
+
const entry = roots.get(root.id)
|
|
136
|
+
if (!entry || entry.removing) return
|
|
137
|
+
send(entry)
|
|
138
|
+
check(entry)
|
|
139
|
+
})
|
|
140
|
+
minted.add(source)
|
|
141
|
+
document.body.appendChild(source)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const defined = () => !!globalThis.customElements?.get?.("pgbus-stream-source")
|
|
145
|
+
|
|
146
|
+
// pgbus fires pgbus:connected only after the tab's seat has joined, so the
|
|
147
|
+
// announce lands on its row. A tab still off its roster a moment later has no
|
|
148
|
+
// identity (pgbus joins an anonymous connection to nothing), or its announce
|
|
149
|
+
// failed: say so once. No retry (an accepted risk).
|
|
150
|
+
function check(entry) {
|
|
151
|
+
clearTimeout(entry.timer)
|
|
152
|
+
entry.timer = setTimeout(() => {
|
|
153
|
+
const root = entry.root
|
|
154
|
+
if (entry.removing || !root.isConnected) return
|
|
155
|
+
const mine = root.ownerDocument.getElementById(SOURCE + root.id)?.pgbusSeat
|
|
156
|
+
if (mine && seatsOf(root).has(mine)) return
|
|
157
|
+
console.warn(
|
|
158
|
+
`[phlex-reactive] #${root.id} never appeared on its presence roster: config.streams_authorize ` +
|
|
159
|
+
"returned no identity for this stream, or its presence_set request failed (logged above)",
|
|
160
|
+
)
|
|
161
|
+
}, 2500)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Send the tab's state through presence_set — only once the source has a
|
|
165
|
+
// connection (the row the write lands on). Until then the announce on
|
|
166
|
+
// pgbus:connected sends it.
|
|
167
|
+
function send(entry) {
|
|
168
|
+
const root = entry.root
|
|
169
|
+
if (!entry.core || !root.ownerDocument.getElementById(SOURCE + root.id)?.getAttribute("connection-id")) return
|
|
170
|
+
entry.core.proceed(root, "presence_set", JSON.stringify(entry.state ?? {}))
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// The seats the root's render saw: the list the server names on the root
|
|
174
|
+
// (data-reactive-presence-roster: a template need not render an element per
|
|
175
|
+
// tab), or, without it, the tabs' own elements.
|
|
176
|
+
function seatsOf(root) {
|
|
177
|
+
const named = root.getAttribute(ROSTER)
|
|
178
|
+
if (named != null) return new Set(named.split(" ").filter(Boolean))
|
|
179
|
+
return new Set([...root.querySelectorAll(`[${PEER}]`)].map((el) => el.getAttribute(PEER)))
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Mark "me" and this person's other elements, then report the seats that
|
|
183
|
+
// joined or left since the last paint.
|
|
184
|
+
function paint(entry) {
|
|
185
|
+
const root = entry.root
|
|
186
|
+
// The seat pgbus's element minted (undefined on a pgbus without seats).
|
|
187
|
+
const mine = root.ownerDocument.getElementById(SOURCE + root.id)?.pgbusSeat
|
|
188
|
+
const marked = root.querySelectorAll(`[${PEER}],[${MEMBER}]`)
|
|
189
|
+
const seats = seatsOf(root)
|
|
190
|
+
let member
|
|
191
|
+
for (const el of marked) {
|
|
192
|
+
if (el.getAttribute(PEER) === mine) member = el.getAttribute(MEMBER)
|
|
193
|
+
}
|
|
194
|
+
for (const el of marked) {
|
|
195
|
+
const me = el.getAttribute(PEER) === mine
|
|
196
|
+
el.toggleAttribute("data-reactive-presence-me", me)
|
|
197
|
+
el.toggleAttribute("data-reactive-presence-same-member", !me && member != null && el.getAttribute(MEMBER) === member)
|
|
198
|
+
}
|
|
199
|
+
const before = entry.seats
|
|
200
|
+
entry.seats = seats
|
|
201
|
+
if (!before) return
|
|
202
|
+
const joined = [...seats].filter((s) => !before.has(s))
|
|
203
|
+
const left = [...before].filter((s) => !seats.has(s))
|
|
204
|
+
if (joined.length || left.length) entry.core.emit("reactive:presence", { joined, left, me: mine ?? null })
|
|
205
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var c=new Map,m=new WeakSet;function h(t,r){let e=t.element,n=c.get(e.id);if(!n)c.set(e.id,n={state:null,seats:null});n.root=e,n.core=r,n.removing=!1,b(e);let o=(i)=>i.target===e&&queueMicrotask(()=>p(n)),a=(i)=>i.target===e&&i.detail?.action==="presence_set"&&console.error(`[phlex-reactive] #${e.id}: its presence_set request failed`,i.detail);e.addEventListener("turbo:morph-element",o),e.addEventListener("reactive:error",a),n.off=()=>{e.removeEventListener("turbo:morph-element",o),e.removeEventListener("reactive:error",a)},p(n)}function R(t){let r=t.element,e=c.get(r.id);if(!e||e.root!==r)return;e.off(),e.removing=!0,queueMicrotask(()=>{if(!e.removing)return;c.delete(r.id),r.ownerDocument.getElementById("reactive-presence-src-"+r.id)?.remove()})}function S(t,r){if(!t?.hasAttribute?.("data-reactive-presence")){console.warn("[phlex-reactive] js.presence ran outside a reactive_presence root — ignored");return}let e=c.get(t.id);if(!e)c.set(t.id,e={root:t,state:null,seats:null});e.state={...e.state,...r},g(e)}function b(t){let r="reactive-presence-src-"+t.id,e=document.getElementById(r);if(e&&m.has(e))return;if(e?.remove(),!f())setTimeout(()=>{if(!f())console.error("[phlex-reactive] reactive_presence needs the pgbus client (<pgbus-stream-source>) on this page — "+`#${t.id} is not subscribed to its presence stream`)},5000);let n=document.createElement("pgbus-stream-source");n.id=r,n.setAttribute("src",t.getAttribute("data-reactive-presence")),n.setAttribute("presence",""),n.hidden=!0,n.addEventListener("pgbus:connected",()=>{let o=c.get(t.id);if(!o||o.removing)return;g(o),v(o)}),m.add(n),document.body.appendChild(n)}var f=()=>!!globalThis.customElements?.get?.("pgbus-stream-source");function v(t){clearTimeout(t.timer),t.timer=setTimeout(()=>{let r=t.root;if(t.removing||!r.isConnected)return;let e=r.ownerDocument.getElementById("reactive-presence-src-"+r.id)?.pgbusSeat;if(e&&E(r).has(e))return;console.warn(`[phlex-reactive] #${r.id} never appeared on its presence roster: config.streams_authorize returned no identity for this stream, or its presence_set request failed (logged above)`)},2500)}function g(t){let r=t.root;if(!t.core||!r.ownerDocument.getElementById("reactive-presence-src-"+r.id)?.getAttribute("connection-id"))return;t.core.proceed(r,"presence_set",JSON.stringify(t.state??{}))}function E(t){let r=t.getAttribute("data-reactive-presence-roster");if(r!=null)return new Set(r.split(" ").filter(Boolean));return new Set([...t.querySelectorAll("[data-reactive-presence-peer]")].map((e)=>e.getAttribute("data-reactive-presence-peer")))}function p(t){let r=t.root,e=r.ownerDocument.getElementById("reactive-presence-src-"+r.id)?.pgbusSeat,n=r.querySelectorAll("[data-reactive-presence-peer],[data-reactive-presence-member]"),o=E(r),a;for(let s of n)if(s.getAttribute("data-reactive-presence-peer")===e)a=s.getAttribute("data-reactive-presence-member");for(let s of n){let l=s.getAttribute("data-reactive-presence-peer")===e;s.toggleAttribute("data-reactive-presence-me",l),s.toggleAttribute("data-reactive-presence-same-member",!l&&a!=null&&s.getAttribute("data-reactive-presence-member")===a)}let i=t.seats;if(t.seats=o,!i)return;let u=[...o].filter((s)=>!i.has(s)),d=[...i].filter((s)=>!o.has(s));if(u.length||d.length)t.core.emit("reactive:presence",{joined:u,left:d,me:e??null})}export{h as connect,R as disconnect,S as set};
|
|
2
|
+
|
|
3
|
+
//# debugId=A98AC1EA085C2A8E64756E2164756E21
|
|
4
|
+
//# sourceMappingURL=presence.min.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["features/presence.js"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"// phlex/reactive/features/presence — who is viewing a stream, one seat per\n// tab (issue #358). One of the feature modules the core imports on demand\n// (issue #275); in the default client it is part of the one file.\n//\n// The markup is the Ruby side's (reactive_presence and its helpers):\n//\n// data-reactive-presence=\"<signed src>\" the roster root; its stream\n// data-reactive-presence-roster=\"<seats>\" on the root: the seats rendered\n// data-reactive-presence-peer=\"<seat>\" a tab's element\n// data-reactive-presence-member=\"<id>\" a person's (or a tab's) element\n//\n// and what this module sets, for the app's CSS, after the first paint and\n// after every morph of the root:\n//\n// data-reactive-presence-me this tab's own peer element\n// data-reactive-presence-same-member this person's other elements\n//\n// The roster is rendered ONCE for every viewer (one broadcast), so the server\n// cannot say which row is \"me\": the module does, from the tab's seat.\n//\n// The subscription. The root carries its presence stream's signed src; the\n// module mints a <pgbus-stream-source presence> for it in <body>, with a\n// deterministic id (reactive-presence-src-<root id>), as the defer push lane\n// mints its one-shot source. pgbus's element mints the tab's seat (one per\n// document), sends it as ?seat= and exposes it as element.pgbusSeat: the\n// transport stores it on the tab's presence row, a reconnect (a new\n// connection id) keeps it, and this module reads it to find \"me\". A plain\n// replace of the root disconnects and\n// reconnects the controller: the source is removed only a microtask after a\n// disconnect, and kept when the same root id comes back.\n//\n// Announcing. On every pgbus:connected (the first one and each reconnect) the\n// module sends presence_set with the tab's last state ({} at first), through\n// the root's own pipeline (core.proceed): the signed token, the typed state,\n// the request queue. That write puts the tab on the roster for everyone (and\n// the actor's own reply shows it), and a reconnect, which is a fresh row with\n// no state, gets its state back. The runtime sends the source's connection id\n// as X-Reactive-Presence, so the write lands on this tab's row.\n//\n// Events. The module keeps the seats it last saw in the root (the root's\n// data-reactive-presence-roster list); when a morph changes them it dispatches\n// reactive:presence on the root with { joined, left, me } — from the DOM, so a\n// replayed frame that changes nothing fires nothing.\n//\n// This module never imports the core: it reaches a controller through the\n// `core` handle (core.proceed, core.emit).\n\nconst SOURCE = \"reactive-presence-src-\"\nconst PEER = \"data-reactive-presence-peer\"\nconst MEMBER = \"data-reactive-presence-member\"\nconst ROSTER = \"data-reactive-presence-roster\"\n\n// root id -> { root, core, state, seats, removing, off }: what a root's\n// connection left behind, kept across a replace of the root.\nconst roots = new Map()\n// The sources this module minted and listens to (a Turbo cache restore brings\n// back a clone without the listener).\nconst minted = new WeakSet()\n\nexport function connect(controller, core) {\n const root = controller.element\n let entry = roots.get(root.id)\n if (!entry) roots.set(root.id, (entry = { state: null, seats: null }))\n entry.root = root\n entry.core = core\n entry.removing = false\n subscribe(root)\n const morphed = (event) => event.target === root && queueMicrotask(() => paint(entry))\n // A failed announce (a network error, a 5xx) leaves the tab's row without\n // its note and state until the next js.presence or reconnect: say so.\n const failed = (event) =>\n event.target === root &&\n event.detail?.action === \"presence_set\" &&\n console.error(`[phlex-reactive] #${root.id}: its presence_set request failed`, event.detail)\n root.addEventListener(\"turbo:morph-element\", morphed)\n root.addEventListener(\"reactive:error\", failed)\n entry.off = () => {\n root.removeEventListener(\"turbo:morph-element\", morphed)\n root.removeEventListener(\"reactive:error\", failed)\n }\n paint(entry)\n}\n\nexport function disconnect(controller) {\n const root = controller.element\n const entry = roots.get(root.id)\n if (!entry || entry.root !== root) return\n entry.off()\n entry.removing = true\n queueMicrotask(() => {\n if (!entry.removing) return\n roots.delete(root.id)\n root.ownerDocument.getElementById(SOURCE + root.id)?.remove()\n })\n}\n\n// js.presence(**state): merge into the tab's state and send it. Before the\n// tab has a connection the state waits for the announce on connect.\nexport function set(root, state) {\n if (!root?.hasAttribute?.(\"data-reactive-presence\")) {\n console.warn(\"[phlex-reactive] js.presence ran outside a reactive_presence root — ignored\")\n return\n }\n let entry = roots.get(root.id)\n if (!entry) roots.set(root.id, (entry = { root, state: null, seats: null }))\n entry.state = { ...entry.state, ...state }\n send(entry)\n}\n\nfunction subscribe(root) {\n const id = SOURCE + root.id\n const found = document.getElementById(id)\n if (found && minted.has(found)) return\n found?.remove()\n // pgbus's client is an async module script, so this controller can connect\n // before <pgbus-stream-source> is defined: mint the element anyway (it\n // upgrades when pgbus defines it), and call a still-missing client a\n // misconfiguration only after a grace period.\n if (!defined()) {\n setTimeout(() => {\n if (!defined()) {\n console.error(\n \"[phlex-reactive] reactive_presence needs the pgbus client (<pgbus-stream-source>) on this page — \" +\n `#${root.id} is not subscribed to its presence stream`,\n )\n }\n }, 5000)\n }\n const source = document.createElement(\"pgbus-stream-source\")\n source.id = id\n source.setAttribute(\"src\", root.getAttribute(\"data-reactive-presence\"))\n source.setAttribute(\"presence\", \"\")\n source.hidden = true\n source.addEventListener(\"pgbus:connected\", () => {\n const entry = roots.get(root.id)\n if (!entry || entry.removing) return\n send(entry)\n check(entry)\n })\n minted.add(source)\n document.body.appendChild(source)\n}\n\nconst defined = () => !!globalThis.customElements?.get?.(\"pgbus-stream-source\")\n\n// pgbus fires pgbus:connected only after the tab's seat has joined, so the\n// announce lands on its row. A tab still off its roster a moment later has no\n// identity (pgbus joins an anonymous connection to nothing), or its announce\n// failed: say so once. No retry (an accepted risk).\nfunction check(entry) {\n clearTimeout(entry.timer)\n entry.timer = setTimeout(() => {\n const root = entry.root\n if (entry.removing || !root.isConnected) return\n const mine = root.ownerDocument.getElementById(SOURCE + root.id)?.pgbusSeat\n if (mine && seatsOf(root).has(mine)) return\n console.warn(\n `[phlex-reactive] #${root.id} never appeared on its presence roster: config.streams_authorize ` +\n \"returned no identity for this stream, or its presence_set request failed (logged above)\",\n )\n }, 2500)\n}\n\n// Send the tab's state through presence_set — only once the source has a\n// connection (the row the write lands on). Until then the announce on\n// pgbus:connected sends it.\nfunction send(entry) {\n const root = entry.root\n if (!entry.core || !root.ownerDocument.getElementById(SOURCE + root.id)?.getAttribute(\"connection-id\")) return\n entry.core.proceed(root, \"presence_set\", JSON.stringify(entry.state ?? {}))\n}\n\n// The seats the root's render saw: the list the server names on the root\n// (data-reactive-presence-roster: a template need not render an element per\n// tab), or, without it, the tabs' own elements.\nfunction seatsOf(root) {\n const named = root.getAttribute(ROSTER)\n if (named != null) return new Set(named.split(\" \").filter(Boolean))\n return new Set([...root.querySelectorAll(`[${PEER}]`)].map((el) => el.getAttribute(PEER)))\n}\n\n// Mark \"me\" and this person's other elements, then report the seats that\n// joined or left since the last paint.\nfunction paint(entry) {\n const root = entry.root\n // The seat pgbus's element minted (undefined on a pgbus without seats).\n const mine = root.ownerDocument.getElementById(SOURCE + root.id)?.pgbusSeat\n const marked = root.querySelectorAll(`[${PEER}],[${MEMBER}]`)\n const seats = seatsOf(root)\n let member\n for (const el of marked) {\n if (el.getAttribute(PEER) === mine) member = el.getAttribute(MEMBER)\n }\n for (const el of marked) {\n const me = el.getAttribute(PEER) === mine\n el.toggleAttribute(\"data-reactive-presence-me\", me)\n el.toggleAttribute(\"data-reactive-presence-same-member\", !me && member != null && el.getAttribute(MEMBER) === member)\n }\n const before = entry.seats\n entry.seats = seats\n if (!before) return\n const joined = [...seats].filter((s) => !before.has(s))\n const left = [...before].filter((s) => !seats.has(s))\n if (joined.length || left.length) entry.core.emit(\"reactive:presence\", { joined, left, me: mine ?? null })\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "AAsDA,IAAM,EAAQ,IAAI,IAGZ,EAAS,IAAI,QAEZ,SAAS,CAAO,CAAC,EAAY,EAAM,CACxC,IAAM,EAAO,EAAW,QACpB,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