gpui-base 0.7.0

Behavior, interaction, and infrastructure foundations for GPUI applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use gpui::{
    AnyElement, App, Div, ElementId, FocusHandle, InteractiveElement, Interactivity, IntoElement,
    KeyDownEvent, ParentElement, RenderOnce, Role, SharedString, Stateful,
    StatefulInteractiveElement, StyleRefinement, Styled, Window, accesskit, div,
    prelude::FluentBuilder as _,
};
use smallvec::SmallVec;

use crate::StyledExt as _;

/// Upper bound on tab-stop hops when wrapping focus back into the toolbar, so
/// a toolbar whose items all vanished from the tab order can never hang the
/// key handler. Mirrors `Root`'s focus-trap loop bound.
const MAX_FOCUS_ATTEMPTS: usize = 100;

/// An unstyled container that groups a set of controls and owns roving
/// keyboard focus among them.
///
/// This is the behavior primitive behind a styled toolbar. The container
/// exposes `Toolbar` semantics to assistive technology (`Role::Toolbar` with
/// an orientation) and moves focus between its focusable descendants with the
/// arrow keys, so applications do not have to reimplement the roving-focus
/// contract per toolbar. It works with any focusable children — buttons,
/// menu triggers, inputs — because traversal walks the rendered tab stops
/// and constrains them to this subtree, mirroring how `Root` constrains
/// focus-trap cycling.
///
/// Keyboard contract:
///
/// - Left and Right move focus to the previous or next focusable descendant,
///   wrapping around at either end (the same default as Base UI's `loopFocus`).
/// - When `disabled`, the arrow keys do nothing. Hosted controls must be
///   disabled by their owner; the flag only suppresses the toolbar's own
///   navigation.
///
/// The container is not itself a tab stop, so ordinary `Tab` traversal enters
/// and leaves the toolbar through its items, matching the ARIA toolbar
/// pattern.
///
/// An input hosted inside the toolbar keeps its own arrow-key behavior: text
/// inputs consume the arrow keys for caret movement before the toolbar sees
/// them. Place inputs at the trailing end of a horizontal toolbar, as the
/// Base UI Toolbar recommends.
#[derive(IntoElement)]
pub struct Toolbar {
    id: ElementId,
    base: Stateful<Div>,
    style: StyleRefinement,
    disabled: bool,
    children: SmallVec<[AnyElement; 4]>,
}

impl Toolbar {
    pub fn new(id: impl Into<ElementId>) -> Self {
        let id = id.into();
        Self {
            base: div().id(id.clone()),
            style: StyleRefinement::default(),
            disabled: false,
            children: SmallVec::new(),
            id,
        }
    }

    /// Disables the toolbar's own keyboard navigation. Hosted controls are
    /// not automatically disabled.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

fn step_focus(window: &mut Window, cx: &mut App, forward: bool) {
    if forward {
        window.focus_next(cx);
    } else {
        window.focus_prev(cx);
    }
}

/// Move focus to the next (or previous) focusable element inside `container`.
///
/// Traversal walks the window's tab stops like `Root`'s focus-trap cycling:
/// step once, and if the step landed outside the container, keep stepping
/// until the focus re-enters or comes back to where it started (in which
/// case the toolbar has no other focusable item and focus stays put).
fn move_focus(container: &FocusHandle, forward: bool, window: &mut Window, cx: &mut App) {
    let Some(start) = window.focused(cx) else {
        return;
    };

    step_focus(window, cx, forward);
    if container.contains_focused(window, cx)
        && window.focused(cx).is_some_and(|focused| focused != start)
    {
        return;
    }

    for _ in 0..MAX_FOCUS_ATTEMPTS {
        step_focus(window, cx, forward);
        if container.contains_focused(window, cx)
            && window.focused(cx).is_some_and(|focused| focused != start)
        {
            return;
        }
        if window.focused(cx).is_some_and(|focused| focused == start) {
            break;
        }
    }

    window.focus(&start, cx);
}

fn handle_key_down(
    disabled: bool,
    container: &FocusHandle,
    event: &KeyDownEvent,
    window: &mut Window,
    cx: &mut App,
) {
    if disabled {
        return;
    }

    let forward = match event.keystroke.key.as_str() {
        "left" => Some(false),
        "right" => Some(true),
        _ => None,
    };

    if let Some(forward) = forward {
        move_focus(container, forward, window, cx);
        cx.stop_propagation();
    }
}

impl Styled for Toolbar {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl ParentElement for Toolbar {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl InteractiveElement for Toolbar {
    fn interactivity(&mut self) -> &mut Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for Toolbar {}

impl RenderOnce for Toolbar {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let Self {
            base,
            style,
            disabled,
            children,
            ..
        } = self;

