stimeo-ui 0.17.0 → 0.18.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 (297) hide show
  1. package/CHANGELOG.md +106 -1
  2. package/README.md +19 -10
  3. package/dist/cable/index.d.ts +9 -8
  4. package/dist/cable/index.js +22 -14
  5. package/dist/cable/index.js.map +1 -1
  6. package/dist/coerce-JtZVNG5h.d.ts +20 -0
  7. package/dist/controllers/accordion_controller.js +14 -6
  8. package/dist/controllers/accordion_controller.js.map +1 -1
  9. package/dist/controllers/alert_dialog_controller.js +145 -118
  10. package/dist/controllers/alert_dialog_controller.js.map +1 -1
  11. package/dist/controllers/announcer_controller.d.ts +5 -3
  12. package/dist/controllers/announcer_controller.js +113 -17
  13. package/dist/controllers/announcer_controller.js.map +1 -1
  14. package/dist/controllers/auto_submit_controller.js +185 -60
  15. package/dist/controllers/auto_submit_controller.js.map +1 -1
  16. package/dist/controllers/avatar_controller.js +55 -43
  17. package/dist/controllers/avatar_controller.js.map +1 -1
  18. package/dist/controllers/breadcrumb_controller.js.map +1 -1
  19. package/dist/controllers/bulk_select_controller.d.ts +3 -3
  20. package/dist/controllers/bulk_select_controller.js +64 -50
  21. package/dist/controllers/bulk_select_controller.js.map +1 -1
  22. package/dist/controllers/calendar_controller.d.ts +15 -12
  23. package/dist/controllers/calendar_controller.js +55 -53
  24. package/dist/controllers/calendar_controller.js.map +1 -1
  25. package/dist/controllers/carousel_controller.d.ts +9 -5
  26. package/dist/controllers/carousel_controller.js +124 -86
  27. package/dist/controllers/carousel_controller.js.map +1 -1
  28. package/dist/controllers/character_counter_controller.d.ts +27 -6
  29. package/dist/controllers/character_counter_controller.js +291 -95
  30. package/dist/controllers/character_counter_controller.js.map +1 -1
  31. package/dist/controllers/checkbox_controller.js +6 -0
  32. package/dist/controllers/checkbox_controller.js.map +1 -1
  33. package/dist/controllers/clipboard_controller.js +118 -27
  34. package/dist/controllers/clipboard_controller.js.map +1 -1
  35. package/dist/controllers/collapsible_controller.d.ts +1 -1
  36. package/dist/controllers/collapsible_controller.js +52 -49
  37. package/dist/controllers/collapsible_controller.js.map +1 -1
  38. package/dist/controllers/color_picker_controller.js +29 -7
  39. package/dist/controllers/color_picker_controller.js.map +1 -1
  40. package/dist/controllers/combobox_controller.d.ts +1 -1
  41. package/dist/controllers/combobox_controller.js +210 -71
  42. package/dist/controllers/combobox_controller.js.map +1 -1
  43. package/dist/controllers/command_palette_controller.d.ts +9 -9
  44. package/dist/controllers/command_palette_controller.js +289 -140
  45. package/dist/controllers/command_palette_controller.js.map +1 -1
  46. package/dist/controllers/conditional_fields_controller.js +145 -58
  47. package/dist/controllers/conditional_fields_controller.js.map +1 -1
  48. package/dist/controllers/confirm_controller.js +145 -118
  49. package/dist/controllers/confirm_controller.js.map +1 -1
  50. package/dist/controllers/context_menu_controller.d.ts +49 -14
  51. package/dist/controllers/context_menu_controller.js +138 -73
  52. package/dist/controllers/context_menu_controller.js.map +1 -1
  53. package/dist/controllers/count_up_controller.js.map +1 -1
  54. package/dist/controllers/countdown_controller.d.ts +2 -2
  55. package/dist/controllers/countdown_controller.js +109 -21
  56. package/dist/controllers/countdown_controller.js.map +1 -1
  57. package/dist/controllers/currency_input_controller.d.ts +75 -11
  58. package/dist/controllers/currency_input_controller.js +446 -72
  59. package/dist/controllers/currency_input_controller.js.map +1 -1
  60. package/dist/controllers/data_grid_controller.d.ts +10 -8
  61. package/dist/controllers/data_grid_controller.js +134 -28
  62. package/dist/controllers/data_grid_controller.js.map +1 -1
  63. package/dist/controllers/date_range_picker_controller.d.ts +12 -9
  64. package/dist/controllers/date_range_picker_controller.js +93 -72
  65. package/dist/controllers/date_range_picker_controller.js.map +1 -1
  66. package/dist/controllers/dialog_controller.d.ts +4 -5
  67. package/dist/controllers/dialog_controller.js +145 -118
  68. package/dist/controllers/dialog_controller.js.map +1 -1
  69. package/dist/controllers/direct_upload_controller.d.ts +1 -1
  70. package/dist/controllers/direct_upload_controller.js +24 -14
  71. package/dist/controllers/direct_upload_controller.js.map +1 -1
  72. package/dist/controllers/dirty_form_controller.d.ts +6 -1
  73. package/dist/controllers/dirty_form_controller.js +68 -31
  74. package/dist/controllers/dirty_form_controller.js.map +1 -1
  75. package/dist/controllers/dismissible_controller.js +64 -46
  76. package/dist/controllers/dismissible_controller.js.map +1 -1
  77. package/dist/controllers/drawer_controller.js +145 -118
  78. package/dist/controllers/drawer_controller.js.map +1 -1
  79. package/dist/controllers/dropdown_controller.js +76 -63
  80. package/dist/controllers/dropdown_controller.js.map +1 -1
  81. package/dist/controllers/editable_controller.js +199 -62
  82. package/dist/controllers/editable_controller.js.map +1 -1
  83. package/dist/controllers/empty_state_controller.js +13 -6
  84. package/dist/controllers/empty_state_controller.js.map +1 -1
  85. package/dist/controllers/file_dropzone_controller.d.ts +3 -0
  86. package/dist/controllers/file_dropzone_controller.js +55 -48
  87. package/dist/controllers/file_dropzone_controller.js.map +1 -1
  88. package/dist/controllers/filter_controller.js +9 -2
  89. package/dist/controllers/filter_controller.js.map +1 -1
  90. package/dist/controllers/flash_controller.d.ts +4 -4
  91. package/dist/controllers/flash_controller.js +66 -33
  92. package/dist/controllers/flash_controller.js.map +1 -1
  93. package/dist/controllers/focus_controller.d.ts +3 -3
  94. package/dist/controllers/focus_controller.js +39 -14
  95. package/dist/controllers/focus_controller.js.map +1 -1
  96. package/dist/controllers/form_field_controller.js +52 -43
  97. package/dist/controllers/form_field_controller.js.map +1 -1
  98. package/dist/controllers/form_validation_controller.d.ts +3 -3
  99. package/dist/controllers/form_validation_controller.js +18 -11
  100. package/dist/controllers/form_validation_controller.js.map +1 -1
  101. package/dist/controllers/frame_loading_controller.d.ts +13 -12
  102. package/dist/controllers/frame_loading_controller.js +55 -48
  103. package/dist/controllers/frame_loading_controller.js.map +1 -1
  104. package/dist/controllers/highlight_controller.d.ts +5 -4
  105. package/dist/controllers/highlight_controller.js.map +1 -1
  106. package/dist/controllers/hover_card_controller.d.ts +4 -1
  107. package/dist/controllers/hover_card_controller.js +67 -61
  108. package/dist/controllers/hover_card_controller.js.map +1 -1
  109. package/dist/controllers/idle_controller.d.ts +6 -5
  110. package/dist/controllers/idle_controller.js +10 -6
  111. package/dist/controllers/idle_controller.js.map +1 -1
  112. package/dist/controllers/input_mask_controller.d.ts +30 -13
  113. package/dist/controllers/input_mask_controller.js +411 -24
  114. package/dist/controllers/input_mask_controller.js.map +1 -1
  115. package/dist/controllers/intersection_controller.js +3 -0
  116. package/dist/controllers/intersection_controller.js.map +1 -1
  117. package/dist/controllers/lazy_frame_controller.d.ts +3 -2
  118. package/dist/controllers/lazy_frame_controller.js +15 -3
  119. package/dist/controllers/lazy_frame_controller.js.map +1 -1
  120. package/dist/controllers/listbox_controller.d.ts +10 -7
  121. package/dist/controllers/listbox_controller.js +260 -79
  122. package/dist/controllers/listbox_controller.js.map +1 -1
  123. package/dist/controllers/local_time_controller.d.ts +8 -6
  124. package/dist/controllers/local_time_controller.js +48 -13
  125. package/dist/controllers/local_time_controller.js.map +1 -1
  126. package/dist/controllers/masonry_controller.js +11 -4
  127. package/dist/controllers/masonry_controller.js.map +1 -1
  128. package/dist/controllers/menu_controller.d.ts +24 -5
  129. package/dist/controllers/menu_controller.js +138 -82
  130. package/dist/controllers/menu_controller.js.map +1 -1
  131. package/dist/controllers/menubar_controller.d.ts +49 -7
  132. package/dist/controllers/menubar_controller.js +65 -19
  133. package/dist/controllers/menubar_controller.js.map +1 -1
  134. package/dist/controllers/meter_controller.d.ts +13 -20
  135. package/dist/controllers/meter_controller.js +270 -24
  136. package/dist/controllers/meter_controller.js.map +1 -1
  137. package/dist/controllers/multi_select_controller.d.ts +17 -15
  138. package/dist/controllers/multi_select_controller.js +251 -94
  139. package/dist/controllers/multi_select_controller.js.map +1 -1
  140. package/dist/controllers/navigation_menu_controller.d.ts +19 -5
  141. package/dist/controllers/navigation_menu_controller.js +67 -19
  142. package/dist/controllers/navigation_menu_controller.js.map +1 -1
  143. package/dist/controllers/nested_form_controller.js +98 -64
  144. package/dist/controllers/nested_form_controller.js.map +1 -1
  145. package/dist/controllers/network_status_controller.js +70 -52
  146. package/dist/controllers/network_status_controller.js.map +1 -1
  147. package/dist/controllers/number_input_controller.d.ts +24 -6
  148. package/dist/controllers/number_input_controller.js +344 -94
  149. package/dist/controllers/number_input_controller.js.map +1 -1
  150. package/dist/controllers/optimistic_controller.d.ts +8 -5
  151. package/dist/controllers/optimistic_controller.js +29 -11
  152. package/dist/controllers/optimistic_controller.js.map +1 -1
  153. package/dist/controllers/otp_controller.d.ts +35 -4
  154. package/dist/controllers/otp_controller.js +502 -104
  155. package/dist/controllers/otp_controller.js.map +1 -1
  156. package/dist/controllers/overflow_indicator_controller.js +6 -0
  157. package/dist/controllers/overflow_indicator_controller.js.map +1 -1
  158. package/dist/controllers/overflow_menu_controller.d.ts +10 -9
  159. package/dist/controllers/overflow_menu_controller.js +136 -21
  160. package/dist/controllers/overflow_menu_controller.js.map +1 -1
  161. package/dist/controllers/pagination_controller.d.ts +3 -2
  162. package/dist/controllers/pagination_controller.js +47 -14
  163. package/dist/controllers/pagination_controller.js.map +1 -1
  164. package/dist/controllers/password_reveal_controller.d.ts +5 -4
  165. package/dist/controllers/password_reveal_controller.js +52 -49
  166. package/dist/controllers/password_reveal_controller.js.map +1 -1
  167. package/dist/controllers/password_strength_controller.d.ts +1 -1
  168. package/dist/controllers/password_strength_controller.js +13 -6
  169. package/dist/controllers/password_strength_controller.js.map +1 -1
  170. package/dist/controllers/persist_controller.js +48 -128
  171. package/dist/controllers/persist_controller.js.map +1 -1
  172. package/dist/controllers/pointer_drag_controller.d.ts +19 -8
  173. package/dist/controllers/pointer_drag_controller.js +249 -23
  174. package/dist/controllers/pointer_drag_controller.js.map +1 -1
  175. package/dist/controllers/popover_controller.d.ts +3 -3
  176. package/dist/controllers/popover_controller.js +82 -65
  177. package/dist/controllers/popover_controller.js.map +1 -1
  178. package/dist/controllers/portal_controller.js +6 -0
  179. package/dist/controllers/portal_controller.js.map +1 -1
  180. package/dist/controllers/preview_guard_controller.js +14 -3
  181. package/dist/controllers/preview_guard_controller.js.map +1 -1
  182. package/dist/controllers/progress_controller.d.ts +9 -19
  183. package/dist/controllers/progress_controller.js +271 -27
  184. package/dist/controllers/progress_controller.js.map +1 -1
  185. package/dist/controllers/radio_group_controller.d.ts +11 -8
  186. package/dist/controllers/radio_group_controller.js +167 -80
  187. package/dist/controllers/radio_group_controller.js.map +1 -1
  188. package/dist/controllers/range_slider_controller.d.ts +4 -3
  189. package/dist/controllers/range_slider_controller.js +27 -7
  190. package/dist/controllers/range_slider_controller.js.map +1 -1
  191. package/dist/controllers/rating_controller.js +93 -57
  192. package/dist/controllers/rating_controller.js.map +1 -1
  193. package/dist/controllers/read_more_controller.js +10 -6
  194. package/dist/controllers/read_more_controller.js.map +1 -1
  195. package/dist/controllers/reading_progress_controller.js +22 -5
  196. package/dist/controllers/reading_progress_controller.js.map +1 -1
  197. package/dist/controllers/relative_time_controller.d.ts +4 -4
  198. package/dist/controllers/relative_time_controller.js +75 -11
  199. package/dist/controllers/relative_time_controller.js.map +1 -1
  200. package/dist/controllers/reset_on_restore_controller.d.ts +3 -3
  201. package/dist/controllers/reset_on_restore_controller.js +6 -0
  202. package/dist/controllers/reset_on_restore_controller.js.map +1 -1
  203. package/dist/controllers/resizable_controller.d.ts +3 -0
  204. package/dist/controllers/resizable_controller.js +55 -22
  205. package/dist/controllers/resizable_controller.js.map +1 -1
  206. package/dist/controllers/roving_controller.d.ts +3 -3
  207. package/dist/controllers/roving_controller.js +10 -4
  208. package/dist/controllers/roving_controller.js.map +1 -1
  209. package/dist/controllers/scroll_area_controller.js +129 -88
  210. package/dist/controllers/scroll_area_controller.js.map +1 -1
  211. package/dist/controllers/scroll_restore_controller.d.ts +3 -3
  212. package/dist/controllers/scroll_restore_controller.js +14 -2
  213. package/dist/controllers/scroll_restore_controller.js.map +1 -1
  214. package/dist/controllers/scroll_visibility_controller.js +93 -60
  215. package/dist/controllers/scroll_visibility_controller.js.map +1 -1
  216. package/dist/controllers/scrollspy_controller.js +11 -5
  217. package/dist/controllers/scrollspy_controller.js.map +1 -1
  218. package/dist/controllers/separator_controller.d.ts +1 -1
  219. package/dist/controllers/separator_controller.js +59 -43
  220. package/dist/controllers/separator_controller.js.map +1 -1
  221. package/dist/controllers/sidebar_controller.d.ts +1 -1
  222. package/dist/controllers/sidebar_controller.js +150 -122
  223. package/dist/controllers/sidebar_controller.js.map +1 -1
  224. package/dist/controllers/skeleton_controller.js +55 -48
  225. package/dist/controllers/skeleton_controller.js.map +1 -1
  226. package/dist/controllers/slider_controller.d.ts +2 -1
  227. package/dist/controllers/slider_controller.js +27 -6
  228. package/dist/controllers/slider_controller.js.map +1 -1
  229. package/dist/controllers/smart_sticky_header_controller.d.ts +1 -1
  230. package/dist/controllers/smart_sticky_header_controller.js +13 -5
  231. package/dist/controllers/smart_sticky_header_controller.js.map +1 -1
  232. package/dist/controllers/sortable_controller.d.ts +4 -4
  233. package/dist/controllers/sortable_controller.js +27 -14
  234. package/dist/controllers/sortable_controller.js.map +1 -1
  235. package/dist/controllers/spinner_controller.js +55 -48
  236. package/dist/controllers/spinner_controller.js.map +1 -1
  237. package/dist/controllers/step_indicator_controller.d.ts +4 -4
  238. package/dist/controllers/step_indicator_controller.js +6 -0
  239. package/dist/controllers/step_indicator_controller.js.map +1 -1
  240. package/dist/controllers/stepper_controller.d.ts +2 -3
  241. package/dist/controllers/stepper_controller.js +6 -0
  242. package/dist/controllers/stepper_controller.js.map +1 -1
  243. package/dist/controllers/stick_to_bottom_controller.d.ts +3 -1
  244. package/dist/controllers/stick_to_bottom_controller.js +19 -8
  245. package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
  246. package/dist/controllers/sticky_observer_controller.js +49 -43
  247. package/dist/controllers/sticky_observer_controller.js.map +1 -1
  248. package/dist/controllers/submit_once_controller.d.ts +2 -1
  249. package/dist/controllers/submit_once_controller.js +145 -85
  250. package/dist/controllers/submit_once_controller.js.map +1 -1
  251. package/dist/controllers/switch_controller.d.ts +7 -4
  252. package/dist/controllers/switch_controller.js +172 -28
  253. package/dist/controllers/switch_controller.js.map +1 -1
  254. package/dist/controllers/tabs_controller.d.ts +7 -4
  255. package/dist/controllers/tabs_controller.js +6 -1
  256. package/dist/controllers/tabs_controller.js.map +1 -1
  257. package/dist/controllers/tags_input_controller.d.ts +4 -3
  258. package/dist/controllers/tags_input_controller.js +157 -28
  259. package/dist/controllers/tags_input_controller.js.map +1 -1
  260. package/dist/controllers/textarea_autosize_controller.d.ts +1 -1
  261. package/dist/controllers/textarea_autosize_controller.js +40 -19
  262. package/dist/controllers/textarea_autosize_controller.js.map +1 -1
  263. package/dist/controllers/theme_controller.d.ts +3 -2
  264. package/dist/controllers/theme_controller.js +10 -4
  265. package/dist/controllers/theme_controller.js.map +1 -1
  266. package/dist/controllers/time_picker_controller.d.ts +38 -5
  267. package/dist/controllers/time_picker_controller.js +192 -54
  268. package/dist/controllers/time_picker_controller.js.map +1 -1
  269. package/dist/controllers/toast_controller.d.ts +4 -5
  270. package/dist/controllers/toast_controller.js +58 -27
  271. package/dist/controllers/toast_controller.js.map +1 -1
  272. package/dist/controllers/toggle_group_controller.d.ts +2 -3
  273. package/dist/controllers/toggle_group_controller.js +158 -56
  274. package/dist/controllers/toggle_group_controller.js.map +1 -1
  275. package/dist/controllers/toolbar_controller.d.ts +8 -6
  276. package/dist/controllers/toolbar_controller.js +150 -21
  277. package/dist/controllers/toolbar_controller.js.map +1 -1
  278. package/dist/controllers/tooltip_controller.d.ts +4 -1
  279. package/dist/controllers/tooltip_controller.js.map +1 -1
  280. package/dist/controllers/transition_controller.js.map +1 -1
  281. package/dist/controllers/tree_view_controller.d.ts +1 -1
  282. package/dist/controllers/tree_view_controller.js +134 -25
  283. package/dist/controllers/tree_view_controller.js.map +1 -1
  284. package/dist/index.d.ts +2 -0
  285. package/dist/index.js +2451 -1312
  286. package/dist/index.js.map +1 -1
  287. package/dist/inspector/cli.d.ts +15 -11
  288. package/dist/inspector/cli.js +16 -3
  289. package/dist/inspector/cli.js.map +1 -1
  290. package/dist/inspector/cli_bin.js +53 -8
  291. package/dist/inspector/cli_bin.js.map +1 -1
  292. package/dist/inspector/examples.json +13 -13
  293. package/dist/inspector/manifest.json +19 -5
  294. package/dist/positioning/index.d.ts +7 -7
  295. package/dist/positioning/index.js +6 -0
  296. package/dist/positioning/index.js.map +1 -1
  297. package/package.json +10 -9
