stimeo-ui 0.8.0 → 0.10.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 (167) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/dist/controllers/accordion_controller.js.map +1 -1
  3. package/dist/controllers/alert_dialog_controller.js +17 -7
  4. package/dist/controllers/alert_dialog_controller.js.map +1 -1
  5. package/dist/controllers/announcer_controller.js +1 -1
  6. package/dist/controllers/announcer_controller.js.map +1 -1
  7. package/dist/controllers/auto_submit_controller.js.map +1 -1
  8. package/dist/controllers/avatar_controller.js.map +1 -1
  9. package/dist/controllers/breadcrumb_controller.js.map +1 -1
  10. package/dist/controllers/bulk_select_controller.d.ts +62 -15
  11. package/dist/controllers/bulk_select_controller.js +139 -28
  12. package/dist/controllers/bulk_select_controller.js.map +1 -1
  13. package/dist/controllers/calendar_controller.js.map +1 -1
  14. package/dist/controllers/carousel_controller.js.map +1 -1
  15. package/dist/controllers/character_counter_controller.js.map +1 -1
  16. package/dist/controllers/clipboard_controller.d.ts +48 -15
  17. package/dist/controllers/clipboard_controller.js +102 -20
  18. package/dist/controllers/clipboard_controller.js.map +1 -1
  19. package/dist/controllers/collapsible_controller.d.ts +1 -1
  20. package/dist/controllers/collapsible_controller.js +1 -1
  21. package/dist/controllers/collapsible_controller.js.map +1 -1
  22. package/dist/controllers/color_picker_controller.d.ts +37 -6
  23. package/dist/controllers/color_picker_controller.js +180 -43
  24. package/dist/controllers/color_picker_controller.js.map +1 -1
  25. package/dist/controllers/combobox_controller.js.map +1 -1
  26. package/dist/controllers/command_palette_controller.js +15 -5
  27. package/dist/controllers/command_palette_controller.js.map +1 -1
  28. package/dist/controllers/conditional_fields_controller.js.map +1 -1
  29. package/dist/controllers/confirm_controller.js +15 -5
  30. package/dist/controllers/confirm_controller.js.map +1 -1
  31. package/dist/controllers/context_menu_controller.d.ts +5 -4
  32. package/dist/controllers/context_menu_controller.js.map +1 -1
  33. package/dist/controllers/count_up_controller.js.map +1 -1
  34. package/dist/controllers/countdown_controller.js +1 -1
  35. package/dist/controllers/countdown_controller.js.map +1 -1
  36. package/dist/controllers/data_grid_controller.d.ts +25 -9
  37. package/dist/controllers/data_grid_controller.js +151 -25
  38. package/dist/controllers/data_grid_controller.js.map +1 -1
  39. package/dist/controllers/date_range_picker_controller.js.map +1 -1
  40. package/dist/controllers/dialog_controller.js +15 -5
  41. package/dist/controllers/dialog_controller.js.map +1 -1
  42. package/dist/controllers/direct_upload_controller.d.ts +2 -2
  43. package/dist/controllers/direct_upload_controller.js +1 -5
  44. package/dist/controllers/direct_upload_controller.js.map +1 -1
  45. package/dist/controllers/dismissible_controller.js.map +1 -1
  46. package/dist/controllers/drawer_controller.d.ts +2 -2
  47. package/dist/controllers/drawer_controller.js +17 -7
  48. package/dist/controllers/drawer_controller.js.map +1 -1
  49. package/dist/controllers/editable_controller.d.ts +34 -9
  50. package/dist/controllers/editable_controller.js +83 -30
  51. package/dist/controllers/editable_controller.js.map +1 -1
  52. package/dist/controllers/file_dropzone_controller.js.map +1 -1
  53. package/dist/controllers/filter_controller.d.ts +15 -3
  54. package/dist/controllers/filter_controller.js +32 -1
  55. package/dist/controllers/filter_controller.js.map +1 -1
  56. package/dist/controllers/flash_controller.js.map +1 -1
  57. package/dist/controllers/focus_controller.d.ts +5 -0
  58. package/dist/controllers/focus_controller.js +45 -7
  59. package/dist/controllers/focus_controller.js.map +1 -1
  60. package/dist/controllers/form_field_controller.js +1 -1
  61. package/dist/controllers/form_field_controller.js.map +1 -1
  62. package/dist/controllers/form_validation_controller.js.map +1 -1
  63. package/dist/controllers/frame_loading_controller.js.map +1 -1
  64. package/dist/controllers/highlight_controller.js.map +1 -1
  65. package/dist/controllers/input_mask_controller.js.map +1 -1
  66. package/dist/controllers/intersection_controller.d.ts +4 -3
  67. package/dist/controllers/intersection_controller.js.map +1 -1
  68. package/dist/controllers/lazy_frame_controller.d.ts +2 -2
  69. package/dist/controllers/lazy_frame_controller.js.map +1 -1
  70. package/dist/controllers/listbox_controller.js.map +1 -1
  71. package/dist/controllers/masonry_controller.d.ts +36 -5
  72. package/dist/controllers/masonry_controller.js +129 -17
  73. package/dist/controllers/masonry_controller.js.map +1 -1
  74. package/dist/controllers/menu_controller.d.ts +1 -1
  75. package/dist/controllers/menu_controller.js.map +1 -1
  76. package/dist/controllers/menubar_controller.js +2 -2
  77. package/dist/controllers/menubar_controller.js.map +1 -1
  78. package/dist/controllers/meter_controller.d.ts +1 -1
  79. package/dist/controllers/meter_controller.js.map +1 -1
  80. package/dist/controllers/multi_select_controller.js +1 -1
  81. package/dist/controllers/multi_select_controller.js.map +1 -1
  82. package/dist/controllers/navigation_menu_controller.js.map +1 -1
  83. package/dist/controllers/nested_form_controller.js.map +1 -1
  84. package/dist/controllers/number_input_controller.js.map +1 -1
  85. package/dist/controllers/otp_controller.d.ts +4 -1
  86. package/dist/controllers/otp_controller.js +29 -16
  87. package/dist/controllers/otp_controller.js.map +1 -1
  88. package/dist/controllers/overflow_indicator_controller.js.map +1 -1
  89. package/dist/controllers/overflow_menu_controller.js +2 -2
  90. package/dist/controllers/overflow_menu_controller.js.map +1 -1
  91. package/dist/controllers/pagination_controller.d.ts +1 -1
  92. package/dist/controllers/pagination_controller.js.map +1 -1
  93. package/dist/controllers/password_reveal_controller.d.ts +27 -2
  94. package/dist/controllers/password_reveal_controller.js +102 -3
  95. package/dist/controllers/password_reveal_controller.js.map +1 -1
  96. package/dist/controllers/password_strength_controller.d.ts +71 -17
  97. package/dist/controllers/password_strength_controller.js +287 -42
  98. package/dist/controllers/password_strength_controller.js.map +1 -1
  99. package/dist/controllers/pointer_drag_controller.d.ts +3 -2
  100. package/dist/controllers/pointer_drag_controller.js.map +1 -1
  101. package/dist/controllers/popover_controller.js.map +1 -1
  102. package/dist/controllers/portal_controller.d.ts +1 -1
  103. package/dist/controllers/portal_controller.js.map +1 -1
  104. package/dist/controllers/progress_controller.js.map +1 -1
  105. package/dist/controllers/radio_group_controller.js.map +1 -1
  106. package/dist/controllers/range_slider_controller.js.map +1 -1
  107. package/dist/controllers/rating_controller.js.map +1 -1
  108. package/dist/controllers/read_more_controller.js.map +1 -1
  109. package/dist/controllers/relative_time_controller.js.map +1 -1
  110. package/dist/controllers/reset_before_cache_controller.d.ts +26 -4
  111. package/dist/controllers/reset_before_cache_controller.js +51 -5
  112. package/dist/controllers/reset_before_cache_controller.js.map +1 -1
  113. package/dist/controllers/resizable_controller.d.ts +23 -7
  114. package/dist/controllers/resizable_controller.js +128 -55
  115. package/dist/controllers/resizable_controller.js.map +1 -1
  116. package/dist/controllers/roving_controller.d.ts +2 -1
  117. package/dist/controllers/roving_controller.js.map +1 -1
  118. package/dist/controllers/scroll_area_controller.js.map +1 -1
  119. package/dist/controllers/scroll_restore_controller.d.ts +33 -11
  120. package/dist/controllers/scroll_restore_controller.js +127 -27
  121. package/dist/controllers/scroll_restore_controller.js.map +1 -1
  122. package/dist/controllers/scroll_visibility_controller.d.ts +42 -10
  123. package/dist/controllers/scroll_visibility_controller.js +167 -14
  124. package/dist/controllers/scroll_visibility_controller.js.map +1 -1
  125. package/dist/controllers/scrollspy_controller.js.map +1 -1
  126. package/dist/controllers/separator_controller.js.map +1 -1
  127. package/dist/controllers/sidebar_controller.js +15 -5
  128. package/dist/controllers/sidebar_controller.js.map +1 -1
  129. package/dist/controllers/skeleton_controller.js.map +1 -1
  130. package/dist/controllers/slider_controller.js.map +1 -1
  131. package/dist/controllers/spinner_controller.js.map +1 -1
  132. package/dist/controllers/step_indicator_controller.js +0 -5
  133. package/dist/controllers/step_indicator_controller.js.map +1 -1
  134. package/dist/controllers/stick_to_bottom_controller.d.ts +3 -2
  135. package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
  136. package/dist/controllers/submit_once_controller.js.map +1 -1
  137. package/dist/controllers/switch_controller.js.map +1 -1
  138. package/dist/controllers/tabs_controller.js.map +1 -1
  139. package/dist/controllers/tags_input_controller.js.map +1 -1
  140. package/dist/controllers/textarea_autosize_controller.js.map +1 -1
  141. package/dist/controllers/theme_controller.d.ts +32 -6
  142. package/dist/controllers/theme_controller.js +151 -40
  143. package/dist/controllers/theme_controller.js.map +1 -1
  144. package/dist/controllers/time_picker_controller.js.map +1 -1
  145. package/dist/controllers/toast_controller.d.ts +2 -2
  146. package/dist/controllers/toast_controller.js +2 -2
  147. package/dist/controllers/toast_controller.js.map +1 -1
  148. package/dist/controllers/toggle_group_controller.js.map +1 -1
  149. package/dist/controllers/toolbar_controller.js.map +1 -1
  150. package/dist/controllers/transition_controller.d.ts +11 -7
  151. package/dist/controllers/transition_controller.js +79 -15
  152. package/dist/controllers/transition_controller.js.map +1 -1
  153. package/dist/controllers/tree_view_controller.js.map +1 -1
  154. package/dist/index.d.ts +6 -3
  155. package/dist/index.js +1612 -529
  156. package/dist/index.js.map +1 -1
  157. package/dist/inspector/cli.d.ts +3 -4
  158. package/dist/inspector/cli.js +3 -0
  159. package/dist/inspector/cli.js.map +1 -1
  160. package/dist/inspector/cli_bin.js +8 -5
  161. package/dist/inspector/cli_bin.js.map +1 -1
  162. package/dist/inspector/examples.json +25 -25
  163. package/dist/inspector/manifest.json +18 -11
  164. package/dist/positioning/index.d.ts +18 -4
  165. package/dist/positioning/index.js +84 -25
  166. package/dist/positioning/index.js.map +1 -1
  167. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/controllers/stick_to_bottom_controller.ts"],"names":[],"mappings":";;;;;AAmBO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OACE,OAAO,MAAA,CAAO,UAAA,KAAe,cAC7B,MAAA,CAAO,UAAA,CAAW,kCAAkC,CAAA,CAAE,OAAA;AAE1D;;;ACpBA,IAAM,aAAA,GAAgB,CAAC,KAAA,KAA4B;AACjD,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO,IAAI,KAAK,QAAA,KAAa,IAAA,CAAK,cAAc,CAAA,IAA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AA8B;AAC5B,IAAA,IAAA,CAAK,SAAS,UAAA,EAAW;AACzB,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,eAAA,CAAgB,QAAA,GAA2B,IAAA,CAAK,SAAA,EAAU,EAAS;AACjE,IAAA,MAAM,GAAA,GAAM,KAAK,OAAA,CAAQ,YAAA;AACzB,IAAA,IAAI,OAAO,IAAA,CAAK,OAAA,CAAQ,QAAA,KAAa,UAAA,EAAY;AAC/C,MAAA,IAAA,CAAK,OAAA,CAAQ,QAAA,CAAS,EAAE,GAAA,EAAK,UAAU,CAAA;AAAA,IACzC,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,QAAQ,SAAA,GAAY,GAAA;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA,EAGA,QAAA,GAAwB;AACtB,IAAA,OAAO,IAAA,CAAK,gBAAA,GAAmB,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,OAAA;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,SAAA,GAA4B;AAC1B,IAAA,IAAI,oBAAA,IAAwB,OAAO,SAAA;AACnC,IAAA,OAAO,IAAA,CAAK,aAAA,KAAkB,QAAA,GAAW,QAAA,GAAW,MAAA;AAAA,EACtD;AACF","file":"stick_to_bottom_controller.js","sourcesContent":["/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n * (count-up, highlight, overflow-indicator, scroll-visibility, stick-to-bottom,\n * transition).\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/** Counts the element nodes in an added-node list (text nodes are ignored). */\nconst countElements = (nodes: NodeList): number => {\n let n = 0;\n for (const node of nodes) if (node.nodeType === Node.ELEMENT_NODE) n += 1;\n return n;\n};\n\n/**\n * Headless **stick-to-bottom**: auto-follows new content to the bottom of a scroll\n * container (a chat log, a live console) — but only while the user is already near the\n * bottom; if they have scrolled up to read, it holds position and flags that new content\n * arrived instead (no APG pattern; honors WCAG 2.3.3 via `prefers-reduced-motion` and\n * never steals focus).\n *\n * Markup contract (identifier: `stimeo--stick-to-bottom`):\n * <div data-controller=\"stimeo--stick-to-bottom\"\n * data-stimeo--stick-to-bottom-threshold-value=\"80\"\n * data-stimeo--stick-to-bottom-pin-on-connect-value=\"true\" style=\"overflow:auto\">\n * <ul data-stimeo--stick-to-bottom-target=\"content\"><!-- Turbo Stream appends --></ul>\n * </div>\n *\n * The container is \"pinned\" while its distance from the bottom is within `threshold`. A\n * `MutationObserver` on `content` (or the element) reacts to appended children: while\n * pinned it scrolls to the bottom; while unpinned it sets `data-has-new` and emits `new`.\n * Scrolling recomputes pinned and reflects `data-pinned`, emitting `pin` on change; the\n * `scrollToBottom` action jumps back down (a \"new messages\" button).\n *\n * A container renders at `scrollTop` 0 — unpinned — so out of the box it flags the first\n * append rather than following it. `pinOnConnect` opts into the other starting point:\n * `connect()` jumps to the bottom and reads the state back from where it landed. It runs\n * on every connect, so a container inserted or re-rendered later (a Turbo Stream, a panel\n * built on open) starts at the bottom too — which a once-per-document page event cannot\n * do. It is off by default, so a restored reading position (a Turbo cache restore, a user\n * who had scrolled up) is never yanked to the bottom unless the consumer asks for it.\n *\n * `pin` dispatches `{ pinned }`; `new` dispatches `{ count }`.\n *\n * @remarks\n * The `MutationObserver` watches `childList` only (not `subtree`), so it follows\n * direct appends to `content` (or the element). Appends made deeper inside a nested\n * wrapper are not detected — keep messages as direct children, or call the public\n * `scrollToBottom` action after such inserts.\n *\n * Behavior only — it does not add content (Turbo Stream / the consumer does) and is the\n * minimal follow primitive, not a full chat UI (no virtualization / message input). State\n * is derived from the scroll position each pass (no module-scope state), so `connect()`\n * re-syncs after a Turbo Stream insert; reduced motion forces an instant jump\n * independently of consumer CSS; auto-scroll never moves focus; the observer and the\n * passive scroll listener are released on `disconnect()` (Turbo navigation included).\n */\nexport class StickToBottomController extends Controller<HTMLElement> {\n static override targets = [\"content\"];\n static override values = {\n threshold: { type: Number, default: 80 },\n behavior: { type: String, default: \"auto\" },\n pinOnConnect: { type: Boolean, default: false },\n };\n static actions = [\"scrollToBottom\"] as const;\n static events = [\"pin\", \"new\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n\n declare thresholdValue: number;\n declare behaviorValue: string;\n declare pinOnConnectValue: boolean;\n\n #observer: MutationObserver | null = null;\n /** Watches for the box a deferred `pinOnConnect` jump is still waiting on. */\n #layout: ResizeObserver | null = null;\n #pinned = false;\n\n readonly #onScroll = (): void => this.#updatePinned();\n\n override connect(): void {\n // Instant whatever `behavior` says, overriding a consumer's `scroll-behavior: smooth`:\n // an animated jump emits scroll events on the way down, each recomputing pinned from a\n // position still far from the bottom, so the container would unpin (and re-pin)\n // mid-flight before it ever settles.\n if (this.pinOnConnectValue && this.#measurable()) this.#scrollToBottom(\"instant\");\n // Read the state back from where the container actually is, asked for a jump or not: a\n // request the engine does not honor must leave it unpinned, so the next append is\n // flagged rather than swallowed. This also drops a stale data-pinned / data-has-new a\n // Turbo cache restore brought back.\n this.#pinned = this.#isPinned();\n this.#reflectPinned();\n\n this.element.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n if (typeof MutationObserver !== \"undefined\") {\n this.#observer = new MutationObserver((mutations) => this.#onMutations(mutations));\n this.#observer.observe(this.#watched(), { childList: true });\n }\n if (this.pinOnConnectValue && !this.#measurable()) this.#pinWhenLaidOut();\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"scroll\", this.#onScroll);\n this.#observer?.disconnect();\n this.#observer = null;\n this.#stopWaitingForLayout();\n }\n\n /**\n * Jumps to the bottom and re-pins (wired to a \"new messages\" button).\n *\n * The has-new flag clears on request — the user has acknowledged the arrival — while\n * pinned is read back from where the scroll landed: a jump that arrives by the time\n * this returns pins immediately, an animated one settles from its own scroll events,\n * and a jump the engine cannot honor leaves the container unpinned, so the next append\n * flags it again instead of being swallowed by a pinned state that does not hold.\n *\n * Which of those happens is not this method's to decide — see {@link behaviorValue}.\n */\n scrollToBottom(): void {\n this.#scrollToBottom();\n this.element.removeAttribute(\"data-has-new\");\n this.#updatePinned();\n }\n\n /** Follows appended children while pinned; otherwise flags new content. */\n #onMutations(mutations: MutationRecord[]): void {\n let added = 0;\n for (const mutation of mutations) added += countElements(mutation.addedNodes);\n if (added === 0) return;\n\n if (this.#pinned) {\n this.#scrollToBottom();\n } else {\n this.element.setAttribute(\"data-has-new\", \"true\");\n this.dispatch(\"new\", { detail: { count: added } });\n }\n }\n\n /** Recomputes pinned from the scroll position and reflects it on a transition. */\n #updatePinned(): void {\n const pinned = this.#isPinned();\n if (pinned === this.#pinned) return;\n this.#pinned = pinned;\n this.#reflectPinned();\n this.dispatch(\"pin\", { detail: { pinned } });\n }\n\n /** Mirrors the current `#pinned` onto the state hooks (clearing has-new once pinned). */\n #reflectPinned(): void {\n if (this.#pinned) {\n this.element.setAttribute(\"data-pinned\", \"true\");\n this.element.removeAttribute(\"data-has-new\"); // caught up with the bottom\n } else {\n this.element.removeAttribute(\"data-pinned\");\n }\n }\n\n #isPinned(): boolean {\n const el = this.element;\n return el.scrollHeight - el.clientHeight - el.scrollTop <= this.thresholdValue;\n }\n\n /**\n * Whether the container has a box to scroll and to measure. One that is not rendered\n * (inside a closed panel) reports every metric as 0, which reads as \"already at the\n * bottom\" — a position describing no layout the user will ever see.\n */\n #measurable(): boolean {\n return this.element.clientHeight > 0;\n }\n\n /**\n * Holds the `pinOnConnect` jump until the container is laid out, then runs it and\n * re-reads the state — otherwise the panel opens at the top still claiming the bottom.\n */\n #pinWhenLaidOut(): void {\n if (typeof ResizeObserver === \"undefined\") return;\n this.#layout = new ResizeObserver(() => {\n if (!this.#measurable()) return;\n this.#stopWaitingForLayout();\n this.#scrollToBottom(\"instant\");\n this.#updatePinned();\n });\n this.#layout.observe(this.element);\n }\n\n /** Releases the layout watch, whether or not the deferred jump ever ran. */\n #stopWaitingForLayout(): void {\n this.#layout?.disconnect();\n this.#layout = null;\n }\n\n /**\n * Scrolls to the bottom, clamped by the engine to the maximum scroll offset — which is\n * 0 for a container tall enough to hold its whole content, so the jump moves nothing\n * there. `behavior` defaults to the configured follow behavior; pass `\"instant\"` for a\n * jump that must not animate.\n */\n #scrollToBottom(behavior: ScrollBehavior = this.#behavior()): void {\n const top = this.element.scrollHeight;\n if (typeof this.element.scrollTo === \"function\") {\n this.element.scrollTo({ top, behavior });\n } else {\n this.element.scrollTop = top;\n }\n }\n\n /** The append-watched element: the `content` target, or the container itself. */\n #watched(): HTMLElement {\n return this.hasContentTarget ? this.contentTarget : this.element;\n }\n\n /**\n * The behavior a follow-scroll runs with. `\"auto\"` is **not** a request to arrive at\n * once: it hands the decision to the element's computed `scroll-behavior`, so a\n * consumer stylesheet saying `smooth` animates these scrolls too. Only `\"instant\"`\n * overrides that CSS, which is why reduced motion and the `pinOnConnect` jump name it.\n */\n #behavior(): ScrollBehavior {\n if (prefersReducedMotion()) return \"instant\";\n return this.behaviorValue === \"smooth\" ? \"smooth\" : \"auto\";\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/controllers/stick_to_bottom_controller.ts"],"names":[],"mappings":";;;;;AAkBO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OACE,OAAO,MAAA,CAAO,UAAA,KAAe,cAC7B,MAAA,CAAO,UAAA,C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C3B,MAAA,IAAA,CAAK,gBAAgB,SAAS,CAAA;AAC9B,MAAA,IAAA,CAAK,aAAA,EAAc;AAAA,IACrB,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,OAAO,CAAA;AAAA,EACnC;AAAA;AAAA,EAGA,qBAAA,GAA8B;AAC5B,IAAA,IAAA,CAAK,SAAS,UAAA,EAAW;AACzB,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,eAAA,CAAgB,QAAA,GAA2B,IAAA,CAAK,SAAA,EAAU,EAAS;AACjE,IAAA,MAAM,GAAA,GAAM,KAAK,OAAA,CAAQ,YAAA;AACzB,IAAA,IAAI,OAAO,IAAA,CAAK,OAAA,CAAQ,QAAA,KAAa,UAAA,EAAY;AAC/C,MAAA,IAAA,CAAK,OAAA,CAAQ,QAAA,CAAS,EAAE,GAAA,EAAK,UAAU,CAAA;AAAA,IACzC,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,QAAQ,SAAA,GAAY,GAAA;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA,EAGA,QAAA,GAAwB;AACtB,IAAA,OAAO,IAAA,CAAK,gBAAA,GAAmB,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,OAAA;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,SAAA,GAA4B;AAC1B,IAAA,IAAI,oBAAA,IAAwB,OAAO,SAAA;AACnC,IAAA,OAAO,IAAA,CAAK,aAAA,KAAkB,QAAA,GAAW,QAAA,GAAW,MAAA;AAAA,EACtD;AACF","file":"stick_to_bottom_controller.js","sourcesContent":["/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n *.\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/** Counts the element nodes in an added-node list (text nodes are ignored). */\nconst countElements = (nodes: NodeList): number => {\n let n = 0;\n for (const node of nodes) if (node.nodeType === Node.ELEMENT_NODE) n += 1;\n return n;\n};\n\n/**\n * Headless **stick-to-bottom**: auto-follows new content to the bottom of a scroll\n * container (a chat log, a live console) — but only while the user is already near the\n * bottom; if they have scrolled up to read, it holds position and flags that new content\n * arrived instead (no APG pattern; honors WCAG 2.3.3 via `prefers-reduced-motion` and\n * never steals focus).\n *\n * Markup contract (identifier: `stimeo--stick-to-bottom`):\n * <div data-controller=\"stimeo--stick-to-bottom\"\n * data-stimeo--stick-to-bottom-threshold-value=\"80\"\n * data-stimeo--stick-to-bottom-pin-on-connect-value=\"true\" style=\"overflow:auto\">\n * <ul data-stimeo--stick-to-bottom-target=\"content\"><!-- Turbo Stream appends --></ul>\n * </div>\n *\n * The container is \"pinned\" while its distance from the bottom is within `threshold`. A\n * `MutationObserver` on `content` (or the element) reacts to appended children: while\n * pinned it scrolls to the bottom; while unpinned it sets `data-has-new` and emits `new`.\n * Scrolling recomputes pinned and reflects `data-pinned`, emitting `pin` on change; the\n * `scrollToBottom` action jumps back down (a \"new messages\" button).\n *\n * A container that already overflows renders at `scrollTop` 0 — further than\n * `threshold` from the bottom, so unpinned — and flags the first append rather\n * than following it. `pinOnConnect` opts into the other starting point:\n * `connect()` jumps to the bottom and reads the state back from where it landed. It runs\n * on every connect, so a container inserted or re-rendered later (a Turbo Stream, a panel\n * built on open) starts at the bottom too — which a once-per-document page event cannot\n * do. It is off by default, so a restored reading position (a Turbo cache restore, a user\n * who had scrolled up) is never yanked to the bottom unless the consumer asks for it.\n *\n * `pin` dispatches `{ pinned }`; `new` dispatches `{ count }`.\n *\n * @remarks\n * The `MutationObserver` watches `childList` only (not `subtree`), so it follows\n * direct appends to `content` (or the element). Appends made deeper inside a nested\n * wrapper are not detected — keep messages as direct children, or call the public\n * `scrollToBottom` action after such inserts.\n *\n * Behavior only — it does not add content (Turbo Stream / the consumer does) and is the\n * minimal follow primitive, not a full chat UI (no virtualization / message input). State\n * is derived from the scroll position each pass (no module-scope state), so `connect()`\n * re-syncs after a Turbo Stream insert; reduced motion forces an instant jump\n * independently of consumer CSS; auto-scroll never moves focus; the observer and the\n * passive scroll listener are released on `disconnect()` (Turbo navigation included).\n */\nexport class StickToBottomController extends Controller<HTMLElement> {\n static override targets = [\"content\"];\n static override values = {\n threshold: { type: Number, default: 80 },\n behavior: { type: String, default: \"auto\" },\n pinOnConnect: { type: Boolean, default: false },\n };\n static actions = [\"scrollToBottom\"] as const;\n static events = [\"pin\", \"new\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n\n declare thresholdValue: number;\n declare behaviorValue: string;\n declare pinOnConnectValue: boolean;\n\n #observer: MutationObserver | null = null;\n /** Watches for the box a deferred `pinOnConnect` jump is still waiting on. */\n #layout: ResizeObserver | null = null;\n #pinned = false;\n\n readonly #onScroll = (): void => this.#updatePinned();\n\n override connect(): void {\n // Instant whatever `behavior` says, overriding a consumer's `scroll-behavior: smooth`:\n // an animated jump emits scroll events on the way down, each recomputing pinned from a\n // position still far from the bottom, so the container would unpin (and re-pin)\n // mid-flight before it ever settles.\n if (this.pinOnConnectValue && this.#measurable()) this.#scrollToBottom(\"instant\");\n // Read the state back from where the container actually is, asked for a jump or not: a\n // request the engine does not honor must leave it unpinned, so the next append is\n // flagged rather than swallowed. This also drops a stale data-pinned / data-has-new a\n // Turbo cache restore brought back.\n this.#pinned = this.#isPinned();\n this.#reflectPinned();\n\n this.element.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n if (typeof MutationObserver !== \"undefined\") {\n this.#observer = new MutationObserver((mutations) => this.#onMutations(mutations));\n this.#observer.observe(this.#watched(), { childList: true });\n }\n if (this.pinOnConnectValue && !this.#measurable()) this.#pinWhenLaidOut();\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"scroll\", this.#onScroll);\n this.#observer?.disconnect();\n this.#observer = null;\n this.#stopWaitingForLayout();\n }\n\n /**\n * Jumps to the bottom and re-pins (wired to a \"new messages\" button).\n *\n * The has-new flag clears on request — the user has acknowledged the arrival — while\n * pinned is read back from where the scroll landed: a jump that arrives by the time\n * this returns pins immediately, an animated one settles from its own scroll events,\n * and a jump the engine cannot honor leaves the container unpinned, so the next append\n * flags it again instead of being swallowed by a pinned state that does not hold.\n *\n * Which of those happens is not this method's to decide — see {@link behaviorValue}.\n */\n scrollToBottom(): void {\n this.#scrollToBottom();\n this.element.removeAttribute(\"data-has-new\");\n this.#updatePinned();\n }\n\n /** Follows appended children while pinned; otherwise flags new content. */\n #onMutations(mutations: MutationRecord[]): void {\n let added = 0;\n for (const mutation of mutations) added += countElements(mutation.addedNodes);\n if (added === 0) return;\n\n if (this.#pinned) {\n this.#scrollToBottom();\n } else {\n this.element.setAttribute(\"data-has-new\", \"true\");\n this.dispatch(\"new\", { detail: { count: added } });\n }\n }\n\n /** Recomputes pinned from the scroll position and reflects it on a transition. */\n #updatePinned(): void {\n const pinned = this.#isPinned();\n if (pinned === this.#pinned) return;\n this.#pinned = pinned;\n this.#reflectPinned();\n this.dispatch(\"pin\", { detail: { pinned } });\n }\n\n /** Mirrors the current `#pinned` onto the state hooks (clearing has-new once pinned). */\n #reflectPinned(): void {\n if (this.#pinned) {\n this.element.setAttribute(\"data-pinned\", \"true\");\n this.element.removeAttribute(\"data-has-new\"); // caught up with the bottom\n } else {\n this.element.removeAttribute(\"data-pinned\");\n }\n }\n\n #isPinned(): boolean {\n const el = this.element;\n return el.scrollHeight - el.clientHeight - el.scrollTop <= this.thresholdValue;\n }\n\n /**\n * Whether the container has a box to scroll and to measure. One that is not rendered\n * (inside a closed panel) reports every metric as 0, which reads as \"already at the\n * bottom\" — a position describing no layout the user will ever see.\n */\n #measurable(): boolean {\n return this.element.clientHeight > 0;\n }\n\n /**\n * Holds the `pinOnConnect` jump until the container is laid out, then runs it and\n * re-reads the state — otherwise the panel opens at the top still claiming the bottom.\n */\n #pinWhenLaidOut(): void {\n if (typeof ResizeObserver === \"undefined\") return;\n this.#layout = new ResizeObserver(() => {\n if (!this.#measurable()) return;\n this.#stopWaitingForLayout();\n this.#scrollToBottom(\"instant\");\n this.#updatePinned();\n });\n this.#layout.observe(this.element);\n }\n\n /** Releases the layout watch, whether or not the deferred jump ever ran. */\n #stopWaitingForLayout(): void {\n this.#layout?.disconnect();\n this.#layout = null;\n }\n\n /**\n * Scrolls to the bottom, clamped by the engine to the maximum scroll offset — which is\n * 0 for a container tall enough to hold its whole content, so the jump moves nothing\n * there. `behavior` defaults to the configured follow behavior; pass `\"instant\"` for a\n * jump that must not animate.\n */\n #scrollToBottom(behavior: ScrollBehavior = this.#behavior()): void {\n const top = this.element.scrollHeight;\n if (typeof this.element.scrollTo === \"function\") {\n this.element.scrollTo({ top, behavior });\n } else {\n this.element.scrollTop = top;\n }\n }\n\n /** The append-watched element: the `content` target, or the container itself. */\n #watched(): HTMLElement {\n return this.hasContentTarget ? this.contentTarget : this.element;\n }\n\n /**\n * The behavior a follow-scroll runs with. `\"auto\"` is **not** a request to arrive at\n * once: it hands the decision to the element's computed `scroll-behavior`, so a\n * consumer stylesheet saying `smooth` animates these scrolls too. Only `\"instant\"`\n * overrides that CSS, which is why reduced motion and the `pinOnConnect` jump name it.\n */\n #behavior(): ScrollBehavior {\n if (prefersReducedMotion()) return \"instant\";\n return this.behaviorValue === \"smooth\" ? \"smooth\" : \"auto\";\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/detach_gate.ts","../../src/utils/safe_timeout.ts","../../src/controllers/submit_once_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;;;ACJO,IAAM,iBAAN,MAAkD;AAAA,EAC9C,UAAA;AAAA,EACA,QAAA,uBAAe,GAAA,EAA6B;AAAA;AAAA,EAGrD,YAAY,SAAA,EAAmB;AAC7B,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,KAAA,CAAM,SAAY,KAAA,EAA4B;AAC5C,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAO,CAAA;AAC1C,IAAA,IAAI,QAAA,EAAU;AACZ,MAAA,QAAA,CAAS,OAAA,GAAU,KAAA;AAAA,IACrB,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,QAAA,CAAS,IAAI,OAAA,EAAS;AAAA,QACzB,QAAA,EAAU,OAAA,CAAQ,YAAA,CAAa,IAAA,CAAK,UAAU,CAAA;AAAA,QAC9C,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH;AAEA,IAAA,IAAA,CAAK,QAAA,CAAS,SAAS,KAAK,CAAA;AAAA,EAC9B;AAAA;AAAA,EAGA,OAAO,OAAA,EAAkB;AACvB,IAAA,MAAM,MAAA,GAAS,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;AAAA,EAGA,uBAAuB,OAAA,EAA4C;AACjE,IAAA,IAAI,OAAA,YAAmB,iBAAA,EAAmB,OAAO,OAAA,CAAQ,IAAA,KAAS,QAAA;AAClE,IAAA,OACE,mBAAmB,gBAAA,KAAqB,OAAA,CAAQ,IAAA,KAAS,QAAA,IAAY,QAAQ,IAAA,KAAS,OAAA,CAAA;AAAA,EAE1F;AAAA;AAAA,EAGA,WAAA,CAAY,SAAwB,KAAA,EAA0C;AAC5E,IAAA,OACE,KAAA,CAAM,IAAA;AAAA,MACJ,CAAC,SACC,OAAA,CAAQ,QAAA,CAAS,IAAI,CAAA,IACrB,IAAA,CAAK,OAAA,CAAQ,+CAA+C,CAAA,KAAM;AAAA,KACtE,IAAK,IAAA;AAAA,EAET;AAAA;AAAA,EAGA,cAAc,KAAA,EAAmC;AAC/C,IAAA,MAAM,OAAA,GAAW,MAA6C,MAAA,EAAQ,OAAA;AACtE,IAAA,OAAO,OAAO,OAAA,KAAY,SAAA,GAAY,OAAA,GAAU,MAAA;AAAA,EAClD;AACF","file":"submit_once_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","/** 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 (the `MicrotaskCoalescer` split).\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 * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * Policy stays with the consumer (the `SafeTimeout` / `FocusTrap` lineage —\n * this util owns the discrimination only):\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * #teardown(): void {\n * this.#gate.cancel(); // disarm a still-queued probe (double-run guard)\n * // …\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True while a probe is queued — the last disconnect was ambiguous and no\n * reconnect has cancelled it yet. Read it from `connect()` to tell the\n * reconnect half of an in-page move from a first connect: a controller whose\n * initialisation restarts a measurement (a min-duration floor, an elapsed\n * counter) must skip it for the move, where nothing actually restarted.\n */\n get pending(): boolean {\n return this.#pending;\n }\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n if (!host.element.isConnected) return true;\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return !tokens.includes(host.identifier);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n if (DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n queueMicrotask(() => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n });\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { announce } from \"../utils/announce\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { DetachGate } from \"../utils/detach_gate\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Native controls that can submit a form. */\ntype SubmitControl = HTMLButtonElement | HTMLInputElement;\n\n/** Why an active submission returned to idle. */\ntype CompletionReason = \"canceled\" | \"manual\" | \"timeout\" | \"turbo\";\n\n/** A text/value write that cannot be represented by an {@link AttributeLease}. */\ntype LabelWrite =\n | {\n readonly channel: \"text\";\n readonly control: HTMLButtonElement;\n readonly original: string;\n readonly written: string;\n }\n | {\n readonly channel: \"value\";\n readonly control: HTMLInputElement;\n readonly original: string;\n readonly written: string;\n };\n\n/** One form's independent in-flight submission. */\ninterface SubmissionSession {\n readonly form: HTMLFormElement;\n readonly submitter: SubmitControl | null;\n readonly submitterHadFocus: boolean;\n readonly controls: Set<SubmitControl>;\n timeoutId: number | null;\n labelWrite: LabelWrite | null;\n idlePart: HTMLElement | null;\n busyPart: HTMLElement | null;\n}\n\n/** Per-button override for the controller's default busy label. */\nconst BUTTON_BUSY_LABEL = \"data-submit-once-busy-label\";\n\n/**\n * Headless form-scoped double-submit guard (identifier:\n * `stimeo--submit-once`). It disables every native submit control associated\n * with the submitting form, publishes busy state, and restores only the state\n * it still owns when the operation finishes.\n *\n * Turbo forms need no `data-action`: the controller observes\n * `turbo:submit-start` and `turbo:submit-end` itself.\n *\n * A non-Turbo async form owns its own lifecycle and declares each transition:\n * `submit->stimeo--submit-once#start` applies the busy state synchronously,\n * before the request is issued, and `#finish` / `#cancel` end it. Cancelling the\n * event's default is how such a form suppresses the native navigation, so it\n * never means the submission died — only `#cancel` does. A submit already\n * cancelled by an earlier listener never starts a session at all.\n *\n * ```html\n * <form data-controller=\"stimeo--submit-once\"\n * data-action=\"submit->stimeo--submit-once#start\n * save:complete->stimeo--submit-once#finish\n * save:error->stimeo--submit-once#cancel\">\n * <button type=\"submit\">Save</button>\n * </form>\n * ```\n *\n * A form whose submit a later listener vetoes needs `#cancel` wired to that\n * veto, or a non-zero `timeout`, to leave the busy state.\n *\n * Plain text buttons can use `busyLabel` (overridden by\n * `data-submit-once-busy-label`). A button with authored structure instead uses\n * an `idle` / `busy` target pair inside that button, so icons and descendants\n * are never replaced with `textContent`:\n *\n * ```html\n * <form data-controller=\"stimeo--submit-once\"\n * data-stimeo--submit-once-announce-text-value=\"Saving…\"\n * data-stimeo--submit-once-announce-ready-text-value=\"Saved.\">\n * <button type=\"submit\" data-stimeo--submit-once-target=\"submit\">\n * <span data-stimeo--submit-once-target=\"idle\">Save</span>\n * <span data-stimeo--submit-once-target=\"busy\" hidden>Saving…</span>\n * </button>\n * </form>\n * ```\n *\n * Events:\n * - `stimeo--submit-once:start` — `{ form, submitter }`.\n * - `stimeo--submit-once:reconcile` — `{ forms: HTMLFormElement[] }`, the forms\n * whose in-flight submission the Turbo cache rewind abandoned. `end` would\n * claim the submission resolved, so the rewind reports itself instead.\n * - `stimeo--submit-once:end` — `{ form, submitter, reason, success? }`, where\n * `reason` is `\"turbo\"`, `\"timeout\"`, `\"manual\"`, or `\"canceled\"`. Only\n * `\"canceled\"` skips the completion announcement, because no operation ran.\n *\n * @remarks\n * Behavior only: the consumer owns every visual, label, and announcement\n * string. `announceText` / `announceReadyText` are empty by default and speak\n * through the page's shared `stimeo--announcer` only on real state transitions.\n * Attribute writes use {@link AttributeLease}, so a consumer mutation made\n * while busy wins over restoration. {@link DetachGate} preserves an in-flight\n * session across an in-page move, while {@link BeforeCacheReset} rewinds the\n * snapshot before Turbo caches it. Cache/detach rewinds are silent and never\n * move focus.\n */\nexport class SubmitOnceController extends Controller<HTMLElement> {\n static override targets = [\"submit\", \"idle\", \"busy\"];\n static override values = {\n announceText: { type: String, default: \"\" },\n announceReadyText: { type: String, default: \"\" },\n busyLabel: { type: String, default: \"\" },\n timeout: { type: Number, default: 0 },\n restoreFocus: { type: Boolean, default: false },\n };\n static actions = [\"cancel\", \"finish\", \"start\"] as const;\n static events = [\"start\", \"end\", \"reconcile\"] as const;\n\n declare readonly submitTargets: SubmitControl[];\n declare readonly idleTargets: HTMLElement[];\n declare readonly busyTargets: HTMLElement[];\n\n declare announceTextValue: string;\n declare announceReadyTextValue: string;\n declare busyLabelValue: string;\n declare timeoutValue: number;\n declare restoreFocusValue: boolean;\n\n readonly #timers = new SafeTimeout();\n readonly #gate = new DetachGate();\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #sessions = new Map<HTMLFormElement, SubmissionSession>();\n\n readonly #disabled = new AttributeLease<SubmitControl>(\"disabled\");\n readonly #controlBusy = new AttributeLease<SubmitControl>(\"aria-busy\");\n readonly #formBusy = new AttributeLease<HTMLFormElement>(\"aria-busy\");\n readonly #submitting = new AttributeLease<HTMLFormElement>(\"data-submitting\");\n readonly #ariaLabel = new AttributeLease<HTMLButtonElement>(\"aria-label\");\n readonly #hidden = new AttributeLease<HTMLElement>(\"hidden\");\n\n readonly #onSubmitStart = (event: Event): void => {\n this.start(event);\n };\n\n readonly #onSubmitEnd = (event: Event): void => {\n this.#complete(this.#eventForm(event), \"turbo\", this.#eventSuccess(event));\n };\n\n /** Blocks a later native submit while one for the same form is still active. */\n readonly #onNativeSubmit = (event: Event): void => {\n // The submit event's target is its form. This listener runs in capture so it\n // always observes that first event before a public `start` action creates the\n // session, while a later event sees the session and is canceled here.\n const session = this.#sessionFor(event.target);\n if (!session) return;\n this.#syncControls(session);\n event.preventDefault();\n };\n\n override connect(): void {\n this.#gate.cancel();\n this.#beforeCache.activate();\n this.element.addEventListener(\"submit\", this.#onNativeSubmit, true);\n this.element.addEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"submit\", this.#onNativeSubmit, true);\n this.element.removeEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#beforeCache.deactivate();\n this.#gate.disconnected(this, () => this.#teardown());\n }\n\n /**\n * Begins the submission represented by `event`.\n *\n * Native `submit` events are intended for non-Turbo async forms. Turbo calls\n * this path through its auto-subscribed `turbo:submit-start` event. An event\n * whose default an earlier listener already cancelled carries no submission,\n * so it starts nothing.\n */\n start(event: Event): void {\n if (event.defaultPrevented) return;\n const form = this.#eventForm(event);\n if (!form || this.#sessions.has(form)) return;\n\n const controls = this.#submitControls(form);\n const submitter = this.#resolveSubmitter(event, controls);\n const session: SubmissionSession = {\n form,\n submitter,\n submitterHadFocus: submitter !== null && document.activeElement === submitter,\n controls: new Set(),\n timeoutId: null,\n labelWrite: null,\n idlePart: null,\n busyPart: null,\n };\n this.#sessions.set(form, session);\n\n this.#formBusy.write(form, \"true\");\n this.#submitting.write(form, \"true\");\n this.#syncControls(session, controls);\n this.#enterLabel(session);\n this.dispatch(\"start\", { detail: { form, submitter } });\n\n if (this.timeoutValue > 0) {\n session.timeoutId = this.#timers.set(\n () => this.#complete(form, \"timeout\", false),\n this.timeoutValue,\n );\n }\n\n announce(this.announceTextValue);\n }\n\n /**\n * Completes a non-Turbo async submission for the form associated with\n * `event`. When called directly with no event, it completes the controller's\n * sole active form (or the controller element itself when it is a form).\n */\n finish(event?: Event): void {\n const form = event ? this.#eventForm(event) : this.#defaultForm();\n this.#complete(form, \"manual\", event ? this.#eventSuccess(event) : undefined);\n }\n\n /**\n * Abandons the submission for the form associated with `event` because it\n * never reached the network — a veto from validation, or a request the\n * consumer gave up before sending. With no event it targets the controller's\n * sole active form, exactly like {@link finish}.\n *\n * The distinction from `finish` is observable: a request that ran and failed\n * is `finish` with `success: false` and still announces completion, while a\n * submission that never happened announces nothing.\n */\n cancel(event?: Event): void {\n const form = event ? this.#eventForm(event) : this.#defaultForm();\n this.#complete(form, \"canceled\", false);\n }\n\n /** Disables a newly connected explicit submit target during its form's session. */\n submitTargetConnected(target: SubmitControl): void {\n const session = this.#sessionFor(target.form);\n if (!session || !this.#isNativeSubmitControl(target)) return;\n this.#enterControl(session, target);\n }\n\n /** Ends one session, restores owned state, and reports the observable completion. */\n #complete(form: HTMLFormElement | null, reason: CompletionReason, success?: boolean): void {\n const session = this.#sessionFor(form);\n if (!session) return;\n this.#sessions.delete(session.form);\n this.#returnSessionState(session);\n\n const detail =\n success === undefined\n ? { form: session.form, submitter: session.submitter, reason }\n : { form: session.form, submitter: session.submitter, reason, success };\n this.dispatch(\"end\", { detail });\n this.#restoreFocus(session);\n if (reason !== \"canceled\") announce(this.announceReadyTextValue);\n }\n\n /** Applies the busy state to every current native/explicit control exactly once. */\n #syncControls(session: SubmissionSession, controls = this.#submitControls(session.form)): void {\n for (const control of controls) this.#enterControl(session, control);\n }\n\n /** Temporarily disables one enabled submit control while retaining authored state. */\n #enterControl(session: SubmissionSession, control: SubmitControl): void {\n if (session.controls.has(control) || control.matches(\":disabled\")) return;\n session.controls.add(control);\n this.#disabled.write(control, \"\");\n this.#controlBusy.write(control, \"true\");\n }\n\n /** Swaps only the triggering control's safe label channel. */\n #enterLabel(session: SubmissionSession): void {\n const control = session.submitter;\n if (!control) return;\n\n const idlePart = this.#partInside(control, this.idleTargets);\n const busyPart = this.#partInside(control, this.busyTargets);\n if (idlePart && busyPart) {\n session.idlePart = idlePart;\n session.busyPart = busyPart;\n this.#hidden.write(idlePart, \"\");\n this.#hidden.write(busyPart, null);\n }\n\n const label = control.getAttribute(BUTTON_BUSY_LABEL) ?? this.busyLabelValue;\n if (label.length === 0) return;\n if (control instanceof HTMLInputElement) {\n // `input[type=image]#value` is submitted data, not a visible label.\n if (control.type !== \"submit\") return;\n session.labelWrite = {\n channel: \"value\",\n control,\n original: control.value,\n written: label,\n };\n control.value = label;\n return;\n }\n if (control.hasAttribute(\"aria-label\")) {\n this.#ariaLabel.write(control, label);\n return;\n }\n // A structured button needs the explicit idle/busy pair above. Replacing its\n // textContent would destroy icons, counters, and application-owned listeners.\n if (control.childElementCount > 0) return;\n session.labelWrite = {\n channel: \"text\",\n control,\n original: control.textContent ?? \"\",\n written: label,\n };\n control.textContent = label;\n }\n\n /** Returns labels, controls, and form hooks, respecting intervening consumer writes. */\n #returnSessionState(session: SubmissionSession): void {\n if (session.timeoutId !== null) {\n this.#timers.clear(session.timeoutId);\n session.timeoutId = null;\n }\n\n if (session.labelWrite?.channel === \"value\") {\n const { control, original, written } = session.labelWrite;\n if (control.value === written) control.value = original;\n } else if (session.labelWrite?.channel === \"text\") {\n const { control, original, written } = session.labelWrite;\n if (control.childElementCount === 0 && control.textContent === written) {\n control.textContent = original;\n }\n }\n session.labelWrite = null;\n\n if (session.submitter instanceof HTMLButtonElement) {\n this.#ariaLabel.return(session.submitter);\n }\n if (session.idlePart) this.#hidden.return(session.idlePart);\n if (session.busyPart) this.#hidden.return(session.busyPart);\n session.idlePart = null;\n session.busyPart = null;\n\n for (const control of session.controls) {\n this.#controlBusy.return(control);\n this.#disabled.return(control);\n }\n session.controls.clear();\n this.#submitting.return(session.form);\n this.#formBusy.return(session.form);\n }\n\n /** Restores focus only when disabling the focused submitter actually stranded it. */\n #restoreFocus(session: SubmissionSession): void {\n const submitter = session.submitter;\n if (!this.restoreFocusValue || !session.submitterHadFocus || !submitter?.isConnected) return;\n const active = document.activeElement;\n if (active === null || active === document.body || active === document.documentElement) {\n submitter.focus();\n }\n }\n\n /** Silently abandons every session before caching or on a real detach. */\n #abandonSessions(): void {\n this.#timers.clearAll();\n for (const session of this.#sessions.values()) {\n session.timeoutId = null;\n this.#returnSessionState(session);\n }\n this.#sessions.clear();\n }\n\n /** Keeps Turbo's cached snapshot idle, without events, announcements, or focus moves. */\n #rewindForCache(): void {\n const forms = [...this.#sessions.keys()];\n this.#abandonSessions();\n // A submission in flight dies with the navigation, so a consumer still\n // painting \"submitting\" from `start` would never be released.\n if (forms.length > 0) this.dispatch(\"reconcile\", { detail: { forms } });\n }\n\n /** Tears down a true detach; an in-page move is canceled by the next `connect()`. */\n #teardown(): void {\n this.#gate.cancel();\n this.#abandonSessions();\n }\n\n /** All native controls associated with `form`, plus valid explicit targets. */\n #submitControls(form: HTMLFormElement): SubmitControl[] {\n const controls = new Set<SubmitControl>();\n for (const element of Array.from(form.elements)) {\n if (this.#isNativeSubmitControl(element)) controls.add(element);\n }\n // Browsers historically omit input[type=image] from form.elements. Search\n // the form's tree root as well so descendant and external `form=` image\n // submitters receive the same guard without broadening into sibling forms.\n const root = form.getRootNode() as ParentNode;\n for (const image of root.querySelectorAll<HTMLInputElement>('input[type=\"image\"]')) {\n if (image.form === form) controls.add(image);\n }\n return Array.from(controls);\n }\n\n /** Resolves the real submitter, falling back to the first enabled submit control. */\n #resolveSubmitter(event: Event, controls: SubmitControl[]): SubmitControl | null {\n const submitter = this.#eventSubmitter(event);\n if (submitter && controls.includes(submitter)) return submitter;\n return controls.find((control) => !control.matches(\":disabled\")) ?? controls[0] ?? null;\n }\n\n /** Reads a native or Turbo submitter without assuming `SubmitEvent` exists. */\n #eventSubmitter(event: Event): SubmitControl | null {\n if (typeof SubmitEvent !== \"undefined\" && event instanceof SubmitEvent) {\n return this.#isNativeSubmitControl(event.submitter) ? event.submitter : null;\n }\n const detail = (event as CustomEvent<{ formSubmission?: { submitter?: HTMLElement | null } }>)\n .detail;\n const submitter = detail?.formSubmission?.submitter;\n return this.#isNativeSubmitControl(submitter) ? submitter : null;\n }\n\n /** Finds the form represented by an action/Turbo event and verifies this scope owns it. */\n #eventForm(event: Event): HTMLFormElement | null {\n const detail = (\n event as CustomEvent<{\n form?: HTMLFormElement;\n formSubmission?: { formElement?: HTMLFormElement; submitter?: HTMLElement | null };\n }>\n ).detail;\n const target = event.target;\n const candidate =\n (target instanceof HTMLFormElement ? target : null) ??\n (target instanceof Element ? target.closest(\"form\") : null) ??\n detail?.formSubmission?.formElement ??\n detail?.form ??\n this.#eventSubmitter(event)?.form ??\n (this.element instanceof HTMLFormElement ? this.element : null);\n return candidate && this.#ownsForm(candidate) ? candidate : null;\n }\n\n /** The only unambiguous form for a direct `finish()` call. */\n #defaultForm(): HTMLFormElement | null {\n if (this.element instanceof HTMLFormElement && this.#ownsForm(this.element))\n return this.element;\n if (this.#sessions.size === 1) return this.#sessions.keys().next().value ?? null;\n return null;\n }\n\n /** Prevents an ancestor controller from also taking over a nested instance's form. */\n #ownsForm(form: HTMLFormElement): boolean {\n let candidate: Element | null = form;\n while (candidate) {\n const identifiers = (candidate.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n if (identifiers.includes(this.identifier)) return candidate === this.element;\n candidate = candidate.parentElement;\n }\n return false;\n }\n\n /** Returns the active session for a form-shaped external event value. */\n #sessionFor(candidate: unknown): SubmissionSession | undefined {\n if (!(candidate instanceof HTMLFormElement)) return undefined;\n return this.#sessions.get(candidate);\n }\n\n /** Effective native submit controls, including implicit buttons and image inputs. */\n #isNativeSubmitControl(element: unknown): element is SubmitControl {\n if (element instanceof HTMLButtonElement) return element.type === \"submit\";\n return (\n element instanceof HTMLInputElement && (element.type === \"submit\" || element.type === \"image\")\n );\n }\n\n /** Finds a structured label part belonging to this button, not a nested control. */\n #partInside(control: SubmitControl, parts: HTMLElement[]): HTMLElement | null {\n return (\n parts.find(\n (part) =>\n control.contains(part) &&\n part.closest(\"button, input[type=submit], input[type=image]\") === control,\n ) ?? null\n );\n }\n\n /** Reads an optional boolean `success` from Turbo or a manual completion event. */\n #eventSuccess(event: Event): boolean | undefined {\n const success = (event as CustomEvent<{ success?: unknown }>).detail?.success;\n return typeof success === \"boolean\" ? success : undefined;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/detach_gate.ts","../../src/utils/safe_timeout.ts","../../src/controllers/submit_once_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;;;ACJO,IAAM,iBAAN,MAAkD;AAAA,EAC9C,UAAA;AAAA,EACA,QAAA,uBAAe,GAAA,EAA6B;AAAA;AAAA,EAGrD,YAAY,SAAA,EAAmB;AAC7B,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,KAAA,CAAM,SAAY,KAAA,EAA4B;AAC5C,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAO,CAAA;AAC1C,IAAA,IAAI,QAAA,EAAU;AACZ,MAAA,QAAA,CAAS,OAAA,GAAU,KAAA;AAAA,IACrB,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,QAAA,CAAS,IAAI,OAAA,EAAS;AAAA,QACzB,QAAA,EAAU,OAAA,CAAQ,YAAA,CAAa,IAAA,CAAK,UAAU,CAAA;AAAA,QAC9C,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH;AAEA,IAAA,IAAA,CAAK,QAAA,CAAS,SAAS,KAAK,CAAA;AAAA,EAC9B;AAAA;AAAA,EAGA,OAAO,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U,GAAA,CAAI,SAAS,CAAA;AAAA,EACrC;AAAA;AAAA,EAGA,uBAAuB,OAAA,EAA4C;AACjE,IAAA,IAAI,OAAA,YAAmB,iBAAA,EAAmB,OAAO,OAAA,CAAQ,IAAA,KAAS,QAAA;AAClE,IAAA,OACE,mBAAmB,gBAAA,KAAqB,OAAA,CAAQ,IAAA,KAAS,QAAA,IAAY,QAAQ,IAAA,KAAS,OAAA,CAAA;AAAA,EAE1F;AAAA;AAAA,EAGA,WAAA,CAAY,SAAwB,KAAA,EAA0C;AAC5E,IAAA,OACE,KAAA,CAAM,IAAA;AAAA,MACJ,CAAC,SACC,OAAA,CAAQ,QAAA,CAAS,IAAI,CAAA,IACrB,IAAA,CAAK,OAAA,CAAQ,+CAA+C,CAAA,KAAM;AAAA,KACtE,IAAK,IAAA;AAAA,EAET;AAAA;AAAA,EAGA,cAAc,KAAA,EAAmC;AAC/C,IAAA,MAAM,OAAA,GAAW,MAA6C,MAAA,EAAQ,OAAA;AACtE,IAAA,OAAO,OAAO,OAAA,KAAY,SAAA,GAAY,OAAA,GAAU,MAAA;AAAA,EAClD;AACF","file":"submit_once_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","/** 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 * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * Policy stays with the consumer; this util owns the discrimination only:\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * #teardown(): void {\n * this.#gate.cancel(); // disarm a still-queued probe (double-run guard)\n * // …\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True while a probe is queued — the last disconnect was ambiguous and no\n * reconnect has cancelled it yet. Read it from `connect()` to tell the\n * reconnect half of an in-page move from a first connect: a controller whose\n * initialisation restarts a measurement (a min-duration floor, an elapsed\n * counter) must skip it for the move, where nothing actually restarted.\n */\n get pending(): boolean {\n return this.#pending;\n }\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n if (!host.element.isConnected) return true;\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return !tokens.includes(host.identifier);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n if (DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n queueMicrotask(() => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n });\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { announce } from \"../utils/announce\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { DetachGate } from \"../utils/detach_gate\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Native controls that can submit a form. */\ntype SubmitControl = HTMLButtonElement | HTMLInputElement;\n\n/** Why an active submission returned to idle. */\ntype CompletionReason = \"canceled\" | \"manual\" | \"timeout\" | \"turbo\";\n\n/** A text/value write that cannot be represented by an {@link AttributeLease}. */\ntype LabelWrite =\n | {\n readonly channel: \"text\";\n readonly control: HTMLButtonElement;\n readonly original: string;\n readonly written: string;\n }\n | {\n readonly channel: \"value\";\n readonly control: HTMLInputElement;\n readonly original: string;\n readonly written: string;\n };\n\n/** One form's independent in-flight submission. */\ninterface SubmissionSession {\n readonly form: HTMLFormElement;\n readonly submitter: SubmitControl | null;\n readonly submitterHadFocus: boolean;\n readonly controls: Set<SubmitControl>;\n timeoutId: number | null;\n labelWrite: LabelWrite | null;\n idlePart: HTMLElement | null;\n busyPart: HTMLElement | null;\n}\n\n/** Per-button override for the controller's default busy label. */\nconst BUTTON_BUSY_LABEL = \"data-submit-once-busy-label\";\n\n/**\n * Headless form-scoped double-submit guard (identifier:\n * `stimeo--submit-once`). It disables every native submit control associated\n * with the submitting form, publishes busy state, and restores only the state\n * it still owns when the operation finishes.\n *\n * Turbo forms need no `data-action`: the controller observes\n * `turbo:submit-start` and `turbo:submit-end` itself.\n *\n * A non-Turbo async form owns its own lifecycle and declares each transition:\n * `submit->stimeo--submit-once#start` applies the busy state synchronously,\n * before the request is issued, and `#finish` / `#cancel` end it. Cancelling the\n * event's default is how such a form suppresses the native navigation, so it\n * never means the submission died — only `#cancel` does. A submit already\n * cancelled by an earlier listener never starts a session at all.\n *\n * ```html\n * <form data-controller=\"stimeo--submit-once\"\n * data-action=\"submit->stimeo--submit-once#start\n * save:complete->stimeo--submit-once#finish\n * save:error->stimeo--submit-once#cancel\">\n * <button type=\"submit\">Save</button>\n * </form>\n * ```\n *\n * A form whose submit a later listener vetoes needs `#cancel` wired to that\n * veto, or a non-zero `timeout`, to leave the busy state.\n *\n * Plain text buttons can use `busyLabel` (overridden by\n * `data-submit-once-busy-label`). A button with authored structure instead uses\n * an `idle` / `busy` target pair inside that button, so icons and descendants\n * are never replaced with `textContent`:\n *\n * ```html\n * <form data-controller=\"stimeo--submit-once\"\n * data-stimeo--submit-once-announce-text-value=\"Saving…\"\n * data-stimeo--submit-once-announce-ready-text-value=\"Saved.\">\n * <button type=\"submit\" data-stimeo--submit-once-target=\"submit\">\n * <span data-stimeo--submit-once-target=\"idle\">Save</span>\n * <span data-stimeo--submit-once-target=\"busy\" hidden>Saving…</span>\n * </button>\n * </form>\n * ```\n *\n * Events:\n * - `stimeo--submit-once:start` — `{ form, submitter }`.\n * - `stimeo--submit-once:reconcile` — `{ forms: HTMLFormElement[] }`, the forms\n * whose in-flight submission the Turbo cache rewind abandoned. `end` would\n * claim the submission resolved, so the rewind reports itself instead.\n * - `stimeo--submit-once:end` — `{ form, submitter, reason, success? }`, where\n * `reason` is `\"turbo\"`, `\"timeout\"`, `\"manual\"`, or `\"canceled\"`. Only\n * `\"canceled\"` skips the completion announcement, because no operation ran.\n *\n * @remarks\n * Behavior only: the consumer owns every visual, label, and announcement\n * string. `announceText` / `announceReadyText` are empty by default and speak\n * through the page's shared `stimeo--announcer` only on real state transitions.\n * Attribute writes use {@link AttributeLease}, so a consumer mutation made\n * while busy wins over restoration. {@link DetachGate} preserves an in-flight\n * session across an in-page move, while {@link BeforeCacheReset} rewinds the\n * snapshot before Turbo caches it. Cache/detach rewinds are silent and never\n * move focus.\n */\nexport class SubmitOnceController extends Controller<HTMLElement> {\n static override targets = [\"submit\", \"idle\", \"busy\"];\n static override values = {\n announceText: { type: String, default: \"\" },\n announceReadyText: { type: String, default: \"\" },\n busyLabel: { type: String, default: \"\" },\n timeout: { type: Number, default: 0 },\n restoreFocus: { type: Boolean, default: false },\n };\n static actions = [\"cancel\", \"finish\", \"start\"] as const;\n static events = [\"start\", \"end\", \"reconcile\"] as const;\n\n declare readonly submitTargets: SubmitControl[];\n declare readonly idleTargets: HTMLElement[];\n declare readonly busyTargets: HTMLElement[];\n\n declare announceTextValue: string;\n declare announceReadyTextValue: string;\n declare busyLabelValue: string;\n declare timeoutValue: number;\n declare restoreFocusValue: boolean;\n\n readonly #timers = new SafeTimeout();\n readonly #gate = new DetachGate();\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #sessions = new Map<HTMLFormElement, SubmissionSession>();\n\n readonly #disabled = new AttributeLease<SubmitControl>(\"disabled\");\n readonly #controlBusy = new AttributeLease<SubmitControl>(\"aria-busy\");\n readonly #formBusy = new AttributeLease<HTMLFormElement>(\"aria-busy\");\n readonly #submitting = new AttributeLease<HTMLFormElement>(\"data-submitting\");\n readonly #ariaLabel = new AttributeLease<HTMLButtonElement>(\"aria-label\");\n readonly #hidden = new AttributeLease<HTMLElement>(\"hidden\");\n\n readonly #onSubmitStart = (event: Event): void => {\n this.start(event);\n };\n\n readonly #onSubmitEnd = (event: Event): void => {\n this.#complete(this.#eventForm(event), \"turbo\", this.#eventSuccess(event));\n };\n\n /** Blocks a later native submit while one for the same form is still active. */\n readonly #onNativeSubmit = (event: Event): void => {\n // The submit event's target is its form. This listener runs in capture so it\n // always observes that first event before a public `start` action creates the\n // session, while a later event sees the session and is canceled here.\n const session = this.#sessionFor(event.target);\n if (!session) return;\n this.#syncControls(session);\n event.preventDefault();\n };\n\n override connect(): void {\n this.#gate.cancel();\n this.#beforeCache.activate();\n this.element.addEventListener(\"submit\", this.#onNativeSubmit, true);\n this.element.addEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"submit\", this.#onNativeSubmit, true);\n this.element.removeEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#beforeCache.deactivate();\n this.#gate.disconnected(this, () => this.#teardown());\n }\n\n /**\n * Begins the submission represented by `event`.\n *\n * Native `submit` events are intended for non-Turbo async forms. Turbo calls\n * this path through its auto-subscribed `turbo:submit-start` event. An event\n * whose default an earlier listener already cancelled carries no submission,\n * so it starts nothing.\n */\n start(event: Event): void {\n if (event.defaultPrevented) return;\n const form = this.#eventForm(event);\n if (!form || this.#sessions.has(form)) return;\n\n const controls = this.#submitControls(form);\n const submitter = this.#resolveSubmitter(event, controls);\n const session: SubmissionSession = {\n form,\n submitter,\n submitterHadFocus: submitter !== null && document.activeElement === submitter,\n controls: new Set(),\n timeoutId: null,\n labelWrite: null,\n idlePart: null,\n busyPart: null,\n };\n this.#sessions.set(form, session);\n\n this.#formBusy.write(form, \"true\");\n this.#submitting.write(form, \"true\");\n this.#syncControls(session, controls);\n this.#enterLabel(session);\n this.dispatch(\"start\", { detail: { form, submitter } });\n\n if (this.timeoutValue > 0) {\n session.timeoutId = this.#timers.set(\n () => this.#complete(form, \"timeout\", false),\n this.timeoutValue,\n );\n }\n\n announce(this.announceTextValue);\n }\n\n /**\n * Completes a non-Turbo async submission for the form associated with\n * `event`. When called directly with no event, it completes the controller's\n * sole active form (or the controller element itself when it is a form).\n */\n finish(event?: Event): void {\n const form = event ? this.#eventForm(event) : this.#defaultForm();\n this.#complete(form, \"manual\", event ? this.#eventSuccess(event) : undefined);\n }\n\n /**\n * Abandons the submission for the form associated with `event` because it\n * never reached the network — a veto from validation, or a request the\n * consumer gave up before sending. With no event it targets the controller's\n * sole active form, exactly like {@link finish}.\n *\n * The distinction from `finish` is observable: a request that ran and failed\n * is `finish` with `success: false` and still announces completion, while a\n * submission that never happened announces nothing.\n */\n cancel(event?: Event): void {\n const form = event ? this.#eventForm(event) : this.#defaultForm();\n this.#complete(form, \"canceled\", false);\n }\n\n /** Disables a newly connected explicit submit target during its form's session. */\n submitTargetConnected(target: SubmitControl): void {\n const session = this.#sessionFor(target.form);\n if (!session || !this.#isNativeSubmitControl(target)) return;\n this.#enterControl(session, target);\n }\n\n /** Ends one session, restores owned state, and reports the observable completion. */\n #complete(form: HTMLFormElement | null, reason: CompletionReason, success?: boolean): void {\n const session = this.#sessionFor(form);\n if (!session) return;\n this.#sessions.delete(session.form);\n this.#returnSessionState(session);\n\n const detail =\n success === undefined\n ? { form: session.form, submitter: session.submitter, reason }\n : { form: session.form, submitter: session.submitter, reason, success };\n this.dispatch(\"end\", { detail });\n this.#restoreFocus(session);\n if (reason !== \"canceled\") announce(this.announceReadyTextValue);\n }\n\n /** Applies the busy state to every current native/explicit control exactly once. */\n #syncControls(session: SubmissionSession, controls = this.#submitControls(session.form)): void {\n for (const control of controls) this.#enterControl(session, control);\n }\n\n /** Temporarily disables one enabled submit control while retaining authored state. */\n #enterControl(session: SubmissionSession, control: SubmitControl): void {\n if (session.controls.has(control) || control.matches(\":disabled\")) return;\n session.controls.add(control);\n this.#disabled.write(control, \"\");\n this.#controlBusy.write(control, \"true\");\n }\n\n /** Swaps only the triggering control's safe label channel. */\n #enterLabel(session: SubmissionSession): void {\n const control = session.submitter;\n if (!control) return;\n\n const idlePart = this.#partInside(control, this.idleTargets);\n const busyPart = this.#partInside(control, this.busyTargets);\n if (idlePart && busyPart) {\n session.idlePart = idlePart;\n session.busyPart = busyPart;\n this.#hidden.write(idlePart, \"\");\n this.#hidden.write(busyPart, null);\n }\n\n const label = control.getAttribute(BUTTON_BUSY_LABEL) ?? this.busyLabelValue;\n if (label.length === 0) return;\n if (control instanceof HTMLInputElement) {\n // `input[type=image]#value` is submitted data, not a visible label.\n if (control.type !== \"submit\") return;\n session.labelWrite = {\n channel: \"value\",\n control,\n original: control.value,\n written: label,\n };\n control.value = label;\n return;\n }\n if (control.hasAttribute(\"aria-label\")) {\n this.#ariaLabel.write(control, label);\n return;\n }\n // A structured button needs the explicit idle/busy pair above. Replacing its\n // textContent would destroy icons, counters, and application-owned listeners.\n if (control.childElementCount > 0) return;\n session.labelWrite = {\n channel: \"text\",\n control,\n original: control.textContent ?? \"\",\n written: label,\n };\n control.textContent = label;\n }\n\n /** Returns labels, controls, and form hooks, respecting intervening consumer writes. */\n #returnSessionState(session: SubmissionSession): void {\n if (session.timeoutId !== null) {\n this.#timers.clear(session.timeoutId);\n session.timeoutId = null;\n }\n\n if (session.labelWrite?.channel === \"value\") {\n const { control, original, written } = session.labelWrite;\n if (control.value === written) control.value = original;\n } else if (session.labelWrite?.channel === \"text\") {\n const { control, original, written } = session.labelWrite;\n if (control.childElementCount === 0 && control.textContent === written) {\n control.textContent = original;\n }\n }\n session.labelWrite = null;\n\n if (session.submitter instanceof HTMLButtonElement) {\n this.#ariaLabel.return(session.submitter);\n }\n if (session.idlePart) this.#hidden.return(session.idlePart);\n if (session.busyPart) this.#hidden.return(session.busyPart);\n session.idlePart = null;\n session.busyPart = null;\n\n for (const control of session.controls) {\n this.#controlBusy.return(control);\n this.#disabled.return(control);\n }\n session.controls.clear();\n this.#submitting.return(session.form);\n this.#formBusy.return(session.form);\n }\n\n /** Restores focus only when disabling the focused submitter actually stranded it. */\n #restoreFocus(session: SubmissionSession): void {\n const submitter = session.submitter;\n if (!this.restoreFocusValue || !session.submitterHadFocus || !submitter?.isConnected) return;\n const active = document.activeElement;\n if (active === null || active === document.body || active === document.documentElement) {\n submitter.focus();\n }\n }\n\n /** Silently abandons every session before caching or on a real detach. */\n #abandonSessions(): void {\n this.#timers.clearAll();\n for (const session of this.#sessions.values()) {\n session.timeoutId = null;\n this.#returnSessionState(session);\n }\n this.#sessions.clear();\n }\n\n /** Keeps Turbo's cached snapshot idle, without events, announcements, or focus moves. */\n #rewindForCache(): void {\n const forms = [...this.#sessions.keys()];\n this.#abandonSessions();\n // A submission in flight dies with the navigation, so a consumer still\n // painting \"submitting\" from `start` would never be released.\n if (forms.length > 0) this.dispatch(\"reconcile\", { detail: { forms } });\n }\n\n /** Tears down a true detach; an in-page move is canceled by the next `connect()`. */\n #teardown(): void {\n this.#gate.cancel();\n this.#abandonSessions();\n }\n\n /** All native controls associated with `form`, plus valid explicit targets. */\n #submitControls(form: HTMLFormElement): SubmitControl[] {\n const controls = new Set<SubmitControl>();\n for (const element of Array.from(form.elements)) {\n if (this.#isNativeSubmitControl(element)) controls.add(element);\n }\n // Browsers omit input[type=image] from form.elements. Search\n // the form's tree root as well so descendant and external `form=` image\n // submitters receive the same guard without broadening into sibling forms.\n const root = form.getRootNode() as ParentNode;\n for (const image of root.querySelectorAll<HTMLInputElement>('input[type=\"image\"]')) {\n if (image.form === form) controls.add(image);\n }\n return Array.from(controls);\n }\n\n /** Resolves the real submitter, falling back to the first enabled submit control. */\n #resolveSubmitter(event: Event, controls: SubmitControl[]): SubmitControl | null {\n const submitter = this.#eventSubmitter(event);\n if (submitter && controls.includes(submitter)) return submitter;\n return controls.find((control) => !control.matches(\":disabled\")) ?? controls[0] ?? null;\n }\n\n /** Reads a native or Turbo submitter without assuming `SubmitEvent` exists. */\n #eventSubmitter(event: Event): SubmitControl | null {\n if (typeof SubmitEvent !== \"undefined\" && event instanceof SubmitEvent) {\n return this.#isNativeSubmitControl(event.submitter) ? event.submitter : null;\n }\n const detail = (event as CustomEvent<{ formSubmission?: { submitter?: HTMLElement | null } }>)\n .detail;\n const submitter = detail?.formSubmission?.submitter;\n return this.#isNativeSubmitControl(submitter) ? submitter : null;\n }\n\n /** Finds the form represented by an action/Turbo event and verifies this scope owns it. */\n #eventForm(event: Event): HTMLFormElement | null {\n const detail = (\n event as CustomEvent<{\n form?: HTMLFormElement;\n formSubmission?: { formElement?: HTMLFormElement; submitter?: HTMLElement | null };\n }>\n ).detail;\n const target = event.target;\n const candidate =\n (target instanceof HTMLFormElement ? target : null) ??\n (target instanceof Element ? target.closest(\"form\") : null) ??\n detail?.formSubmission?.formElement ??\n detail?.form ??\n this.#eventSubmitter(event)?.form ??\n (this.element instanceof HTMLFormElement ? this.element : null);\n return candidate && this.#ownsForm(candidate) ? candidate : null;\n }\n\n /** The only unambiguous form for a direct `finish()` call. */\n #defaultForm(): HTMLFormElement | null {\n if (this.element instanceof HTMLFormElement && this.#ownsForm(this.element))\n return this.element;\n if (this.#sessions.size === 1) return this.#sessions.keys().next().value ?? null;\n return null;\n }\n\n /** Prevents an ancestor controller from also taking over a nested instance's form. */\n #ownsForm(form: HTMLFormElement): boolean {\n let candidate: Element | null = form;\n while (candidate) {\n const identifiers = (candidate.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n if (identifiers.includes(this.identifier)) return candidate === this.element;\n candidate = candidate.parentElement;\n }\n return false;\n }\n\n /** Returns the active session for a form-shaped external event value. */\n #sessionFor(candidate: unknown): SubmissionSession | undefined {\n if (!(candidate instanceof HTMLFormElement)) return undefined;\n return this.#sessions.get(candidate);\n }\n\n /** Effective native submit controls, including implicit buttons and image inputs. */\n #isNativeSubmitControl(element: unknown): element is SubmitControl {\n if (element instanceof HTMLButtonElement) return element.type === \"submit\";\n return (\n element instanceof HTMLInputElement && (element.type === \"submit\" || element.type === \"image\")\n );\n }\n\n /** Finds a structured label part belonging to this button, not a nested control. */\n #partInside(control: SubmitControl, parts: HTMLElement[]): HTMLElement | null {\n return (\n parts.find(\n (part) =>\n control.contains(part) &&\n part.closest(\"button, input[type=submit], input[type=image]\") === control,\n ) ?? null\n );\n }\n\n /** Reads an optional boolean `success` from Turbo or a manual completion event. */\n #eventSuccess(event: Event): boolean | undefined {\n const success = (event as CustomEvent<{ success?: unknown }>).detail?.success;\n return typeof success === \"boolean\" ? success : undefined;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/default_attribute.ts","../../src/utils/focus_candidate.ts","../../src/utils/interactive_host.ts","../../src/controllers/switch_controller.ts"],"names":[],"mappings":";;;;;AAYO,SAAS,mBAAA,CAAoB,OAAA,EAAkB,IAAA,EAAc,KAAA,EAAwB;AAC1F,EAAA,IAAI,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,EAAG,OAAO,KAAA;AACvC,EAAA,OAAA,CAAQ,YAAA,CAAa,MAAM,KAAK,CAAA;AAChC,EAAA,OAAO,IAAA;AACT;;;ACLO,SAAS,yBAAyB,OAAA,EAA+B;AACtE,EAAA,IAAI,QAAA,GAA2B,OAAA,CAAQ,OAAA,CAAQ,oBAAoB,CAAA;AACnE,EAAA,OAAO,QAAA,EAAU;AACf,IAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,CAAE,IAAA,CAAK,CAAC,KAAA,KAAU,KAAA,CAAM,OAAA,KAAY,QAAQ,CAAA;AACvF,IAAA,IAAI,CAAC,MAAA,EAAQ,QAAA,CAAS,OAAO,GAAG,OAAO,IAAA;AACvC,IAAA,QAAA,GAAW,QAAA,CAAS,aAAA,EAAe,OAAA,CAAQ,oBAAoB,CAAA,IAAK,IAAA;AAAA,EACtE;AACA,EAAA,OAAO,KAAA;AACT;;;ACZO,IAAM,yBAAA,GACX,wIAAA;AASK,SAAS,kBAAkB,OAAA,EAA+B;AAC/D,EAAA,IAAI,OAAA,CAAQ,OAAA,CAAQ,yBAAyB,CAAA,EAAG,OAAO,IAAA;AAEvD,EAAA,IAAI,OAAA,GAA8B,OAAA;AAClC,EAAA,OAAO,OAAA,EAAS;AACd,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,YAAA,CAAa,iBAAiB,CAAA;AAClD,IAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,MAAA,MAAM,K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BAAA,CAAA,EAAoB,OAAO,KAAA;AACzD,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,QAAA,IAAY,wBAAA,CAAyB,KAAK,OAAO,CAAA;AAAA,EACvE;AAAA;AAAA,EAGA,IAAI,QAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,cAAc,CAAA,KAAM,MAAA;AAAA,EACvD;AAAA;AAAA,EAGA,IAAI,SAAS,KAAA,EAAgB;AAC3B,IAAA,MAAM,SAAA,GAAY,QAAQ,MAAA,GAAS,OAAA;AACnC,IAAA,IAAA,CAAK,wBAAA,CAAyB,GAAA,CAAI,cAAA,EAAgB,SAAS,CAAA;AAC3D,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,cAAA,EAAgB,SAAS,CAAA;AACnD,IAAA,IAAA,CAAK,QAAA,CAAS,WAAW,EAAE,MAAA,EAAQ,EAAE,OAAA,EAAS,KAAA,IAAS,CAAA;AAAA,EACzD;AACF","file":"switch_controller.js","sourcesContent":["/**\n * Adds an attribute default without displacing an authored value.\n *\n * Attribute presence — including an authored empty string — is the ownership\n * boundary. The return value lets a caller remember that it supplied the\n * default when that caller must later restore the authored state.\n *\n * @param element - Element that owns the attribute\n * @param name - Attribute name\n * @param value - Value to write only when the attribute is absent\n * @returns Whether this call added the attribute\n */\nexport function setDefaultAttribute(element: Element, name: string, value: string): boolean {\n if (element.hasAttribute(name)) return false;\n element.setAttribute(name, value);\n return true;\n}\n","/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported for the consumer that needs this rule *without* the rest of\n * {@link canTakeFocus}: `toolbar` bounds its own `hidden` walk at the toolbar\n * root, which is a different rule, so it composes the two itself.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the three conditions that make the platform refuse\n * focus are checked: `hidden` / `inert` (an ancestor's counts),\n * `input[type=\"hidden\"]`, the native `disabled` property, and `disabled`\n * inherited from an ancestor `fieldset`. CSS-only invisibility is handled by\n * {@link isRenderedForFocus} when a consumer needs sequential-focus semantics.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n if (element.closest(\"[hidden], [inert]\")) return false;\n if (element instanceof HTMLInputElement && element.type === \"hidden\") return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n\n/** Elements whose semantics or authored attributes can place them in sequential focus order. */\nexport const TAB_STOP_CANDIDATE_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"iframe\",\n \"audio[controls]\",\n \"video[controls]\",\n \"[tabindex]\",\n \"[contenteditable]\",\n].join(\",\");\n\n/** Optional browser visibility API used to exclude CSS-hidden candidates. */\ninterface VisibilityCheckable {\n checkVisibility?: (options?: { visibilityProperty?: boolean }) => boolean;\n}\n\n/** Whether CSS visibility allows an otherwise eligible element to participate in focus order. */\nexport function isRenderedForFocus(element: HTMLElement): boolean {\n const check = (element as HTMLElement & VisibilityCheckable).checkVisibility;\n return typeof check === \"function\" ? check.call(element, { visibilityProperty: true }) : true;\n}\n\n/** Parses an authored `tabindex`; invalid syntax has no explicit focus-order meaning. */\nfunction authoredTabindex(element: HTMLElement): number | null {\n const value = element.getAttribute(\"tabindex\");\n if (value === null || !/^[+-]?\\d+$/.test(value.trim())) return null;\n return Number(value);\n}\n\n/** Whether the element's native semantics place it in sequential focus order. */\nfunction hasNativeTabStop(element: HTMLElement): boolean {\n if (element instanceof HTMLAnchorElement || element instanceof HTMLAreaElement) {\n return element.hasAttribute(\"href\");\n }\n if (\n element instanceof HTMLButtonElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n ) {\n return true;\n }\n if (element instanceof HTMLInputElement) return element.type !== \"hidden\";\n if (element instanceof HTMLIFrameElement) return true;\n if (element.tagName === \"AUDIO\" || element.tagName === \"VIDEO\") {\n return element.hasAttribute(\"controls\");\n }\n if (element instanceof HTMLElement && element.tagName === \"SUMMARY\") {\n const details = element.parentElement;\n return (\n details instanceof HTMLDetailsElement &&\n Array.from(details.children).find((child) => child.tagName === \"SUMMARY\") === element\n );\n }\n return false;\n}\n\n/** Whether an explicit `contenteditable` value creates an editable tab stop. */\nfunction hasEditableTabStop(element: HTMLElement): boolean {\n const value = element.getAttribute(\"contenteditable\")?.toLowerCase();\n return value === \"\" || value === \"true\" || value === \"plaintext-only\";\n}\n\n/**\n * Whether an element is a usable sequential Tab stop right now.\n *\n * Native semantics, authored `tabindex`, editable hosts, inherited disabled state,\n * HTML `hidden`/`inert`, and CSS visibility are evaluated together. `aria-disabled`\n * remains focusable because it communicates unavailability without removing the\n * control from discovery order.\n */\nexport function isTabStop(element: HTMLElement): boolean {\n if (!canTakeFocus(element) || !isRenderedForFocus(element)) return false;\n\n const tabindex = authoredTabindex(element);\n if (tabindex !== null) return tabindex >= 0;\n return hasNativeTabStop(element) || hasEditableTabStop(element);\n}\n\n/** Returns every usable sequential Tab stop below `root` in document order. */\nexport function tabStopsWithin(root: ParentNode): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)).filter(\n isTabStop,\n );\n}\n\n/** Returns the first usable sequential Tab stop below `root`, if one exists. */\nexport function firstTabStop(root: ParentNode): HTMLElement | null {\n for (const candidate of root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)) {\n if (isTabStop(candidate)) return candidate;\n }\n return null;\n}\n\n/** Whether `root` contains at least one usable sequential Tab stop. */\nexport function hasTabStop(root: ParentNode): boolean {\n return firstTabStop(root) !== null;\n}\n","/**\n * Native interactive elements whose built-in activation must not be replaced\n * wholesale by a controller. Deliberately excludes `[tabindex]`: a generic\n * element made focusable is the supported host for several headless patterns.\n * Contenteditable is handled by {@link isInteractiveHost} because its state is\n * inherited and its keywords are ASCII-case-insensitive.\n */\nexport const INTERACTIVE_HOST_SELECTOR =\n \"button, input, select, textarea, label, a[href], area[href], summary, details, audio[controls], video[controls], iframe, object, embed\";\n\n/**\n * Whether an element owns native activation or an inherited editing surface.\n *\n * The `contenteditable` missing and invalid states inherit. Walking explicitly\n * also keeps `contenteditable=\"false\"` as a real boundary inside an editable\n * ancestor instead of treating any ancestor attribute as decisive.\n */\nexport function isInteractiveHost(element: HTMLElement): boolean {\n if (element.matches(INTERACTIVE_HOST_SELECTOR)) return true;\n\n let current: HTMLElement | null = element;\n while (current) {\n const raw = current.getAttribute(\"contenteditable\");\n if (raw !== null) {\n const value = raw.trim().toLowerCase();\n if (value === \"false\") return false;\n if (value === \"\" || value === \"true\" || value === \"plaintext-only\") return true;\n }\n current = current.parentElement;\n }\n return false;\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { setDefaultAttribute } from \"../utils/default_attribute\";\nimport { inheritsFieldsetDisabled } from \"../utils/focus_candidate\";\nimport { isInteractiveHost } from \"../utils/interactive_host\";\n\n/** Attributes whose in-place changes can alter the host or its required defaults. */\nconst OBSERVED_ATTRIBUTES = [\n \"role\",\n \"aria-checked\",\n \"tabindex\",\n \"type\",\n \"href\",\n \"contenteditable\",\n \"controls\",\n];\n\n/** Ancestor attributes whose inherited state can change the supported host. */\nconst OBSERVED_ANCESTOR_ATTRIBUTES = [\"contenteditable\"];\n\n/**\n * Headless, accessible switch (toggle) behavior.\n *\n * Markup contract (identifier: `stimeo--switch`):\n * <button type=\"button\" data-controller=\"stimeo--switch\"\n * data-action=\"stimeo--switch#toggle keydown->stimeo--switch#onKeydown\"\n * role=\"switch\" aria-checked=\"false\">…</button>\n *\n * Implements the WAI-ARIA APG **Switch** pattern. The controller element is the\n * switch itself; its on/off state is reflected solely through `aria-checked`.\n *\n * `changed` dispatches `{ checked: boolean }`.\n *\n * @remarks\n * Behavior only — the consumer owns all styling (typically keyed off the\n * `[aria-checked=\"true\"]` attribute). On a native `<button>` host, the browser\n * already synthesizes a click for Space/Enter, so {@link onKeydown} leaves the\n * initial key to the browser and suppresses repeated keydowns. Non-button hosts\n * such as `<div role=\"switch\" tabindex=\"0\">` are driven directly. Other native\n * interactive hosts stand down because their checked/navigation semantics would\n * conflict with `aria-checked` as this controller's sole source of truth.\n *\n * Behavior provided:\n * - Click (or Space/Enter) toggles `aria-checked` between `\"true\"` and `\"false\"`.\n * - A `stimeo--switch:changed` event is dispatched on every toggle so the\n * consumer can react (its `detail.checked` carries the new boolean state).\n */\nexport class SwitchController extends Controller<HTMLElement> {\n static actions = [\"onKeydown\", \"toggle\"] as const;\n static events = [\"changed\"] as const;\n\n /** Defaults this instance introduced and may therefore remove safely. */\n readonly #ownedDefaults = new Set<string>();\n /** Controller writes that must not be mistaken for authored morph changes. */\n readonly #internalAttributeValues = new Map<string, string>();\n\n readonly #attributeObserver = new MutationObserver((records) => {\n this.#releaseAuthoredDefaults(records);\n // Stop observation while restoring defaults so the writes do not schedule a\n // second, empty callback batch. Re-observe synchronously before returning.\n this.#attributeObserver.disconnect();\n this.#reconcileDefaults();\n this.#observeAttributes();\n });\n\n /** Blocks disabled pointer/native-key activation before consumer click handlers. */\n readonly #onClickCapture = (event: MouseEvent): void => {\n if (!this.#isSupportedHost || !this.#isActivationDisabled) return;\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n\n /** Ensures the switch exposes a role and is keyboard-reachable. */\n override connect(): void {\n this.#reconcileDefaults();\n this.element.addEventListener(\"click\", this.#onClickCapture, true);\n this.#observeAttributes();\n }\n\n /** Releases the explicit click guard and retained-element attribute observer. */\n override disconnect(): void {\n this.element.removeEventListener(\"click\", this.#onClickCapture, true);\n this.#attributeObserver.disconnect();\n this.#internalAttributeValues.clear();\n }\n\n /** Toggles the checked state. Bound via `data-action` (click). */\n toggle(): void {\n if (!this.#isSupportedHost || this.#isActivationDisabled) return;\n this.#checked = !this.#checked;\n }\n\n /**\n * Activates the switch on Space/Enter for non-native hosts and suppresses key\n * repeat. Bound via `data-action` (keydown). A native `<button type=\"button\">`\n * owns the initial key-to-click synthesis; repeated keydowns are canceled before\n * the browser can synthesize additional clicks.\n */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO toggle the switch —\n // composition depends on this yield.\n if (event.defaultPrevented) return;\n if (!this.#isSupportedHost) return;\n if (event.key !== \" \" && event.key !== \"Enter\") return;\n if (this.#isActivationDisabled) {\n event.preventDefault();\n event.stopImmediatePropagation();\n return;\n }\n if (this.element instanceof HTMLButtonElement) {\n if (event.repeat) event.preventDefault();\n return;\n }\n event.preventDefault();\n if (event.repeat) return;\n this.toggle();\n }\n\n /** Re-adds only missing defaults, preserving every authored attribute value. */\n #reconcileDefaults(): void {\n if (!this.#isSupportedHost) {\n this.#removeOwnedDefaults();\n return;\n }\n this.#setOwnedDefault(\"role\", \"switch\");\n this.#setOwnedDefault(\"aria-checked\", \"false\");\n // Native buttons are focusable already; generic hosts need a Tab stop for\n // the keyboard action above to be reachable.\n if (!(this.element instanceof HTMLButtonElement)) {\n this.#setOwnedDefault(\"tabindex\", \"0\");\n }\n }\n\n /** Records a newly introduced default without claiming authored markup. */\n #setOwnedDefault(name: string, value: string): void {\n if (setDefaultAttribute(this.element, name, value)) this.#ownedDefaults.add(name);\n }\n\n /**\n * Gives ownership back when a retained-element morph authors a value. Missing\n * owned attributes stay owned so reconciliation can restore them.\n */\n #releaseAuthoredDefaults(records: MutationRecord[]): void {\n for (const record of records) {\n if (record.target === this.element) {\n const name = record.attributeName;\n if (name && this.#ownedDefaults.has(name)) {\n const value = this.element.getAttribute(name);\n if (value !== null && this.#internalAttributeValues.get(name) !== value) {\n this.#ownedDefaults.delete(name);\n }\n }\n }\n }\n this.#internalAttributeValues.clear();\n }\n\n /** Removes only defaults introduced by this instance when a host becomes invalid. */\n #removeOwnedDefaults(): void {\n for (const name of this.#ownedDefaults) this.element.removeAttribute(name);\n this.#ownedDefaults.clear();\n this.#internalAttributeValues.clear();\n }\n\n /** Watches retained host attributes that Turbo can morph without reconnecting. */\n #observeAttributes(): void {\n this.#attributeObserver.observe(this.element, {\n attributes: true,\n attributeFilter: OBSERVED_ATTRIBUTES,\n });\n let ancestor = this.element.parentElement;\n while (ancestor) {\n this.#attributeObserver.observe(ancestor, {\n attributes: true,\n attributeFilter: OBSERVED_ANCESTOR_ATTRIBUTES,\n });\n ancestor = ancestor.parentElement;\n }\n }\n\n /** Whether the host has one activation model that this controller can own. */\n get #isSupportedHost(): boolean {\n if (this.element instanceof HTMLButtonElement) return this.element.type === \"button\";\n return !isInteractiveHost(this.element);\n }\n\n /** Whether ARIA or native HTML semantics make the supported switch inoperable. */\n get #isActivationDisabled(): boolean {\n let current: HTMLElement | null = this.element;\n while (current) {\n if (current.getAttribute(\"aria-disabled\") === \"true\") return true;\n current = current.parentElement;\n }\n if (!(this.element instanceof HTMLButtonElement)) return false;\n return this.element.disabled || inheritsFieldsetDisabled(this.element);\n }\n\n /** Whether the switch is currently on. */\n get #checked(): boolean {\n return this.element.getAttribute(\"aria-checked\") === \"true\";\n }\n\n /** Reflects the new state on `aria-checked` and notifies listeners. */\n set #checked(value: boolean) {\n const reflected = value ? \"true\" : \"false\";\n this.#internalAttributeValues.set(\"aria-checked\", reflected);\n this.element.setAttribute(\"aria-checked\", reflected);\n this.dispatch(\"changed\", { detail: { checked: value } });\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/default_attribute.ts","../../src/utils/focus_candidate.ts","../../src/utils/interactive_host.ts","../../src/controllers/switch_controller.ts"],"names":[],"mappings":";;;;;AAYO,SAAS,mBAAA,CAAoB,OAAA,EAAkB,IAAA,EAAc,KAAA,EAAwB;AAC1F,EAAA,IAAI,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,EAAG,OAAO,KAAA;AACvC,EAAA,OAAA,CAAQ,YAAA,CAAa,MAAM,KAAK,CAAA;AAChC,EAAA,OAAO,IAAA;AACT;;;ACLO,SAAS,yBAAyB,OAAA,EAA+B;AACtE,EAAA,IAAI,QAAA,GAA2B,OAAA,CAAQ,OAAA,CAAQ,oBAAoB,CAAA;AACnE,EAAA,OAAO,QAAA,EAAU;AACf,IAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,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;AACF","file":"switch_controller.js","sourcesContent":["/**\n * Adds an attribute default without displacing an authored value.\n *\n * Attribute presence — including an authored empty string — is the ownership\n * boundary. The return value lets a caller remember that it supplied the\n * default when that caller must later restore the authored state.\n *\n * @param element - Element that owns the attribute\n * @param name - Attribute name\n * @param value - Value to write only when the attribute is absent\n * @returns Whether this call added the attribute\n */\nexport function setDefaultAttribute(element: Element, name: string, value: string): boolean {\n if (element.hasAttribute(name)) return false;\n element.setAttribute(name, value);\n return true;\n}\n","/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported on its own for callers that need the disabled-inheritance rule without\n * the rest of {@link canTakeFocus} — a control's availability check, or a `hidden`\n * walk bounded at a widget root, which is a different rule to compose with.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the three conditions that make the platform refuse\n * focus are checked: `hidden` / `inert` (an ancestor's counts),\n * `input[type=\"hidden\"]`, the native `disabled` property, and `disabled`\n * inherited from an ancestor `fieldset`. CSS-only invisibility is handled by\n * {@link isRenderedForFocus} when a consumer needs sequential-focus semantics.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n if (element.closest(\"[hidden], [inert]\")) return false;\n if (element instanceof HTMLInputElement && element.type === \"hidden\") return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n\n/** Elements whose semantics or authored attributes can place them in sequential focus order. */\nexport const TAB_STOP_CANDIDATE_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"iframe\",\n \"audio[controls]\",\n \"video[controls]\",\n \"[tabindex]\",\n \"[contenteditable]\",\n].join(\",\");\n\n/** Optional browser visibility API used to exclude CSS-hidden candidates. */\ninterface VisibilityCheckable {\n checkVisibility?: (options?: { visibilityProperty?: boolean }) => boolean;\n}\n\n/** Whether CSS visibility allows an otherwise eligible element to participate in focus order. */\nexport function isRenderedForFocus(element: HTMLElement): boolean {\n const check = (element as HTMLElement & VisibilityCheckable).checkVisibility;\n return typeof check === \"function\" ? check.call(element, { visibilityProperty: true }) : true;\n}\n\n/** Parses an authored `tabindex`; invalid syntax has no explicit focus-order meaning. */\nfunction authoredTabindex(element: HTMLElement): number | null {\n const value = element.getAttribute(\"tabindex\");\n if (value === null || !/^[+-]?\\d+$/.test(value.trim())) return null;\n return Number(value);\n}\n\n/** Whether the element's native semantics place it in sequential focus order. */\nfunction hasNativeTabStop(element: HTMLElement): boolean {\n if (element instanceof HTMLAnchorElement || element instanceof HTMLAreaElement) {\n return element.hasAttribute(\"href\");\n }\n if (\n element instanceof HTMLButtonElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n ) {\n return true;\n }\n if (element instanceof HTMLInputElement) return element.type !== \"hidden\";\n if (element instanceof HTMLIFrameElement) return true;\n if (element.tagName === \"AUDIO\" || element.tagName === \"VIDEO\") {\n return element.hasAttribute(\"controls\");\n }\n if (element instanceof HTMLElement && element.tagName === \"SUMMARY\") {\n const details = element.parentElement;\n return (\n details instanceof HTMLDetailsElement &&\n Array.from(details.children).find((child) => child.tagName === \"SUMMARY\") === element\n );\n }\n return false;\n}\n\n/** Whether an explicit `contenteditable` value creates an editable tab stop. */\nfunction hasEditableTabStop(element: HTMLElement): boolean {\n const value = element.getAttribute(\"contenteditable\")?.toLowerCase();\n return value === \"\" || value === \"true\" || value === \"plaintext-only\";\n}\n\n/**\n * Whether an element is a usable sequential Tab stop right now.\n *\n * Native semantics, authored `tabindex`, editable hosts, inherited disabled state,\n * HTML `hidden`/`inert`, and CSS visibility are evaluated together. `aria-disabled`\n * remains focusable because it communicates unavailability without removing the\n * control from discovery order.\n */\nexport function isTabStop(element: HTMLElement): boolean {\n if (!canTakeFocus(element) || !isRenderedForFocus(element)) return false;\n\n const tabindex = authoredTabindex(element);\n if (tabindex !== null) return tabindex >= 0;\n return hasNativeTabStop(element) || hasEditableTabStop(element);\n}\n\n/** Returns every usable sequential Tab stop below `root` in document order. */\nexport function tabStopsWithin(root: ParentNode): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)).filter(\n isTabStop,\n );\n}\n\n/** Returns the first usable sequential Tab stop below `root`, if one exists. */\nexport function firstTabStop(root: ParentNode): HTMLElement | null {\n for (const candidate of root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)) {\n if (isTabStop(candidate)) return candidate;\n }\n return null;\n}\n\n/** Whether `root` contains at least one usable sequential Tab stop. */\nexport function hasTabStop(root: ParentNode): boolean {\n return firstTabStop(root) !== null;\n}\n","/**\n * Native interactive elements whose built-in activation must not be replaced\n * wholesale by a controller. Deliberately excludes `[tabindex]`: a generic\n * element made focusable is the supported host for several headless patterns.\n * Contenteditable is handled by {@link isInteractiveHost} because its state is\n * inherited and its keywords are ASCII-case-insensitive.\n */\nexport const INTERACTIVE_HOST_SELECTOR =\n \"button, input, select, textarea, label, a[href], area[href], summary, details, audio[controls], video[controls], iframe, object, embed\";\n\n/**\n * Whether an element owns native activation or an inherited editing surface.\n *\n * The `contenteditable` missing and invalid states inherit. Walking explicitly\n * also keeps `contenteditable=\"false\"` as a real boundary inside an editable\n * ancestor instead of treating any ancestor attribute as decisive.\n */\nexport function isInteractiveHost(element: HTMLElement): boolean {\n if (element.matches(INTERACTIVE_HOST_SELECTOR)) return true;\n\n let current: HTMLElement | null = element;\n while (current) {\n const raw = current.getAttribute(\"contenteditable\");\n if (raw !== null) {\n const value = raw.trim().toLowerCase();\n if (value === \"false\") return false;\n if (value === \"\" || value === \"true\" || value === \"plaintext-only\") return true;\n }\n current = current.parentElement;\n }\n return false;\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { setDefaultAttribute } from \"../utils/default_attribute\";\nimport { inheritsFieldsetDisabled } from \"../utils/focus_candidate\";\nimport { isInteractiveHost } from \"../utils/interactive_host\";\n\n/** Attributes whose in-place changes can alter the host or its required defaults. */\nconst OBSERVED_ATTRIBUTES = [\n \"role\",\n \"aria-checked\",\n \"tabindex\",\n \"type\",\n \"href\",\n \"contenteditable\",\n \"controls\",\n];\n\n/** Ancestor attributes whose inherited state can change the supported host. */\nconst OBSERVED_ANCESTOR_ATTRIBUTES = [\"contenteditable\"];\n\n/**\n * Headless, accessible switch (toggle) behavior.\n *\n * Markup contract (identifier: `stimeo--switch`):\n * <button type=\"button\" data-controller=\"stimeo--switch\"\n * data-action=\"stimeo--switch#toggle keydown->stimeo--switch#onKeydown\"\n * role=\"switch\" aria-checked=\"false\">…</button>\n *\n * Implements the WAI-ARIA APG **Switch** pattern. The controller element is the\n * switch itself; its on/off state is reflected solely through `aria-checked`.\n *\n * `changed` dispatches `{ checked: boolean }`.\n *\n * @remarks\n * Behavior only — the consumer owns all styling (typically keyed off the\n * `[aria-checked=\"true\"]` attribute). On a native `<button>` host, the browser\n * already synthesizes a click for Space/Enter, so {@link onKeydown} leaves the\n * initial key to the browser and suppresses repeated keydowns. Non-button hosts\n * such as `<div role=\"switch\" tabindex=\"0\">` are driven directly. Other native\n * interactive hosts stand down because their checked/navigation semantics would\n * conflict with `aria-checked` as this controller's sole source of truth.\n *\n * Behavior provided:\n * - Click (or Space/Enter) toggles `aria-checked` between `\"true\"` and `\"false\"`.\n * - A `stimeo--switch:changed` event is dispatched on every toggle so the\n * consumer can react (its `detail.checked` carries the new boolean state).\n */\nexport class SwitchController extends Controller<HTMLElement> {\n static actions = [\"onKeydown\", \"toggle\"] as const;\n static events = [\"changed\"] as const;\n\n /** Defaults this instance introduced and may therefore remove safely. */\n readonly #ownedDefaults = new Set<string>();\n /** Controller writes that must not be mistaken for authored morph changes. */\n readonly #internalAttributeValues = new Map<string, string>();\n\n readonly #attributeObserver = new MutationObserver((records) => {\n this.#releaseAuthoredDefaults(records);\n // Stop observation while restoring defaults so the writes do not schedule a\n // second, empty callback batch. Re-observe synchronously before returning.\n this.#attributeObserver.disconnect();\n this.#reconcileDefaults();\n this.#observeAttributes();\n });\n\n /** Blocks disabled pointer/native-key activation before consumer click handlers. */\n readonly #onClickCapture = (event: MouseEvent): void => {\n if (!this.#isSupportedHost || !this.#isActivationDisabled) return;\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n\n /** Ensures the switch exposes a role and is keyboard-reachable. */\n override connect(): void {\n this.#reconcileDefaults();\n this.element.addEventListener(\"click\", this.#onClickCapture, true);\n this.#observeAttributes();\n }\n\n /** Releases the explicit click guard and retained-element attribute observer. */\n override disconnect(): void {\n this.element.removeEventListener(\"click\", this.#onClickCapture, true);\n this.#attributeObserver.disconnect();\n this.#internalAttributeValues.clear();\n }\n\n /** Toggles the checked state. Bound via `data-action` (click). */\n toggle(): void {\n if (!this.#isSupportedHost || this.#isActivationDisabled) return;\n this.#checked = !this.#checked;\n }\n\n /**\n * Activates the switch on Space/Enter for non-native hosts and suppresses key\n * repeat. Bound via `data-action` (keydown). A native `<button type=\"button\">`\n * owns the initial key-to-click synthesis; repeated keydowns are canceled before\n * the browser can synthesize additional clicks.\n */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO toggle the switch —\n // composition depends on this yield.\n if (event.defaultPrevented) return;\n if (!this.#isSupportedHost) return;\n if (event.key !== \" \" && event.key !== \"Enter\") return;\n if (this.#isActivationDisabled) {\n event.preventDefault();\n event.stopImmediatePropagation();\n return;\n }\n if (this.element instanceof HTMLButtonElement) {\n if (event.repeat) event.preventDefault();\n return;\n }\n event.preventDefault();\n if (event.repeat) return;\n this.toggle();\n }\n\n /** Re-adds only missing defaults, preserving every authored attribute value. */\n #reconcileDefaults(): void {\n if (!this.#isSupportedHost) {\n this.#removeOwnedDefaults();\n return;\n }\n this.#setOwnedDefault(\"role\", \"switch\");\n this.#setOwnedDefault(\"aria-checked\", \"false\");\n // Native buttons are focusable already; generic hosts need a Tab stop for\n // the keyboard action above to be reachable.\n if (!(this.element instanceof HTMLButtonElement)) {\n this.#setOwnedDefault(\"tabindex\", \"0\");\n }\n }\n\n /** Records a newly introduced default without claiming authored markup. */\n #setOwnedDefault(name: string, value: string): void {\n if (setDefaultAttribute(this.element, name, value)) this.#ownedDefaults.add(name);\n }\n\n /**\n * Gives ownership back when a retained-element morph authors a value. Missing\n * owned attributes stay owned so reconciliation can restore them.\n */\n #releaseAuthoredDefaults(records: MutationRecord[]): void {\n for (const record of records) {\n if (record.target === this.element) {\n const name = record.attributeName;\n if (name && this.#ownedDefaults.has(name)) {\n const value = this.element.getAttribute(name);\n if (value !== null && this.#internalAttributeValues.get(name) !== value) {\n this.#ownedDefaults.delete(name);\n }\n }\n }\n }\n this.#internalAttributeValues.clear();\n }\n\n /** Removes only defaults introduced by this instance when a host becomes invalid. */\n #removeOwnedDefaults(): void {\n for (const name of this.#ownedDefaults) this.element.removeAttribute(name);\n this.#ownedDefaults.clear();\n this.#internalAttributeValues.clear();\n }\n\n /** Watches retained host attributes that Turbo can morph without reconnecting. */\n #observeAttributes(): void {\n this.#attributeObserver.observe(this.element, {\n attributes: true,\n attributeFilter: OBSERVED_ATTRIBUTES,\n });\n let ancestor = this.element.parentElement;\n while (ancestor) {\n this.#attributeObserver.observe(ancestor, {\n attributes: true,\n attributeFilter: OBSERVED_ANCESTOR_ATTRIBUTES,\n });\n ancestor = ancestor.parentElement;\n }\n }\n\n /** Whether the host has one activation model that this controller can own. */\n get #isSupportedHost(): boolean {\n if (this.element instanceof HTMLButtonElement) return this.element.type === \"button\";\n return !isInteractiveHost(this.element);\n }\n\n /** Whether ARIA or native HTML semantics make the supported switch inoperable. */\n get #isActivationDisabled(): boolean {\n let current: HTMLElement | null = this.element;\n while (current) {\n if (current.getAttribute(\"aria-disabled\") === \"true\") return true;\n current = current.parentElement;\n }\n if (!(this.element instanceof HTMLButtonElement)) return false;\n return this.element.disabled || inheritsFieldsetDisabled(this.element);\n }\n\n /** Whether the switch is currently on. */\n get #checked(): boolean {\n return this.element.getAttribute(\"aria-checked\") === \"true\";\n }\n\n /** Reflects the new state on `aria-checked` and notifies listeners. */\n set #checked(value: boolean) {\n const reflected = value ? \"true\" : \"false\";\n this.#internalAttributeValues.set(\"aria-checked\", reflected);\n this.element.setAttribute(\"aria-checked\", reflected);\n this.dispatch(\"changed\", { detail: { checked: value } });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/controllers/tabs_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,SAAA,KAAc,KAAA;AACxD;;;AC4EO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,KACvC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,IACvC,KAAA,CAAM,QAAA,IAAY,CAAC,KAAA,CAAM,QAAA,CAAS,OAAO,CAAA;AAE9C;;;ACpEO,IAAM,cAAA,GAAN,cAA6B,UAAA,CAAwB;AAAA,EAC1D,OAAgB,OAAA,GAAU,CAAC,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,EACjD,OAAO,OAAA,GAAU,CAAC,WAAA,EAAa,QAAQ,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAc9B,OAAA,GAAgB;AACvB,IAAA,MAAM,WAAA,GAAc,KAAK,UAAA,CAAW,SAAA;AAAA,MAClC,CAAC,GAAA,KAAQ,GAAA,CAAI,YAAA,CAAa,eAAe,CAAA,KAAM;AAAA,KACjD;AACA,IAAA,IAAA,CAAK,YAAA,CAAa,gBAAgB,EAAA,GAAK,CAAA,GAAI,aAAa,EAAE,KAAA,EAAO,OAAO,CAAA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AO,MAAM,CAAA;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAA,CAAa,KAAA,EAAe,EAAE,KAAA,EAAM,EAA6B;AAC/D,IAAA,IAAA,CAAK,UAAA,CAAW,OAAA,CAAQ,CAAC,GAAA,EAAK,CAAA,KAAM;AAClC,MAAA,MAAM,WAAW,CAAA,KAAM,KAAA;AACvB,MAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,QAAA,GAAW,MAAA,GAAS,OAAO,CAAA;AAC7D,MAAA,GAAA,CAAI,QAAA,GAAW,WAAW,CAAA,GAAI,EAAA;AAAA,IAChC,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,CAAa,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AACtC,MAAA,KAAA,CAAM,SAAS,CAAA,KAAM,KAAA;AAAA,IACvB,CAAC,CAAA;AACD,IAAA,IAAI,KAAA,EAAO,IAAA,CAAK,UAAA,CAAW,KAAK,GAAG,KAAA,EAAM;AAAA,EAC3C;AACF","file":"tabs_controller.js","sourcesContent":["/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { isRtl } from \"../utils/logical_scroll\";\n\n/**\n * Headless, accessible tabs behavior.\n *\n * Markup contract (identifier: `stimeo--tabs`):\n * <div data-controller=\"stimeo--tabs\">\n * <div role=\"tablist\" aria-label=\"…\" data-stimeo--tabs-target=\"list\">\n * <button role=\"tab\" id=\"tab-1\" aria-controls=\"panel-1\"\n * data-stimeo--tabs-target=\"tab\"\n * data-action=\"stimeo--tabs#select\n * keydown->stimeo--tabs#onKeydown\">Tab 1</button>\n * <!-- more tabs -->\n * </div>\n * <div role=\"tabpanel\" id=\"panel-1\" aria-labelledby=\"tab-1\"\n * data-stimeo--tabs-target=\"panel\">…</div>\n * <!-- more panels -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Tabs** pattern with **automatic activation**:\n * moving focus with the arrow keys immediately selects the focused tab. Tabs are\n * paired to panels by index (the Nth tab controls the Nth panel).\n *\n * @remarks\n * Behavior only. State is exposed through `aria-selected`, roving `tabindex`\n * (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;\n * the consumer owns all styling. The required `list` target marks the tablist\n * container as part of the semantic contract — that container carries\n * `role=\"tablist\"` and an accessible name; the controller performs no runtime\n * work on it.\n *\n * Behavior provided:\n * - Click a tab to select it.\n * - `ArrowRight`/`ArrowLeft` move to and select the next/previous tab (wrapping);\n * `Home`/`End` select the first/last tab.\n */\nexport class TabsController extends Controller<HTMLElement> {\n static override targets = [\"tab\", \"panel\", \"list\"];\n static actions = [\"onKeydown\", \"select\"] as const;\n\n declare readonly listTarget: HTMLElement;\n declare readonly tabTargets: HTMLButtonElement[];\n declare readonly panelTargets: HTMLElement[];\n\n /**\n * Selects the initially active tab: the pre-selected one, else the first.\n *\n * `findIndex` makes this first-wins when the author marked several — the first\n * in DOM order is the only deterministic reading of \"which one did they mean\" —\n * and `#selectIndex` then writes an explicit value onto every tab, so a\n * forgotten `aria-selected` cannot leave a tab looking unselectable.\n */\n override connect(): void {\n const preselected = this.tabTargets.findIndex(\n (tab) => tab.getAttribute(\"aria-selected\") === \"true\",\n );\n this.#selectIndex(preselected === -1 ? 0 : preselected, { focus: false });\n }\n\n /** Selects the clicked tab. Bound via `data-action` (click). */\n select(event: Event): void {\n const index = this.tabTargets.indexOf(event.currentTarget as HTMLButtonElement);\n if (index !== -1) this.#selectIndex(index, { focus: false });\n }\n\n /** Implements arrow/Home/End navigation with automatic activation. */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key (a grabbed drag handle, a\n // nested menu) must not ALSO act on it — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n const tabs = this.tabTargets;\n const currentIndex = tabs.indexOf(event.currentTarget as HTMLButtonElement);\n if (currentIndex === -1) return;\n\n let nextIndex: number | null = null;\n // Logical, not physical. APG defines these as \"next / previous control\", and\n // says a vertical arrangement swaps in Down/Up for the same meaning — so the\n // pair is one axis's spelling of an order, and the order reverses with the\n // writing direction. Read from the controller element: the container is what\n // lays the items out, and a child may carry its own `dir` (an LTR input\n // inside an RTL form is ordinary authoring).\n const step = isRtl(this.element) ? -1 : 1;\n switch (event.key) {\n case \"ArrowRight\":\n nextIndex = (currentIndex + step + tabs.length) % tabs.length;\n break;\n case \"ArrowLeft\":\n nextIndex = (currentIndex - step + tabs.length) % tabs.length;\n break;\n case \"Home\":\n nextIndex = 0;\n break;\n case \"End\":\n nextIndex = tabs.length - 1;\n break;\n default:\n return;\n }\n\n event.preventDefault();\n this.#selectIndex(nextIndex, { focus: true });\n }\n\n /**\n * Activates the tab/panel pair at `index`: updates `aria-selected`, the roving\n * `tabindex`, and panel visibility. Optionally moves focus to the new tab.\n */\n #selectIndex(index: number, { focus }: { focus: boolean }): void {\n this.tabTargets.forEach((tab, i) => {\n const selected = i === index;\n tab.setAttribute(\"aria-selected\", selected ? \"true\" : \"false\");\n tab.tabIndex = selected ? 0 : -1;\n });\n this.panelTargets.forEach((panel, i) => {\n panel.hidden = i !== index;\n });\n if (focus) this.tabTargets[index]?.focus();\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/controllers/tabs_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,SAAA,KAAc,KAAA;AACxD;;;AC4EO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,KACvC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,IACvC,KAAA,CAAM,QAAA,IAAY,CAAC,KAAA,CAAM,QAAA,CAAS,OAAO,CAAA;AAE9C;;;ACpEO,IAAM,cAAA,GAAN,cAA6B,UAAA,CAAwB;AAAA,EAC1D,OAAgB,OAAA,GAAU,CAAC,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,EACjD,OAAO,OAAA,GAAU,CAAC,WAAA,EAAa,QAAQ,CAAA;A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AAA,IAAU,IAAA,CAAK,MAAA;AACvD,QAAA;AAAA,MACF,KAAK,MAAA;AACH,QAAA,SAAA,GAAY,CAAA;AACZ,QAAA;AAAA,MACF,KAAK,KAAA;AACH,QAAA,SAAA,GAAY,KAAK,MAAA,GAAS,CAAA;AAC1B,QAAA;AAAA,MACF;AACE,QAAA;AAAA;AAGJ,IAAA,KAAA,CAAM,cAAA,EAAe;AACrB,IAAA,IAAA,CAAK,YAAA,CAAa,SAAA,EAAW,EAAE,KAAA,EAAO,MAAM,CAAA;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAA,CAAa,KAAA,EAAe,EAAE,KAAA,EAAM,EAA6B;AAC/D,IAAA,IAAA,CAAK,UAAA,CAAW,OAAA,CAAQ,CAAC,GAAA,EAAK,CAAA,KAAM;AAClC,MAAA,MAAM,WAAW,CAAA,KAAM,KAAA;AACvB,MAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,QAAA,GAAW,MAAA,GAAS,OAAO,CAAA;AAC7D,MAAA,GAAA,CAAI,QAAA,GAAW,WAAW,CAAA,GAAI,EAAA;AAAA,IAChC,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,CAAa,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AACtC,MAAA,KAAA,CAAM,SAAS,CAAA,KAAM,KAAA;AAAA,IACvB,CAAC,CAAA;AACD,IAAA,IAAI,KAAA,EAAO,IAAA,CAAK,UAAA,CAAW,KAAK,GAAG,KAAA,EAAM;AAAA,EAC3C;AACF","file":"tabs_controller.js","sourcesContent":["/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n\n/**\n * True when a press arrived carrying any modifier, for the keys the browser and\n * the OS own outright: return without calling `preventDefault()` and without\n * moving any state.\n *\n * `Control+Home` and `Control+End` jump the document to its ends, and a widget\n * that swallows them makes the shortcut work or not depending on where focus\n * happens to sit. {@link isReservedArrowChord} answers the same question for the\n * arrows, but returns `false` for every other key so that this one can decide.\n *\n * There is no `allow` list here on purpose. APG assigns no modifier chord to\n * `Home`/`End`, so a widget that wanted one would be claiming a combination the\n * pattern never gave it.\n *\n * @example\n * ```ts\n * case \"Home\":\n * case \"End\":\n * if (hasModifierChord(event)) return;\n * ```\n */\nexport function hasModifierChord(event: KeyboardEvent): boolean {\n return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { isRtl } from \"../utils/logical_scroll\";\n\n/**\n * Headless, accessible tabs behavior.\n *\n * Markup contract (identifier: `stimeo--tabs`):\n * <div data-controller=\"stimeo--tabs\">\n * <div role=\"tablist\" aria-label=\"…\" data-stimeo--tabs-target=\"list\">\n * <button role=\"tab\" id=\"tab-1\" aria-controls=\"panel-1\"\n * data-stimeo--tabs-target=\"tab\"\n * data-action=\"stimeo--tabs#select\n * keydown->stimeo--tabs#onKeydown\">Tab 1</button>\n * <!-- more tabs -->\n * </div>\n * <div role=\"tabpanel\" id=\"panel-1\" aria-labelledby=\"tab-1\"\n * data-stimeo--tabs-target=\"panel\">…</div>\n * <!-- more panels -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Tabs** pattern with **automatic activation**:\n * moving focus with the arrow keys immediately selects the focused tab. Tabs are\n * paired to panels by index (the Nth tab controls the Nth panel).\n *\n * @remarks\n * Behavior only. State is exposed through `aria-selected`, roving `tabindex`\n * (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;\n * the consumer owns all styling. The required `list` target marks the tablist\n * container as part of the semantic contract — that container carries\n * `role=\"tablist\"` and an accessible name; the controller performs no runtime\n * work on it.\n *\n * Behavior provided:\n * - Click a tab to select it.\n * - `ArrowRight`/`ArrowLeft` move to and select the next/previous tab (wrapping);\n * `Home`/`End` select the first/last tab.\n */\nexport class TabsController extends Controller<HTMLElement> {\n static override targets = [\"tab\", \"panel\", \"list\"];\n static actions = [\"onKeydown\", \"select\"] as const;\n\n declare readonly listTarget: HTMLElement;\n declare readonly tabTargets: HTMLButtonElement[];\n declare readonly panelTargets: HTMLElement[];\n\n /**\n * Selects the initially active tab: the pre-selected one, else the first.\n *\n * `findIndex` makes this first-wins when the author marked several — the first\n * in DOM order is the only deterministic reading of \"which one did they mean\" —\n * and `#selectIndex` then writes an explicit value onto every tab, so a\n * forgotten `aria-selected` cannot leave a tab looking unselectable.\n */\n override connect(): void {\n const preselected = this.tabTargets.findIndex(\n (tab) => tab.getAttribute(\"aria-selected\") === \"true\",\n );\n this.#selectIndex(preselected === -1 ? 0 : preselected, { focus: false });\n }\n\n /** Selects the clicked tab. Bound via `data-action` (click). */\n select(event: Event): void {\n const index = this.tabTargets.indexOf(event.currentTarget as HTMLButtonElement);\n if (index !== -1) this.#selectIndex(index, { focus: false });\n }\n\n /** Implements arrow/Home/End navigation with automatic activation. */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key (a grabbed drag handle, a\n // nested menu) must not ALSO act on it — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n const tabs = this.tabTargets;\n const currentIndex = tabs.indexOf(event.currentTarget as HTMLButtonElement);\n if (currentIndex === -1) return;\n\n let nextIndex: number | null = null;\n // Logical, not physical. APG defines these as \"next / previous control\", and\n // says a vertical arrangement swaps in Down/Up for the same meaning — so the\n // pair is one axis's spelling of an order, and the order reverses with the\n // writing direction. Read from the controller element: the container is what\n // lays the items out, and a child may carry its own `dir` (an LTR input\n // inside an RTL form is ordinary authoring).\n const step = isRtl(this.element) ? -1 : 1;\n switch (event.key) {\n case \"ArrowRight\":\n nextIndex = (currentIndex + step + tabs.length) % tabs.length;\n break;\n case \"ArrowLeft\":\n nextIndex = (currentIndex - step + tabs.length) % tabs.length;\n break;\n case \"Home\":\n nextIndex = 0;\n break;\n case \"End\":\n nextIndex = tabs.length - 1;\n break;\n default:\n return;\n }\n\n event.preventDefault();\n this.#selectIndex(nextIndex, { focus: true });\n }\n\n /**\n * Activates the tab/panel pair at `index`: updates `aria-selected`, the roving\n * `tabindex`, and panel visibility. Optionally moves focus to the new tab.\n */\n #selectIndex(index: number, { focus }: { focus: boolean }): void {\n this.tabTargets.forEach((tab, i) => {\n const selected = i === index;\n tab.setAttribute(\"aria-selected\", selected ? \"true\" : \"false\");\n tab.tabIndex = selected ? 0 : -1;\n });\n this.panelTargets.forEach((panel, i) => {\n panel.hidden = i !== index;\n });\n if (focus) this.tabTargets[index]?.focus();\n }\n}\n"]}