        // The handle must survive across frames so containment checks and the
        // key handler refer to the same dispatch-tree node; button.rs uses
        // the same keyed-state pattern for its own focus handle.
        let focus_handle = window
            .use_keyed_state(self.id.clone(), cx, |_, cx| {
                cx.focus_handle().tab_stop(false)
            })
            .read(cx)
            .clone();
        let key_handler = {
            let focus_handle = focus_handle.clone();
            move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
                handle_key_down(disabled, &focus_handle, event, window, cx);
            }
        };

        base.track_focus(&focus_handle)
            .role(Role::Toolbar)
            .aria_orientation(accesskit::Orientation::Horizontal)
            .on_key_down(key_handler)
            .children(children)
            .refine_style(&style)
    }
}

/// A semantic subgroup of items within a [`Toolbar`].
///
/// The group carries no behavior or styling of its own: the surrounding
/// toolbar's roving arrow-key focus traverses its items exactly like the
/// toolbar's direct children, because containment follows the element tree.
/// Its value is structure — assistive technology announces the group and its
/// accessible name, so a run of related controls reads as one unit ("Undo",
/// "Redo" inside a "History" group).
///
/// Unlike Base UI's `Toolbar.Group`, the group cannot disable its children.
/// That API propagates through React context into Base UI's own button
/// primitives; GPUI composition offers no equivalent for arbitrary children,
/// and the platform a11y layer exposes no disabled state for a container
/// node. Disabling the hosted controls is the group owner's job.
#[derive(IntoElement)]
pub struct ToolbarGroup {
    base: Stateful<Div>,
    style: StyleRefinement,
    label: Option<SharedString>,
    children: SmallVec<[AnyElement; 4]>,
}

impl ToolbarGroup {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            base: div().id(id.into()),
            style: StyleRefinement::default(),
            label: None,
            children: SmallVec::new(),
        }
    }

    /// Sets the accessible name announced for the group, e.g. "History".
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }
}

impl Styled for ToolbarGroup {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl ParentElement for ToolbarGroup {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl InteractiveElement for ToolbarGroup {
    fn interactivity(&mut self) -> &mut Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for ToolbarGroup {}

impl RenderOnce for ToolbarGroup {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        // A group is one inline segment of the bar, so its children flow
        // along the row and center on the bar's cross axis; the same neutral
        // geometry `Tab` applies. Spacing between items is the caller's
        // (matching the bar's own gap).
        self.base
            .flex()
            .items_center()
            .role(Role::Group)
            .when_some(self.label, |this, label| this.aria_label(label))
            .children(self.children)
            .refine_style(&self.style)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_toolbar_builder() {
        let toolbar = Toolbar::new("toolbar").disabled(true).child(div());

        assert!(toolbar.disabled);
        assert_eq!(toolbar.children.len(), 1);
    }

    #[test]
    fn test_toolbar_defaults() {
        let toolbar = Toolbar::new("toolbar");

        assert!(!toolbar.disabled);
        assert!(toolbar.children.is_empty());
    }

    #[test]
    fn test_toolbar_group_builder() {
        let group = ToolbarGroup::new("history-group")
            .label("History")
            .child(div())
            .child(div());

        assert_eq!(group.label.as_deref(), Some("History"));
        assert_eq!(group.children.len(), 2);
    }

    #[cfg(test)]
    mod behavior {
        use super::*;
        use gpui::{
            Context, Element as _, FocusHandle, Render, TestAppContext, VisualTestContext, canvas,
            px,
        };
        use std::sync::{Arc, Mutex};

        struct NavHarness {
            items: [FocusHandle; 3],
        }

        impl Render for NavHarness {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                let [first, second, third] = &self.items;
                Toolbar::new("nav-toolbar")
                    .child(div().id("first").size(px(20.)).track_focus(first))
                    .child(div().id("second").size(px(20.)).track_focus(second))
                    .child(div().id("third").size(px(20.)).track_focus(third))
            }
        }