@@ -51,10 +51,12 @@ import { Controller } from '@hotwired/stimulus';
51
51
  * region beside the new stand-in or an authored target.
52
52
  *
53
53
  * **A restored page does not read out an earlier message.** A region holding a
54
- * message this controller wrote carries `data-<identifier>-announced` until the message
54
+ * message this controller wrote carries `["text", original, written]` in
55
+ * `data-<identifier>-announced` until the message
55
56
  * is cleared after `clearAfter`. The teardown drops the clearing timers, so a connection
56
- * that is not the other half of a move empties every marked authored region it finds;
57
- * an authored region's own initial text carries no mark and stays. Nothing is dropped or emptied on `turbo:before-cache`, which Turbo
57
+ * that is not the other half of a move empties only a region still holding that
58
+ * recorded text alone. Authored replacements, element children, and invalid records
59
+ * stay. Nothing is dropped or emptied on `turbo:before-cache`, which Turbo
58
60
  * also dispatches on pages that stay (a promoted frame navigation, a state-less
59
61
  * `popstate`, a refresh of a cached URL): the messages queued there are still read.
60
62
  *
@@ -97,6 +97,17 @@ var KeyedTimers = class {
97
97
  }
98
98
  };
99
99
 
100
+ var ListenerSet = class {
101
+ #abort = new AbortController();
102
+ add(target, type, handler, options) {
103
+ target.addEventListener(type, handler, { ...options, signal: this.#abort.signal });
104
+ }
105
+ dispose() {
106
+ this.#abort.abort();
107
+ this.#abort = new AbortController();
108
+ }
109
+ };
110
+
100
111
  var MicrotaskCoalescer = class {
101
112
  #run;
102
113
  #queued = false;
@@ -113,6 +124,9 @@ var MicrotaskCoalescer = class {
113
124
  this.#queued = false;
114
125
  this.#generation += 1;
115
126
  }
127
+ get pending() {
128
+ return this.#queued;
129
+ }
116
130
  schedule() {
117
131
  if (!this.#active || this.#queued) return;
118
132
  this.#queued = true;
@@ -169,6 +183,94 @@ var NumberValueReader = class {
169
183
  }
170
184
  };
171
185
 
186
+ function setAttributeIfChanged(element, name, value, beforeWrite) {
187
+ if (element.getAttribute(name) === value) return false;
188
+ if (value === null) element.removeAttribute(name);
189
+ else element.setAttribute(name, value);
190
+ return true;
191
+ }
192
+
193
+ var OwnedText = class {
194
+ #attribute;
195
+ #channel;
196
+ #guard;
197
+ #writes = /* @__PURE__ */ new WeakMap();
198
+ constructor(attribute, channel = "text", guard = () => true) {
199
+ this.#attribute = attribute;
200
+ this.#channel = channel;
201
+ this.#guard = guard;
202
+ }
203
+ hasRecord(element) {
204
+ return element.hasAttribute(this.#attribute);
205
+ }
206
+ read(element, evidence = {}) {
207
+ if (evidence.source === "live") return this.#writes.get(element) ?? null;
208
+ const raw = element.getAttribute(this.#attribute);
209
+ if (raw === null) return null;
210
+ try {
211
+ const record = JSON.parse(raw);
212
+ if (!Array.isArray(record) || record.length !== 3 || record[0] !== this.#channel || typeof record[1] !== "string" || typeof record[2] !== "string")
213
+ return null;
214
+ return { original: record[1], written: record[2] };
215
+ } catch {
216
+ return null;
217
+ }
218
+ }
219
+ owns(element, evidence = {}) {
220
+ return this.#ownedRecord(element, evidence) !== null;
221
+ }
222
+ #ownedRecord(element, evidence) {
223
+ const record = this.read(element, evidence);
224
+ if (record === null || !this.#guard(element)) return null;
225
+ if (this.#channel === "text" && element.firstElementChild !== null) return null;
226
+ const current = this.#current(element);
227
+ return current === record.written || evidence.source === "live" && evidence.allowOriginal === true && current === record.original ? record : null;
228
+ }
229
+ write(element, written, original, force = false) {
230
+ const current = this.#current(element);
231
+ if (current === null) return;
232
+ const before = original ?? this.#writes.get(element)?.original ?? this.read(element)?.original ?? current;
233
+ if (force || current !== written) this.#put(element, written);
234
+ this.remember(element, written, before);
235
+ }
236
+ remember(element, written, original) {
237
+ const current = this.#current(element);
238
+ if (current === null) return;
239
+ const before = original ?? this.#writes.get(element)?.original ?? this.read(element)?.original ?? current;
240
+ this.#writes.set(element, { original: before, written });
241
+ setAttributeIfChanged(
242
+ element,
243
+ this.#attribute,
244
+ JSON.stringify([this.#channel, before, written])
245
+ );
246
+ }
247
+ clear(element, evidence = {}) {
248
+ if (!this.owns(element, evidence)) return false;
249
+ if (this.#current(element) !== "") this.#put(element, "");
250
+ this.forget(element);
251
+ return true;
252
+ }
253
+ restore(element, evidence = {}) {
254
+ const record = this.#ownedRecord(element, evidence);
255
+ if (record === null) return false;
256
+ if (this.#current(element) !== record.original) this.#put(element, record.original);
257
+ this.forget(element);
258
+ return true;
259
+ }
260
+ forget(element) {
261
+ setAttributeIfChanged(element, this.#attribute, null);
262
+ this.#writes.delete(element);
263
+ }
264
+ #current(element) {
265
+ if (this.#channel === "text") return element.textContent ?? "";
266
+ return element instanceof HTMLInputElement ? element.value : null;
267
+ }
268
+ #put(element, text) {
269
+ if (this.#channel === "text") element.textContent = text;
270
+ else if (element instanceof HTMLInputElement) element.value = text;
271
+ }
272
+ };
273
+
172
274
  var LEVELS = ["polite", "assertive"];
173
275
  var STAND_IN = "stand-in";
174
276
  var ANNOUNCED = "announced";
@@ -185,14 +287,13 @@ var AnnouncerController = class _AnnouncerController extends Controller {
185
287
  static actions = ["announce"];
186
288
  #timers = new SafeTimeout();
187
289
  #gate = new DetachGate();
290
+ #listeners = new ListenerSet();
188
291
  #regionTimers = new KeyedTimers();
189
292
  #generated = /* @__PURE__ */ new Map();
190
293
  get #standIn() {
191
294
  return `data-${this.identifier}-${STAND_IN}`;
192
295
  }
193
- get #announced() {
194
- return `data-${this.identifier}-${ANNOUNCED}`;
195
- }
296
+ #messageText = new OwnedText(`data-${this.identifier}-${ANNOUNCED}`);
196
297
  #queues = /* @__PURE__ */ new Map();
197
298
  #draining = /* @__PURE__ */ new Set();
198
299
  #reconcile = new MicrotaskCoalescer(() => this.#reconcileRegions());
@@ -217,8 +318,8 @@ var AnnouncerController = class _AnnouncerController extends Controller {
217
318
  this.#emptyInheritedMessages();
218
319
  this.#reconcileRegions();
219
320
  this.#hostWatch.observe(this.element, { childList: true });
220
- this.element.addEventListener("stimeo--announcer:announce", this.#onAnnounceEvent);
221
- window.addEventListener("stimeo--announcer:announce", this.#onAnnounceEvent);
321
+ this.#listeners.add(this.element, "stimeo--announcer:announce", this.#onAnnounceEvent);
322
+ this.#listeners.add(window, "stimeo--announcer:announce", this.#onAnnounceEvent);
222
323
  }
223
324
  disconnect() {
224
325
  this.#gate.disconnected(this, () => this.#teardown());
@@ -226,8 +327,7 @@ var AnnouncerController = class _AnnouncerController extends Controller {
226
327
  #teardown() {
227
328
  this.#reconcile.cancel();
228
329
  this.#hostWatch.disconnect();
229
- this.element.removeEventListener("stimeo--announcer:announce", this.#onAnnounceEvent);
230
- window.removeEventListener("stimeo--announcer:announce", this.#onAnnounceEvent);
330
+ this.#listeners.dispose();
231
331
  this.#timers.clearAll();
232
332
  this.#regionTimers.clearAll();
233
333
  this.#queues.clear();
@@ -279,9 +379,7 @@ var AnnouncerController = class _AnnouncerController extends Controller {
279
379
  }
280
380
  #emptyInheritedMessages() {
281
381
  for (const region of [...this.politeTargets, ...this.assertiveTargets]) {
282
- if (!region.hasAttribute(this.#announced)) continue;
283
- region.replaceChildren();
284
- region.removeAttribute(this.#announced);
382
+ this.#messageText.clear(region);
285
383
  }
286
384
  }
287
385
  #removeGenerated() {
@@ -325,24 +423,22 @@ var AnnouncerController = class _AnnouncerController extends Controller {
325
423
  }
326
424
  if (this.dedupeReannounceValue && region.textContent === message) {
327
425
  region.textContent = "";
426
+ this.#messageText.forget(region);
328
427
  this.#scheduleDrain(level);
329
428
  return;
330
429
  }
331
430
  queue.shift();
332
431
  this.#regionTimers.clear(region);
333
- region.textContent = message;
334
- region.setAttribute(this.#announced, "");
335
- this.#scheduleClear(region, message);
432
+ this.#messageText.write(region, message, void 0, true);
433
+ this.#scheduleClear(region);
336
434
  if (queue.length > 0) this.#scheduleDrain(level);
337
435
  }
338
- #scheduleClear(region, message) {
436
+ #scheduleClear(region) {
339
437
  if (this.#safeClearAfter <= 0) return;
340
438
  this.#regionTimers.set(
341
439
  region,
342
440
  () => {
343
- if (region.textContent !== message) return;
344
- region.textContent = "";
345
- region.removeAttribute(this.#announced);
441
+ this.#messageText.clear(region);
346
442
  },
347
443
  this.#safeClearAfter
348
444
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/detach_gate.ts","../../src/utils/timer_bounds.ts","../../src/utils/safe_timeout.ts","../../src/utils/keyed_timers.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/number_bounds.ts","../../src/utils/coerce.ts","../../src/utils/number_value.ts","../../src/controllers/announcer_controller.ts"],"names":[],"mappings":";;AAsFO,IAAM,UAAA,GAAN,MAAM,WAAA,CAAW;AAAA,EAEtB,QAAA,GAAW,KAAA;AAAA,EASX,IAAI,OAAA,GAAmB;AACrB,IAAA,OAAO,IAAA,CAAK,QAAA;AAAA,EACd;AAAA,EAOA,OAAO,WAAW,IAAA,EAA+B;AAC/C,IAAA,OAAO,CAAC,IAAA,CAAK,OAAA,CAAQ,eAAe,CAAC,WAAA,CAAW,QAAQ,IAAI,CAAA;AAAA,EAC9D;AAAA,EAWA,YAAA,CAAa,MAAsB,QAAA,EAA4B;AAC7D,IAAA,MAAM,OAAA,GAAU,WAAA,CAAW,QAAA,CAAS,IAAI,CAAA;AACxC,IAAA,IAAI,CAAC,OAAA,IAAW,WAAA,CAAW,UAAA,CAAW,IAAI,CAAA,EAAG;AAG3C,MAAA,IAAA,CAAK,QAAA,GAAW,KAAA;AAChB,MAAA,QAAA,EAAS;AACT,MAAA;AAAA,IACF;AACA,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA;AAChB,IAAA,MAAM,QAAQ,MAAY;AACxB,MAAA,IAAI,CAAC,KAAK,QAAA,EAAU;AACpB,MAAA,IAAA,CAAK,QAAA,GAAW,KAAA;AAChB,MAAA,QAAA,EAAS;AAAA,IACX,CAAA;AACA,IAAA,IAAI,OAAA,EAAS,UAAA,CAAW,KAAA,E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AS,KAAA;AACf,EAAA,KAAA,CAAM,MAAA,GAAS,MAAA;AACf,EAAA,KAAA,CAAM,OAAA,GAAU,GAAA;AAChB,EAAA,KAAA,CAAM,MAAA,GAAS,GAAA;AACf,EAAA,KAAA,CAAM,QAAA,GAAW,QAAA;AACjB,EAAA,KAAA,CAAM,IAAA,GAAO,eAAA;AACb,EAAA,KAAA,CAAM,QAAA,GAAW,YAAA;AACjB,EAAA,KAAA,CAAM,UAAA,GAAa,QAAA;AACrB","file":"announcer_controller.js","sourcesContent":["/**\n * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * An element out of the document is a real detach, with one exception: a\n * `data-turbo-permanent` element, or one inside it, that Turbo carries to the\n * next page. Turbo takes it out of the old `<body>`, which Stimulus answers with\n * a `disconnect()` while it is out of the document, and puts it into the new one\n * a few microtasks later in the same task, where the same instance connects\n * again. Such a disconnect is probed until the next task instead.\n *\n * Policy stays with the consumer; this util owns the discrimination only:\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * dismiss(): void {\n * this.#gate.cancel(); // a direct path: disarm a probe a disconnect queued\n * this.#teardown();\n * }\n *\n * #teardown(): void {\n * // … (`disconnected` has already disarmed the probe on its own path)\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True while a probe is queued — the last disconnect was ambiguous and no\n * reconnect has cancelled it yet. Read it from `connect()` to tell the\n * reconnect half of an in-page move from a first connect: a controller whose\n * initialisation restarts a measurement (a min-duration floor, an elapsed\n * counter) must skip it for the move, where nothing actually restarted.\n */\n get pending(): boolean {\n return this.#pending;\n }\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n return !host.element.isConnected || !DetachGate.#listed(host);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains. An\n * element Turbo carries to the next page is probed until the next task, by\n * which time Turbo has put it back.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n const carried = DetachGate.#carried(host);\n if (!carried && DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n const probe = (): void => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n };\n if (carried) setTimeout(probe, 0);\n else queueMicrotask(probe);\n }\n\n /**\n * Whether `host` is out of the document inside a `data-turbo-permanent` element, its\n * identifier still listed: where Turbo holds an element it carries to the next page.\n */\n static #carried(host: DetachGateHost): boolean {\n const element = host.element;\n return (\n !element.isConnected &&\n element.closest(\"[data-turbo-permanent]\") !== null &&\n DetachGate.#listed(host)\n );\n }\n\n /** Whether the element's `data-controller` still lists the identifier. */\n static #listed(host: DetachGateHost): boolean {\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return tokens.includes(host.identifier);\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","/**\n * Largest delay a timer can hold: the platform stores it in a 32-bit signed\n * integer, and anything larger overflows to `1`, so a delay meant to be far in\n * the future fires almost immediately. A declared delay above this bound names\n * no delay at all, and a controller reading one falls back to its default.\n */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\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\nexport { MAX_TIMER_DELAY_MS } from \"./timer_bounds\";\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { SafeTimeout } from \"./safe_timeout\";\n\n/**\n * Keeps at most one pending timer per key, and releases them all together.\n *\n * A region, a row, a message or a speaker that is armed again while its earlier\n * timer is still pending must end up with exactly one timer deciding when its\n * state ends. Two timers on one key means the earlier deadline wins: it cuts the\n * new emphasis short, clears text written after it, or drops a speaker who is\n * still typing — and then reports an ending for a state that is already gone.\n * Arming through this registry cancels the key's earlier timer in the same step,\n * and no timer id ever reaches the caller.\n *\n * An entry lives exactly as long as its timer: it goes as the timer fires, and\n * the whole ledger goes on `clearAll()`. That is a correctness rule, not\n * tidiness — a platform may hand an id released by `clearTimeout` to the next\n * timer it creates, so an entry that outlived its timer would let a later\n * `clear()` on that key cancel whatever timer now holds the id, on some other\n * key entirely.\n *\n * The ledger is a plain `Map`, and the key may be anything. Weak keys would\n * retain nothing less: while a timer is pending the platform already holds the\n * key through the callback, and the entry is gone the moment the timer is.\n *\n * Scope is the one-per-key timer only. What the timer means, and the roster of\n * keys it is armed for, stay with the consumer, so a second kind of timer on the\n * same keys (a transition wait, an animation frame) is a second registry, and a\n * timer that belongs to no key stays on a plain `SafeTimeout`.\n *\n * @example\n * ```ts\n * readonly #expiry = new KeyedTimers<string>();\n *\n * #onSignal(name: string): void {\n * this.#expiry.set(name, () => this.#drop(name), this.#timeout);\n * }\n *\n * disconnect(): void {\n * this.#expiry.clearAll();\n * }\n * ```\n */\nexport class KeyedTimers<K> {\n readonly #timers = new SafeTimeout();\n\n /** The pending timer of each key; an entry lives exactly as long as its timer. */\n readonly #pending = new Map<K, number>();\n\n /**\n * Arms `callback` after `delay` ms for `key`, cancelling the timer `key` had\n * pending. The entry is dropped before the callback runs, so the callback sees\n * the key unarmed and may arm it again for the next round.\n */\n set(key: K, callback: () => void, delay: number): void {\n this.clear(key);\n const id = this.#timers.set(() => {\n this.#pending.delete(key);\n callback();\n }, delay);\n this.#pending.set(key, id);\n }\n\n /**\n * Cancels `key`'s pending timer, if it has one.\n *\n * A timer id is a positive integer, so `-1` stands for \"nothing pending\" and\n * the registry ignores an id it does not own — the unarmed case needs no\n * branch of its own, and no other key's timer can be reached from here.\n */\n clear(key: K): void {\n this.#timers.clear(this.#pending.get(key) ?? -1);\n this.#pending.delete(key);\n }\n\n /**\n * Cancels every pending timer and forgets every key. Call this from a\n * controller's `disconnect()` so no timer, and no entry, outlives the element.\n */\n clearAll(): void {\n this.#timers.clearAll();\n this.#pending.clear();\n }\n\n /** Whether `key` has a timer pending. */\n has(key: K): boolean {\n return this.#pending.has(key);\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { MAX_TIMER_DELAY_MS } from \"./timer_bounds\";\n\n/** Semantic constraints on an already decoded number, independent of the DOM. */\nexport interface NumberBounds {\n /** Finite numbers are required, including when this field is omitted. */\n readonly finite?: true;\n /** Inclusive lower endpoint. */\n readonly min?: number;\n /** Inclusive upper endpoint. */\n readonly max?: number;\n /** Exclusive lower endpoint. */\n readonly exclusiveMin?: number;\n /** Require a number without a fractional part. */\n readonly integer?: boolean;\n /** Exact decoded numbers accepted by a discrete contract. */\n readonly allowedValues?: readonly number[];\n /** JSON-safe exceptions to finite-number checking for unbounded endpoints. */\n readonly allowInfinity?: \"negative\" | \"positive\" | \"both\";\n}\n\n/** One constraint for each Number Value, including shorthand declarations. */\nexport type NumberValueConstraints<Values> = {\n readonly [Key in keyof Values as Values[Key] extends\n | NumberConstructor\n | { type: NumberConstructor }\n ? Key\n : never]: NumberBounds;\n};\n\n/** Reusable semantic domains; fractional inputs remain fractional unless excluded. */\nexport const NUMBER_BOUNDS = {\n finite: { finite: true },\n nonNegative: { finite: true, min: 0 },\n positive: { finite: true, exclusiveMin: 0 },\n nonNegativeInteger: { finite: true, min: 0, integer: true },\n positiveInteger: { finite: true, exclusiveMin: 0, integer: true },\n lowerBound: { finite: true, allowInfinity: \"negative\" },\n upperBound: { finite: true, allowInfinity: \"positive\" },\n timer: { finite: true, min: 0, max: MAX_TIMER_DELAY_MS },\n positiveTimer: { finite: true, exclusiveMin: 0, max: MAX_TIMER_DELAY_MS },\n} as const satisfies Record<string, NumberBounds>;\n\n/**\n * Checks all declared bounds without rounding, clamping, or coercing the input.\n * Infinity exceptions relax only finite checking; every other bound still applies.\n */\nexport function matchesNumberBounds(value: number, bounds: NumberBounds): boolean {\n if (!Number.isFinite(value)) {\n const direction = value === Infinity ? \"positive\" : value === -Infinity ? \"negative\" : null;\n if (direction === null) return false;\n if (bounds.allowInfinity !== \"both\" && bounds.allowInfinity !== direction) return false;\n }\n if (bounds.min !== undefined && value < bounds.min) return false;\n if (bounds.max !== undefined && value > bounds.max) return false;\n if (bounds.exclusiveMin !== undefined && value <= bounds.exclusiveMin) return false;\n if (bounds.integer && !Number.isInteger(value)) return false;\n if (bounds.allowedValues !== undefined && !bounds.allowedValues.includes(value)) return false;\n return true;\n}\n\n/** Decodes a Number Value literal; action params use their own JSON decoder. */\nexport function decodeNumberValue(raw: string): number {\n return Number(raw.replace(/_/g, \"\"));\n}\n","/**\n * Numeric coercion for controllers that accept a number through a Value, an action\n * param, or an event detail.\n *\n * Stimulus decodes action params as JSON when possible and leaves other text\n * untouched. CustomEvent detail can also supply a number or numeric string.\n * The reader accepts those two types while rejecting blank and non-finite input.\n */\n\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/**\n * Reads a finite number or nonblank numeric string; other input returns `null`.\n * Blank strings cannot silently reset a value to zero.\n */\nexport function toFiniteNumber(raw: unknown): number | null {\n if (typeof raw !== \"number\" && typeof raw !== \"string\") return null;\n if (typeof raw === \"string\" && raw.trim().length === 0) return null;\n const value = Number(raw);\n return Number.isFinite(value) ? value : null;\n}\n\n/**\n * Returns an accepted decoded Number Value or the caller's fallback unchanged.\n * The caller owns the fallback contract; this reader does not parse or write a Value.\n */\nexport function readNumber(raw: number, fallback: number, bounds: NumberBounds): number {\n return matchesNumberBounds(raw, bounds) ? raw : fallback;\n}\n","import { readNumber } from \"./coerce\";\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/** The instance identity carried by a Number Value read. */\nexport interface NumberValueOwner {\n readonly identifier: string;\n readonly element: Element;\n}\n\n/** Reads current declarations at the point of use without rewriting their attributes. */\nexport class NumberValueReader {\n /** The last rejected literal per Value; no history grows for an unchanged instance. */\n readonly #lastRejected = new Map<string, string>();\n\n /** Resolves the declared number using its own fallback and shared class contract. */\n read(\n owner: NumberValueOwner,\n name: string,\n raw: number,\n fallback: number,\n bounds: NumberBounds,\n ): number {\n const resolved = readNumber(raw, fallback, bounds);\n if (matchesNumberBounds(raw, bounds)) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n const attribute = `data-${owner.identifier}-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}-value`;\n const literal = owner.element.getAttribute(attribute);\n if (literal === null) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n if (this.#lastRejected.get(name) !== literal) {\n this.#lastRejected.set(name, literal);\n console.warn(\n `Stimeo UI: \"${owner.identifier}\" has an invalid number Value \"${name}\" declaration ${JSON.stringify(literal)}; using ${fallback}.`,\n );\n }\n return resolved;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { DetachGate } from \"../utils/detach_gate\";\nimport { KeyedTimers } from \"../utils/keyed_timers\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { NUMBER_BOUNDS, type NumberValueConstraints } from \"../utils/number_bounds\";\nimport { NumberValueReader } from \"../utils/number_value\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** The two politeness levels this controller keeps a region for. */\nconst LEVELS = [\"polite\", \"assertive\"] as const;\n\n/** One of the politeness levels in {@link LEVELS}. */\ntype Level = (typeof LEVELS)[number];\n\n/** Suffix of the marker on a live region this controller generated; see the class remarks. */\nconst STAND_IN = \"stand-in\";\n\n/** Suffix of the marker on a region holding a message this controller wrote. */\nconst ANNOUNCED = \"announced\";\n\n/**\n * Headless, shared **live-region announcer** — a polite/assertive screen-reader\n * announcement base (no dedicated APG pattern; follows the WAI-ARIA \"Alert\" /\n * \"Status\" live-region guidance and WCAG 2.2 **4.1.3 Status Messages**).\n *\n * Markup contract (identifier: `stimeo--announcer`):\n * <!-- Place once per page; the consumer visually hides the regions in CSS. -->\n * <div data-controller=\"stimeo--announcer\">\n * <div data-stimeo--announcer-target=\"polite\" aria-live=\"polite\" aria-atomic=\"true\"></div>\n * <div data-stimeo--announcer-target=\"assertive\" aria-live=\"assertive\" aria-atomic=\"true\"></div>\n * </div>\n *\n * <!-- Attribute-only trigger: declare the activation event explicitly. -->\n * <button data-action=\"click->stimeo--announcer#announce\"\n * data-stimeo--announcer-message-param=\"Saved\"\n * data-stimeo--announcer-assertive-param=\"false\">Save</button>\n *\n * <!-- Programmatic trigger (e.g. from another controller / Turbo Stream). -->\n * window.dispatchEvent(new CustomEvent(\"stimeo--announcer:announce\", {\n * detail: { message: \"12 results\", assertive: false },\n * }))\n *\n * The announcer is the shared live region other controllers hand their messages\n * to (`stimeo--auto-submit`, `stimeo--flash` and `stimeo--bulk-select` among\n * them) instead of each carrying their own.\n *\n * @remarks\n * Behavior only, with **one deliberate exception**: when a `polite`/`assertive`\n * target is absent the controller *generates* the missing region **on connect**\n * and applies the canonical visually-hidden inline style (see {@link visuallyHide}).\n * A live region must exist and be visually hidden to do its job, and a generated\n * node has no consumer CSS hook to hide it; consumers who want to own styling\n * supply their own targets. Generation happens up front rather than on the first\n * announcement because assistive tech reports changes to a region it already\n * knows about — a region created and written within one task loses that first\n * message. The controller never moves focus — announcements must not steal it\n * (WCAG 2.2 4.1.3). Listeners, the queues and the clear timers are torn down, and any\n * generated regions removed, once the element is really detached. An in-page move,\n * and a `data-turbo-permanent` announcer Turbo carries to the next page, reconnect\n * the same instance with all of them in place, so what was queued is still read and a\n * message on display is still cleared on time.\n *\n * **Generated regions are marked, so a restore never doubles them.** Each\n * stand-in carries `data-<identifier>-stand-in`. The region set is kept whole until\n * the controller is detached, so a stand-in can reach a copy of the page — a page Turbo\n * restores from its cache is one. The teardown removes the stand-ins a connection\n * generated, so a marked child a host arrives with came from an earlier one:\n * `connect()` drops it before generating its own, and it never sits as a second\n * region beside the new stand-in or an authored target.\n *\n * **A restored page does not read out an earlier message.** A region holding a\n * message this controller wrote carries `data-<identifier>-announced` until the message\n * is cleared after `clearAfter`. The teardown drops the clearing timers, so a connection\n * that is not the other half of a move empties every marked authored region it finds;\n * an authored region's own initial text carries no mark and stays. Nothing is dropped or emptied on `turbo:before-cache`, which Turbo\n * also dispatches on pages that stay (a promoted frame navigation, a state-less\n * `popstate`, a refresh of a cached URL): the messages queued there are still read.\n *\n * **Messages are queued, one write per task.** Assistive tech announces what it\n * observes changing, so two messages written into one region within a single task\n * are one observed change and the earlier message is never read. Each politeness\n * has its own FIFO — an assertive message never waits behind polite ones — and a\n * message is written only in a task where its region already existed.\n *\n * **The region set is kept whole while connected.** Exactly one region per\n * politeness is present: an authored target retires the stand-in generated for it,\n * losing one materialises a stand-in again, and a generated region removed by a\n * morph (it is absent from the server's HTML, so a morph drops it) is put back\n * without waiting for the next message.\n */\nexport class AnnouncerController extends Controller<HTMLElement> {\n /** Numeric read boundaries share one reader for this controller instance. */\n readonly #numbers = new NumberValueReader();\n\n static override targets = [\"polite\", \"assertive\"];\n static override values = {\n clearAfter: { type: Number, default: 1000 },\n dedupeReannounce: { type: Boolean, default: true },\n };\n\n static valueConstraints = {\n clearAfter: NUMBER_BOUNDS.timer,\n } satisfies NumberValueConstraints<typeof AnnouncerController.values>;\n static actions = [\"announce\"] as const;\n\n declare readonly politeTarget: HTMLElement;\n declare readonly assertiveTarget: HTMLElement;\n declare readonly politeTargets: HTMLElement[];\n declare readonly assertiveTargets: HTMLElement[];\n declare readonly hasPoliteTarget: boolean;\n declare readonly hasAssertiveTarget: boolean;\n\n declare clearAfterValue: number;\n declare dedupeReannounceValue: boolean;\n\n /** Drain timers, which belong to a politeness level rather than to a region. */\n readonly #timers = new SafeTimeout();\n\n /** Tells an in-page move or a permanent carry from a real detach. */\n readonly #gate = new DetachGate();\n\n /** The auto-clear each region may have outstanding; a newer message releases it. */\n readonly #regionTimers = new KeyedTimers<HTMLElement>();\n\n /** The stand-in last generated per absent target, which may have left the document since. */\n readonly #generated = new Map<Level, HTMLElement>();\n\n /** The stand-in marker, in the namespace this controller is registered under. */\n get #standIn(): string {\n return `data-${this.identifier}-${STAND_IN}`;\n }\n\n /** The written-message marker, in the namespace this controller is registered under. */\n get #announced(): string {\n return `data-${this.identifier}-${ANNOUNCED}`;\n }\n\n /** Messages waiting to be written, oldest first, one queue per politeness. */\n readonly #queues = new Map<Level, string[]>();\n\n /** Politeness levels whose next drain is already armed. */\n readonly #draining = new Set<Level>();\n\n /** Collapses a batch of target callbacks (and morph removals) into one pass. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileRegions());\n\n /**\n * Watches the host's own children for a generated region disappearing. A morph\n * drops it — the server's HTML never had it — and no target callback reports\n * that, because a generated region carries no target attribute. `subtree` stays\n * off so writing a message inside a region does not re-enter this pass.\n */\n readonly #hostWatch = new MutationObserver(() => {\n this.#reconcile.schedule();\n });\n\n /**\n * Guards against handling the same CustomEvent twice. An event dispatched on\n * the controller element with `bubbles: true` reaches both the element and the\n * `window` listener; this WeakSet ensures it announces only once.\n */\n readonly #handled = new WeakSet<Event>();\n\n /** Receives programmatic announcements at the element or bubbled to `window`. */\n readonly #onAnnounceEvent = (event: Event): void => {\n if (this.#handled.has(event)) return;\n this.#handled.add(event);\n const detail = (event as CustomEvent<unknown>).detail;\n const message = this.#messageFromDetail(detail);\n if (!message) return;\n this.#announce(message, this.#assertiveFromDetail(detail));\n };\n\n /**\n * Seats the regions and starts listening. The reconnection that completes an in-page\n * move or a permanent carry finds all of it in place, the queues and timers included.\n */\n override connect(): void {\n const moved = this.#gate.pending;\n this.#gate.cancel();\n if (moved) return;\n this.#reconcile.activate();\n this.#dropInheritedStandIns();\n this.#emptyInheritedMessages();\n // Materialise any missing region now, so it is in the accessibility tree\n // before the first message rather than appearing with it.\n this.#reconcileRegions();\n this.#hostWatch.observe(this.element, { childList: true });\n this.element.addEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n window.addEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n }\n\n /** Tears everything down once the element is really detached. */\n override disconnect(): void {\n this.#gate.disconnected(this, () => this.#teardown());\n }\n\n /** Releases the listeners, the queues, the timers and the stand-ins. */\n #teardown(): void {\n this.#reconcile.cancel();\n this.#hostWatch.disconnect();\n this.element.removeEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n window.removeEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n this.#timers.clearAll();\n this.#regionTimers.clearAll();\n this.#queues.clear();\n this.#draining.clear();\n this.#removeGenerated();\n }\n\n /** Retires the stand-in once the consumer supplies a polite region. */\n politeTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's polite region goes away. */\n politeTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Retires the stand-in once the consumer supplies an assertive region. */\n assertiveTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's assertive region goes away. */\n assertiveTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Brings the region set back to exactly one region per politeness and reports\n * whether anything had to be created.\n *\n * A region created here is not written to in the same task: assistive tech\n * reports changes to regions it already knows about, so {@link drain} waits a\n * task whenever this says a region is new.\n */\n #reconcileRegions(): boolean {\n let created = false;\n for (const level of LEVELS) {\n if (this.#hasTargetFor(level)) {\n // The consumer owns this politeness now; a stand-in would be a second\n // region for it, and an empty one nothing ever writes to.\n this.#generated.get(level)?.remove();\n continue;\n }\n const existing = this.#generated.get(level);\n if (existing?.isConnected) continue;\n this.#generated.set(level, this.#createRegion(level));\n created = true;\n }\n return created;\n }\n\n /** Whether the consumer supplied a target for `level`. */\n #hasTargetFor(level: Level): boolean {\n return level === \"assertive\" ? this.hasAssertiveTarget : this.hasPoliteTarget;\n }\n\n /** Builds a visually hidden, marked live region for `level` and attaches it. */\n #createRegion(level: Level): HTMLElement {\n const region = document.createElement(\"div\");\n region.setAttribute(\"aria-live\", level);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.setAttribute(this.#standIn, \"\");\n visuallyHide(region);\n this.element.appendChild(region);\n return region;\n }\n\n /** Removes the stand-ins the host arrived with; see the class remarks. */\n #dropInheritedStandIns(): void {\n for (const child of Array.from(this.element.children)) {\n if (child.hasAttribute(this.#standIn)) child.remove();\n }\n }\n\n /**\n * Empties the authored regions that hold a message this controller wrote, which no\n * clearing timer of this connection is left to clear; see the class remarks.\n */\n #emptyInheritedMessages(): void {\n for (const region of [...this.politeTargets, ...this.assertiveTargets]) {\n if (!region.hasAttribute(this.#announced)) continue;\n region.replaceChildren();\n region.removeAttribute(this.#announced);\n }\n }\n\n /** Removes the stand-ins this connection generated; authored targets stay. */\n #removeGenerated(): void {\n for (const region of this.#generated.values()) region.remove();\n }\n\n /**\n * Announces a message. Reads the text from a Stimulus action param\n * (`message`, plus optional `assertive`) for attribute-only triggers, falling\n * back to a CustomEvent `detail` when the same handler is wired to an event.\n * An empty/non-string message is ignored so untrusted payloads cannot blank\n * the region.\n */\n announce(event: Event): void {\n const params = (event as { params?: Record<string, unknown> }).params;\n const fromParam = params?.message;\n const message =\n typeof fromParam === \"string\" && fromParam.length > 0\n ? fromParam\n : this.#messageFromDetail((event as CustomEvent<unknown>).detail);\n if (!message) return;\n\n const assertive =\n params?.assertive === true ||\n this.#assertiveFromDetail((event as CustomEvent<unknown>).detail);\n this.#announce(message, assertive);\n }\n\n /**\n * Queues `message` for its politeness and arms the drain.\n *\n * Queuing is what makes a burst audible: assistive tech announces the changes it\n * observes, so several messages written into one region within a single task are\n * one change and only the last is read.\n */\n #announce(message: string, assertive: boolean): void {\n const level: Level = assertive ? \"assertive\" : \"polite\";\n const queue = this.#queues.get(level);\n if (queue) {\n queue.push(message);\n } else {\n this.#queues.set(level, [message]);\n }\n this.#scheduleDrain(level);\n }\n\n /** Arms one drain pass for `level`; further messages ride the pass already armed. */\n #scheduleDrain(level: Level): void {\n if (this.#draining.has(level)) return;\n this.#draining.add(level);\n this.#timers.set(() => {\n this.#draining.delete(level);\n this.#drain(level);\n }, 0);\n }\n\n /**\n * Writes one queued message, then arms the next pass while the queue holds more.\n *\n * Two steps take a whole pass without consuming the message: materialising a\n * region (it has to be in the accessibility tree before the text arrives) and\n * emptying a region that already holds this exact text (an unchanged node is not\n * re-read, so `dedupeReannounce` clears first and writes on the following pass).\n *\n * @stimeoRuntimeOnly `dedupeReannounce` decides whether one queued message is spoken again; the\n * region's text is the message itself.\n */\n #drain(level: Level): void {\n const queue = this.#queues.get(level);\n const message = queue?.[0];\n if (queue === undefined || message === undefined) return;\n\n const created = this.#reconcileRegions();\n const region = this.#regionFor(level);\n // With nothing created every politeness has a seated region; the second check\n // narrows the type.\n if (created || region === undefined) {\n this.#scheduleDrain(level);\n return;\n }\n\n if (this.dedupeReannounceValue && region.textContent === message) {\n region.textContent = \"\";\n this.#scheduleDrain(level);\n return;\n }\n\n queue.shift();\n // A non-positive `clearAfter` arms nothing below, so the region's pending\n // timer is released here rather than by the arming that replaces it.\n this.#regionTimers.clear(region);\n region.textContent = message;\n region.setAttribute(this.#announced, \"\");\n this.#scheduleClear(region, message);\n if (queue.length > 0) this.#scheduleDrain(level);\n }\n\n /**\n * Clears the region after `clearAfter` ms, unless a newer message replaced it.\n *\n * @stimeoRuntimeOnly `clearAfter` is the delay of the one clearing timer this call arms.\n */\n #scheduleClear(region: HTMLElement, message: string): void {\n if (this.#safeClearAfter <= 0) return;\n this.#regionTimers.set(\n region,\n () => {\n if (region.textContent !== message) return;\n region.textContent = \"\";\n region.removeAttribute(this.#announced);\n },\n this.#safeClearAfter,\n );\n }\n\n /**\n * The region a politeness writes into: its target, else its last stand-in. A\n * morph can drop the stand-in, and only a reconcile pass that created nothing\n * guarantees it is seated; a detached node announces nothing.\n */\n #regionFor(level: Level): HTMLElement | undefined {\n if (level === \"assertive\" && this.hasAssertiveTarget) return this.assertiveTarget;\n if (level === \"polite\" && this.hasPoliteTarget) return this.politeTarget;\n return this.#generated.get(level);\n }\n\n /** Extracts a non-empty string `message` from a CustomEvent detail, else null. */\n #messageFromDetail(detail: unknown): string | null {\n if (detail && typeof detail === \"object\" && \"message\" in detail) {\n const value = (detail as Record<string, unknown>).message;\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n }\n\n /** Reads an `assertive === true` flag from a CustomEvent detail (default polite). */\n #assertiveFromDetail(detail: unknown): boolean {\n return (\n !!detail &&\n typeof detail === \"object\" &&\n (detail as Record<string, unknown>).assertive === true\n );\n }\n /** Current `clearAfter` declaration resolved against its numeric contract. */\n get #safeClearAfter(): number {\n return this.#numbers.read(\n this,\n \"clearAfter\",\n this.clearAfterValue,\n AnnouncerController.values.clearAfter.default,\n AnnouncerController.valueConstraints.clearAfter,\n );\n }\n}\n\n/**\n * Applies the canonical visually-hidden (\"sr-only\") inline style to a generated\n * live region so its text is announced without being seen. Inline so the library\n * stays self-contained when the consumer provides no target/CSS of its own.\n *\n * Pure (no `this`); exported for direct unit testing.\n */\nexport function visuallyHide(node: HTMLElement): void {\n const { style } = node;\n style.position = \"absolute\";\n style.width = \"1px\";\n style.height = \"1px\";\n style.margin = \"-1px\";\n style.padding = \"0\";\n style.border = \"0\";\n style.overflow = \"hidden\";\n style.clip = \"rect(0 0 0 0)\";\n style.clipPath = \"inset(50%)\";\n style.whiteSpace = \"nowrap\";\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/detach_gate.ts","../../src/utils/timer_bounds.ts","../../src/utils/safe_timeout.ts","../../src/utils/keyed_timers.ts","../../src/utils/listener_set.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/number_bounds.ts","../../src/utils/coerce.ts","../../src/utils/number_value.ts","../../src/utils/attribute_write.ts","../../src/utils/owned_text.ts","../../src/controllers/announcer_controller.ts"],"names":[],"mappings":";;AAsFO,IAAM,UAAA,GAAN,MAAM,WAAA,CAAW;AAAA,EAEtB,QAAA,GAAW,KAAA;AAAA,EASX,IAAI,O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MAAA,KAAW,QAAA,IAAY,aAAa,MAAA,EAAQ;AAC/D,MAAA,MAAM,QAAS,MAAA,CAAmC,OAAA;AAClD,MAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,MAAA,GAAS,GAAG,OAAO,KAAA;AAAA,IAC5D;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EAGA,qBAAqB,MAAA,EAA0B;AAC7C,IAAA,OACE,CAAC,CAAC,MAAA,IACF,OAAO,MAAA,KAAW,QAAA,IACjB,OAAmC,SAAA,KAAc,IAAA;AAAA,EAEtD;AAAA,EAEA,IAAI,eAAA,GAA0B;AAC5B,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,MACnB,IAAA;AAAA,MACA,YAAA;AAAA,MACA,IAAA,CAAK,eAAA;AAAA,MACL,oBAAA,CAAoB,OAAO,UAAA,CAAW,OAAA;AAAA,MACtC,qBAAoB,gBAAA,CAAiB;AAAA,KACvC;AAAA,EACF;AACF;AASO,SAAS,aAAa,IAAA,EAAyB;AACpD,EAAA,MAAM,EAAE,OAAM,GAAI,IAAA;AAClB,EAAA,KAAA,CAAM,QAAA,GAAW,UAAA;AACjB,EAAA,KAAA,CAAM,KAAA,GAAQ,KAAA;AACd,EAAA,KAAA,CAAM,MAAA,GAAS,KAAA;AACf,EAAA,KAAA,CAAM,MAAA,GAAS,MAAA;AACf,EAAA,KAAA,CAAM,OAAA,GAAU,GAAA;AAChB,EAAA,KAAA,CAAM,MAAA,GAAS,GAAA;AACf,EAAA,KAAA,CAAM,QAAA,GAAW,QAAA;AACjB,EAAA,KAAA,CAAM,IAAA,GAAO,eAAA;AACb,EAAA,KAAA,CAAM,QAAA,GAAW,YAAA;AACjB,EAAA,KAAA,CAAM,UAAA,GAAa,QAAA;AACrB","file":"announcer_controller.js","sourcesContent":["/**\n * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * An element out of the document is a real detach, with one exception: a\n * `data-turbo-permanent` element, or one inside it, that Turbo carries to the\n * next page. Turbo takes it out of the old `<body>`, which Stimulus answers with\n * a `disconnect()` while it is out of the document, and puts it into the new one\n * a few microtasks later in the same task, where the same instance connects\n * again. Such a disconnect is probed until the next task instead.\n *\n * Policy stays with the consumer; this util owns the discrimination only:\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * dismiss(): void {\n * this.#gate.cancel(); // a direct path: disarm a probe a disconnect queued\n * this.#teardown();\n * }\n *\n * #teardown(): void {\n * // … (`disconnected` has already disarmed the probe on its own path)\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True while a probe is queued — the last disconnect was ambiguous and no\n * reconnect has cancelled it yet. Read it from `connect()` to tell the\n * reconnect half of an in-page move from a first connect: a controller whose\n * initialisation restarts a measurement (a min-duration floor, an elapsed\n * counter) must skip it for the move, where nothing actually restarted.\n */\n get pending(): boolean {\n return this.#pending;\n }\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n return !host.element.isConnected || !DetachGate.#listed(host);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains. An\n * element Turbo carries to the next page is probed until the next task, by\n * which time Turbo has put it back.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n const carried = DetachGate.#carried(host);\n if (!carried && DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n const probe = (): void => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n };\n if (carried) setTimeout(probe, 0);\n else queueMicrotask(probe);\n }\n\n /**\n * Whether `host` is out of the document inside a `data-turbo-permanent` element, its\n * identifier still listed: where Turbo holds an element it carries to the next page.\n */\n static #carried(host: DetachGateHost): boolean {\n const element = host.element;\n return (\n !element.isConnected &&\n element.closest(\"[data-turbo-permanent]\") !== null &&\n DetachGate.#listed(host)\n );\n }\n\n /** Whether the element's `data-controller` still lists the identifier. */\n static #listed(host: DetachGateHost): boolean {\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return tokens.includes(host.identifier);\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","/**\n * Largest delay a timer can hold: the platform stores it in a 32-bit signed\n * integer, and anything larger wraps around, so a delay meant to be far in the\n * future can fire almost immediately. A declared delay above this bound names\n * no delay at all, and a controller reading one falls back to its default.\n */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\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*. One pending timer per key is `KeyedTimers`\n * (`keyed_timers.ts`), and a timer a person can hold open, with its remaining-time\n * accounting, is `PausableTimers` (`pausable_timers.ts`).\n */\n\nexport { MAX_TIMER_DELAY_MS } from \"./timer_bounds\";\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { SafeTimeout } from \"./safe_timeout\";\n\n/**\n * Keeps at most one pending timer per key, and releases them all together.\n *\n * A region, a row, a message or a speaker that is armed again while its earlier\n * timer is still pending must end up with exactly one timer deciding when its\n * state ends. Two timers on one key means the earlier deadline wins: it cuts the\n * new emphasis short, clears text written after it, or drops a speaker who is\n * still typing — and then reports an ending for a state that is already gone.\n * Arming through this registry cancels the key's earlier timer in the same step,\n * and no timer id ever reaches the caller.\n *\n * An entry lives exactly as long as its timer: it goes as the timer fires, and\n * the whole ledger goes on `clearAll()`. That is a correctness rule, not\n * tidiness — a platform may hand an id released by `clearTimeout` to the next\n * timer it creates, so an entry that outlived its timer would let a later\n * `clear()` on that key cancel whatever timer now holds the id, on some other\n * key entirely.\n *\n * The ledger is a plain `Map`, and the key may be anything. Weak keys would\n * retain nothing less: while a timer is pending the platform already holds the\n * key through the callback, and the entry is gone the moment the timer is.\n *\n * Scope is the one-per-key timer only. What the timer means, and the roster of\n * keys it is armed for, stay with the consumer, so a second kind of timer on the\n * same keys (a transition wait, an animation frame) is a second registry, and a\n * timer that belongs to no key stays on a plain `SafeTimeout`.\n *\n * @example\n * ```ts\n * readonly #expiry = new KeyedTimers<string>();\n *\n * #onSignal(name: string): void {\n * this.#expiry.set(name, () => this.#drop(name), this.#timeout);\n * }\n *\n * disconnect(): void {\n * this.#expiry.clearAll();\n * }\n * ```\n */\nexport class KeyedTimers<K> {\n readonly #timers = new SafeTimeout();\n\n /** The pending timer of each key; an entry lives exactly as long as its timer. */\n readonly #pending = new Map<K, number>();\n\n /**\n * Arms `callback` after `delay` ms for `key`, cancelling the timer `key` had\n * pending. The entry is dropped before the callback runs, so the callback sees\n * the key unarmed and may arm it again for the next round.\n */\n set(key: K, callback: () => void, delay: number): void {\n this.clear(key);\n const id = this.#timers.set(() => {\n this.#pending.delete(key);\n callback();\n }, delay);\n this.#pending.set(key, id);\n }\n\n /**\n * Cancels `key`'s pending timer, if it has one.\n *\n * A timer id is a positive integer, so `-1` stands for \"nothing pending\" and\n * the registry ignores an id it does not own — the unarmed case needs no\n * branch of its own, and no other key's timer can be reached from here.\n */\n clear(key: K): void {\n this.#timers.clear(this.#pending.get(key) ?? -1);\n this.#pending.delete(key);\n }\n\n /**\n * Cancels every pending timer and forgets every key. Call this from a\n * controller's `disconnect()` so no timer, and no entry, outlives the element.\n */\n clearAll(): void {\n this.#timers.clearAll();\n this.#pending.clear();\n }\n\n /** Whether `key` has a timer pending. */\n has(key: K): boolean {\n return this.#pending.has(key);\n }\n}\n","/** What {@link ListenerSet.add} passes on besides the signal it supplies itself. */\nexport type ListenerOptions = Omit<AddEventListenerOptions, \"signal\">;\n\n/**\n * The event map a target's own `addEventListener` types its handlers with: the\n * window's, a document's, an HTML or SVG element's, any other element's, or a\n * media query list's. Other targets name none.\n */\ntype EventMapOf<T extends EventTarget> = T extends Window\n ? WindowEventMap\n : T extends Document\n ? DocumentEventMap\n : T extends HTMLElement\n ? HTMLElementEventMap\n : T extends SVGElement\n ? SVGElementEventMap\n : T extends Element\n ? ElementEventMap\n : T extends MediaQueryList\n ? MediaQueryListEventMap\n : Record<never, never>;\n\n/**\n * Owns every listener a controller attaches for one connected lifetime and\n * releases them together, so an event name is spelled once and the release\n * cannot drift from the registration.\n *\n * Detaching by hand repeats three things at the release site — the type, the\n * handler reference and the capture flag — and any one of them drifting leaves\n * a listener alive on an element the controller no longer drives. Aborting the\n * signal a registration was created with releases it whatever it was made of,\n * so the release site names nothing.\n *\n * One set per lifetime, held as a field and never rebuilt.\n * {@link ListenerSet.dispose} is the only thing that closes a generation, and it opens\n * the next one in the same step, so the lifecycle hooks can call `add` and\n * `dispose` in any order any number of times, and no `add` ever meets an\n * already aborted signal — a DOM that registers a listener on such a signal\n * would keep it forever. Rebuilding the set instead would leak:\n * `addEventListener` matches an existing registration on target, type, callback\n * and capture alone, so re-adding the same handler while the first registration\n * is live is discarded, and that live registration keeps the signal it was\n * attached with — a set built by a second `connect()` can never release what it\n * appears to own.\n *\n * Scope is the registration only. Timers, observers, leases and the order they\n * are unwound in stay with the controller, which places `dispose()` in its\n * cleanup sequence. A receiver that changes at runtime (a\n * swapped target) is rebound by calling `dispose()` and then `add()` again from\n * the rebind, not by a second set.\n *\n * A lifetime shorter than the connection — while a Value holds, until a first\n * load, while a subscription is open — gets a set of its own, which the end of\n * that lifetime disposes. A controller therefore holds one set per lifetime: the\n * connection's, and one for each swapped receiver or shorter span.\n *\n * The set must own every registration of a tuple it holds: a listener the same\n * target already carries for the same type, callback and capture flag keeps the\n * right to remove it, and this set's `add` for that tuple is discarded. A\n * subscription shared between instances behind a participant count, listeners of\n * several elements that come and go one at a time, and those one gesture holds\n * keep their own pair of calls or a signal of their own.\n *\n * @example\n * ```ts\n * readonly #listeners = new ListenerSet();\n *\n * connect(): void {\n * this.#listeners.add(this.element, \"submit\", this.#onNativeSubmit, { capture: true });\n * this.#listeners.add(this.element, \"turbo:submit-start\", this.#onSubmitStart);\n * this.#listeners.add(this.element, \"turbo:submit-end\", this.#onSubmitEnd);\n * }\n *\n * disconnect(): void {\n * this.#listeners.dispose();\n * }\n * ```\n */\nexport class ListenerSet {\n /** The generation every `add` joins until the next `dispose()`. */\n #abort = new AbortController();\n\n /**\n * Attaches `handler` to the open generation, exactly as the caller spelled it.\n *\n * The set supplies the signal, so `options` carries everything else the DOM\n * accepts — `capture` included. A removal by hand would have to repeat that\n * flag; aborting the signal releases the listener without it.\n *\n * A `type` the target's own event map names types `handler` with that event,\n * as the target's `addEventListener` does, so a handler written for a\n * `KeyboardEvent` is passed as it is; any other `type` takes an\n * `EventListener`.\n */\n add<T extends EventTarget, K extends keyof EventMapOf<T> & string>(\n target: T,\n type: K,\n handler: (event: EventMapOf<T>[K]) => void,\n options?: ListenerOptions,\n ): void;\n add(target: EventTarget, type: string, handler: EventListener, options?: ListenerOptions): void;\n add(target: EventTarget, type: string, handler: EventListener, options?: ListenerOptions): void {\n target.addEventListener(type, handler, { ...options, signal: this.#abort.signal });\n }\n\n /**\n * Releases every listener of the open generation, synchronously, and opens the\n * next one. Idempotent, and safe before anything has been added.\n */\n dispose(): void {\n this.#abort.abort();\n this.#abort = new AbortController();\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Whether a requested pass has yet to run. */\n get pending(): boolean {\n return this.#queued;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { MAX_TIMER_DELAY_MS } from \"./timer_bounds\";\n\n/** Semantic constraints on an already decoded number, independent of the DOM. */\nexport interface NumberBounds {\n /** Finite numbers are required, including when this field is omitted. */\n readonly finite?: true;\n /** Inclusive lower endpoint. */\n readonly min?: number;\n /** Inclusive upper endpoint. */\n readonly max?: number;\n /** Exclusive lower endpoint. */\n readonly exclusiveMin?: number;\n /** Require a number without a fractional part. */\n readonly integer?: boolean;\n /** Exact decoded numbers accepted by a discrete contract. */\n readonly allowedValues?: readonly number[];\n /** JSON-safe exceptions to finite-number checking for unbounded endpoints. */\n readonly allowInfinity?: \"negative\" | \"positive\" | \"both\";\n}\n\n/** One constraint for each Number Value, including shorthand declarations. */\nexport type NumberValueConstraints<Values> = {\n readonly [Key in keyof Values as Values[Key] extends\n | NumberConstructor\n | { type: NumberConstructor }\n ? Key\n : never]: NumberBounds;\n};\n\n/** Reusable semantic domains; fractional inputs remain fractional unless excluded. */\nexport const NUMBER_BOUNDS = {\n finite: { finite: true },\n nonNegative: { finite: true, min: 0 },\n positive: { finite: true, exclusiveMin: 0 },\n nonNegativeInteger: { finite: true, min: 0, integer: true },\n positiveInteger: { finite: true, exclusiveMin: 0, integer: true },\n lowerBound: { finite: true, allowInfinity: \"negative\" },\n upperBound: { finite: true, allowInfinity: \"positive\" },\n timer: { finite: true, min: 0, max: MAX_TIMER_DELAY_MS },\n positiveTimer: { finite: true, exclusiveMin: 0, max: MAX_TIMER_DELAY_MS },\n} as const satisfies Record<string, NumberBounds>;\n\n/**\n * Checks all declared bounds without rounding, clamping, or coercing the input.\n * Infinity exceptions relax only finite checking; every other bound still applies.\n */\nexport function matchesNumberBounds(value: number, bounds: NumberBounds): boolean {\n if (!Number.isFinite(value)) {\n const direction = value === Infinity ? \"positive\" : value === -Infinity ? \"negative\" : null;\n if (direction === null) return false;\n if (bounds.allowInfinity !== \"both\" && bounds.allowInfinity !== direction) return false;\n }\n if (bounds.min !== undefined && value < bounds.min) return false;\n if (bounds.max !== undefined && value > bounds.max) return false;\n if (bounds.exclusiveMin !== undefined && value <= bounds.exclusiveMin) return false;\n if (bounds.integer && !Number.isInteger(value)) return false;\n if (bounds.allowedValues !== undefined && !bounds.allowedValues.includes(value)) return false;\n return true;\n}\n\n/** Decodes a Number Value literal; action params use their own JSON decoder. */\nexport function decodeNumberValue(raw: string): number {\n return Number(raw.replace(/_/g, \"\"));\n}\n","/**\n * Numeric coercion for controllers that accept a number through a Value, an action\n * param, or an event detail.\n *\n * Stimulus decodes action params as JSON when possible and leaves other text\n * untouched. CustomEvent detail can also supply a number or numeric string.\n * The reader accepts those two types while rejecting blank and non-finite input.\n */\n\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/** Numeric update input, accepting decoded action params before CustomEvent detail. */\nexport type NumericValueEvent = Event & {\n params?: { amount?: unknown };\n detail?: { value?: unknown };\n};\n\n/** Reads the nullish action-param/detail precedence without falling back from invalid input. */\nexport function eventNumber(event: NumericValueEvent): number | null {\n return toFiniteNumber(event.params?.amount ?? event.detail?.value);\n}\n\n/**\n * Reads a finite number or nonblank numeric string; other input returns `null`.\n * Blank strings cannot silently reset a value to zero.\n */\nexport function toFiniteNumber(raw: unknown): number | null {\n if (typeof raw !== \"number\" && typeof raw !== \"string\") return null;\n if (typeof raw === \"string\" && raw.trim().length === 0) return null;\n const value = Number(raw);\n return Number.isFinite(value) ? value : null;\n}\n\n/**\n * Returns an accepted decoded Number Value or the caller's fallback unchanged.\n * The caller owns the fallback contract; this reader does not parse or write a Value.\n */\nexport function readNumber(raw: number, fallback: number, bounds: NumberBounds): number {\n return matchesNumberBounds(raw, bounds) ? raw : fallback;\n}\n","import { readNumber } from \"./coerce\";\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/** The instance identity carried by a Number Value read. */\nexport interface NumberValueOwner {\n readonly identifier: string;\n readonly element: Element;\n}\n\n/** Reads current declarations at the point of use without rewriting their attributes. */\nexport class NumberValueReader {\n /** The last rejected literal per Value; no history grows for an unchanged instance. */\n readonly #lastRejected = new Map<string, string>();\n\n /** Resolves the declared number using its own fallback and shared class contract. */\n read(\n owner: NumberValueOwner,\n name: string,\n raw: number,\n fallback: number,\n bounds: NumberBounds,\n ): number {\n const resolved = readNumber(raw, fallback, bounds);\n if (matchesNumberBounds(raw, bounds)) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n const attribute = `data-${owner.identifier}-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}-value`;\n const literal = owner.element.getAttribute(attribute);\n if (literal === null) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n if (this.#lastRejected.get(name) !== literal) {\n this.#lastRejected.set(name, literal);\n console.warn(\n `Stimeo UI: \"${owner.identifier}\" has an invalid number Value \"${name}\" declaration ${JSON.stringify(literal)}; using ${fallback}.`,\n );\n }\n return resolved;\n }\n}\n","/**\n * Reflects a serialized attribute value only when the current value differs.\n *\n * A same-value `setAttribute` still queues a mutation record for every observer, so an\n * unchanged value writes nothing.\n *\n * @param element - The element whose attribute is reflected.\n * @param name - The attribute name, using the non-namespaced DOM API.\n * @param value - The serialized value, or null to remove the attribute.\n * @param beforeWrite - Called only for a change, before the DOM mutation, so the\n * caller can record ownership or identify its own observer records.\n * @returns Whether an attribute was written or removed.\n */\nexport function setAttributeIfChanged(\n element: Element,\n name: string,\n value: string | null,\n beforeWrite?: () => void,\n): boolean {\n if (element.getAttribute(name) === value) return false;\n beforeWrite?.();\n if (value === null) element.removeAttribute(name);\n else element.setAttribute(name, value);\n return true;\n}\n","import { setAttributeIfChanged } from \"./attribute_write\";\n\n/** The original string and the last string written through one channel. */\nexport interface TextWrite {\n readonly original: string;\n readonly written: string;\n}\n\n/** Live evidence is tied to this instance and this exact element. */\nexport type TextEvidence =\n | { readonly source?: \"dom\" }\n | { readonly source: \"live\"; readonly allowOriginal?: boolean };\n\n/**\n * Records plain text or an input's value as `[channel, original, written]` in\n * an identifier-derived attribute supplied by the caller. Ownership requires a\n * valid record and the same current string; text containing an element is never\n * owned. The caller decides when to acquire, clear, restore, or forget a slot.\n *\n * DOM evidence survives a clone. Live evidence only describes writes made by\n * this instance to that element, so it can preserve a caller's held semantic\n * state or repair a morph that omitted the record. Neither proves who last\n * wrote an identical string. An optional guard protects other authored state.\n */\nexport class OwnedText<T extends HTMLElement = HTMLElement> {\n readonly #attribute: string;\n readonly #channel: \"text\" | \"value\";\n readonly #guard: (element: T) => boolean;\n readonly #writes = new WeakMap<T, TextWrite>();\n\n constructor(\n attribute: string,\n channel: \"text\" | \"value\" = \"text\",\n guard: (element: T) => boolean = () => true,\n ) {\n this.#attribute = attribute;\n this.#channel = channel;\n this.#guard = guard;\n }\n\n /** Whether the slot carries a record, including an invalid one. */\n hasRecord(element: T): boolean {\n return element.hasAttribute(this.#attribute);\n }\n\n /** Reads validated DOM evidence, or explicitly requested instance evidence. */\n read(element: T, evidence: TextEvidence = {}): TextWrite | null {\n if (evidence.source === \"live\") return this.#writes.get(element) ?? null;\n const raw = element.getAttribute(this.#attribute);\n if (raw === null) return null;\n try {\n const record: unknown = JSON.parse(raw);\n if (\n !Array.isArray(record) ||\n record.length !== 3 ||\n record[0] !== this.#channel ||\n typeof record[1] !== \"string\" ||\n typeof record[2] !== \"string\"\n )\n return null;\n return { original: record[1], written: record[2] };\n } catch {\n return null;\n }\n }\n\n /** Checks the current string, the text structure, and the caller's guard. */\n owns(element: T, evidence: TextEvidence = {}): boolean {\n return this.#ownedRecord(element, evidence) !== null;\n }\n\n /** Returns the matching evidence after checking structure and the caller's guard. */\n #ownedRecord(element: T, evidence: TextEvidence): TextWrite | null {\n const record = this.read(element, evidence);\n if (record === null || !this.#guard(element)) return null;\n if (this.#channel === \"text\" && element.firstElementChild !== null) return null;\n const current = this.#current(element);\n return current === record.written ||\n (evidence.source === \"live\" && evidence.allowOriginal === true && current === record.original)\n ? record\n : null;\n }\n\n /** Acquires the slot, preserving the first original unless the caller supplies one. */\n write(element: T, written: string, original?: string, force = false): void {\n const current = this.#current(element);\n if (current === null) return;\n const before =\n original ?? this.#writes.get(element)?.original ?? this.read(element)?.original ?? current;\n if (force || current !== written) this.#put(element, written);\n this.remember(element, written, before);\n }\n\n /** Records a write whose property assignment, such as caret handling, the caller owns. */\n remember(element: T, written: string, original?: string): void {\n const current = this.#current(element);\n if (current === null) return;\n const before =\n original ?? this.#writes.get(element)?.original ?? this.read(element)?.original ?? current;\n this.#writes.set(element, { original: before, written });\n setAttributeIfChanged(\n element,\n this.#attribute,\n JSON.stringify([this.#channel, before, written]),\n );\n }\n\n /** Empties an owned slot and releases its evidence. */\n clear(element: T, evidence: TextEvidence = {}): boolean {\n if (!this.owns(element, evidence)) return false;\n if (this.#current(element) !== \"\") this.#put(element, \"\");\n this.forget(element);\n return true;\n }\n\n /** Restores an owned slot's original string and releases its evidence. */\n restore(element: T, evidence: TextEvidence = {}): boolean {\n const record = this.#ownedRecord(element, evidence);\n if (record === null) return false;\n if (this.#current(element) !== record.original) this.#put(element, record.original);\n this.forget(element);\n return true;\n }\n\n /** Drops evidence without changing the slot, including an invalid DOM record. */\n forget(element: T): void {\n setAttributeIfChanged(element, this.#attribute, null);\n this.#writes.delete(element);\n }\n\n /** Reads the property belonging to this channel. */\n #current(element: T): string | null {\n if (this.#channel === \"text\") return element.textContent ?? \"\";\n return element instanceof HTMLInputElement ? element.value : null;\n }\n\n /** Writes the property belonging to this channel. */\n #put(element: T, text: string): void {\n if (this.#channel === \"text\") element.textContent = text;\n else if (element instanceof HTMLInputElement) element.value = text;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { DetachGate } from \"../utils/detach_gate\";\nimport { KeyedTimers } from \"../utils/keyed_timers\";\nimport { ListenerSet } from \"../utils/listener_set\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { NUMBER_BOUNDS, type NumberValueConstraints } from \"../utils/number_bounds\";\nimport { NumberValueReader } from \"../utils/number_value\";\nimport { OwnedText } from \"../utils/owned_text\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** The two politeness levels this controller keeps a region for. */\nconst LEVELS = [\"polite\", \"assertive\"] as const;\n\n/** One of the politeness levels in {@link LEVELS}. */\ntype Level = (typeof LEVELS)[number];\n\n/** Suffix of the marker on a live region this controller generated; see the class remarks. */\nconst STAND_IN = \"stand-in\";\n\n/** Suffix of the marker on a region holding a message this controller wrote. */\nconst ANNOUNCED = \"announced\";\n\n/**\n * Headless, shared **live-region announcer** — a polite/assertive screen-reader\n * announcement base (no dedicated APG pattern; follows the WAI-ARIA \"Alert\" /\n * \"Status\" live-region guidance and WCAG 2.2 **4.1.3 Status Messages**).\n *\n * Markup contract (identifier: `stimeo--announcer`):\n * <!-- Place once per page; the consumer visually hides the regions in CSS. -->\n * <div data-controller=\"stimeo--announcer\">\n * <div data-stimeo--announcer-target=\"polite\" aria-live=\"polite\" aria-atomic=\"true\"></div>\n * <div data-stimeo--announcer-target=\"assertive\" aria-live=\"assertive\" aria-atomic=\"true\"></div>\n * </div>\n *\n * <!-- Attribute-only trigger: declare the activation event explicitly. -->\n * <button data-action=\"click->stimeo--announcer#announce\"\n * data-stimeo--announcer-message-param=\"Saved\"\n * data-stimeo--announcer-assertive-param=\"false\">Save</button>\n *\n * <!-- Programmatic trigger (e.g. from another controller / Turbo Stream). -->\n * window.dispatchEvent(new CustomEvent(\"stimeo--announcer:announce\", {\n * detail: { message: \"12 results\", assertive: false },\n * }))\n *\n * The announcer is the shared live region other controllers hand their messages\n * to (`stimeo--auto-submit`, `stimeo--flash` and `stimeo--bulk-select` among\n * them) instead of each carrying their own.\n *\n * @remarks\n * Behavior only, with **one deliberate exception**: when a `polite`/`assertive`\n * target is absent the controller *generates* the missing region **on connect**\n * and applies the canonical visually-hidden inline style (see {@link visuallyHide}).\n * A live region must exist and be visually hidden to do its job, and a generated\n * node has no consumer CSS hook to hide it; consumers who want to own styling\n * supply their own targets. Generation happens up front rather than on the first\n * announcement because assistive tech reports changes to a region it already\n * knows about — a region created and written within one task loses that first\n * message. The controller never moves focus — announcements must not steal it\n * (WCAG 2.2 4.1.3). Listeners, the queues and the clear timers are torn down, and any\n * generated regions removed, once the element is really detached. An in-page move,\n * and a `data-turbo-permanent` announcer Turbo carries to the next page, reconnect\n * the same instance with all of them in place, so what was queued is still read and a\n * message on display is still cleared on time.\n *\n * **Generated regions are marked, so a restore never doubles them.** Each\n * stand-in carries `data-<identifier>-stand-in`. The region set is kept whole until\n * the controller is detached, so a stand-in can reach a copy of the page — a page Turbo\n * restores from its cache is one. The teardown removes the stand-ins a connection\n * generated, so a marked child a host arrives with came from an earlier one:\n * `connect()` drops it before generating its own, and it never sits as a second\n * region beside the new stand-in or an authored target.\n *\n * **A restored page does not read out an earlier message.** A region holding a\n * message this controller wrote carries `[\"text\", original, written]` in\n * `data-<identifier>-announced` until the message\n * is cleared after `clearAfter`. The teardown drops the clearing timers, so a connection\n * that is not the other half of a move empties only a region still holding that\n * recorded text alone. Authored replacements, element children, and invalid records\n * stay. Nothing is dropped or emptied on `turbo:before-cache`, which Turbo\n * also dispatches on pages that stay (a promoted frame navigation, a state-less\n * `popstate`, a refresh of a cached URL): the messages queued there are still read.\n *\n * **Messages are queued, one write per task.** Assistive tech announces what it\n * observes changing, so two messages written into one region within a single task\n * are one observed change and the earlier message is never read. Each politeness\n * has its own FIFO — an assertive message never waits behind polite ones — and a\n * message is written only in a task where its region already existed.\n *\n * **The region set is kept whole while connected.** Exactly one region per\n * politeness is present: an authored target retires the stand-in generated for it,\n * losing one materialises a stand-in again, and a generated region removed by a\n * morph (it is absent from the server's HTML, so a morph drops it) is put back\n * without waiting for the next message.\n */\nexport class AnnouncerController extends Controller<HTMLElement> {\n /** Numeric read boundaries share one reader for this controller instance. */\n readonly #numbers = new NumberValueReader();\n\n static override targets = [\"polite\", \"assertive\"];\n static override values = {\n clearAfter: { type: Number, default: 1000 },\n dedupeReannounce: { type: Boolean, default: true },\n };\n\n static valueConstraints = {\n clearAfter: NUMBER_BOUNDS.timer,\n } satisfies NumberValueConstraints<typeof AnnouncerController.values>;\n static actions = [\"announce\"] as const;\n\n declare readonly politeTarget: HTMLElement;\n declare readonly assertiveTarget: HTMLElement;\n declare readonly politeTargets: HTMLElement[];\n declare readonly assertiveTargets: HTMLElement[];\n declare readonly hasPoliteTarget: boolean;\n declare readonly hasAssertiveTarget: boolean;\n\n declare clearAfterValue: number;\n declare dedupeReannounceValue: boolean;\n\n /** Drain timers, which belong to a politeness level rather than to a region. */\n readonly #timers = new SafeTimeout();\n\n /** Tells an in-page move or a permanent carry from a real detach. */\n readonly #gate = new DetachGate();\n\n /** The announce listeners, released by the teardown a real detach runs. */\n readonly #listeners = new ListenerSet();\n\n /** The auto-clear each region may have outstanding; a newer message releases it. */\n readonly #regionTimers = new KeyedTimers<HTMLElement>();\n\n /** The stand-in last generated per absent target, which may have left the document since. */\n readonly #generated = new Map<Level, HTMLElement>();\n\n /** The stand-in marker, in the namespace this controller is registered under. */\n get #standIn(): string {\n return `data-${this.identifier}-${STAND_IN}`;\n }\n\n /** The written-message marker, in the namespace this controller is registered under. */\n readonly #messageText = new OwnedText(`data-${this.identifier}-${ANNOUNCED}`);\n\n /** Messages waiting to be written, oldest first, one queue per politeness. */\n readonly #queues = new Map<Level, string[]>();\n\n /** Politeness levels whose next drain is already armed. */\n readonly #draining = new Set<Level>();\n\n /** Collapses a batch of target callbacks (and morph removals) into one pass. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileRegions());\n\n /**\n * Watches the host's own children for a generated region disappearing. A morph\n * drops it — the server's HTML never had it — and no target callback reports\n * that, because a generated region carries no target attribute. `subtree` stays\n * off so writing a message inside a region does not re-enter this pass.\n */\n readonly #hostWatch = new MutationObserver(() => {\n this.#reconcile.schedule();\n });\n\n /**\n * Guards against handling the same CustomEvent twice. An event dispatched on\n * the controller element with `bubbles: true` reaches both the element and the\n * `window` listener; this WeakSet ensures it announces only once.\n */\n readonly #handled = new WeakSet<Event>();\n\n /** Receives programmatic announcements at the element or bubbled to `window`. */\n readonly #onAnnounceEvent = (event: Event): void => {\n if (this.#handled.has(event)) return;\n this.#handled.add(event);\n const detail = (event as CustomEvent<unknown>).detail;\n const message = this.#messageFromDetail(detail);\n if (!message) return;\n this.#announce(message, this.#assertiveFromDetail(detail));\n };\n\n /**\n * Seats the regions and starts listening. The reconnection that completes an in-page\n * move or a permanent carry finds all of it in place, the queues and timers included.\n */\n override connect(): void {\n const moved = this.#gate.pending;\n this.#gate.cancel();\n if (moved) return;\n this.#reconcile.activate();\n this.#dropInheritedStandIns();\n this.#emptyInheritedMessages();\n // Materialise any missing region now, so it is in the accessibility tree\n // before the first message rather than appearing with it.\n this.#reconcileRegions();\n this.#hostWatch.observe(this.element, { childList: true });\n this.#listeners.add(this.element, \"stimeo--announcer:announce\", this.#onAnnounceEvent);\n this.#listeners.add(window, \"stimeo--announcer:announce\", this.#onAnnounceEvent);\n }\n\n /** Tears everything down once the element is really detached. */\n override disconnect(): void {\n this.#gate.disconnected(this, () => this.#teardown());\n }\n\n /** Releases the listeners, the queues, the timers and the stand-ins. */\n #teardown(): void {\n this.#reconcile.cancel();\n this.#hostWatch.disconnect();\n this.#listeners.dispose();\n this.#timers.clearAll();\n this.#regionTimers.clearAll();\n this.#queues.clear();\n this.#draining.clear();\n this.#removeGenerated();\n }\n\n /** Retires the stand-in once the consumer supplies a polite region. */\n politeTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's polite region goes away. */\n politeTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Retires the stand-in once the consumer supplies an assertive region. */\n assertiveTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's assertive region goes away. */\n assertiveTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Brings the region set back to exactly one region per politeness and reports\n * whether anything had to be created.\n *\n * A region created here is not written to in the same task: assistive tech\n * reports changes to regions it already knows about, so {@link #drain} waits a\n * task whenever this says a region is new.\n */\n #reconcileRegions(): boolean {\n let created = false;\n for (const level of LEVELS) {\n if (this.#hasTargetFor(level)) {\n // The consumer owns this politeness now; a stand-in would be a second\n // region for it, and an empty one nothing ever writes to.\n this.#generated.get(level)?.remove();\n continue;\n }\n const existing = this.#generated.get(level);\n if (existing?.isConnected) continue;\n this.#generated.set(level, this.#createRegion(level));\n created = true;\n }\n return created;\n }\n\n /** Whether the consumer supplied a target for `level`. */\n #hasTargetFor(level: Level): boolean {\n return level === \"assertive\" ? this.hasAssertiveTarget : this.hasPoliteTarget;\n }\n\n /** Builds a visually hidden, marked live region for `level` and attaches it. */\n #createRegion(level: Level): HTMLElement {\n const region = document.createElement(\"div\");\n region.setAttribute(\"aria-live\", level);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.setAttribute(this.#standIn, \"\");\n visuallyHide(region);\n this.element.appendChild(region);\n return region;\n }\n\n /** Removes the stand-ins the host arrived with; see the class remarks. */\n #dropInheritedStandIns(): void {\n for (const child of Array.from(this.element.children)) {\n if (child.hasAttribute(this.#standIn)) child.remove();\n }\n }\n\n /**\n * Empties the authored regions that hold a message this controller wrote, which no\n * clearing timer of this connection is left to clear; see the class remarks.\n */\n #emptyInheritedMessages(): void {\n for (const region of [...this.politeTargets, ...this.assertiveTargets]) {\n this.#messageText.clear(region);\n }\n }\n\n /** Removes the stand-ins this connection generated; authored targets stay. */\n #removeGenerated(): void {\n for (const region of this.#generated.values()) region.remove();\n }\n\n /**\n * Announces a message. Reads the text from a Stimulus action param\n * (`message`, plus optional `assertive`) for attribute-only triggers, falling\n * back to a CustomEvent `detail` when the same handler is wired to an event.\n * An empty/non-string message is ignored so untrusted payloads cannot blank\n * the region.\n */\n announce(event: Event): void {\n const params = (event as { params?: Record<string, unknown> }).params;\n const fromParam = params?.message;\n const message =\n typeof fromParam === \"string\" && fromParam.length > 0\n ? fromParam\n : this.#messageFromDetail((event as CustomEvent<unknown>).detail);\n if (!message) return;\n\n const assertive =\n params?.assertive === true ||\n this.#assertiveFromDetail((event as CustomEvent<unknown>).detail);\n this.#announce(message, assertive);\n }\n\n /**\n * Queues `message` for its politeness and arms the drain.\n *\n * Queuing is what makes a burst audible: assistive tech announces the changes it\n * observes, so several messages written into one region within a single task are\n * one change and only the last is read.\n */\n #announce(message: string, assertive: boolean): void {\n const level: Level = assertive ? \"assertive\" : \"polite\";\n const queue = this.#queues.get(level);\n if (queue) {\n queue.push(message);\n } else {\n this.#queues.set(level, [message]);\n }\n this.#scheduleDrain(level);\n }\n\n /** Arms one drain pass for `level`; further messages ride the pass already armed. */\n #scheduleDrain(level: Level): void {\n if (this.#draining.has(level)) return;\n this.#draining.add(level);\n this.#timers.set(() => {\n this.#draining.delete(level);\n this.#drain(level);\n }, 0);\n }\n\n /**\n * Writes one queued message, then arms the next pass while the queue holds more.\n *\n * Two steps take a whole pass without consuming the message: materialising a\n * region (it has to be in the accessibility tree before the text arrives) and\n * emptying a region that already holds this exact text (an unchanged node is not\n * re-read, so `dedupeReannounce` clears first and writes on the following pass).\n *\n * @stimeoRuntimeOnly `dedupeReannounce` decides whether one queued message is spoken again; the\n * region's text is the message itself.\n */\n #drain(level: Level): void {\n const queue = this.#queues.get(level);\n const message = queue?.[0];\n if (queue === undefined || message === undefined) return;\n\n const created = this.#reconcileRegions();\n const region = this.#regionFor(level);\n // With nothing created every politeness has a seated region; the second check\n // narrows the type.\n if (created || region === undefined) {\n this.#scheduleDrain(level);\n return;\n }\n\n if (this.dedupeReannounceValue && region.textContent === message) {\n region.textContent = \"\";\n this.#messageText.forget(region);\n this.#scheduleDrain(level);\n return;\n }\n\n queue.shift();\n // A non-positive `clearAfter` arms nothing below, so the region's pending\n // timer is released here rather than by the arming that replaces it.\n this.#regionTimers.clear(region);\n this.#messageText.write(region, message, undefined, true);\n this.#scheduleClear(region);\n if (queue.length > 0) this.#scheduleDrain(level);\n }\n\n /**\n * Clears the region after `clearAfter` ms if it still shows only the message this\n * controller recorded there. A newer message re-arms the region's one timer.\n *\n * @stimeoRuntimeOnly `clearAfter` is the delay of the one clearing timer this call arms.\n */\n #scheduleClear(region: HTMLElement): void {\n if (this.#safeClearAfter <= 0) return;\n this.#regionTimers.set(\n region,\n () => {\n this.#messageText.clear(region);\n },\n this.#safeClearAfter,\n );\n }\n\n /**\n * The region a politeness writes into: its target, else its last stand-in. A\n * morph can drop the stand-in, and only a reconcile pass that created nothing\n * guarantees it is seated; a detached node announces nothing.\n */\n #regionFor(level: Level): HTMLElement | undefined {\n if (level === \"assertive\" && this.hasAssertiveTarget) return this.assertiveTarget;\n if (level === \"polite\" && this.hasPoliteTarget) return this.politeTarget;\n return this.#generated.get(level);\n }\n\n /** Extracts a non-empty string `message` from a CustomEvent detail, else null. */\n #messageFromDetail(detail: unknown): string | null {\n if (detail && typeof detail === \"object\" && \"message\" in detail) {\n const value = (detail as Record<string, unknown>).message;\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n }\n\n /** Reads an `assertive === true` flag from a CustomEvent detail (default polite). */\n #assertiveFromDetail(detail: unknown): boolean {\n return (\n !!detail &&\n typeof detail === \"object\" &&\n (detail as Record<string, unknown>).assertive === true\n );\n }\n /** Current `clearAfter` declaration resolved against its numeric contract. */\n get #safeClearAfter(): number {\n return this.#numbers.read(\n this,\n \"clearAfter\",\n this.clearAfterValue,\n AnnouncerController.values.clearAfter.default,\n AnnouncerController.valueConstraints.clearAfter,\n );\n }\n}\n\n/**\n * Applies the canonical visually-hidden (\"sr-only\") inline style to a generated\n * live region so its text is announced without being seen. Inline so the library\n * stays self-contained when the consumer provides no target/CSS of its own.\n *\n * Pure (no `this`); exported for direct unit testing.\n */\nexport function visuallyHide(node: HTMLElement): void {\n const { style } = node;\n style.position = \"absolute\";\n style.width = \"1px\";\n style.height = \"1px\";\n style.margin = \"-1px\";\n style.padding = \"0\";\n style.border = \"0\";\n style.overflow = \"hidden\";\n style.clip = \"rect(0 0 0 0)\";\n style.clipPath = \"inset(50%)\";\n style.whiteSpace = \"nowrap\";\n}\n"]}