stimeo-ui 0.13.0 → 0.14.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.
Files changed (103) hide show
  1. package/CHANGELOG.md +39 -5
  2. package/dist/cable/index.d.ts +1 -1
  3. package/dist/cable/index.js.map +1 -1
  4. package/dist/controllers/accordion_controller.d.ts +1 -1
  5. package/dist/controllers/accordion_controller.js.map +1 -1
  6. package/dist/controllers/calendar_controller.d.ts +2 -2
  7. package/dist/controllers/calendar_controller.js +31 -7
  8. package/dist/controllers/calendar_controller.js.map +1 -1
  9. package/dist/controllers/carousel_controller.js +8 -6
  10. package/dist/controllers/carousel_controller.js.map +1 -1
  11. package/dist/controllers/clipboard_controller.d.ts +1 -1
  12. package/dist/controllers/clipboard_controller.js.map +1 -1
  13. package/dist/controllers/collapsible_controller.d.ts +1 -1
  14. package/dist/controllers/collapsible_controller.js.map +1 -1
  15. package/dist/controllers/conditional_fields_controller.js +7 -1
  16. package/dist/controllers/conditional_fields_controller.js.map +1 -1
  17. package/dist/controllers/currency_input_controller.js +68 -23
  18. package/dist/controllers/currency_input_controller.js.map +1 -1
  19. package/dist/controllers/date_range_picker_controller.d.ts +3 -3
  20. package/dist/controllers/date_range_picker_controller.js +31 -7
  21. package/dist/controllers/date_range_picker_controller.js.map +1 -1
  22. package/dist/controllers/dialog_controller.d.ts +2 -2
  23. package/dist/controllers/dialog_controller.js.map +1 -1
  24. package/dist/controllers/direct_upload_controller.js +21 -10
  25. package/dist/controllers/direct_upload_controller.js.map +1 -1
  26. package/dist/controllers/dismissible_controller.d.ts +1 -1
  27. package/dist/controllers/dismissible_controller.js.map +1 -1
  28. package/dist/controllers/dropdown_controller.d.ts +1 -1
  29. package/dist/controllers/dropdown_controller.js.map +1 -1
  30. package/dist/controllers/form_field_controller.js +7 -1
  31. package/dist/controllers/form_field_controller.js.map +1 -1
  32. package/dist/controllers/input_mask_controller.d.ts +3 -2
  33. package/dist/controllers/input_mask_controller.js +33 -12
  34. package/dist/controllers/input_mask_controller.js.map +1 -1
  35. package/dist/controllers/intersection_controller.js +10 -5
  36. package/dist/controllers/intersection_controller.js.map +1 -1
  37. package/dist/controllers/lazy_frame_controller.js +10 -5
  38. package/dist/controllers/lazy_frame_controller.js.map +1 -1
  39. package/dist/controllers/local_time_controller.d.ts +3 -2
  40. package/dist/controllers/local_time_controller.js +34 -7
  41. package/dist/controllers/local_time_controller.js.map +1 -1
  42. package/dist/controllers/masonry_controller.d.ts +1 -1
  43. package/dist/controllers/masonry_controller.js +1 -1
  44. package/dist/controllers/masonry_controller.js.map +1 -1
  45. package/dist/controllers/menu_controller.js +10 -2
  46. package/dist/controllers/menu_controller.js.map +1 -1
  47. package/dist/controllers/menubar_controller.js +10 -2
  48. package/dist/controllers/menubar_controller.js.map +1 -1
  49. package/dist/controllers/navigation_menu_controller.js +8 -2
  50. package/dist/controllers/navigation_menu_controller.js.map +1 -1
  51. package/dist/controllers/otp_controller.js +23 -10
  52. package/dist/controllers/otp_controller.js.map +1 -1
  53. package/dist/controllers/overflow_menu_controller.js +10 -1
  54. package/dist/controllers/overflow_menu_controller.js.map +1 -1
  55. package/dist/controllers/password_reveal_controller.d.ts +1 -1
  56. package/dist/controllers/password_reveal_controller.js.map +1 -1
  57. package/dist/controllers/pointer_drag_controller.js +10 -3
  58. package/dist/controllers/pointer_drag_controller.js.map +1 -1
  59. package/dist/controllers/portal_controller.js +21 -10
  60. package/dist/controllers/portal_controller.js.map +1 -1
  61. package/dist/controllers/radio_group_controller.js +11 -3
  62. package/dist/controllers/radio_group_controller.js.map +1 -1
  63. package/dist/controllers/read_more_controller.d.ts +1 -1
  64. package/dist/controllers/read_more_controller.js.map +1 -1
  65. package/dist/controllers/relative_time_controller.js +31 -5
  66. package/dist/controllers/relative_time_controller.js.map +1 -1
  67. package/dist/controllers/reset_before_cache_controller.js +23 -10
  68. package/dist/controllers/reset_before_cache_controller.js.map +1 -1
  69. package/dist/controllers/resizable_controller.js +7 -2
  70. package/dist/controllers/resizable_controller.js.map +1 -1
  71. package/dist/controllers/roving_controller.js +7 -3
  72. package/dist/controllers/roving_controller.js.map +1 -1
  73. package/dist/controllers/scroll_visibility_controller.d.ts +1 -1
  74. package/dist/controllers/scroll_visibility_controller.js +22 -13
  75. package/dist/controllers/scroll_visibility_controller.js.map +1 -1
  76. package/dist/controllers/scrollspy_controller.d.ts +1 -1
  77. package/dist/controllers/scrollspy_controller.js +11 -6
  78. package/dist/controllers/scrollspy_controller.js.map +1 -1
  79. package/dist/controllers/smart_sticky_header_controller.js +23 -12
  80. package/dist/controllers/smart_sticky_header_controller.js.map +1 -1
  81. package/dist/controllers/sticky_observer_controller.js +10 -5
  82. package/dist/controllers/sticky_observer_controller.js.map +1 -1
  83. package/dist/controllers/switch_controller.d.ts +1 -1
  84. package/dist/controllers/switch_controller.js.map +1 -1
  85. package/dist/controllers/tabs_controller.d.ts +1 -1
  86. package/dist/controllers/tabs_controller.js.map +1 -1
  87. package/dist/controllers/theme_controller.d.ts +2 -3
  88. package/dist/controllers/theme_controller.js +23 -13
  89. package/dist/controllers/theme_controller.js.map +1 -1
  90. package/dist/controllers/toggle_group_controller.js +11 -3
  91. package/dist/controllers/toggle_group_controller.js.map +1 -1
  92. package/dist/controllers/toolbar_controller.js +7 -3
  93. package/dist/controllers/toolbar_controller.js.map +1 -1
  94. package/dist/index.js +165 -171
  95. package/dist/index.js.map +1 -1
  96. package/dist/inspector/cli.d.ts +38 -1
  97. package/dist/inspector/cli.js +80 -7
  98. package/dist/inspector/cli.js.map +1 -1
  99. package/dist/inspector/cli_bin.js +103 -7
  100. package/dist/inspector/cli_bin.js.map +1 -1
  101. package/dist/inspector/examples.json +5 -5
  102. package/dist/inspector/manifest.json +127 -1
  103. package/package.json +9 -11
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/aria_ids.ts","../../src/utils/escape_layer.ts","../../src/controllers/dropdown_controller.ts"],"names":[],"mappings":";;;;;AAkBA,IAAI,OAAA,GAA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AO;AAAA,KAC5C,CAAA;AACD,IAAA,IAAA,CAAK,WAAW,MAAA,GAAS,KAAA;AACzB,IAAA,IAAI,KAAK,gBAAA,EAAkB;AACzB,MAAA,IAAA,CAAK,aAAA,CAAc,YAAA,CAAa,eAAA,EAAiB,MAAM,CAAA;AAAA,IACzD;AAAA,EACF;AAAA;AAAA,EAGA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,aAAa,UAAA,EAAW;AAC7B,IAAA,IAAI,CAAC,KAAK,aAAA,EAAe;AACzB,IAAA,IAAA,CAAK,WAAW,MAAA,GAAS,IAAA;AACzB,IAAA,IAAI,KAAK,gBAAA,EAAkB;AACzB,MAAA,IAAA,CAAK,aAAA,CAAc,YAAA,CAAa,eAAA,EAAiB,OAAO,CAAA;AAAA,IAC1D;AAAA,EACF;AAAA;AAAA,EAGA,gBAAA,GAAyB;AACvB,IAAA,IAAA,CAAK,KAAA,EAAM;AACX,IAAA,IAAI,IAAA,CAAK,gBAAA,EAAkB,IAAA,CAAK,aAAA,CAAc,KAAA,EAAM;AAAA,EACtD;AAAA;AAAA,EAGA,IAAI,OAAA,GAAmB;AACrB,IAAA,OAAO,IAAA,CAAK,aAAA,IAAiB,CAAC,IAAA,CAAK,UAAA,CAAW,MAAA;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,yBAAA,GAAkC;AAChC,IAAA,IAAI,CAAC,IAAA,CAAK,gBAAA,IAAoB,CAAC,KAAK,aAAA,EAAe;AACnD,IAAA,IAAI,IAAA,CAAK,aAAA,CAAc,YAAA,CAAa,eAAe,CAAA,EAAG;AAEtD,IAAA,IAAA,CAAK,aAAA,CAAc,YAAA;AAAA,MACjB,eAAA;AAAA,MACA,QAAA,CAAS,IAAA,CAAK,UAAA,EAAY,uBAAuB;AAAA,KACnD;AAAA,EACF;AACF","file":"dropdown_controller.js","sourcesContent":["/**\n * Minimal id primitives for wiring ARIA relationships.\n *\n * Accessible relationships such as `aria-describedby`, `aria-errormessage`,\n * `aria-labelledby`, and `aria-activedescendant` reference their targets by DOM\n * `id`. When a controller must establish such a relationship but the consumer's\n * markup left the target without an `id`, it needs to mint one that is stable for\n * the page's lifetime and guaranteed not to collide with another generated id.\n *\n * These helpers own *only* id generation/assignment. The linking policy (which\n * attribute, what order, when to add or remove it) stays in each controller —\n * this deliberately avoids a premature generic \"ARIA linker\" abstraction.\n */\n\n/**\n * Monotonic counter backing {@link uniqueId}. Module-scoped so every generated\n * id is unique across all controller instances sharing this module in a document.\n */\nlet counter = 0;\n\n/**\n * Returns a unique, DOM-id-safe string of the form `` `${prefix}-${n}` `` where\n * `n` increases on each call.\n *\n * The counter alone guarantees uniqueness against other *generated* ids, but a\n * consumer-authored element could already own `` `${prefix}-${n}` ``. When a\n * `document` is available the candidate is therefore advanced until no element\n * with that id exists, so a generated id never collides with author markup\n * either — the minimal \"id registry\" guarantee these helpers exist to provide.\n *\n * @param prefix - Leading segment of the id (e.g. a controller's identifier).\n * Defaults to `\"stimeo\"`.\n */\nexport function uniqueId(prefix = \"stimeo\"): string {\n let candidate: string;\n do {\n counter += 1;\n candidate = `${prefix}-${counter}`;\n } while (typeof document !== \"undefined\" && document.getElementById(candidate) !== null);\n return candidate;\n}\n\n/**\n * Returns `element`'s existing `id`, or assigns it a freshly generated\n * {@link uniqueId} (with the given `prefix`) and returns that. Idempotent: an\n * element that already has an id keeps it, so consumer-authored ids are never\n * overwritten.\n *\n * @param element - The element to read or stamp an `id` onto.\n * @param prefix - Prefix forwarded to {@link uniqueId} when one must be generated.\n * @returns The element's id (existing or newly assigned).\n */\nexport function ensureId(element: Element, prefix = \"stimeo\"): string {\n if (element.id) return element.id;\n const id = uniqueId(prefix);\n element.id = id;\n return id;\n}\n","/**\n * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest handler resolves the\n * press. A keydown that is part of an IME composition (`event.isComposing`)\n * cancels the composition, never a layer, and is ignored here for every layer\n * at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered.\n */\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n stack: EscapeLayer[];\n onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = new WeakMap<Document, EscapeLayerRegistry>();\n\n #ownerDocument: Document | null = null;\n /** Dismissal callback while active; `null` when inactive. */\n #onDismiss: (() => void) | null = null;\n /** Live predicate deciding whether the layer claims a press; `null` = always. */\n #claims: (() => boolean) | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n registry.stack.push(this);\n this.#ownerDocument = ownerDocument;\n this.#onDismiss = options.onDismiss;\n this.#claims = options.claims ?? null;\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return;\n\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (registry) {\n const index = registry.stack.lastIndexOf(this);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n ownerDocument.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(ownerDocument);\n }\n }\n this.#ownerDocument = null;\n this.#onDismiss = null;\n this.#claims = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return false;\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === this;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.#onDismiss?.();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: EscapeLayer[]): EscapeLayer | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.#claims && !layer.#claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { ensureId } from \"../utils/aria_ids\";\nimport { claimsWhileFocusWithin, EscapeLayer } from \"../utils/escape_layer\";\n\n/**\n * Headless, accessible dropdown menu behavior.\n *\n * Markup contract (identifier: `stimeo--dropdown`):\n * <div data-controller=\"stimeo--dropdown\">\n * <button data-stimeo--dropdown-target=\"trigger\"\n * data-action=\"stimeo--dropdown#toggle\">Menu</button>\n * <div data-stimeo--dropdown-target=\"menu\">...</div>\n * </div>\n *\n * This is a **disclosure** pattern (WAI-ARIA APG): a button toggles the\n * visibility of an adjacent region. It is intentionally *not* a full APG\n * \"menu\" widget — there is no roving-tabindex arrow-key navigation.\n *\n * @remarks\n * The library owns behavior only (ARIA state, keyboard, focus, outside-click).\n * Visual styling is left entirely to the consumer's CSS.\n *\n * Behavior provided:\n * - The trigger is associated with the menu through `aria-controls`.\n * - Click the trigger to toggle the menu (`aria-expanded` + `hidden` reflect state).\n * - `Escape` closes the menu and returns focus to the trigger. While open the\n * menu is a layer on the shared `EscapeLayer` stack; it claims a press\n * only while focus is inside the controller or fell to the body (a click on\n * non-focusable menu content), so a press aimed at another layer never closes\n * the menu or steals focus, and one keypress closes exactly one layer.\n * - A click outside the controller element closes the menu.\n */\nexport class DropdownController extends Controller<HTMLElement> {\n static override targets = [\"trigger\", \"menu\"];\n static actions = [\"close\", \"open\", \"toggle\"] as const;\n\n declare readonly triggerTarget: HTMLButtonElement;\n declare readonly menuTarget: HTMLElement;\n declare readonly hasMenuTarget: boolean;\n declare readonly hasTriggerTarget: boolean;\n\n /** Escape-stack membership while open; the shared resolver dismisses via it. */\n readonly #escapeLayer = new EscapeLayer();\n\n /** Closes the menu when a click lands outside the controller's element. */\n readonly #onOutsideClick = (event: MouseEvent): void => {\n if (!this.element.contains(event.target as Node)) {\n this.close();\n }\n };\n\n /** Starts in the closed state and registers outside-click handling. */\n override connect(): void {\n this.#associateTriggerWithMenu();\n this.close();\n document.addEventListener(\"click\", this.#onOutsideClick, true);\n }\n\n /** Removes the listeners registered in {@link connect}. */\n override disconnect(): void {\n this.#escapeLayer.deactivate();\n document.removeEventListener(\"click\", this.#onOutsideClick, true);\n }\n\n /** Toggles the menu between open and closed. Bound via `data-action`. */\n toggle(): void {\n if (this.#isOpen) {\n this.close();\n } else {\n this.open();\n }\n }\n\n /** Reveals the menu and reflects the open state on the trigger. */\n open(): void {\n if (!this.hasMenuTarget) return;\n this.#escapeLayer.activate(document, {\n onDismiss: () => this.#closeAndRestore(),\n claims: claimsWhileFocusWithin(this.element),\n });\n this.menuTarget.hidden = false;\n if (this.hasTriggerTarget) {\n this.triggerTarget.setAttribute(\"aria-expanded\", \"true\");\n }\n }\n\n /** Hides the menu and reflects the closed state on the trigger. */\n close(): void {\n this.#escapeLayer.deactivate();\n if (!this.hasMenuTarget) return;\n this.menuTarget.hidden = true;\n if (this.hasTriggerTarget) {\n this.triggerTarget.setAttribute(\"aria-expanded\", \"false\");\n }\n }\n\n /** Closes and restores focus to the trigger (the keyboard-dismissal path). */\n #closeAndRestore(): void {\n this.close();\n if (this.hasTriggerTarget) this.triggerTarget.focus();\n }\n\n /** Whether the menu is currently visible. */\n get #isOpen(): boolean {\n return this.hasMenuTarget && !this.menuTarget.hidden;\n }\n\n /**\n * Associates the disclosure trigger and controlled region without clobbering\n * authored markup.\n */\n #associateTriggerWithMenu(): void {\n if (!this.hasTriggerTarget || !this.hasMenuTarget) return;\n if (this.triggerTarget.hasAttribute(\"aria-controls\")) return;\n\n this.triggerTarget.setAttribute(\n \"aria-controls\",\n ensureId(this.menuTarget, \"stimeo--dropdown-menu\"),\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/aria_ids.ts","../../src/utils/escape_layer.ts","../../src/controllers/dropdown_controller.ts"],"names":[],"mappings":";;;;;AAkBA,IAAI,OAAA,GAAU,CAAA;AAeP,SAAS,QAAA,CAAS,SAAS,QAAA,EAAkB;AAClD,EAAA,IAAI,SAAA;AACJ,EAAA,GAAG;AACD,IAAA,OAAA,IAAW,CAAA;AACX,IAAA,SAAA,GAAY,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA;AAAA,EAClC,SAAS,OAAO,QAAA,KAAa,eAAe,QAAA,CAAS,cAAA,CAAe,SAAS,CAAA,KAAM,IAAA;AACnF,EAAA,OAAO,SAAA;AACT;AAYO,SAAS,QAAA,CAAS,OAAA,EAAkB,MAAA,GAAS,QAAA,EAAkB;AACpE,EAAA,IAAI,OAAA,CAAQ,EAAA,EAAI,OAAO,OAAA,CAAQ,EAAA;AAC/B,EAAA,MAAM,EAAA,GAAK,SAAS,MAAM,CAAA;AAC1B,EAAA,OAAA,CAAQ,EAAA,GAAK,EAAA;AACb,EAAA,OAAO,EAAA;AACT;;;ACOO,SAAS,uBAAuB,OAAA,EAAiC;AACtE,EAAA,OAAO,MAAM;AACX,IAAA,MAAM,MAAA,GAAS,QAAQ,aAAA,CAAc,aAAA;AACrC,IAAA,OAAO,MAAA,KAAW,QAAQ,MAAA,KAAW,OAAA,CAAQ,cAAc,IAAA,IAAQ,OAAA,CAAQ,SAAS,MAAM,CAAA;AAAA,EAC5F,CAAA;AACF;AAEO,IAAM,WAAA,GAAN,MAAM,YAAA,CAAY;AAAA,EACvB,OAAgB,WAAA,mBAAc,IAAI,OAAA,EAAuC;AAAA,EAEzE,cAAA,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IAAA,CAAK,aAAA,CAAc,YAAA,CAAa,eAAe,CAAA,EAAG;AAEtD,IAAA,IAAA,CAAK,aAAA,CAAc,YAAA;AAAA,MACjB,eAAA;AAAA,MACA,QAAA,CAAS,IAAA,CAAK,UAAA,EAAY,uBAAuB;AAAA,KACnD;AAAA,EACF;AACF","file":"dropdown_controller.js","sourcesContent":["/**\n * Minimal id primitives for wiring ARIA relationships.\n *\n * Accessible relationships such as `aria-describedby`, `aria-errormessage`,\n * `aria-labelledby`, and `aria-activedescendant` reference their targets by DOM\n * `id`. When a controller must establish such a relationship but the consumer's\n * markup left the target without an `id`, it needs to mint one that is stable for\n * the page's lifetime and guaranteed not to collide with another generated id.\n *\n * These helpers own *only* id generation/assignment. The linking policy (which\n * attribute, what order, when to add or remove it) stays in each controller —\n * this deliberately avoids a premature generic \"ARIA linker\" abstraction.\n */\n\n/**\n * Monotonic counter backing {@link uniqueId}. Module-scoped so every generated\n * id is unique across all controller instances sharing this module in a document.\n */\nlet counter = 0;\n\n/**\n * Returns a unique, DOM-id-safe string of the form `` `${prefix}-${n}` `` where\n * `n` increases on each call.\n *\n * The counter alone guarantees uniqueness against other *generated* ids, but a\n * consumer-authored element could already own `` `${prefix}-${n}` ``. When a\n * `document` is available the candidate is therefore advanced until no element\n * with that id exists, so a generated id never collides with author markup\n * either — the minimal \"id registry\" guarantee these helpers exist to provide.\n *\n * @param prefix - Leading segment of the id (e.g. a controller's identifier).\n * Defaults to `\"stimeo\"`.\n */\nexport function uniqueId(prefix = \"stimeo\"): string {\n let candidate: string;\n do {\n counter += 1;\n candidate = `${prefix}-${counter}`;\n } while (typeof document !== \"undefined\" && document.getElementById(candidate) !== null);\n return candidate;\n}\n\n/**\n * Returns `element`'s existing `id`, or assigns it a freshly generated\n * {@link uniqueId} (with the given `prefix`) and returns that. Idempotent: an\n * element that already has an id keeps it, so consumer-authored ids are never\n * overwritten.\n *\n * @param element - The element to read or stamp an `id` onto.\n * @param prefix - Prefix forwarded to {@link uniqueId} when one must be generated.\n * @returns The element's id (existing or newly assigned).\n */\nexport function ensureId(element: Element, prefix = \"stimeo\"): string {\n if (element.id) return element.id;\n const id = uniqueId(prefix);\n element.id = id;\n return id;\n}\n","/**\n * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest handler resolves the\n * press. A keydown that is part of an IME composition (`event.isComposing`)\n * cancels the composition, never a layer, and is ignored here for every layer\n * at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered.\n */\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n stack: EscapeLayer[];\n onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = new WeakMap<Document, EscapeLayerRegistry>();\n\n #ownerDocument: Document | null = null;\n /** Dismissal callback while active; `null` when inactive. */\n #onDismiss: (() => void) | null = null;\n /** Live predicate deciding whether the layer claims a press; `null` = always. */\n #claims: (() => boolean) | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n registry.stack.push(this);\n this.#ownerDocument = ownerDocument;\n this.#onDismiss = options.onDismiss;\n this.#claims = options.claims ?? null;\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return;\n\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (registry) {\n const index = registry.stack.lastIndexOf(this);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n ownerDocument.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(ownerDocument);\n }\n }\n this.#ownerDocument = null;\n this.#onDismiss = null;\n this.#claims = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return false;\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === this;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.#onDismiss?.();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: EscapeLayer[]): EscapeLayer | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.#claims && !layer.#claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { ensureId } from \"../utils/aria_ids\";\nimport { claimsWhileFocusWithin, EscapeLayer } from \"../utils/escape_layer\";\n\n/**\n * Headless, accessible dropdown menu behavior.\n *\n * Markup contract (identifier: `stimeo--dropdown`):\n * <div data-controller=\"stimeo--dropdown\">\n * <button data-stimeo--dropdown-target=\"trigger\"\n * data-action=\"click->stimeo--dropdown#toggle\">Menu</button>\n * <div data-stimeo--dropdown-target=\"menu\">...</div>\n * </div>\n *\n * This is a **disclosure** pattern (WAI-ARIA APG): a button toggles the\n * visibility of an adjacent region. It is intentionally *not* a full APG\n * \"menu\" widget — there is no roving-tabindex arrow-key navigation.\n *\n * @remarks\n * The library owns behavior only (ARIA state, keyboard, focus, outside-click).\n * Visual styling is left entirely to the consumer's CSS.\n *\n * Behavior provided:\n * - The trigger is associated with the menu through `aria-controls`.\n * - Click the trigger to toggle the menu (`aria-expanded` + `hidden` reflect state).\n * - `Escape` closes the menu and returns focus to the trigger. While open the\n * menu is a layer on the shared `EscapeLayer` stack; it claims a press\n * only while focus is inside the controller or fell to the body (a click on\n * non-focusable menu content), so a press aimed at another layer never closes\n * the menu or steals focus, and one keypress closes exactly one layer.\n * - A click outside the controller element closes the menu.\n */\nexport class DropdownController extends Controller<HTMLElement> {\n static override targets = [\"trigger\", \"menu\"];\n static actions = [\"close\", \"open\", \"toggle\"] as const;\n\n declare readonly triggerTarget: HTMLButtonElement;\n declare readonly menuTarget: HTMLElement;\n declare readonly hasMenuTarget: boolean;\n declare readonly hasTriggerTarget: boolean;\n\n /** Escape-stack membership while open; the shared resolver dismisses via it. */\n readonly #escapeLayer = new EscapeLayer();\n\n /** Closes the menu when a click lands outside the controller's element. */\n readonly #onOutsideClick = (event: MouseEvent): void => {\n if (!this.element.contains(event.target as Node)) {\n this.close();\n }\n };\n\n /** Starts in the closed state and registers outside-click handling. */\n override connect(): void {\n this.#associateTriggerWithMenu();\n this.close();\n document.addEventListener(\"click\", this.#onOutsideClick, true);\n }\n\n /** Removes the listeners registered in {@link connect}. */\n override disconnect(): void {\n this.#escapeLayer.deactivate();\n document.removeEventListener(\"click\", this.#onOutsideClick, true);\n }\n\n /** Toggles the menu between open and closed. Bound via `data-action`. */\n toggle(): void {\n if (this.#isOpen) {\n this.close();\n } else {\n this.open();\n }\n }\n\n /** Reveals the menu and reflects the open state on the trigger. */\n open(): void {\n if (!this.hasMenuTarget) return;\n this.#escapeLayer.activate(document, {\n onDismiss: () => this.#closeAndRestore(),\n claims: claimsWhileFocusWithin(this.element),\n });\n this.menuTarget.hidden = false;\n if (this.hasTriggerTarget) {\n this.triggerTarget.setAttribute(\"aria-expanded\", \"true\");\n }\n }\n\n /** Hides the menu and reflects the closed state on the trigger. */\n close(): void {\n this.#escapeLayer.deactivate();\n if (!this.hasMenuTarget) return;\n this.menuTarget.hidden = true;\n if (this.hasTriggerTarget) {\n this.triggerTarget.setAttribute(\"aria-expanded\", \"false\");\n }\n }\n\n /** Closes and restores focus to the trigger (the keyboard-dismissal path). */\n #closeAndRestore(): void {\n this.close();\n if (this.hasTriggerTarget) this.triggerTarget.focus();\n }\n\n /** Whether the menu is currently visible. */\n get #isOpen(): boolean {\n return this.hasMenuTarget && !this.menuTarget.hidden;\n }\n\n /**\n * Associates the disclosure trigger and controlled region without clobbering\n * authored markup.\n */\n #associateTriggerWithMenu(): void {\n if (!this.hasTriggerTarget || !this.hasMenuTarget) return;\n if (this.triggerTarget.hasAttribute(\"aria-controls\")) return;\n\n this.triggerTarget.setAttribute(\n \"aria-controls\",\n ensureId(this.menuTarget, \"stimeo--dropdown-menu\"),\n );\n }\n}\n"]}
@@ -100,6 +100,12 @@ var BeforeCacheReset = class _BeforeCacheReset {
100
100
  }
