1use std::collections::HashMap;
2use wgpui::{
3 AnyElement, App, Bounds, Element, ElementId, FocusHandle, Global, GlobalElementId,
4 InteractiveElement, Interactivity, IntoElement, LayoutId, ParentElement, Pixels,
5 StatefulInteractiveElement, StyleRefinement, Styled, WeakFocusHandle, Window,
6};
7
8pub fn init(cx: &mut App) {
10 cx.set_global(FocusTrapManager::new());
11}
12
13pub trait FocusTrapElement: InteractiveElement + Sized {
15 fn focus_trap(
40 self,
41 id: impl Into<ElementId>,
42 focus_handle: &FocusHandle,
43 ) -> FocusTrapContainer<Self>
44 where
45 Self: ParentElement + Styled + Element + 'static,
46 {
47 FocusTrapContainer::new(id, focus_handle.clone(), self)
48 }
49}
50impl<T: InteractiveElement + Sized> FocusTrapElement for T {}
51
52pub(crate) struct FocusTrapManager {
54 traps: HashMap<GlobalElementId, WeakFocusHandle>,
56}
57
58impl Global for FocusTrapManager {}
59
60impl FocusTrapManager {
61 fn new() -> Self {
63 Self {
64 traps: HashMap::new(),
65 }
66 }
67
68 pub(crate) fn global(cx: &App) -> &Self {
69 cx.global::<FocusTrapManager>()
70 }
71
72 fn global_mut(cx: &mut App) -> &mut Self {
73 cx.global_mut::<FocusTrapManager>()
74 }
75
76 fn register_trap(id: &GlobalElementId, container_handle: WeakFocusHandle, cx: &mut App) {
78 let this = Self::global_mut(cx);
79 this.traps.insert(id.clone(), container_handle);
80 this.cleanup();
81 }
82
83 fn find_active_trap(window: &Window, cx: &App) -> Option<FocusHandle> {
85 let mut active: Option<FocusHandle> = None;
86 for container_handle in Self::global(cx).traps.values() {
87 let Some(container) = container_handle.upgrade() else {
88 continue;
89 };
90
91 if container.contains_focused(window, cx)
92 && active
93 .as_ref()
94 .is_none_or(|current| current.contains(&container, window))
95 {
96 active = Some(container);
101 }
102 }
103 active
104 }
105
106 fn cleanup(&mut self) {
108 self.traps.retain(|_, handle| handle.upgrade().is_some());
109 }
110}
111
112impl Default for FocusTrapManager {
113 fn default() -> Self {
114 Self::new()
115 }
116}
117
118pub struct FocusTrapContainer<E: InteractiveElement + ParentElement + Styled + Element> {
123 id: ElementId,
124 focus_handle: FocusHandle,
125 base: E,
126}
127
128impl<E: InteractiveElement + ParentElement + Styled + Element> FocusTrapContainer<E> {
129 pub(crate) fn new(id: impl Into<ElementId>, focus_handle: FocusHandle, child: E) -> Self {
130 Self {
131 id: id.into(),
132 base: child.track_focus(&focus_handle),
133 focus_handle,
134 }
135 }
136}
137
138impl<E: InteractiveElement + ParentElement + Styled + Element> IntoElement
139 for FocusTrapContainer<E>
140{
141 type Element = Self;
142
143 fn into_element(self) -> Self::Element {
144 self
145 }
146}
147impl<E: InteractiveElement + ParentElement + Styled + Element> ParentElement
148 for FocusTrapContainer<E>
149{
150 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
151 self.base.extend(elements);
152 }
153}
154impl<E: InteractiveElement + ParentElement + Styled + Element> InteractiveElement
155 for FocusTrapContainer<E>
156{
157 fn interactivity(&mut self) -> &mut Interactivity {
158 self.base.interactivity()
159 }
160}
161impl<E: InteractiveElement + ParentElement + Styled + Element> StatefulInteractiveElement
162 for FocusTrapContainer<E>
163{
164}
165impl<E: InteractiveElement + ParentElement + Styled + Element> Styled for FocusTrapContainer<E> {
166 fn style(&mut self) -> &mut StyleRefinement {
167 self.base.style()
168 }
169}
170
171impl<E: InteractiveElement + ParentElement + Styled + Element + 'static> Element
172 for FocusTrapContainer<E>
173{
174 type RequestLayoutState = E::RequestLayoutState;
175 type PrepaintState = E::PrepaintState;
176
177 fn id(&self) -> Option<ElementId> {
178 Some(self.id.clone())
179 }
180
181 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
182 None
183 }
184
185 fn a11y_role(&self) -> Option<wgpui::Role> {
186 self.base.a11y_role()
187 }
188
189 fn take_a11y_actions(&mut self) -> Vec<(wgpui::accesskit::Action, wgpui::A11yActionListener)> {
190 self.base.take_a11y_actions()
191 }
192
193 fn a11y_focus_handle(&self) -> Option<wgpui::FocusHandle> {
194 self.base.a11y_focus_handle()
195 }
196
197 fn a11y_reports_active_descendant(&self) -> bool {
198 self.base.a11y_reports_active_descendant()
199 }
200
201 fn write_a11y_info(&self, node: &mut wgpui::accesskit::Node) {
202 self.base.write_a11y_info(node);
203 }
204
205 fn a11y_synthetic_children(
206 &mut self,
207 prepaint: &mut Self::PrepaintState,
208 builder: &mut wgpui::A11ySubtreeBuilder,
209 ) {
210 self.base.a11y_synthetic_children(prepaint, builder);
211 }
212
213 fn request_layout(
214 &mut self,
215 global_id: Option<&wgpui::GlobalElementId>,
216 _inspector_id: Option<&wgpui::InspectorElementId>,
217 window: &mut Window,
218 cx: &mut App,
219 ) -> (LayoutId, Self::RequestLayoutState) {
220 FocusTrapManager::register_trap(global_id.unwrap(), self.focus_handle.downgrade(), cx);
222
223 self.base.request_layout(global_id, None, window, cx)
224 }
225
226 fn prepaint(
227 &mut self,
228 global_id: Option<&wgpui::GlobalElementId>,
229 inspector_id: Option<&wgpui::InspectorElementId>,
230 bounds: Bounds<Pixels>,
231 request_layout: &mut Self::RequestLayoutState,
232 window: &mut Window,
233 cx: &mut App,
234 ) -> Self::PrepaintState {
235 self.base
236 .prepaint(global_id, inspector_id, bounds, request_layout, window, cx)
237 }
238
239 fn paint(
240 &mut self,
241 global_id: Option<&wgpui::GlobalElementId>,
242 inspector_id: Option<&wgpui::InspectorElementId>,
243 bounds: Bounds<Pixels>,
244 request_layout: &mut Self::RequestLayoutState,
245 prepaint: &mut Self::PrepaintState,
246 window: &mut Window,
247 cx: &mut App,
248 ) {
249 self.base.paint(
250 global_id,
251 inspector_id,
252 bounds,
253 request_layout,
254 prepaint,
255 window,
256 cx,
257 )
258 }
259}
260
261#[doc(hidden)]
263pub fn active_focus_trap(window: &Window, cx: &App) -> Option<FocusHandle> {
264 FocusTrapManager::find_active_trap(window, cx)
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270 use crate::TestSupportExt as _;
271 use wgpui::{Role, TestAppContext, accesskit, div};
272
273 #[wgpui::test]
274 fn trap_exports_inner_semantics_through_the_outer_native_hooks(cx: &mut TestAppContext) {
275 cx.update(|cx| {
276 for (role, name) in [
277 (Role::Dialog, "Edit server"),
278 (Role::AlertDialog, "Delete server?"),
279 ] {
280 let trap = div()
281 .id("inner-host")
282 .test_support()
283 .role(role)
284 .aria_label(name)
285 .aria_description("Server settings")
286 .focus_trap("outer-trap", &cx.focus_handle());
287 assert_eq!(Element::id(&trap), Some("outer-trap".into()));
291 assert_eq!(trap.a11y_role(), Some(role));
292 let mut node = accesskit::Node::new(role);
293 trap.write_a11y_info(&mut node);
294 assert_eq!(node.label(), Some(name));
295 assert_eq!(node.description(), Some("Server settings"));
296 }
297 });
298 }
299}