stimeo-ui 0.16.0 → 0.17.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.
- package/CHANGELOG.md +31 -0
- package/README.md +8 -1
- package/dist/cable/index.d.ts +79 -23
- package/dist/cable/index.js +363 -436
- package/dist/cable/index.js.map +1 -1
- package/dist/controllers/accordion_controller.d.ts +4 -2
- package/dist/controllers/accordion_controller.js +166 -55
- package/dist/controllers/accordion_controller.js.map +1 -1
- package/dist/controllers/alert_dialog_controller.d.ts +12 -2
- package/dist/controllers/alert_dialog_controller.js +862 -221
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/announcer_controller.d.ts +35 -5
- package/dist/controllers/announcer_controller.js +135 -198
- package/dist/controllers/announcer_controller.js.map +1 -1
- package/dist/controllers/aspect_ratio_controller.js +0 -10
- package/dist/controllers/aspect_ratio_controller.js.map +1 -1
- package/dist/controllers/auto_submit_controller.d.ts +30 -6
- package/dist/controllers/auto_submit_controller.js +271 -127
- package/dist/controllers/auto_submit_controller.js.map +1 -1
- package/dist/controllers/avatar_controller.js +171 -105
- package/dist/controllers/avatar_controller.js.map +1 -1
- package/dist/controllers/breadcrumb_controller.js +0 -130
- package/dist/controllers/breadcrumb_controller.js.map +1 -1
- package/dist/controllers/bulk_select_controller.d.ts +18 -0
- package/dist/controllers/bulk_select_controller.js +262 -52
- package/dist/controllers/bulk_select_controller.js.map +1 -1
- package/dist/controllers/calendar_controller.d.ts +24 -5
- package/dist/controllers/calendar_controller.js +175 -209
- package/dist/controllers/calendar_controller.js.map +1 -1
- package/dist/controllers/carousel_controller.d.ts +34 -7
- package/dist/controllers/carousel_controller.js +461 -399
- package/dist/controllers/carousel_controller.js.map +1 -1
- package/dist/controllers/character_counter_controller.d.ts +17 -1
- package/dist/controllers/character_counter_controller.js +246 -156
- package/dist/controllers/character_counter_controller.js.map +1 -1
- package/dist/controllers/checkbox_controller.d.ts +7 -2
- package/dist/controllers/checkbox_controller.js +32 -74
- package/dist/controllers/checkbox_controller.js.map +1 -1
- package/dist/controllers/clipboard_controller.d.ts +16 -5
- package/dist/controllers/clipboard_controller.js +168 -147
- package/dist/controllers/clipboard_controller.js.map +1 -1
- package/dist/controllers/collapsible_controller.d.ts +16 -4
- package/dist/controllers/collapsible_controller.js +301 -120
- package/dist/controllers/collapsible_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +18 -6
- package/dist/controllers/color_picker_controller.js +149 -139
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/combobox_controller.d.ts +23 -5
- package/dist/controllers/combobox_controller.js +360 -133
- package/dist/controllers/combobox_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.d.ts +45 -14
- package/dist/controllers/command_palette_controller.js +970 -358
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/conditional_fields_controller.d.ts +15 -2
- package/dist/controllers/conditional_fields_controller.js +166 -124
- package/dist/controllers/conditional_fields_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.d.ts +49 -12
- package/dist/controllers/confirm_controller.js +939 -248
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/context_menu_controller.d.ts +31 -4
- package/dist/controllers/context_menu_controller.js +256 -128
- package/dist/controllers/context_menu_controller.js.map +1 -1
- package/dist/controllers/count_up_controller.d.ts +13 -1
- package/dist/controllers/count_up_controller.js +73 -21
- package/dist/controllers/count_up_controller.js.map +1 -1
- package/dist/controllers/countdown_controller.d.ts +45 -1
- package/dist/controllers/countdown_controller.js +183 -148
- package/dist/controllers/countdown_controller.js.map +1 -1
- package/dist/controllers/currency_input_controller.d.ts +21 -2
- package/dist/controllers/currency_input_controller.js +134 -158
- package/dist/controllers/currency_input_controller.js.map +1 -1
- package/dist/controllers/data_grid_controller.d.ts +15 -4
- package/dist/controllers/data_grid_controller.js +114 -186
- package/dist/controllers/data_grid_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.d.ts +30 -5
- package/dist/controllers/date_range_picker_controller.js +288 -206
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.d.ts +13 -1
- package/dist/controllers/dialog_controller.js +858 -223
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/direct_upload_controller.d.ts +24 -7
- package/dist/controllers/direct_upload_controller.js +73 -153
- package/dist/controllers/direct_upload_controller.js.map +1 -1
- package/dist/controllers/dirty_form_controller.js +14 -48
- package/dist/controllers/dirty_form_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.d.ts +19 -0
- package/dist/controllers/dismissible_controller.js +175 -21
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.d.ts +39 -11
- package/dist/controllers/drawer_controller.js +933 -341
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/dropdown_controller.d.ts +31 -1
- package/dist/controllers/dropdown_controller.js +312 -82
- package/dist/controllers/dropdown_controller.js.map +1 -1
- package/dist/controllers/editable_controller.d.ts +12 -1
- package/dist/controllers/editable_controller.js +158 -68
- package/dist/controllers/editable_controller.js.map +1 -1
- package/dist/controllers/empty_state_controller.js +67 -53
- package/dist/controllers/empty_state_controller.js.map +1 -1
- package/dist/controllers/file_dropzone_controller.d.ts +60 -18
- package/dist/controllers/file_dropzone_controller.js +311 -207
- package/dist/controllers/file_dropzone_controller.js.map +1 -1
- package/dist/controllers/filter_controller.js +67 -39
- package/dist/controllers/filter_controller.js.map +1 -1
- package/dist/controllers/flash_controller.d.ts +31 -8
- package/dist/controllers/flash_controller.js +172 -314
- package/dist/controllers/flash_controller.js.map +1 -1
- package/dist/controllers/focus_controller.d.ts +12 -3
- package/dist/controllers/focus_controller.js +654 -240
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_field_controller.js +147 -132
- package/dist/controllers/form_field_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js +13 -86
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/frame_loading_controller.d.ts +41 -9
- package/dist/controllers/frame_loading_controller.js +264 -213
- package/dist/controllers/frame_loading_controller.js.map +1 -1
- package/dist/controllers/highlight_controller.d.ts +22 -2
- package/dist/controllers/highlight_controller.js +107 -75
- package/dist/controllers/highlight_controller.js.map +1 -1
- package/dist/controllers/hover_card_controller.d.ts +56 -3
- package/dist/controllers/hover_card_controller.js +309 -118
- package/dist/controllers/hover_card_controller.js.map +1 -1
- package/dist/controllers/idle_controller.d.ts +42 -1
- package/dist/controllers/idle_controller.js +267 -101
- package/dist/controllers/idle_controller.js.map +1 -1
- package/dist/controllers/input_mask_controller.js +71 -72
- package/dist/controllers/input_mask_controller.js.map +1 -1
- package/dist/controllers/intersection_controller.d.ts +32 -13
- package/dist/controllers/intersection_controller.js +147 -106
- package/dist/controllers/intersection_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.d.ts +16 -0
- package/dist/controllers/lazy_frame_controller.js +9 -65
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/listbox_controller.d.ts +34 -2
- package/dist/controllers/listbox_controller.js +306 -204
- package/dist/controllers/listbox_controller.js.map +1 -1
- package/dist/controllers/local_time_controller.d.ts +1 -1
- package/dist/controllers/local_time_controller.js +54 -64
- package/dist/controllers/local_time_controller.js.map +1 -1
- package/dist/controllers/masonry_controller.d.ts +11 -3
- package/dist/controllers/masonry_controller.js +70 -93
- package/dist/controllers/masonry_controller.js.map +1 -1
- package/dist/controllers/menu_controller.d.ts +32 -7
- package/dist/controllers/menu_controller.js +214 -156
- package/dist/controllers/menu_controller.js.map +1 -1
- package/dist/controllers/menubar_controller.d.ts +4 -4
- package/dist/controllers/menubar_controller.js +170 -329
- package/dist/controllers/menubar_controller.js.map +1 -1
- package/dist/controllers/meter_controller.d.ts +20 -0
- package/dist/controllers/meter_controller.js +151 -67
- package/dist/controllers/meter_controller.js.map +1 -1
- package/dist/controllers/multi_select_controller.d.ts +32 -4
- package/dist/controllers/multi_select_controller.js +593 -358
- package/dist/controllers/multi_select_controller.js.map +1 -1
- package/dist/controllers/navigation_menu_controller.d.ts +8 -1
- package/dist/controllers/navigation_menu_controller.js +124 -232
- package/dist/controllers/navigation_menu_controller.js.map +1 -1
- package/dist/controllers/nested_form_controller.d.ts +10 -0
- package/dist/controllers/nested_form_controller.js +352 -182
- package/dist/controllers/nested_form_controller.js.map +1 -1
- package/dist/controllers/network_status_controller.d.ts +23 -0
- package/dist/controllers/network_status_controller.js +242 -54
- package/dist/controllers/network_status_controller.js.map +1 -1
- package/dist/controllers/number_input_controller.d.ts +26 -2
- package/dist/controllers/number_input_controller.js +320 -263
- package/dist/controllers/number_input_controller.js.map +1 -1
- package/dist/controllers/optimistic_controller.js +16 -76
- package/dist/controllers/optimistic_controller.js.map +1 -1
- package/dist/controllers/otp_controller.d.ts +20 -4
- package/dist/controllers/otp_controller.js +198 -193
- package/dist/controllers/otp_controller.js.map +1 -1
- package/dist/controllers/overflow_indicator_controller.d.ts +5 -0
- package/dist/controllers/overflow_indicator_controller.js +116 -113
- package/dist/controllers/overflow_indicator_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.d.ts +48 -11
- package/dist/controllers/overflow_menu_controller.js +343 -283
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/pagination_controller.d.ts +35 -6
- package/dist/controllers/pagination_controller.js +295 -119
- package/dist/controllers/pagination_controller.js.map +1 -1
- package/dist/controllers/password_reveal_controller.d.ts +45 -8
- package/dist/controllers/password_reveal_controller.js +389 -121
- package/dist/controllers/password_reveal_controller.js.map +1 -1
- package/dist/controllers/password_strength_controller.d.ts +14 -5
- package/dist/controllers/password_strength_controller.js +99 -153
- package/dist/controllers/password_strength_controller.js.map +1 -1
- package/dist/controllers/persist_controller.d.ts +11 -4
- package/dist/controllers/persist_controller.js +237 -103
- package/dist/controllers/persist_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.d.ts +19 -7
- package/dist/controllers/pointer_drag_controller.js +185 -165
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/popover_controller.d.ts +38 -2
- package/dist/controllers/popover_controller.js +236 -97
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/controllers/portal_controller.d.ts +44 -4
- package/dist/controllers/portal_controller.js +209 -76
- package/dist/controllers/portal_controller.js.map +1 -1
- package/dist/controllers/preview_guard_controller.d.ts +10 -4
- package/dist/controllers/preview_guard_controller.js +232 -116
- package/dist/controllers/preview_guard_controller.js.map +1 -1
- package/dist/controllers/progress_controller.d.ts +11 -0
- package/dist/controllers/progress_controller.js +125 -56
- package/dist/controllers/progress_controller.js.map +1 -1
- package/dist/controllers/radio_group_controller.d.ts +14 -5
- package/dist/controllers/radio_group_controller.js +117 -137
- package/dist/controllers/radio_group_controller.js.map +1 -1
- package/dist/controllers/range_slider_controller.d.ts +43 -3
- package/dist/controllers/range_slider_controller.js +192 -105
- package/dist/controllers/range_slider_controller.js.map +1 -1
- package/dist/controllers/rating_controller.d.ts +20 -4
- package/dist/controllers/rating_controller.js +418 -207
- package/dist/controllers/rating_controller.js.map +1 -1
- package/dist/controllers/read_more_controller.d.ts +2 -0
- package/dist/controllers/read_more_controller.js +134 -63
- package/dist/controllers/read_more_controller.js.map +1 -1
- package/dist/controllers/reading_progress_controller.d.ts +1 -1
- package/dist/controllers/reading_progress_controller.js +147 -135
- package/dist/controllers/reading_progress_controller.js.map +1 -1
- package/dist/controllers/relative_time_controller.d.ts +18 -4
- package/dist/controllers/relative_time_controller.js +145 -110
- package/dist/controllers/relative_time_controller.js.map +1 -1
- package/dist/controllers/reset_on_restore_controller.d.ts +85 -0
- package/dist/controllers/{reset_before_cache_controller.js → reset_on_restore_controller.js} +97 -38
- package/dist/controllers/reset_on_restore_controller.js.map +1 -0
- package/dist/controllers/resizable_controller.d.ts +28 -2
- package/dist/controllers/resizable_controller.js +255 -139
- package/dist/controllers/resizable_controller.js.map +1 -1
- package/dist/controllers/roving_controller.js +39 -84
- package/dist/controllers/roving_controller.js.map +1 -1
- package/dist/controllers/scroll_area_controller.d.ts +7 -3
- package/dist/controllers/scroll_area_controller.js +428 -225
- package/dist/controllers/scroll_area_controller.js.map +1 -1
- package/dist/controllers/scroll_restore_controller.js +0 -53
- package/dist/controllers/scroll_restore_controller.js.map +1 -1
- package/dist/controllers/scroll_visibility_controller.d.ts +28 -12
- package/dist/controllers/scroll_visibility_controller.js +395 -145
- package/dist/controllers/scroll_visibility_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.d.ts +6 -1
- package/dist/controllers/scrollspy_controller.js +181 -242
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/separator_controller.d.ts +19 -4
- package/dist/controllers/separator_controller.js +267 -140
- package/dist/controllers/separator_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.d.ts +64 -7
- package/dist/controllers/sidebar_controller.js +1023 -386
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.d.ts +23 -0
- package/dist/controllers/skeleton_controller.js +248 -97
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/slider_controller.d.ts +27 -1
- package/dist/controllers/slider_controller.js +159 -79
- package/dist/controllers/slider_controller.js.map +1 -1
- package/dist/controllers/smart_sticky_header_controller.d.ts +21 -3
- package/dist/controllers/smart_sticky_header_controller.js +162 -63
- package/dist/controllers/smart_sticky_header_controller.js.map +1 -1
- package/dist/controllers/sortable_controller.js +0 -112
- package/dist/controllers/sortable_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.d.ts +39 -4
- package/dist/controllers/spinner_controller.js +277 -169
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/step_indicator_controller.d.ts +5 -0
- package/dist/controllers/step_indicator_controller.js +99 -46
- package/dist/controllers/step_indicator_controller.js.map +1 -1
- package/dist/controllers/stepper_controller.d.ts +12 -3
- package/dist/controllers/stepper_controller.js +114 -73
- package/dist/controllers/stepper_controller.js.map +1 -1
- package/dist/controllers/stick_to_bottom_controller.d.ts +6 -0
- package/dist/controllers/stick_to_bottom_controller.js +262 -138
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
- package/dist/controllers/sticky_observer_controller.d.ts +11 -0
- package/dist/controllers/sticky_observer_controller.js +214 -49
- package/dist/controllers/sticky_observer_controller.js.map +1 -1
- package/dist/controllers/submit_once_controller.d.ts +23 -8
- package/dist/controllers/submit_once_controller.js +294 -205
- package/dist/controllers/submit_once_controller.js.map +1 -1
- package/dist/controllers/switch_controller.d.ts +12 -1
- package/dist/controllers/switch_controller.js +33 -60
- package/dist/controllers/switch_controller.js.map +1 -1
- package/dist/controllers/tabs_controller.d.ts +2 -2
- package/dist/controllers/tabs_controller.js +35 -29
- package/dist/controllers/tabs_controller.js.map +1 -1
- package/dist/controllers/tags_input_controller.d.ts +12 -0
- package/dist/controllers/tags_input_controller.js +136 -145
- package/dist/controllers/tags_input_controller.js.map +1 -1
- package/dist/controllers/textarea_autosize_controller.d.ts +10 -0
- package/dist/controllers/textarea_autosize_controller.js +71 -58
- package/dist/controllers/textarea_autosize_controller.js.map +1 -1
- package/dist/controllers/theme_controller.d.ts +21 -9
- package/dist/controllers/theme_controller.js +130 -112
- package/dist/controllers/theme_controller.js.map +1 -1
- package/dist/controllers/time_picker_controller.d.ts +18 -1
- package/dist/controllers/time_picker_controller.js +146 -80
- package/dist/controllers/time_picker_controller.js.map +1 -1
- package/dist/controllers/toast_controller.d.ts +36 -11
- package/dist/controllers/toast_controller.js +186 -297
- package/dist/controllers/toast_controller.js.map +1 -1
- package/dist/controllers/toggle_group_controller.d.ts +12 -3
- package/dist/controllers/toggle_group_controller.js +95 -136
- package/dist/controllers/toggle_group_controller.js.map +1 -1
- package/dist/controllers/toolbar_controller.js +68 -98
- package/dist/controllers/toolbar_controller.js.map +1 -1
- package/dist/controllers/tooltip_controller.d.ts +45 -3
- package/dist/controllers/tooltip_controller.js +158 -124
- package/dist/controllers/tooltip_controller.js.map +1 -1
- package/dist/controllers/transition_controller.d.ts +22 -4
- package/dist/controllers/transition_controller.js +123 -119
- package/dist/controllers/transition_controller.js.map +1 -1
- package/dist/controllers/tree_view_controller.d.ts +21 -11
- package/dist/controllers/tree_view_controller.js +150 -345
- package/dist/controllers/tree_view_controller.js.map +1 -1
- package/dist/index.d.ts +8 -5
- package/dist/index.js +6370 -9346
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +23 -3
- package/dist/inspector/cli.js +92 -37
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +92 -56
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +8 -8
- package/dist/inspector/manifest.json +787 -100
- package/dist/positioning/index.d.ts +8 -0
- package/dist/positioning/index.js +148 -47
- package/dist/positioning/index.js.map +1 -1
- package/package.json +6 -6
- package/dist/controllers/reset_before_cache_controller.d.ts +0 -76
- package/dist/controllers/reset_before_cache_controller.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/before_cache_reset.ts","../../src/utils/escape_layer.ts","../../src/utils/focus_candidate.ts","../../src/utils/focus_trap.ts","../../src/utils/state_reason.ts","../../src/utils/safe_timeout.ts","../../src/utils/transition_completion.ts","../../src/controllers/drawer_controller.ts"],"names":[],"mappings":";;;;;AA2CO,IAAM,gBAAA,GAAN,MAAM,iBAAA,CAAiB;AAAA;AAAA,EAE5B,OAAgB,YAAA,mBAAe,IAAI,GAAA,EAAsB;AAAA;AAAA,EAGzD,OAAgB,iBAAiB,MAAY;AAC3C,IAAA,KAAA,MAAW,UAAA,IAAc,iBAAA,CAAiB,YAAA,EAAc,UAAA,CAAW,OAAA,EAAQ;AAAA,EAC7E,CAAA;AAAA,EAES,OAAA;AAAA;AAAA,EAGT,YAAY,MAAA,EAAoB;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,MAAA;AAAA,EACjB;AAAA;AAAA,EAGA,QAAA,GAAiB;AACf,IAAA,MAAM,KAAA,GAAQ,iB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;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,oBAAA,GAA6B;AAC3B,IAAA,MAAM,QAAQ,IAAA,CAAK,WAAA;AACnB,IAAA,IAAA,CAAK,YAAA,GAAe,KAAA;AACpB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,KAAA,EAAO,MAAM,IAAA,CAAK,YAAA,CAAa,KAAK,CAAC,CAAA;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,aAAa,KAAA,EAA0B;AACrC,IAAA,KAAA,CAAM,MAAA,GAAS,IAAA;AACf,IAAA,IAAI,IAAA,CAAK,gBAAA,EAAkB,IAAA,CAAK,aAAA,CAAc,MAAA,GAAS,IAAA;AACvD,IAAA,IAAA,CAAK,MAAM,UAAA,EAAW;AAAA,EACxB;AAAA;AAAA,EAGA,IAAI,OAAA,GAAmB;AACrB,IAAA,OAAO,KAAK,cAAA,IAAkB,IAAA,CAAK,WAAA,CAAY,YAAA,CAAa,YAAY,CAAA,KAAM,MAAA;AAAA,EAChF;AACF","file":"drawer_controller.js","sourcesContent":["/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way.\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest handler resolves the\n * press. A keydown that is part of an IME composition (`event.isComposing`)\n * cancels the composition, never a layer, and is ignored here for every layer\n * at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered.\n */\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n stack: EscapeLayer[];\n onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = new WeakMap<Document, EscapeLayerRegistry>();\n\n #ownerDocument: Document | null = null;\n /** Dismissal callback while active; `null` when inactive. */\n #onDismiss: (() => void) | null = null;\n /** Live predicate deciding whether the layer claims a press; `null` = always. */\n #claims: (() => boolean) | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n registry.stack.push(this);\n this.#ownerDocument = ownerDocument;\n this.#onDismiss = options.onDismiss;\n this.#claims = options.claims ?? null;\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return;\n\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (registry) {\n const index = registry.stack.lastIndexOf(this);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n ownerDocument.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(ownerDocument);\n }\n }\n this.#ownerDocument = null;\n this.#onDismiss = null;\n this.#claims = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return false;\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === this;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.#onDismiss?.();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: EscapeLayer[]): EscapeLayer | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.#claims && !layer.#claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported on its own for callers that need the disabled-inheritance rule without\n * the rest of {@link canTakeFocus} — a control's availability check, or a `hidden`\n * walk bounded at a widget root, which is a different rule to compose with.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the four conditions that make the platform refuse\n * focus are checked: `hidden` / `inert` (an ancestor's counts),\n * `input[type=\"hidden\"]`, the native `disabled` property, and `disabled`\n * inherited from an ancestor `fieldset`. CSS-only invisibility is handled by\n * {@link isRenderedForFocus} when a consumer needs sequential-focus semantics.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n if (element.closest(\"[hidden], [inert]\")) return false;\n if (element instanceof HTMLInputElement && element.type === \"hidden\") return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n\n/** Elements whose semantics or authored attributes can place them in sequential focus order. */\nexport const TAB_STOP_CANDIDATE_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"iframe\",\n \"audio[controls]\",\n \"video[controls]\",\n \"[tabindex]\",\n \"[contenteditable]\",\n].join(\",\");\n\n/** Optional browser visibility API used to exclude CSS-hidden candidates. */\ninterface VisibilityCheckable {\n checkVisibility?: (options?: { visibilityProperty?: boolean }) => boolean;\n}\n\n/** Whether CSS visibility allows an otherwise eligible element to participate in focus order. */\nexport function isRenderedForFocus(element: HTMLElement): boolean {\n const check = (element as HTMLElement & VisibilityCheckable).checkVisibility;\n return typeof check === \"function\" ? check.call(element, { visibilityProperty: true }) : true;\n}\n\n/** Parses an authored `tabindex`; invalid syntax has no explicit focus-order meaning. */\nfunction authoredTabindex(element: HTMLElement): number | null {\n const value = element.getAttribute(\"tabindex\");\n if (value === null || !/^[+-]?\\d+$/.test(value.trim())) return null;\n return Number(value);\n}\n\n/** Whether the element's native semantics place it in sequential focus order. */\nfunction hasNativeTabStop(element: HTMLElement): boolean {\n if (element instanceof HTMLAnchorElement || element instanceof HTMLAreaElement) {\n return element.hasAttribute(\"href\");\n }\n if (\n element instanceof HTMLButtonElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n ) {\n return true;\n }\n if (element instanceof HTMLInputElement) return element.type !== \"hidden\";\n if (element instanceof HTMLIFrameElement) return true;\n if (element.tagName === \"AUDIO\" || element.tagName === \"VIDEO\") {\n return element.hasAttribute(\"controls\");\n }\n if (element instanceof HTMLElement && element.tagName === \"SUMMARY\") {\n const details = element.parentElement;\n return (\n details instanceof HTMLDetailsElement &&\n Array.from(details.children).find((child) => child.tagName === \"SUMMARY\") === element\n );\n }\n return false;\n}\n\n/** Whether an explicit `contenteditable` value creates an editable tab stop. */\nfunction hasEditableTabStop(element: HTMLElement): boolean {\n const value = element.getAttribute(\"contenteditable\")?.toLowerCase();\n return value === \"\" || value === \"true\" || value === \"plaintext-only\";\n}\n\n/**\n * Whether an element is a usable sequential Tab stop right now.\n *\n * Native semantics, authored `tabindex`, editable hosts, inherited disabled state,\n * HTML `hidden`/`inert`, and CSS visibility are evaluated together. `aria-disabled`\n * remains focusable because it communicates unavailability without removing the\n * control from discovery order.\n */\nexport function isTabStop(element: HTMLElement): boolean {\n if (!canTakeFocus(element) || !isRenderedForFocus(element)) return false;\n\n const tabindex = authoredTabindex(element);\n if (tabindex !== null) return tabindex >= 0;\n return hasNativeTabStop(element) || hasEditableTabStop(element);\n}\n\n/** Returns every usable sequential Tab stop below `root` in document order. */\nexport function tabStopsWithin(root: ParentNode): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)).filter(\n isTabStop,\n );\n}\n\n/** Returns the first usable sequential Tab stop below `root`, if one exists. */\nexport function firstTabStop(root: ParentNode): HTMLElement | null {\n for (const candidate of root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)) {\n if (isTabStop(candidate)) return candidate;\n }\n return null;\n}\n\n/** Whether `root` contains at least one usable sequential Tab stop. */\nexport function hasTabStop(root: ParentNode): boolean {\n return firstTabStop(root) !== null;\n}\n","import { BeforeCacheReset } from \"./before_cache_reset\";\nimport { EscapeLayer } from \"./escape_layer\";\nimport { tabStopsWithin } from \"./focus_candidate\";\n\n/**\n * Modal focus-trap primitive shared by the modal-overlay controllers\n * (dialog / alert-dialog / confirm / drawer / command-palette / sidebar); the\n * non-modal focus scope (focus) reuses it with the modal side effects opted out.\n *\n * The WAI-ARIA APG modal pattern is more than \"cycle Tab inside a box\": a modal\n * also locks background scroll, makes the rest of the page `inert` (so assistive\n * technology and pointer/Tab cannot reach it, honoring `aria-modal=\"true\"`),\n * sends focus inside on open, and restores it to the opener on close — and every\n * one of those side effects must be reverted if the element is torn down while\n * open (a Turbo navigation mid-dialog) and kept out of the snapshot Turbo\n * caches (`turbo:before-cache`). {@link FocusTrap} owns that whole modal\n * lifecycle so each controller only decides *when* to open/close and *what*\n * \"close\" means.\n *\n * It is intentionally **policy-free about closing**. Escape semantics differ per\n * widget (a plain dialog just closes; an alert-dialog closes *as a cancel* with a\n * reason; a drawer runs an exit transition), so the trap merely forwards Escape\n * to an {@link FocusTrapOptions.onEscape | onEscape} callback and never decides on\n * its own what closing entails.\n *\n * @remarks\n * The container is read through a getter so a controller can hand over a Stimulus\n * target without worrying about when the trap instance is constructed relative to\n * `connect()`.\n */\n\n/** Behavior hooks a controller supplies when constructing a {@link FocusTrap}. */\nexport interface FocusTrapOptions {\n /**\n * Called when `Escape` is pressed while the trap is active. When omitted,\n * `Escape` is left alone (the trap never joins the Escape stack). Dismissal\n * is resolved by the shared {@link EscapeLayer}: an Escape already consumed\n * by an inner handler is ignored, and among active layers the most recently\n * activated claiming one owns the press. The resolver consumes the event\n * before invoking the callback.\n */\n onEscape?: () => void;\n /**\n * Returns the element to focus when the trap activates. When it returns `null`\n * (or is omitted), the first focusable descendant is used, falling back to the\n * container itself (made programmatically focusable with `tabindex=-1`).\n */\n initialFocus?: () => HTMLElement | null;\n /**\n * Returns the element to focus on deactivation when nothing was focused before\n * the trap opened (e.g. the trigger). The element focused *before* opening\n * always takes precedence.\n */\n fallbackFocus?: () => HTMLElement | null;\n /**\n * Lock background scroll (`body` overflow) while active. Defaults to `true` for\n * the modal overlays; a lighter focus scope passes `false`. Read on `activate`.\n */\n lockScroll?: boolean | (() => boolean);\n /**\n * Make background siblings `inert` while active (the `aria-modal` isolation).\n * Defaults to `true` for the modal overlays; a soft focus scope can opt out so\n * the background stays reachable while `Tab` still cycles inside. Read on `activate`.\n */\n isolate?: boolean | (() => boolean);\n /**\n * Move focus inside on `activate`. Defaults to `true`; a focus scope that only\n * wants the `Tab` boundary (no focus move) passes `false`. Read on `activate`.\n */\n autoFocus?: boolean | (() => boolean);\n}\n\n/**\n * Owns the modal side effects (scroll lock, background `inert`, focus trap, focus\n * restore) for a single container, applied on {@link activate} and reverted on\n * {@link deactivate}.\n */\nexport class FocusTrap {\n /** The element focused before activation, restored on deactivation. */\n #previouslyFocused: HTMLElement | null = null;\n /** The body's inline `overflow` before locking, restored on deactivation. */\n #previousBodyOverflow = \"\";\n /** Whether scroll was locked this activation (so it is only restored if applied). */\n #scrollLocked = false;\n /** Background siblings made `inert` while active, restored on deactivation. */\n #inertedSiblings: HTMLElement[] = [];\n /** Whether the modal side effects are currently applied. */\n #activeState = false;\n /** Registers the trap on the shared Escape stack while active (see {@link EscapeLayer}). */\n readonly #escapeLayer = new EscapeLayer();\n\n /** Returns the trapped element; called on every operation for the live target. */\n readonly #getContainer: () => HTMLElement;\n /** Closing/focus hooks; see {@link FocusTrapOptions}. */\n readonly #options: FocusTrapOptions;\n\n /**\n * @param getContainer - Returns the trapped element. Called on every operation\n * so the live target is always used.\n * @param options - Closing/focus hooks; see {@link FocusTrapOptions}.\n */\n constructor(getContainer: () => HTMLElement, options: FocusTrapOptions = {}) {\n this.#getContainer = getContainer;\n this.#options = options;\n }\n\n /** Whether the trap is currently active. */\n get active(): boolean {\n return this.#activeState;\n }\n\n /**\n * Applies the trap: records the current focus, optionally locks background scroll\n * and makes background siblings `inert`, listens for `Tab`/`Escape`, and (unless\n * `autoFocus` is off) moves focus inside. No-ops if already active.\n */\n activate(): void {\n if (this.#activeState) return;\n this.#activeState = true;\n // Record the opener so it can be refocused on close. `<body>` (the default\n // active element when nothing is focused) is treated as \"nothing\", so the\n // fallback target — typically the trigger — wins in that case.\n const active = document.activeElement;\n this.#previouslyFocused =\n active instanceof HTMLElement && active !== document.body ? active : null;\n if (this.#flag(this.#options.lockScroll, true)) {\n this.#previousBodyOverflow = document.body.style.overflow;\n document.body.style.overflow = \"hidden\";\n this.#scrollLocked = true;\n }\n if (this.#flag(this.#options.isolate, true)) this.#isolateBackground();\n document.addEventListener(\"keydown\", this.#onKeydown);\n this.#beforeCache.activate();\n const onEscape = this.#options.onEscape;\n if (onEscape) this.#escapeLayer.activate(document, { onDismiss: () => onEscape() });\n if (this.#flag(this.#options.autoFocus, true)) this.#focusInitial();\n }\n\n /**\n * Reverts every side effect applied by {@link activate}. No-ops if inactive, so\n * a controller can call it defensively from both `close()` and `disconnect()`.\n *\n * @param restoreFocus - Move focus back to the opener (default `true`). Pass\n * `false` on teardown (`disconnect`), where yanking focus is undesirable.\n */\n deactivate({ restoreFocus = true }: { restoreFocus?: boolean } = {}): void {\n if (!this.#activeState) return;\n this.#activeState = false;\n this.#escapeLayer.deactivate();\n document.removeEventListener(\"keydown\", this.#onKeydown);\n this.#beforeCache.deactivate();\n if (this.#scrollLocked) {\n document.body.style.overflow = this.#previousBodyOverflow;\n this.#scrollLocked = false;\n }\n this.#releaseBackground();\n if (restoreFocus) {\n const target = this.#previouslyFocused ?? this.#options.fallbackFocus?.() ?? null;\n target?.focus();\n }\n }\n\n /** Resolves a boolean-or-getter option, defaulting when it was not provided. */\n #flag(option: boolean | (() => boolean) | undefined, fallback: boolean): boolean {\n if (option === undefined) return fallback;\n return typeof option === \"function\" ? option() : option;\n }\n\n /**\n * Reverts the side effects just before Turbo caches the page snapshot, so an\n * overlay left open does not bake the scroll lock into `body[style]` — a\n * restored page would feed that locked value back into {@link activate} as the\n * baseline, and closing would then never unlock the page. Markup state stays\n * untouched (restore-open designs reopen against a clean baseline), and focus\n * is left alone mid-navigation. The listener lives only while active.\n */\n readonly #beforeCache = new BeforeCacheReset(() => this.deactivate({ restoreFocus: false }));\n\n /**\n * Handles `Tab` (focus trap) while active. `Escape` dismissal is owned by the\n * shared {@link EscapeLayer} resolver, so Tab trapping stays independent of\n * which layer currently owns Escape.\n */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (event.key === \"Tab\") this.#trapTab(event);\n };\n\n /** Keeps `Tab` focus cycling within the container's focusable elements. */\n #trapTab(event: KeyboardEvent): void {\n const focusable = this.#focusableElements();\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = document.activeElement;\n\n // If focus has somehow escaped the container, pull it back to the first item.\n if (!(active instanceof Node) || !this.#getContainer().contains(active)) {\n event.preventDefault();\n first?.focus();\n return;\n }\n\n if (event.shiftKey && active === first) {\n event.preventDefault();\n last?.focus();\n } else if (!event.shiftKey && active === last) {\n event.preventDefault();\n first?.focus();\n }\n }\n\n /**\n * Marks every element outside the container's subtree as `inert` so background\n * content cannot be focused or reached by assistive technology, honoring the\n * `aria-modal=\"true\"` contract. An element that was *already* `inert` is left\n * untracked so `#releaseBackground` does not wrongly clear it.\n *\n * The walk climbs from the container to `body` and inerts each ancestor's other\n * children. Scanning only `body`'s children would skip the branch the container\n * sits in — everything beside it inside that branch is background too, and a\n * nested container is the ordinary case.\n */\n #isolateBackground(): void {\n const container = this.#getContainer();\n this.#inertedSiblings = [];\n for (let node: HTMLElement = container; node !== document.body; ) {\n const parent = node.parentElement;\n if (!parent) break;\n for (const sibling of Array.from(parent.children)) {\n if (!(sibling instanceof HTMLElement)) continue;\n if (sibling === node || sibling.inert) continue;\n sibling.inert = true;\n this.#inertedSiblings.push(sibling);\n }\n node = parent;\n }\n }\n\n /** Reverts the `inert` flags applied by `#isolateBackground`. */\n #releaseBackground(): void {\n for (const sibling of this.#inertedSiblings) {\n sibling.inert = false;\n }\n this.#inertedSiblings = [];\n }\n\n /** Moves focus to the initial target, the first focusable, or the container. */\n #focusInitial(): void {\n const preferred = this.#options.initialFocus?.();\n if (preferred) {\n preferred.focus();\n return;\n }\n const focusable = this.#focusableElements();\n if (focusable[0]) {\n focusable[0].focus();\n return;\n }\n const container = this.#getContainer();\n container.tabIndex = -1;\n container.focus();\n }\n\n /** Collects the container's currently focusable descendants in DOM order. */\n #focusableElements(): HTMLElement[] {\n return tabStopsWithin(this.#getContainer());\n }\n}\n","/**\n * Why a component's public open/closed state moved, carried as `detail.reason`\n * on the state event that reports the move.\n *\n * The attribute a component publishes (`aria-expanded`, `hidden`, `data-state`)\n * only says *what* the state is now. A subscriber that mirrors the state\n * elsewhere, or reports it, needs *why*: closing on `Escape` and closing because\n * the consumer called the action are the same attribute write and different\n * events to the page around it.\n *\n * `\"api\"` is the one every subscriber has to look at. A close the consumer asked\n * for arrives back at their own listener, so a listener that closes something\n * else on `close` loops unless it ignores its own calls.\n *\n * | Reason | The state moved because |\n * | --- | --- |\n * | `\"user\"` | a control of this component was operated |\n * | `\"select\"` | an item inside it was activated |\n * | `\"escape\"` | `Escape` was pressed and this layer owned it |\n * | `\"outside\"` | a pointer landed outside it, or on its backdrop |\n * | `\"focus\"` | focus entered or left it |\n * | `\"pointer\"` | the pointer entered or left it |\n * | `\"scroll\"` | a tracked scroll container scrolled |\n * | `\"api\"` | a public action was called with no DOM event |\n */\nexport type StateReason =\n | \"user\"\n | \"select\"\n | \"escape\"\n | \"outside\"\n | \"focus\"\n | \"pointer\"\n | \"scroll\"\n | \"api\";\n\n/** Focus modality: the events a focus move delivers to an action. */\nconst FOCUS_EVENTS = new Set([\"blur\", \"focus\", \"focusin\", \"focusout\"]);\n\n/** Pointer modality: the crossing events an action is bound to for hover. */\nconst POINTER_EVENTS = new Set([\"mouseenter\", \"mouseleave\", \"pointerenter\", \"pointerleave\"]);\n\n/**\n * Reads the interaction behind a **public action** from the DOM event it was\n * handed.\n *\n * Stimulus always passes the event to an action it invoked from `data-action`,\n * and a consumer calling the method themselves passes nothing — which is what\n * separates `\"api\"` from the rest.\n *\n * Only an action entry may resolve a reason this way. Inside the component the\n * event type no longer identifies the interaction: one `click` is the trigger\n * being pressed, the page outside being pressed, and an item being activated,\n * and those paths pass their own reason instead.\n *\n * @param event - The event the action received, if any.\n * @returns `\"api\"` with no event, else the modality the event type names, else\n * `\"user\"`.\n *\n * @example\n * ```ts\n * toggle(event?: Event): void {\n * this.#apply(!this.#isOpen, stateReasonFor(event));\n * }\n * ```\n */\nexport function stateReasonFor(event?: Event | null): \"user\" | \"focus\" | \"pointer\" | \"api\" {\n if (!event) return \"api\";\n if (FOCUS_EVENTS.has(event.type)) return \"focus\";\n if (POINTER_EVENTS.has(event.type)) return \"pointer\";\n return \"user\";\n}\n","/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * 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/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { SafeTimeout } from \"./safe_timeout\";\n\n/** Computed transition fields needed to determine when an element has settled. */\nexport type TransitionStyle = Pick<\n CSSStyleDeclaration,\n \"transitionProperty\" | \"transitionDuration\" | \"transitionDelay\"\n>;\n\n/** Parsed transition property paired with its effective duration and delay. */\ninterface TransitionTiming {\n property: string;\n totalMs: number;\n}\n\n/** Parses a CSS `<time>` into milliseconds, returning `0` for malformed values. */\nfunction timeMs(value: string): number {\n const trimmed = value.trim();\n const amount = Number.parseFloat(trimmed);\n if (!Number.isFinite(amount)) return 0;\n if (trimmed.endsWith(\"ms\")) return amount;\n if (trimmed.endsWith(\"s\")) return amount * 1000;\n return 0;\n}\n\n/** Splits a computed comma-separated CSS list into normalized, non-empty items. */\nfunction cssList(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n/**\n * Pairs transition properties, durations, and delays using CSS list repetition.\n *\n * The `transition-property` list determines the number of transitions. Shorter\n * duration/delay lists repeat, while extra values are ignored. A negative delay\n * shortens the remaining wall-clock time, and a non-positive total is settled.\n */\nfunction transitionTimings(style: TransitionStyle): TransitionTiming[] {\n const properties = cssList(style.transitionProperty);\n const durations = cssList(style.transitionDuration).map(timeMs);\n const delays = cssList(style.transitionDelay).map(timeMs);\n const effectiveProperties =\n properties.length > 0\n ? properties\n : Array.from({ length: Math.max(durations.length, delays.length, 1) }, () => \"all\");\n const effectiveDurations = durations.length > 0 ? durations : [0];\n const effectiveDelays = delays.length > 0 ? delays : [0];\n\n return effectiveProperties\n .filter((property) => property !== \"none\")\n .map((property, index) => ({\n property,\n totalMs: Math.max(\n 0,\n (effectiveDurations[index % effectiveDurations.length] ?? 0) +\n (effectiveDelays[index % effectiveDelays.length] ?? 0),\n ),\n }));\n}\n\n/** Maximum total over already-parsed timings (0 when the list is empty). */\nfunction maxTotalMs(timings: TransitionTiming[]): number {\n return timings.reduce((max, { totalMs }) => Math.max(max, totalMs), 0);\n}\n\n/** Maximum effective transition duration plus delay, in milliseconds. */\nexport function maxTransitionTotalMs(style: TransitionStyle): number {\n return maxTotalMs(transitionTimings(style));\n}\n\n/** Optional tuning for a single {@link TransitionCompletion.wait} call. */\nexport interface TransitionWaitOptions {\n /**\n * Positive wall-clock override (ms) for the bounded fallback, replacing the\n * auto-computed `max + 50ms` timer verbatim. It also keeps the wait armed for\n * a computed 0ms transition (no synchronous completion): the consumer asserts\n * a transition budget that computed styles cannot see. Non-positive and\n * non-finite (`NaN` / `Infinity`) values are ignored.\n */\n timeoutMs?: number;\n}\n\n/**\n * Owns one cancellable wait for an element's CSS transitions to settle.\n *\n * When available, active CSS transitions provide their expanded property names.\n * Tracking those names lets shorthand declarations settle from their longhand\n * terminal events. A terminal event from an interrupted phase is ignored while a\n * replacement transition for the same property is still active. Because that set\n * is sampled when the wait is armed, a property whose transition only starts a\n * frame later would otherwise be settled over; the still-running set is therefore\n * re-read before completing and adopted when it is not yet empty. Without Web\n * Animations data, explicit transition properties retain the declared-property\n * behavior and the ambiguous `transition-property: all` form waits until the\n * computed maximum wall-clock time. A `max + 50ms` timeout is always armed\n * because browsers emit no terminal event when a property never transitions, an\n * ancestor disappears, or rendering is otherwise interrupted; a consumer with\n * better knowledge can replace that fallback via\n * {@link TransitionWaitOptions.timeoutMs}.\n */\nexport class TransitionCompletion {\n readonly #timers = new SafeTimeout();\n #element: HTMLElement | null = null;\n #complete: (() => void) | null = null;\n #pendingProperties: Set<string> | null = null;\n #deadline = 0;\n\n /**\n * Replaces any prior wait and invokes `complete` synchronously for a 0ms\n * transition (including when `getComputedStyle` is unavailable).\n *\n * With a positive `options.timeoutMs` the synchronous fast-path is skipped and\n * the override replaces the auto-computed fallback (see {@link TransitionWaitOptions}).\n */\n wait(element: HTMLElement, complete: () => void, options: TransitionWaitOptions = {}): void {\n this.cancel();\n\n const requested = options.timeoutMs ?? 0;\n const override = Number.isFinite(requested) && requested > 0 ? requested : 0;\n // A non-browser / partial-DOM environment cannot report a computable\n // transition, which is indistinguishable from a 0ms one.\n const timings =\n typeof window.getComputedStyle === \"function\"\n ? transitionTimings(window.getComputedStyle(element))\n : [];\n const maximum = maxTotalMs(timings);\n if (maximum <= 0 && override <= 0) {\n complete();\n return;\n }\n\n this.#element = element;\n this.#complete = complete;\n this.#deadline = Date.now() + maximum;\n const activeProperties = this.#activeTransitionProperties(element);\n this.#pendingProperties =\n activeProperties.size > 0 ? activeProperties : this.#explicitPendingProperties(timings);\n element.addEventListener(\"transitionend\", this.#onTerminal);\n element.addEventListener(\"transitioncancel\", this.#onTerminal);\n this.#timers.set(() => this.#finish(), override > 0 ? override : maximum + 50);\n }\n\n /** Cancels the pending wait without invoking its completion callback. */\n cancel(): void {\n this.#complete = null;\n this.#teardown();\n }\n\n /**\n * Handles terminal events from the observed element only.\n *\n * For explicit property lists, every declared positive-time property must\n * settle. For `all`, no reliable property set exists, so an event can finish\n * only after the computed maximum time; the safety timeout owns the usual path.\n */\n readonly #onTerminal = (event: Event): void => {\n if (event.target !== this.#element) return;\n const transitionEvent = event as TransitionEvent;\n // A pseudo-element's transition is reported with its originating element\n // as `target`; it must not settle the element's own transition.\n if (transitionEvent.pseudoElement) return;\n\n if (this.#pendingProperties) {\n const propertyName = transitionEvent.propertyName;\n const active = this.#activeTransitionProperties(this.#element);\n // An interrupted transition queues its cancel event before the replacement\n // phase starts, but dispatch can happen after the new wait is armed. The\n // replacement is then the active transition for this property, so the stale\n // terminal event must not settle the new phase.\n if (active.has(propertyName)) return;\n if (!this.#pendingProperties.delete(propertyName)) return;\n if (this.#pendingProperties.size > 0) return;\n // The tracked set is an arm-time snapshot, so a transition the phase starts\n // one frame later is absent from it. Re-reading the still-running set before\n // settling adopts those stragglers instead of completing over them; the\n // fallback timer stays armed, so this cannot extend the wait unboundedly.\n if (active.size > 0) {\n this.#pendingProperties = active;\n return;\n }\n this.#finish();\n return;\n }\n\n if (Date.now() >= this.#deadline) this.#finish();\n };\n\n /**\n * Returns active CSS transition properties expanded to the names reported by\n * terminal events. CSS animations and pseudo-element effects are excluded.\n */\n #activeTransitionProperties(element: HTMLElement | null): Set<string> {\n if (!element || typeof element.getAnimations !== \"function\") return new Set();\n\n try {\n const properties = element.getAnimations().flatMap((animation) => {\n if (animation.playState === \"idle\" || animation.playState === \"finished\") return [];\n const effect = animation.effect as KeyframeEffect | null;\n // A pseudo-element effect names the originating element as its target, so\n // `target` alone cannot separate it. Its terminal events are ignored, so\n // tracking its properties would only strand the wait on the fallback.\n if (effect?.pseudoElement) return [];\n const target = effect?.target;\n if (target && target !== element) return [];\n const property = (animation as Partial<CSSTransition>).transitionProperty;\n return typeof property === \"string\" && property.length > 0 ? [property] : [];\n });\n return new Set(properties);\n } catch {\n // Partial DOM implementations can expose getAnimations without supporting\n // it. The declared-property tracker and bounded timer remain safe fallbacks.\n return new Set();\n }\n }\n\n /** Returns explicit positive-time properties, or `null` for the ambiguous `all`. */\n #explicitPendingProperties(timings: TransitionTiming[]): Set<string> | null {\n if (timings.some(({ property }) => property === \"all\")) return null;\n const pending = new Set(\n timings.filter(({ totalMs }) => totalMs > 0).map(({ property }) => property),\n );\n // An empty set is only reachable through a timeout override (a 0ms transition\n // otherwise completes synchronously). With nothing to track, fall back to the\n // deadline rule so any terminal event can settle the wait, exactly like `all`.\n return pending.size > 0 ? pending : null;\n }\n\n /** Completes exactly once, releasing listeners and the fallback before the callback. */\n #finish(): void {\n const complete = this.#complete;\n if (!complete) return;\n this.#complete = null;\n this.#teardown();\n complete();\n }\n\n /** Releases the exact element listeners and timer owned by the current wait. */\n #teardown(): void {\n this.#timers.clearAll();\n this.#element?.removeEventListener(\"transitionend\", this.#onTerminal);\n this.#element?.removeEventListener(\"transitioncancel\", this.#onTerminal);\n this.#element = null;\n this.#pendingProperties = null;\n this.#deadline = 0;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { FocusTrap } from \"../utils/focus_trap\";\nimport { type StateReason, stateReasonFor } from \"../utils/state_reason\";\nimport { TransitionCompletion } from \"../utils/transition_completion\";\n\n/** Edge a drawer slides from; reflected as `data-placement` for the consumer CSS. */\ntype Placement = \"left\" | \"right\" | \"top\" | \"bottom\";\n\n/**\n * Headless, accessible **drawer / slide-over** behavior.\n *\n * Markup contract (identifier: `stimeo--drawer`):\n * <div data-controller=\"stimeo--drawer\" data-stimeo--drawer-placement-value=\"right\">\n * <button data-stimeo--drawer-target=\"trigger\"\n * data-action=\"click->stimeo--drawer#open\">Open panel</button>\n * <div data-stimeo--drawer-target=\"overlay\"\n * data-action=\"click->stimeo--drawer#closeOnBackdrop\" hidden>\n * <div data-stimeo--drawer-target=\"panel\" role=\"dialog\" aria-modal=\"true\"\n * aria-labelledby=\"t\" data-state=\"closed\" hidden>\n * <h2 id=\"t\">…</h2>\n * <button data-action=\"click->stimeo--drawer#close\">Close</button>\n * </div>\n * </div>\n * </div>\n *\n * Implements the WAI-ARIA APG **Dialog (Modal)** pattern. It is the same modal as\n * `stimeo--dialog`; what it adds is the state plumbing an enter/exit *slide*\n * needs: `data-state` (`open`/`closed`) is synced on the panel and overlay so CSS\n * can animate, and `hidden` is applied only *after* the close transition finishes\n * (so the exit animation can play). `placement` is reflected as `data-placement`\n * for the CSS to read — the controller never computes coordinates.\n *\n * @remarks\n * Behavior only. The modal lifecycle (focus trap, scroll lock, background\n * `inert`, focus restore, teardown reversal) is delegated to the shared\n * `FocusTrap`. Placement, slide direction, distance, and easing are all the\n * consumer's CSS — `data-placement` is merely a flag.\n *\n * Behavior provided:\n * - {@link DrawerController.open | open}/{@link DrawerController.close | close}\n * toggle `data-state` and (deferred) `hidden`.\n * - On open, focus moves to the first focusable element in the panel.\n * - `Tab`/`Shift+Tab` cycle focus within the panel; `Escape` closes.\n * - {@link closeOnBackdrop} closes only when the overlay *itself* is clicked.\n * - Each move of the open state is reported: `stimeo--drawer:open` and\n * `stimeo--drawer:close` dispatch `{ reason: StateReason }`, as soon as\n * `data-state` is written — the deferred `hidden` and the exit transition are\n * not waited for. Both are informational, so neither is cancelable. A call\n * that leaves the state where it already was, the normalization in\n * {@link connect}, the reconciliation that follows panel churn, and\n * {@link disconnect} are all silent.\n */\nexport class DrawerController extends Controller<HTMLElement> {\n static override targets = [\"trigger\", \"overlay\", \"panel\"];\n static override values = {\n placement: { type: String, default: \"right\" },\n open: { type: Boolean, default: false },\n };\n static actions = [\"close\", \"closeOnBackdrop\", \"open\"] as const;\n static events = [\"close\", \"open\"] as const;\n\n declare readonly triggerTarget: HTMLElement;\n declare readonly overlayTarget: HTMLElement;\n declare readonly panelTarget: HTMLElement;\n declare readonly hasTriggerTarget: boolean;\n declare readonly hasOverlayTarget: boolean;\n declare readonly hasPanelTarget: boolean;\n\n declare placementValue: string;\n declare openValue: boolean;\n\n /** Exact panel currently owned by the modal lifecycle (survives target churn safely). */\n #activePanel: HTMLElement | null = null;\n\n /** Owns the modal side effects; Escape closes, focus falls back to the trigger. */\n readonly #trap = new FocusTrap(() => this.#activePanel ?? this.panelTarget, {\n onEscape: () => this.#close(\"escape\"),\n fallbackFocus: () => (this.hasTriggerTarget ? this.triggerTarget : null),\n });\n\n /** Owns the cancellable close-transition wait and its bounded fallback. */\n readonly #transition = new TransitionCompletion();\n /** Distinguishes dynamic target churn from callbacks around controller teardown. */\n #connected = false;\n\n /** Whether state moves are reported: set once `connect()` settled the baseline. */\n #reporting = false;\n\n /**\n * Reflects placement and establishes the initial open/closed state.\n *\n * The DOM is the source of truth on reconnect (Turbo cache restore / morph): a\n * restored snapshot whose panel is already `data-state=\"open\"` stays open\n * rather than being re-derived from the declarative `open` Value (which would\n * close a user-opened drawer). The `open` Value only seeds a genuinely fresh\n * render. We normalize to a clean closed baseline first so\n * {@link DrawerController.open | open} runs its full reveal + trap activation —\n * the `FocusTrap` is inactive after a disconnect and must be re-activated.\n */\n override connect(): void {\n this.#connected = true;\n this.#activePanel = this.hasPanelTarget ? this.panelTarget : null;\n this.#reflectPlacement();\n const shouldOpen = this.#isOpen || this.openValue;\n this.#applyClosedState();\n if (shouldOpen) this.#open(\"api\");\n this.#reporting = true;\n }\n\n /** Reverts the modal side effects and pending hide if torn down while open. */\n override disconnect(): void {\n this.#connected = false;\n this.#reporting = false;\n this.#transition.cancel();\n this.#trap.deactivate({ restoreFocus: false });\n this.#activePanel = null;\n }\n\n /** Adopts a panel target added by a Turbo morph after the controller connected. */\n panelTargetConnected(panel: HTMLElement): void {\n if (!this.#connected || (this.#activePanel?.isConnected && this.#activePanel !== panel)) return;\n this.#adoptPanel(panel);\n }\n\n /** Closes and releases modal side effects when the actively trapped panel disappears. */\n panelTargetDisconnected(panel: HTMLElement): void {\n if (panel !== this.#activePanel) return;\n this.#transition.cancel();\n this.#activePanel = null;\n if (!this.#connected) return;\n\n panel.setAttribute(\"data-state\", \"closed\");\n panel.hidden = true;\n if (this.hasOverlayTarget) {\n this.overlayTarget.setAttribute(\"data-state\", \"closed\");\n this.overlayTarget.hidden = true;\n }\n this.openValue = false;\n this.#trap.deactivate();\n\n // Handles morph implementations that add the replacement before removing\n // the old target (its connected callback was intentionally ignored above).\n if (this.hasPanelTarget) this.#adoptPanel(this.panelTarget);\n }\n\n /** Keeps `data-placement` in sync if the value changes at runtime. */\n placementValueChanged(): void {\n this.#reflectPlacement();\n }\n\n /** Opens the drawer: reveals it, syncs `data-state`, traps focus. */\n open(event?: Event): void {\n this.#open(stateReasonFor(event));\n }\n\n /** Reveals the drawer, syncs `data-state`, reports a move, then traps focus. */\n #open(reason: StateReason): void {\n if (!this.hasPanelTarget || this.#isOpen) return;\n this.#transition.cancel();\n this.#activePanel = this.panelTarget;\n // Reveal the panel/overlay while they are still in their `data-state=\"closed\"`\n // (off-screen) position, so the browser has a rendered \"from\" frame.\n this.panelTarget.hidden = false;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = false;\n // Force a reflow to commit that closed frame before flipping to \"open\"; without\n // it the enter transition is skipped (going straight from display:none to the\n // open position paints no intermediate state, so the panel jumps in instead of\n // sliding). The exit transition already works because the panel stays displayed.\n void this.panelTarget.offsetWidth;\n this.#setState(\"open\");\n this.openValue = true;\n if (this.#reporting) this.dispatch(\"open\", { detail: { reason }, cancelable: false });\n // A subscriber may close it again from the handler above. Everything below\n // applies to an element that is open; run it against a closed one and the\n // side effects have no path back — the later `close()` returns early.\n if (!this.#isOpen) return;\n this.#trap.activate();\n }\n\n /**\n * Closes the drawer: syncs `data-state` to start the exit transition, then\n * defers both `hidden` *and* the modal teardown (scroll lock / background\n * `inert` / focus restore) until the transition finishes. This keeps the\n * background inert and focus trapped while the drawer is still visually on\n * screen, preserving the modal contract during the exit animation.\n */\n close(event?: Event): void {\n this.#close(stateReasonFor(event));\n }\n\n /** Closes only when the overlay itself (not its contents) is clicked. */\n closeOnBackdrop(event: MouseEvent): void {\n if (this.hasOverlayTarget && event.target === this.overlayTarget) this.#close(\"outside\");\n }\n\n /** Starts the exit transition, reports a move, then defers `hidden` and teardown. */\n #close(reason: StateReason): void {\n if (!this.hasPanelTarget || !this.#isOpen) return;\n this.openValue = false;\n this.#setState(\"closed\");\n if (this.#reporting) this.dispatch(\"close\", { detail: { reason }, cancelable: false });\n // A subscriber may reopen it from the handler above; hiding after the exit\n // transition would then apply `hidden` to a drawer that is on screen.\n if (this.#isOpen) return;\n this.#hideAfterTransition();\n }\n\n /**\n * Writes `data-placement` from the current `placement` value.\n *\n * @stimeoRenderRoot\n */\n #reflectPlacement(): void {\n if (this.hasPanelTarget) this.panelTarget.setAttribute(\"data-placement\", this.#placement);\n }\n\n /**\n * Reconciles a replacement panel and companion overlay from its explicit DOM state.\n *\n * @stimeoRenderRoot\n */\n #adoptPanel(panel: HTMLElement): void {\n this.#transition.cancel();\n const trapWasActive = this.#trap.active;\n this.#activePanel = panel;\n panel.setAttribute(\"data-placement\", this.#placement);\n if (panel.getAttribute(\"data-state\") === \"open\") {\n panel.hidden = false;\n if (this.hasOverlayTarget) {\n this.overlayTarget.setAttribute(\"data-state\", \"open\");\n this.overlayTarget.hidden = false;\n }\n this.openValue = true;\n if (trapWasActive) this.#trap.deactivate({ restoreFocus: false });\n this.#trap.activate();\n return;\n }\n\n panel.setAttribute(\"data-state\", \"closed\");\n panel.hidden = true;\n if (this.hasOverlayTarget) {\n this.overlayTarget.setAttribute(\"data-state\", \"closed\");\n this.overlayTarget.hidden = true;\n }\n this.openValue = false;\n this.#trap.deactivate();\n }\n\n /** Validated placement (`left`/`right`/`top`/`bottom`), defaulting to `right`. */\n get #placement(): Placement {\n const value = this.placementValue;\n return value === \"left\" || value === \"top\" || value === \"bottom\" ? value : \"right\";\n }\n\n /** Syncs `data-state` on the panel and overlay together. */\n #setState(state: \"open\" | \"closed\"): void {\n if (this.hasPanelTarget) this.panelTarget.setAttribute(\"data-state\", state);\n if (this.hasOverlayTarget) this.overlayTarget.setAttribute(\"data-state\", state);\n }\n\n /** Fully reflects the closed state up front (used on connect when not open). */\n #applyClosedState(): void {\n this.#setState(\"closed\");\n if (this.hasPanelTarget) this.panelTarget.hidden = true;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = true;\n }\n\n /**\n * Applies `hidden` once the panel's close transition ends, so the exit slide\n * can play. The shared waiter hides synchronously for 0ms transitions and\n * supplies a bounded fallback when the browser emits no terminal event.\n */\n #hideAfterTransition(): void {\n const panel = this.panelTarget;\n this.#activePanel = panel;\n this.#transition.wait(panel, () => this.#applyHidden(panel));\n }\n\n /**\n * Runs once the close transition has finished: applies `hidden` to the panel\n * and overlay, then reverts the modal side effects (scroll lock, background\n * `inert`, keydown listener) and restores focus to the opener. Deferring the\n * `FocusTrap` teardown to here — rather than at\n * {@link DrawerController.close | close} time — keeps the background unreachable\n * and focus trapped for the whole exit animation.\n */\n #applyHidden(panel: HTMLElement): void {\n panel.hidden = true;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = true;\n this.#trap.deactivate();\n }\n\n /** Whether the drawer is open (tracked via `data-state`, not `hidden`). */\n get #isOpen(): boolean {\n return this.hasPanelTarget && this.panelTarget.getAttribute(\"data-state\") === \"open\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/shared_registry.ts","../../src/utils/attribute_lease.ts","../../src/utils/detach_gate.ts","../../src/utils/escape_layer.ts","../../src/utils/focus_candidate.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/query_open_descendants.ts","../../src/utils/tabindex_loan.ts","../../src/utils/focus_trap.ts","../../src/utils/listener_set.ts","../../src/utils/morph_render_watcher.ts","../../src/utils/lived_mark.ts","../../src/utils/state_reason.ts","../../src/utils/safe_timeout.ts","../../src/utils/transition_completion.ts","../../src/controllers/drawer_controller.ts"],"names":["above"],"mappings":";;AA4BO,SAAS,cAAA,CAAiC,KAAa,MAAA,EAAoB;AAChF,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AAC7B,EAAA,MAAM,KAAA,GAAQ,UAAA;AACd,EAAA,MAAM,QAAA,GAAW,MAAM,MAAM,CAAA;AAC7B,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA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AI,CAAA;AACjE,IAAA,IAAA,CAAK,oBAAoB,IAAI,CAAA;AAAA,EAC/B;AAAA,EAOA,oBAAA,GAA6B;AAC3B,IAAA,MAAM,QAAQ,IAAA,CAAK,WAAA;AACnB,IAAA,IAAA,CAAK,YAAA,GAAe,KAAA;AACpB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,KAAA,EAAO,MAAM,IAAA,CAAK,YAAA,CAAa,KAAK,CAAC,CAAA;AAAA,EAC7D;AAAA,EAUA,aAAa,KAAA,EAA0B;AACrC,IAAA,IAAA,CAAK,YAAA,CAAa,OAAO,IAAI,CAAA;AAC7B,IAAA,IAAA,CAAK,oBAAoB,IAAI,CAAA;AAC7B,IAAA,IAAA,CAAK,MAAM,UAAA,EAAW;AAAA,EACxB;AAAA,EAGA,IAAI,OAAA,GAAmB;AACrB,IAAA,OAAO,KAAK,cAAA,IAAkB,IAAA,CAAK,WAAA,CAAY,YAAA,CAAa,YAAY,CAAA,KAAM,MAAA;AAAA,EAChF;AACF","file":"drawer_controller.js","sourcesContent":["/**\n * One registry per page for every copy of the library.\n *\n * Each `stimeo-ui/controllers/*` file, and each opt-in entry, is built on its own and carries\n * its own copy of every utility it uses, so a page that imports controllers one by one, or one\n * of them next to the barrel, evaluates a utility several times. A registry that coordinates\n * instances of different controllers — the stacks of leased values, the loans of a\n * `tabindex`, the Escape layers, the focus traps — must not be split by that: a dialog inside\n * a drawer, or a character counter and a form field on one input, coordinate whichever files\n * they came from. So such a registry lives once on `globalThis`, under a `Symbol.for` key the\n * copies agree on, and the first copy to ask for it creates it.\n *\n * The key names the registry and the version of its shape\n * (`stimeo-ui.<utility>.registry.v<n>`). Copies whose registries have the same shape share\n * one; a release that changes the shape changes the version, so a copy of another release\n * keeps a registry of its own instead of reading entries it does not understand — the two\n * then coordinate within each release only. An entry another copy put in a registry is read\n * through its fields alone, never through `#private` members, which belong to the class of\n * the copy that created it.\n */\n\n/**\n * The registry stored under `key`, created by `create` on first use.\n *\n * @param key - `stimeo-ui.<utility>.registry.v<n>`: the version is that of the shape `create`\n * returns.\n * @param create - Builds the empty registry.\n */\nexport function sharedRegistry<T extends object>(key: string, create: () => T): T {\n const symbol = Symbol.for(key);\n const scope = globalThis as unknown as Record<symbol, T | undefined>;\n const existing = scope[symbol];\n if (existing !== undefined) return existing;\n const registry = create();\n Object.defineProperty(globalThis, symbol, { value: registry });\n return registry;\n}\n","import { sharedRegistry } from \"./shared_registry\";\n\n/** What a lease's record says: the author's value, its last write, the leases beneath. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n readonly written: string | null;\n /** Whether it hands back what the lease right beneath it wrote last. */\n readonly linked: boolean;\n /** The records of the other owners' leases beneath it, nearest first. */\n readonly beneath: readonly string[];\n}\n\n/** One lease's hold on one element's attribute, in the stack every lease of it shares. */\ninterface AttributeHold {\n /** The lease holding it; `null` for a hold read from a copy's record until its lease takes it. */\n lease: object | null;\n readonly record: string;\n written: string | null;\n /** What it hands back with nothing beneath it: the author's value. */\n readonly original: string | null;\n /** Whether it hands back what the hold beneath it wrote last instead. */\n linked: boolean;\n}\n\n/** The holds on each element by attribute, and every lease's record name by attribute. */\ninterface AttributeLeaseRegistry {\n readonly stacks: WeakMap<Element, Map<string, AttributeHold[]>>;\n readonly names: Map<string, Set<string>>;\n}\n\n/** Whether a parsed record entry is an attribute value: a string, or `null` for absence. */\nfunction isAttributeValue(value: unknown): value is string | null {\n return value === null || typeof value === \"string\";\n}\n\n/**\n * Reads the record a lease left on `element`: the author's value, the value the lease wrote\n * last, whether it hands back the value beneath it (`false` before the names when it does not)\n * and the records beneath it. `undefined` when the record is missing or holds anything else.\n */\nfunction readLeaseRecord(element: Element, record: string): AttributeLeaseRecord | undefined {\n try {\n const parsed: unknown = JSON.parse(element.getAttribute(record) ?? \"null\");\n if (!Array.isArray(parsed)) return undefined;\n const [original, written, ...rest] = parsed as unknown[];\n const linked = rest[0] !== false;\n const beneath = linked ? rest : rest.slice(1);\n if (!beneath.every((under): under is string => typeof under === \"string\")) return undefined;\n return isAttributeValue(original) && isAttributeValue(written)\n ? { original, written, linked, beneath }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The value `element`'s author wrote for `attribute`, as the record a lease of any owner leaves\n * on the element carries it; `undefined` while no lease leaves one, as when nothing has moved\n * the attribute off the author's value. A field a reveal turned from `password` into `text`\n * still reads `\"password\"` here.\n */\nexport function leasedAuthorValue(element: Element, attribute: string): string | null | undefined {\n const suffix = `-${attribute}-lease`;\n for (const name of element.getAttributeNames()) {\n if (!name.startsWith(\"data-\") || !name.endsWith(suffix)) continue;\n const record = readLeaseRecord(element, name);\n if (record) return record.original;\n }\n return undefined;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * **Every lease of an attribute shares one stack of holds per element**, whatever its owner\n * and whichever file of the package constructed it (the stacks are one per page): the holds\n * sit in the order their leases first wrote the element, each with the value it wrote last.\n * The element's value is the highest hold's that carries it, and the page's when none does.\n * A write reaches the element unless a hold above the writer carries the element's value: the\n * top hold always shows its writes, a hold beneath it shows nothing while a hold above keeps\n * its value on the element, and once the page has put a value there that no hold carries, the\n * next write of any hold replaces it. A return gives a value back only from the hold the\n * element's value is: the value the hold beneath it wrote last, or the author's once nothing\n * is beneath it; any other return only leaves the stack, and the page's value stays. Holds\n * that wrote the same value are told apart by the stack, never by the value: the higher one\n * keeps it. A first write over a top hold whose value the page has replaced takes the\n * element's value as the author's. Two instances of one controller on one element — an\n * element outside their scope — stack the same way.\n *\n * A **base lease** (`{ base: true }`) holds the element's own state rather than a value over\n * it — a form field's ARIA on its control is one — so its first write goes to the bottom of\n * the stack, beneath the leases of other owners already there: a temporary value another\n * owner leased stays shown and returns to the base lease's latest value.\n *\n * **The stack travels with the element.** While a hold shows a value other than the author's,\n * lies on another hold or is covered by one, the element carries its owner's record\n * `data-<owner>-<attribute>-lease`: JSON of the author's value and the value the hold wrote\n * last (each a string, or `null` for an absent attribute), `false` where the hold hands back\n * the author's value rather than the latest value of the hold beneath it, and the records of\n * every hold beneath it, nearest first. Returning the last lease of an owner removes its\n * record. A copy of the element — a page Turbo restores from its cache is one — therefore\n * carries the stack, and the first lease to touch the copy reads it back under the record\n * names of the leases constructed so far, which include every lease that wrote a record the\n * cache holds, and orders the holds by the records each one lists beneath it. Each lease takes\n * the hold its owner's record describes over in place. Complete records for distinct owners\n * preserve their order across a copy. The records describe holds by owner, not by instance:\n * one owner holding the element more than once leaves only its topmost hold's record, which\n * the first of its leases to write or return on the copy takes. Lower holds of that owner and\n * their positions are absent; mutually listed owners cannot express their full live order.\n * A hold that showed the author's value alone carries no record and is taken by its first\n * write on the copy. Missing or unreadable records also leave their holds unknown, so copying\n * the DOM does not promise identical decisions for every live stack. Without a record it can\n * read, a new stack takes the current value as the author's. A Turbo morph removes records\n * absent from the server HTML; existing holds remain in memory until their leases return.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events,\n * and nothing rewinds a live page before Turbo caches it: `turbo:before-cache` also\n * fires on pages that stay.\n */\nexport class AttributeLease<T extends Element = Element> {\n /** The holds on each element, bottom first, and the record names; one per page. */\n static readonly #registry = sharedRegistry(\n \"stimeo-ui.attribute-lease.registry.v1\",\n (): AttributeLeaseRegistry => ({ stacks: new WeakMap(), names: new Map() }),\n );\n readonly #attribute: string;\n readonly #record: string;\n readonly #base: boolean;\n readonly #held = new Set<T>();\n\n /**\n * @param attribute - The attribute whose temporary values this lease owns.\n * @param owner - Names the record on the element; the controller's identifier.\n * @param options - `base`: written beneath the other owners' leases.\n */\n constructor(attribute: string, owner: string, options: { readonly base?: boolean } = {}) {\n this.#attribute = attribute;\n this.#record = `data-${owner}-${attribute}-lease`;\n this.#base = options.base === true;\n const names = AttributeLease.#registry.names;\n names.set(attribute, (names.get(attribute) ?? new Set<string>()).add(this.#record));\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const stack = this.#stack(element);\n const hold = this.#take(stack) ?? this.#acquire(element, stack);\n this.#held.add(element);\n const shows = !this.#covered(element, stack, hold);\n hold.written = value;\n this.#mark(element, stack);\n if (shows) this.#reflect(element, value);\n }\n\n /**\n * Returns one lease, also on a restored copy, to the value the hold beneath it wrote last or\n * the author's, without overwriting a value a consumer wrote since. Says whether there was a\n * lease to return: a hold this lease has, or the hold a copy's record describes while no live\n * lease of the owner has taken it — a copy of a page an earlier connection wrote carries one.\n */\n return(element: T): boolean {\n const held = this.#held.delete(element);\n const known = AttributeLease.#registry.stacks.get(element)?.has(this.#attribute);\n const stack = held || known || element.hasAttribute(this.#record) ? this.#stack(element) : [];\n const hold = this.#take(stack);\n if (!hold) return false;\n const carries = element.getAttribute(this.#attribute) === hold.written;\n const owns = carries && !this.#covered(element, stack, hold);\n const index = stack.indexOf(hold);\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n this.#mark(element, stack);\n if (!owns) return true;\n const below = hold.linked ? stack[index - 1] : undefined;\n this.#reflect(element, below ? below.written : hold.original);\n return true;\n }\n\n /** Returns every lease it holds, with the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#held)) this.return(element);\n }\n\n /** The element's stack, read from its records the first time. */\n #stack(element: T): AttributeHold[] {\n const stacks = AttributeLease.#registry.stacks;\n const byAttribute = stacks.get(element) ?? new Map<string, AttributeHold[]>();\n stacks.set(element, byAttribute);\n const stack = byAttribute.get(this.#attribute) ?? this.#seed(element);\n byAttribute.set(this.#attribute, stack);\n return stack;\n }\n\n /** The holds a copy's records describe, each above every hold its record lists beneath. */\n #seed(element: T): AttributeHold[] {\n const found: (AttributeLeaseRecord & { readonly record: string })[] = [];\n for (const record of AttributeLease.#registry.names.get(this.#attribute) ?? []) {\n const read = readLeaseRecord(element, record);\n if (read) found.push({ ...read, record });\n }\n const depth = ({ beneath }: (typeof found)[number]) =>\n beneath.filter((name) => found.some((other) => other.record === name)).length;\n return found\n .sort((one, other) => depth(one) - depth(other))\n .map(({ record, written, original, linked }, index) => ({\n lease: null,\n record,\n written,\n original,\n linked: linked && index > 0,\n }));\n }\n\n /** Its hold in `stack`, taking over one read from its record. */\n #take(stack: AttributeHold[]): AttributeHold | undefined {\n const hold =\n stack.find((held) => held.lease === this) ??\n stack.find((held) => held.lease === null && held.record === this.#record);\n if (hold) hold.lease = this;\n return hold;\n }\n\n /** A new hold: on top, over the top hold while the element shows it; a base one at the bottom. */\n #acquire(element: T, stack: AttributeHold[]): AttributeHold {\n const current = element.getAttribute(this.#attribute);\n const top = stack.at(-1);\n const bottom = stack[0];\n const over = top?.written === current ? top : undefined;\n const from = this.#base ? bottom : over;\n const hold: AttributeHold = {\n lease: this,\n record: this.#record,\n written: current,\n original: from ? from.original : current,\n linked: !this.#base && over !== undefined,\n };\n if (this.#base && bottom) {\n bottom.linked = true;\n stack.unshift(hold);\n } else stack.push(hold);\n return hold;\n }\n\n /** Whether a hold above `hold` carries the element's value, which is then that hold's. */\n #covered(element: T, stack: readonly AttributeHold[], hold: AttributeHold): boolean {\n const current = element.getAttribute(this.#attribute);\n return stack.slice(stack.indexOf(hold) + 1).some((above) => above.written === current);\n }\n\n /** Leaves each owner's record of its topmost hold, or none where nothing needs one. */\n #mark(element: T, stack: readonly AttributeHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n stack.forEach((hold, index) => {\n const names = stack.slice(0, index).map((under) => under.record);\n const beneath = [...new Set(names.reverse())].filter((name) => name !== hold.record);\n const marker = hold.linked || beneath.length === 0 ? [] : [false];\n records.set(\n hold.record,\n hold.written === hold.original && beneath.length === 0 && index === stack.length - 1\n ? null\n : JSON.stringify([hold.original, hold.written, ...marker, ...beneath]),\n );\n });\n for (const [name, recorded] of records) {\n if (element.getAttribute(name) === recorded) continue;\n if (recorded === null) element.removeAttribute(name);\n else element.setAttribute(name, recorded);\n }\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n if (element.getAttribute(this.#attribute) === value) return;\n if (value === null) element.removeAttribute(this.#attribute);\n else element.setAttribute(this.#attribute, value);\n }\n}\n","/**\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 * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest handler resolves the\n * press. A keydown that is part of an IME composition (`event.isComposing`)\n * cancels the composition, never a layer, and is ignored here for every layer\n * at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered. The map is one per page\n * (`sharedRegistry`), so the layers of controllers imported from different\n * files share one stack and one listener.\n */\n\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** An active layer on its document's stack: what the resolver reads, from any copy. */\ninterface LayerEntry {\n readonly onDismiss: () => void;\n readonly claims: (() => boolean) | null;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n readonly stack: LayerEntry[];\n readonly onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = sharedRegistry(\n \"stimeo-ui.escape-layer.registry.v1\",\n () => new WeakMap<Document, EscapeLayerRegistry>(),\n );\n\n /** The document and the entry of this layer while it is active. */\n #active: { readonly document: Document; readonly entry: LayerEntry } | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n const entry = { onDismiss: options.onDismiss, claims: options.claims ?? null };\n registry.stack.push(entry);\n this.#active = { document: ownerDocument, entry };\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const active = this.#active;\n if (!active) return;\n\n const registry = EscapeLayer.#registries.get(active.document);\n if (registry) {\n const index = registry.stack.lastIndexOf(active.entry);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n active.document.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(active.document);\n }\n }\n this.#active = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const active = this.#active;\n if (!active) return false;\n const registry = EscapeLayer.#registries.get(active.document);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === active.entry;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.onDismiss();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: readonly LayerEntry[]): LayerEntry | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.claims && !layer.claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported on its own for callers that need the disabled-inheritance rule without\n * the rest of {@link canTakeFocus} — a control's availability check, or a `hidden`\n * walk bounded at a widget root, which is a different rule to compose with.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether the engine reports `element` assigned to no slot of the open shadow root its parent\n * hosts: such an element is not in the flat tree, so it and what it holds are rendered nowhere\n * and cannot take focus.\n */\nfunction unslotted(element: Element): boolean {\n return element.assignedSlot === null && element.parentElement?.shadowRoot != null;\n}\n\n/**\n * The parent of `element` in the flat tree: the slot it is assigned to, its parent element,\n * or the host of the shadow root it is a child of; `null` at the top of the document or of a\n * detached tree, and for an element the engine assigns to no slot of the open shadow root its\n * parent hosts, which is outside the flat tree. A closed shadow root does not report its slots,\n * so an element assigned to one climbs to the host.\n */\nexport function flatTreeParent(element: Element): Element | null {\n if (unslotted(element)) return null;\n const parent = element.assignedSlot ?? element.parentNode;\n if (parent instanceof ShadowRoot) return parent.host;\n return parent instanceof Element ? parent : null;\n}\n\n/** Whether `element` is `ancestor` or one of its descendants in the flat tree. */\nexport function flatTreeContains(ancestor: Element, element: Element | null): boolean {\n for (let node = element; node; node = flatTreeParent(node)) {\n if (node === ancestor) return true;\n }\n return false;\n}\n\n/** The nearest of `element` and its flat-tree ancestors that matches `selector`, or `null`. */\nexport function closestInFlatTree(element: Element, selector: string): Element | null {\n for (let node: Element | null = element; node; node = flatTreeParent(node)) {\n if (node.matches(selector)) return node;\n }\n return null;\n}\n\n/**\n * The children of `element` in the flat tree: its open shadow root's children, a slot's\n * assigned elements (its own children when nothing is assigned to it), or its children.\n */\nexport function flatTreeChildren(element: Element): Element[] {\n return ownedScope(element) ?? Array.from(element.children);\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the conditions that make the platform refuse\n * focus are checked: `hidden` / `inert` on the element or a flat-tree ancestor\n * (the host of an open shadow root it sits in, the slot it is assigned to), the\n * element or an ancestor left out of the flat tree (one the engine assigns to no\n * slot of the open shadow root its parent hosts), `input[type=\"hidden\"]`, the\n * native `disabled` property, and `disabled` inherited from an ancestor\n * `fieldset`. CSS-only invisibility is handled by {@link isRenderedForFocus}\n * when a consumer needs sequential-focus semantics.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n for (let node: Element | null = element; node; node = flatTreeParent(node)) {\n if (unslotted(node) || node.matches(\"[hidden], [inert]\")) return false;\n }\n if (element instanceof HTMLInputElement && element.type === \"hidden\") return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n\n/** Elements whose semantics or authored attributes can place them in sequential focus order. */\nexport const TAB_STOP_CANDIDATE_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"iframe\",\n \"audio[controls]\",\n \"video[controls]\",\n \"[tabindex]\",\n \"[contenteditable]\",\n].join(\",\");\n\n/** Optional browser visibility API used to exclude CSS-hidden candidates. */\ninterface VisibilityCheckable {\n checkVisibility?: (options?: { visibilityProperty?: boolean }) => boolean;\n}\n\n/** Whether CSS visibility allows an otherwise eligible element to participate in focus order. */\nexport function isRenderedForFocus(element: HTMLElement): boolean {\n const check = (element as HTMLElement & VisibilityCheckable).checkVisibility;\n return typeof check === \"function\" ? check.call(element, { visibilityProperty: true }) : true;\n}\n\n/** Parses an authored `tabindex`; invalid syntax has no explicit focus-order meaning. */\nfunction authoredTabindex(element: Element): number | null {\n const value = element.getAttribute(\"tabindex\");\n if (value === null || !/^[+-]?\\d+$/.test(value.trim())) return null;\n return Number(value);\n}\n\n/** Whether the element's native semantics place it in sequential focus order. */\nfunction hasNativeTabStop(element: HTMLElement): boolean {\n if (element instanceof HTMLAnchorElement || element instanceof HTMLAreaElement) {\n return element.hasAttribute(\"href\");\n }\n if (\n element instanceof HTMLButtonElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n ) {\n return true;\n }\n if (element instanceof HTMLInputElement) return element.type !== \"hidden\";\n if (element instanceof HTMLIFrameElement) return true;\n if (element.tagName === \"AUDIO\" || element.tagName === \"VIDEO\") {\n return element.hasAttribute(\"controls\");\n }\n if (element instanceof HTMLElement && element.tagName === \"SUMMARY\") {\n const details = element.parentElement;\n return (\n details instanceof HTMLDetailsElement &&\n Array.from(details.children).find((child) => child.tagName === \"SUMMARY\") === element\n );\n }\n return false;\n}\n\n/** Whether an explicit `contenteditable` value creates an editable tab stop. */\nfunction hasEditableTabStop(element: HTMLElement): boolean {\n const value = element.getAttribute(\"contenteditable\")?.toLowerCase();\n return value === \"\" || value === \"true\" || value === \"plaintext-only\";\n}\n\n/**\n * Whether an element is a usable sequential Tab stop right now.\n *\n * Native semantics, authored `tabindex`, editable hosts, inherited disabled state,\n * HTML `hidden`/`inert`, and CSS visibility are evaluated together. `aria-disabled`\n * remains focusable because it communicates unavailability without removing the\n * control from discovery order.\n */\nexport function isTabStop(element: HTMLElement): boolean {\n if (!canTakeFocus(element) || !isRenderedForFocus(element)) return false;\n\n const tabindex = authoredTabindex(element);\n if (tabindex !== null) return tabindex >= 0;\n return hasNativeTabStop(element) || hasEditableTabStop(element);\n}\n\n/** Returns every usable sequential Tab stop below `root` in document order. */\nexport function tabStopsWithin(root: ParentNode): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)).filter(\n isTabStop,\n );\n}\n\n/** Returns the first usable sequential Tab stop below `root`, if one exists. */\nexport function firstTabStop(root: ParentNode): HTMLElement | null {\n for (const candidate of root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)) {\n if (isTabStop(candidate)) return candidate;\n }\n return null;\n}\n\n/** Whether `root` contains at least one usable sequential Tab stop. */\nexport function hasTabStop(root: ParentNode): boolean {\n return firstTabStop(root) !== null;\n}\n\n/** An element sequential focus navigation can stop on. */\nexport type TabStopElement = HTMLElement | SVGElement;\n\n/** Whether the element is a radio button. */\nfunction isRadio(element: Element | null): element is HTMLInputElement {\n return element instanceof HTMLInputElement && element.type === \"radio\";\n}\n\n/**\n * Whether two radios form one group: the same non-empty `name`, the same form owner and\n * the same tree. A radio without a name is a group of its own.\n */\nfunction sameRadioGroup(a: HTMLInputElement, b: HTMLInputElement): boolean {\n return (\n a.name !== \"\" && a.name === b.name && a.form === b.form && a.getRootNode() === b.getRootNode()\n );\n}\n\n/**\n * Whether the element is part of editable content: the nearest ancestor that sets a valid\n * `contenteditable` decides. `false` ends the editable region (a non-editable island\n * inside an editor); an invalid value inherits from further up.\n */\nfunction isInEditableContent(element: Element): boolean {\n for (let node = element.parentElement; node; node = node.parentElement) {\n if (node.getAttribute(\"contenteditable\")?.toLowerCase() === \"false\") return false;\n if (hasEditableTabStop(node)) return true;\n }\n return false;\n}\n\n/** The XLink namespace, where an SVG link may carry its `href`. */\nconst XLINK_NAMESPACE = \"http://www.w3.org/1999/xlink\";\n\n/** Whether the element is an SVG link: an SVG `a` with `href` or `xlink:href`. */\nfunction isSvgLink(element: Element): boolean {\n return (\n element instanceof SVGElement &&\n element.localName === \"a\" &&\n (element.hasAttribute(\"href\") || element.hasAttributeNS(XLINK_NAMESPACE, \"href\"))\n );\n}\n\n/**\n * Whether an image-map area has a rendered image: an `img` in the area's tree whose\n * `usemap` names the area's map (by `name`, or by `id` without one) and that is rendered.\n * The area has no box of its own for {@link isRenderedForFocus} to check.\n */\nfunction hasRenderedImage(area: HTMLAreaElement): boolean {\n const map = area.closest(\"map\");\n const key = map?.name || map?.id;\n if (!map || !key) return false;\n const root = map.getRootNode() as Document | ShadowRoot;\n return Array.from(root.querySelectorAll<HTMLElement>(\"img[usemap]\")).some(\n (image) => image.getAttribute(\"usemap\") === `#${key}` && isRenderedForFocus(image),\n );\n}\n\n/** Whether the element can take focus and has no negative `tabindex`. */\nfunction isFocusableInOrder(element: TabStopElement): boolean {\n const tabindex = authoredTabindex(element);\n return (tabindex === null || tabindex >= 0) && canTakeFocus(element as HTMLElement);\n}\n\n/**\n * The engine's verdict for the stops {@link isTabStop} does not judge the way sequential\n * navigation does, or `null` for every other element: an image-map area with an `href` or\n * its own `tabindex` stops while an image that uses its map is rendered; an object stops\n * while it holds a nested document, as an iframe does; an SVG link stops while it is\n * rendered. Each also needs to take focus and not be taken out of the order with a\n * negative `tabindex`.\n */\nfunction extraStop(element: TabStopElement): boolean | null {\n if (element instanceof HTMLAreaElement) {\n const focusable = element.hasAttribute(\"href\") || authoredTabindex(element) !== null;\n return focusable && isFocusableInOrder(element) && hasRenderedImage(element);\n }\n if (element instanceof HTMLObjectElement) {\n return (\n isFocusableInOrder(element) && isRenderedForFocus(element) && element.contentWindow !== null\n );\n }\n if (isSvgLink(element))\n return isFocusableInOrder(element) && isRenderedForFocus(element as HTMLElement);\n return null;\n}\n\n/**\n * Whether sequential navigation stops on the element: a usable Tab stop\n * ({@link isTabStop}), or one of the stops `extraStop` judges, except a link inside\n * editable content without a `tabindex` of its own, which the engine leaves to editing.\n * Other controls inside an editing host, and the host itself, stay stops.\n */\nfunction isSequentialStop(element: TabStopElement): boolean {\n const stop =\n extraStop(element) ??\n (element.matches(TAB_STOP_CANDIDATE_SELECTOR) && isTabStop(element as HTMLElement));\n if (!stop) return false;\n const link =\n element instanceof HTMLAnchorElement ||\n element instanceof HTMLAreaElement ||\n isSvgLink(element);\n return !(link && authoredTabindex(element) === null && isInEditableContent(element));\n}\n\n/**\n * The elements of the focus navigation scope `element` owns: its open shadow root's\n * children, or a slot's assigned elements (its fallback content when nothing is\n * assigned). `null` when it owns no scope. A closed shadow root cannot be read, so its\n * host owns none.\n */\nfunction ownedScope(element: Element): Element[] | null {\n if (element.shadowRoot) return Array.from(element.shadowRoot.children);\n if (element instanceof HTMLSlotElement) {\n const assigned = element.assignedElements();\n return assigned.length > 0 ? assigned : Array.from(element.children);\n }\n return null;\n}\n\n/** One member of a focus navigation scope: its tabindex and the stops it contributes. */\ninterface ScopeEntry {\n readonly tabindex: number;\n readonly stops: TabStopElement[];\n}\n\n/** What a walk of the order records besides the order itself. */\ninterface OrderWalk {\n /** The element a move starts from. */\n readonly from: Element | null;\n /** Every stop, in flat-tree order. */\n readonly tree: TabStopElement[];\n /** How many entries of {@link OrderWalk.tree} come before `from`; `-1` until the walk meets it. */\n fromAt: number;\n}\n\n/**\n * Orders one focus navigation scope the way HTML's sequential navigation does: members\n * with a positive `tabindex` first, ascending, ties in tree order, then the rest in tree\n * order. A member that owns a scope (a shadow host, a slot) is followed by that scope's\n * own order; one taken out of the order with a negative `tabindex` takes its scope with it.\n */\nfunction orderScope(elements: Element[], walk: OrderWalk): TabStopElement[] {\n const entries: ScopeEntry[] = [];\n const visit = (element: Element): void => {\n if (element === walk.from) walk.fromAt = walk.tree.length;\n const tabindex = authoredTabindex(element) ?? 0;\n const stop =\n (element instanceof HTMLElement || element instanceof SVGElement) && isSequentialStop(element)\n ? element\n : null;\n if (stop) walk.tree.push(stop);\n const owned = ownedScope(element);\n if (owned) {\n if (tabindex >= 0) {\n entries.push({ tabindex, stops: [...(stop ? [stop] : []), ...orderScope(owned, walk)] });\n }\n return;\n }\n if (stop) entries.push({ tabindex, stops: [stop] });\n for (const child of Array.from(element.children)) visit(child);\n };\n for (const element of elements) visit(element);\n const positive = entries.filter((entry) => entry.tabindex > 0);\n positive.sort((a, b) => a.tabindex - b.tabindex);\n const rest = entries.filter((entry) => entry.tabindex === 0);\n return [...positive, ...rest].flatMap((entry) => entry.stops);\n}\n\n/**\n * Whether a candidate passes the radio-group rule the engine applies: a checked radio\n * among the stops always does; an unchecked one only as the first radio of a group with\n * no checked stop, and not while focus is on a radio of that group. `tree` is the walk's\n * stops in flat-tree order, so a group is counted within the walked root only.\n */\nfunction passesRadioRule(\n element: TabStopElement,\n tree: TabStopElement[],\n focusedRadio: HTMLInputElement | null,\n): boolean {\n if (!isRadio(element) || element.checked) return true;\n const group = tree.filter(\n (stop): stop is HTMLInputElement =>\n stop === element || (isRadio(stop) && sameRadioGroup(stop, element)),\n );\n if (group.some((radio) => radio.checked)) return false;\n if (group[0] !== element) return false;\n return focusedRadio === null || !sameRadioGroup(focusedRadio, element);\n}\n\n/**\n * The index in `order` a move from the walk's `from` visits first. A start the walk did\n * not meet is outside: the move enters at the first stop, or the last going backward. A\n * start that is a stop moves one place along the order. Any other start (the root, an\n * element with a negative `tabindex`) moves to the nearest stop after it in tree order,\n * or before it going backward, and wraps when there is none.\n */\nfunction startIndex(\n order: TabStopElement[],\n walk: OrderWalk,\n backward: boolean,\n isStop: (element: TabStopElement) => boolean,\n): number {\n if (walk.fromAt < 0) return backward ? order.length - 1 : 0;\n const at = order.indexOf(walk.from as TabStopElement);\n if (at >= 0) return backward ? at - 1 : at + 1;\n const neighbour = backward\n ? walk.tree.slice(0, walk.fromAt).reverse().find(isStop)\n : walk.tree.slice(walk.fromAt).find(isStop);\n if (neighbour) return order.indexOf(neighbour);\n return backward ? order.length - 1 : 0;\n}\n\n/**\n * The stops below `root` in the order a sequential move from `from` visits them: the\n * next stop first (the previous one when `backward`), wrapping at the ends, with `from`\n * itself left out. Without a `from` — or with one outside `root` — the list starts at the\n * first stop, or at the last one when `backward`.\n *\n * The order is HTML's sequential navigation order within `root`: positive `tabindex`\n * first, ascending, then `tabindex=\"0\"` and native stops in tree order. Open shadow roots\n * are walked in flat-tree order, slots expanded, each scope ordered on its own; a closed\n * shadow root is not read. A radio group, counted within `root`, stops once: on its\n * checked radio when that radio can take focus, even with focus elsewhere in the group,\n * and otherwise on its first radio that can, unless focus is already in the group.\n * A link inside editable content without its own `tabindex` is not a stop. Every stop\n * also passes its applicable focusability and rendering checks.\n *\n * @param root - The element whose descendants are ordered; it is not a stop itself.\n * @param from - Where the move starts, usually {@link deepActiveElement}.\n * @param backward - Whether the move goes backward (`Shift+Tab`).\n */\nexport function sequentialTabStops(\n root: Element,\n from: Element | null = null,\n backward = false,\n): TabStopElement[] {\n const walk: OrderWalk = { from, tree: [], fromAt: from === root ? 0 : -1 };\n const order = orderScope(ownedScope(root) ?? Array.from(root.children), walk);\n const focusedRadio = walk.fromAt >= 0 && isRadio(from) ? from : null;\n const isStop = (element: TabStopElement): boolean =>\n passesRadioRule(element, walk.tree, focusedRadio);\n const start = startIndex(order, walk, backward, isStop);\n const visited = backward\n ? [...order.slice(0, start + 1).reverse(), ...order.slice(start + 1).reverse()]\n : [...order.slice(start), ...order.slice(0, start)];\n return visited.filter((element) => element !== from && isStop(element));\n}\n\n/**\n * The element that holds focus in `ownerDocument`, looking through open shadow roots:\n * `document.activeElement` stops at a shadow host. A closed shadow root cannot be read,\n * so focus inside one reads as its host.\n */\nexport function deepActiveElement(ownerDocument: Document): Element | null {\n let active = ownerDocument.activeElement;\n while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;\n return active;\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","/** Queries physical descendants and nested open shadow trees, including `root`'s own. */\nexport function queryOpenDescendants<T extends Element = Element>(\n root: ParentNode,\n selector: string,\n): T[] {\n const matches: T[] = [];\n const roots: ParentNode[] = [root];\n for (const scope of roots) {\n matches.push(...scope.querySelectorAll<T>(selector));\n if (scope.nodeType === Node.ELEMENT_NODE) {\n const shadow = (scope as Element).shadowRoot;\n if (shadow) roots.push(shadow);\n }\n for (const element of scope.querySelectorAll(\"*\")) {\n if (element.shadowRoot) roots.push(element.shadowRoot);\n }\n }\n return matches;\n}\n","import { queryOpenDescendants } from \"./query_open_descendants\";\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** One loan's hold on one element's `tabindex`, in the stack every loan of it shares. */\ninterface LoanHold {\n /** The loan holding it; `null` for a loan read from a copy's record until a loan takes it. */\n loan: object | null;\n readonly record: string;\n readonly value: string;\n /** Whether it hands back the value of the hold beneath it; otherwise no `tabindex`. */\n linked: boolean;\n}\n\n/** The loans on each element, bottom first, and every loan's record name. */\ninterface TabindexLoanRegistry {\n readonly stacks: WeakMap<HTMLElement, LoanHold[]>;\n readonly names: Set<string>;\n}\n\n/**\n * Shared bookkeeping for a `tabindex` a controller lends an element temporarily.\n *\n * A controller that must move focus somewhere the author never made focusable\n * (a landmark root, a scroll destination) reaches for the same trick: add a\n * `tabindex` just-in-time and hand it back once it is no longer needed. The\n * borrow is the easy half; the return is what the two conditions below are for.\n *\n * **Returning needs two conditions, not one.** Owning the borrow is not enough:\n * the attribute must also still hold the value this instance wrote. A consumer\n * that changed it afterwards — `tabindex=\"0\"` to make the root its own Tab stop\n * — owns it now, and removing it there silently discards authored markup. The\n * bookkeeping is dropped either way, since the loan is over regardless of who\n * ends up owning the value.\n *\n * **Never borrow over a value no loan holds.** An element whose `tabindex` no loan\n * holds — the author's, or one the page wrote over the loans — is the author's to\n * control, so there is nothing to lend and nothing to return.\n *\n * **Every loan of an element shares one stack of loans**, whatever its owner and\n * whichever file of the package constructed it (the stacks are one per page). A loan\n * lends over the loans that hold the element while its `tabindex` is theirs — sharing\n * their value, or covering it with its own — and lends again where the page removed\n * the `tabindex`. The `tabindex` is the highest loan's that lends its value: returning\n * that loan gives the element the value of the loan beneath it, or no `tabindex`, and\n * any other return only leaves the stack. So two loans of one value — every focus trap\n * lends its container under one owner — keep it until the last of them returns, and a\n * loan lent after the page removed an earlier one's `tabindex` keeps it when the\n * earlier one returns.\n *\n * **A loan is recorded on the element.** Lending writes\n * `data-<owner>-tabindex-loan` holding the value the owner's topmost loan lends next\n * to the `tabindex`, and the owner's last loan to end removes it. A copy of the\n * element — a page Turbo restores from its cache is one — so tells its owners' loans\n * from an authored `tabindex`: `lend()` takes over a loan its owner recorded, and\n * `reclaim()` gives back one no loan has taken over; the `tabindex` goes with the last\n * of them. A copy keeps no order of its loans beyond putting those of the value it\n * carries on top. Without a record a `tabindex` is the author's. Nothing returns a\n * live loan before Turbo caches the page: `turbo:before-cache` also fires on pages\n * that stay, and the loan is still in use there.\n *\n * The registry is keyed by element, so a controller borrowing on a single\n * element (`this.element`) and one borrowing across a changing set of targets\n * use the same API — the single-element case is a set of one. It holds no\n * opinion about *when* to borrow or where focus goes next; that stays in the\n * controller.\n *\n * **The API is deliberately small.** Each consumer entry includes its own copy\n * of the class, so unused methods still increase its runtime output.\n *\n * @example\n * ```ts\n * readonly #tabindex = new TabindexLoan(\"-1\", this.identifier);\n *\n * connect() {\n * this.#tabindex.reclaim(this.element);\n * }\n *\n * #rescueFocus() {\n * this.#tabindex.lend(this.element);\n * this.element.focus();\n * }\n *\n * disconnect() {\n * this.#tabindex.returnAll();\n * }\n * ```\n */\nexport class TabindexLoan<T extends HTMLElement = HTMLElement> {\n /** The loans on each element and the record names, one per page. */\n static readonly #registry = sharedRegistry(\n \"stimeo-ui.tabindex-loan.registry.v1\",\n (): TabindexLoanRegistry => ({ stacks: new WeakMap(), names: new Set() }),\n );\n readonly #value: string;\n readonly #record: string;\n readonly #lent = new Set<T>();\n\n /**\n * @param value - the `tabindex` to lend. `\"-1\"` is programmatically focusable but\n * not a Tab stop; `\"0\"` is a real Tab stop, which a scroll region with no\n * focusable content of its own needs.\n * @param owner - Names the record on the element; the controller's identifier.\n */\n constructor(value: string, owner: string) {\n this.#value = value;\n this.#record = `data-${owner}-tabindex-loan`;\n TabindexLoan.#registry.names.add(this.#record);\n }\n\n /**\n * Lends `element` the value over the loans holding its `tabindex`, or where the page removed\n * it; a `tabindex` no loan holds is left alone, and a loan recorded on a copy taken over.\n */\n lend(element: T): void {\n const stack = this.#stack(element);\n const current = element.getAttribute(\"tabindex\");\n const held =\n stack.find((hold) => hold.loan === this) ??\n stack.find(\n (hold) => hold.loan === null && hold.record === this.#record && hold.value === this.#value,\n );\n const linked = stack.at(-1)?.value === current;\n if (!held && current !== null && !linked) return;\n this.#lent.add(element);\n if (held) held.loan = this;\n else stack.push({ loan: this, record: this.#record, value: this.#value, linked });\n this.#mark(element, stack);\n if (current === null || (!held && current !== this.#value)) {\n element.setAttribute(\"tabindex\", this.#value);\n }\n }\n\n /** Takes back every loan; one whose value the element shows hands it to the loan beneath. */\n returnAll(): void {\n for (const element of this.#lent) {\n const stack = this.#stack(element);\n const hold = stack.find((held) => held.loan === this);\n if (hold) this.#release(element, stack, hold);\n }\n this.#lent.clear();\n }\n\n /**\n * Gives back a loan its owner recorded on a restored copy that no loan has taken over, unless\n * the record holds another value or the element holds focus.\n */\n reclaim(element: HTMLElement): void {\n if (element.getAttribute(this.#record) !== this.#value) return;\n const stack = this.#stack(element);\n const hold = stack.find((held) => held.loan === null && held.record === this.#record);\n if (hold && !element.matches(\":focus\")) this.#release(element, stack, hold);\n }\n\n /** Gives back, as {@link reclaim} does, every loan of its owner recorded inside `root`. */\n reclaimWithin(root: ParentNode): void {\n for (const element of queryOpenDescendants<HTMLElement>(root, `[${this.#record}]`)) {\n this.reclaim(element);\n }\n }\n\n /** The element's loans, read from its records the first time. */\n #stack(element: HTMLElement): LoanHold[] {\n const stacks = TabindexLoan.#registry.stacks;\n const stack = stacks.get(element) ?? this.#seed(element);\n stacks.set(element, stack);\n return stack;\n }\n\n /** The loans a copy's records describe, those of the value it carries on top. */\n #seed(element: HTMLElement): LoanHold[] {\n const current = element.getAttribute(\"tabindex\");\n const holds: LoanHold[] = [];\n for (const record of TabindexLoan.#registry.names) {\n const value = element.getAttribute(record);\n if (value !== null) holds.push({ loan: null, record, value, linked: true });\n }\n holds.sort((one, other) => Number(one.value === current) - Number(other.value === current));\n for (const [index, hold] of holds.entries()) hold.linked = index > 0;\n return holds;\n }\n\n /** Takes `hold` off, handing the value it shows to the loan beneath. */\n #release(element: HTMLElement, stack: LoanHold[], hold: LoanHold): void {\n const current = element.getAttribute(\"tabindex\");\n const index = stack.indexOf(hold);\n const owns =\n current === hold.value && !stack.slice(index + 1).some((above) => above.value === current);\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n this.#mark(element, stack);\n if (!owns) return;\n const below = hold.linked ? stack[index - 1] : undefined;\n if (!below) element.removeAttribute(\"tabindex\");\n else if (below.value !== current) element.setAttribute(\"tabindex\", below.value);\n }\n\n /** Leaves each owner's record of the value its topmost loan lends. */\n #mark(element: HTMLElement, stack: readonly LoanHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n for (const hold of stack) records.set(hold.record, hold.value);\n for (const [name, recorded] of records) {\n if (element.getAttribute(name) === recorded) continue;\n if (recorded === null) element.removeAttribute(name);\n else element.setAttribute(name, recorded);\n }\n }\n}\n","import { DetachGate, type DetachGateHost } from \"./detach_gate\";\nimport { EscapeLayer } from \"./escape_layer\";\nimport {\n canTakeFocus,\n closestInFlatTree,\n deepActiveElement,\n flatTreeChildren,\n flatTreeContains,\n flatTreeParent,\n isRenderedForFocus,\n sequentialTabStops,\n type TabStopElement,\n} from \"./focus_candidate\";\nimport { MicrotaskCoalescer } from \"./microtask_coalescer\";\nimport { queryOpenDescendants } from \"./query_open_descendants\";\nimport { sharedRegistry } from \"./shared_registry\";\nimport { TabindexLoan } from \"./tabindex_loan\";\n\n/**\n * Modal focus-trap primitive shared by the modal-overlay controllers\n * (dialog / alert-dialog / confirm / drawer / command-palette / sidebar); the\n * non-modal focus scope (focus) reuses it with the modal side effects opted out.\n *\n * The WAI-ARIA APG modal pattern is more than \"cycle Tab inside a box\": a modal\n * also locks background scroll, makes the rest of the page `inert` (so assistive\n * technology and pointer/Tab cannot reach it, honoring `aria-modal=\"true\"`),\n * sends focus inside on open, and restores it to the opener on close — and every\n * one of those side effects must be reverted if the element is torn down while\n * open (a Turbo navigation mid-dialog). {@link FocusTrap} owns that whole modal\n * lifecycle so each controller only decides *when* to open/close and *what*\n * \"close\" means.\n *\n * **Tab.** While active, the trap takes every `Tab` and `Shift+Tab` itself: it\n * cancels the engine's move and focuses the next or previous stop, wrapping at the\n * ends, so where focus goes does not depend on the engine's settings (macOS Safari\n * skips buttons and links by default). The order is HTML's sequential navigation order\n * within the container, as {@link sequentialTabStops} computes it: positive `tabindex`\n * first, ascending, then the rest in tree order; a radio group stops once; open shadow\n * roots are walked in flat-tree order. Focus found outside the container enters at the\n * first stop on `Tab` and at the last on `Shift+Tab`. `Alt+Tab` (Safari's key for\n * moving to every control) is handled like `Tab`; `Ctrl+Tab`, `Meta+Tab`, a key that is\n * part of an IME composition, and a `Tab` an inner handler already consumed are left\n * alone. A move into a text input selects its text, as the engine's own `Tab` does.\n *\n * What the trap does not reach the way the engine does: an iframe is one stop, and\n * inside it the frame's own document moves focus, out of the frame included; a date\n * or time input is one stop, its fields left to the arrow keys; a scrollable region\n * with nothing focusable inside is not a stop unless it carries `tabindex=\"0\"`; content\n * behind a closed shadow root is not reached; a `details` element without a `summary`\n * child is not reached, because script cannot focus the summary the engine generates for\n * it; an `embed` is not a stop.\n *\n * One listener per document resolves each `Tab` to one trap: the most recently\n * activated trap whose container is connected and rendered. A trap whose\n * container is gone or hidden passes the key to the one below it; with none left the\n * key is the engine's. The registry of each document — the stack, the listener, the\n * background and the scroll locks — is one per page (`sharedRegistry`), so the traps of\n * controllers imported from different files share it.\n *\n * **Background `inert` across traps.** The active traps of a document share one background. It\n * takes the shape of the most recently activated isolating trap: the other children of each element\n * from its container up to `body` in the flat tree are `inert` (a container inside an open shadow\n * root makes the rest of that shadow tree and the page around its host `inert`), while that\n * container, the containers of every trap activated after it, and their ancestors are not. A modal\n * opened over another modal it is not nested in (a confirm at the end of `<body>` asked from inside\n * a dialog) is therefore operable, and the modal below it is background until it closes. Releasing\n * a trap, in any order, hands the background to the traps still active. The traps only ever release\n * the `inert` they applied; an element that was `inert` before is neither tracked nor cleared. The\n * scroll lock is shared the same way: the first trap that locks the `body` saves its own\n * `overflow`, and the last one released gives it back to that `body`, also once another `body`\n * has taken its place in the document. A Turbo morph that drops the locked style and the saved\n * value while a trap is active is followed by a lock that saves the `overflow` the morph left.\n *\n * **Focus back across traps.** A release that restores focus tries a way back in order: the element\n * that held focus when the trap activated, then the open shadow hosts around that element,\n * innermost first (one that rendered its content again keeps no element to return to, and a host\n * that delegates focus or carries a `tabindex` still takes it), then `fallbackFocus`, then what\n * traps released before it handed over. A trap activated while focus sat inside another active\n * trap's container is opened from that trap, and when that trap is released first, with or without\n * restoring focus, it hands its way back to the trap opened from it, behind that trap's own.\n * Closing the last of a stack of traps therefore returns focus to where the first was opened from,\n * in whatever order the traps between them closed, unless an element earlier on the last trap's way\n * back, its own opener or its `fallbackFocus`, can still take focus. An element on the way back is\n * tried only while it is connected, can take focus and is rendered, and the next one is tried when\n * `focus()` leaves focus where it was. With nothing left to try, focus goes where activation sends\n * it in the trap that takes `Tab` now, unless that trap's `autoFocus` is off or focus is already\n * inside it. A release leaves focus alone while it sits in a trap activated after the released one\n * that takes `Tab`; focus still inside the released trap's own container counts only for a trap\n * nested inside that container.\n *\n * **Open shadow roots.** Where focus is, is read through open shadow roots, and which\n * container holds an element is read along the flat tree: a slotted element is inside the\n * slot it is assigned to, and an element in a shadow root is inside its host. Content behind\n * a closed shadow root reads as its host.\n *\n * **The Turbo cache.** An active trap keeps every side effect through `turbo:before-cache`,\n * which Turbo also dispatches on pages that stay (a frame navigation promoted to a visit, a\n * `popstate` without Turbo state, a refresh of a cached URL). A page Turbo restores is a copy,\n * taken at some point of the navigation, that can carry the side effects of a trap that was\n * active then. So the traps mark what they change: each element they make `inert` carries\n * `data-stimeo-focus-trap-inert`, a locked `body` carries its saved `overflow` in\n * `data-stimeo-focus-trap-overflow`, and a container they lend a `tabindex` carries\n * `data-stimeo-focus-trap-tabindex-loan`. {@link FocusTrap.connect} and\n * {@link FocusTrap.activate} release the marked `inert` and scroll lock no active trap holds,\n * and {@link FocusTrap.connect} takes back every `tabindex` the traps lent that no trap\n * holds, unless the element holds focus. Turbo's morph keeps only the attributes the\n * server sent, so it drops the marks with what they mark; an element that has lost its mark\n * is no longer the traps', so the next activation, release or refresh makes it `inert` again\n * where it is background and leaves an `inert` the server sent alone. While a trap is\n * active, a morph (`turbo:morph` after a page morph, `turbo:morph-element` for each element\n * any morph renders) is followed, before the next task, by one pass that does so and locks\n * the `body` again: the background of an open modal never stays operable after a morph.\n *\n * **Lifecycle.** A controller calls {@link FocusTrap.connect} from its `connect()` and\n * {@link FocusTrap.disconnect} from its `disconnect()`. A disconnect releases an active trap at\n * once without moving focus. A `tabindex` kept on a container that held focus at a release\n * survives an in-page move (a disconnect the reconnect of the same controller follows in the\n * same mutation batch), and is taken back, once focus is elsewhere, when the controller's\n * element has left the document, its `data-controller` no longer lists the identifier, or no\n * reconnect followed within a microtask.\n *\n * It is intentionally **policy-free about closing**. Escape semantics differ per\n * widget (a plain dialog just closes; an alert-dialog closes *as a cancel* with a\n * reason; a drawer runs an exit transition), so the trap merely forwards Escape\n * to an {@link FocusTrapOptions.onEscape | onEscape} callback and never decides on\n * its own what closing entails.\n *\n * @remarks\n * The container is read through a getter so a controller can hand over a Stimulus\n * target without worrying about when the trap instance is constructed relative to\n * `connect()`.\n */\n\n/** Names the records the traps leave on the elements they change. */\nconst FOCUS_TRAP_OWNER = \"stimeo-focus-trap\";\n/** Marks an element a trap made `inert`. */\nconst INERT_MARK = `data-${FOCUS_TRAP_OWNER}-inert`;\n/** Holds, on a `body` a trap locked, the inline `overflow` it had before. */\nconst OVERFLOW_MARK = `data-${FOCUS_TRAP_OWNER}-overflow`;\n\n/** Behavior hooks a controller supplies when constructing a {@link FocusTrap}. */\nexport interface FocusTrapOptions {\n /**\n * Called when `Escape` is pressed while the trap is active. When omitted,\n * `Escape` is left alone (the trap never joins the Escape stack). Dismissal\n * is resolved by the shared {@link EscapeLayer}: an Escape already consumed\n * by an inner handler is ignored, and among active layers the most recently\n * activated claiming one owns the press. The resolver consumes the event\n * before invoking the callback.\n */\n onEscape?: () => void;\n /**\n * Returns the element to focus when the trap activates. When it returns `null`\n * (or is omitted), the first stop of the trap's order is used, falling back to the\n * container itself. A container without a `tabindex` is lent `tabindex=\"-1\"` for that,\n * taken back on release and when the trap moves onto another container, except while the\n * container holds focus: then the loan stays until a later release or move of the trap, or\n * the controller's detach, finds focus elsewhere; an in-page move of the controller keeps it.\n */\n initialFocus?: () => HTMLElement | null;\n /**\n * Returns the element to focus on deactivation (e.g. the trigger) when nothing was\n * focused before the trap opened, or the element focused before opening cannot take\n * focus at deactivation. The element focused before opening takes precedence while it\n * can.\n */\n fallbackFocus?: () => HTMLElement | null;\n /**\n * Lock background scroll (`body` overflow) while active. Defaults to `true` for\n * the modal overlays; a lighter focus scope passes `false`. Read on `activate`.\n */\n lockScroll?: boolean | (() => boolean);\n /**\n * Make background siblings `inert` while active (the `aria-modal` isolation).\n * Defaults to `true` for the modal overlays; a soft focus scope can opt out so\n * the background stays reachable while `Tab` still cycles inside. Read on `activate`,\n * and again on {@link FocusTrap.refreshIsolation}.\n */\n isolate?: boolean | (() => boolean);\n /**\n * Move focus inside on `activate`. Defaults to `true`; a focus scope that only\n * wants the `Tab` handling (no focus move) passes `false`. Read on `activate`, and\n * again on {@link FocusTrap.refreshContainer}.\n */\n autoFocus?: boolean | (() => boolean);\n}\n\n/** An active trap as its document's registry holds it, read and set through its fields alone. */\ninterface TrapEntry {\n /** The container, or `null` when it cannot be read. */\n readonly container: () => HTMLElement | null;\n /** Focuses the next stop, or the previous one when `backward`. */\n readonly moveFocus: (backward: boolean) => void;\n /** Focuses where activation does, unless `autoFocus` is off or focus is already inside. */\n readonly refocus: () => void;\n /**\n * `isolate` as read on activation or on the last refresh, kept apart from the `inert` the\n * traps applied, which is empty when every background element was already `inert`.\n */\n isolated: boolean;\n /** The `body` it locked, while it holds a scroll lock. */\n lockedBody: HTMLElement | null;\n /**\n * The most recently activated trap whose container held the opener when this trap\n * activated, while that trap is active: the one that hands this trap its way back if\n * released first.\n */\n openedFrom: TrapEntry | null;\n /** The way back handed over by traps released before it. */\n handedBack: HTMLElement[];\n}\n\n/**\n * A document's active traps, most recently activated last, its one `Tab` listener, its one\n * morph listener, the background elements the traps have made `inert`, and the active traps\n * that lock scroll.\n */\ninterface TrapRegistry {\n readonly stack: TrapEntry[];\n readonly onKeydown: (event: KeyboardEvent) => void;\n readonly onMorph: () => void;\n readonly inerted: Set<HTMLElement>;\n readonly scrollLocks: Set<TrapEntry>;\n}\n\n/**\n * Owns the modal side effects (scroll lock, background `inert`, `Tab` handling, focus\n * restore) for a single container, applied on {@link activate} and reverted on\n * {@link deactivate}.\n */\nexport class FocusTrap {\n /** Each document's trap registry; a WeakMap keeps documents collectible. */\n static readonly #registries = sharedRegistry(\n \"stimeo-ui.focus-trap.registry.v2\",\n () => new WeakMap<Document, TrapRegistry>(),\n );\n /** Input types whose text a move into the field selects. */\n static readonly #TEXT_ENTRY_TYPES = new Set([\n \"text\",\n \"search\",\n \"email\",\n \"url\",\n \"tel\",\n \"password\",\n \"number\",\n ]);\n\n /**\n * The element focused before activation and the open shadow hosts around it, innermost\n * first: the start of the way back.\n */\n #openers: HTMLElement[] = [];\n /** This trap as its document's registry holds it. */\n readonly #entry: TrapEntry;\n /** The `tabindex` lent to each container that had no stop to focus, by container. */\n readonly #tabindexLoans = new Map<HTMLElement, TabindexLoan>();\n /** Whether the modal side effects are currently applied. */\n #activeState = false;\n /** Registers the trap on the shared Escape stack while active (see {@link EscapeLayer}). */\n readonly #escapeLayer = new EscapeLayer();\n /** Tells an in-page move of the controller from its detach, for a kept `tabindex`. */\n readonly #gate = new DetachGate();\n\n /** Returns the trapped element; called on every operation for the live target. */\n readonly #getContainer: () => HTMLElement;\n /** Closing/focus hooks; see {@link FocusTrapOptions}. */\n readonly #options: FocusTrapOptions;\n\n /**\n * @param getContainer - Returns the trapped element. Called on every operation\n * so the live target is always used.\n * @param options - Closing/focus hooks; see {@link FocusTrapOptions}.\n */\n constructor(getContainer: () => HTMLElement, options: FocusTrapOptions = {}) {\n this.#getContainer = getContainer;\n this.#options = options;\n this.#entry = {\n container: () => this.#readContainer(),\n moveFocus: (backward) => this.#moveFocus(backward),\n refocus: () => this.#refocus(),\n isolated: false,\n lockedBody: null,\n openedFrom: null,\n handedBack: [],\n };\n }\n\n /** Whether the trap is currently active. */\n get active(): boolean {\n return this.#activeState;\n }\n\n /**\n * Applies the trap: releases the marked `inert` and scroll lock no active trap holds,\n * records the current focus and the active trap it sits in, optionally locks background\n * scroll and makes background siblings `inert`, takes the top of the document's `Tab`\n * resolver, joins the Escape stack when `onEscape` is given, and (unless `autoFocus` is off)\n * moves focus inside. No-ops if already active.\n */\n activate(): void {\n if (this.#activeState) return;\n FocusTrap.#sweep();\n this.#activeState = true;\n this.#openers = FocusTrap.#focusPath();\n this.#entry.openedFrom = FocusTrap.#trapHolding(this.#openers[0] ?? null);\n if (this.#flag(this.#options.lockScroll, true)) this.#lockScroll();\n this.#entry.isolated = this.#flag(this.#options.isolate, true);\n this.#joinStack();\n FocusTrap.#reconcileBackground(document);\n const onEscape = this.#options.onEscape;\n if (onEscape) this.#escapeLayer.activate(document, { onDismiss: () => onEscape() });\n if (this.#flag(this.#options.autoFocus, true)) this.#focusInitial();\n }\n\n /**\n * Reverts every side effect applied by {@link activate}, hands the way back to each active\n * trap opened from this one, and, once focus has moved, takes back the `tabindex` lent to a\n * container that does not hold focus. While inactive it only takes back a `tabindex` kept on\n * a container that no longer holds focus, so a controller can call it defensively from\n * `close()`. A controller's `disconnect()` calls {@link disconnect} instead.\n *\n * @param restoreFocus - Move focus back along the way back (default `true`): the opener,\n * `fallbackFocus`, then what was handed over. Pass `false` where yanking focus is\n * undesirable; the way back is handed over either way.\n */\n deactivate({ restoreFocus = true }: { restoreFocus?: boolean } = {}): void {\n if (!this.#activeState) {\n this.#returnTabindexes();\n return;\n }\n this.#activeState = false;\n this.#escapeLayer.deactivate();\n const above = this.#leaveStack();\n this.#unlockScroll();\n FocusTrap.#reconcileBackground(document);\n const wayBack = this.#handOver(above);\n if (restoreFocus) this.#restore(wayBack, above);\n this.#returnTabindexes();\n }\n\n /**\n * Call from the controller's `connect()`: a reconnect that follows {@link disconnect} in the\n * same mutation batch is an in-page move, and a `tabindex` kept on a container that held\n * focus at a release stays lent. Releases the marked `inert` and scroll lock no active trap\n * holds, and takes back every `tabindex` the traps lent that no trap holds, unless the\n * element holds focus: what a page restored from Turbo's cache carries, on the container\n * and on one a trap moved off.\n */\n connect(): void {\n this.#gate.cancel();\n FocusTrap.#sweep();\n new TabindexLoan(\"-1\", FOCUS_TRAP_OWNER).reclaimWithin(document);\n }\n\n /**\n * Call from the controller's `disconnect()`, passing the controller. An active trap is\n * released at once without moving focus, as {@link deactivate} with `restoreFocus: false`\n * does. Then a `tabindex` kept on a container that no longer holds focus is taken back at\n * once when the controller's element has left the document or its `data-controller` no\n * longer lists the identifier, and otherwise a microtask later unless {@link connect} came\n * first.\n *\n * @param host - The controller: its `element` and `identifier` tell a detach from an\n * in-page move.\n */\n disconnect(host: DetachGateHost): void {\n if (this.#activeState) this.deactivate({ restoreFocus: false });\n this.#gate.disconnected(host, () => this.#returnTabindexes());\n }\n\n /**\n * Re-reads `isolate` while active and applies the difference in place: the shared\n * background is brought in line with the traps' new state, so it is made `inert` when\n * this trap's isolation turned on and released when it turned off — only ever the\n * `inert` the traps applied. The recorded opener, the Escape layer, the place in the\n * trap stack and the scroll lock are left as they are. No-op while inactive or when\n * the option reads as it did.\n *\n * Focus moves only when isolating would strand it: an element in the background this\n * call just made `inert` loses focus to `<body>`, so focus goes where activation sends\n * it — the initial target, the first stop, the container. Focus already inside, on\n * `<body>`, or anywhere a release reaches stays where it is.\n */\n refreshIsolation(): void {\n if (!this.#activeState) return;\n const isolate = this.#flag(this.#options.isolate, true);\n if (isolate === this.#entry.isolated) return;\n this.#entry.isolated = isolate;\n const stranded = FocusTrap.#reconcileBackground(document);\n const active = deepActiveElement(document);\n if (stranded.some((element) => flatTreeContains(element, active))) this.#focusInitial();\n }\n\n /**\n * Moves the active trap onto the container its getter returns now, keeping its place in the\n * trap stack, the way back (the recorded opener, what was handed over and the trap it was\n * opened from), the Escape layer and the scroll lock, brings the shared background in line\n * with the new container, and takes back the `tabindex` lent to the old one unless it holds\n * focus; that loan stays until a later release or move of the trap, or the controller's\n * detach, finds focus elsewhere. Focus moves where activation sends it only when `Tab`\n * resolves to this trap, `autoFocus` is on and focus is outside the new container. No-op\n * while inactive.\n */\n refreshContainer(): void {\n if (!this.#activeState) return;\n FocusTrap.#reconcileBackground(document);\n this.#returnTabindexes();\n if (this.#ownsTab()) this.#refocus();\n }\n\n /** Resolves a boolean-or-getter option, defaulting when it was not provided. */\n #flag(option: boolean | (() => boolean) | undefined, fallback: boolean): boolean {\n if (option === undefined) return fallback;\n return typeof option === \"function\" ? option() : option;\n }\n\n /**\n * Puts this trap on top of the document's stack; the first trap installs the `Tab` listener\n * and the morph listener.\n */\n #joinStack(): void {\n const registry = FocusTrap.#registry(document);\n if (registry.stack.length === 0) {\n document.addEventListener(\"keydown\", registry.onKeydown);\n document.addEventListener(\"turbo:morph\", registry.onMorph);\n document.addEventListener(\"turbo:morph-element\", registry.onMorph);\n }\n registry.stack.push(this.#entry);\n }\n\n /**\n * Takes this trap off the document's stack and returns the traps activated after it; the last\n * trap removes the `Tab` listener and the morph listener. A pass a morph scheduled before\n * then finds no trap and changes nothing.\n */\n #leaveStack(): TrapEntry[] {\n const registry = FocusTrap.#registry(document);\n const index = registry.stack.indexOf(this.#entry);\n const above = registry.stack.slice(index + 1);\n registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n document.removeEventListener(\"keydown\", registry.onKeydown);\n document.removeEventListener(\"turbo:morph\", registry.onMorph);\n document.removeEventListener(\"turbo:morph-element\", registry.onMorph);\n }\n return above;\n }\n\n /**\n * The element that holds focus, then the open shadow hosts around it, innermost first. Empty\n * when nothing holds focus: `<body>`, the default active element, is treated as nothing, so\n * the way back starts at the fallback target, typically the trigger.\n */\n static #focusPath(): HTMLElement[] {\n const path: HTMLElement[] = [];\n for (\n let active = document.activeElement;\n active;\n active = active.shadowRoot?.activeElement ?? null\n ) {\n if (active instanceof HTMLElement && active !== document.body) path.unshift(active);\n }\n return path;\n }\n\n /**\n * The most recently activated trap on the document's stack whose container holds `element`\n * in the flat tree.\n */\n static #trapHolding(element: HTMLElement | null): TrapEntry | null {\n for (const trap of [...FocusTrap.#registry(document).stack].reverse()) {\n const container = trap.container();\n if (container && flatTreeContains(container, element)) return trap;\n }\n return null;\n }\n\n /**\n * Ends this activation's way back: the opener and the shadow hosts around it, `fallbackFocus` and\n * what was handed over, in that order. Each trap in `above` opened from this one gets it behind\n * its own and is pointed at the trap this one was opened from, so the links only ever lead to\n * traps activated earlier. The record is cleared before anything moves focus, so an activation a\n * focus listener starts keeps its own.\n */\n #handOver(above: TrapEntry[]): HTMLElement[] {\n const entry = this.#entry;\n const wayBack = [\n ...this.#openers,\n this.#options.fallbackFocus?.() ?? null,\n ...entry.handedBack,\n ].filter((element): element is HTMLElement => element !== null);\n for (const trap of above) {\n if (trap.openedFrom !== entry) continue;\n trap.handedBack = [...trap.handedBack, ...wayBack];\n trap.openedFrom = entry.openedFrom;\n }\n this.#openers = [];\n entry.openedFrom = null;\n entry.handedBack = [];\n return wayBack;\n }\n\n /**\n * Moves focus back after a release, unless focus sits in a trap of `above` that takes `Tab`\n * (focus inside this trap's own container counts only for a trap nested inside it): to the\n * first element of `wayBack` that is connected, can take focus and is rendered, and that\n * `focus()` moves focus to (or that a focus listener sends elsewhere); with none, where\n * activation sends it in the trap that takes `Tab` now, unless that trap's `autoFocus` is off\n * or focus is already inside it. A focus listener that activates this trap again ends it.\n */\n #restore(wayBack: HTMLElement[], above: TrapEntry[]): void {\n const active = deepActiveElement(document);\n const released = this.#readContainer();\n const holds = (trap: TrapEntry): boolean => {\n const container = trap.container();\n if (!container || !FocusTrap.#takesTab(trap) || !flatTreeContains(container, active)) {\n return false;\n }\n return (\n !released || !flatTreeContains(released, active) || flatTreeContains(released, container)\n );\n };\n if (above.some(holds)) return;\n for (const element of wayBack) {\n if (this.#activeState) return;\n if (!element.isConnected || !canTakeFocus(element) || !isRenderedForFocus(element)) continue;\n const before = deepActiveElement(document);\n element.focus();\n const after = deepActiveElement(document);\n if (after === element || after !== before) return;\n }\n FocusTrap.#tabOwner(FocusTrap.#registry(document).stack)?.refocus();\n }\n\n /** Focuses where activation does, unless `autoFocus` is off or focus is already inside. */\n #refocus(): void {\n if (!this.#flag(this.#options.autoFocus, true)) return;\n if (flatTreeContains(this.#getContainer(), deepActiveElement(document))) return;\n this.#focusInitial();\n }\n\n /** Lends `container` `tabindex=\"-1\"` so it can take focus; no-op when it carries a `tabindex`. */\n #lendTabindex(container: HTMLElement): void {\n const loan = this.#tabindexLoans.get(container) ?? new TabindexLoan(\"-1\", FOCUS_TRAP_OWNER);\n loan.lend(container);\n this.#tabindexLoans.set(container, loan);\n }\n\n /**\n * Takes back each lent `tabindex` except the one on the element that holds focus: removing\n * it there drops focus to `<body>`, and that element can be where the next trap returns\n * focus to. That loan stays until a later release or move of this trap, or the controller's\n * detach, finds focus elsewhere.\n */\n #returnTabindexes(): void {\n const focused = deepActiveElement(document);\n for (const [element, loan] of [...this.#tabindexLoans]) {\n if (element === focused) continue;\n loan.returnAll();\n this.#tabindexLoans.delete(element);\n }\n }\n\n /**\n * Locks the `body`'s scroll for this trap. A lock on a `body` that carries no saved\n * `overflow` saves its inline one on it: the first lock does, and so does a lock taken\n * after a Turbo morph dropped the saved value along with the locked style, while a lock\n * taken over another one does not save the locked value as the page's own.\n */\n #lockScroll(): void {\n const registry = FocusTrap.#registry(document);\n const body = document.body;\n if (!body.hasAttribute(OVERFLOW_MARK)) body.setAttribute(OVERFLOW_MARK, body.style.overflow);\n registry.scrollLocks.add(this.#entry);\n this.#entry.lockedBody = body;\n body.style.overflow = \"hidden\";\n }\n\n /**\n * Releases this trap's scroll lock, if it holds one. The last lock on the `body` it locked,\n * released in whatever order, gives that `body` its saved `overflow` back, while the `body`\n * still carries it.\n */\n #unlockScroll(): void {\n const registry = FocusTrap.#registry(document);\n const body = this.#entry.lockedBody;\n this.#entry.lockedBody = null;\n if (!registry.scrollLocks.delete(this.#entry) || !body) return;\n if (!FocusTrap.#isLocked(registry, body)) FocusTrap.#unlock(body);\n }\n\n /** Whether an active trap holds a scroll lock on `body`. */\n static #isLocked(registry: TrapRegistry, body: HTMLElement): boolean {\n return [...registry.scrollLocks].some((trap) => trap.lockedBody === body);\n }\n\n /** Gives `body` the `overflow` its mark saved and drops the mark; no mark, no change. */\n static #unlock(body: HTMLElement): void {\n const saved = body.getAttribute(OVERFLOW_MARK);\n if (saved === null) return;\n body.removeAttribute(OVERFLOW_MARK);\n body.style.overflow = saved;\n }\n\n /**\n * Releases the marked side effects no active trap holds: the `inert` of each marked\n * element the traps do not track, and the scroll lock of a marked `body` no trap locked.\n */\n static #sweep(): void {\n const registry = FocusTrap.#registry(document);\n for (const element of queryOpenDescendants<HTMLElement>(document, `[${INERT_MARK}]`)) {\n if (registry.inerted.has(element)) continue;\n element.removeAttribute(INERT_MARK);\n element.inert = false;\n }\n if (!FocusTrap.#isLocked(registry, document.body)) FocusTrap.#unlock(document.body);\n }\n\n /** The document's trap registry, created on first use. */\n static #registry(ownerDocument: Document): TrapRegistry {\n const existing = FocusTrap.#registries.get(ownerDocument);\n if (existing) return existing;\n const morphs = new MicrotaskCoalescer(() => FocusTrap.#reapply(registry));\n morphs.activate();\n const registry: TrapRegistry = {\n stack: [],\n onKeydown: (event) => FocusTrap.#resolveTab(registry.stack, event),\n onMorph: () => morphs.schedule(),\n inerted: new Set(),\n scrollLocks: new Set(),\n };\n FocusTrap.#registries.set(ownerDocument, registry);\n return registry;\n }\n\n /**\n * Puts back what a Turbo morph took from the active traps, which keeps only the attributes\n * the server sent: the background's `inert` and marks, and a locked `body`'s `overflow`\n * with its saved value, saving the `overflow` the morph left.\n */\n static #reapply(registry: TrapRegistry): void {\n FocusTrap.#reconcileBackground(document);\n const body = document.body;\n if (!FocusTrap.#isLocked(registry, body)) return;\n if (!body.hasAttribute(OVERFLOW_MARK)) body.setAttribute(OVERFLOW_MARK, body.style.overflow);\n body.style.overflow = \"hidden\";\n }\n\n /**\n * Brings the document's background `inert` in line with its stack of active traps, as\n * `#backgroundOf` computes it: an element the traps made `inert` that is no longer\n * background is released, and background that is not `inert` yet is made so, marked and\n * tracked. A tracked element that has lost its mark is no longer the traps' — a Turbo\n * morph keeps only the attributes the server sent, taking the mark with the `inert`, or\n * keeping an `inert` of the server's own — so it is forgotten first and judged like any\n * other element. Returns the elements this call made `inert`.\n */\n static #reconcileBackground(ownerDocument: Document): HTMLElement[] {\n const registry = FocusTrap.#registry(ownerDocument);\n for (const element of registry.inerted) {\n if (!element.hasAttribute(INERT_MARK)) registry.inerted.delete(element);\n }\n const background = FocusTrap.#backgroundOf(registry);\n for (const element of registry.inerted) {\n if (background.has(element)) continue;\n element.removeAttribute(INERT_MARK);\n element.inert = false;\n registry.inerted.delete(element);\n }\n const added: HTMLElement[] = [];\n for (const element of background) {\n if (registry.inerted.has(element)) continue;\n element.setAttribute(INERT_MARK, \"\");\n element.inert = true;\n registry.inerted.add(element);\n added.push(element);\n }\n return added;\n }\n\n /**\n * The elements the stack wants `inert`. Without an isolating trap, none. Otherwise the shape of\n * the most recently activated isolating trap: its container and the container's ancestors below\n * `body` are kept, and every other child of their parents is background, all in the flat tree.\n * Scanning only `body`'s children would miss the branch a container sits in, and a nested\n * container is the ordinary case. A trap activated after it that sits in that background is\n * carved out of it the same way, down its own branch; one inside the kept part adds nothing, so a\n * trap that does not isolate never makes more of the page `inert`. An element that is `inert`\n * without the traps having made it so is left out, so it is neither tracked, lifted nor released.\n * A trap whose container cannot be read counts as neither isolating nor kept.\n */\n static #backgroundOf(registry: TrapRegistry): Set<HTMLElement> {\n const containers = registry.stack.map((trap) => trap.container());\n let top = -1;\n registry.stack.forEach((trap, index) => {\n if (trap.isolated && containers[index]) top = index;\n });\n const background = new Set<HTMLElement>();\n if (top < 0) return background;\n const kept = new Set<Element>();\n const keep = (path: Element[]): void => {\n for (const node of path) {\n kept.add(node);\n background.delete(node as HTMLElement);\n }\n for (const node of path) {\n const parent = flatTreeParent(node);\n for (const sibling of parent ? flatTreeChildren(parent) : []) {\n if (!(sibling instanceof HTMLElement) || kept.has(sibling)) continue;\n if (sibling.inert && !registry.inerted.has(sibling)) continue;\n background.add(sibling);\n }\n }\n };\n containers.slice(top).forEach((container, index) => {\n const path: Element[] = [];\n for (\n let node: Element | null = container;\n node && node !== document.body && !kept.has(node);\n ) {\n path.push(node);\n node = flatTreeParent(node);\n }\n if (index === 0 || path.some((node) => background.has(node as HTMLElement))) keep(path);\n });\n return background;\n }\n\n /**\n * The container, or `null` when the getter throws (a controller whose target has left\n * the page). The shared stack reads every trap's container; one that cannot be read\n * must not break `Tab` or the background for the others.\n */\n #readContainer(): HTMLElement | null {\n try {\n return this.#getContainer();\n } catch {\n return null;\n }\n }\n\n /**\n * Hands a keydown to the trap that takes it. The shared listener runs in the document\n * bubble phase, after element-level handlers, so a `Tab` an inner widget consumed is\n * left to that widget.\n */\n static #resolveTab(stack: TrapEntry[], event: KeyboardEvent): void {\n if (event.key !== \"Tab\" || event.defaultPrevented) return;\n if (event.isComposing || event.keyCode === 229) return;\n if (event.ctrlKey || event.metaKey) return;\n const owner = FocusTrap.#tabOwner(stack);\n if (!owner) return;\n event.preventDefault();\n owner.moveFocus(event.shiftKey);\n }\n\n /** The most recently activated trap whose container can take `Tab`, or `null`. */\n static #tabOwner(stack: TrapEntry[]): TrapEntry | null {\n for (const trap of [...stack].reverse()) {\n if (FocusTrap.#takesTab(trap)) return trap;\n }\n return null;\n }\n\n /**\n * Whether the trap's container can be read, is connected and is rendered (no `hidden` on it\n * or on a flat-tree ancestor), so the trap can take `Tab`.\n */\n static #takesTab(trap: TrapEntry): boolean {\n const container = trap.container();\n if (!container) return false;\n return (\n container.isConnected &&\n !closestInFlatTree(container, \"[hidden]\") &&\n isRenderedForFocus(container)\n );\n }\n\n /** Whether this trap is the one its document's `Tab` resolves to. */\n #ownsTab(): boolean {\n return FocusTrap.#tabOwner(FocusTrap.#registry(document).stack) === this.#entry;\n }\n\n /**\n * Focuses the next stop from where focus is (the previous one when `backward`),\n * wrapping at the ends. The stops are checked before focusing, and a `focus()` that\n * still leaves focus where it was (an engine without `checkVisibility` cannot see a\n * stop hidden by CSS) moves on to the following stop, each stop tried at most once.\n * Focus and blur listeners run inside `focus()` and can release this trap or activate\n * another one, so every attempt first checks that this trap still owns `Tab`. A\n * listener that sends focus elsewhere is left to do so.\n */\n #moveFocus(backward: boolean): void {\n const from = deepActiveElement(document);\n for (const stop of sequentialTabStops(this.#getContainer(), from, backward)) {\n if (!this.#ownsTab()) return;\n const before = deepActiveElement(document);\n stop.focus();\n const after = deepActiveElement(document);\n if (after === before) continue;\n if (after === stop) FocusTrap.#selectOnEntry(stop);\n return;\n }\n }\n\n /** Selects the text of an input that focus moved into, as the engine's own `Tab` does. */\n static #selectOnEntry(stop: TabStopElement): void {\n if (stop instanceof HTMLInputElement && FocusTrap.#TEXT_ENTRY_TYPES.has(stop.type)) {\n stop.select();\n }\n }\n\n /** Moves focus to the initial target, the first stop of the trap's order, or the container. */\n #focusInitial(): void {\n const preferred = this.#options.initialFocus?.();\n if (preferred) {\n preferred.focus();\n return;\n }\n const container = this.#getContainer();\n const [first] = sequentialTabStops(container);\n if (first) {\n first.focus();\n return;\n }\n this.#lendTabindex(container);\n container.focus();\n }\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. {@link\n * 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 * 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, or one that\n * lives for less than the connection, keeps its own pair of calls.\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, which has to match at release time and no\n * longer has a second place to drift from.\n */\n add(\n target: EventTarget,\n type: string,\n handler: EventListener,\n options?: Omit<AddEventListenerOptions, \"signal\">,\n ): 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","import { ListenerSet } from \"./listener_set\";\nimport { MicrotaskCoalescer } from \"./microtask_coalescer\";\n\n/**\n * Coalesces retained-element morphs and explicit lifecycle requests into one pass.\n *\n * Observe the controller's element after its initial state is settled. Morphs on\n * that element and bubbling morphs on its descendants share the same microtask\n * as {@link schedule}. The callback repairs derived output; the controller owns\n * any logical transition reporting. {@link disconnect} releases the listener and\n * cancels pending work, including work from an earlier connected lifetime.\n */\nexport class MorphRenderWatcher {\n readonly #listeners = new ListenerSet();\n readonly #pass: MicrotaskCoalescer;\n #element: Element | null = null;\n readonly #onMorph = (): void => this.#pass.schedule();\n\n /** @param run - the single pass that repairs the settled controller's output. */\n constructor(run: () => void) {\n this.#pass = new MicrotaskCoalescer(run);\n }\n\n /** Opens observation; observing the same element again preserves queued work. */\n observe(element: Element): void {\n if (this.#element === element) return;\n this.disconnect();\n this.#element = element;\n this.#pass.activate();\n this.#listeners.add(element, \"turbo:morph-element\", this.#onMorph);\n }\n\n /** Requests one pass; requests outside an observed lifetime are ignored. */\n schedule(): void {\n this.#pass.schedule();\n }\n\n /** Releases observation and pending work synchronously; safe to repeat. */\n disconnect(): void {\n this.#listeners.dispose();\n this.#pass.cancel();\n this.#element = null;\n }\n}\n","import { MorphRenderWatcher } from \"./morph_render_watcher\";\n\n/**\n * How one connection of a controller relates to the page it connects on.\n *\n * - `\"fresh\"` — the first connection of this instance, on an element without the mark: a page\n * the server rendered, or an element added to the live page.\n * - `\"reconnect\"` — a later connection of the same instance: an in-page move, or a\n * `data-turbo-permanent` element Turbo carried to the next page.\n * - `\"restored\"` — the first connection of this instance, on an element that carries the\n * mark: a copy of the page Turbo restores from its cache (Back and Forward, a promoted frame\n * navigation followed by Back) or shows as the preview of a cached page.\n */\nexport type LivedConnection = \"fresh\" | \"reconnect\" | \"restored\";\n\n/**\n * Tells a copy of a page Turbo restores from its cache from a fresh render, by a mark each\n * connection leaves on the controller element.\n *\n * {@link LivedMark.connect} writes `data-<identifier>-lived` on the element and says how the\n * connection relates to the page. Nothing removes the mark: Turbo copies the page into its\n * cache at different moments of a navigation — after the body swap on a visit, at the start of\n * the navigation on a promoted frame — before the controller disconnects or after it, and the\n * copy carries the mark either way, while server markup never does. A new instance that finds\n * the mark is on such a copy; a reconnect of the same instance is not, whatever the element\n * carries. A Turbo morph keeps only the attributes the server sent, so the mark is written\n * again after every morph of the element or its descendants, until\n * {@link LivedMark.disconnect}. `turbo:before-cache` plays no part: Turbo also dispatches it\n * on pages that stay.\n *\n * The mark is an internal hook, not a styling one, and its name ends in no suffix Stimulus\n * reads.\n */\nexport class LivedMark {\n readonly #name: string;\n /** Whether this instance has connected before. */\n #lived = false;\n /** The element the mark is written on, for the pass that follows a morph. */\n #element: Element | null = null;\n readonly #morph = new MorphRenderWatcher(() => this.#write());\n\n /** @param identifier - The controller's identifier; the mark is `data-<identifier>-lived`. */\n constructor(identifier: string) {\n this.#name = `data-${identifier}-lived`;\n }\n\n /** Marks `element`, follows its morphs, and says how this connection relates to the page. */\n connect(element: Element): LivedConnection {\n const connection = this.#lived\n ? \"reconnect\"\n : element.hasAttribute(this.#name)\n ? \"restored\"\n : \"fresh\";\n this.#lived = true;\n this.#element = element;\n this.#write();\n this.#morph.observe(element);\n return connection;\n }\n\n /** Stops following morphs; the mark stays, for a copy Turbo may take after this. */\n disconnect(): void {\n this.#morph.disconnect();\n }\n\n /** Writes the mark on the element. */\n #write(): void {\n this.#element?.setAttribute(this.#name, \"\");\n }\n}\n","/**\n * Why a component's public state moved, carried as `detail.reason`\n * on the state event that reports the move.\n *\n * The attribute a component publishes (`aria-expanded`, `hidden`, `data-state`)\n * only says *what* the state is now. A subscriber that mirrors the state\n * elsewhere, or reports it, needs *why*: closing on `Escape` and closing because\n * the consumer called the action are the same attribute write and different\n * events to the page around it.\n *\n * `\"api\"` is the one every subscriber has to look at. A close the consumer asked\n * for arrives back at their own listener, so a listener that closes something\n * else on `close` loops unless it ignores its own calls.\n *\n * | Reason | The state moved because |\n * | --- | --- |\n * | `\"user\"` | a control of this component was operated |\n * | `\"select\"` | an item inside it was activated |\n * | `\"escape\"` | `Escape` was pressed and this layer owned it |\n * | `\"outside\"` | a pointer landed outside it, or on its backdrop |\n * | `\"focus\"` | focus entered or left it |\n * | `\"pointer\"` | the pointer entered or left it |\n * | `\"scroll\"` | a tracked scroll container scrolled |\n * | `\"api\"` | a public action was called with no DOM event |\n * | `\"timeout\"` | an automatic timer advanced or dismissed the state |\n * | `\"limit\"` | a capacity limit dismissed an item |\n * | `\"media\"` | an operating-system media preference changed |\n */\nexport type StateReason =\n | \"user\"\n | \"select\"\n | \"escape\"\n | \"outside\"\n | \"focus\"\n | \"pointer\"\n | \"scroll\"\n | \"api\"\n | \"timeout\"\n | \"limit\"\n | \"media\";\n\n/** Focus modality: the events a focus move delivers to an action. */\nconst FOCUS_EVENTS = new Set([\"blur\", \"focus\", \"focusin\", \"focusout\"]);\n\n/** Pointer modality: the crossing events an action is bound to for hover. */\nconst POINTER_EVENTS = new Set([\"mouseenter\", \"mouseleave\", \"pointerenter\", \"pointerleave\"]);\n\n/**\n * Reads the interaction behind a **public action** from the DOM event it was\n * handed.\n *\n * Stimulus always passes the event to an action it invoked from `data-action`,\n * and a consumer calling the method themselves passes nothing — which is what\n * separates `\"api\"` from the rest.\n *\n * Only an action entry may resolve a reason this way. Inside the component the\n * event type no longer identifies the interaction: one `click` is the trigger\n * being pressed, the page outside being pressed, and an item being activated,\n * and those paths pass their own reason instead.\n *\n * @param event - The event the action received, if any.\n * @returns `\"api\"` with no event, else the modality the event type names, else\n * `\"user\"`.\n *\n * @example\n * ```ts\n * toggle(event?: Event): void {\n * this.#apply(!this.#isOpen, stateReasonFor(event));\n * }\n * ```\n */\nexport function stateReasonFor(event?: Event | null): \"user\" | \"focus\" | \"pointer\" | \"api\" {\n if (!event) return \"api\";\n if (FOCUS_EVENTS.has(event.type)) return \"focus\";\n if (POINTER_EVENTS.has(event.type)) return \"pointer\";\n return \"user\";\n}\n","/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\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/** Computed transition fields needed to determine when an element has settled. */\nexport type TransitionStyle = Pick<\n CSSStyleDeclaration,\n \"transitionProperty\" | \"transitionDuration\" | \"transitionDelay\"\n>;\n\n/** Parsed transition property paired with its effective duration and delay. */\ninterface TransitionTiming {\n property: string;\n totalMs: number;\n}\n\n/** Parses a CSS `<time>` into milliseconds, returning `0` for malformed values. */\nfunction timeMs(value: string): number {\n const trimmed = value.trim();\n const amount = Number.parseFloat(trimmed);\n if (!Number.isFinite(amount)) return 0;\n if (trimmed.endsWith(\"ms\")) return amount;\n if (trimmed.endsWith(\"s\")) return amount * 1000;\n return 0;\n}\n\n/** Splits a computed comma-separated CSS list into normalized, non-empty items. */\nfunction cssList(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n/**\n * Pairs transition properties, durations, and delays using CSS list repetition.\n *\n * The `transition-property` list determines the number of transitions. Shorter\n * duration/delay lists repeat, while extra values are ignored. A negative delay\n * shortens the remaining wall-clock time, and a non-positive total is settled.\n */\nfunction transitionTimings(style: TransitionStyle): TransitionTiming[] {\n const properties = cssList(style.transitionProperty);\n const durations = cssList(style.transitionDuration).map(timeMs);\n const delays = cssList(style.transitionDelay).map(timeMs);\n const effectiveProperties =\n properties.length > 0\n ? properties\n : Array.from({ length: Math.max(durations.length, delays.length, 1) }, () => \"all\");\n const effectiveDurations = durations.length > 0 ? durations : [0];\n const effectiveDelays = delays.length > 0 ? delays : [0];\n\n return effectiveProperties\n .filter((property) => property !== \"none\")\n .map((property, index) => ({\n property,\n totalMs: Math.max(\n 0,\n (effectiveDurations[index % effectiveDurations.length] ?? 0) +\n (effectiveDelays[index % effectiveDelays.length] ?? 0),\n ),\n }));\n}\n\n/** Maximum total over already-parsed timings (0 when the list is empty). */\nfunction maxTotalMs(timings: TransitionTiming[]): number {\n return timings.reduce((max, { totalMs }) => Math.max(max, totalMs), 0);\n}\n\n/** Maximum effective transition duration plus delay, in milliseconds. */\nexport function maxTransitionTotalMs(style: TransitionStyle): number {\n return maxTotalMs(transitionTimings(style));\n}\n\n/** Optional tuning for a single {@link TransitionCompletion.wait} call. */\nexport interface TransitionWaitOptions {\n /**\n * Positive wall-clock override (ms) for the bounded fallback, replacing the\n * auto-computed `max + 50ms` timer verbatim. It also keeps the wait armed for\n * a computed 0ms transition (no synchronous completion): the consumer asserts\n * a transition budget that computed styles cannot see. Non-positive and\n * non-finite (`NaN` / `Infinity`) values are ignored.\n */\n timeoutMs?: number;\n}\n\n/**\n * Owns one cancellable wait for an element's CSS transitions to settle.\n *\n * When available, active CSS transitions provide their expanded property names.\n * Tracking those names lets shorthand declarations settle from their longhand\n * terminal events. A terminal event from an interrupted phase is ignored while a\n * replacement transition for the same property is still active. Because that set\n * is sampled when the wait is armed, a property whose transition only starts a\n * frame later would otherwise be settled over; the still-running set is therefore\n * re-read before completing and adopted when it is not yet empty. Without Web\n * Animations data, explicit transition properties retain the declared-property\n * behavior and the ambiguous `transition-property: all` form waits until the\n * computed maximum wall-clock time. A `max + 50ms` timeout is always armed\n * because browsers emit no terminal event when a property never transitions, an\n * ancestor disappears, or rendering is otherwise interrupted; a consumer with\n * better knowledge can replace that fallback via\n * {@link TransitionWaitOptions.timeoutMs}.\n */\nexport class TransitionCompletion {\n readonly #timers = new SafeTimeout();\n #element: HTMLElement | null = null;\n #complete: (() => void) | null = null;\n #pendingProperties: Set<string> | null = null;\n #deadline = 0;\n\n /**\n * Replaces any prior wait and invokes `complete` synchronously for a 0ms\n * transition (including when `getComputedStyle` is unavailable).\n *\n * With a positive `options.timeoutMs` the synchronous fast-path is skipped and\n * the override replaces the auto-computed fallback (see {@link TransitionWaitOptions}).\n */\n wait(element: HTMLElement, complete: () => void, options: TransitionWaitOptions = {}): void {\n this.cancel();\n\n const requested = options.timeoutMs ?? 0;\n const override = Number.isFinite(requested) && requested > 0 ? requested : 0;\n // A non-browser / partial-DOM environment cannot report a computable\n // transition, which is indistinguishable from a 0ms one.\n const timings =\n typeof window.getComputedStyle === \"function\"\n ? transitionTimings(window.getComputedStyle(element))\n : [];\n const maximum = maxTotalMs(timings);\n if (maximum <= 0 && override <= 0) {\n complete();\n return;\n }\n\n this.#element = element;\n this.#complete = complete;\n this.#deadline = Date.now() + maximum;\n const activeProperties = this.#activeTransitionProperties(element);\n this.#pendingProperties =\n activeProperties.size > 0 ? activeProperties : this.#explicitPendingProperties(timings);\n element.addEventListener(\"transitionend\", this.#onTerminal);\n element.addEventListener(\"transitioncancel\", this.#onTerminal);\n this.#timers.set(() => this.#finish(), override > 0 ? override : maximum + 50);\n }\n\n /** Cancels the pending wait without invoking its completion callback. */\n cancel(): void {\n this.#complete = null;\n this.#teardown();\n }\n\n /**\n * Handles terminal events from the observed element only.\n *\n * For explicit property lists, every declared positive-time property must\n * settle. For `all`, no reliable property set exists, so an event can finish\n * only after the computed maximum time; the safety timeout owns the usual path.\n */\n readonly #onTerminal = (event: Event): void => {\n if (event.target !== this.#element) return;\n const transitionEvent = event as TransitionEvent;\n // A pseudo-element's transition is reported with its originating element\n // as `target`; it must not settle the element's own transition.\n if (transitionEvent.pseudoElement) return;\n\n if (this.#pendingProperties) {\n const propertyName = transitionEvent.propertyName;\n const active = this.#activeTransitionProperties(this.#element);\n // An interrupted transition queues its cancel event before the replacement\n // phase starts, but dispatch can happen after the new wait is armed. The\n // replacement is then the active transition for this property, so the stale\n // terminal event must not settle the new phase.\n if (active.has(propertyName)) return;\n if (!this.#pendingProperties.delete(propertyName)) return;\n if (this.#pendingProperties.size > 0) return;\n // The tracked set is an arm-time snapshot, so a transition the phase starts\n // one frame later is absent from it. Re-reading the still-running set before\n // settling adopts those stragglers instead of completing over them; the\n // fallback timer stays armed, so this cannot extend the wait unboundedly.\n if (active.size > 0) {\n this.#pendingProperties = active;\n return;\n }\n this.#finish();\n return;\n }\n\n if (Date.now() >= this.#deadline) this.#finish();\n };\n\n /**\n * Returns active CSS transition properties expanded to the names reported by\n * terminal events. CSS animations and pseudo-element effects are excluded.\n */\n #activeTransitionProperties(element: HTMLElement | null): Set<string> {\n if (!element || typeof element.getAnimations !== \"function\") return new Set();\n\n try {\n const properties = element.getAnimations().flatMap((animation) => {\n if (animation.playState === \"idle\" || animation.playState === \"finished\") return [];\n const effect = animation.effect as KeyframeEffect | null;\n // A pseudo-element effect names the originating element as its target, so\n // `target` alone cannot separate it. Its terminal events are ignored, so\n // tracking its properties would only strand the wait on the fallback.\n if (effect?.pseudoElement) return [];\n const target = effect?.target;\n if (target && target !== element) return [];\n const property = (animation as Partial<CSSTransition>).transitionProperty;\n return typeof property === \"string\" && property.length > 0 ? [property] : [];\n });\n return new Set(properties);\n } catch {\n // Partial DOM implementations can expose getAnimations without supporting\n // it. The declared-property tracker and bounded timer remain safe fallbacks.\n return new Set();\n }\n }\n\n /** Returns explicit positive-time properties, or `null` for the ambiguous `all`. */\n #explicitPendingProperties(timings: TransitionTiming[]): Set<string> | null {\n if (timings.some(({ property }) => property === \"all\")) return null;\n const pending = new Set(\n timings.filter(({ totalMs }) => totalMs > 0).map(({ property }) => property),\n );\n // An empty set is only reachable through a timeout override (a 0ms transition\n // otherwise completes synchronously). With nothing to track, fall back to the\n // deadline rule so any terminal event can settle the wait, exactly like `all`.\n return pending.size > 0 ? pending : null;\n }\n\n /** Completes exactly once, releasing listeners and the fallback before the callback. */\n #finish(): void {\n const complete = this.#complete;\n if (!complete) return;\n this.#complete = null;\n this.#teardown();\n complete();\n }\n\n /** Releases the exact element listeners and timer owned by the current wait. */\n #teardown(): void {\n this.#timers.clearAll();\n this.#element?.removeEventListener(\"transitionend\", this.#onTerminal);\n this.#element?.removeEventListener(\"transitioncancel\", this.#onTerminal);\n this.#element = null;\n this.#pendingProperties = null;\n this.#deadline = 0;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { FocusTrap } from \"../utils/focus_trap\";\nimport { LivedMark } from \"../utils/lived_mark\";\nimport { MorphRenderWatcher } from \"../utils/morph_render_watcher\";\nimport { type StateReason, stateReasonFor } from \"../utils/state_reason\";\nimport { TransitionCompletion } from \"../utils/transition_completion\";\n\n/** Edge a drawer slides from; reflected as `data-placement` for the consumer CSS. */\ntype Placement = \"left\" | \"right\" | \"top\" | \"bottom\";\n\n/**\n * Headless, accessible **drawer / slide-over** behavior.\n *\n * Markup contract (identifier: `stimeo--drawer`):\n * <div data-controller=\"stimeo--drawer\" data-stimeo--drawer-placement-value=\"right\">\n * <button data-stimeo--drawer-target=\"trigger\"\n * data-action=\"click->stimeo--drawer#open\">Open panel</button>\n * <div data-stimeo--drawer-target=\"overlay\"\n * data-action=\"click->stimeo--drawer#closeOnBackdrop\" hidden>\n * <div data-stimeo--drawer-target=\"panel\" role=\"dialog\" aria-modal=\"true\"\n * aria-labelledby=\"t\" data-state=\"closed\" hidden>\n * <h2 id=\"t\">…</h2>\n * <button data-action=\"click->stimeo--drawer#close\">Close</button>\n * </div>\n * </div>\n * </div>\n *\n * Implements the WAI-ARIA APG **Dialog (Modal)** pattern. It is the same modal as\n * `stimeo--dialog`; what it adds is the state plumbing an enter/exit *slide*\n * needs: `data-state` (`open`/`closed`) is synced on the panel and overlay so CSS\n * can animate, and `hidden` is applied only *after* the close transition finishes\n * (so the exit animation can play). `placement` is reflected as `data-placement`\n * for the CSS to read — the controller never computes coordinates.\n *\n * @remarks\n * Behavior only. The modal lifecycle (focus trap, scroll lock, background\n * `inert`, focus restore, teardown reversal) is delegated to the shared\n * `FocusTrap`. Placement, slide direction, distance, and easing are all the\n * consumer's CSS — `data-placement` is merely a flag.\n *\n * Behavior provided:\n * - {@link DrawerController.open | open}/{@link DrawerController.close | close}\n * toggle `data-state` and (deferred) `hidden`.\n * - On open, focus moves to the first focusable element in the panel.\n * - `Tab`/`Shift+Tab` cycle focus within the panel; `Escape` closes.\n * - {@link closeOnBackdrop} closes only when the overlay *itself* is clicked.\n * - Each move of the open state is reported: `stimeo--drawer:open` and\n * `stimeo--drawer:close` dispatch `{ reason: StateReason }`, as soon as\n * `data-state` is written — the deferred `hidden` and the exit transition are\n * not waited for. Both are informational, so neither is cancelable. A call\n * that leaves the state where it already was, the normalization in\n * {@link connect}, the reconciliation that follows panel or overlay churn,\n * and {@link disconnect} are all silent.\n * - After {@link disconnect} the actions do nothing until the controller\n * connects again: no state is written, nothing is reported and the focus\n * trap is not taken.\n */\nexport class DrawerController extends Controller<HTMLElement> {\n static override targets = [\"trigger\", \"overlay\", \"panel\"];\n static override values = {\n placement: { type: String, default: \"right\" },\n open: { type: Boolean, default: false },\n };\n static actions = [\"close\", \"closeOnBackdrop\", \"open\"] as const;\n static events = [\"close\", \"open\"] as const;\n\n declare readonly triggerTarget: HTMLElement;\n declare readonly overlayTarget: HTMLElement;\n declare readonly overlayTargets: HTMLElement[];\n declare readonly panelTarget: HTMLElement;\n declare readonly panelTargets: HTMLElement[];\n declare readonly hasTriggerTarget: boolean;\n declare readonly hasOverlayTarget: boolean;\n declare readonly hasPanelTarget: boolean;\n\n declare placementValue: string;\n declare openValue: boolean;\n\n /** Exact panel currently owned by the modal lifecycle (survives target churn safely). */\n #activePanel: HTMLElement | null = null;\n #openState = false;\n\n /** Owns the modal side effects; Escape closes, focus falls back to the trigger. */\n readonly #trap = new FocusTrap(() => this.#activePanel ?? this.panelTarget, {\n onEscape: () => this.#close(\"escape\"),\n fallbackFocus: () => (this.hasTriggerTarget ? this.triggerTarget : null),\n });\n\n /** Owns the cancellable close-transition wait and its bounded fallback. */\n readonly #transition = new TransitionCompletion();\n /** Distinguishes dynamic target churn from callbacks around controller teardown. */\n #connected = false;\n\n /** Whether state moves are reported: set once `connect()` settled the baseline. */\n #reporting = false;\n\n /**\n * Marks the element at each connection and tells a new instance on a copy of the page Turbo\n * restores from its cache from a fresh render and from a reconnect of this instance.\n */\n readonly #lived = new LivedMark(this.identifier);\n\n readonly #morphRender = new MorphRenderWatcher(() => this.#repair());\n\n /** Borrows `data-state` on each panel and overlay, to give back when one stops being a target. */\n readonly #stateLease = new AttributeLease<HTMLElement>(\"data-state\", this.identifier);\n /** Borrows `hidden` on each panel and overlay, for the same return. */\n readonly #hiddenLease = new AttributeLease<HTMLElement>(\"hidden\", this.identifier);\n /** Borrows `data-placement` on each panel, for the same return. */\n readonly #placementLease = new AttributeLease<HTMLElement>(\"data-placement\", this.identifier);\n\n /**\n * Reflects placement and establishes the initial open/closed state.\n *\n * A panel the server renders `data-state=\"open\"` opens, and so does an `open` Value\n * of `true`, which only seeds that first render. A reconnect of this instance (an\n * in-page move, a permanent element carried to the next page) keeps an open drawer\n * open: the panel's `data-state` decides, not the Value. A copy of the page Turbo\n * restores from its cache comes back closed, whatever opened the drawer — the server's\n * markup, the `open` Value or the user — and the `open` Value is written `false`: every\n * connection leaves `data-<identifier>-lived` on the element, a copy carries it, and a\n * new instance that finds it is on such a copy. The baseline is normalized closed first,\n * silently, so {@link DrawerController.open | open} runs its full reveal and takes the\n * `FocusTrap` again.\n */\n override connect(): void {\n const restored = this.#lived.connect(this.element) === \"restored\";\n this.#trap.connect();\n this.#morphRender.observe(this.element);\n this.#connected = true;\n this.#activePanel = this.hasPanelTarget ? this.panelTarget : null;\n this.#reflectPlacement();\n const shouldOpen = !restored && (this.#isOpen || this.openValue);\n this.#applyClosedState();\n if (restored) this.openValue = false;\n if (shouldOpen) this.#open(\"api\");\n this.#reporting = true;\n }\n\n /** Reverts the modal side effects and pending hide if torn down while open. */\n override disconnect(): void {\n this.#lived.disconnect();\n this.#morphRender.disconnect();\n this.#connected = false;\n this.#reporting = false;\n this.#transition.cancel();\n this.#trap.disconnect(this);\n this.#activePanel = null;\n }\n\n /**\n * Adopts a panel target that arrives while no owned panel is on the page. The owned panel\n * moving within the element arrives here too, and stays owned as it is.\n */\n panelTargetConnected(panel: HTMLElement): void {\n if (!this.#connected || this.#activePanel?.isConnected) return;\n this.#adoptPanel(panel);\n }\n\n /**\n * Gives a panel that no longer resolves as a target its own `data-state`, `hidden` and\n * `data-placement` back — after `disconnect()` too, since dropping the identifier leaves the\n * element on the page. When the owned panel leaves, or a move puts another panel in front\n * of it, the drawer closes and adopts the panel now first: an open one takes the modal trap\n * over in place, and otherwise, or with no panel left, the modal side effects are released.\n * A move that keeps the owned panel first changes nothing. After {@link disconnect} nothing\n * is adopted: a panel still owned once a handler disconnected the controller only releases\n * the modal side effects as it leaves.\n */\n panelTargetDisconnected(panel: HTMLElement): void {\n const stays = this.panelTargets.includes(panel);\n if (!stays) {\n this.#stateLease.return(panel);\n this.#hiddenLease.return(panel);\n this.#placementLease.return(panel);\n }\n if (panel !== this.#activePanel || (stays && this.panelTarget === panel)) return;\n this.#transition.cancel();\n this.#activePanel = null;\n if (!this.#connected) {\n this.#trap.deactivate({ restoreFocus: false });\n return;\n }\n\n this.#openState = false;\n if (stays) {\n this.#writeState(panel, \"closed\");\n this.#writeHidden(panel, true);\n }\n this.#writeOverlayState(\"closed\");\n this.#writeOverlayHidden(true);\n this.openValue = false;\n\n // Handles morph implementations that add the replacement before removing\n // the old target (its connected callback was intentionally ignored above).\n if (this.hasPanelTarget) this.#adoptPanel(this.panelTarget);\n else this.#trap.deactivate();\n }\n\n /** Reflects the open state onto an overlay that arrives in front of the others. */\n overlayTargetConnected(): void {\n this.#morphRender.schedule();\n }\n\n /**\n * Gives an overlay that no longer resolves as the target its own `data-state` and `hidden`\n * back — after `disconnect()` too, since dropping the identifier leaves the element on the\n * page — and reflects the open state onto the overlay left.\n */\n overlayTargetDisconnected(overlay: HTMLElement): void {\n if (!this.overlayTargets.includes(overlay)) {\n this.#stateLease.return(overlay);\n this.#hiddenLease.return(overlay);\n }\n this.#morphRender.schedule();\n }\n\n /** Keeps `data-placement` in sync if the value changes at runtime. */\n placementValueChanged(): void {\n if (this.#connected) this.#repair();\n else this.#reflectPlacement();\n }\n\n /** Opens the drawer: reveals it, syncs `data-state`, traps focus. */\n open(event?: Event): void {\n if (!this.#connected) return;\n this.#open(stateReasonFor(event));\n }\n\n /** Reveals the drawer, syncs `data-state`, reports a move, then traps focus. */\n #open(reason: StateReason): void {\n if (!this.hasPanelTarget || this.#isOpen) return;\n this.#transition.cancel();\n this.#activePanel = this.panelTarget;\n // Reveal the panel/overlay while they are still in their `data-state=\"closed\"`\n // (off-screen) position, so the browser has a rendered \"from\" frame.\n this.#writeHidden(this.panelTarget, false);\n this.#writeOverlayHidden(false);\n // Force a reflow to commit that closed frame before flipping to \"open\"; without\n // it the enter transition is skipped (going straight from display:none to the\n // open position paints no intermediate state, so the panel jumps in instead of\n // sliding). The exit transition already works because the panel stays displayed.\n void this.panelTarget.offsetWidth;\n this.#setState(\"open\");\n this.openValue = true;\n if (this.#reporting) this.dispatch(\"open\", { detail: { reason }, cancelable: false });\n // A subscriber may close it again from the handler above. Everything below\n // applies to an element that is open; run it against a closed one and the\n // side effects have no path back — the later `close()` returns early.\n if (!this.#isOpen) return;\n this.#trap.activate();\n }\n\n /**\n * Closes the drawer: syncs `data-state` to start the exit transition, then\n * defers both `hidden` *and* the modal teardown (scroll lock / background\n * `inert` / focus restore) until the transition finishes. This keeps the\n * background inert and focus trapped while the drawer is still visually on\n * screen, preserving the modal contract during the exit animation.\n */\n close(event?: Event): void {\n if (!this.#connected) return;\n this.#close(stateReasonFor(event));\n }\n\n /** Closes only when the overlay itself (not its contents) is clicked. */\n closeOnBackdrop(event: MouseEvent): void {\n if (!this.#connected) return;\n if (this.hasOverlayTarget && event.target === this.overlayTarget) this.#close(\"outside\");\n }\n\n /** Starts the exit transition, reports a move, then defers `hidden` and teardown. */\n #close(reason: StateReason): void {\n if (!this.hasPanelTarget || !this.#isOpen) return;\n this.openValue = false;\n this.#setState(\"closed\");\n if (this.#reporting) this.dispatch(\"close\", { detail: { reason }, cancelable: false });\n // A subscriber may reopen it from the handler above; hiding after the exit\n // transition would then apply `hidden` to a drawer that is on screen.\n if (this.#isOpen) return;\n this.#hideAfterTransition();\n }\n\n /**\n * Writes `data-placement` from the current `placement` value.\n *\n * @stimeoRenderRoot\n */\n #reflectPlacement(): void {\n if (this.hasPanelTarget) this.#placementLease.write(this.panelTarget, this.#placement);\n }\n\n /**\n * Reconciles a replacement panel and companion overlay from its explicit DOM state. An open\n * panel takes the modal trap, moved onto it in place when already active.\n */\n #adoptPanel(panel: HTMLElement): void {\n this.#transition.cancel();\n this.#activePanel = panel;\n this.#placementLease.write(panel, this.#placement);\n if (panel.getAttribute(\"data-state\") === \"open\") {\n this.#openState = true;\n this.#writeHidden(panel, false);\n this.#writeOverlayState(\"open\");\n this.#writeOverlayHidden(false);\n this.openValue = true;\n if (this.#trap.active) this.#trap.refreshContainer();\n else this.#trap.activate();\n return;\n }\n\n this.#openState = false;\n this.#writeState(panel, \"closed\");\n this.#writeHidden(panel, true);\n this.#writeOverlayState(\"closed\");\n this.#writeOverlayHidden(true);\n this.openValue = false;\n this.#trap.deactivate();\n }\n\n /** Repairs the current panel without restarting its modal lifetime. */\n #repair(): void {\n this.#reflectPlacement();\n if (!this.hasPanelTarget) return;\n this.#setState(this.#openState ? \"open\" : \"closed\");\n const hidden = !this.#openState && !this.#trap.active;\n this.#writeHidden(this.panelTarget, hidden);\n this.#writeOverlayHidden(hidden);\n }\n\n /** Validated placement (`left`/`right`/`top`/`bottom`), defaulting to `right`. */\n get #placement(): Placement {\n const value = this.placementValue;\n return value === \"left\" || value === \"top\" || value === \"bottom\" ? value : \"right\";\n }\n\n /** Syncs `data-state` on the panel and overlay together. */\n #setState(state: \"open\" | \"closed\"): void {\n this.#openState = state === \"open\";\n if (this.hasPanelTarget) this.#writeState(this.panelTarget, state);\n this.#writeOverlayState(state);\n }\n\n /** Writes `data-state` on a panel or overlay, through the lease that gives it back. */\n #writeState(element: HTMLElement, state: \"open\" | \"closed\"): void {\n this.#stateLease.write(element, state);\n }\n\n /** Writes `hidden` on a panel or overlay, through the lease that gives it back. */\n #writeHidden(element: HTMLElement, hidden: boolean): void {\n this.#hiddenLease.write(element, hidden ? \"\" : null);\n }\n\n /** Writes `data-state` on the first overlay. */\n #writeOverlayState(state: \"open\" | \"closed\"): void {\n if (this.hasOverlayTarget) this.#writeState(this.overlayTarget, state);\n }\n\n /** Writes `hidden` on the first overlay. */\n #writeOverlayHidden(hidden: boolean): void {\n if (this.hasOverlayTarget) this.#writeHidden(this.overlayTarget, hidden);\n }\n\n /** Fully reflects the closed state up front (used on connect when not open). */\n #applyClosedState(): void {\n this.#setState(\"closed\");\n if (this.hasPanelTarget) this.#writeHidden(this.panelTarget, true);\n this.#writeOverlayHidden(true);\n }\n\n /**\n * Applies `hidden` once the panel's close transition ends, so the exit slide\n * can play. The shared waiter hides synchronously for 0ms transitions and\n * supplies a bounded fallback when the browser emits no terminal event.\n */\n #hideAfterTransition(): void {\n const panel = this.panelTarget;\n this.#activePanel = panel;\n this.#transition.wait(panel, () => this.#applyHidden(panel));\n }\n\n /**\n * Runs once the close transition has finished: applies `hidden` to the panel\n * and overlay, then reverts the modal side effects (scroll lock, background\n * `inert`, keydown listener) and restores focus to the opener. Deferring the\n * `FocusTrap` teardown to here — rather than at\n * {@link DrawerController.close | close} time — keeps the background unreachable\n * and focus trapped for the whole exit animation.\n */\n #applyHidden(panel: HTMLElement): void {\n this.#writeHidden(panel, true);\n this.#writeOverlayHidden(true);\n this.#trap.deactivate();\n }\n\n /** Whether the drawer is open (tracked via `data-state`, not `hidden`). */\n get #isOpen(): boolean {\n return this.hasPanelTarget && this.panelTarget.getAttribute(\"data-state\") === \"open\";\n }\n}\n"]}
|