Skip to main content

ui/
focus.rs

1//! Keyboard focus traversal — `tab` and `shift-tab` between controls.
2//!
3//! gpui has all the machinery and none of it is on by default: a focus handle
4//! carries a `tab_index` and a `tab_stop` flag, `.track_focus` registers the
5//! handle for the frame, and [`Window::focus_next`] walks the order — but
6//! `tab_stop` starts `false` and gpui binds no keys. This module turns it on.
7//!
8//! # Order is paint order
9//!
10//! gpui sorts tab stops by their `tab_index` path and then by insertion, so
11//! leaving every index at 0 yields the order the controls are painted in.
12//! Nothing has to be numbered by hand, and inserting a control in the middle of
13//! a form does not renumber the rest — which is the failure mode that makes
14//! HTML `tabindex` a liability.
15//!
16//! # Where the handle lives
17//!
18//! Most of this crate is `fn(&Theme, ..) -> Div`: stateless, with the app
19//! owning whether a checkbox is checked. Focus is more of that state, so the
20//! app owns the handle too and [`focusable`] wires it up. Giving every widget a
21//! handle of its own would mean giving every widget an identity and a lifetime,
22//! which is the entity machinery [`crate::input::TextField`] needs and a
23//! checkbox does not.
24//!
25//! ```ignore
26//! ui::focus::init(cx);                    // once, at startup
27//!
28//! // ..and on the root view, so `tab` works wherever focus currently is:
29//! focus::traversal(div().track_focus(&self.focus_handle))
30//!     .child(focus::focusable(&theme, &self.ok_focus, popover::button(&theme, "OK", "ok")))
31//! ```
32
33use gpui::{App, Div, FocusHandle, KeyBinding, Window, actions, prelude::*};
34
35use theme::Theme;
36
37actions!(
38    bezel_focus,
39    [FocusNext, FocusPrev, Activate, Decrement, Increment]
40);
41
42/// Claimed by every [`focusable`] control, so `enter` and `space` mean "press
43/// this" only where something is actually focused.
44///
45/// Scoping matters here: [`crate::palette`] and [`crate::combobox`] both bind
46/// `enter` for their own lists, and a multi-line field binds it to insert a
47/// newline. A focused control sits deeper in the focus path than any of them,
48/// so it wins `enter` while focused and gives it straight back afterwards.
49pub const CONTROL_KEY_CONTEXT: &str = "Control";
50
51/// Bind `tab` and `shift-tab`. Call once at startup.
52///
53/// Optional, like [`crate::input::init`] — the actions are public, so an app
54/// that wants different keys binds those instead. The bindings are global
55/// rather than scoped to a context: traversal is a property of the window, not
56/// of whatever happens to be focused.
57///
58/// Nothing in this crate claims `tab` for itself, deliberately. A multi-line
59/// field could reasonably insert one, but trapping `tab` inside a text box is
60/// the classic way to make a form impossible to leave by keyboard.
61///
62/// [`Decrement`]/[`Increment`] on `left`/`right` are for a control that holds a
63/// *value* rather than a press — [`slider`](crate::widgets::Controls::slider)
64/// is the one. They
65/// carry no step: only the caller knows the range, and a library that picked
66/// one would be picking it for a percentage and a font size alike.
67pub fn init(cx: &mut App) {
68    cx.bind_keys([
69        KeyBinding::new("tab", FocusNext, None),
70        KeyBinding::new("shift-tab", FocusPrev, None),
71        // Both, because both are standard and they disagree by platform: the
72        // web and Windows press a focused button with `space`, macOS with
73        // `enter`. Scoped to a focused control, neither is ambiguous.
74        KeyBinding::new("enter", Activate, Some(CONTROL_KEY_CONTEXT)),
75        KeyBinding::new("space", Activate, Some(CONTROL_KEY_CONTEXT)),
76        KeyBinding::new("left", Decrement, Some(CONTROL_KEY_CONTEXT)),
77        KeyBinding::new("right", Increment, Some(CONTROL_KEY_CONTEXT)),
78    ]);
79}
80
81/// Attach the traversal handlers, normally to the app's root element.
82///
83/// It has to live on an element rather than on the app because moving focus
84/// needs a [`Window`], and an app-level action handler only gets an [`App`].
85pub fn traversal(el: Div) -> Div {
86    el.on_action(|_: &FocusNext, window: &mut Window, cx: &mut App| window.focus_next(cx))
87        .on_action(|_: &FocusPrev, window: &mut Window, cx: &mut App| window.focus_prev(cx))
88}
89
90/// Put a stateless control into the tab order, show when it holds focus, and
91/// let `enter`/`space` press it.
92///
93/// The ring is the same one [`crate::input::TextField`] paints — the border in
94/// [`Theme::caret`] — so a focused button and a focused field read alike.
95///
96/// Keyboard focus only, like CSS `:focus-visible`. A control also takes focus
97/// when clicked, and a ring that landed on it there would outline a slider for
98/// the whole drag — the pointer already says which control is being used.
99///
100/// It lands on the control's *own* border, which is why every control in
101/// [`crate::widgets`] carries one even where it paints nothing: gpui sizes
102/// border-box, so a border that only appeared on focus would move the content
103/// under it by a pixel. A ring wrapped *around* the control instead would cost
104/// every one of them a radius parameter, and would prise a focused tab off the
105/// hairline its underline has to overlap.
106///
107/// Pressing dispatches [`Activate`], which the caller handles beside its
108/// `on_click`. Deliberately not folded into one callback: a control that is
109/// pressed by mouse and by key is doing the same thing, but only the caller
110/// knows what that is, and a keyboard-only affordance that silently diverges
111/// from the click is worse than none.
112pub fn focusable(theme: &Theme, handle: &FocusHandle, el: Div) -> Div {
113    // `tab_stop` writes through to the shared focus entry, so re-asserting it
114    // every render is free and keeps the flag next to the element that wants
115    // it, rather than at whatever distant place the handle was constructed.
116    let handle = handle.clone().tab_stop(true);
117    el.key_context(CONTROL_KEY_CONTEXT)
118        .track_focus(&handle)
119        .focus_visible(|style| style.border_color(theme.caret))
120}