stimeo-ui 0.2.1 → 0.3.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 (184) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/dist/cable/index.d.ts +16 -16
  3. package/dist/cable/index.js.map +1 -1
  4. package/dist/controllers/accordion_controller.js +10 -0
  5. package/dist/controllers/accordion_controller.js.map +1 -1
  6. package/dist/controllers/alert_dialog_controller.js.map +1 -1
  7. package/dist/controllers/breadcrumb_controller.d.ts +97 -10
  8. package/dist/controllers/breadcrumb_controller.js +225 -13
  9. package/dist/controllers/breadcrumb_controller.js.map +1 -1
  10. package/dist/controllers/calendar_controller.d.ts +11 -1
  11. package/dist/controllers/calendar_controller.js +89 -22
  12. package/dist/controllers/calendar_controller.js.map +1 -1
  13. package/dist/controllers/carousel_controller.d.ts +16 -1
  14. package/dist/controllers/carousel_controller.js +47 -6
  15. package/dist/controllers/carousel_controller.js.map +1 -1
  16. package/dist/controllers/collapsible_controller.js +2 -2
  17. package/dist/controllers/collapsible_controller.js.map +1 -1
  18. package/dist/controllers/color_picker_controller.d.ts +12 -1
  19. package/dist/controllers/color_picker_controller.js +46 -7
  20. package/dist/controllers/color_picker_controller.js.map +1 -1
  21. package/dist/controllers/combobox_controller.d.ts +14 -1
  22. package/dist/controllers/combobox_controller.js +162 -23
  23. package/dist/controllers/combobox_controller.js.map +1 -1
  24. package/dist/controllers/command_palette_controller.d.ts +2 -0
  25. package/dist/controllers/command_palette_controller.js +194 -17
  26. package/dist/controllers/command_palette_controller.js.map +1 -1
  27. package/dist/controllers/confirm_controller.js.map +1 -1
  28. package/dist/controllers/context_menu_controller.d.ts +7 -6
  29. package/dist/controllers/context_menu_controller.js +32 -10
  30. package/dist/controllers/context_menu_controller.js.map +1 -1
  31. package/dist/controllers/count_up_controller.js.map +1 -1
  32. package/dist/controllers/data_grid_controller.d.ts +19 -1
  33. package/dist/controllers/data_grid_controller.js +82 -4
  34. package/dist/controllers/data_grid_controller.js.map +1 -1
  35. package/dist/controllers/date_range_picker_controller.d.ts +1 -0
  36. package/dist/controllers/date_range_picker_controller.js +27 -3
  37. package/dist/controllers/date_range_picker_controller.js.map +1 -1
  38. package/dist/controllers/dialog_controller.js.map +1 -1
  39. package/dist/controllers/dismissible_controller.js.map +1 -1
  40. package/dist/controllers/drawer_controller.js.map +1 -1
  41. package/dist/controllers/dropdown_controller.d.ts +1 -2
  42. package/dist/controllers/dropdown_controller.js.map +1 -1
  43. package/dist/controllers/editable_controller.js +1 -0
  44. package/dist/controllers/editable_controller.js.map +1 -1
  45. package/dist/controllers/focus_controller.d.ts +1 -1
  46. package/dist/controllers/focus_controller.js.map +1 -1
  47. package/dist/controllers/form_field_controller.js.map +1 -1
  48. package/dist/controllers/form_validation_controller.js +1 -1
  49. package/dist/controllers/form_validation_controller.js.map +1 -1
  50. package/dist/controllers/highlight_controller.js.map +1 -1
  51. package/dist/controllers/hover_card_controller.d.ts +1 -1
  52. package/dist/controllers/hover_card_controller.js.map +1 -1
  53. package/dist/controllers/intersection_controller.js +36 -11
  54. package/dist/controllers/intersection_controller.js.map +1 -1
  55. package/dist/controllers/lazy_frame_controller.js +31 -10
  56. package/dist/controllers/lazy_frame_controller.js.map +1 -1
  57. package/dist/controllers/listbox_controller.d.ts +9 -2
  58. package/dist/controllers/listbox_controller.js +257 -53
  59. package/dist/controllers/listbox_controller.js.map +1 -1
  60. package/dist/controllers/local_time_controller.js +2 -2
  61. package/dist/controllers/local_time_controller.js.map +1 -1
  62. package/dist/controllers/menu_controller.d.ts +29 -11
  63. package/dist/controllers/menu_controller.js +104 -17
  64. package/dist/controllers/menu_controller.js.map +1 -1
  65. package/dist/controllers/menubar_controller.d.ts +91 -11
  66. package/dist/controllers/menubar_controller.js +415 -63
  67. package/dist/controllers/menubar_controller.js.map +1 -1
  68. package/dist/controllers/meter_controller.js.map +1 -1
  69. package/dist/controllers/multi_select_controller.d.ts +31 -5
  70. package/dist/controllers/multi_select_controller.js +312 -29
  71. package/dist/controllers/multi_select_controller.js.map +1 -1
  72. package/dist/controllers/navigation_menu_controller.d.ts +65 -18
  73. package/dist/controllers/navigation_menu_controller.js +154 -27
  74. package/dist/controllers/navigation_menu_controller.js.map +1 -1
  75. package/dist/controllers/nested_form_controller.d.ts +4 -5
  76. package/dist/controllers/nested_form_controller.js.map +1 -1
  77. package/dist/controllers/number_input_controller.d.ts +1 -1
  78. package/dist/controllers/number_input_controller.js +7 -0
  79. package/dist/controllers/number_input_controller.js.map +1 -1
  80. package/dist/controllers/otp_controller.js +18 -1
  81. package/dist/controllers/otp_controller.js.map +1 -1
  82. package/dist/controllers/overflow_indicator_controller.d.ts +3 -2
  83. package/dist/controllers/overflow_indicator_controller.js +81 -13
  84. package/dist/controllers/overflow_indicator_controller.js.map +1 -1
  85. package/dist/controllers/overflow_menu_controller.d.ts +78 -19
  86. package/dist/controllers/overflow_menu_controller.js +381 -57
  87. package/dist/controllers/overflow_menu_controller.js.map +1 -1
  88. package/dist/controllers/pagination_controller.d.ts +36 -5
  89. package/dist/controllers/pagination_controller.js +163 -32
  90. package/dist/controllers/pagination_controller.js.map +1 -1
  91. package/dist/controllers/persist_controller.js +6 -6
  92. package/dist/controllers/persist_controller.js.map +1 -1
  93. package/dist/controllers/pointer_drag_controller.d.ts +2 -3
  94. package/dist/controllers/pointer_drag_controller.js +9 -1
  95. package/dist/controllers/pointer_drag_controller.js.map +1 -1
  96. package/dist/controllers/popover_controller.d.ts +1 -2
  97. package/dist/controllers/popover_controller.js +2 -2
  98. package/dist/controllers/popover_controller.js.map +1 -1
  99. package/dist/controllers/portal_controller.d.ts +4 -4
  100. package/dist/controllers/portal_controller.js.map +1 -1
  101. package/dist/controllers/progress_controller.js.map +1 -1
  102. package/dist/controllers/radio_group_controller.js +22 -3
  103. package/dist/controllers/radio_group_controller.js.map +1 -1
  104. package/dist/controllers/range_slider_controller.d.ts +14 -4
  105. package/dist/controllers/range_slider_controller.js +32 -6
  106. package/dist/controllers/range_slider_controller.js.map +1 -1
  107. package/dist/controllers/rating_controller.js +16 -2
  108. package/dist/controllers/rating_controller.js.map +1 -1
  109. package/dist/controllers/read_more_controller.js +63 -19
  110. package/dist/controllers/read_more_controller.js.map +1 -1
  111. package/dist/controllers/reading_progress_controller.js.map +1 -1
  112. package/dist/controllers/resizable_controller.d.ts +3 -1
  113. package/dist/controllers/resizable_controller.js +65 -1
  114. package/dist/controllers/resizable_controller.js.map +1 -1
  115. package/dist/controllers/roving_controller.js +17 -2
  116. package/dist/controllers/roving_controller.js.map +1 -1
  117. package/dist/controllers/scroll_area_controller.js +86 -12
  118. package/dist/controllers/scroll_area_controller.js.map +1 -1
  119. package/dist/controllers/scroll_restore_controller.js +1 -1
  120. package/dist/controllers/scroll_restore_controller.js.map +1 -1
  121. package/dist/controllers/scroll_visibility_controller.d.ts +6 -3
  122. package/dist/controllers/scroll_visibility_controller.js +33 -3
  123. package/dist/controllers/scroll_visibility_controller.js.map +1 -1
  124. package/dist/controllers/scrollspy_controller.d.ts +64 -15
  125. package/dist/controllers/scrollspy_controller.js +346 -73
  126. package/dist/controllers/scrollspy_controller.js.map +1 -1
  127. package/dist/controllers/separator_controller.d.ts +20 -5
  128. package/dist/controllers/separator_controller.js +9 -0
  129. package/dist/controllers/separator_controller.js.map +1 -1
  130. package/dist/controllers/sidebar_controller.d.ts +1 -1
  131. package/dist/controllers/sidebar_controller.js.map +1 -1
  132. package/dist/controllers/skeleton_controller.js +1 -1
  133. package/dist/controllers/skeleton_controller.js.map +1 -1
  134. package/dist/controllers/slider_controller.d.ts +11 -1
  135. package/dist/controllers/slider_controller.js +32 -6
  136. package/dist/controllers/slider_controller.js.map +1 -1
  137. package/dist/controllers/sortable_controller.d.ts +3 -1
  138. package/dist/controllers/sortable_controller.js +34 -3
  139. package/dist/controllers/sortable_controller.js.map +1 -1
  140. package/dist/controllers/spinner_controller.js +1 -1
  141. package/dist/controllers/spinner_controller.js.map +1 -1
  142. package/dist/controllers/stick_to_bottom_controller.d.ts +5 -6
  143. package/dist/controllers/stick_to_bottom_controller.js +2 -1
  144. package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
  145. package/dist/controllers/sticky_observer_controller.js +32 -11
  146. package/dist/controllers/sticky_observer_controller.js.map +1 -1
  147. package/dist/controllers/submit_once_controller.d.ts +2 -2
  148. package/dist/controllers/submit_once_controller.js.map +1 -1
  149. package/dist/controllers/switch_controller.js +1 -0
  150. package/dist/controllers/switch_controller.js.map +1 -1
  151. package/dist/controllers/tabs_controller.d.ts +11 -3
  152. package/dist/controllers/tabs_controller.js +26 -3
  153. package/dist/controllers/tabs_controller.js.map +1 -1
  154. package/dist/controllers/tags_input_controller.js +22 -2
  155. package/dist/controllers/tags_input_controller.js.map +1 -1
  156. package/dist/controllers/theme_controller.d.ts +1 -1
  157. package/dist/controllers/theme_controller.js +22 -3
  158. package/dist/controllers/theme_controller.js.map +1 -1
  159. package/dist/controllers/time_picker_controller.js +20 -1
  160. package/dist/controllers/time_picker_controller.js.map +1 -1
  161. package/dist/controllers/toast_controller.d.ts +4 -5
  162. package/dist/controllers/toast_controller.js +4 -5
  163. package/dist/controllers/toast_controller.js.map +1 -1
  164. package/dist/controllers/toggle_group_controller.js +23 -2
  165. package/dist/controllers/toggle_group_controller.js.map +1 -1
  166. package/dist/controllers/toolbar_controller.d.ts +53 -13
  167. package/dist/controllers/toolbar_controller.js +230 -31
  168. package/dist/controllers/toolbar_controller.js.map +1 -1
  169. package/dist/controllers/tooltip_controller.d.ts +1 -1
  170. package/dist/controllers/tooltip_controller.js.map +1 -1
  171. package/dist/controllers/transition_controller.js.map +1 -1
  172. package/dist/controllers/tree_view_controller.d.ts +87 -6
  173. package/dist/controllers/tree_view_controller.js +467 -51
  174. package/dist/controllers/tree_view_controller.js.map +1 -1
  175. package/dist/index.js +3514 -689
  176. package/dist/index.js.map +1 -1
  177. package/dist/inspector/cli.d.ts +375 -39
  178. package/dist/inspector/cli.js +228 -14
  179. package/dist/inspector/cli.js.map +1 -1
  180. package/dist/inspector/cli_bin.js +419 -48
  181. package/dist/inspector/cli_bin.js.map +1 -1
  182. package/dist/inspector/examples.json +24 -24
  183. package/dist/inspector/manifest.json +1040 -125
  184. package/package.json +5 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/roving_tabindex.ts","../../src/controllers/toolbar_controller.ts"],"names":[],"mappings":";;;;;AAqBO,IAAM,iBAAN,MAAqB;AAAA;AAAA,EAEjB,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT,YAAY,QAAA,EAA+B;AACzC,IAAA,IAAA,CAAK,SAAA,GAAY,QAAA;AAAA,EACnB;AAAA;AAAA,EAGA,IAAI,WAAA,GAAsB;AACxB,IAAA,OAAO,IAAA,CAAK,WAAU,CAAE,SAAA,CAAU,CAAC,IAAA,KAAS,IAAA,CAAK,aAAa,CAAC,CAAA;AAAA,EACjE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,UAAU,KAAA,EAAe,EAAE,QAAQ,KAAA,EAAM,GAAyB,EAAC,EAAS;AAC1E,IAAA,MAAM,KAAA,GAAQ,KAAK,SAAA,EAAU;AAC7B,IAAA,KAAA,CAAM,OAAA,CAAQ,CAAC,IAAA,EAAM,CAAA,KAAM;AACzB,MAAA,IAAA,CAAK,QAAA,GAAW,CAAA,KAAM,KAAA,GAAQ,CAAA,GAAI,EAAA;AAAA,IACpC,CAAC,CAAA;AACD,IAAA,IAAI,KAAA,EAAO,KAAA,CAAM,KAAK,CAAA,EAAG,KAAA,EAAM;AAAA,EACjC;AACF,CAAA;AAkBO,SAAS,UAAA,CACd,OAAA,EACA,MAAA,EACA,KAAA,EACA,IAAA,EACQ;AACR,EAAA,IAAI,MAAA,KAAW,GAAG,OAAO,EAAA;AACzB,EAAA,MAAM,OAAO,OAAA,GAAU,KAAA;AACvB,EAAA,IAAI,IAAA,KAAS,MAAA,EAAQ,OAAA,CAAQ,IAAA,GAAO,MAAA,IA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MAAA,CAAO,CAAC,YAAY,IAAA,CAAK,YAAA,CAAa,OAAO,CAAC,CAAA;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa,OAAA,EAA+B;AAC1C,IAAA,IAAI,OAAA,CAAQ,YAAA,CAAa,QAAQ,CAAA,EAAG,OAAO,KAAA;AAC3C,IAAA,IAAI,OAAA,CAAQ,YAAA,CAAa,eAAe,CAAA,KAAM,QAAQ,OAAO,KAAA;AAC7D,IAAA,OAAO,CAAE,OAAA,CAAiD,QAAA;AAAA,EAC5D;AACF","file":"toolbar_controller.js","sourcesContent":["/**\n * Low-level roving-tabindex primitive shared by composite-widget controllers.\n *\n * The APG roving-tabindex pattern keeps a composite widget a single Tab stop:\n * exactly one item is in the Tab sequence (`tabindex=\"0\"`) while the rest are\n * removed from it (`tabindex=\"-1\"`), and the arrow keys move both DOM focus and\n * that single tabbable position together. {@link RovingTabindex} owns *only* that\n * mechanical bookkeeping — \"which one item is tabbable, and move focus there\".\n *\n * It is intentionally **policy-free**. Orientation, wrapping vs. clamping,\n * selection-follows-focus, typeahead, and `Home`/`End` semantics differ per APG\n * pattern (Radio Group, Toolbar, Rating, …); folding them into one helper would\n * flatten those widgets to a lowest common denominator and lose each pattern's\n * correctness. Those decisions therefore stay in each controller, which calls\n * {@link RovingTabindex.setActive} with an index it computed itself (optionally\n * via the pure {@link rovingMove} helper).\n *\n * @remarks\n * Items are read lazily through a getter so a controller can add or remove\n * targets (Stimulus re-scans the DOM) without re-wiring this helper.\n */\nexport class RovingTabindex {\n /** Returns the current ordered item elements; called on every operation. */\n readonly #getItems: () => HTMLElement[];\n\n /**\n * @param getItems - Returns the current ordered item elements. Called on every\n * operation so the live target list is always used.\n */\n constructor(getItems: () => HTMLElement[]) {\n this.#getItems = getItems;\n }\n\n /** Index of the currently tabbable item (`tabindex=\"0\"`), or `-1` if none. */\n get activeIndex(): number {\n return this.#getItems().findIndex((item) => item.tabIndex === 0);\n }\n\n /**\n * Makes exactly the item at `index` tabbable (`tabindex=\"0\"`) and removes every\n * other item from the Tab sequence (`tabindex=\"-1\"`). An out-of-range `index`\n * (e.g. `-1`) leaves all items at `-1`, which a controller can use to express\n * \"nothing is currently tabbable\".\n *\n * @param index - Position of the item to make tabbable.\n * @param options - Pass `{ focus: true }` to also move DOM focus to that item.\n */\n setActive(index: number, { focus = false }: { focus?: boolean } = {}): void {\n const items = this.#getItems();\n items.forEach((item, i) => {\n item.tabIndex = i === index ? 0 : -1;\n });\n if (focus) items[index]?.focus();\n }\n}\n\n/** Edge behavior for {@link rovingMove}: cycle past the ends, or stop at them. */\nexport type RovingWrap = \"wrap\" | \"clamp\";\n\n/**\n * Pure helper that resolves the target index for a one-step directional move.\n *\n * Keyboard/orientation mapping stays in the caller: it decides that a key means\n * `delta` `+1` (next) or `-1` (previous) and whether the widget should `\"wrap\"`\n * (Radio Group, Toolbar) or `\"clamp\"` at the ends.\n *\n * @param current - The index focus is moving from.\n * @param length - Number of items in the set.\n * @param delta - `+1` to move to the next item, `-1` for the previous.\n * @param wrap - `\"wrap\"` cycles around the ends; `\"clamp\"` stops at them.\n * @returns The resolved index, or `-1` when there are no items.\n */\nexport function rovingMove(\n current: number,\n length: number,\n delta: number,\n wrap: RovingWrap,\n): number {\n if (length === 0) return -1;\n const next = current + delta;\n if (wrap === \"wrap\") return (next + length) % length;\n return Math.min(length - 1, Math.max(0, next));\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { RovingTabindex, type RovingWrap, rovingMove } from \"../utils/roving_tabindex\";\n\n/**\n * Headless, accessible toolbar behavior.\n *\n * Markup contract (identifier: `stimeo--toolbar`):\n * <div data-controller=\"stimeo--toolbar\" role=\"toolbar\" aria-label=\"Text formatting\"\n * data-stimeo--toolbar-orientation-value=\"horizontal\">\n * <button type=\"button\" data-stimeo--toolbar-target=\"control\"\n * data-action=\"keydown->stimeo--toolbar#onKeydown\">Bold</button>\n * <!-- more controls; exactly one tabindex=0 -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Toolbar** pattern: the group is a single Tab\n * stop (roving tabindex) and the arrow keys move focus between controls. Each\n * control's own function (press, toggle, open a menu) stays with that element or\n * its own controller — the toolbar only owns navigation.\n *\n * @remarks\n * Behavior only. The roving mechanics are delegated to {@link RovingTabindex};\n * orientation and wrap policy stay here per the APG (they differ per widget).\n *\n * Behavior provided:\n * - Exactly one control is tabbable (`tabindex=\"0\"`); the rest are `-1`.\n * - `ArrowRight`/`ArrowLeft` (horizontal) or `ArrowDown`/`ArrowUp` (vertical)\n * move focus to the next/previous control; `Home`/`End` to the first/last.\n * - With `wrap=true` movement cycles past the ends; with `wrap=false` it stops.\n * - Returning focus from outside lands on the most recently active control,\n * because that is the one left tabbable.\n */\nexport class ToolbarController extends Controller<HTMLElement> {\n static override targets = [\"control\"];\n static override values = {\n orientation: { type: String, default: \"horizontal\" },\n wrap: { type: Boolean, default: true },\n };\n static actions = [\"onKeydown\"] as const;\n\n declare readonly controlTargets: HTMLElement[];\n declare orientationValue: string;\n declare wrapValue: boolean;\n\n readonly #roving = new RovingTabindex(() => this.controlTargets);\n\n /**\n * Establishes the single tab stop: keep an existing one if it is still\n * navigable, else the first navigable control. Disabled / hidden controls are\n * skipped so the toolbar's lone Tab stop never lands on an unfocusable element\n * (which would make the whole group unreachable on Tab re-entry).\n */\n override connect(): void {\n const active = this.#roving.activeIndex;\n const activeEl = active === -1 ? null : this.controlTargets[active];\n if (activeEl && this.#isNavigable(activeEl)) {\n this.#roving.setActive(active);\n return;\n }\n const first = this.#navigableControls[0];\n this.#roving.setActive(first ? this.controlTargets.indexOf(first) : -1);\n }\n\n /** Arrow/Home/End move focus and the single tab stop. Bound via `data-action`. */\n onKeydown(event: KeyboardEvent): void {\n const navigable = this.#navigableControls;\n const current = navigable.indexOf(event.currentTarget as HTMLElement);\n if (current === -1) return;\n\n const length = navigable.length;\n const wrap: RovingWrap = this.wrapValue ? \"wrap\" : \"clamp\";\n const vertical = this.orientationValue === \"vertical\";\n const forwardKey = vertical ? \"ArrowDown\" : \"ArrowRight\";\n const backwardKey = vertical ? \"ArrowUp\" : \"ArrowLeft\";\n\n let next: number;\n if (event.key === forwardKey) {\n next = rovingMove(current, length, 1, wrap);\n } else if (event.key === backwardKey) {\n next = rovingMove(current, length, -1, wrap);\n } else if (event.key === \"Home\") {\n next = 0;\n } else if (event.key === \"End\") {\n next = length - 1;\n } else {\n return;\n }\n\n event.preventDefault();\n const target = navigable[next];\n if (target) this.#roving.setActive(this.controlTargets.indexOf(target), { focus: true });\n }\n\n /** Controls eligible for the roving tab stop (excludes disabled / hidden). */\n get #navigableControls(): HTMLElement[] {\n return this.controlTargets.filter((control) => this.#isNavigable(control));\n }\n\n /**\n * A control can hold the tab stop unless it is `hidden`, `aria-disabled`, or a\n * natively `disabled` form control. CSS-only visibility cannot be detected\n * headlessly and stays the consumer's responsibility.\n */\n #isNavigable(control: HTMLElement): boolean {\n if (control.hasAttribute(\"hidden\")) return false;\n if (control.getAttribute(\"aria-disabled\") === \"true\") return false;\n return !(control as HTMLButtonElement | HTMLInputElement).disabled;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/utils/composition_tracker.ts","../../src/utils/focus_candidate.ts","../../src/utils/roving_tabindex.ts","../../src/controllers/toolbar_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,CAA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,GAAoC;AACtC,IAAA,OAAO,IAAA,CAAK,eAAe,MAAA,CAAO,CAAC,YAAY,IAAA,CAAK,YAAA,CAAa,OAAO,CAAC,CAAA;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,aAAa,OAAA,EAA+B;AAC1C,IAAA,IAAI,IAAA,CAAK,SAAA,CAAU,OAAO,CAAA,EAAG,OAAO,KAAA;AACpC,IAAA,IAAI,EAAE,UAAA,IAAc,OAAA,CAAA,EAAU,OAAO,IAAA;AACrC,IAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,IAAA,EAAM,OAAO,KAAA;AACtC,IAAA,OAAO,CAAC,yBAAyB,OAAO,CAAA;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,UAAU,OAAA,EAA+B;AACvC,IAAA,IAAI,IAAA,GAA2B,OAAA;AAC/B,IAAA,OAAO,IAAA,IAAQ,IAAA,KAAS,IAAA,CAAK,OAAA,EAAS;AACpC,MAAA,IAAI,IAAA,CAAK,YAAA,CAAa,QAAQ,CAAA,EAAG,OAAO,IAAA;AACxC,MAAA,IAAA,GAAO,IAAA,CAAK,aAAA;AAAA,IACd;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"toolbar_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","/** Minimal event shape carrying the platform's per-event composition signal. */\nexport interface CompositionSignal {\n readonly isComposing?: boolean;\n}\n\n/** Hooks that keep component-specific work outside {@link CompositionTracker}. */\nexport interface CompositionTrackerOptions {\n /** Runs after lifecycle state is set for a `compositionstart` event. */\n readonly onStart?: (event: Event) => void;\n /** Runs after lifecycle state is cleared for a `compositionend` event. */\n readonly onEnd?: (event: Event) => void;\n}\n\n/**\n * Owns IME composition listeners and transient state for one or more event targets.\n *\n * Some browsers omit `KeyboardEvent.isComposing` on the keydown that confirms a\n * conversion. Tracking `compositionstart` through `compositionend` supplies the\n * missing lifecycle signal without relying on deprecated numeric key codes.\n * Component policy stays with the consumer: filtering, validation, and submission\n * belong in the optional {@link CompositionTrackerOptions.onEnd} callback.\n *\n * @example\n * ```ts\n * #composition = new CompositionTracker({ onEnd: () => this.filter() });\n *\n * connect(): void {\n * this.#composition.observe(this.inputTarget);\n * }\n *\n * disconnect(): void {\n * this.#composition.disconnect();\n * }\n *\n * onKeydown(event: KeyboardEvent): void {\n * if (this.#composition.isComposing(event)) return;\n * }\n * ```\n */\nexport class CompositionTracker {\n readonly #observedTargets = new Set<EventTarget>();\n readonly #activeTargets = new Set<EventTarget>();\n readonly #onStart: ((event: Event) => void) | undefined;\n readonly #onEnd: ((event: Event) => void) | undefined;\n\n constructor(options: CompositionTrackerOptions = {}) {\n this.#onStart = options.onStart;\n this.#onEnd = options.onEnd;\n }\n\n /** Starts lifecycle tracking for `target`; repeated calls are idempotent. */\n observe(target: EventTarget): void {\n if (this.#observedTargets.has(target)) return;\n target.addEventListener(\"compositionstart\", this.#handleStart);\n target.addEventListener(\"compositionend\", this.#handleEnd);\n this.#observedTargets.add(target);\n }\n\n /** Stops tracking one target and clears any active composition it owned. */\n unobserve(target: EventTarget): void {\n if (!this.#observedTargets.delete(target)) return;\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n this.#activeTargets.delete(target);\n }\n\n /** Releases every listener and clears state so reconnect starts cleanly. */\n disconnect(): void {\n for (const target of this.#observedTargets) {\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n }\n this.#observedTargets.clear();\n this.#activeTargets.clear();\n }\n\n /** True when lifecycle tracking or the current event reports composition. */\n isComposing(event?: CompositionSignal): boolean {\n return this.#activeTargets.size > 0 || event?.isComposing === true;\n }\n\n readonly #handleStart = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.add(event.currentTarget);\n this.#onStart?.(event);\n };\n\n readonly #handleEnd = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.delete(event.currentTarget);\n this.#onEnd?.(event);\n };\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` (an ancestor's counts), the native `disabled`\n * property, and `disabled` inherited from an ancestor `fieldset`. CSS-only\n * invisibility is not detectable here and stays the consumer's problem.\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]\")) 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 * Low-level roving-tabindex primitive shared by composite-widget controllers.\n *\n * The APG roving-tabindex pattern keeps a composite widget a single Tab stop:\n * exactly one item is in the Tab sequence (`tabindex=\"0\"`) while the rest are\n * removed from it (`tabindex=\"-1\"`), and the arrow keys move both DOM focus and\n * that single tabbable position together. {@link RovingTabindex} owns *only* that\n * mechanical bookkeeping — \"which one item is tabbable, and move focus there\".\n *\n * It is intentionally **policy-free**. Orientation, wrapping vs. clamping,\n * selection-follows-focus, typeahead, and `Home`/`End` semantics differ per APG\n * pattern (Radio Group, Toolbar, Rating, …); folding them into one helper would\n * flatten those widgets to a lowest common denominator and lose each pattern's\n * correctness. Those decisions therefore stay in each controller, which calls\n * {@link RovingTabindex.setActive} with an index it computed itself (optionally\n * via the pure {@link rovingMove} helper).\n *\n * @remarks\n * Items are read lazily through a getter so a controller can add or remove\n * targets (Stimulus re-scans the DOM) without re-wiring this helper.\n */\nexport class RovingTabindex {\n /** Returns the current ordered item elements; called on every operation. */\n readonly #getItems: () => HTMLElement[];\n\n /**\n * @param getItems - Returns the current ordered item elements. Called on every\n * operation so the live target list is always used.\n */\n constructor(getItems: () => HTMLElement[]) {\n this.#getItems = getItems;\n }\n\n /** Index of the currently tabbable item (`tabindex=\"0\"`), or `-1` if none. */\n get activeIndex(): number {\n return this.#getItems().findIndex((item) => item.tabIndex === 0);\n }\n\n /**\n * Makes exactly the item at `index` tabbable (`tabindex=\"0\"`) and removes every\n * other item from the Tab sequence (`tabindex=\"-1\"`). An out-of-range `index`\n * (e.g. `-1`) leaves all items at `-1`, which a controller can use to express\n * \"nothing is currently tabbable\".\n *\n * @param index - Position of the item to make tabbable.\n * @param options - Pass `{ focus: true }` to also move DOM focus to that item.\n */\n setActive(index: number, { focus = false }: { focus?: boolean } = {}): void {\n const items = this.#getItems();\n items.forEach((item, i) => {\n item.tabIndex = i === index ? 0 : -1;\n });\n if (focus) items[index]?.focus();\n }\n}\n\n/** Edge behavior for {@link rovingMove}: cycle past the ends, or stop at them. */\nexport type RovingWrap = \"wrap\" | \"clamp\";\n\n/**\n * Pure helper that resolves the target index for a one-step directional move.\n *\n * Keyboard/orientation mapping stays in the caller: it decides that a key means\n * `delta` `+1` (next) or `-1` (previous) and whether the widget should `\"wrap\"`\n * (Radio Group, Toolbar) or `\"clamp\"` at the ends.\n *\n * @param current - The index focus is moving from.\n * @param length - Number of items in the set.\n * @param delta - `+1` to move to the next item, `-1` for the previous.\n * @param wrap - `\"wrap\"` cycles around the ends; `\"clamp\"` stops at them.\n * @returns The resolved index, or `-1` when there are no items.\n */\nexport function rovingMove(\n current: number,\n length: number,\n delta: number,\n wrap: RovingWrap,\n): number {\n if (length === 0) return -1;\n const next = current + delta;\n if (wrap === \"wrap\") return (next + length) % length;\n return Math.min(length - 1, Math.max(0, next));\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { inheritsFieldsetDisabled } from \"../utils/focus_candidate\";\nimport { isRtl } from \"../utils/logical_scroll\";\nimport { RovingTabindex, type RovingWrap, rovingMove } from \"../utils/roving_tabindex\";\n\n/**\n * Attributes that flip a control between navigable and not. Watched on the whole\n * subtree because a *sibling* controller (an editor toggling `disabled` on its\n * command buttons, a form enabling a fieldset) is what usually changes them.\n * Watched together with `childList`, which covers controls added or removed at\n * runtime without depending on Stimulus's asynchronous target callbacks.\n * `tabindex` is deliberately absent: the controller writes it itself, so\n * observing it would feed back into the observer.\n */\nconst STATE_ATTRIBUTES = [\"disabled\", \"hidden\"];\n\n/**\n * Headless, accessible toolbar behavior.\n *\n * Markup contract (identifier: `stimeo--toolbar`):\n * <div data-controller=\"stimeo--toolbar\" role=\"toolbar\" aria-label=\"Text formatting\"\n * data-stimeo--toolbar-orientation-value=\"horizontal\">\n * <button type=\"button\" data-stimeo--toolbar-target=\"control\">Bold</button>\n * <!-- more controls -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Toolbar** pattern: the group is a single Tab\n * stop (roving tabindex) and the arrow keys move focus between controls. Each\n * control's own function (press, toggle, open a menu) stays with that element or\n * its own controller — the toolbar only owns navigation.\n *\n * @remarks\n * Behavior only. The roving mechanics are delegated to {@link RovingTabindex};\n * orientation and wrap policy stay here per the APG (they differ per widget).\n * ARIA (`role=\"toolbar\"`, the accessible name, and `aria-orientation=\"vertical\"`\n * when the axis is vertical) is the author's, exactly as with `role`.\n *\n * Behavior provided:\n * - Exactly one *navigable* control is tabbable (`tabindex=\"0\"`); the rest are\n * `-1`. The invariant is re-established on connect, on control add/remove,\n * whenever `disabled` / `hidden` changes under the toolbar, and whenever an\n * enclosing `<fieldset>` is disabled or re-enabled — disabling the control that\n * held the Tab stop must never make the whole group unreachable by Tab, and\n * unlocking the surrounding form must bring it back.\n * - `ArrowRight`/`ArrowLeft` (horizontal) or `ArrowDown`/`ArrowUp` (vertical)\n * move focus to the next/previous navigable control; `Home`/`End` to the\n * first/last. `aria-disabled=\"true\"` controls remain in that roving order and\n * can be both origins and destinations; only their activation is suppressed\n * by the control itself or its owning behavior. Native `disabled` and `hidden`\n * controls are excluded.\n * - With `wrap=true` movement cycles past the ends; with `wrap=false` it stops.\n * - `orientation` accepts `horizontal` (default) and `vertical`; any other value\n * degrades to `horizontal`. There is no `both` — for two-axis navigation use\n * `stimeo--roving`, whose same-named Value does accept it.\n * - Returning focus from outside lands on the most recently *active* control —\n * the last one moved to by key, click, or programmatic `focus()`, because that\n * is the one left tabbable (`focusin` keeps the Tab stop in sync).\n *\n * Keydown is **delegated on the container**, so controls added at runtime need\n * no per-element `data-action` (Stimulus binds those asynchronously, which is\n * unreliable for appended nodes). A `data-action=\"keydown->stimeo--toolbar#onKeydown\"`\n * on each control stays supported; it does not double-move, because the second\n * pass sees `defaultPrevented`.\n *\n * Initial Tab stop: to choose it, write `tabindex` on **every** control (exactly\n * one `0`, the rest `-1`). Natively focusable elements are `tabindex=\"0\"`\n * effectively when the attribute is absent, so annotating only the intended\n * entry point makes the *first* control win instead.\n *\n * Known constraint: a toolbar that contains a text input competes with it for\n * the arrow keys — the APG expects the toolbar to own them. Keep free-text\n * fields outside the toolbar (IME composition is yielded to, but caret movement\n * is not).\n */\nexport class ToolbarController extends Controller<HTMLElement> {\n static override targets = [\"control\"];\n static override values = {\n orientation: { type: String, default: \"horizontal\" },\n wrap: { type: Boolean, default: true },\n };\n static actions = [\"onKeydown\"] as const;\n\n declare readonly controlTargets: HTMLElement[];\n declare orientationValue: string;\n declare wrapValue: boolean;\n\n readonly #roving = new RovingTabindex(() => this.controlTargets);\n readonly #composition = new CompositionTracker();\n #observer: MutationObserver | null = null;\n /**\n * Live between `connect()` and `disconnect()`. Stimulus reports the *initial*\n * targets before `connect()` and re-reports them as disconnected after\n * `disconnect()`; gating on this keeps the target callbacks from clobbering\n * the authored Tab stop on mount and from resurrecting one after teardown.\n */\n #connected = false;\n\n override connect(): void {\n this.#ensureTabStop();\n this.element.addEventListener(\"keydown\", this.#onKeydown);\n this.element.addEventListener(\"focusin\", this.#onFocusin);\n this.#composition.observe(this.element);\n if (typeof MutationObserver !== \"undefined\") {\n const observer = new MutationObserver(() => this.#ensureTabStop());\n observer.observe(this.element, {\n subtree: true,\n childList: true,\n attributes: true,\n attributeFilter: STATE_ATTRIBUTES,\n });\n // A `<fieldset disabled>` above the root disables the toolbar's form\n // controls from outside the observed subtree, so each enclosing fieldset's\n // own `disabled` is watched too. The walk starts at the parent: re-observing\n // the root would replace its options and lose the subtree registration.\n for (\n let fieldset = this.element.parentElement?.closest(\"fieldset\") ?? null;\n fieldset;\n fieldset = fieldset.parentElement?.closest(\"fieldset\") ?? null\n ) {\n observer.observe(fieldset, { attributes: true, attributeFilter: [\"disabled\"] });\n }\n this.#observer = observer;\n }\n this.#connected = true;\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.element.removeEventListener(\"keydown\", this.#onKeydown);\n this.element.removeEventListener(\"focusin\", this.#onFocusin);\n this.#composition.disconnect();\n this.#observer?.disconnect();\n this.#observer = null;\n }\n\n /**\n * A control added at runtime is dropped out of the Tab sequence first — a\n * fresh `<button>` is tabbable by default, which would make the group two Tab\n * stops — and then the lone stop is re-established.\n */\n controlTargetConnected(control: HTMLElement): void {\n if (!this.#connected) return;\n control.tabIndex = -1;\n this.#ensureTabStop();\n }\n\n /** Removing the control that held the Tab stop must not orphan the group. */\n controlTargetDisconnected(): void {\n if (!this.#connected) return;\n this.#ensureTabStop();\n }\n\n /**\n * Arrow/Home/End move focus and the single tab stop.\n *\n * Binding this per control with `data-action` is **optional** — the same\n * handling runs from the container's delegated listener. It stays a declared\n * action so per-control wiring keeps working; wiring both does not\n * double-move, because the delegated pass then yields on `defaultPrevented`.\n */\n onKeydown(event: KeyboardEvent): void {\n this.#handleKeydown(event);\n }\n\n /** Delegated counterpart of {@link onKeydown}; bound on the container. */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n this.#handleKeydown(event);\n };\n\n /**\n * Syncs the Tab stop to a control focused by other means (click, programmatic\n * `focus()`) so Tab re-entry returns there. A non-navigable control is ignored:\n * the lone Tab stop must never sit on something the user cannot operate.\n */\n readonly #onFocusin = (event: FocusEvent): void => {\n const index = this.#indexOf(event.target);\n const control = index === -1 ? undefined : this.controlTargets[index];\n if (!control || !this.#isNavigable(control)) return;\n this.#roving.setActive(index);\n };\n\n #handleKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key (a grabbed drag handle, a\n // nested menu) must not ALSO move the roving focus. This is what makes the\n // per-control `data-action` and the delegated listener idempotent.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n // Arrow/Home/End belong to the IME while a composition is in flight.\n if (this.#composition.isComposing(event)) return;\n // Re-assert the invariant before acting: the attribute observer runs async\n // (and may be absent), so a Tab stop invalidated moments ago can still be in\n // place here.\n this.#ensureTabStop();\n\n const from = this.#indexOf(event.target);\n if (from === -1) return;\n\n const vertical = this.orientationValue === \"vertical\";\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 rtl = !vertical && isRtl(this.element);\n const forwardKey = vertical ? \"ArrowDown\" : rtl ? \"ArrowLeft\" : \"ArrowRight\";\n const backwardKey = vertical ? \"ArrowUp\" : rtl ? \"ArrowRight\" : \"ArrowLeft\";\n\n let target: HTMLElement | undefined;\n if (event.key === forwardKey) {\n target = this.#nextNavigable(from, 1);\n } else if (event.key === backwardKey) {\n target = this.#nextNavigable(from, -1);\n } else if (event.key === \"Home\") {\n target = this.#navigableControls[0];\n } else if (event.key === \"End\") {\n const navigable = this.#navigableControls;\n target = navigable[navigable.length - 1];\n } else {\n return;\n }\n\n event.preventDefault();\n if (target) this.#roving.setActive(this.controlTargets.indexOf(target), { focus: true });\n }\n\n /**\n * Re-establishes the single Tab stop: keep the current one while it is still\n * navigable, else hand it to the first navigable control. `-1` (no Tab stop at\n * all) is reached only when every control is unavailable, and is recovered\n * from as soon as one becomes navigable again. Idempotent by construction, so\n * connect, the target callbacks, the observer, and keydown can all call it.\n */\n #ensureTabStop(): void {\n const active = this.#roving.activeIndex;\n const activeEl = active === -1 ? null : this.controlTargets[active];\n if (activeEl && this.#isNavigable(activeEl)) {\n this.#roving.setActive(active);\n return;\n }\n const first = this.#navigableControls[0];\n this.#roving.setActive(first ? this.controlTargets.indexOf(first) : -1);\n }\n\n /**\n * First navigable control strictly in the `delta` direction from `fromIndex`,\n * scanning the **full** control list rather than the navigable subset so a\n * non-navigable origin is never a dead end. When the direction yields nothing\n * the origin keeps focus; when the origin itself is not navigable the first\n * navigable control is used instead, so an arrow key always escapes.\n */\n #nextNavigable(fromIndex: number, delta: number): HTMLElement | undefined {\n const controls = this.controlTargets;\n const length = controls.length;\n const wrap: RovingWrap = this.wrapValue ? \"wrap\" : \"clamp\";\n let index = fromIndex;\n for (let step = 0; step < length; step++) {\n const next = rovingMove(index, length, delta, wrap);\n if (next === index) break; // clamped at an end (or a single control)\n index = next;\n const candidate = controls[index];\n if (candidate && this.#isNavigable(candidate)) return candidate;\n }\n const origin = controls[fromIndex];\n return origin && this.#isNavigable(origin) ? origin : this.#navigableControls[0];\n }\n\n /** Index in `controlTargets` of the control owning `target` (it or a descendant). */\n #indexOf(target: EventTarget | null): number {\n const node = target as Node | null;\n if (!node) return -1;\n return this.controlTargets.findIndex((control) => control === node || control.contains(node));\n }\n\n /** Controls eligible for the roving tab stop (excludes native disabled / hidden). */\n get #navigableControls(): HTMLElement[] {\n return this.controlTargets.filter((control) => this.#isNavigable(control));\n }\n\n /**\n * A control can hold the tab stop unless it is `hidden` or a disabled form\n * control. `aria-disabled` remains navigable per the APG; activation suppression\n * belongs to the control itself or its owning behavior. Native disabledness is\n * read from the `disabled` property, narrowed by an `in` check rather than\n * asserted since `<a>` and `<div role=\"button\">` are legitimate controls that\n * are unaffected by a disabled fieldset. CSS-only visibility cannot be detected\n * headlessly and stays the consumer's responsibility.\n */\n #isNavigable(control: HTMLElement): boolean {\n if (this.#isHidden(control)) return false;\n if (!(\"disabled\" in control)) return true;\n if (control.disabled === true) return false;\n return !inheritsFieldsetDisabled(control);\n }\n\n /**\n * Whether `control`, or anything between it and the toolbar root, is `hidden`.\n *\n * Reading only the control's own attribute lets an invisible control hold the\n * single Tab stop, which takes the *whole* toolbar out of the Tab sequence — an\n * ordinary `hidden` wrapper is enough. The walk stops at the root: a toolbar\n * inside a `hidden` region is already out of the page's Tab order.\n */\n #isHidden(control: HTMLElement): boolean {\n let node: HTMLElement | null = control;\n while (node && node !== this.element) {\n if (node.hasAttribute(\"hidden\")) return true;\n node = node.parentElement;\n }\n return false;\n }\n}\n"]}
@@ -36,7 +36,7 @@ import { Controller } from '@hotwired/stimulus';
36
36
  * stack, so `Escape` dismisses it even when a hover (not focus) triggered it and
37
37
  * focus is elsewhere. The resolver ignores an Escape already consumed by an
38
38
  * inner handler and lets the most recently shown layer own the press, so one
39
- * keypress closes exactly one layer (the shared layered-Escape contract).
39
+ * keypress closes exactly one layer.
40
40
  * - Visibility flips `hidden` and `data-state` (`open`/`closed`); the
41
41
  * `aria-describedby` reference is always preserved.
42
42
  * - Opt-in **dismiss on scroll** (`closeOnScroll`): while shown, scrolling a tracked
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/escape_layer.ts","../../src/utils/safe_timeout.ts","../../src/utils/scroll_dismiss.ts","../../src/controllers/tooltip_controller.ts"],"names":[],"mappings":";;;;;AAuEO,IAAM,WAAA,GAAN,MAAM,YAAA,CAAY;AAAA,EACvB,OAAgB,WAAA,mBAAc,IAAI,OAAA,EAAuC;AAAA,EAEzE,cAAA,GAAkC,IAAA;AAAA;AAAA,EAElC,UAAA,GAAkC,IAAA;AAAA;AAAA,EAElC,OAAA,GAAkC,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,QAAA,CAAS,aAAA,GAA0B,QAAA,EAAU,OAAA,EAAmC;AAC9E,IAAA,IAAA,CAAK,UAAA,EAAW;AAChB,IAAA,IAAI,QAAA,GAAW,YAAA,CAAY,WAAA,CAAY,GAAA,CAAI,aAAa,CAAA;AACxD,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,QAAA,GAAW,aAAY,eAAA,EAAgB;AACvC,MAAA,YAAA,CAAY,WAAA,CAAY,GAAA,CAAI,aAAA,EAAe,QAAQ,CAAA;AACnD,MAAA,aAAA,CAAc,gBAAA,CAAiB,SAAA,EAAW,QAAA,CAAS,SAAS,CAAA;AAAA,IAC9D;AACA,IAAA,QAAA,CAAS,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB,IAAA,IAAA,CAAK,cAAA,GAAiB,aAAA;AACtB,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,SAAA;AAC1B,IAAA,IAAA,CAAK,OAAA,GAAU,QAAQ,MAAA,IAAU,IA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,KAAA,CAAM,IAAA,CAAK,YAAY,CAAA;AACpC,MAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AAAA,IACtB;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,UAAA,GAAsB;AACxB,IAAA,OAAO,IAAA,CAAK,gBAAA,IAAoB,CAAC,IAAA,CAAK,aAAA,CAAc,MAAA;AAAA,EACtD;AACF","file":"tooltip_controller.js","sourcesContent":["/**\n * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest-first half of the\n * shared layered-Escape contract. A keydown that is part of an IME composition\n * (`event.isComposing`) cancels the composition, never a layer, and is ignored\n * here for every layer at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered.\n */\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n stack: EscapeLayer[];\n onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = new WeakMap<Document, EscapeLayerRegistry>();\n\n #ownerDocument: Document | null = null;\n /** Dismissal callback while active; `null` when inactive. */\n #onDismiss: (() => void) | null = null;\n /** Live predicate deciding whether the layer claims a press; `null` = always. */\n #claims: (() => boolean) | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n registry.stack.push(this);\n this.#ownerDocument = ownerDocument;\n this.#onDismiss = options.onDismiss;\n this.#claims = options.claims ?? null;\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return;\n\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (registry) {\n const index = registry.stack.lastIndexOf(this);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n ownerDocument.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(ownerDocument);\n }\n }\n this.#ownerDocument = null;\n this.#onDismiss = null;\n this.#claims = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return false;\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === this;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.#onDismiss?.();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: EscapeLayer[]): EscapeLayer | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.#claims && !layer.#claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","/**\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","/**\n * Invokes `onScroll` when the page — or any scrollable ancestor of `element` —\n * scrolls, returning a cleanup that detaches every listener.\n *\n * `scroll` events do not bubble, and a single capture-phase listener on\n * `window`/`document` is unreliable for descendant scroll containers — so this\n * attaches a `scroll` listener directly to each scroll-parent ancestor (walking\n * `parentElement` and checking `overflow`) plus the window. That mirrors the\n * *intent* of `@floating-ui/dom`'s `autoUpdate` scroll tracking; it is a\n * deliberately simple resolver and does not cross shadow roots. This is precisely\n * the case a consumer cannot cover with `data-action` alone, which is why the\n * surface controllers own it.\n *\n * The listeners are `passive` (the handler never calls `preventDefault`), so they\n * never delay scrolling. Pass the surface's anchor/root so the relevant scroll\n * parents are found even when the floating element is portaled elsewhere.\n */\nexport function observeScrollDismiss(element: Element, onScroll: () => void): () => void {\n const targets: Array<Element | Window> = [...scrollParents(element), window];\n const handler = (): void => onScroll();\n for (const target of targets) {\n target.addEventListener(\"scroll\", handler, { passive: true });\n }\n return () => {\n for (const target of targets) target.removeEventListener(\"scroll\", handler);\n };\n}\n\n/** The scrollable ancestors of `element`, nearest first (window excluded). */\nfunction scrollParents(element: Element): Element[] {\n const parents: Element[] = [];\n let node = element.parentElement;\n while (node) {\n if (isScrollable(node)) parents.push(node);\n node = node.parentElement;\n }\n return parents;\n}\n\n/** Whether `element` is a scroll container (any axis `auto`/`scroll`/`overlay`). */\nfunction isScrollable(element: Element): boolean {\n const style = getComputedStyle(element);\n return /auto|scroll|overlay/.test(style.overflow + style.overflowX + style.overflowY);\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { EscapeLayer } from \"../utils/escape_layer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\nimport { observeScrollDismiss } from \"../utils/scroll_dismiss\";\n\n/**\n * Headless, accessible **tooltip** behavior.\n *\n * Markup contract (identifier: `stimeo--tooltip`):\n * <span data-controller=\"stimeo--tooltip\">\n * <button data-stimeo--tooltip-target=\"trigger\" aria-describedby=\"tip\"\n * data-action=\"mouseenter->stimeo--tooltip#show\n * mouseleave->stimeo--tooltip#hide\n * focusin->stimeo--tooltip#show\n * focusout->stimeo--tooltip#hide\">Save</button>\n * <span id=\"tip\" role=\"tooltip\" data-stimeo--tooltip-target=\"content\"\n * data-action=\"mouseenter->stimeo--tooltip#show\n * mouseleave->stimeo--tooltip#hide\" hidden>…</span>\n * </span>\n *\n * Implements the WAI-ARIA APG **Tooltip** pattern and WCAG 2.2 SC 1.4.13\n * (hoverable / dismissible / persistent). The tooltip never receives focus and\n * holds no interactive content — for that use `stimeo--hover-card` or\n * `stimeo--popover`. The `aria-describedby` association is declared in the\n * consumer's markup; this controller only toggles visibility.\n *\n * @remarks\n * Behavior only — placement is the consumer's CSS (static) or the opt-in\n * `stimeo-ui/positioning` module (dynamic); this controller never imports it.\n *\n * Behavior provided:\n * - Show on `mouseenter`/`focusin`, hide on `mouseleave`/`focusout`, each gated by\n * `showDelay`/`hideDelay` to prevent flicker.\n * - **Hoverable bridge**: binding show/hide on the content too means moving the\n * pointer from trigger into the tooltip cancels the pending hide, so it stays up.\n * - **Persistent across input modalities**: focus and pointer presence are tracked\n * separately, so leaving one does not hide while the other still requires the hint.\n * - **Dismissible**: while shown, the tooltip joins the shared {@link EscapeLayer}\n * stack, so `Escape` dismisses it even when a hover (not focus) triggered it and\n * focus is elsewhere. The resolver ignores an Escape already consumed by an\n * inner handler and lets the most recently shown layer own the press, so one\n * keypress closes exactly one layer (the shared layered-Escape contract).\n * - Visibility flips `hidden` and `data-state` (`open`/`closed`); the\n * `aria-describedby` reference is always preserved.\n * - Opt-in **dismiss on scroll** (`closeOnScroll`): while shown, scrolling a tracked\n * scroll-parent ancestor (or the window) hides the tooltip — the Radix / floating-ui\n * convention, useful for focus-triggered tooltips that a pointer-leave cannot\n * dismiss. Off by default.\n */\nexport class TooltipController extends Controller<HTMLElement> {\n static override targets = [\"trigger\", \"content\"];\n static override values = {\n showDelay: { type: Number, default: 0 },\n hideDelay: { type: Number, default: 0 },\n closeOnScroll: { type: Boolean, default: false },\n };\n static actions = [\"hide\", \"show\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n declare readonly showDelayValue: number;\n declare readonly hideDelayValue: number;\n declare readonly closeOnScrollValue: boolean;\n\n /** Registry whose pending timers are cancelled individually with their guard ids. */\n readonly #timers = new SafeTimeout();\n /** Escape-stack membership while shown; the shared resolver dismisses via it. */\n readonly #escapeLayer = new EscapeLayer();\n /** The id of the currently pending show timer, if any. */\n #pendingShow: number | null = null;\n /** The id of the currently pending hide timer, if any. */\n #pendingHide: number | null = null;\n /** Whether focus or the pointer currently requires the tooltip to persist. */\n #focusActive = false;\n #pointerActive = false;\n /** Cleanup for the dismiss-on-scroll listeners while shown, or `null`. */\n #stopScrollDismiss: (() => void) | null = null;\n\n /** Starts hidden with no stale timer or interaction state from a prior connection. */\n override connect(): void {\n this.#cancelShow();\n this.#cancelHide();\n this.#resetInteractionState();\n this.#conceal();\n }\n\n /** Clears timers, the Escape-stack membership, and scroll listeners so nothing outlives the element. */\n override disconnect(): void {\n this.#cancelShow();\n this.#cancelHide();\n this.#resetInteractionState();\n this.#escapeLayer.deactivate();\n this.#stopScrollDismiss?.();\n this.#stopScrollDismiss = null;\n }\n\n /** Shows after `showDelay`, recording the focus/pointer reason supplied by an action event. */\n show(event?: Event): void {\n this.#activateInteraction(event);\n this.#cancelHide();\n if (this.#isVisible || this.#pendingShow !== null) return;\n if (this.showDelayValue <= 0) {\n this.#reveal();\n return;\n }\n this.#pendingShow = this.#timers.set(() => {\n this.#pendingShow = null;\n this.#reveal();\n }, this.showDelayValue);\n }\n\n /** Hides after `hideDelay` once no focus/pointer reason remains; eventless calls are explicit. */\n hide(event?: Event): void {\n const interactionEnded = this.#deactivateInteraction(event);\n if (interactionEnded && this.#hasActiveInteraction) {\n this.#cancelHide();\n return;\n }\n this.#cancelShow();\n if (!this.#isVisible || this.#pendingHide !== null) return;\n if (this.hideDelayValue <= 0) {\n this.#conceal();\n return;\n }\n this.#pendingHide = this.#timers.set(() => {\n this.#pendingHide = null;\n this.#conceal();\n }, this.hideDelayValue);\n }\n\n /** Reveals the content and joins the Escape stack / starts the scroll watcher. */\n #reveal(): void {\n if (!this.hasContentTarget) return;\n this.contentTarget.hidden = false;\n this.contentTarget.setAttribute(\"data-state\", \"open\");\n // No claims predicate: a shown hover hint is dismissible regardless of\n // where focus sits (WCAG 2.2 SC 1.4.13), so it always claims while shown.\n this.#escapeLayer.activate(document, { onDismiss: () => this.#dismiss() });\n if (this.closeOnScrollValue && !this.#stopScrollDismiss) {\n this.#stopScrollDismiss = observeScrollDismiss(this.element, () => this.#dismiss());\n }\n }\n\n /** Hides the content and leaves the Escape stack / stops the scroll watcher. */\n #conceal(): void {\n // Release the layer and observers first, unconditionally: if the content\n // target was removed from the DOM while shown, an early return would leak\n // the stack entry and the scroll-dismiss listeners.\n this.#escapeLayer.deactivate();\n this.#stopScrollDismiss?.();\n this.#stopScrollDismiss = null;\n if (!this.hasContentTarget) return;\n this.contentTarget.hidden = true;\n this.contentTarget.setAttribute(\"data-state\", \"closed\");\n }\n\n /** Cancels pending timers and conceals immediately (shared Escape / scroll path). */\n #dismiss(): void {\n this.#cancelShow();\n this.#cancelHide();\n this.#conceal();\n }\n\n /** Records the modality whose enter/focus event requires the tooltip to stay visible. */\n #activateInteraction(event?: Event): void {\n if (event?.type === \"mouseenter\") this.#pointerActive = true;\n if (event?.type === \"focusin\") this.#focusActive = true;\n }\n\n /** Clears a modality on leave/blur and reports whether the event represented such a change. */\n #deactivateInteraction(event?: Event): boolean {\n if (event?.type === \"mouseleave\") {\n this.#pointerActive = false;\n return true;\n }\n if (event?.type === \"focusout\") {\n this.#focusActive = false;\n return true;\n }\n return false;\n }\n\n /** Discards interaction reasons at a lifecycle boundary. */\n #resetInteractionState(): void {\n this.#focusActive = false;\n this.#pointerActive = false;\n }\n\n /** Whether focus or pointer presence still requires a persistent tooltip. */\n get #hasActiveInteraction(): boolean {\n return this.#focusActive || this.#pointerActive;\n }\n\n /** Cancels any pending show timer. */\n #cancelShow(): void {\n if (this.#pendingShow !== null) {\n this.#timers.clear(this.#pendingShow);\n this.#pendingShow = null;\n }\n }\n\n /** Cancels any pending hide timer. */\n #cancelHide(): void {\n if (this.#pendingHide !== null) {\n this.#timers.clear(this.#pendingHide);\n this.#pendingHide = null;\n }\n }\n\n /** Whether the tooltip is currently shown. */\n get #isVisible(): boolean {\n return this.hasContentTarget && !this.contentTarget.hidden;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/escape_layer.ts","../../src/utils/safe_timeout.ts","../../src/utils/scroll_dismiss.ts","../../src/controllers/tooltip_controller.ts"],"names":[],"mappings":";;;;;AAuEO,IAAM,WAAA,GAAN,MAAM,YAAA,CAAY;AAAA,EACvB,OAAgB,WAAA,mBAAc,IAAI,OAAA,EAAuC;AAAA,EAEzE,cAAA,GAAkC,IAAA;AAAA;AAAA,EAElC,UAAA,GAAkC,IAAA;AAAA;AAAA,EAElC,OAAA,GAAkC,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,QAAA,CAAS,aAAA,GAA0B,QAAA,EAAU,OAAA,EAAmC;AAC9E,IAAA,IAAA,CAAK,UAAA,EAAW;AAChB,IAAA,IAAI,QAAA,GAAW,YAAA,CAAY,WAAA,CAAY,GAAA,CAAI,aAAa,CAAA;AACxD,IA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,EAGA,IAAI,qBAAA,GAAiC;AACnC,IAAA,OAAO,IAAA,CAAK,gBAAgB,IAAA,CAAK,cAAA;AAAA,EACnC;AAAA;AAAA,EAGA,WAAA,GAAoB;AAClB,IAAA,IAAI,IAAA,CAAK,iBAAiB,IAAA,EAAM;AAC9B,MAAA,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,IAAA,CAAK,YAAY,CAAA;AACpC,MAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AAAA,IACtB;AAAA,EACF;AAAA;AAAA,EAGA,WAAA,GAAoB;AAClB,IAAA,IAAI,IAAA,CAAK,iBAAiB,IAAA,EAAM;AAC9B,MAAA,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,IAAA,CAAK,YAAY,CAAA;AACpC,MAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AAAA,IACtB;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,UAAA,GAAsB;AACxB,IAAA,OAAO,IAAA,CAAK,gBAAA,IAAoB,CAAC,IAAA,CAAK,aAAA,CAAc,MAAA;AAAA,EACtD;AACF","file":"tooltip_controller.js","sourcesContent":["/**\n * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest handler resolves the\n * press. A keydown that is part of an IME composition (`event.isComposing`)\n * cancels the composition, never a layer, and is ignored here for every layer\n * at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered.\n */\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n stack: EscapeLayer[];\n onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = new WeakMap<Document, EscapeLayerRegistry>();\n\n #ownerDocument: Document | null = null;\n /** Dismissal callback while active; `null` when inactive. */\n #onDismiss: (() => void) | null = null;\n /** Live predicate deciding whether the layer claims a press; `null` = always. */\n #claims: (() => boolean) | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n registry.stack.push(this);\n this.#ownerDocument = ownerDocument;\n this.#onDismiss = options.onDismiss;\n this.#claims = options.claims ?? null;\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return;\n\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (registry) {\n const index = registry.stack.lastIndexOf(this);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n ownerDocument.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(ownerDocument);\n }\n }\n this.#ownerDocument = null;\n this.#onDismiss = null;\n this.#claims = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return false;\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === this;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.#onDismiss?.();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: EscapeLayer[]): EscapeLayer | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.#claims && !layer.#claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","/**\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","/**\n * Invokes `onScroll` when the page — or any scrollable ancestor of `element` —\n * scrolls, returning a cleanup that detaches every listener.\n *\n * `scroll` events do not bubble, and a single capture-phase listener on\n * `window`/`document` is unreliable for descendant scroll containers — so this\n * attaches a `scroll` listener directly to each scroll-parent ancestor (walking\n * `parentElement` and checking `overflow`) plus the window. That mirrors the\n * *intent* of `@floating-ui/dom`'s `autoUpdate` scroll tracking; it is a\n * deliberately simple resolver and does not cross shadow roots. This is precisely\n * the case a consumer cannot cover with `data-action` alone, which is why the\n * surface controllers own it.\n *\n * The listeners are `passive` (the handler never calls `preventDefault`), so they\n * never delay scrolling. Pass the surface's anchor/root so the relevant scroll\n * parents are found even when the floating element is portaled elsewhere.\n */\nexport function observeScrollDismiss(element: Element, onScroll: () => void): () => void {\n const targets: Array<Element | Window> = [...scrollParents(element), window];\n const handler = (): void => onScroll();\n for (const target of targets) {\n target.addEventListener(\"scroll\", handler, { passive: true });\n }\n return () => {\n for (const target of targets) target.removeEventListener(\"scroll\", handler);\n };\n}\n\n/** The scrollable ancestors of `element`, nearest first (window excluded). */\nfunction scrollParents(element: Element): Element[] {\n const parents: Element[] = [];\n let node = element.parentElement;\n while (node) {\n if (isScrollable(node)) parents.push(node);\n node = node.parentElement;\n }\n return parents;\n}\n\n/** Whether `element` is a scroll container (any axis `auto`/`scroll`/`overlay`). */\nfunction isScrollable(element: Element): boolean {\n const style = getComputedStyle(element);\n return /auto|scroll|overlay/.test(style.overflow + style.overflowX + style.overflowY);\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { EscapeLayer } from \"../utils/escape_layer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\nimport { observeScrollDismiss } from \"../utils/scroll_dismiss\";\n\n/**\n * Headless, accessible **tooltip** behavior.\n *\n * Markup contract (identifier: `stimeo--tooltip`):\n * <span data-controller=\"stimeo--tooltip\">\n * <button data-stimeo--tooltip-target=\"trigger\" aria-describedby=\"tip\"\n * data-action=\"mouseenter->stimeo--tooltip#show\n * mouseleave->stimeo--tooltip#hide\n * focusin->stimeo--tooltip#show\n * focusout->stimeo--tooltip#hide\">Save</button>\n * <span id=\"tip\" role=\"tooltip\" data-stimeo--tooltip-target=\"content\"\n * data-action=\"mouseenter->stimeo--tooltip#show\n * mouseleave->stimeo--tooltip#hide\" hidden>…</span>\n * </span>\n *\n * Implements the WAI-ARIA APG **Tooltip** pattern and WCAG 2.2 SC 1.4.13\n * (hoverable / dismissible / persistent). The tooltip never receives focus and\n * holds no interactive content — for that use `stimeo--hover-card` or\n * `stimeo--popover`. The `aria-describedby` association is declared in the\n * consumer's markup; this controller only toggles visibility.\n *\n * @remarks\n * Behavior only — placement is the consumer's CSS (static) or the opt-in\n * `stimeo-ui/positioning` module (dynamic); this controller never imports it.\n *\n * Behavior provided:\n * - Show on `mouseenter`/`focusin`, hide on `mouseleave`/`focusout`, each gated by\n * `showDelay`/`hideDelay` to prevent flicker.\n * - **Hoverable bridge**: binding show/hide on the content too means moving the\n * pointer from trigger into the tooltip cancels the pending hide, so it stays up.\n * - **Persistent across input modalities**: focus and pointer presence are tracked\n * separately, so leaving one does not hide while the other still requires the hint.\n * - **Dismissible**: while shown, the tooltip joins the shared {@link EscapeLayer}\n * stack, so `Escape` dismisses it even when a hover (not focus) triggered it and\n * focus is elsewhere. The resolver ignores an Escape already consumed by an\n * inner handler and lets the most recently shown layer own the press, so one\n * keypress closes exactly one layer.\n * - Visibility flips `hidden` and `data-state` (`open`/`closed`); the\n * `aria-describedby` reference is always preserved.\n * - Opt-in **dismiss on scroll** (`closeOnScroll`): while shown, scrolling a tracked\n * scroll-parent ancestor (or the window) hides the tooltip — the Radix / floating-ui\n * convention, useful for focus-triggered tooltips that a pointer-leave cannot\n * dismiss. Off by default.\n */\nexport class TooltipController extends Controller<HTMLElement> {\n static override targets = [\"trigger\", \"content\"];\n static override values = {\n showDelay: { type: Number, default: 0 },\n hideDelay: { type: Number, default: 0 },\n closeOnScroll: { type: Boolean, default: false },\n };\n static actions = [\"hide\", \"show\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n declare readonly showDelayValue: number;\n declare readonly hideDelayValue: number;\n declare readonly closeOnScrollValue: boolean;\n\n /** Registry whose pending timers are cancelled individually with their guard ids. */\n readonly #timers = new SafeTimeout();\n /** Escape-stack membership while shown; the shared resolver dismisses via it. */\n readonly #escapeLayer = new EscapeLayer();\n /** The id of the currently pending show timer, if any. */\n #pendingShow: number | null = null;\n /** The id of the currently pending hide timer, if any. */\n #pendingHide: number | null = null;\n /** Whether focus or the pointer currently requires the tooltip to persist. */\n #focusActive = false;\n #pointerActive = false;\n /** Cleanup for the dismiss-on-scroll listeners while shown, or `null`. */\n #stopScrollDismiss: (() => void) | null = null;\n\n /** Starts hidden with no stale timer or interaction state from a prior connection. */\n override connect(): void {\n this.#cancelShow();\n this.#cancelHide();\n this.#resetInteractionState();\n this.#conceal();\n }\n\n /** Clears timers, the Escape-stack membership, and scroll listeners so nothing outlives the element. */\n override disconnect(): void {\n this.#cancelShow();\n this.#cancelHide();\n this.#resetInteractionState();\n this.#escapeLayer.deactivate();\n this.#stopScrollDismiss?.();\n this.#stopScrollDismiss = null;\n }\n\n /** Shows after `showDelay`, recording the focus/pointer reason supplied by an action event. */\n show(event?: Event): void {\n this.#activateInteraction(event);\n this.#cancelHide();\n if (this.#isVisible || this.#pendingShow !== null) return;\n if (this.showDelayValue <= 0) {\n this.#reveal();\n return;\n }\n this.#pendingShow = this.#timers.set(() => {\n this.#pendingShow = null;\n this.#reveal();\n }, this.showDelayValue);\n }\n\n /** Hides after `hideDelay` once no focus/pointer reason remains; eventless calls are explicit. */\n hide(event?: Event): void {\n const interactionEnded = this.#deactivateInteraction(event);\n if (interactionEnded && this.#hasActiveInteraction) {\n this.#cancelHide();\n return;\n }\n this.#cancelShow();\n if (!this.#isVisible || this.#pendingHide !== null) return;\n if (this.hideDelayValue <= 0) {\n this.#conceal();\n return;\n }\n this.#pendingHide = this.#timers.set(() => {\n this.#pendingHide = null;\n this.#conceal();\n }, this.hideDelayValue);\n }\n\n /** Reveals the content and joins the Escape stack / starts the scroll watcher. */\n #reveal(): void {\n if (!this.hasContentTarget) return;\n this.contentTarget.hidden = false;\n this.contentTarget.setAttribute(\"data-state\", \"open\");\n // No claims predicate: a shown hover hint is dismissible regardless of\n // where focus sits (WCAG 2.2 SC 1.4.13), so it always claims while shown.\n this.#escapeLayer.activate(document, { onDismiss: () => this.#dismiss() });\n if (this.closeOnScrollValue && !this.#stopScrollDismiss) {\n this.#stopScrollDismiss = observeScrollDismiss(this.element, () => this.#dismiss());\n }\n }\n\n /** Hides the content and leaves the Escape stack / stops the scroll watcher. */\n #conceal(): void {\n // Release the layer and observers first, unconditionally: if the content\n // target was removed from the DOM while shown, an early return would leak\n // the stack entry and the scroll-dismiss listeners.\n this.#escapeLayer.deactivate();\n this.#stopScrollDismiss?.();\n this.#stopScrollDismiss = null;\n if (!this.hasContentTarget) return;\n this.contentTarget.hidden = true;\n this.contentTarget.setAttribute(\"data-state\", \"closed\");\n }\n\n /** Cancels pending timers and conceals immediately (shared Escape / scroll path). */\n #dismiss(): void {\n this.#cancelShow();\n this.#cancelHide();\n this.#conceal();\n }\n\n /** Records the modality whose enter/focus event requires the tooltip to stay visible. */\n #activateInteraction(event?: Event): void {\n if (event?.type === \"mouseenter\") this.#pointerActive = true;\n if (event?.type === \"focusin\") this.#focusActive = true;\n }\n\n /** Clears a modality on leave/blur and reports whether the event represented such a change. */\n #deactivateInteraction(event?: Event): boolean {\n if (event?.type === \"mouseleave\") {\n this.#pointerActive = false;\n return true;\n }\n if (event?.type === \"focusout\") {\n this.#focusActive = false;\n return true;\n }\n return false;\n }\n\n /** Discards interaction reasons at a lifecycle boundary. */\n #resetInteractionState(): void {\n this.#focusActive = false;\n this.#pointerActive = false;\n }\n\n /** Whether focus or pointer presence still requires a persistent tooltip. */\n get #hasActiveInteraction(): boolean {\n return this.#focusActive || this.#pointerActive;\n }\n\n /** Cancels any pending show timer. */\n #cancelShow(): void {\n if (this.#pendingShow !== null) {\n this.#timers.clear(this.#pendingShow);\n this.#pendingShow = null;\n }\n }\n\n /** Cancels any pending hide timer. */\n #cancelHide(): void {\n if (this.#pendingHide !== null) {\n this.#timers.clear(this.#pendingHide);\n this.#pendingHide = null;\n }\n }\n\n /** Whether the tooltip is currently shown. */\n get #isVisible(): boolean {\n return this.hasContentTarget && !this.contentTarget.hidden;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/utils/safe_timeout.ts","../../src/utils/transition_completion.ts","../../src/controllers/transition_controller.ts"],"names":[],"mappings":";;;;;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AAA,EAAG,IAAA,CAAK,QAAQ,SAAA,CAAU,GAAA,CAAI,GAAG,MAAM,CAAA;AAAA,EAC7D;AAAA,EAEA,WAAW,KAAA,EAAuB;AAChC,IAAA,MAAM,MAAA,GAAS,KAAA,CAAM,OAAA,CAAQ,QAAQ,CAAA;AACrC,IAAA,IAAI,MAAA,CAAO,SAAS,CAAA,EAAG,IAAA,CAAK,QAAQ,SAAA,CAAU,MAAA,CAAO,GAAG,MAAM,CAAA;AAAA,EAChE;AAAA;AAAA,EAGA,MAAA,GAAe;AACb,IAAA,IAAA,CAAK,OAAA;AAAA,MACH,IAAA,CAAK,UAAA;AAAA,MACL,IAAA,CAAK,cAAA;AAAA,MACL,IAAA,CAAK,YAAA;AAAA,MACL,IAAA,CAAK,UAAA;AAAA,MACL,IAAA,CAAK,cAAA;AAAA,MACL,IAAA,CAAK;AAAA,KACP;AAAA,EACF;AAAA,EAEA,KAAK,QAAA,EAA8B;AACjC,IAAA,IAAI,OAAO,MAAA,CAAO,qBAAA,KAA0B,UAAA,EAAY;AACtD,MAAA,OAAO,MAAA,CAAO,qBAAA,CAAsB,MAAM,QAAA,EAAU,CAAA;AAAA,IACtD;AACA,IAAA,OAAO,MAAA,CAAO,UAAA,CAAW,QAAA,EAAU,CAAC,CAAA;AAAA,EACtC;AAAA,EAEA,WAAW,EAAA,EAAkB;AAC3B,IAAA,IAAI,OAAO,MAAA,CAAO,oBAAA,KAAyB,UAAA,EAAY,MAAA,CAAO,qBAAqB,EAAE,CAAA;AAAA,SAChF,MAAA,CAAO,aAAa,EAAE,CAAA;AAAA,EAC7B;AACF","file":"transition_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 * Each of those controllers used to duplicate the same guarded `matchMedia`\n * read; this one-liner keeps the media query string and the environment guard\n * single-sourced. The preference is intentionally re-read on every call — the\n * controllers check it at each animation/scroll start (WCAG 2.2 **2.3.3**), so\n * flipping the OS setting takes effect immediately without any listener or\n * 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","/**\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 { SafeTimeout } from \"./safe_timeout\";\n\n/** Computed transition fields needed to determine when an element has settled. */\nexport type TransitionStyle = Pick<\n CSSStyleDeclaration,\n \"transitionProperty\" | \"transitionDuration\" | \"transitionDelay\"\n>;\n\n/** Parsed transition property paired with its effective duration and delay. */\ninterface TransitionTiming {\n property: string;\n totalMs: number;\n}\n\n/** Parses a CSS `<time>` into milliseconds, returning `0` for malformed values. */\nfunction timeMs(value: string): number {\n const trimmed = value.trim();\n const amount = Number.parseFloat(trimmed);\n if (!Number.isFinite(amount)) return 0;\n if (trimmed.endsWith(\"ms\")) return amount;\n if (trimmed.endsWith(\"s\")) return amount * 1000;\n return 0;\n}\n\n/** Splits a computed comma-separated CSS list into normalized, non-empty items. */\nfunction cssList(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n/**\n * Pairs transition properties, durations, and delays using CSS list repetition.\n *\n * The `transition-property` list determines the number of transitions. Shorter\n * duration/delay lists repeat, while extra values are ignored. A negative delay\n * shortens the remaining wall-clock time, and a non-positive total is settled.\n */\nfunction transitionTimings(style: TransitionStyle): TransitionTiming[] {\n const properties = cssList(style.transitionProperty);\n const durations = cssList(style.transitionDuration).map(timeMs);\n const delays = cssList(style.transitionDelay).map(timeMs);\n const effectiveProperties =\n properties.length > 0\n ? properties\n : Array.from({ length: Math.max(durations.length, delays.length, 1) }, () => \"all\");\n const effectiveDurations = durations.length > 0 ? durations : [0];\n const effectiveDelays = delays.length > 0 ? delays : [0];\n\n return effectiveProperties\n .filter((property) => property !== \"none\")\n .map((property, index) => ({\n property,\n totalMs: Math.max(\n 0,\n (effectiveDurations[index % effectiveDurations.length] ?? 0) +\n (effectiveDelays[index % effectiveDelays.length] ?? 0),\n ),\n }));\n}\n\n/** Maximum total over already-parsed timings (0 when the list is empty). */\nfunction maxTotalMs(timings: TransitionTiming[]): number {\n return timings.reduce((max, { totalMs }) => Math.max(max, totalMs), 0);\n}\n\n/** Maximum effective transition duration plus delay, in milliseconds. */\nexport function maxTransitionTotalMs(style: TransitionStyle): number {\n return maxTotalMs(transitionTimings(style));\n}\n\n/** Optional tuning for a single {@link TransitionCompletion.wait} call. */\nexport interface TransitionWaitOptions {\n /**\n * Positive wall-clock override (ms) for the bounded fallback, replacing the\n * auto-computed `max + 50ms` timer verbatim. It also keeps the wait armed for\n * a computed 0ms transition (no synchronous completion): the consumer asserts\n * a transition budget that computed styles cannot see. Non-positive and\n * non-finite (`NaN` / `Infinity`) values are ignored.\n */\n timeoutMs?: number;\n}\n\n/**\n * Owns one cancellable wait for an element's CSS transitions to settle.\n *\n * When available, active CSS transitions provide their expanded property names.\n * Tracking those names lets shorthand declarations settle from their longhand\n * terminal events. A terminal event from an interrupted phase is ignored while a\n * replacement transition for the same property is still active. Because that set\n * is sampled when the wait is armed, a property whose transition only starts a\n * frame later would otherwise be settled over; the still-running set is therefore\n * re-read before completing and adopted when it is not yet empty. Without Web\n * Animations data, explicit transition properties retain the declared-property\n * behavior and the ambiguous `transition-property: all` form waits until the\n * computed maximum wall-clock time. A `max + 50ms` timeout is always armed\n * because browsers emit no terminal event when a property never transitions, an\n * ancestor disappears, or rendering is otherwise interrupted; a consumer with\n * better knowledge can replace that fallback via\n * {@link TransitionWaitOptions.timeoutMs}.\n */\nexport class TransitionCompletion {\n readonly #timers = new SafeTimeout();\n #element: HTMLElement | null = null;\n #complete: (() => void) | null = null;\n #pendingProperties: Set<string> | null = null;\n #deadline = 0;\n\n /**\n * Replaces any prior wait and invokes `complete` synchronously for a 0ms\n * transition (including when `getComputedStyle` is unavailable).\n *\n * With a positive `options.timeoutMs` the synchronous fast-path is skipped and\n * the override replaces the auto-computed fallback (see {@link TransitionWaitOptions}).\n */\n wait(element: HTMLElement, complete: () => void, options: TransitionWaitOptions = {}): void {\n this.cancel();\n\n const requested = options.timeoutMs ?? 0;\n const override = Number.isFinite(requested) && requested > 0 ? requested : 0;\n // A non-browser / partial-DOM environment cannot report a computable\n // transition, which is indistinguishable from a 0ms one.\n const timings =\n typeof window.getComputedStyle === \"function\"\n ? transitionTimings(window.getComputedStyle(element))\n : [];\n const maximum = maxTotalMs(timings);\n if (maximum <= 0 && override <= 0) {\n complete();\n return;\n }\n\n this.#element = element;\n this.#complete = complete;\n this.#deadline = Date.now() + maximum;\n const activeProperties = this.#activeTransitionProperties(element);\n this.#pendingProperties =\n activeProperties.size > 0 ? activeProperties : this.#explicitPendingProperties(timings);\n element.addEventListener(\"transitionend\", this.#onTerminal);\n element.addEventListener(\"transitioncancel\", this.#onTerminal);\n this.#timers.set(() => this.#finish(), override > 0 ? override : maximum + 50);\n }\n\n /** Cancels the pending wait without invoking its completion callback. */\n cancel(): void {\n this.#complete = null;\n this.#teardown();\n }\n\n /**\n * Handles terminal events from the observed element only.\n *\n * For explicit property lists, every declared positive-time property must\n * settle. For `all`, no reliable property set exists, so an event can finish\n * only after the computed maximum time; the safety timeout owns the usual path.\n */\n readonly #onTerminal = (event: Event): void => {\n if (event.target !== this.#element) return;\n const transitionEvent = event as TransitionEvent;\n // A pseudo-element's transition is reported with its originating element\n // as `target`; it must not settle the element's own transition.\n if (transitionEvent.pseudoElement) return;\n\n if (this.#pendingProperties) {\n const propertyName = transitionEvent.propertyName;\n const active = this.#activeTransitionProperties(this.#element);\n // An interrupted transition queues its cancel event before the replacement\n // phase starts, but dispatch can happen after the new wait is armed. The\n // replacement is then the active transition for this property, so the stale\n // terminal event must not settle the new phase.\n if (active.has(propertyName)) return;\n if (!this.#pendingProperties.delete(propertyName)) return;\n if (this.#pendingProperties.size > 0) return;\n // The tracked set is an arm-time snapshot, so a transition the phase starts\n // one frame later is absent from it. Re-reading the still-running set before\n // settling adopts those stragglers instead of completing over them; the\n // fallback timer stays armed, so this cannot extend the wait unboundedly.\n if (active.size > 0) {\n this.#pendingProperties = active;\n return;\n }\n this.#finish();\n return;\n }\n\n if (Date.now() >= this.#deadline) this.#finish();\n };\n\n /**\n * Returns active CSS transition properties expanded to the names reported by\n * terminal events. CSS animations and pseudo-element effects are excluded.\n */\n #activeTransitionProperties(element: HTMLElement | null): Set<string> {\n if (!element || typeof element.getAnimations !== \"function\") return new Set();\n\n try {\n const properties = element.getAnimations().flatMap((animation) => {\n if (animation.playState === \"idle\" || animation.playState === \"finished\") return [];\n const effect = animation.effect as KeyframeEffect | null;\n // A pseudo-element effect names the originating element as its target, so\n // `target` alone cannot separate it. Its terminal events are ignored, so\n // tracking its properties would only strand the wait on the fallback.\n if (effect?.pseudoElement) return [];\n const target = effect?.target;\n if (target && target !== element) return [];\n const property = (animation as Partial<CSSTransition>).transitionProperty;\n return typeof property === \"string\" && property.length > 0 ? [property] : [];\n });\n return new Set(properties);\n } catch {\n // Partial DOM implementations can expose getAnimations without supporting\n // it. The declared-property tracker and bounded timer remain safe fallbacks.\n return new Set();\n }\n }\n\n /** Returns explicit positive-time properties, or `null` for the ambiguous `all`. */\n #explicitPendingProperties(timings: TransitionTiming[]): Set<string> | null {\n if (timings.some(({ property }) => property === \"all\")) return null;\n const pending = new Set(\n timings.filter(({ totalMs }) => totalMs > 0).map(({ property }) => property),\n );\n // An empty set is only reachable through a timeout override (a 0ms transition\n // otherwise completes synchronously). With nothing to track, fall back to the\n // deadline rule so any terminal event can settle the wait, exactly like `all`.\n return pending.size > 0 ? pending : null;\n }\n\n /** Completes exactly once, releasing listeners and the fallback before the callback. */\n #finish(): void {\n const complete = this.#complete;\n if (!complete) return;\n this.#complete = null;\n this.#teardown();\n complete();\n }\n\n /** Releases the exact element listeners and timer owned by the current wait. */\n #teardown(): void {\n this.#timers.clearAll();\n this.#element?.removeEventListener(\"transitionend\", this.#onTerminal);\n this.#element?.removeEventListener(\"transitioncancel\", this.#onTerminal);\n this.#element = null;\n this.#pendingProperties = null;\n this.#deadline = 0;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\nimport { TransitionCompletion } from \"../utils/transition_completion\";\n\n/** Splits a space-separated class-list value into individual, non-empty tokens. */\nconst tokensOf = (value: string): string[] => value.split(/\\s+/).filter(Boolean);\n\n/**\n * Headless **enter/leave transition base**: stages CSS classes for showing and hiding\n * an element (the shared substrate other widgets can lean on instead of hand-rolling\n * it). Counterpart to Headless UI `Transition` / Alpine `x-transition` (no APG pattern;\n * honors WCAG 2.2 **2.3.3** via `prefers-reduced-motion` and keeps the visual state in\n * sync with `hidden`).\n *\n * Markup contract (identifier: `stimeo--transition`):\n * <div data-controller=\"stimeo--transition\"\n * data-stimeo--transition-enter-value=\"ease-out duration-200\"\n * data-stimeo--transition-enter-from-value=\"opacity-0\"\n * data-stimeo--transition-enter-to-value=\"opacity-100\"\n * data-stimeo--transition-leave-value=\"ease-in duration-150\"\n * data-stimeo--transition-leave-from-value=\"opacity-100\"\n * data-stimeo--transition-leave-to-value=\"opacity-0\" hidden>…</div>\n *\n * `enter()` unhides the element, applies `enter` + `enterFrom`, then on the next frame\n * swaps `enterFrom` → `enterTo` so the CSS transition runs, and settles to `entered`\n * once the transition completes. `leave()` mirrors it and re-applies `hidden`.\n * `toggle()` reverses the current direction. The element carries `data-transition-state`\n * (`entering` / `entered` / `leaving` / `left`) and `entered` / `left` events fire on\n * completion.\n *\n * @remarks\n * Behavior only — the animation itself is the consumer's CSS; this controls *when* the\n * stage classes are applied. Completion is owned by the shared\n * {@link TransitionCompletion}: every declared transition property must settle\n * (`transitionend` / `transitioncancel`, pseudo-element events excluded) with a\n * `max(duration + delay) + 50ms` bounded fallback, and a computed 0ms transition\n * settles synchronously at the staging frame. A positive `timeout` Value replaces the\n * fallback verbatim and keeps the wait armed even for a computed 0ms transition.\n * Under `prefers-reduced-motion: reduce` it switches instantly (no staging). An\n * interrupting call cancels the in-flight transition and starts the new one. State\n * lives solely in `hidden` / `data-transition-state`, and `connect()` reconciles to a\n * stable state (stripping any half-applied stage classes from a Turbo cache); the\n * terminal-event listeners, rAF, and fallback timer are released on `disconnect()`\n * (Turbo navigation included).\n */\nexport class TransitionController extends Controller<HTMLElement> {\n static override values = {\n enter: { type: String, default: \"\" },\n enterFrom: { type: String, default: \"\" },\n enterTo: { type: String, default: \"\" },\n leave: { type: String, default: \"\" },\n leaveFrom: { type: String, default: \"\" },\n leaveTo: { type: String, default: \"\" },\n timeout: { type: Number, default: 0 },\n };\n static actions = [\"enter\", \"leave\", \"toggle\"] as const;\n static events = [\"entered\", \"left\"] as const;\n\n declare enterValue: string;\n declare enterFromValue: string;\n declare enterToValue: string;\n declare leaveValue: string;\n declare leaveFromValue: string;\n declare leaveToValue: string;\n declare timeoutValue: number;\n\n /** Owns the cancellable completion wait (terminal events + bounded fallback). */\n readonly #transition = new TransitionCompletion();\n #rafId: number | null = null;\n\n override connect(): void {\n // Drop any half-applied stage classes a cache may have captured, then settle the\n // state hook to match the element's current visibility.\n this.#strip();\n this.element.setAttribute(\"data-transition-state\", this.element.hidden ? \"left\" : \"entered\");\n }\n\n override disconnect(): void {\n this.#cancel();\n }\n\n /** Shows the element with the enter transition. */\n enter(): void {\n this.#run(\"enter\");\n }\n\n /** Hides the element with the leave transition. */\n leave(): void {\n this.#run(\"leave\");\n }\n\n /** Reverses the current direction (enter when hidden/leaving, else leave). */\n toggle(): void {\n const state = this.element.getAttribute(\"data-transition-state\");\n if (state === \"entered\" || state === \"entering\") this.leave();\n else this.enter();\n }\n\n #run(kind: \"enter\" | \"leave\"): void {\n this.#cancel();\n const isEnter = kind === \"enter\";\n if (isEnter) this.element.hidden = false;\n this.element.setAttribute(\"data-transition-state\", isEnter ? \"entering\" : \"leaving\");\n\n if (prefersReducedMotion()) {\n this.#finish(kind);\n return;\n }\n\n const base = isEnter ? this.enterValue : this.leaveValue;\n const from = isEnter ? this.enterFromValue : this.leaveFromValue;\n const to = isEnter ? this.enterToValue : this.leaveToValue;\n\n this.#add(base, from);\n this.#rafId = this.#raf(() => {\n this.#rafId = null;\n this.#remove(from);\n this.#add(to);\n // The consumer's `timeout` Value (positive) replaces the auto-computed\n // fallback so an author-declared budget always wins over computed styles.\n this.#transition.wait(this.element, () => this.#finish(kind), {\n timeoutMs: this.timeoutValue,\n });\n });\n }\n\n /** Settles the element into the completed state, clearing the stage classes. */\n #finish(kind: \"enter\" | \"leave\"): void {\n this.#strip();\n if (kind === \"enter\") {\n this.element.setAttribute(\"data-transition-state\", \"entered\");\n this.dispatch(\"entered\", { detail: {} });\n } else {\n this.element.hidden = true;\n this.element.setAttribute(\"data-transition-state\", \"left\");\n this.dispatch(\"left\", { detail: {} });\n }\n }\n\n /** Cancels any in-flight transition (interruption / teardown). */\n #cancel(): void {\n if (this.#rafId !== null) {\n this.#cancelRaf(this.#rafId);\n this.#rafId = null;\n }\n this.#transition.cancel();\n this.#strip();\n }\n\n #add(...lists: string[]): void {\n const tokens = lists.flatMap(tokensOf);\n if (tokens.length > 0) this.element.classList.add(...tokens);\n }\n\n #remove(...lists: string[]): void {\n const tokens = lists.flatMap(tokensOf);\n if (tokens.length > 0) this.element.classList.remove(...tokens);\n }\n\n /** Removes every stage class so no half-applied state lingers. */\n #strip(): void {\n this.#remove(\n this.enterValue,\n this.enterFromValue,\n this.enterToValue,\n this.leaveValue,\n this.leaveFromValue,\n this.leaveToValue,\n );\n }\n\n #raf(callback: () => void): number {\n if (typeof window.requestAnimationFrame === \"function\") {\n return window.requestAnimationFrame(() => callback());\n }\n return window.setTimeout(callback, 0);\n }\n\n #cancelRaf(id: number): void {\n if (typeof window.cancelAnimationFrame === \"function\") window.cancelAnimationFrame(id);\n else window.clearTimeout(id);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/utils/safe_timeout.ts","../../src/utils/transition_completion.ts","../../src/controllers/transition_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;;;ACAA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MA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OAAA;AAAA,MACH,IAAA,CAAK,UAAA;AAAA,MACL,IAAA,CAAK,cAAA;AAAA,MACL,IAAA,CAAK,YAAA;AAAA,MACL,IAAA,CAAK,UAAA;AAAA,MACL,IAAA,CAAK,cAAA;AAAA,MACL,IAAA,CAAK;AAAA,KACP;AAAA,EACF;AAAA,EAEA,KAAK,QAAA,EAA8B;AACjC,IAAA,IAAI,OAAO,MAAA,CAAO,qBAAA,KAA0B,UAAA,EAAY;AACtD,MAAA,OAAO,MAAA,CAAO,qBAAA,CAAsB,MAAM,QAAA,EAAU,CAAA;AAAA,IACtD;AACA,IAAA,OAAO,MAAA,CAAO,UAAA,CAAW,QAAA,EAAU,CAAC,CAAA;AAAA,EACtC;AAAA,EAEA,WAAW,EAAA,EAAkB;AAC3B,IAAA,IAAI,OAAO,MAAA,CAAO,oBAAA,KAAyB,UAAA,EAAY,MAAA,CAAO,qBAAqB,EAAE,CAAA;AAAA,SAChF,MAAA,CAAO,aAAa,EAAE,CAAA;AAAA,EAC7B;AACF","file":"transition_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","/**\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 { SafeTimeout } from \"./safe_timeout\";\n\n/** Computed transition fields needed to determine when an element has settled. */\nexport type TransitionStyle = Pick<\n CSSStyleDeclaration,\n \"transitionProperty\" | \"transitionDuration\" | \"transitionDelay\"\n>;\n\n/** Parsed transition property paired with its effective duration and delay. */\ninterface TransitionTiming {\n property: string;\n totalMs: number;\n}\n\n/** Parses a CSS `<time>` into milliseconds, returning `0` for malformed values. */\nfunction timeMs(value: string): number {\n const trimmed = value.trim();\n const amount = Number.parseFloat(trimmed);\n if (!Number.isFinite(amount)) return 0;\n if (trimmed.endsWith(\"ms\")) return amount;\n if (trimmed.endsWith(\"s\")) return amount * 1000;\n return 0;\n}\n\n/** Splits a computed comma-separated CSS list into normalized, non-empty items. */\nfunction cssList(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n/**\n * Pairs transition properties, durations, and delays using CSS list repetition.\n *\n * The `transition-property` list determines the number of transitions. Shorter\n * duration/delay lists repeat, while extra values are ignored. A negative delay\n * shortens the remaining wall-clock time, and a non-positive total is settled.\n */\nfunction transitionTimings(style: TransitionStyle): TransitionTiming[] {\n const properties = cssList(style.transitionProperty);\n const durations = cssList(style.transitionDuration).map(timeMs);\n const delays = cssList(style.transitionDelay).map(timeMs);\n const effectiveProperties =\n properties.length > 0\n ? properties\n : Array.from({ length: Math.max(durations.length, delays.length, 1) }, () => \"all\");\n const effectiveDurations = durations.length > 0 ? durations : [0];\n const effectiveDelays = delays.length > 0 ? delays : [0];\n\n return effectiveProperties\n .filter((property) => property !== \"none\")\n .map((property, index) => ({\n property,\n totalMs: Math.max(\n 0,\n (effectiveDurations[index % effectiveDurations.length] ?? 0) +\n (effectiveDelays[index % effectiveDelays.length] ?? 0),\n ),\n }));\n}\n\n/** Maximum total over already-parsed timings (0 when the list is empty). */\nfunction maxTotalMs(timings: TransitionTiming[]): number {\n return timings.reduce((max, { totalMs }) => Math.max(max, totalMs), 0);\n}\n\n/** Maximum effective transition duration plus delay, in milliseconds. */\nexport function maxTransitionTotalMs(style: TransitionStyle): number {\n return maxTotalMs(transitionTimings(style));\n}\n\n/** Optional tuning for a single {@link TransitionCompletion.wait} call. */\nexport interface TransitionWaitOptions {\n /**\n * Positive wall-clock override (ms) for the bounded fallback, replacing the\n * auto-computed `max + 50ms` timer verbatim. It also keeps the wait armed for\n * a computed 0ms transition (no synchronous completion): the consumer asserts\n * a transition budget that computed styles cannot see. Non-positive and\n * non-finite (`NaN` / `Infinity`) values are ignored.\n */\n timeoutMs?: number;\n}\n\n/**\n * Owns one cancellable wait for an element's CSS transitions to settle.\n *\n * When available, active CSS transitions provide their expanded property names.\n * Tracking those names lets shorthand declarations settle from their longhand\n * terminal events. A terminal event from an interrupted phase is ignored while a\n * replacement transition for the same property is still active. Because that set\n * is sampled when the wait is armed, a property whose transition only starts a\n * frame later would otherwise be settled over; the still-running set is therefore\n * re-read before completing and adopted when it is not yet empty. Without Web\n * Animations data, explicit transition properties retain the declared-property\n * behavior and the ambiguous `transition-property: all` form waits until the\n * computed maximum wall-clock time. A `max + 50ms` timeout is always armed\n * because browsers emit no terminal event when a property never transitions, an\n * ancestor disappears, or rendering is otherwise interrupted; a consumer with\n * better knowledge can replace that fallback via\n * {@link TransitionWaitOptions.timeoutMs}.\n */\nexport class TransitionCompletion {\n readonly #timers = new SafeTimeout();\n #element: HTMLElement | null = null;\n #complete: (() => void) | null = null;\n #pendingProperties: Set<string> | null = null;\n #deadline = 0;\n\n /**\n * Replaces any prior wait and invokes `complete` synchronously for a 0ms\n * transition (including when `getComputedStyle` is unavailable).\n *\n * With a positive `options.timeoutMs` the synchronous fast-path is skipped and\n * the override replaces the auto-computed fallback (see {@link TransitionWaitOptions}).\n */\n wait(element: HTMLElement, complete: () => void, options: TransitionWaitOptions = {}): void {\n this.cancel();\n\n const requested = options.timeoutMs ?? 0;\n const override = Number.isFinite(requested) && requested > 0 ? requested : 0;\n // A non-browser / partial-DOM environment cannot report a computable\n // transition, which is indistinguishable from a 0ms one.\n const timings =\n typeof window.getComputedStyle === \"function\"\n ? transitionTimings(window.getComputedStyle(element))\n : [];\n const maximum = maxTotalMs(timings);\n if (maximum <= 0 && override <= 0) {\n complete();\n return;\n }\n\n this.#element = element;\n this.#complete = complete;\n this.#deadline = Date.now() + maximum;\n const activeProperties = this.#activeTransitionProperties(element);\n this.#pendingProperties =\n activeProperties.size > 0 ? activeProperties : this.#explicitPendingProperties(timings);\n element.addEventListener(\"transitionend\", this.#onTerminal);\n element.addEventListener(\"transitioncancel\", this.#onTerminal);\n this.#timers.set(() => this.#finish(), override > 0 ? override : maximum + 50);\n }\n\n /** Cancels the pending wait without invoking its completion callback. */\n cancel(): void {\n this.#complete = null;\n this.#teardown();\n }\n\n /**\n * Handles terminal events from the observed element only.\n *\n * For explicit property lists, every declared positive-time property must\n * settle. For `all`, no reliable property set exists, so an event can finish\n * only after the computed maximum time; the safety timeout owns the usual path.\n */\n readonly #onTerminal = (event: Event): void => {\n if (event.target !== this.#element) return;\n const transitionEvent = event as TransitionEvent;\n // A pseudo-element's transition is reported with its originating element\n // as `target`; it must not settle the element's own transition.\n if (transitionEvent.pseudoElement) return;\n\n if (this.#pendingProperties) {\n const propertyName = transitionEvent.propertyName;\n const active = this.#activeTransitionProperties(this.#element);\n // An interrupted transition queues its cancel event before the replacement\n // phase starts, but dispatch can happen after the new wait is armed. The\n // replacement is then the active transition for this property, so the stale\n // terminal event must not settle the new phase.\n if (active.has(propertyName)) return;\n if (!this.#pendingProperties.delete(propertyName)) return;\n if (this.#pendingProperties.size > 0) return;\n // The tracked set is an arm-time snapshot, so a transition the phase starts\n // one frame later is absent from it. Re-reading the still-running set before\n // settling adopts those stragglers instead of completing over them; the\n // fallback timer stays armed, so this cannot extend the wait unboundedly.\n if (active.size > 0) {\n this.#pendingProperties = active;\n return;\n }\n this.#finish();\n return;\n }\n\n if (Date.now() >= this.#deadline) this.#finish();\n };\n\n /**\n * Returns active CSS transition properties expanded to the names reported by\n * terminal events. CSS animations and pseudo-element effects are excluded.\n */\n #activeTransitionProperties(element: HTMLElement | null): Set<string> {\n if (!element || typeof element.getAnimations !== \"function\") return new Set();\n\n try {\n const properties = element.getAnimations().flatMap((animation) => {\n if (animation.playState === \"idle\" || animation.playState === \"finished\") return [];\n const effect = animation.effect as KeyframeEffect | null;\n // A pseudo-element effect names the originating element as its target, so\n // `target` alone cannot separate it. Its terminal events are ignored, so\n // tracking its properties would only strand the wait on the fallback.\n if (effect?.pseudoElement) return [];\n const target = effect?.target;\n if (target && target !== element) return [];\n const property = (animation as Partial<CSSTransition>).transitionProperty;\n return typeof property === \"string\" && property.length > 0 ? [property] : [];\n });\n return new Set(properties);\n } catch {\n // Partial DOM implementations can expose getAnimations without supporting\n // it. The declared-property tracker and bounded timer remain safe fallbacks.\n return new Set();\n }\n }\n\n /** Returns explicit positive-time properties, or `null` for the ambiguous `all`. */\n #explicitPendingProperties(timings: TransitionTiming[]): Set<string> | null {\n if (timings.some(({ property }) => property === \"all\")) return null;\n const pending = new Set(\n timings.filter(({ totalMs }) => totalMs > 0).map(({ property }) => property),\n );\n // An empty set is only reachable through a timeout override (a 0ms transition\n // otherwise completes synchronously). With nothing to track, fall back to the\n // deadline rule so any terminal event can settle the wait, exactly like `all`.\n return pending.size > 0 ? pending : null;\n }\n\n /** Completes exactly once, releasing listeners and the fallback before the callback. */\n #finish(): void {\n const complete = this.#complete;\n if (!complete) return;\n this.#complete = null;\n this.#teardown();\n complete();\n }\n\n /** Releases the exact element listeners and timer owned by the current wait. */\n #teardown(): void {\n this.#timers.clearAll();\n this.#element?.removeEventListener(\"transitionend\", this.#onTerminal);\n this.#element?.removeEventListener(\"transitioncancel\", this.#onTerminal);\n this.#element = null;\n this.#pendingProperties = null;\n this.#deadline = 0;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\nimport { TransitionCompletion } from \"../utils/transition_completion\";\n\n/** Splits a space-separated class-list value into individual, non-empty tokens. */\nconst tokensOf = (value: string): string[] => value.split(/\\s+/).filter(Boolean);\n\n/**\n * Headless **enter/leave transition base**: stages CSS classes for showing and hiding\n * an element (the shared substrate other widgets can lean on instead of hand-rolling\n * it). Counterpart to Headless UI `Transition` / Alpine `x-transition` (no APG pattern;\n * honors WCAG 2.2 **2.3.3** via `prefers-reduced-motion` and keeps the visual state in\n * sync with `hidden`).\n *\n * Markup contract (identifier: `stimeo--transition`):\n * <div data-controller=\"stimeo--transition\"\n * data-stimeo--transition-enter-value=\"ease-out duration-200\"\n * data-stimeo--transition-enter-from-value=\"opacity-0\"\n * data-stimeo--transition-enter-to-value=\"opacity-100\"\n * data-stimeo--transition-leave-value=\"ease-in duration-150\"\n * data-stimeo--transition-leave-from-value=\"opacity-100\"\n * data-stimeo--transition-leave-to-value=\"opacity-0\" hidden>…</div>\n *\n * `enter()` unhides the element, applies `enter` + `enterFrom`, then on the next frame\n * swaps `enterFrom` → `enterTo` so the CSS transition runs, and settles to `entered`\n * once the transition completes. `leave()` mirrors it and re-applies `hidden`.\n * `toggle()` reverses the current direction. The element carries `data-transition-state`\n * (`entering` / `entered` / `leaving` / `left`) and `entered` / `left` events fire on\n * completion.\n *\n * @remarks\n * Behavior only — the animation itself is the consumer's CSS; this controls *when* the\n * stage classes are applied. Completion is owned by the shared\n * {@link TransitionCompletion}: every declared transition property must settle\n * (`transitionend` / `transitioncancel`, pseudo-element events excluded) with a\n * `max(duration + delay) + 50ms` bounded fallback, and a computed 0ms transition\n * settles synchronously at the staging frame. A positive `timeout` Value replaces the\n * fallback verbatim and keeps the wait armed even for a computed 0ms transition.\n * Under `prefers-reduced-motion: reduce` it switches instantly (no staging). An\n * interrupting call cancels the in-flight transition and starts the new one. State\n * lives solely in `hidden` / `data-transition-state`, and `connect()` reconciles to a\n * stable state (stripping any half-applied stage classes from a Turbo cache); the\n * terminal-event listeners, rAF, and fallback timer are released on `disconnect()`\n * (Turbo navigation included).\n */\nexport class TransitionController extends Controller<HTMLElement> {\n static override values = {\n enter: { type: String, default: \"\" },\n enterFrom: { type: String, default: \"\" },\n enterTo: { type: String, default: \"\" },\n leave: { type: String, default: \"\" },\n leaveFrom: { type: String, default: \"\" },\n leaveTo: { type: String, default: \"\" },\n timeout: { type: Number, default: 0 },\n };\n static actions = [\"enter\", \"leave\", \"toggle\"] as const;\n static events = [\"entered\", \"left\"] as const;\n\n declare enterValue: string;\n declare enterFromValue: string;\n declare enterToValue: string;\n declare leaveValue: string;\n declare leaveFromValue: string;\n declare leaveToValue: string;\n declare timeoutValue: number;\n\n /** Owns the cancellable completion wait (terminal events + bounded fallback). */\n readonly #transition = new TransitionCompletion();\n #rafId: number | null = null;\n\n override connect(): void {\n // Drop any half-applied stage classes a cache may have captured, then settle the\n // state hook to match the element's current visibility.\n this.#strip();\n this.element.setAttribute(\"data-transition-state\", this.element.hidden ? \"left\" : \"entered\");\n }\n\n override disconnect(): void {\n this.#cancel();\n }\n\n /** Shows the element with the enter transition. */\n enter(): void {\n this.#run(\"enter\");\n }\n\n /** Hides the element with the leave transition. */\n leave(): void {\n this.#run(\"leave\");\n }\n\n /** Reverses the current direction (enter when hidden/leaving, else leave). */\n toggle(): void {\n const state = this.element.getAttribute(\"data-transition-state\");\n if (state === \"entered\" || state === \"entering\") this.leave();\n else this.enter();\n }\n\n #run(kind: \"enter\" | \"leave\"): void {\n this.#cancel();\n const isEnter = kind === \"enter\";\n if (isEnter) this.element.hidden = false;\n this.element.setAttribute(\"data-transition-state\", isEnter ? \"entering\" : \"leaving\");\n\n if (prefersReducedMotion()) {\n this.#finish(kind);\n return;\n }\n\n const base = isEnter ? this.enterValue : this.leaveValue;\n const from = isEnter ? this.enterFromValue : this.leaveFromValue;\n const to = isEnter ? this.enterToValue : this.leaveToValue;\n\n this.#add(base, from);\n this.#rafId = this.#raf(() => {\n this.#rafId = null;\n this.#remove(from);\n this.#add(to);\n // The consumer's `timeout` Value (positive) replaces the auto-computed\n // fallback so an author-declared budget always wins over computed styles.\n this.#transition.wait(this.element, () => this.#finish(kind), {\n timeoutMs: this.timeoutValue,\n });\n });\n }\n\n /** Settles the element into the completed state, clearing the stage classes. */\n #finish(kind: \"enter\" | \"leave\"): void {\n this.#strip();\n if (kind === \"enter\") {\n this.element.setAttribute(\"data-transition-state\", \"entered\");\n this.dispatch(\"entered\", { detail: {} });\n } else {\n this.element.hidden = true;\n this.element.setAttribute(\"data-transition-state\", \"left\");\n this.dispatch(\"left\", { detail: {} });\n }\n }\n\n /** Cancels any in-flight transition (interruption / teardown). */\n #cancel(): void {\n if (this.#rafId !== null) {\n this.#cancelRaf(this.#rafId);\n this.#rafId = null;\n }\n this.#transition.cancel();\n this.#strip();\n }\n\n #add(...lists: string[]): void {\n const tokens = lists.flatMap(tokensOf);\n if (tokens.length > 0) this.element.classList.add(...tokens);\n }\n\n #remove(...lists: string[]): void {\n const tokens = lists.flatMap(tokensOf);\n if (tokens.length > 0) this.element.classList.remove(...tokens);\n }\n\n /** Removes every stage class so no half-applied state lingers. */\n #strip(): void {\n this.#remove(\n this.enterValue,\n this.enterFromValue,\n this.enterToValue,\n this.leaveValue,\n this.leaveFromValue,\n this.leaveToValue,\n );\n }\n\n #raf(callback: () => void): number {\n if (typeof window.requestAnimationFrame === \"function\") {\n return window.requestAnimationFrame(() => callback());\n }\n return window.setTimeout(callback, 0);\n }\n\n #cancelRaf(id: number): void {\n if (typeof window.cancelAnimationFrame === \"function\") window.cancelAnimationFrame(id);\n else window.clearTimeout(id);\n }\n}\n"]}
@@ -10,6 +10,8 @@ import { Controller } from '@hotwired/stimulus';
10
10
  * data-action="keydown->stimeo--tree-view#onKeydown
11
11
  * click->stimeo--tree-view#onClick">
12
12
  * <span>src</span>
13
+ * <button type="button" tabindex="-1" aria-hidden="true"
14
+ * data-action="click->stimeo--tree-view#toggle"></button>
13
15
  * <ul role="group" data-stimeo--tree-view-target="group" hidden>
14
16
  * <li role="treeitem" aria-selected="false" tabindex="-1"
15
17
  * data-stimeo--tree-view-target="item" data-action="…">…</li>
@@ -24,31 +26,110 @@ import { Controller } from '@hotwired/stimulus';
24
26
  *
25
27
  * Behavior provided:
26
28
  * - `ArrowDown`/`ArrowUp` move between visible items; `Home`/`End` jump to the
27
- * first / last visible item; printable characters typeahead by label prefix.
29
+ * first / last visible item; printable characters typeahead by label prefix
30
+ * (`aria-label` first, else the item's own text), with a repeated character
31
+ * cycling through the items that start with it.
28
32
  * - `ArrowRight` expands a collapsed parent or steps into its first child;
29
33
  * `ArrowLeft` collapses an expanded parent or steps to the parent item.
30
- * - `Enter`/`Space`/click select the item (single selection via `aria-selected`).
34
+ * - `Enter`/`Space`/click select the item (single selection via `aria-selected`);
35
+ * an `aria-disabled="true"` item stays focusable but cannot be selected.
31
36
  * - `aria-expanded` and each child `group`'s `hidden` stay in sync, dispatching
32
37
  * `stimeo--tree-view:toggle`; selection dispatches `stimeo--tree-view:select`.
38
+ * - The optional `toggle` action expands / collapses the nearest item, so a
39
+ * chevron gives pointer users the reach that `ArrowRight` gives the keyboard.
40
+ *
41
+ * Contract notes:
42
+ * - A child container is resolved by `role="group"`, not by the target: the
43
+ * `group` target is what `stimeo check`'s accessibility rule anchors on, which
44
+ * is why the contract still declares it.
45
+ * - Nested interactive controls ({@link NESTED_INTERACTIVE}) and IME composition
46
+ * keys are left alone; a click on a child `group`'s own box (its indentation
47
+ * band) selects nothing rather than the parent row.
48
+ * - A key a descendant already consumed (`event.defaultPrevented`) is yielded,
49
+ * so a composed widget inside a row never causes a double move.
50
+ *
51
+ * Consumer contract — the item host:
52
+ * - **Host `role="treeitem"` on a non-interactive element** (`li`, `div`), never
53
+ * on {@link NESTED_INTERACTIVE}. APG's *Navigation Treeview* does host it on a
54
+ * link, but that variant activates on `Enter`, which this pattern has already
55
+ * spent on selection; a link host is therefore out of contract and would need
56
+ * `Enter` / click / `select` redefined first.
57
+ * - An out-of-contract host makes `onKeydown` and `onClick` stand down
58
+ * **entirely** — no movement, no selection, no `select` — rather than respond
59
+ * partially. `stimeo check` cannot flag it: the rule schema states which
60
+ * attributes are required and cannot forbid an element shape.
61
+ *
62
+ * Consumer contract — controls nested inside a row:
63
+ * - Keep them out of the Tab sequence (`tabindex="-1"`); the tree is one Tab
64
+ * stop and writes `tabindex` on nothing but its own item targets.
65
+ * - Moving focus *into* a control (to start an inline rename) is the consumer's
66
+ * call — the tree never focuses one.
67
+ * - When the edit or action ends, focus the `treeitem` itself. The roving
68
+ * position never moved, so that alone restores the keyboard path.
69
+ * - The tree consumes none of the control's events, by two mechanisms:
70
+ * {@link NESTED_INTERACTIVE} names controls by *element shape*, the
71
+ * `defaultPrevented` yield covers widgets no selector can name.
33
72
  */
34
73
  declare class TreeViewController extends Controller<HTMLElement> {
35
74
  #private;
36
75
  static targets: string[];
37
- static actions: readonly ["onClick", "onKeydown"];
76
+ static actions: readonly ["onClick", "onKeydown", "toggle"];
38
77
  static events: readonly ["select", "toggle"];
39
78
  readonly itemTargets: HTMLElement[];
40
- /** Establishes the single tab stop (keeps an existing one, else the first). */
79
+ /**
80
+ * Reconciles authored expansion state and establishes the single tab stop.
81
+ * Idempotent, so a Turbo cache restore / morph re-runs it safely (re-adding
82
+ * the same listener reference is a no-op per the DOM spec).
83
+ */
41
84
  connect(): void;
42
- /** Clears the pending typeahead-reset timer. */
85
+ /** Detaches the focus trackers, drops the typeahead buffer and its timer. */
43
86
  disconnect(): void;
87
+ /**
88
+ * Re-normalizes the tab stop when a `treeitem` is added at runtime, so an
89
+ * appended item carrying `tabindex="0"` cannot turn the tree into two Tab
90
+ * stops. Skipped before `connect()`: Stimulus registers the initial targets
91
+ * first, and `connect()` owns the initial tab-stop policy.
92
+ */
93
+ itemTargetConnected(): void;
94
+ /**
95
+ * Restores the roving invariants when a `treeitem` leaves at runtime — a Turbo
96
+ * Stream `remove`, a morph, or plain DOM surgery. The mirror of
97
+ * {@link TreeViewController.itemTargetConnected}: without it, removing the row
98
+ * that held `tabindex="0"` leaves every survivor at `-1`, i.e. a tree with
99
+ * **no** Tab stop, and drops DOM focus to `<body>` when the removed subtree
100
+ * held it.
101
+ *
102
+ * The replacement is the nearest surviving *visible* item in the pre-removal
103
+ * order — the one after the gap, else the one before it — which is the row
104
+ * `ArrowDown` would have reached. Removing a non-active item changes nothing.
105
+ * When no visible item survives, a tree with zero Tab stops is the correct end
106
+ * state.
107
+ *
108
+ * Focus is only *restored*, never *stolen*: DOM focus moves solely when it was
109
+ * inside the removed subtree and the document has nowhere left to put it.
110
+ */
111
+ itemTargetDisconnected(item: HTMLElement): void;
44
112
  /**
45
113
  * Routes tree keyboard interaction. Because `treeitem`s nest, only the handler
46
114
  * on the nearest item to the event target acts; the same keydown bubbling to an
47
- * ancestor item's handler is ignored to avoid double moves / selections.
115
+ * ancestor item's handler is ignored to avoid double moves / selections. Keys
116
+ * from a nested interactive control (or an IME composition) are left untouched.
48
117
  */
49
118
  onKeydown(event: KeyboardEvent): void;
50
119
  /** Selects the clicked item (nearest to the target only). */
51
120
  onClick(event: Event): void;
121
+ /**
122
+ * Expands or collapses the `treeitem` nearest to the event target. Optional:
123
+ * wire it on a chevron control so pointer users can reach child nodes, which
124
+ * otherwise only `ArrowRight` / `ArrowLeft` can do. A leaf item is a no-op.
125
+ *
126
+ * The toggled row then takes focus and the tab stop, matching what the keyboard
127
+ * path guarantees. Without it, a browser that focuses buttons on mousedown leaves
128
+ * focus on the clicked chevron: arrows would stop working until focus returns to a
129
+ * row, and a decorative `aria-hidden` chevron would hold focus. The synchronous
130
+ * `stimeo--tree-view:toggle` event is observed before this final focus hand-off.
131
+ */
132
+ toggle(event: Event): void;
52
133
  }
53
134
 
54
135
  export { TreeViewController };