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