101
101
  };
102
102
 
103
+ // src/utils/event_owner.ts
104
+ function ownerIndex(candidates, node) {
105
+ if (!(node instanceof Node)) return -1;
106
+ return candidates.findIndex((candidate) => candidate.contains(node));
107
+ }
108
+
103
109
  // src/utils/microtask_coalescer.ts
104
110
  var MicrotaskCoalescer = class {
105
111
  #run;
@@ -357,7 +363,7 @@ var FormFieldController = class _FormFieldController extends Controller {
357
363
  return this.errorTargets.includes(target);
358
364
  return record.attributeName === "id" && [...this.descriptionTargets, ...this.errorTargets].includes(target);
359
365
  }
360
- return this.errorTargets.some((error) => error === target || error.contains(target));
366
+ return ownerIndex(this.errorTargets, target) !== -1;
361
367
  }
362
368
  /** Returns borrowed control ARIA before Turbo snapshots the page. */
363
369
  #rewindForCache() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/aria_ids.ts","../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/microtask_coalescer.ts","../../src/controllers/form_field_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,QAAA,CAAS,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAS;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OAAO;AAAA,KACxB;AAAA,EACF;AAAA;AAAA,EAGA,oBAAoB,MAAA,EAAiC;AACnD,IAAA,MAAM,SAAS,MAAA,CAAO,MAAA;AACtB,IAAA,IAAI,MAAA,CAAO,SAAS,YAAA,EAAc;AAChC,MAAA,IAAI,OAAO,aAAA,KAAkB,QAAA;AAC3B,QAAA,OAAO,IAAA,CAAK,YAAA,CAAa,QAAA,CAAS,MAAqB,CAAA;AACzD,MAAA,OACE,MAAA,CAAO,aAAA,KAAkB,IAAA,IACzB,CAAC,GAAG,IAAA,CAAK,kBAAA,EAAoB,GAAG,IAAA,CAAK,YAAY,CAAA,CAAE,QAAA,CAAS,MAAqB,CAAA;AAAA,IAErF;AAEA,IAAA,OAAO,IAAA,CAAK,YAAA,CAAa,IAAA,CAAK,CAAC,KAAA,KAAU,UAAU,MAAA,IAAU,KAAA,CAAM,QAAA,CAAS,MAAM,CAAC,CAAA;AAAA,EACrF;AAAA;AAAA,EAEA,eAAA,GAAwB;AACtB,IAAA,IAAA,CAAK,iBAAiB,SAAA,EAAU;AAChC,IAAA,IAAA,CAAK,kBAAkB,SAAA,EAAU;AACjC,IAAA,IAAA,CAAK,aAAa,SAAA,EAAU;AAAA,EAC9B;AACF","file":"form_field_controller.js","sourcesContent":["/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A component that has to reach assistive tech does not carry a live region of its\n * own: a region only announces what changes *after* assistive tech already knows\n * about it, which a region that appears (or is un-hidden) with its message cannot\n * satisfy. The one region that can is the announcer sitting in the page from the\n * start, so state changes are handed to it as an event and it does the reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — the library ships no English strings — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n\n/**\n * Fills `{name}` placeholders in an announcement template from `values`.\n *\n * The same substitution the value-text templates use, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = values[name];\n return replacement === undefined ? match : String(replacement);\n });\n}\n","/**\n * Minimal id primitives for wiring ARIA relationships.\n *\n * Accessible relationships such as `aria-describedby`, `aria-errormessage`,\n * `aria-labelledby`, and `aria-activedescendant` reference their targets by DOM\n * `id`. When a controller must establish such a relationship but the consumer's\n * markup left the target without an `id`, it needs to mint one that is stable for\n * the page's lifetime and guaranteed not to collide with another generated id.\n *\n * These helpers own *only* id generation/assignment. The linking policy (which\n * attribute, what order, when to add or remove it) stays in each controller —\n * this deliberately avoids a premature generic \"ARIA linker\" abstraction.\n */\n\n/**\n * Monotonic counter backing {@link uniqueId}. Module-scoped so every generated\n * id is unique across all controller instances sharing this module in a document.\n */\nlet counter = 0;\n\n/**\n * Returns a unique, DOM-id-safe string of the form `` `${prefix}-${n}` `` where\n * `n` increases on each call.\n *\n * The counter alone guarantees uniqueness against other *generated* ids, but a\n * consumer-authored element could already own `` `${prefix}-${n}` ``. When a\n * `document` is available the candidate is therefore advanced until no element\n * with that id exists, so a generated id never collides with author markup\n * either — the minimal \"id registry\" guarantee these helpers exist to provide.\n *\n * @param prefix - Leading segment of the id (e.g. a controller's identifier).\n * Defaults to `\"stimeo\"`.\n */\nexport function uniqueId(prefix = \"stimeo\"): string {\n let candidate: string;\n do {\n counter += 1;\n candidate = `${prefix}-${counter}`;\n } while (typeof document !== \"undefined\" && document.getElementById(candidate) !== null);\n return candidate;\n}\n\n/**\n * Returns `element`'s existing `id`, or assigns it a freshly generated\n * {@link uniqueId} (with the given `prefix`) and returns that. Idempotent: an\n * element that already has an id keeps it, so consumer-authored ids are never\n * overwritten.\n *\n * @param element - The element to read or stamp an `id` onto.\n * @param prefix - Prefix forwarded to {@link uniqueId} when one must be generated.\n * @returns The element's id (existing or newly assigned).\n */\nexport function ensureId(element: Element, prefix = \"stimeo\"): string {\n if (element.id) return element.id;\n const id = uniqueId(prefix);\n element.id = id;\n return id;\n}\n","/** One temporarily controlled attribute value and the authored value it displaced. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n written: string | null;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events.\n * A consumer that must not let a derived value become the authored baseline of a\n * cached page returns its leases from its own `turbo:before-cache` rewind, where the\n * matching `disconnect()` also releases the subscription.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #records = new Map<T, AttributeLeaseRecord>();\n\n /** @param attribute - The attribute whose temporary values this lease owns. */\n constructor(attribute: string) {\n this.#attribute = attribute;\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const existing = this.#records.get(element);\n if (existing) {\n existing.written = value;\n } else {\n this.#records.set(element, {\n original: element.getAttribute(this.#attribute),\n written: value,\n });\n }\n\n this.#reflect(element, value);\n }\n\n /** Returns one lease without overwriting a value subsequently authored by a consumer. */\n return(element: T): void {\n const record = this.#records.get(element);\n if (!record) return;\n this.#records.delete(element);\n const stillOwned = element.getAttribute(this.#attribute) === record.written;\n if (stillOwned) this.#reflect(element, record.original);\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n if (element.getAttribute(this.#attribute) === value) return;\n if (value === null) element.removeAttribute(this.#attribute);\n else element.setAttribute(this.#attribute, value);\n }\n\n /** Returns every outstanding lease using the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#records.keys())) this.return(element);\n }\n}\n","/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way.\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { announce } from \"../utils/announce\";\nimport { ensureId } from \"../utils/aria_ids\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\n\n/** Stimulus action params understood by {@link FormFieldController.setError}. */\ninterface SetErrorParams {\n /** The error message to display. */\n message?: string;\n}\n\n/** An action event carrying Stimulus `data-*-param` values. */\ntype ActionEvent = Event & { params?: SetErrorParams };\n\n/** Programmatic behavior switches for {@link FormFieldController.setError}. */\nexport interface FormFieldSetErrorOptions {\n /** Override the `focusOnError` Value for this call. */\n focus?: boolean;\n}\n\n/** Detail dispatched with `stimeo--form-field:validate`. */\nexport interface FormFieldValidateDetail {\n /** Whether the explicit validation action left the field valid. */\n valid: boolean;\n /** The first visible error message, or an empty string when valid/unavailable. */\n message: string;\n}\n\n/** Attributes on retained association targets that can change the ARIA graph. */\nconst OBSERVED_ATTRIBUTES = [\"hidden\", \"id\"];\n\n/**\n * Headless, accessible form-field association behavior.\n *\n * Markup contract (identifier: `stimeo--form-field`):\n * <div data-controller=\"stimeo--form-field\">\n * <label for=\"email\">Email</label>\n * <input id=\"email\" type=\"email\" aria-invalid=\"false\"\n * data-stimeo--form-field-target=\"control\" />\n * <p data-stimeo--form-field-target=\"description\">We'll send a confirmation.</p>\n * <p hidden data-stimeo--form-field-target=\"error\"></p>\n * </div>\n *\n * Not an APG widget pattern — this is the wiring substrate behind form controls:\n * it supports **Name, Role, Value** (WCAG 4.1.2) and **error identification**\n * (3.3.1 / 4.1.3) by composing the control's `aria-describedby`, toggling\n * `aria-invalid`, and pointing `aria-errormessage` at the visual error.\n *\n * `validate` dispatches `{ valid: boolean, message: string }`.\n *\n * @remarks\n * Behavior only — it sets semantic attributes and the `hidden` state of the\n * visual error; it never validates input (the consumer / server decides) and\n * never styles. Runtime errors are handed to a separately seated\n * `stimeo--announcer`, because showing a live region together with its first\n * message is not a reliable announcement primitive.\n *\n * Behavior provided:\n * - Assigns ids to description/error targets and composes the control's\n * `aria-describedby` from them in DOM order (preserving the control's authored\n * tokens and removing duplicates).\n * - Reflects server-rendered errors: an error target that is already visible and\n * non-empty at connect puts the field into the invalid state (progressive\n * enhancement).\n * - Reconciles added, removed, replaced, and retained/morphed targets without\n * emitting validation events or announcements.\n * - {@link setError} / {@link clearError} drive the invalid state at runtime and\n * dispatch `stimeo--form-field:validate`.\n */\nexport class FormFieldController extends Controller<HTMLElement> {\n static override targets = [\"control\", \"description\", \"error\"];\n static override values = {\n focusOnError: { type: Boolean, default: false },\n };\n static actions = [\"clearError\", \"setError\"] as const;\n static events = [\"validate\"] as const;\n\n declare readonly controlTarget: HTMLElement;\n declare readonly hasControlTarget: boolean;\n declare readonly descriptionTargets: HTMLElement[];\n declare readonly errorTargets: HTMLElement[];\n declare readonly hasErrorTarget: boolean;\n /** Whether an explicit {@link setError} call moves focus to the current control. */\n declare focusOnErrorValue: boolean;\n\n /** Root attribute (CSS hook) reflecting the invalid state. */\n static readonly #INVALID_ATTR = \"data-stimeo--form-field-invalid\";\n\n /** Collapses one target/morph batch into one silent ARIA reconciliation. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileDom());\n /** Returns borrowed control ARIA before Turbo snapshots the page. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #ariaDescribedBy = new AttributeLease<HTMLElement>(\"aria-describedby\");\n readonly #ariaErrorMessage = new AttributeLease<HTMLElement>(\"aria-errormessage\");\n readonly #ariaInvalid = new AttributeLease<HTMLElement>(\"aria-invalid\");\n /** Watches retained target ids, error visibility, and error content. */\n readonly #observer = new MutationObserver((records) => {\n if (records.some((record) => this.#isRelevantMutation(record))) {\n this.#reconcile.schedule();\n }\n });\n\n #activeControl: HTMLElement | null = null;\n #baseDescribedBy: string[] = [];\n #explicitInvalid = false;\n #initialized = false;\n\n /** Wires the initial graph and starts retained-target reconciliation. */\n override connect(): void {\n this.#reconcile.activate();\n this.#ensureAssociationIds();\n this.#beforeCache.activate();\n\n // A restored DOM can contain the invalid hook with no surviving visual\n // message. Treat that one shape as the persisted explicit setError state;\n // visible server errors remain derived and can clear when their DOM clears.\n if (!this.#initialized) {\n this.#explicitInvalid =\n this.element.hasAttribute(FormFieldController.#INVALID_ATTR) &&\n this.#shownErrors().length === 0;\n this.#initialized = true;\n }\n\n this.#reconcileDom();\n this.#observer.observe(this.element, {\n attributes: true,\n attributeFilter: OBSERVED_ATTRIBUTES,\n characterData: true,\n childList: true,\n subtree: true,\n });\n }\n\n /** Releases observers, queued work, and ARIA borrowed on the current control. */\n override disconnect(): void {\n this.#reconcile.cancel();\n this.#observer.disconnect();\n this.#beforeCache.deactivate();\n this.#activeControl && this.#releaseControl(this.#activeControl);\n }\n\n /** Reconciles a control inserted or replaced at runtime. */\n controlTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Schedules restoration of authored ARIA when a control leaves this field. */\n controlTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Reconciles a description inserted or replaced at runtime. */\n descriptionTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Removes a departed description from the control's association graph. */\n descriptionTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Reconciles an error region inserted or replaced at runtime. */\n errorTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Removes a departed error from invalid state and the association graph. */\n errorTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Marks the field invalid and shows the error message. Bound via `data-action`\n * (`#setError`) or callable directly.\n *\n * A non-empty shown message is announced exactly once through the shared\n * assertive announcer. Initial/server reconciliation is deliberately silent.\n *\n * @param arg - Either the message string, or the action event whose\n * `data-stimeo--form-field-message-param` supplies it. When no message is\n * resolvable, any already-populated error targets are simply (re)shown.\n * @param options - Programmatic overrides. Stimulus actions use the Values.\n */\n setError(arg?: string | ActionEvent, options: FormFieldSetErrorOptions = {}): void {\n const message = this.#resolveMessage(arg);\n if (message !== null && this.hasErrorTarget) {\n this.errorTargets[0]?.replaceChildren(document.createTextNode(message));\n }\n for (const error of this.errorTargets) {\n error.hidden = (error.textContent ?? \"\").trim() === \"\";\n }\n\n // setError is an explicit invalid request: it remains invalid even if an\n // error target is absent or replaced before clearError is called.\n this.#explicitInvalid = true;\n this.#reconcileDom();\n const shownMessage = this.#shownMessage();\n const detail: FormFieldValidateDetail = { valid: false, message: shownMessage };\n this.dispatch(\"validate\", { detail });\n announce(shownMessage, { assertive: true });\n\n if (options.focus ?? this.focusOnErrorValue) this.#activeControl?.focus();\n }\n\n /**\n * Clears the error: empties and hides every error target and marks the field\n * valid. Bound via `data-action` (`#clearError`) or callable directly.\n *\n * Clearing is silent: the visual/ARIA state and validation event are sufficient,\n * while success wording remains an explicit consumer announcement.\n */\n clearError(): void {\n for (const error of this.errorTargets) {\n error.replaceChildren();\n error.hidden = true;\n }\n this.#explicitInvalid = false;\n this.#reconcileDom();\n const detail: FormFieldValidateDetail = { valid: true, message: \"\" };\n this.dispatch(\"validate\", { detail });\n }\n\n /**\n * Rebuilds ids and derived ARIA from the settled target graph without reporting\n * a user validation action.\n */\n #reconcileDom(): void {\n this.#ensureAssociationIds();\n this.#adoptCurrentControl();\n\n const shown = this.#shownErrors();\n const invalid = this.#explicitInvalid || shown.length > 0;\n this.element.toggleAttribute(FormFieldController.#INVALID_ATTR, invalid);\n\n const control = this.#activeControl;\n if (!control) return;\n\n this.#ariaInvalid.write(control, invalid ? \"true\" : \"false\");\n\n const primaryErrorId = shown[0]?.id ?? null;\n this.#ariaErrorMessage.write(control, primaryErrorId);\n\n const associationIds = this.#orderedElements([...this.descriptionTargets, ...shown]).map(\n (element) => element.id,\n );\n const describedBy = this.#uniqueTokens([...this.#baseDescribedBy, ...associationIds]);\n this.#ariaDescribedBy.write(control, describedBy.length > 0 ? describedBy.join(\" \") : null);\n }\n\n /** Assigns stable ids before either capture or reflection uses them. */\n #ensureAssociationIds(): void {\n for (const description of this.descriptionTargets) {\n ensureId(description, \"stimeo--form-field-desc\");\n }\n for (const error of this.errorTargets) {\n ensureId(error, \"stimeo--form-field-error\");\n }\n }\n\n /** Switches ARIA ownership when the singular current control target changes. */\n #adoptCurrentControl(): void {\n const next = this.hasControlTarget ? this.controlTarget : null;\n if (next === this.#activeControl) return;\n this.#activeControl && this.#releaseControl(this.#activeControl);\n this.#activeControl = next;\n this.#baseDescribedBy = next ? this.#externalDescribedByTokens(next) : [];\n }\n\n /** Restores one departed control without overwriting later consumer edits. */\n #releaseControl(control: HTMLElement): void {\n this.#ariaDescribedBy.return(control);\n this.#ariaErrorMessage.return(control);\n this.#ariaInvalid.return(control);\n if (control === this.#activeControl) {\n this.#activeControl = null;\n this.#baseDescribedBy = [];\n }\n }\n\n /** Error targets currently visible and non-empty, in document order. */\n #shownErrors(): HTMLElement[] {\n return this.#orderedElements(\n this.errorTargets.filter((error) => !error.hidden && (error.textContent ?? \"\").trim() !== \"\"),\n );\n }\n\n /** Text of the first shown error, for validation detail and announcement. */\n #shownMessage(): string {\n return (this.#shownErrors()[0]?.textContent ?? \"\").trim();\n }\n\n /** Resolves a message from a string argument or an action event's params. */\n #resolveMessage(arg?: string | ActionEvent): string | null {\n if (typeof arg === \"string\") return arg;\n const message = arg?.params?.message;\n return typeof message === \"string\" ? message : null;\n }\n\n /**\n * Tokens authored on a newly adopted control, excluding ids this controller\n * owns through its current description/error targets.\n */\n #externalDescribedByTokens(control: HTMLElement): string[] {\n const owned = new Set([\n ...this.descriptionTargets.map((description) => description.id),\n ...this.errorTargets.map((error) => error.id),\n ]);\n const existing = control.getAttribute(\"aria-describedby\") ?? \"\";\n return this.#uniqueTokens(\n existing.split(/\\s+/).filter((token) => token.length > 0 && !owned.has(token)),\n );\n }\n\n /** Deduplicates ARIA tokens without disturbing their first occurrence. */\n #uniqueTokens(tokens: string[]): string[] {\n const seen = new Set<string>();\n return tokens.filter((token) => {\n if (token.length === 0 || seen.has(token)) return false;\n seen.add(token);\n return true;\n });\n }\n\n /** Returns unique current targets in DOM order before serializing IDREF lists. */\n #orderedElements(elements: HTMLElement[]): HTMLElement[] {\n const candidates = new Set(elements);\n return [this.element, ...this.element.querySelectorAll<HTMLElement>(\"*\")].filter((element) =>\n candidates.has(element),\n );\n }\n\n /** Whether one retained-node mutation can alter this controller's derived state. */\n #isRelevantMutation(record: MutationRecord): boolean {\n const target = record.target;\n if (record.type === \"attributes\") {\n if (record.attributeName === \"hidden\")\n return this.errorTargets.includes(target as HTMLElement);\n return (\n record.attributeName === \"id\" &&\n [...this.descriptionTargets, ...this.errorTargets].includes(target as HTMLElement)\n );\n }\n\n return this.errorTargets.some((error) => error === target || error.contains(target));\n }\n /** Returns borrowed control ARIA before Turbo snapshots the page. */\n #rewindForCache(): void {\n this.#ariaDescribedBy.returnAll();\n this.#ariaErrorMessage.returnAll();\n this.#ariaInvalid.returnAll();\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/aria_ids.ts","../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/event_owner.ts","../../src/utils/microtask_coalescer.ts","../../src/controllers/form_field_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,QAAA,CAAS,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAS;AACrF,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,EAAK;AAC1B,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACvB,EAAA,MAAA,CAAO,aAAA;AAAA,IACL,IAAI,YAAY,4BAAA,EAA8B;AAAA,MAC5C,QAAQ,EAAE,OAAA,EAAS,MAAM,SAAA,EAAW,OAAA,CAAQ,cAAc,IAAA;AAAK,KAChE;AAAA,GACH;AACF;;;ACVA,IAAI,OAAA,GAAU,CAAA;AAeP,SAAS,QAAA,CAAS,SAAS,QAAA,EAAkB;AAClD,EAAA,IAAI,SAAA;AACJ,EAAA,GAAG;AACD,IAAA,OAAA,IAAW,CAAA;AACX,IAAA,SAAA,GAAY,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA;AAAA,EAClC,SAAS,OAAO,QAAA,KAAa,eAAe,QAAA,CAAS,cAAA,CAAe,SAAS,CAAA,KAAM,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K,YAAY,CAAA,CAAE,QAAA,CAAS,MAAqB,CAAA;AAAA,IAErF;AAEA,IAAA,OAAO,UAAA,CAAW,IAAA,CAAK,YAAA,EAAc,MAAM,CAAA,KAAM,EAAA;AAAA,EACnD;AAAA;AAAA,EAEA,eAAA,GAAwB;AACtB,IAAA,IAAA,CAAK,iBAAiB,SAAA,EAAU;AAChC,IAAA,IAAA,CAAK,kBAAkB,SAAA,EAAU;AACjC,IAAA,IAAA,CAAK,aAAa,SAAA,EAAU;AAAA,EAC9B;AACF","file":"form_field_controller.js","sourcesContent":["/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A component that has to reach assistive tech does not carry a live region of its\n * own: a region only announces what changes *after* assistive tech already knows\n * about it, which a region that appears (or is un-hidden) with its message cannot\n * satisfy. The one region that can is the announcer sitting in the page from the\n * start, so state changes are handed to it as an event and it does the reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — the library ships no English strings — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n\n/**\n * Fills `{name}` placeholders in an announcement template from `values`.\n *\n * The same substitution the value-text templates use, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = values[name];\n return replacement === undefined ? match : String(replacement);\n });\n}\n","/**\n * Minimal id primitives for wiring ARIA relationships.\n *\n * Accessible relationships such as `aria-describedby`, `aria-errormessage`,\n * `aria-labelledby`, and `aria-activedescendant` reference their targets by DOM\n * `id`. When a controller must establish such a relationship but the consumer's\n * markup left the target without an `id`, it needs to mint one that is stable for\n * the page's lifetime and guaranteed not to collide with another generated id.\n *\n * These helpers own *only* id generation/assignment. The linking policy (which\n * attribute, what order, when to add or remove it) stays in each controller —\n * this deliberately avoids a premature generic \"ARIA linker\" abstraction.\n */\n\n/**\n * Monotonic counter backing {@link uniqueId}. Module-scoped so every generated\n * id is unique across all controller instances sharing this module in a document.\n */\nlet counter = 0;\n\n/**\n * Returns a unique, DOM-id-safe string of the form `` `${prefix}-${n}` `` where\n * `n` increases on each call.\n *\n * The counter alone guarantees uniqueness against other *generated* ids, but a\n * consumer-authored element could already own `` `${prefix}-${n}` ``. When a\n * `document` is available the candidate is therefore advanced until no element\n * with that id exists, so a generated id never collides with author markup\n * either — the minimal \"id registry\" guarantee these helpers exist to provide.\n *\n * @param prefix - Leading segment of the id (e.g. a controller's identifier).\n * Defaults to `\"stimeo\"`.\n */\nexport function uniqueId(prefix = \"stimeo\"): string {\n let candidate: string;\n do {\n counter += 1;\n candidate = `${prefix}-${counter}`;\n } while (typeof document !== \"undefined\" && document.getElementById(candidate) !== null);\n return candidate;\n}\n\n/**\n * Returns `element`'s existing `id`, or assigns it a freshly generated\n * {@link uniqueId} (with the given `prefix`) and returns that. Idempotent: an\n * element that already has an id keeps it, so consumer-authored ids are never\n * overwritten.\n *\n * @param element - The element to read or stamp an `id` onto.\n * @param prefix - Prefix forwarded to {@link uniqueId} when one must be generated.\n * @returns The element's id (existing or newly assigned).\n */\nexport function ensureId(element: Element, prefix = \"stimeo\"): string {\n if (element.id) return element.id;\n const id = uniqueId(prefix);\n element.id = id;\n return id;\n}\n","/** One temporarily controlled attribute value and the authored value it displaced. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n written: string | null;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events.\n * A consumer that must not let a derived value become the authored baseline of a\n * cached page returns its leases from its own `turbo:before-cache` rewind, where the\n * matching `disconnect()` also releases the subscription.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #records = new Map<T, AttributeLeaseRecord>();\n\n /** @param attribute - The attribute whose temporary values this lease owns. */\n constructor(attribute: string) {\n this.#attribute = attribute;\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const existing = this.#records.get(element);\n if (existing) {\n existing.written = value;\n } else {\n this.#records.set(element, {\n original: element.getAttribute(this.#attribute),\n written: value,\n });\n }\n\n this.#reflect(element, value);\n }\n\n /** Returns one lease without overwriting a value subsequently authored by a consumer. */\n return(element: T): void {\n const record = this.#records.get(element);\n if (!record) return;\n this.#records.delete(element);\n const stillOwned = element.getAttribute(this.#attribute) === record.written;\n if (stillOwned) this.#reflect(element, record.original);\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n if (element.getAttribute(this.#attribute) === value) return;\n if (value === null) element.removeAttribute(this.#attribute);\n else element.setAttribute(this.#attribute, value);\n }\n\n /** Returns every outstanding lease using the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#records.keys())) this.return(element);\n }\n}\n","/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way.\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Resolves which of a controller's elements owns a node.\n *\n * A delegated listener hears events from a whole subtree, so the handler's first\n * job is almost always the same question: which item, handle, or control does\n * this `event.target` belong to? The same question comes up for a\n * `MutationRecord.target`, for `document.activeElement`, and for a\n * `relatedTarget` on the way out of a hover region.\n *\n * The answer is `Node.contains()`, which is **inclusive** — an element contains\n * itself — so testing the candidate for identity as well would be redundant.\n *\n * **The guard is what makes this safe to call with a raw event target.**\n * `event.target` is typed `EventTarget | null`, and `contains()` takes a `Node?`:\n * browsers throw `TypeError` for anything else, and `window` — the everyday\n * `EventTarget` that is not a `Node` — is what an event dispatched at it carries.\n * Narrowing here means a caller never has to cast, and the rule cannot drift\n * between the places that ask the question.\n *\n * Scope stays with the caller. These helpers say *which candidate owns the node*,\n * not *whether the node belongs to this controller at all* — a component with\n * nested instances of itself decides that first (by comparing the closest\n * annotated ancestor) and passes the candidates it owns.\n */\n\n/**\n * Index in `candidates` of the first one that is, or contains, `node`.\n *\n * `-1` when none does, when `node` is absent, and when it is an `EventTarget`\n * that is not a `Node`. Candidates are tested in array order, so a nested pair\n * resolves to whichever the caller listed first.\n */\nexport function ownerIndex<T extends Element>(\n candidates: readonly T[],\n node: EventTarget | null | undefined,\n): number {\n if (!(node instanceof Node)) return -1;\n return candidates.findIndex((candidate) => candidate.contains(node));\n}\n\n/**\n * The first candidate that is, or contains, `node`; `null` when none does.\n *\n * A miss indexes the array at `-1`, which reads as `undefined` and lands on the\n * same `null` the absent cases produce.\n */\nexport function ownerOf<T extends Element>(\n candidates: readonly T[],\n node: EventTarget | null | undefined,\n): T | null {\n return candidates[ownerIndex(candidates, node)] ?? null;\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { announce } from \"../utils/announce\";\nimport { ensureId } from \"../utils/aria_ids\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { ownerIndex } from \"../utils/event_owner\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\n\n/** Stimulus action params understood by {@link FormFieldController.setError}. */\ninterface SetErrorParams {\n /** The error message to display. */\n message?: string;\n}\n\n/** An action event carrying Stimulus `data-*-param` values. */\ntype ActionEvent = Event & { params?: SetErrorParams };\n\n/** Programmatic behavior switches for {@link FormFieldController.setError}. */\nexport interface FormFieldSetErrorOptions {\n /** Override the `focusOnError` Value for this call. */\n focus?: boolean;\n}\n\n/** Detail dispatched with `stimeo--form-field:validate`. */\nexport interface FormFieldValidateDetail {\n /** Whether the explicit validation action left the field valid. */\n valid: boolean;\n /** The first visible error message, or an empty string when valid/unavailable. */\n message: string;\n}\n\n/** Attributes on retained association targets that can change the ARIA graph. */\nconst OBSERVED_ATTRIBUTES = [\"hidden\", \"id\"];\n\n/**\n * Headless, accessible form-field association behavior.\n *\n * Markup contract (identifier: `stimeo--form-field`):\n * <div data-controller=\"stimeo--form-field\">\n * <label for=\"email\">Email</label>\n * <input id=\"email\" type=\"email\" aria-invalid=\"false\"\n * data-stimeo--form-field-target=\"control\" />\n * <p data-stimeo--form-field-target=\"description\">We'll send a confirmation.</p>\n * <p hidden data-stimeo--form-field-target=\"error\"></p>\n * </div>\n *\n * Not an APG widget pattern — this is the wiring substrate behind form controls:\n * it supports **Name, Role, Value** (WCAG 4.1.2) and **error identification**\n * (3.3.1 / 4.1.3) by composing the control's `aria-describedby`, toggling\n * `aria-invalid`, and pointing `aria-errormessage` at the visual error.\n *\n * `validate` dispatches `{ valid: boolean, message: string }`.\n *\n * @remarks\n * Behavior only — it sets semantic attributes and the `hidden` state of the\n * visual error; it never validates input (the consumer / server decides) and\n * never styles. Runtime errors are handed to a separately seated\n * `stimeo--announcer`, because showing a live region together with its first\n * message is not a reliable announcement primitive.\n *\n * Behavior provided:\n * - Assigns ids to description/error targets and composes the control's\n * `aria-describedby` from them in DOM order (preserving the control's authored\n * tokens and removing duplicates).\n * - Reflects server-rendered errors: an error target that is already visible and\n * non-empty at connect puts the field into the invalid state (progressive\n * enhancement).\n * - Reconciles added, removed, replaced, and retained/morphed targets without\n * emitting validation events or announcements.\n * - {@link setError} / {@link clearError} drive the invalid state at runtime and\n * dispatch `stimeo--form-field:validate`.\n */\nexport class FormFieldController extends Controller<HTMLElement> {\n static override targets = [\"control\", \"description\", \"error\"];\n static override values = {\n focusOnError: { type: Boolean, default: false },\n };\n static actions = [\"clearError\", \"setError\"] as const;\n static events = [\"validate\"] as const;\n\n declare readonly controlTarget: HTMLElement;\n declare readonly hasControlTarget: boolean;\n declare readonly descriptionTargets: HTMLElement[];\n declare readonly errorTargets: HTMLElement[];\n declare readonly hasErrorTarget: boolean;\n /** Whether an explicit {@link setError} call moves focus to the current control. */\n declare focusOnErrorValue: boolean;\n\n /** Root attribute (CSS hook) reflecting the invalid state. */\n static readonly #INVALID_ATTR = \"data-stimeo--form-field-invalid\";\n\n /** Collapses one target/morph batch into one silent ARIA reconciliation. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileDom());\n /** Returns borrowed control ARIA before Turbo snapshots the page. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #ariaDescribedBy = new AttributeLease<HTMLElement>(\"aria-describedby\");\n readonly #ariaErrorMessage = new AttributeLease<HTMLElement>(\"aria-errormessage\");\n readonly #ariaInvalid = new AttributeLease<HTMLElement>(\"aria-invalid\");\n /** Watches retained target ids, error visibility, and error content. */\n readonly #observer = new MutationObserver((records) => {\n if (records.some((record) => this.#isRelevantMutation(record))) {\n this.#reconcile.schedule();\n }\n });\n\n #activeControl: HTMLElement | null = null;\n #baseDescribedBy: string[] = [];\n #explicitInvalid = false;\n #initialized = false;\n\n /** Wires the initial graph and starts retained-target reconciliation. */\n override connect(): void {\n this.#reconcile.activate();\n this.#ensureAssociationIds();\n this.#beforeCache.activate();\n\n // A restored DOM can contain the invalid hook with no surviving visual\n // message. Treat that one shape as the persisted explicit setError state;\n // visible server errors remain derived and can clear when their DOM clears.\n if (!this.#initialized) {\n this.#explicitInvalid =\n this.element.hasAttribute(FormFieldController.#INVALID_ATTR) &&\n this.#shownErrors().length === 0;\n this.#initialized = true;\n }\n\n this.#reconcileDom();\n this.#observer.observe(this.element, {\n attributes: true,\n attributeFilter: OBSERVED_ATTRIBUTES,\n characterData: true,\n childList: true,\n subtree: true,\n });\n }\n\n /** Releases observers, queued work, and ARIA borrowed on the current control. */\n override disconnect(): void {\n this.#reconcile.cancel();\n this.#observer.disconnect();\n this.#beforeCache.deactivate();\n this.#activeControl && this.#releaseControl(this.#activeControl);\n }\n\n /** Reconciles a control inserted or replaced at runtime. */\n controlTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Schedules restoration of authored ARIA when a control leaves this field. */\n controlTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Reconciles a description inserted or replaced at runtime. */\n descriptionTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Removes a departed description from the control's association graph. */\n descriptionTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Reconciles an error region inserted or replaced at runtime. */\n errorTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Removes a departed error from invalid state and the association graph. */\n errorTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Marks the field invalid and shows the error message. Bound via `data-action`\n * (`#setError`) or callable directly.\n *\n * A non-empty shown message is announced exactly once through the shared\n * assertive announcer. Initial/server reconciliation is deliberately silent.\n *\n * @param arg - Either the message string, or the action event whose\n * `data-stimeo--form-field-message-param` supplies it. When no message is\n * resolvable, any already-populated error targets are simply (re)shown.\n * @param options - Programmatic overrides. Stimulus actions use the Values.\n */\n setError(arg?: string | ActionEvent, options: FormFieldSetErrorOptions = {}): void {\n const message = this.#resolveMessage(arg);\n if (message !== null && this.hasErrorTarget) {\n this.errorTargets[0]?.replaceChildren(document.createTextNode(message));\n }\n for (const error of this.errorTargets) {\n error.hidden = (error.textContent ?? \"\").trim() === \"\";\n }\n\n // setError is an explicit invalid request: it remains invalid even if an\n // error target is absent or replaced before clearError is called.\n this.#explicitInvalid = true;\n this.#reconcileDom();\n const shownMessage = this.#shownMessage();\n const detail: FormFieldValidateDetail = { valid: false, message: shownMessage };\n this.dispatch(\"validate\", { detail });\n announce(shownMessage, { assertive: true });\n\n if (options.focus ?? this.focusOnErrorValue) this.#activeControl?.focus();\n }\n\n /**\n * Clears the error: empties and hides every error target and marks the field\n * valid. Bound via `data-action` (`#clearError`) or callable directly.\n *\n * Clearing is silent: the visual/ARIA state and validation event are sufficient,\n * while success wording remains an explicit consumer announcement.\n */\n clearError(): void {\n for (const error of this.errorTargets) {\n error.replaceChildren();\n error.hidden = true;\n }\n this.#explicitInvalid = false;\n this.#reconcileDom();\n const detail: FormFieldValidateDetail = { valid: true, message: \"\" };\n this.dispatch(\"validate\", { detail });\n }\n\n /**\n * Rebuilds ids and derived ARIA from the settled target graph without reporting\n * a user validation action.\n */\n #reconcileDom(): void {\n this.#ensureAssociationIds();\n this.#adoptCurrentControl();\n\n const shown = this.#shownErrors();\n const invalid = this.#explicitInvalid || shown.length > 0;\n this.element.toggleAttribute(FormFieldController.#INVALID_ATTR, invalid);\n\n const control = this.#activeControl;\n if (!control) return;\n\n this.#ariaInvalid.write(control, invalid ? \"true\" : \"false\");\n\n const primaryErrorId = shown[0]?.id ?? null;\n this.#ariaErrorMessage.write(control, primaryErrorId);\n\n const associationIds = this.#orderedElements([...this.descriptionTargets, ...shown]).map(\n (element) => element.id,\n );\n const describedBy = this.#uniqueTokens([...this.#baseDescribedBy, ...associationIds]);\n this.#ariaDescribedBy.write(control, describedBy.length > 0 ? describedBy.join(\" \") : null);\n }\n\n /** Assigns stable ids before either capture or reflection uses them. */\n #ensureAssociationIds(): void {\n for (const description of this.descriptionTargets) {\n ensureId(description, \"stimeo--form-field-desc\");\n }\n for (const error of this.errorTargets) {\n ensureId(error, \"stimeo--form-field-error\");\n }\n }\n\n /** Switches ARIA ownership when the singular current control target changes. */\n #adoptCurrentControl(): void {\n const next = this.hasControlTarget ? this.controlTarget : null;\n if (next === this.#activeControl) return;\n this.#activeControl && this.#releaseControl(this.#activeControl);\n this.#activeControl = next;\n this.#baseDescribedBy = next ? this.#externalDescribedByTokens(next) : [];\n }\n\n /** Restores one departed control without overwriting later consumer edits. */\n #releaseControl(control: HTMLElement): void {\n this.#ariaDescribedBy.return(control);\n this.#ariaErrorMessage.return(control);\n this.#ariaInvalid.return(control);\n if (control === this.#activeControl) {\n this.#activeControl = null;\n this.#baseDescribedBy = [];\n }\n }\n\n /** Error targets currently visible and non-empty, in document order. */\n #shownErrors(): HTMLElement[] {\n return this.#orderedElements(\n this.errorTargets.filter((error) => !error.hidden && (error.textContent ?? \"\").trim() !== \"\"),\n );\n }\n\n /** Text of the first shown error, for validation detail and announcement. */\n #shownMessage(): string {\n return (this.#shownErrors()[0]?.textContent ?? \"\").trim();\n }\n\n /** Resolves a message from a string argument or an action event's params. */\n #resolveMessage(arg?: string | ActionEvent): string | null {\n if (typeof arg === \"string\") return arg;\n const message = arg?.params?.message;\n return typeof message === \"string\" ? message : null;\n }\n\n /**\n * Tokens authored on a newly adopted control, excluding ids this controller\n * owns through its current description/error targets.\n */\n #externalDescribedByTokens(control: HTMLElement): string[] {\n const owned = new Set([\n ...this.descriptionTargets.map((description) => description.id),\n ...this.errorTargets.map((error) => error.id),\n ]);\n const existing = control.getAttribute(\"aria-describedby\") ?? \"\";\n return this.#uniqueTokens(\n existing.split(/\\s+/).filter((token) => token.length > 0 && !owned.has(token)),\n );\n }\n\n /** Deduplicates ARIA tokens without disturbing their first occurrence. */\n #uniqueTokens(tokens: string[]): string[] {\n const seen = new Set<string>();\n return tokens.filter((token) => {\n if (token.length === 0 || seen.has(token)) return false;\n seen.add(token);\n return true;\n });\n }\n\n /** Returns unique current targets in DOM order before serializing IDREF lists. */\n #orderedElements(elements: HTMLElement[]): HTMLElement[] {\n const candidates = new Set(elements);\n return [this.element, ...this.element.querySelectorAll<HTMLElement>(\"*\")].filter((element) =>\n candidates.has(element),\n );\n }\n\n /** Whether one retained-node mutation can alter this controller's derived state. */\n #isRelevantMutation(record: MutationRecord): boolean {\n const target = record.target;\n if (record.type === \"attributes\") {\n if (record.attributeName === \"hidden\")\n return this.errorTargets.includes(target as HTMLElement);\n return (\n record.attributeName === \"id\" &&\n [...this.descriptionTargets, ...this.errorTargets].includes(target as HTMLElement)\n );\n }\n\n return ownerIndex(this.errorTargets, target) !== -1;\n }\n /** Returns borrowed control ARIA before Turbo snapshots the page. */\n #rewindForCache(): void {\n this.#ariaDescribedBy.returnAll();\n this.#ariaErrorMessage.returnAll();\n this.#ariaInvalid.returnAll();\n }\n}\n"]}
