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
@@ -2,6 +2,12 @@ import { Controller } from '@hotwired/stimulus';
2
2
 
3
3
  // src/controllers/context_menu_controller.ts
4
4
 
5
+ // src/utils/arrow_step.ts
6
+ function isReservedArrowChord(event, allow = []) {
7
+ if (!event.key.startsWith("Arrow")) return false;
8
+ return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
9
+ }
10
+
5
11
  // src/utils/escape_layer.ts
6
12
  function claimsWhileFocusWithin(element) {
7
13
  return () => {
@@ -156,16 +162,16 @@ var ContextMenuController = class extends Controller {
156
162
  connect() {
157
163
  this.#closeMenu();
158
164
  this.element.addEventListener("click", this.#onItemClickCapture, true);
159
- document.addEventListener("click", this.#onOutsidePointer);
160
- document.addEventListener("contextmenu", this.#onOutsidePointer);
165
+ document.addEventListener("click", this.#onOutsidePointer, true);
166
+ document.addEventListener("contextmenu", this.#onOutsidePointer, true);
161
167
  }
162
168
  /** Releases the listeners, stack membership, and pending Tab-close task. */
163
169
  disconnect() {
164
170
  this.#timers.clearAll();
165
171
  this.#escapeLayer.deactivate();
166
172
  this.element.removeEventListener("click", this.#onItemClickCapture, true);
167
- document.removeEventListener("click", this.#onOutsidePointer);
168
- document.removeEventListener("contextmenu", this.#onOutsidePointer);
173
+ document.removeEventListener("click", this.#onOutsidePointer, true);
174
+ document.removeEventListener("contextmenu", this.#onOutsidePointer, true);
169
175
  }
170
176
  /**
171
177
  * Opens the menu from a `contextmenu` event: suppresses the native menu and
@@ -177,6 +183,7 @@ var ContextMenuController = class extends Controller {
177
183
  }
178
184
  /** Keyboard entry on the region: `Shift+F10` / `ContextMenu` open at center. */
179
185
  onRegionKeydown(event) {
186
+ if (event.defaultPrevented) return;
180
187
  const isContextKey = event.key === "ContextMenu" || event.key === "F10" && event.shiftKey;
181
188
  if (!isContextKey) return;
182
189
  event.preventDefault();
@@ -185,6 +192,8 @@ var ContextMenuController = class extends Controller {
185
192
  }
186
193
  /** Roving focus and closing keys inside the menu. */
187
194
  onItemKeydown(event) {
195
+ if (event.defaultPrevented) return;
196
+ if (isReservedArrowChord(event)) return;
188
197
  const items = this.#navigableItems;
189
198
  const currentIndex = items.indexOf(event.currentTarget);
190
199
  switch (event.key) {
@@ -247,7 +256,13 @@ var ContextMenuController = class extends Controller {
247
256
  this.#closeMenu();
248
257
  if (this.hasRegionTarget) this.regionTarget.focus();
249
258
  }
250
- /** Closes when a click or context-menu invocation lands outside this instance. */
259
+ /**
260
+ * Closes when a click or context-menu invocation lands outside this instance.
261
+ * Both subscriptions observe in the capture phase, so the target is judged
262
+ * against the tree the user actually pressed even when a consumer handler
263
+ * detaches it, and application code that stops bubbling cannot leave the menu
264
+ * open.
265
+ */
251
266
  #onOutsidePointer = (event) => {
252
267
  if (this.#isOpen && !this.element.contains(event.target)) this.#closeMenu();
253
268
  };
@@ -265,18 +280,25 @@ var ContextMenuController = class extends Controller {
265
280
  event.preventDefault();
266
281
  event.stopImmediatePropagation();
267
282
  };
268
- /** Menu items eligible for roving focus (excludes disabled / hidden). */
283
+ /** Menu items eligible for roving focus (excludes hidden / natively disabled). */
269
284
  get #navigableItems() {
270
285
  return this.itemTargets.filter((item) => this.#isNavigable(item));
271
286
  }
272
287
  /**
273
- * An item can take roving focus unless it is `hidden`, `aria-disabled="true"`,
274
- * or a natively `disabled` form control. CSS-only visibility is not detectable
275
- * here and is the consumer's responsibility.
288
+ * An item can take roving focus unless it is `hidden` or a natively `disabled`
289
+ * form control. CSS-only visibility is not detectable here and is the
290
+ * consumer's responsibility.
291
+ *
292
+ * **`aria-disabled="true"` stays reachable.** APG separates the two attributes
293
+ * by intent: `disabled` is for controls whose existence can be inferred from a
294
+ * neighbour (a greyed Next next to a Prev), while `aria-disabled` marks a
295
+ * control that must stay *discoverable* — and it names menu items as the
296
+ * example. Skipping it would hide the command's existence from a keyboard user
297
+ * entirely. Activation is suppressed separately, so the item announces itself
298
+ * and does nothing.
276
299
  */
277
300
  #isNavigable(item) {
278
301
  if (item.hasAttribute("hidden")) return false;
279
- if (item.getAttribute("aria-disabled") === "true") return false;
280
302
  return !item.disabled;
281
303
  }
282
304
  /** Whether the menu is currently visible. */
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/escape_layer.ts","../../src/utils/safe_timeout.ts","../../src/controllers/context_menu_controller.ts"],"names":[],"mappings":";;;;;AAgEO,SAAS,uBAAuB,OAAA,EAAiC;AACtE,EAAA,OAAO,MAAM;AACX,IAAA,MAAM,MAAA,GAAS,QAAQ,aAAA,CAAc,aAAA;AACrC,IAAA,OAAO,MAAA,KAAW,QAAQ,MAAA,KAAW,OAAA,CAAQ,cAAc,IAAA,IAAQ,OAAA,CAAQ,SAAS,MAAM,CAAA;AAAA,EAC5F,CAAA;AACF;AAEO,IAAM,WAAA,GAAN,MAAM,YAAA,CAAY;AAAA,EACvB,OAAgB,WAAA,mBAAc,IAAI,OAAA,EAAuC;AAAA,EAEzE,cAAA,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,EAA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AAAA;AAAA;AAAA,EAOA,aAAa,IAAA,EAAkC;AAC7C,IAAA,IAAI,IAAA,CAAK,YAAA,CAAa,QAAQ,CAAA,EAAG,OAAO,KAAA;AACxC,IAAA,IAAI,IAAA,CAAK,YAAA,CAAa,eAAe,CAAA,KAAM,QAAQ,OAAO,KAAA;AAC1D,IAAA,OAAO,CAAC,IAAA,CAAK,QAAA;AAAA,EACf;AAAA;AAAA,EAGA,IAAI,OAAA,GAAmB;AACrB,IAAA,OAAO,IAAA,CAAK,aAAA,IAAiB,CAAC,IAAA,CAAK,UAAA,CAAW,MAAA;AAAA,EAChD;AACF","file":"context_menu_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","import { Controller } from \"@hotwired/stimulus\";\nimport { claimsWhileFocusWithin, EscapeLayer } from \"../utils/escape_layer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless, accessible **context menu** behavior.\n *\n * Markup contract (identifier: `stimeo--context-menu`):\n * <div data-controller=\"stimeo--context-menu\">\n * <div data-stimeo--context-menu-target=\"region\" tabindex=\"0\"\n * aria-haspopup=\"menu\" aria-controls=\"ctx\"\n * data-action=\"contextmenu->stimeo--context-menu#open\n * keydown->stimeo--context-menu#onRegionKeydown\">…</div>\n * <ul id=\"ctx\" role=\"menu\" data-stimeo--context-menu-target=\"menu\" hidden>\n * <li role=\"none\">\n * <button role=\"menuitem\" tabindex=\"-1\"\n * data-stimeo--context-menu-target=\"item\"\n * data-action=\"click->stimeo--context-menu#activate\n * keydown->stimeo--context-menu#onItemKeydown\">…</button>\n * </li>\n * </ul>\n * </div>\n *\n * Implements the WAI-ARIA APG **Menu** pattern; the only differences from\n * `stimeo--menu` are the *trigger* (a `contextmenu` event or `Shift+F10` /\n * `ContextMenu` key, not a button click) and that the menu is shown at the\n * pointer coordinate.\n *\n * @remarks\n * Behavior only — the controller reflects the click coordinate as the CSS custom\n * properties `--stimeo-context-menu-x` / `--stimeo-context-menu-y` on the menu\n * so the consumer's CSS can place it (works standalone, no positioning module\n * required). Viewport-edge flip/shift is delegated to the opt-in\n * `stimeo-ui/positioning` module, which this controller never imports.\n *\n * Open state is exposed on the region as `data-state` (`open`/`closed`) — a CSS\n * hook, not an ARIA one. `aria-expanded` is deliberately *not* set on the region\n * because it is a generic container, not a role that supports that state (doing so\n * is an ARIA violation); the region's static `aria-haspopup=\"menu\"` advertises the\n * popup, and assistive tech perceives the open state when focus moves into the\n * `role=\"menu\"`.\n *\n * Behavior provided:\n * - `contextmenu` on the region suppresses the browser menu and opens this one at\n * the pointer; `Shift+F10` / `ContextMenu` opens it at the region's center.\n * - On open, focus moves to the first item; the region's `data-state` syncs.\n * - Roving focus inside the menu: `ArrowUp`/`ArrowDown` (wrapping), `Home`/`End`.\n * - Activating an enabled item (click / native `Enter`/`Space` on the button)\n * closes the menu and restores focus to the region. `aria-disabled` activation\n * is blocked before consumer click handlers run.\n * - `Escape` closes and restores focus to the region. While open the menu is a\n * layer on the shared {@link EscapeLayer} stack; it claims a press only while\n * focus is inside the controller or fell to the body, so one keypress closes\n * exactly one layer (the shared layered-Escape contract). `Tab` lets the\n * browser move focus first, then closes on the next task. An outside click or\n * context-menu invocation closes without stealing focus from its destination.\n *\n * Roving focus skips items that are not navigable — `hidden`, natively\n * `disabled`, or `aria-disabled=\"true\"` — so the keyboard never lands focus on an\n * inert command (matching `stimeo--menu` / `stimeo--command-palette`).\n */\nexport class ContextMenuController extends Controller<HTMLElement> {\n static override targets = [\"region\", \"menu\", \"item\"];\n static actions = [\"activate\", \"onItemKeydown\", \"onRegionKeydown\", \"open\"] as const;\n\n declare readonly regionTarget: HTMLElement;\n declare readonly menuTarget: HTMLElement;\n declare readonly itemTargets: HTMLButtonElement[];\n declare readonly hasRegionTarget: boolean;\n declare readonly hasMenuTarget: boolean;\n\n readonly #timers = new SafeTimeout();\n\n /** Escape-stack membership while open; the shared resolver dismisses via it. */\n readonly #escapeLayer = new EscapeLayer();\n\n /** Starts closed and registers delegated activation and outside-pointer listeners. */\n override connect(): void {\n this.#closeMenu();\n this.element.addEventListener(\"click\", this.#onItemClickCapture, true);\n document.addEventListener(\"click\", this.#onOutsidePointer);\n document.addEventListener(\"contextmenu\", this.#onOutsidePointer);\n }\n\n /** Releases the listeners, stack membership, and pending Tab-close task. */\n override disconnect(): void {\n this.#timers.clearAll();\n this.#escapeLayer.deactivate();\n this.element.removeEventListener(\"click\", this.#onItemClickCapture, true);\n document.removeEventListener(\"click\", this.#onOutsidePointer);\n document.removeEventListener(\"contextmenu\", this.#onOutsidePointer);\n }\n\n /**\n * Opens the menu from a `contextmenu` event: suppresses the native menu and\n * places this one at the pointer coordinate.\n */\n open(event: MouseEvent): void {\n event.preventDefault();\n this.#openAt(event.clientX, event.clientY);\n }\n\n /** Keyboard entry on the region: `Shift+F10` / `ContextMenu` open at center. */\n onRegionKeydown(event: KeyboardEvent): void {\n const isContextKey = event.key === \"ContextMenu\" || (event.key === \"F10\" && event.shiftKey);\n if (!isContextKey) return;\n event.preventDefault();\n const rect = this.hasRegionTarget\n ? this.regionTarget.getBoundingClientRect()\n : { left: 0, top: 0, width: 0, height: 0 };\n this.#openAt(rect.left + rect.width / 2, rect.top + rect.height / 2);\n }\n\n /** Roving focus and closing keys inside the menu. */\n onItemKeydown(event: KeyboardEvent): void {\n const items = this.#navigableItems;\n const currentIndex = items.indexOf(event.currentTarget as HTMLButtonElement);\n\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n if (items.length > 0) {\n const nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % items.length;\n items[nextIndex]?.focus();\n }\n break;\n case \"ArrowUp\":\n event.preventDefault();\n if (items.length > 0) {\n const previousIndex = currentIndex < 0 ? items.length - 1 : currentIndex - 1;\n items[(previousIndex + items.length) % items.length]?.focus();\n }\n break;\n case \"Home\":\n event.preventDefault();\n items[0]?.focus();\n break;\n case \"End\":\n event.preventDefault();\n items[items.length - 1]?.focus();\n break;\n case \"Tab\":\n // Closing synchronously removes the focused item before the browser's\n // default Tab action, which can restart traversal at the document head.\n this.#timers.clearAll();\n this.#timers.set(() => this.#closeMenu(), 0);\n break;\n default:\n break;\n }\n }\n\n /** Closes after an item is activated and restores focus to the region. */\n activate(): void {\n this.#closeAndRestore();\n }\n\n /** Opens the menu at viewport coordinates `(x, y)` and focuses the first item. */\n #openAt(x: number, y: number): void {\n if (!this.hasMenuTarget) return;\n this.#timers.clearAll();\n this.#escapeLayer.activate(document, {\n onDismiss: () => this.#closeAndRestore(),\n claims: claimsWhileFocusWithin(this.element),\n });\n this.menuTarget.style.setProperty(\"--stimeo-context-menu-x\", `${x}px`);\n this.menuTarget.style.setProperty(\"--stimeo-context-menu-y\", `${y}px`);\n this.menuTarget.hidden = false;\n if (this.hasRegionTarget) this.regionTarget.setAttribute(\"data-state\", \"open\");\n this.#navigableItems[0]?.focus();\n }\n\n /** Hides the menu and reflects the collapsed state on the region. */\n #closeMenu(): void {\n this.#timers.clearAll();\n this.#escapeLayer.deactivate();\n if (!this.hasMenuTarget) return;\n this.menuTarget.hidden = true;\n if (this.hasRegionTarget) this.regionTarget.setAttribute(\"data-state\", \"closed\");\n }\n\n /** Closes the menu and returns focus to the region (Escape / activation). */\n #closeAndRestore(): void {\n this.#closeMenu();\n if (this.hasRegionTarget) this.regionTarget.focus();\n }\n\n /** Closes when a click or context-menu invocation lands outside this instance. */\n readonly #onOutsidePointer = (event: MouseEvent): void => {\n if (this.#isOpen && !this.element.contains(event.target as Node)) this.#closeMenu();\n };\n\n /**\n * Captures clicks so `aria-disabled` commands cannot reach consumer handlers.\n * Native Enter/Space activation also synthesizes a click and is blocked here.\n */\n readonly #onItemClickCapture = (event: MouseEvent): void => {\n const target = event.target;\n if (!(target instanceof Node)) return;\n const disabled = this.itemTargets.some(\n (item) => item.getAttribute(\"aria-disabled\") === \"true\" && item.contains(target),\n );\n if (!disabled) return;\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n\n /** Menu items eligible for roving focus (excludes disabled / hidden). */\n get #navigableItems(): HTMLButtonElement[] {\n return this.itemTargets.filter((item) => this.#isNavigable(item));\n }\n\n /**\n * An item can take roving focus unless it is `hidden`, `aria-disabled=\"true\"`,\n * or a natively `disabled` form control. CSS-only visibility is not detectable\n * here and is the consumer's responsibility.\n */\n #isNavigable(item: HTMLButtonElement): boolean {\n if (item.hasAttribute(\"hidden\")) return false;\n if (item.getAttribute(\"aria-disabled\") === \"true\") return false;\n return !item.disabled;\n }\n\n /** Whether the menu is currently visible. */\n get #isOpen(): boolean {\n return this.hasMenuTarget && !this.menuTarget.hidden;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/arrow_step.ts","../../src/utils/escape_layer.ts","../../src/utils/safe_timeout.ts","../../src/controllers/context_menu_controller.ts"],"names":[],"mappings":";;;;;AA+FO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,KACvC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,IACvC,KAAA,CAAM,QAAA,IAAY,CAAC,KAAA,CAAM,QAAA,CAAS,OAAO,CAAA;AAE9C;;;AC1CO,SAAS,uBAAuB,OAAA,EAAiC;AACtE,EAAA,OAAO,MAAM;AACX,IAAA,MAAM,MAAA,GAAS,QAAQ,aAAA,CAAc,aAAA;AACrC,IAAA,OAAO,MAAA,KAAW,QAAQ,MAAA,KAAW,OAAA,CAAQ,cAAc,IAAA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AChD;AACF","file":"context_menu_controller.js","sourcesContent":["import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","/**\n * 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","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { claimsWhileFocusWithin, EscapeLayer } from \"../utils/escape_layer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless, accessible **context menu** behavior.\n *\n * Markup contract (identifier: `stimeo--context-menu`):\n * <div data-controller=\"stimeo--context-menu\">\n * <div data-stimeo--context-menu-target=\"region\" tabindex=\"0\"\n * aria-haspopup=\"menu\" aria-controls=\"ctx\"\n * data-action=\"contextmenu->stimeo--context-menu#open\n * keydown->stimeo--context-menu#onRegionKeydown\">…</div>\n * <ul id=\"ctx\" role=\"menu\" data-stimeo--context-menu-target=\"menu\" hidden>\n * <li role=\"none\">\n * <button role=\"menuitem\" tabindex=\"-1\"\n * data-stimeo--context-menu-target=\"item\"\n * data-action=\"click->stimeo--context-menu#activate\n * keydown->stimeo--context-menu#onItemKeydown\">…</button>\n * </li>\n * </ul>\n * </div>\n *\n * Implements the WAI-ARIA APG **Menu** pattern; the only differences from\n * `stimeo--menu` are the *trigger* (a `contextmenu` event or `Shift+F10` /\n * `ContextMenu` key, not a button click) and that the menu is shown at the\n * pointer coordinate.\n *\n * @remarks\n * Behavior only — the controller reflects the click coordinate as the CSS custom\n * properties `--stimeo-context-menu-x` / `--stimeo-context-menu-y` on the menu\n * so the consumer's CSS can place it (works standalone, no positioning module\n * required). Viewport-edge flip/shift is delegated to the opt-in\n * `stimeo-ui/positioning` module, which this controller never imports.\n *\n * Open state is exposed on the region as `data-state` (`open`/`closed`) — a CSS\n * hook, not an ARIA one. `aria-expanded` is deliberately *not* set on the region\n * because it is a generic container, not a role that supports that state (doing so\n * is an ARIA violation); the region's static `aria-haspopup=\"menu\"` advertises the\n * popup, and assistive tech perceives the open state when focus moves into the\n * `role=\"menu\"`.\n *\n * Behavior provided:\n * - `contextmenu` on the region suppresses the browser menu and opens this one at\n * the pointer; `Shift+F10` / `ContextMenu` opens it at the region's center.\n * - On open, focus moves to the first item; the region's `data-state` syncs.\n * - Roving focus inside the menu: `ArrowUp`/`ArrowDown` (wrapping), `Home`/`End`.\n * - Activating an enabled item (click / native `Enter`/`Space` on the button)\n * closes the menu and restores focus to the region. `aria-disabled` activation\n * is blocked before consumer click handlers run.\n * - `Escape` closes and restores focus to the region. While open the menu is a\n * layer on the shared {@link EscapeLayer} stack; it claims a press only while\n * focus is inside the controller or fell to the body, so one keypress closes\n * exactly one layer. `Tab` lets the browser move focus first, then closes on\n * the next task. An outside click or context-menu invocation closes without\n * stealing focus from its destination.\n *\n * Roving focus skips `hidden` and natively `disabled` items. An\n * `aria-disabled=\"true\"` item stays reachable by arrow keys — APG marks that\n * attribute precisely for controls that must remain discoverable — while its\n * activation is suppressed, so it announces itself and does nothing.\n */\nexport class ContextMenuController extends Controller<HTMLElement> {\n static override targets = [\"region\", \"menu\", \"item\"];\n static actions = [\"activate\", \"onItemKeydown\", \"onRegionKeydown\", \"open\"] as const;\n\n declare readonly regionTarget: HTMLElement;\n declare readonly menuTarget: HTMLElement;\n declare readonly itemTargets: HTMLButtonElement[];\n declare readonly hasRegionTarget: boolean;\n declare readonly hasMenuTarget: boolean;\n\n readonly #timers = new SafeTimeout();\n\n /** Escape-stack membership while open; the shared resolver dismisses via it. */\n readonly #escapeLayer = new EscapeLayer();\n\n /** Starts closed and registers delegated activation and outside-pointer listeners. */\n override connect(): void {\n this.#closeMenu();\n this.element.addEventListener(\"click\", this.#onItemClickCapture, true);\n document.addEventListener(\"click\", this.#onOutsidePointer, true);\n document.addEventListener(\"contextmenu\", this.#onOutsidePointer, true);\n }\n\n /** Releases the listeners, stack membership, and pending Tab-close task. */\n override disconnect(): void {\n this.#timers.clearAll();\n this.#escapeLayer.deactivate();\n this.element.removeEventListener(\"click\", this.#onItemClickCapture, true);\n document.removeEventListener(\"click\", this.#onOutsidePointer, true);\n document.removeEventListener(\"contextmenu\", this.#onOutsidePointer, true);\n }\n\n /**\n * Opens the menu from a `contextmenu` event: suppresses the native menu and\n * places this one at the pointer coordinate.\n */\n open(event: MouseEvent): void {\n event.preventDefault();\n this.#openAt(event.clientX, event.clientY);\n }\n\n /** Keyboard entry on the region: `Shift+F10` / `ContextMenu` open at center. */\n onRegionKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key (a grabbed drag handle, a\n // nested menu) must not ALSO act on it — composition depends on this yield.\n if (event.defaultPrevented) return;\n const isContextKey = event.key === \"ContextMenu\" || (event.key === \"F10\" && event.shiftKey);\n if (!isContextKey) return;\n event.preventDefault();\n const rect = this.hasRegionTarget\n ? this.regionTarget.getBoundingClientRect()\n : { left: 0, top: 0, width: 0, height: 0 };\n this.#openAt(rect.left + rect.width / 2, rect.top + rect.height / 2);\n }\n\n /** Roving focus and closing keys inside the menu. */\n onItemKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key (a grabbed drag handle, a\n // nested menu) must not ALSO act on it — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n const items = this.#navigableItems;\n const currentIndex = items.indexOf(event.currentTarget as HTMLButtonElement);\n\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n if (items.length > 0) {\n const nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % items.length;\n items[nextIndex]?.focus();\n }\n break;\n case \"ArrowUp\":\n event.preventDefault();\n if (items.length > 0) {\n const previousIndex = currentIndex < 0 ? items.length - 1 : currentIndex - 1;\n items[(previousIndex + items.length) % items.length]?.focus();\n }\n break;\n case \"Home\":\n event.preventDefault();\n items[0]?.focus();\n break;\n case \"End\":\n event.preventDefault();\n items[items.length - 1]?.focus();\n break;\n case \"Tab\":\n // Closing synchronously removes the focused item before the browser's\n // default Tab action, which can restart traversal at the document head.\n this.#timers.clearAll();\n this.#timers.set(() => this.#closeMenu(), 0);\n break;\n default:\n break;\n }\n }\n\n /** Closes after an item is activated and restores focus to the region. */\n activate(): void {\n this.#closeAndRestore();\n }\n\n /** Opens the menu at viewport coordinates `(x, y)` and focuses the first item. */\n #openAt(x: number, y: number): void {\n if (!this.hasMenuTarget) return;\n this.#timers.clearAll();\n this.#escapeLayer.activate(document, {\n onDismiss: () => this.#closeAndRestore(),\n claims: claimsWhileFocusWithin(this.element),\n });\n this.menuTarget.style.setProperty(\"--stimeo-context-menu-x\", `${x}px`);\n this.menuTarget.style.setProperty(\"--stimeo-context-menu-y\", `${y}px`);\n this.menuTarget.hidden = false;\n if (this.hasRegionTarget) this.regionTarget.setAttribute(\"data-state\", \"open\");\n this.#navigableItems[0]?.focus();\n }\n\n /** Hides the menu and reflects the collapsed state on the region. */\n #closeMenu(): void {\n this.#timers.clearAll();\n this.#escapeLayer.deactivate();\n if (!this.hasMenuTarget) return;\n this.menuTarget.hidden = true;\n if (this.hasRegionTarget) this.regionTarget.setAttribute(\"data-state\", \"closed\");\n }\n\n /** Closes the menu and returns focus to the region (Escape / activation). */\n #closeAndRestore(): void {\n this.#closeMenu();\n if (this.hasRegionTarget) this.regionTarget.focus();\n }\n\n /**\n * Closes when a click or context-menu invocation lands outside this instance.\n * Both subscriptions observe in the capture phase, so the target is judged\n * against the tree the user actually pressed even when a consumer handler\n * detaches it, and application code that stops bubbling cannot leave the menu\n * open.\n */\n readonly #onOutsidePointer = (event: MouseEvent): void => {\n if (this.#isOpen && !this.element.contains(event.target as Node)) this.#closeMenu();\n };\n\n /**\n * Captures clicks so `aria-disabled` commands cannot reach consumer handlers.\n * Native Enter/Space activation also synthesizes a click and is blocked here.\n */\n readonly #onItemClickCapture = (event: MouseEvent): void => {\n const target = event.target;\n if (!(target instanceof Node)) return;\n const disabled = this.itemTargets.some(\n (item) => item.getAttribute(\"aria-disabled\") === \"true\" && item.contains(target),\n );\n if (!disabled) return;\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n\n /** Menu items eligible for roving focus (excludes hidden / natively disabled). */\n get #navigableItems(): HTMLButtonElement[] {\n return this.itemTargets.filter((item) => this.#isNavigable(item));\n }\n\n /**\n * An item can take roving focus unless it is `hidden` or a natively `disabled`\n * form control. CSS-only visibility is not detectable here and is the\n * consumer's responsibility.\n *\n * **`aria-disabled=\"true\"` stays reachable.** APG separates the two attributes\n * by intent: `disabled` is for controls whose existence can be inferred from a\n * neighbour (a greyed Next next to a Prev), while `aria-disabled` marks a\n * control that must stay *discoverable* — and it names menu items as the\n * example. Skipping it would hide the command's existence from a keyboard user\n * entirely. Activation is suppressed separately, so the item announces itself\n * and does nothing.\n */\n #isNavigable(item: HTMLButtonElement): boolean {\n if (item.hasAttribute(\"hidden\")) return false;\n return !item.disabled;\n }\n\n /** Whether the menu is currently visible. */\n get #isOpen(): boolean {\n return this.hasMenuTarget && !this.menuTarget.hidden;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/controllers/count_up_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OACE,OAAO,MAAA,CAAO,UAAA,KAAe,cAC7B,MAAA,CAAO,UAAA,CAAW,kCAAkC,CAAA,CAAE,OAAA;AAE1D;;;ACSO,IAAM,iBAAA,GAAN,cAAgC,UAAA,CAAwB;AAAA,EAC7D,OAAgB,MAAA,GAAS;AAAA,IACvB,QAAA,EAAU,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,IAAA,EAAK;AAAA,IACxC,IAAA,EAAM,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,EAAE;AAAA,IACjC,IAAA,EAAM,EAAE,IAAA,EAAM,OAAA,EAAS,SAAS,IAAA;AAAK,GACvC;AAAA,EACA,OAAO,OAAA,GAAU,CAAC,OAAO,CAAA;AAAA,EACzB,OAAO,MAAA,GAAS,CAAC,KAAK,CAAA;AAAA,EAMtB,MAAA,GAAwB,IAAA;AAAA;AAAA,EAExB,UAAA,GAAa,EAAA;AAAA,EAEJ,OAAA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AAA,CAAQ,cAAc,IAAA,CAAK,UAAA;AAChC,IAAA,IAAA,CAAK,aAAA,EAAc;AACnB,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,oBAAA,EAAsB,MAAM,CAAA;AAAA,EACxD;AAAA;AAAA,EAGA,aAAA,GAAsB;AACpB,IAAA,IAAI,CAAC,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAA,EAAG;AACvD,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,8BAA8B,CAAA;AACzE,IAAA,IAAI,aAAa,IAAA,EAAM;AACrB,MAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,QAAQ,CAAA;AAChD,MAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,8BAA8B,CAAA;AAAA,IAC7D,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,YAAY,CAAA;AAAA,IAC3C;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,qBAAqB,CAAA;AAAA,EACpD;AACF","file":"count_up_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","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/**\n * Headless **count-up**: animates a number from `from` up to the value already\n * in the DOM — typically started the moment the element scrolls into view by\n * composing with the `stimeo--intersection` primitive (the classic \"animate\n * when visible\"). Distinct from `stimeo--countdown` (time-based). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--count-up`):\n * <span data-controller=\"stimeo--intersection stimeo--count-up\"\n * data-stimeo--intersection-once-value=\"true\"\n * data-action=\"stimeo--intersection:enter->stimeo--count-up#start\">1200</span>\n *\n * The **final number stays authored in the markup** (SEO / no-JS / SR read the\n * real value); `start` animates the displayed text from `from` to it over\n * `duration` ms with an ease-out curve, then restores the exact authored text.\n * With `once` (default) later starts are ignored (`data-count-up-done` records\n * a finished run across Turbo cache restores).\n *\n * @remarks\n * Behavior only — no formatting is imposed: the authored text is parsed for\n * its integer value (separators are ignored) and restored verbatim at the end;\n * intermediate frames render plain integers. Accessibility: when the user\n * prefers reduced motion the animation is skipped entirely (the value just\n * stays final — WCAG 2.3.3). The element is not a live region, so the ticking\n * intermediate numbers are never actively announced; during the run the\n * authored value is additionally kept in `aria-label` (best-effort — generic\n * roles may ignore it) and that lingering label doubles as the\n * interrupted-run marker `connect()` restores from after a Turbo cache\n * snapshot taken mid-animation. The animation frame is canceled on\n * `disconnect()` (Turbo navigation included) and the authored text restored.\n */\nexport class CountUpController extends Controller<HTMLElement> {\n static override values = {\n duration: { type: Number, default: 1200 },\n from: { type: Number, default: 0 },\n once: { type: Boolean, default: true },\n };\n static actions = [\"start\"] as const;\n static events = [\"end\"] as const;\n\n declare durationValue: number;\n declare fromValue: number;\n declare onceValue: boolean;\n\n #frame: number | null = null;\n /** The authored final text, restored verbatim when the run settles. */\n #finalText = \"\";\n\n override connect(): void {\n // Turbo snapshots the page BEFORE the body swap, so a cached page can hold\n // a mid-animation frame (disconnect()'s settle runs too late for it). The\n // OWN-label marker (never a bare aria-label — that may be authored) flags\n // the interrupted run: the label it owns still holds the authored text.\n if (this.element.hasAttribute(\"data-count-up-label\")) {\n this.element.textContent =\n this.element.getAttribute(\"aria-label\") ?? this.element.textContent;\n this.#restoreLabel();\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n }\n\n override disconnect(): void {\n // A run cannot survive the element: settle instantly so the cached\n // snapshot holds the real value, never a mid-animation frame.\n if (this.#frame !== null) this.#settle();\n }\n\n /**\n * Starts the animation (typically from `stimeo--intersection:enter` via\n * `data-action`). No-ops while running, and after a finished run when `once`.\n */\n start(): void {\n if (this.#frame !== null) return;\n if (this.onceValue && this.element.hasAttribute(\"data-count-up-done\")) return;\n\n this.#finalText = this.element.textContent ?? \"\";\n const target = Number.parseInt(this.#finalText.replace(/[^0-9-]/g, \"\"), 10);\n if (Number.isNaN(target)) return;\n\n // Reduced motion: no ticking, just the final value (WCAG 2.3.3).\n if (prefersReducedMotion()) {\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n this.dispatch(\"end\", { detail: { value: target } });\n return;\n }\n\n // AT keeps the real value while the visible text ticks. An authored\n // aria-label is parked (save-restore, never clobbered) and the override is\n // marker-owned so connect()/settle() only ever touch what this set.\n const authored = this.element.getAttribute(\"aria-label\");\n if (authored !== null) {\n this.element.setAttribute(\"data-count-up-original-label\", authored);\n }\n this.element.setAttribute(\"data-count-up-label\", \"true\");\n this.element.setAttribute(\"aria-label\", this.#finalText);\n const started = performance.now();\n const step = (now: number): void => {\n const t = Math.min((now - started) / this.durationValue, 1);\n const eased = 1 - (1 - t) ** 3; // ease-out cubic\n this.element.textContent = String(\n Math.round(this.fromValue + (target - this.fromValue) * eased),\n );\n if (t < 1) {\n this.#frame = requestAnimationFrame(step);\n } else {\n this.#settle();\n this.dispatch(\"end\", { detail: { value: target } });\n }\n };\n this.#frame = requestAnimationFrame(step);\n }\n\n /** Ends the run: cancels the frame and restores the authored presentation. */\n #settle(): void {\n if (this.#frame !== null) cancelAnimationFrame(this.#frame);\n this.#frame = null;\n this.element.textContent = this.#finalText;\n this.#restoreLabel();\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n\n /** Releases the marker-owned aria-label, restoring any parked authored value. */\n #restoreLabel(): void {\n if (!this.element.hasAttribute(\"data-count-up-label\")) return;\n const original = this.element.getAttribute(\"data-count-up-original-label\");\n if (original !== null) {\n this.element.setAttribute(\"aria-label\", original);\n this.element.removeAttribute(\"data-count-up-original-label\");\n } else {\n this.element.removeAttribute(\"aria-label\");\n }\n this.element.removeAttribute(\"data-count-up-label\");\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/controllers/count_up_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;;;ACUO,IAAM,iBAAA,GAAN,cAAgC,UAAA,CAAwB;AAAA,EAC7D,OAAgB,MAAA,GAAS;AAAA,IACvB,QAAA,EAAU,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,IAAA,EAAK;AAAA,IACxC,IAAA,EAAM,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,EAAE;AAAA,IACjC,IAAA,EAAM,EAAE,IAAA,EAAM,OAAA,EAAS,SAAS,IAAA;AAAK,GACvC;AAAA,EACA,OAAO,OAAA,GAAU,CAAC,OAAO,CAAA;AAAA,EACzB,OAAO,MAAA,GAAS,CAAC,KAAK,CAAA;AAAA,EAMtB,MAAA,GAAwB,IAAA;AAAA;AAAA,EAExB,UAAA,GAAa,EAAA;AAAA,EAEJ,OAAA,GAAgB;AAKvB,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAA,EAAG;AACpD,MAAA,IAAA,CAAK,OAAA,CAAQ,cACX,IAAA,CAAK,OAAA,CAAQ,aAAa,YAAY,CAAA,IAAK,KAAK,OAAA,CAAQ,WAAA;AA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AAI,CAAC,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAA,EAAG;AACvD,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,8BAA8B,CAAA;AACzE,IAAA,IAAI,aAAa,IAAA,EAAM;AACrB,MAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,QAAQ,CAAA;AAChD,MAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,8BAA8B,CAAA;AAAA,IAC7D,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,YAAY,CAAA;AAAA,IAC3C;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,qBAAqB,CAAA;AAAA,EACpD;AACF","file":"count_up_controller.js","sourcesContent":["/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n * (count-up, highlight, overflow-indicator, scroll-visibility, stick-to-bottom,\n * transition).\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/**\n * Headless **count-up**: animates a number from `from` up to the value already\n * in the DOM — typically started the moment the element scrolls into view by\n * composing with the `stimeo--intersection` primitive (the classic \"animate\n * when visible\"). Distinct from `stimeo--countdown` (time-based). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--count-up`):\n * <span data-controller=\"stimeo--intersection stimeo--count-up\"\n * data-stimeo--intersection-once-value=\"true\"\n * data-action=\"stimeo--intersection:enter->stimeo--count-up#start\">1200</span>\n *\n * The **final number stays authored in the markup** (SEO / no-JS / SR read the\n * real value); `start` animates the displayed text from `from` to it over\n * `duration` ms with an ease-out curve, then restores the exact authored text.\n * With `once` (default) later starts are ignored (`data-count-up-done` records\n * a finished run across Turbo cache restores).\n *\n * @remarks\n * Behavior only — no formatting is imposed: the authored text is parsed for\n * its integer value (separators are ignored) and restored verbatim at the end;\n * intermediate frames render plain integers. Accessibility: when the user\n * prefers reduced motion the animation is skipped entirely (the value just\n * stays final — WCAG 2.3.3). The element is not a live region, so the ticking\n * intermediate numbers are never actively announced; during the run the\n * authored value is additionally kept in `aria-label` (best-effort — generic\n * roles may ignore it) and that lingering label doubles as the\n * interrupted-run marker `connect()` restores from after a Turbo cache\n * snapshot taken mid-animation. The animation frame is canceled on\n * `disconnect()` (Turbo navigation included) and the authored text restored.\n */\nexport class CountUpController extends Controller<HTMLElement> {\n static override values = {\n duration: { type: Number, default: 1200 },\n from: { type: Number, default: 0 },\n once: { type: Boolean, default: true },\n };\n static actions = [\"start\"] as const;\n static events = [\"end\"] as const;\n\n declare durationValue: number;\n declare fromValue: number;\n declare onceValue: boolean;\n\n #frame: number | null = null;\n /** The authored final text, restored verbatim when the run settles. */\n #finalText = \"\";\n\n override connect(): void {\n // Turbo snapshots the page BEFORE the body swap, so a cached page can hold\n // a mid-animation frame (disconnect()'s settle runs too late for it). The\n // OWN-label marker (never a bare aria-label — that may be authored) flags\n // the interrupted run: the label it owns still holds the authored text.\n if (this.element.hasAttribute(\"data-count-up-label\")) {\n this.element.textContent =\n this.element.getAttribute(\"aria-label\") ?? this.element.textContent;\n this.#restoreLabel();\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n }\n\n override disconnect(): void {\n // A run cannot survive the element: settle instantly so the cached\n // snapshot holds the real value, never a mid-animation frame.\n if (this.#frame !== null) this.#settle();\n }\n\n /**\n * Starts the animation (typically from `stimeo--intersection:enter` via\n * `data-action`). No-ops while running, and after a finished run when `once`.\n */\n start(): void {\n if (this.#frame !== null) return;\n if (this.onceValue && this.element.hasAttribute(\"data-count-up-done\")) return;\n\n this.#finalText = this.element.textContent ?? \"\";\n const target = Number.parseInt(this.#finalText.replace(/[^0-9-]/g, \"\"), 10);\n if (Number.isNaN(target)) return;\n\n // Reduced motion: no ticking, just the final value (WCAG 2.3.3).\n if (prefersReducedMotion()) {\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n this.dispatch(\"end\", { detail: { value: target } });\n return;\n }\n\n // AT keeps the real value while the visible text ticks. An authored\n // aria-label is parked (save-restore, never clobbered) and the override is\n // marker-owned so connect()/settle() only ever touch what this set.\n const authored = this.element.getAttribute(\"aria-label\");\n if (authored !== null) {\n this.element.setAttribute(\"data-count-up-original-label\", authored);\n }\n this.element.setAttribute(\"data-count-up-label\", \"true\");\n this.element.setAttribute(\"aria-label\", this.#finalText);\n const started = performance.now();\n const step = (now: number): void => {\n const t = Math.min((now - started) / this.durationValue, 1);\n const eased = 1 - (1 - t) ** 3; // ease-out cubic\n this.element.textContent = String(\n Math.round(this.fromValue + (target - this.fromValue) * eased),\n );\n if (t < 1) {\n this.#frame = requestAnimationFrame(step);\n } else {\n this.#settle();\n this.dispatch(\"end\", { detail: { value: target } });\n }\n };\n this.#frame = requestAnimationFrame(step);\n }\n\n /** Ends the run: cancels the frame and restores the authored presentation. */\n #settle(): void {\n if (this.#frame !== null) cancelAnimationFrame(this.#frame);\n this.#frame = null;\n this.element.textContent = this.#finalText;\n this.#restoreLabel();\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n\n /** Releases the marker-owned aria-label, restoring any parked authored value. */\n #restoreLabel(): void {\n if (!this.element.hasAttribute(\"data-count-up-label\")) return;\n const original = this.element.getAttribute(\"data-count-up-original-label\");\n if (original !== null) {\n this.element.setAttribute(\"aria-label\", original);\n this.element.removeAttribute(\"data-count-up-original-label\");\n } else {\n this.element.removeAttribute(\"aria-label\");\n }\n this.element.removeAttribute(\"data-count-up-label\");\n }\n}\n"]}
@@ -52,14 +52,32 @@ declare class DataGridController extends Controller<HTMLElement> {
52
52
  readonly rowTargets: HTMLElement[];
53
53
  readonly cellTargets: HTMLElement[];
54
54
  selectionValue: string;
55
- /** Establishes a single tab stop across all navigable cells/headers. */
55
+ /**
56
+ * Establishes a single tab stop across all navigable cells/headers and brings
57
+ * the rows to their baseline.
58
+ *
59
+ * Normalizing here rather than leaving it to {@link selectionValueChanged}
60
+ * guarantees exactly one pass per mount: a re-attached element reuses its
61
+ * cached Stimulus context, whose value observer already knows the `selection`
62
+ * attribute, so the Value callback does not fire a second time.
63
+ */
56
64
  connect(): void;
65
+ /** Reopens the row callback for the next mount. */
66
+ disconnect(): void;
57
67
  /**
58
68
  * Keeps `aria-multiselectable` in step with the `selection` Value. Fires on connect
59
69
  * (so it self-heals after a Turbo morph) and on any runtime change, so the ARIA
60
70
  * never drifts from the selection logic, which reads `selectionValue` live.
61
71
  */
62
72
  selectionValueChanged(): void;
73
+ /**
74
+ * Re-establishes the row baseline for a row added after connect.
75
+ *
76
+ * Each pass walks every row, and Stimulus reports the authored rows one by one
77
+ * before `connect()`, so the mount is gated to keep it linear in the row count
78
+ * rather than quadratic; `connect()` runs the single baseline pass instead.
79
+ */
80
+ rowTargetConnected(): void;
63
81
  /** Cycles the activated column header's sort and emits `sort`. */
64
82
  sort(event: Event): void;
65
83
  /** Toggles selection of the row owning the event target. Bound optionally. */
@@ -1,5 +1,23 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
+ // src/controllers/data_grid_controller.ts
4
+
5
+ // src/utils/logical_scroll.ts
6
+ function isRtl(element) {
7
+ return window.getComputedStyle(element).direction === "rtl";
8
+ }
9
+
10
+ // src/utils/arrow_step.ts
11
+ function logicalArrowKey(key, element) {
12
+ if (key !== "ArrowRight" && key !== "ArrowLeft") return key;
13
+ if (!isRtl(element)) return key;
14
+ return key === "ArrowRight" ? "ArrowLeft" : "ArrowRight";
15
+ }
16
+ function isReservedArrowChord(event, allow = []) {
17
+ if (!event.key.startsWith("Arrow")) return false;
18
+ return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
19
+ }
20
+
3
21
  // src/controllers/data_grid_controller.ts
4
22
  var SORT_CYCLE = ["none", "ascending", "descending"];
5
23
  function nextSortDirection(current) {
@@ -14,11 +32,27 @@ var DataGridController = class extends Controller {
14
32
  };
15
33
  static actions = ["onKeydown", "sort", "toggleSelect"];
16
34
  static events = ["selectionchange", "sort"];
17
- /** Establishes a single tab stop across all navigable cells/headers. */
35
+ /** Gates the row callback so it does not re-walk every row once per authored row on mount. */
36
+ #connected = false;
37
+ /**
38
+ * Establishes a single tab stop across all navigable cells/headers and brings
39
+ * the rows to their baseline.
40
+ *
41
+ * Normalizing here rather than leaving it to {@link selectionValueChanged}
42
+ * guarantees exactly one pass per mount: a re-attached element reuses its
43
+ * cached Stimulus context, whose value observer already knows the `selection`
44
+ * attribute, so the Value callback does not fire a second time.
45
+ */
18
46
  connect() {
19
47
  const cells = this.#navigableCells();
20
48
  const active = cells.find((cell) => cell.tabIndex === 0) ?? cells[0];
21
49
  this.#setActiveCell(active, { focus: false });
50
+ this.#normalizeSelection();
51
+ this.#connected = true;
52
+ }
53
+ /** Reopens the row callback for the next mount. */
54
+ disconnect() {
55
+ this.#connected = false;
22
56
  }
23
57
  /**
24
58
  * Keeps `aria-multiselectable` in step with the `selection` Value. Fires on connect
@@ -27,6 +61,45 @@ var DataGridController = class extends Controller {
27
61
  */
28
62
  selectionValueChanged() {
29
63
  this.#syncSelectable();
64
+ this.#normalizeSelection();
65
+ }
66
+ /**
67
+ * Re-establishes the row baseline for a row added after connect.
68
+ *
69
+ * Each pass walks every row, and Stimulus reports the authored rows one by one
70
+ * before `connect()`, so the mount is gated to keep it linear in the row count
71
+ * rather than quadratic; `connect()` runs the single baseline pass instead.
72
+ */
73
+ rowTargetConnected() {
74
+ if (!this.#connected) return;
75
+ this.#normalizeSelection();
76
+ }
77
+ /**
78
+ * Brings the authored rows to the shape the APG requires, without changing
79
+ * which rows the author chose.
80
+ *
81
+ * Every selectable row gets an explicit value — an absent `aria-selected` means
82
+ * "not selectable" in ARIA, so a forgotten attribute hides a selectable row —
83
+ * and a single-select grid keeps at most one `true`, first in DOM order.
84
+ * A grid that declares `selection="none"` has no selectable rows, so the
85
+ * attribute is removed rather than written: in ARIA its absence is what "not
86
+ * selectable" looks like.
87
+ */
88
+ #normalizeSelection() {
89
+ const rows = this.rowTargets;
90
+ if (this.selectionValue === "none") {
91
+ for (const row of rows) row.removeAttribute("aria-selected");
92
+ return;
93
+ }
94
+ const single = this.selectionValue === "single";
95
+ const first = rows.find((row) => row.getAttribute("aria-selected") === "true");
96
+ for (const row of rows) {
97
+ if (single) {
98
+ row.setAttribute("aria-selected", row === first ? "true" : "false");
99
+ } else if (row.getAttribute("aria-selected") !== "true") {
100
+ row.setAttribute("aria-selected", "false");
101
+ }
102
+ }
30
103
  }
31
104
  /**
32
105
  * Mirrors `selection="multiple"` onto `aria-multiselectable` (APG Grid) so SRs
@@ -53,11 +126,14 @@ var DataGridController = class extends Controller {
53
126
  }
54
127
  /** Toggles selection of the row owning the event target. Bound optionally. */
55
128
  toggleSelect(event) {
129
+ if (this.selectionValue === "none") return;
56
130
  const row = event.currentTarget.closest("[role='row']");
57
131
  if (row && this.rowTargets.includes(row)) this.#toggleRow(row);
58
132
  }
59
133
  /** Grid navigation + sort/select activation. Bound to cells and headers. */
60
134
  onKeydown(event) {
135
+ if (event.defaultPrevented) return;
136
+ if (isReservedArrowChord(event)) return;
61
137
  const cell = event.currentTarget;
62
138
  const matrix = this.#matrix();
63
139
  const position = this.#locate(matrix, cell);
@@ -65,7 +141,7 @@ var DataGridController = class extends Controller {
65
141
  const [row, col] = position;
66
142
  const rowCells = matrix[row] ?? [];
67
143
  let target;
68
- switch (event.key) {
144
+ switch (logicalArrowKey(event.key, this.element)) {
69
145
  case "ArrowRight":
70
146
  target = this.#cellInRow(matrix, row, col + 1);
71
147
  break;
@@ -118,8 +194,10 @@ var DataGridController = class extends Controller {
118
194
  /** Toggles a row's `aria-selected`, honoring single vs. multiple selection. */
119
195
  #toggleRow(row) {
120
196
  const selected = row.getAttribute("aria-selected") === "true";
121
- if (this.selectionValue === "single" && !selected) {
122
- for (const other of this.rowTargets) other.setAttribute("aria-selected", "false");
197
+ if (this.selectionValue === "single") {
198
+ for (const other of this.rowTargets) {
199
+ if (other !== row) other.setAttribute("aria-selected", "false");
200
+ }
123
201
  }
124
202
  row.setAttribute("aria-selected", selected ? "false" : "true");
125
203
  const rows = this.rowTargets.filter((r) => r.getAttribute("aria-selected") === "true");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/controllers/data_grid_controller.ts"],"names":[],"mappings":";;;AAGA,IAAM,UAAA,GAAa,CAAC,MAAA,EAAQ,WAAA,EAAa,YAAY,CAAA;AASrD,SAAS,kBAAkB,OAAA,EAAgC;AACzD,EAAA,MAAM,KAAA,GAAQ,UAAA,CAAW,OAAA,CAAQ,OAAwB,CAAA;AACzD,EAAA,MAAM,IAAA,GAAO,KAAA,GAAQ,CAAA,GAAI,CAAA,GAAI,KAAA;AAC7B,EAAA,OAAO,UAAA,CAAA,CAAY,IAAA,GAAO,CAAA,IAAK,UAAA,CAAW,MAAM,CAAA,IAAK,WAAA;AACvD;AAuCO,IAAM,kBAAA,GAAN,cAAiC,UAAA,CAAwB;AAAA,EAC9D,OAAgB,OAAA,GAAU,CAAC,cAAA,EAAgB,OAAO,MAAM,CAAA;AAAA,EACxD,OAAgB,MAAA,GAAS;AAAA,IACvB,SAAA,EAAW,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,MAAA;AAAO,GAC7C;AAAA,EACA,OAAO,OAAA,GAAU,CAAC,WAAA,EAAa,QAAQ,cAAc,CAAA;AAAA,EACrD,OAAO,MAAA,G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EAGA,UAAA,CAAW,MAAA,EAAyB,GAAA,EAAa,GAAA,EAAsC;AACrF,IAAA,MAAM,KAAA,GAAQ,OAAO,GAAG,CAAA;AACxB,IAAA,IAAI,CAAC,KAAA,IAAS,KAAA,CAAM,MAAA,KAAW,GAAG,OAAO,MAAA;AACzC,IAAA,OAAO,MAAM,IAAA,CAAK,GAAA,CAAI,KAAK,KAAA,CAAM,MAAA,GAAS,CAAC,CAAC,CAAA;AAAA,EAC9C;AACF","file":"data_grid_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/** Cycle order for a sortable column header's `aria-sort`. */\nconst SORT_CYCLE = [\"none\", \"ascending\", \"descending\"] as const;\ntype SortDirection = (typeof SORT_CYCLE)[number];\n\n/**\n * Returns the next `aria-sort` direction in the cycle after `current`. Unknown or\n * ARIA-only values (e.g. `\"other\"`, or an empty/missing attribute) are treated as\n * `\"none\"`, so the first activation always advances to `\"ascending\"` instead of\n * stalling.\n */\nfunction nextSortDirection(current: string): SortDirection {\n const index = SORT_CYCLE.indexOf(current as SortDirection);\n const from = index < 0 ? 0 : index;\n return SORT_CYCLE[(from + 1) % SORT_CYCLE.length] ?? \"ascending\";\n}\n\n/**\n * Headless, accessible **Data Grid** behavior: column sorting, row selection, and\n * roving keyboard navigation over an interactive table.\n *\n * Markup contract (identifier: `stimeo--data-grid`):\n * <table data-controller=\"stimeo--data-grid\" role=\"grid\" aria-label=\"Users\"\n * data-stimeo--data-grid-selection-value=\"single\">\n * <thead><tr role=\"row\">\n * <th role=\"columnheader\" aria-sort=\"none\" tabindex=\"-1\"\n * data-stimeo--data-grid-target=\"columnHeader\"\n * data-action=\"click->stimeo--data-grid#sort\n * keydown->stimeo--data-grid#onKeydown\">Name</th>\n * </tr></thead>\n * <tbody><tr role=\"row\" aria-selected=\"false\"\n * data-stimeo--data-grid-target=\"row\">\n * <td role=\"gridcell\" tabindex=\"0\" data-stimeo--data-grid-target=\"cell\"\n * data-action=\"keydown->stimeo--data-grid#onKeydown\">Jane</td>\n * </tr></tbody>\n * </table>\n *\n * Implements the WAI-ARIA APG **Grid** pattern plus `aria-sort`. The whole grid is\n * a single Tab stop (roving `tabindex`: exactly one cell/header is `0`, the rest\n * `-1`); arrow keys move both DOM focus and that tabbable position. Sort state is\n * exposed via `aria-sort` on headers, selection via `aria-selected` on rows.\n *\n * @remarks\n * Behavior only — the consumer performs the actual data sort/render in response to\n * the `sort` event and owns all styling. No timers or observers are held, so there\n * is nothing to leak across Turbo navigations; `connect()` rebuilds the single tab\n * stop idempotently from the DOM.\n *\n * Behavior provided:\n * - `Arrow*` move between cells (clamped at edges); `Home`/`End` to the row's\n * first/last cell; `Ctrl+Home`/`Ctrl+End` to the grid's first/last cell.\n * - `Enter`/`Space` cycles a header's sort (`none→ascending→descending`) or toggles\n * the focused row's selection when selection is enabled.\n */\nexport class DataGridController extends Controller<HTMLElement> {\n static override targets = [\"columnHeader\", \"row\", \"cell\"];\n static override values = {\n selection: { type: String, default: \"none\" },\n };\n static actions = [\"onKeydown\", \"sort\", \"toggleSelect\"] as const;\n static events = [\"selectionchange\", \"sort\"] as const;\n\n declare readonly columnHeaderTargets: HTMLElement[];\n declare readonly rowTargets: HTMLElement[];\n declare readonly cellTargets: HTMLElement[];\n declare selectionValue: string;\n\n /** Establishes a single tab stop across all navigable cells/headers. */\n override connect(): void {\n const cells = this.#navigableCells();\n const active = cells.find((cell) => cell.tabIndex === 0) ?? cells[0];\n this.#setActiveCell(active, { focus: false });\n }\n\n /**\n * Keeps `aria-multiselectable` in step with the `selection` Value. Fires on connect\n * (so it self-heals after a Turbo morph) and on any runtime change, so the ARIA\n * never drifts from the selection logic, which reads `selectionValue` live.\n */\n selectionValueChanged(): void {\n this.#syncSelectable();\n }\n\n /**\n * Mirrors `selection=\"multiple\"` onto `aria-multiselectable` (APG Grid) so SRs\n * announce that more than one row can be selected; cleared for single/none so a\n * grid never carries a misleading attribute.\n */\n #syncSelectable(): void {\n if (this.selectionValue === \"multiple\") {\n this.element.setAttribute(\"aria-multiselectable\", \"true\");\n } else {\n this.element.removeAttribute(\"aria-multiselectable\");\n }\n }\n\n /** Cycles the activated column header's sort and emits `sort`. */\n sort(event: Event): void {\n const header = event.currentTarget as HTMLElement;\n if (!this.columnHeaderTargets.includes(header)) return;\n\n const direction = nextSortDirection(header.getAttribute(\"aria-sort\") ?? \"none\");\n\n // Only one column is sorted at a time: reset the others to `none`.\n for (const other of this.columnHeaderTargets) {\n other.setAttribute(\"aria-sort\", other === header ? direction : \"none\");\n }\n\n this.#setActiveCell(header, { focus: false });\n this.dispatch(\"sort\", { detail: { column: header, direction } });\n }\n\n /** Toggles selection of the row owning the event target. Bound optionally. */\n toggleSelect(event: Event): void {\n const row = (event.currentTarget as HTMLElement).closest<HTMLElement>(\"[role='row']\");\n if (row && this.rowTargets.includes(row)) this.#toggleRow(row);\n }\n\n /** Grid navigation + sort/select activation. Bound to cells and headers. */\n onKeydown(event: KeyboardEvent): void {\n const cell = event.currentTarget as HTMLElement;\n const matrix = this.#matrix();\n const position = this.#locate(matrix, cell);\n if (!position) return;\n const [row, col] = position;\n const rowCells = matrix[row] ?? [];\n\n let target: HTMLElement | undefined;\n switch (event.key) {\n case \"ArrowRight\":\n target = this.#cellInRow(matrix, row, col + 1);\n break;\n case \"ArrowLeft\":\n target = this.#cellInRow(matrix, row, Math.max(col - 1, 0));\n break;\n case \"ArrowDown\":\n target = this.#cellInRow(matrix, Math.min(row + 1, matrix.length - 1), col);\n break;\n case \"ArrowUp\":\n target = this.#cellInRow(matrix, Math.max(row - 1, 0), col);\n break;\n case \"Home\":\n target = event.ctrlKey ? this.#cellInRow(matrix, 0, 0) : rowCells[0];\n break;\n case \"End\":\n target = event.ctrlKey\n ? this.#cellInRow(matrix, matrix.length - 1, Number.POSITIVE_INFINITY)\n : rowCells[rowCells.length - 1];\n break;\n case \"Enter\":\n case \" \":\n this.#activate(cell);\n event.preventDefault();\n return;\n default:\n return;\n }\n\n if (target) {\n event.preventDefault();\n this.#setActiveCell(target, { focus: true });\n }\n }\n\n /** Performs a header's sort or a cell row's selection toggle on activation. */\n #activate(cell: HTMLElement): void {\n if (this.columnHeaderTargets.includes(cell)) {\n this.#cycleSort(cell);\n return;\n }\n if (this.selectionValue === \"none\") return;\n const row = cell.closest<HTMLElement>(\"[role='row']\");\n if (row && this.rowTargets.includes(row)) this.#toggleRow(row);\n }\n\n /** Shared sort logic for both click and keyboard activation. */\n #cycleSort(header: HTMLElement): void {\n const direction = nextSortDirection(header.getAttribute(\"aria-sort\") ?? \"none\");\n for (const other of this.columnHeaderTargets) {\n other.setAttribute(\"aria-sort\", other === header ? direction : \"none\");\n }\n this.dispatch(\"sort\", { detail: { column: header, direction } });\n }\n\n /** Toggles a row's `aria-selected`, honoring single vs. multiple selection. */\n #toggleRow(row: HTMLElement): void {\n const selected = row.getAttribute(\"aria-selected\") === \"true\";\n if (this.selectionValue === \"single\" && !selected) {\n for (const other of this.rowTargets) other.setAttribute(\"aria-selected\", \"false\");\n }\n row.setAttribute(\"aria-selected\", selected ? \"false\" : \"true\");\n\n const rows = this.rowTargets.filter((r) => r.getAttribute(\"aria-selected\") === \"true\");\n this.dispatch(\"selectionchange\", { detail: { rows } });\n }\n\n /** Makes `cell` the single tabbable cell (roving) and optionally focuses it. */\n #setActiveCell(cell: HTMLElement | undefined, { focus }: { focus: boolean }): void {\n if (!cell) return;\n for (const candidate of this.#navigableCells()) {\n candidate.tabIndex = candidate === cell ? 0 : -1;\n }\n if (focus) cell.focus();\n }\n\n /** All navigable elements (headers + cells) in DOM order. */\n #navigableCells(): HTMLElement[] {\n return this.#matrix().flat();\n }\n\n /** The grid as rows of navigable cells, derived from each `role=\"row\"`. */\n #matrix(): HTMLElement[][] {\n const navigable = new Set<HTMLElement>([...this.columnHeaderTargets, ...this.cellTargets]);\n const rows = Array.from(this.element.querySelectorAll<HTMLElement>(\"[role='row']\"));\n return rows\n .map((row) =>\n Array.from(row.children).filter((child): child is HTMLElement =>\n navigable.has(child as HTMLElement),\n ),\n )\n .filter((cells) => cells.length > 0);\n }\n\n /** Finds `[rowIndex, colIndex]` of `cell` within `matrix`, or null. */\n #locate(matrix: HTMLElement[][], cell: HTMLElement): [number, number] | null {\n for (let row = 0; row < matrix.length; row++) {\n const col = (matrix[row] ?? []).indexOf(cell);\n if (col !== -1) return [row, col];\n }\n return null;\n }\n\n /** The cell at `[row, col]`, clamping `col` to that row's last cell. */\n #cellInRow(matrix: HTMLElement[][], row: number, col: number): HTMLElement | undefined {\n const cells = matrix[row];\n if (!cells || cells.length === 0) return undefined;\n return cells[Math.min(col, cells.length - 1)];\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/controllers/data_grid_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,SAAA,KAAc,KAAA;AACxD;;;AC6CO,SAAS,eAAA,CAAgB,KAAa,OAAA,EAA0B;AACrE,EAAA,IAAI,GAAA,KAAQ,YAAA,IAAgB,GAAA,KAAQ,WAAA,EAAa,OAAO,GAAA;AACxD,EAAA,IAAI,CAAC,KAAA,CAAM,OAAO,CAAA,EAAG,OAAO,GAAA;AAC5B,EAAA,OAAO,GAAA,KAAQ,eAAe,WAAA,GAAc,YAAA;AAC9C;AA2BO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,KACvC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA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,CAAI,KAAK,KAAA,CAAM,MAAA,GAAS,CAAC,CAAC,CAAA;AAAA,EAC9C;AACF","file":"data_grid_controller.js","sourcesContent":["/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord, logicalArrowKey } from \"../utils/arrow_step\";\n\n/** Cycle order for a sortable column header's `aria-sort`. */\nconst SORT_CYCLE = [\"none\", \"ascending\", \"descending\"] as const;\ntype SortDirection = (typeof SORT_CYCLE)[number];\n\n/**\n * Returns the next `aria-sort` direction in the cycle after `current`. Unknown or\n * ARIA-only values (e.g. `\"other\"`, or an empty/missing attribute) are treated as\n * `\"none\"`, so the first activation always advances to `\"ascending\"` instead of\n * stalling.\n */\nfunction nextSortDirection(current: string): SortDirection {\n const index = SORT_CYCLE.indexOf(current as SortDirection);\n const from = index < 0 ? 0 : index;\n return SORT_CYCLE[(from + 1) % SORT_CYCLE.length] ?? \"ascending\";\n}\n\n/**\n * Headless, accessible **Data Grid** behavior: column sorting, row selection, and\n * roving keyboard navigation over an interactive table.\n *\n * Markup contract (identifier: `stimeo--data-grid`):\n * <table data-controller=\"stimeo--data-grid\" role=\"grid\" aria-label=\"Users\"\n * data-stimeo--data-grid-selection-value=\"single\">\n * <thead><tr role=\"row\">\n * <th role=\"columnheader\" aria-sort=\"none\" tabindex=\"-1\"\n * data-stimeo--data-grid-target=\"columnHeader\"\n * data-action=\"click->stimeo--data-grid#sort\n * keydown->stimeo--data-grid#onKeydown\">Name</th>\n * </tr></thead>\n * <tbody><tr role=\"row\" aria-selected=\"false\"\n * data-stimeo--data-grid-target=\"row\">\n * <td role=\"gridcell\" tabindex=\"0\" data-stimeo--data-grid-target=\"cell\"\n * data-action=\"keydown->stimeo--data-grid#onKeydown\">Jane</td>\n * </tr></tbody>\n * </table>\n *\n * Implements the WAI-ARIA APG **Grid** pattern plus `aria-sort`. The whole grid is\n * a single Tab stop (roving `tabindex`: exactly one cell/header is `0`, the rest\n * `-1`); arrow keys move both DOM focus and that tabbable position. Sort state is\n * exposed via `aria-sort` on headers, selection via `aria-selected` on rows.\n *\n * @remarks\n * Behavior only — the consumer performs the actual data sort/render in response to\n * the `sort` event and owns all styling. No timers or observers are held, so there\n * is nothing to leak across Turbo navigations; `connect()` rebuilds the single tab\n * stop idempotently from the DOM.\n *\n * Behavior provided:\n * - `Arrow*` move between cells (clamped at edges); `Home`/`End` to the row's\n * first/last cell; `Ctrl+Home`/`Ctrl+End` to the grid's first/last cell.\n * - `Enter`/`Space` cycles a header's sort (`none→ascending→descending`) or toggles\n * the focused row's selection when selection is enabled.\n */\nexport class DataGridController extends Controller<HTMLElement> {\n static override targets = [\"columnHeader\", \"row\", \"cell\"];\n static override values = {\n selection: { type: String, default: \"none\" },\n };\n static actions = [\"onKeydown\", \"sort\", \"toggleSelect\"] as const;\n static events = [\"selectionchange\", \"sort\"] as const;\n\n declare readonly columnHeaderTargets: HTMLElement[];\n declare readonly rowTargets: HTMLElement[];\n declare readonly cellTargets: HTMLElement[];\n declare selectionValue: string;\n\n /** Gates the row callback so it does not re-walk every row once per authored row on mount. */\n #connected = false;\n\n /**\n * Establishes a single tab stop across all navigable cells/headers and brings\n * the rows to their baseline.\n *\n * Normalizing here rather than leaving it to {@link selectionValueChanged}\n * guarantees exactly one pass per mount: a re-attached element reuses its\n * cached Stimulus context, whose value observer already knows the `selection`\n * attribute, so the Value callback does not fire a second time.\n */\n override connect(): void {\n const cells = this.#navigableCells();\n const active = cells.find((cell) => cell.tabIndex === 0) ?? cells[0];\n this.#setActiveCell(active, { focus: false });\n this.#normalizeSelection();\n this.#connected = true;\n }\n\n /** Reopens the row callback for the next mount. */\n override disconnect(): void {\n this.#connected = false;\n }\n\n /**\n * Keeps `aria-multiselectable` in step with the `selection` Value. Fires on connect\n * (so it self-heals after a Turbo morph) and on any runtime change, so the ARIA\n * never drifts from the selection logic, which reads `selectionValue` live.\n */\n selectionValueChanged(): void {\n this.#syncSelectable();\n this.#normalizeSelection();\n }\n\n /**\n * Re-establishes the row baseline for a row added after connect.\n *\n * Each pass walks every row, and Stimulus reports the authored rows one by one\n * before `connect()`, so the mount is gated to keep it linear in the row count\n * rather than quadratic; `connect()` runs the single baseline pass instead.\n */\n rowTargetConnected(): void {\n if (!this.#connected) return;\n this.#normalizeSelection();\n }\n\n /**\n * Brings the authored rows to the shape the APG requires, without changing\n * which rows the author chose.\n *\n * Every selectable row gets an explicit value — an absent `aria-selected` means\n * \"not selectable\" in ARIA, so a forgotten attribute hides a selectable row —\n * and a single-select grid keeps at most one `true`, first in DOM order.\n * A grid that declares `selection=\"none\"` has no selectable rows, so the\n * attribute is removed rather than written: in ARIA its absence is what \"not\n * selectable\" looks like.\n */\n #normalizeSelection(): void {\n const rows = this.rowTargets;\n if (this.selectionValue === \"none\") {\n // Reclaim, do not merely skip: a grid that *became* unselectable would\n // otherwise keep announcing rows as selected while the logic refuses to\n // change them. In ARIA the absence of the attribute is what \"not\n // selectable\" looks like, so the rows have to lose it outright.\n for (const row of rows) row.removeAttribute(\"aria-selected\");\n return;\n }\n const single = this.selectionValue === \"single\";\n const first = rows.find((row) => row.getAttribute(\"aria-selected\") === \"true\");\n for (const row of rows) {\n if (single) {\n row.setAttribute(\"aria-selected\", row === first ? \"true\" : \"false\");\n } else if (row.getAttribute(\"aria-selected\") !== \"true\") {\n row.setAttribute(\"aria-selected\", \"false\");\n }\n }\n }\n\n /**\n * Mirrors `selection=\"multiple\"` onto `aria-multiselectable` (APG Grid) so SRs\n * announce that more than one row can be selected; cleared for single/none so a\n * grid never carries a misleading attribute.\n */\n #syncSelectable(): void {\n if (this.selectionValue === \"multiple\") {\n this.element.setAttribute(\"aria-multiselectable\", \"true\");\n } else {\n this.element.removeAttribute(\"aria-multiselectable\");\n }\n }\n\n /** Cycles the activated column header's sort and emits `sort`. */\n sort(event: Event): void {\n const header = event.currentTarget as HTMLElement;\n if (!this.columnHeaderTargets.includes(header)) return;\n\n const direction = nextSortDirection(header.getAttribute(\"aria-sort\") ?? \"none\");\n\n // Only one column is sorted at a time: reset the others to `none`.\n for (const other of this.columnHeaderTargets) {\n other.setAttribute(\"aria-sort\", other === header ? direction : \"none\");\n }\n\n this.#setActiveCell(header, { focus: false });\n this.dispatch(\"sort\", { detail: { column: header, direction } });\n }\n\n /** Toggles selection of the row owning the event target. Bound optionally. */\n toggleSelect(event: Event): void {\n // The pointer path guards on `selection=\"none\"` exactly as the keyboard path\n // does, so a grid that declares itself unselectable never grows selected rows.\n if (this.selectionValue === \"none\") return;\n const row = (event.currentTarget as HTMLElement).closest<HTMLElement>(\"[role='row']\");\n if (row && this.rowTargets.includes(row)) this.#toggleRow(row);\n }\n\n /** Grid navigation + sort/select activation. Bound to cells and headers. */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key (a grabbed drag handle, a\n // nested menu) must not ALSO act on it — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n const cell = event.currentTarget as HTMLElement;\n const matrix = this.#matrix();\n const position = this.#locate(matrix, cell);\n if (!position) return;\n const [row, col] = position;\n const rowCells = matrix[row] ?? [];\n\n let target: HTMLElement | undefined;\n // Logical, not physical. The key is normalised rather than the\n // delta negated: these two branches are not mirror images — their guards\n // differ — so swapping the key keeps each guard with its own direction.\n switch (logicalArrowKey(event.key, this.element)) {\n case \"ArrowRight\":\n target = this.#cellInRow(matrix, row, col + 1);\n break;\n case \"ArrowLeft\":\n target = this.#cellInRow(matrix, row, Math.max(col - 1, 0));\n break;\n case \"ArrowDown\":\n target = this.#cellInRow(matrix, Math.min(row + 1, matrix.length - 1), col);\n break;\n case \"ArrowUp\":\n target = this.#cellInRow(matrix, Math.max(row - 1, 0), col);\n break;\n case \"Home\":\n target = event.ctrlKey ? this.#cellInRow(matrix, 0, 0) : rowCells[0];\n break;\n case \"End\":\n target = event.ctrlKey\n ? this.#cellInRow(matrix, matrix.length - 1, Number.POSITIVE_INFINITY)\n : rowCells[rowCells.length - 1];\n break;\n case \"Enter\":\n case \" \":\n this.#activate(cell);\n event.preventDefault();\n return;\n default:\n return;\n }\n\n if (target) {\n event.preventDefault();\n this.#setActiveCell(target, { focus: true });\n }\n }\n\n /** Performs a header's sort or a cell row's selection toggle on activation. */\n #activate(cell: HTMLElement): void {\n if (this.columnHeaderTargets.includes(cell)) {\n this.#cycleSort(cell);\n return;\n }\n if (this.selectionValue === \"none\") return;\n const row = cell.closest<HTMLElement>(\"[role='row']\");\n if (row && this.rowTargets.includes(row)) this.#toggleRow(row);\n }\n\n /** Shared sort logic for both click and keyboard activation. */\n #cycleSort(header: HTMLElement): void {\n const direction = nextSortDirection(header.getAttribute(\"aria-sort\") ?? \"none\");\n for (const other of this.columnHeaderTargets) {\n other.setAttribute(\"aria-sort\", other === header ? direction : \"none\");\n }\n this.dispatch(\"sort\", { detail: { column: header, direction } });\n }\n\n /** Toggles a row's `aria-selected`, honoring single vs. multiple selection. */\n #toggleRow(row: HTMLElement): void {\n const selected = row.getAttribute(\"aria-selected\") === \"true\";\n // Enforce single-ness on every toggle, not only when turning a row on:\n // switching one *off* would otherwise leave a second `true` behind, and\n // nothing else clears it for the rest of the session.\n if (this.selectionValue === \"single\") {\n for (const other of this.rowTargets) {\n if (other !== row) other.setAttribute(\"aria-selected\", \"false\");\n }\n }\n row.setAttribute(\"aria-selected\", selected ? \"false\" : \"true\");\n\n const rows = this.rowTargets.filter((r) => r.getAttribute(\"aria-selected\") === \"true\");\n this.dispatch(\"selectionchange\", { detail: { rows } });\n }\n\n /** Makes `cell` the single tabbable cell (roving) and optionally focuses it. */\n #setActiveCell(cell: HTMLElement | undefined, { focus }: { focus: boolean }): void {\n if (!cell) return;\n for (const candidate of this.#navigableCells()) {\n candidate.tabIndex = candidate === cell ? 0 : -1;\n }\n if (focus) cell.focus();\n }\n\n /** All navigable elements (headers + cells) in DOM order. */\n #navigableCells(): HTMLElement[] {\n return this.#matrix().flat();\n }\n\n /** The grid as rows of navigable cells, derived from each `role=\"row\"`. */\n #matrix(): HTMLElement[][] {\n const navigable = new Set<HTMLElement>([...this.columnHeaderTargets, ...this.cellTargets]);\n const rows = Array.from(this.element.querySelectorAll<HTMLElement>(\"[role='row']\"));\n return rows\n .map((row) =>\n Array.from(row.children).filter((child): child is HTMLElement =>\n navigable.has(child as HTMLElement),\n ),\n )\n .filter((cells) => cells.length > 0);\n }\n\n /** Finds `[rowIndex, colIndex]` of `cell` within `matrix`, or null. */\n #locate(matrix: HTMLElement[][], cell: HTMLElement): [number, number] | null {\n for (let row = 0; row < matrix.length; row++) {\n const col = (matrix[row] ?? []).indexOf(cell);\n if (col !== -1) return [row, col];\n }\n return null;\n }\n\n /** The cell at `[row, col]`, clamping `col` to that row's last cell. */\n #cellInRow(matrix: HTMLElement[][], row: number, col: number): HTMLElement | undefined {\n const cells = matrix[row];\n if (!cells || cells.length === 0) return undefined;\n return cells[Math.min(col, cells.length - 1)];\n }\n}\n"]}
@@ -55,6 +55,7 @@ declare class DateRangePickerController extends Controller<HTMLElement> {
55
55
  static actions: readonly ["applyPreset", "next", "onKeydown", "prev", "previewTo", "selectDate"];
56
56
  static events: readonly ["change"];
57
57
  readonly gridTarget: HTMLElement;
58
+ readonly hasGridTarget: boolean;
58
59
  readonly monthLabelTarget: HTMLElement;
59
60
  readonly cellTargets: HTMLElement[];
60
61
  readonly statusTarget: HTMLElement;