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