@@ -60,8 +60,9 @@ declare function applyMask(value: string, pattern: string, tokens: ReadonlyMap<s
60
60
  * `stimeo--input-mask:reconcile` when the controller itself decides that value —
61
61
  * a server-rendered or restored value normalized on connection, or a re-format
62
62
  * after `pattern` / `tokens` / `unmaskToHidden` changed. A malformed `tokens`
63
- * declaration falls back to the default tokens: it is parsed once in
64
- * `tokensValueChanged`, and the hot path only ever sees the validated map. A field
63
+ * declaration falls back to the default tokens, and a single broken source falls
64
+ * back to that key's default: it is parsed once in `tokensValueChanged`, and the
65
+ * hot path only ever sees the validated map. A field
65
66
  * the user cannot edit (`readonly`, `disabled`, or inside a disabled `<fieldset>`)
66
67
  * keeps the value the page authored — the sink and the state hooks still follow it,
67
68
  * but the field itself is never rewritten. The composition listener is released on
@@ -49,6 +49,30 @@ var CompositionTracker = class {
49
49
  };
50
50
  };
51
51
 
52
+ // src/utils/declared_value.ts
53
+ function parseDeclared(raw, parse, fallback) {
54
+ try {
55
+ return parse(raw);
56
+ } catch {
57
+ return fallback;
58
+ }
59
+ }
60
+ function compileRegExp(source, anchor = "none") {
61
+ return parseDeclared(
62
+ source,
63
+ (text) => {
64
+ const bare = new RegExp(text);
65
+ return anchor === "exact" ? new RegExp(`^(?:${text})$`) : bare;
66
+ },
67
+ null
68
+ );
69
+ }
70
+ function parseJsonObject(raw) {
71
+ const parsed = parseDeclared(raw, (text) => JSON.parse(text), null);
72
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
73
+ return parsed;
74
+ }
75
+
52
76
  // src/utils/focus_candidate.ts
