1use gpui::{
2 AnyElement, App, Bounds, Element, ElementId, FocusHandle, Global, GlobalElementId,
3 InteractiveElement, Interactivity, LayoutId, ParentElement, Pixels, StatefulInteractiveElement,
4 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(
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> ParentElement
139 for FocusTrapContainer<E>
140{
141 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
142 self.base.extend(elements);
143 }
144}
145impl<E: InteractiveElement + ParentElement + Styled + Element> InteractiveElement
146 for FocusTrapContainer<E>
147{
148 fn interactivity(&mut self) -> &mut Interactivity {
149 self.base.interactivity()
150 }
151}
152impl<E: InteractiveElement + ParentElement + Styled + Element> StatefulInteractiveElement
153 for FocusTrapContainer<E>
154{
155}
156impl<E: InteractiveElement + ParentElement + Styled + Element> Styled for FocusTrapContainer<E> {
157 fn style(&mut self) -> &mut StyleRefinement {
158 self.base.style()
159 }
160}
161
162impl<E: InteractiveElement + ParentElement + Styled + Element + 'static> Element
163 for FocusTrapContainer<E>
164{
165 type RequestLayoutState = E::RequestLayoutState;
166 type PrepaintState = E::PrepaintState;
167
168 fn id(&self) -> Option<ElementId> {
169 Some(self.id.clone())
170 }
171
172 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
173 None
174 }
175
176 fn a11y_role(&self) -> Option<gpui::Role> {
177 self.base.a11y_role()
178 }
179
180 fn write_a11y_info(&self, node: &mut gpui::accesskit::Node) {
181 self.base.write_a11y_info(node);
182 }
183
184 fn a11y_synthetic_children(
185 &mut self,
186 prepaint: &mut Self::PrepaintState,
187 builder: &mut gpui::A11ySubtreeBuilder,
188 ) {
189 self.base.a11y_synthetic_children(prepaint, builder);
190 }
191
192 fn request_layout(
193 &mut self,
194 global_id: Option<&gpui::GlobalElementId>,
195 _inspector_id: Option<&gpui::InspectorElementId>,
196 window: &mut Window,
197 cx: &mut App,
198 ) -> (LayoutId, Self::RequestLayoutState) {
199 FocusTrapManager::register_trap(global_id.unwrap(), self.focus_handle.downgrade(), cx);
201
202 self.base.request_layout(global_id, None, window, cx)
203 }
204
205 fn prepaint(
206 &mut self,
207 global_id: Option<&gpui::GlobalElementId>,
208 inspector_id: Option<&gpui::InspectorElementId>,
209 bounds: Bounds<Pixels>,
210 request_layout: &mut Self::RequestLayoutState,
211 window: &mut Window,
212 cx: &mut App,
213 ) -> Self::PrepaintState {
214 self.base
215 .prepaint(global_id, inspector_id, bounds, request_layout, window, cx)
216 }
217
218 fn paint(
219 &mut self,
220 global_id: Option<&gpui::GlobalElementId>,
221 inspector_id: Option<&gpui::InspectorElementId>,
222 bounds: Bounds<Pixels>,
223 request_layout: &mut Self::RequestLayoutState,
224 prepaint: &mut Self::PrepaintState,
225 window: &mut Window,
226 cx: &mut App,
227 ) {
228 self.base.paint(
229 global_id,
230 inspector_id,
231 bounds,
232 request_layout,
233 prepaint,
234 window,
235 cx,
236 )
237 }
238}
239
240#[doc(hidden)]
242pub fn active_focus_trap(window: &Window, cx: &App) -> Option<FocusHandle> {
243 FocusTrapManager::find_active_trap(window, cx)
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249 use crate::TestSupportExt as _;
250 use gpui::{Role, TestAppContext, accesskit, div};
251
252 #[gpui::test]
253 fn trap_exports_inner_semantics_through_the_outer_native_hooks(cx: &mut TestAppContext) {
254 cx.update(|cx| {
255 for (role, name) in [
256 (Role::Dialog, "Edit server"),
257 (Role::AlertDialog, "Delete server?"),
258 ] {
259 let trap = div()
260 .id("inner-host")
261 .test_support()
262 .role(role)
263 .aria_label(name)
264 .aria_description("Server settings")
265 .focus_trap("outer-trap", &cx.focus_handle());
266 assert_eq!(Element::id(&trap), Some("outer-trap".into()));
270 assert_eq!(trap.a11y_role(), Some(role));
271 let mut node = accesskit::Node::new(role);
272 trap.write_a11y_info(&mut node);
273 assert_eq!(node.label(), Some(name));
274 assert_eq!(node.description(), Some("Server settings"));
275 }
276 });
277 }
278}