Skip to main content

gpui_deck/
focus_trap.rs

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
8/// Initialize the focus trap manager as a global
9pub fn init(cx: &mut App) {
10    cx.set_global(FocusTrapManager::new());
11}
12
13/// An extension trait to add `focus_trap` functionality to interactive elements.
14pub trait FocusTrapElement: InteractiveElement + Sized {
15    /// Enable focus trap for this element.
16    ///
17    /// When enabled, focus will automatically cycle within this container
18    /// instead of escaping to parent elements. This is useful for modal dialogs,
19    /// sheets, and other overlay components.
20    ///
21    /// The focus trap works by:
22    /// 1. Registering this element as a focus trap container
23    /// 2. When Tab/Shift-Tab is pressed, Root intercepts the event
24    /// 3. If focus would leave the container, it cycles back to the beginning/end
25    ///
26    /// # Example
27    ///
28    /// ```no_run
29    /// use gpui::{FocusHandle, IntoElement, ParentElement as _};
30    /// use gpui_deck::{Button, FocusTrapElement as _, v_flex};
31    ///
32    /// fn content(container_focus_handle: &FocusHandle) -> impl IntoElement {
33    ///     v_flex()
34    ///         .child(Button::new("btn1").accessibility_label("Button 1").child("Button 1"))
35    ///         .child(Button::new("btn2").accessibility_label("Button 2").child("Button 2"))
36    ///         .child(Button::new("btn3").accessibility_label("Button 3").child("Button 3"))
37    ///         .focus_trap("trap1", container_focus_handle)
38    /// }
39    /// // Pressing Tab will cycle: btn1 -> btn2 -> btn3 -> btn1
40    /// // Focus will not escape to elements outside this container
41    /// ```
42    ///
43    /// See also: <https://github.com/focus-trap/focus-trap-react>
44    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
57/// Global state to manage all focus trap containers
58pub(crate) struct FocusTrapManager {
59    /// Map from container element ID to its focus trap info
60    traps: HashMap<GlobalElementId, WeakFocusHandle>,
61}
62
63impl Global for FocusTrapManager {}
64
65impl FocusTrapManager {
66    /// Create a new focus trap manager
67    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    /// Register a focus trap container
82    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    /// Find which focus trap contains the currently focused element
89    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                // A child scope must confine navigation even if its ancestor
102                // was registered first (or visited first by the HashMap).
103                // Use the rendered focus tree so closing and reopening a
104                // retained scope cannot leave registration order in control.
105                active = Some(container);
106            }
107        }
108        active
109    }
110
111    /// Cleanup any traps with dropped handles
112    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
123/// A wrapper element that implements focus trap behavior.
124///
125/// This element wraps another element and registers it as a focus trap container.
126/// Focus will automatically cycle within the container when Tab/Shift-Tab is pressed.
127pub 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        // Register this focus trap with the manager
214        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/// Returns the focus handle for the active focus trap, if any.
255#[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                // GPUI calls hooks on the outer Element. An observed inner
281                // div alone can claim these semantics while the real element
282                // silently drops them. Check the exact native boundary.
283                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}