53
77
  function inheritsFieldsetDisabled(control) {
54
78
  let fieldset = control.closest("fieldset[disabled]");
@@ -118,22 +142,19 @@ function applyMask(value, pattern, tokens) {
118
142
  }
119
143
  function compileTokens(declaration) {
120
144
  const map = /* @__PURE__ */ new Map();
121
- for (const [key, source] of Object.entries({ ...DEFAULT_TOKENS, ...parseTokens(declaration) })) {
122
- try {
123
- map.set(key, new RegExp(`^(?:${source})$`));
124
- } catch {
125
- }
145
+ for (const [key, source] of Object.entries(DEFAULT_TOKENS)) {
146
+ const compiled = compileRegExp(source, "exact");
147
+ if (compiled) map.set(key, compiled);
148
+ }
149
+ for (const [key, source] of Object.entries(parseTokens(declaration))) {
150
+ const compiled = compileRegExp(source, "exact");
151
+ if (compiled) map.set(key, compiled);
126
152
  }
127
153
  return map;
128
154
  }
129
155
  function parseTokens(declaration) {
130
- let parsed;
131
- try {
132
- parsed = JSON.parse(declaration);
133
- } catch {
134
- return {};
135
- }
136
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
156
+ const parsed = parseJsonObject(declaration);
157
+ if (parsed === null) return {};
137
158
  const tokens = {};
138
159
  for (const [key, source] of Object.entries(parsed)) {
139
160
  if (typeof source === "string") tokens[key] = source;