        fn harness(cx: &mut TestAppContext) -> ([FocusHandle; 3], &mut VisualTestContext) {
            let (state, cx) = cx.add_window_view(move |window, cx| {
                let items = [
                    cx.focus_handle().tab_stop(true),
                    cx.focus_handle().tab_stop(true),
                    cx.focus_handle().tab_stop(true),
                ];
                items[0].focus(window, cx);
                NavHarness { items }
            });
            let items = state.read_with(cx, |harness, _| harness.items.clone());
            cx.update(|window, cx| {
                window.draw(cx).clear(cx);
            });
            (items, cx)
        }

        fn assert_focused(cx: &mut VisualTestContext, expected: &FocusHandle, label: &str) {
            cx.update(|window, _| {
                assert!(
                    expected.is_focused(window),
                    "expected {label} to be focused"
                );
            });
        }

        #[gpui::test]
        fn arrow_keys_rove_focus_across_items(cx: &mut gpui::TestAppContext) {
            let ([first, second, third], cx) = harness(cx);

            cx.simulate_keystrokes("right");
            assert_focused(cx, &second, "second");
            cx.simulate_keystrokes("right");
            assert_focused(cx, &third, "third");

            // Wrapping: past the last item, focus returns to the first.
            cx.simulate_keystrokes("right");
            assert_focused(cx, &first, "first (wrapped)");

            cx.simulate_keystrokes("left");
            assert_focused(cx, &third, "third (wrapped back)");
        }

        #[gpui::test]
        fn toolbar_with_a_single_item_keeps_focus_on_it(cx: &mut gpui::TestAppContext) {
            struct SingleHarness {
                item: FocusHandle,
            }

            impl Render for SingleHarness {
                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                    let item = &self.item;
                    Toolbar::new("single-toolbar")
                        .child(div().id("only").size(px(20.)).track_focus(item))
                }
            }

            let (state, cx) = cx.add_window_view(|window, cx| {
                let item = cx.focus_handle().tab_stop(true);
                item.focus(window, cx);
                SingleHarness { item }
            });
            let item = state.read_with(cx, |harness, _| harness.item.clone());
            cx.update(|window, cx| {
                window.draw(cx).clear(cx);
            });

            cx.simulate_keystrokes("right left right");
            assert_focused(cx, &item, "the only item");
        }

        #[gpui::test]
        fn group_exposes_group_role_and_accessible_name(cx: &mut gpui::TestAppContext) {
            type Captured = Arc<Mutex<Option<accesskit::Node>>>;

            struct Probe(Captured);

            impl Render for Probe {
                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                    let captured = self.0.clone();
                    canvas(
                        move |_, window, cx| {
                            let mut node = accesskit::Node::new(Role::Group);
                            ToolbarGroup::new("history")
                                .label("History")
                                .child(div().size(px(20.)))
                                .render(window, cx)
                                .into_element()
                                .write_a11y_info(&mut node);
                            *captured.lock().unwrap() = Some(node);
                        },
                        |_, _, _, _| {},
                    )
                }
            }

            let captured: Captured = Arc::new(Mutex::new(None));
            let result = captured.clone();
            let (_, cx) = cx.add_window_view(move |_, _| Probe(captured));
            cx.update(|window, cx| window.draw(cx).clear(cx));
            let node = result.lock().unwrap().take().unwrap();

            assert_eq!(node.role(), Role::Group);
            assert_eq!(node.label(), Some("History"));
        }

        #[gpui::test]
        fn disabled_toolbar_ignores_arrow_keys(cx: &mut gpui::TestAppContext) {
            struct DisabledHarness {
                items: [FocusHandle; 2],
            }

            impl Render for DisabledHarness {
                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                    let [first, second] = &self.items;
                    Toolbar::new("disabled-toolbar")
                        .disabled(true)
                        .child(div().id("first").size(px(20.)).track_focus(first))
                        .child(div().id("second").size(px(20.)).track_focus(second))
                }
            }

            let (state, cx) = cx.add_window_view(|window, cx| {
                let items = [
                    cx.focus_handle().tab_stop(true),
                    cx.focus_handle().tab_stop(true),
                ];
                items[0].focus(window, cx);
                DisabledHarness { items }
            });
            let items = state.read_with(cx, |harness, _| harness.items.clone());
            cx.update(|window, cx| {
                window.draw(cx).clear(cx);
            });

            cx.simulate_keystrokes("right");
            assert_focused(cx, &items[0], "first (disabled toolbar)");
        }
    }
}