Skip to main content

gpui_base/
tabs.rs

1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, Axis, Bounds, ClickEvent, Div, Element, ElementId, Entity, FocusHandle,
5    GlobalElementId, InspectorElementId, InteractiveElement, Interactivity, IntoElement,
6    KeyDownEvent, LayoutId, MouseButton, ParentElement, Pixels, Refineable as _, RenderOnce, Role,
7    SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, accesskit, div,
8    prelude::FluentBuilder as _, relative,
9};
10use smallvec::SmallVec;
11
12use crate::{
13    LayoutDirection, StateStyle, StyledExt as _, TestSupportExt as _,
14    a11y_disabled::A11yDisabledExt as _,
15};
16
17type ClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
18
19/// An unstyled tab that owns pointer activation and accessibility behavior.
20///
21/// Inside a [`Tabs`] list the tab also takes part in the list's roving
22/// keyboard focus: it is focusable, Enter and Space activate it like a click,
23/// and the list moves focus between its tabs with the arrow keys. A tab
24/// rendered outside a [`Tabs`] list is pointer-only, as before.
25#[derive(IntoElement)]
26pub struct Tab {
27    id: ElementId,
28    base: Div,
29    style: StyleRefinement,
30    semantic_styles: TabStyles,
31    selected: bool,
32    disabled: bool,
33    children: SmallVec<[AnyElement; 2]>,
34    on_click: Option<ClickHandler>,
35    accessibility_label: Option<SharedString>,
36    position_in_set: Option<usize>,
37    size_of_set: Option<usize>,
38}
39
40impl Tab {
41    pub fn new(id: impl Into<ElementId>) -> Self {
42        Self {
43            id: id.into(),
44            base: div(),
45            style: StyleRefinement::default(),
46            semantic_styles: TabStyles::default(),
47            selected: false,
48            disabled: false,
49            children: SmallVec::new(),
50            on_click: None,
51            accessibility_label: None,
52            position_in_set: None,
53            size_of_set: None,
54        }
55    }
56
57    /// Updates the element identity used when the tab is rendered.
58    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
59        self.id = id.into();
60        self
61    }
62
63    pub fn selected(mut self, selected: bool) -> Self {
64        self.selected = selected;
65        self
66    }
67
68    pub fn disabled(mut self, disabled: bool) -> Self {
69        self.disabled = disabled;
70        self
71    }
72
73    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
74        self.accessibility_label = Some(label.into());
75        self
76    }
77
78    /// Sets this tab's one-based position and the tab list's total size, so
79    /// assistive technology can announce "tab 2 of 5".
80    pub fn set_position(mut self, position: usize, size: usize) -> Self {
81        self.position_in_set = Some(position);
82        self.size_of_set = Some(size);
83        self
84    }
85
86    pub fn on_click(
87        mut self,
88        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
89    ) -> Self {
90        self.on_click = Some(Rc::new(handler));
91        self
92    }
93
94    pub fn styles(mut self, build: impl FnOnce(TabStyles) -> TabStyles) -> Self {
95        self.semantic_styles = build(self.semantic_styles);
96        self
97    }
98
99    fn resolved_style(&self) -> StyleRefinement {
100        crate::state_style::resolve_style(
101            &self.style,
102            [
103                self.selected.then_some(&self.semantic_styles.selected),
104                self.disabled.then_some(&self.semantic_styles.disabled),
105            ]
106            .into_iter()
107            .flatten(),
108        )
109    }
110}
111
112#[derive(Default)]
113pub struct TabStyles {
114    selected: StyleRefinement,
115    disabled: StyleRefinement,
116}
117
118impl TabStyles {
119    pub fn selected(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
120        self.selected
121            .refine(&build(StateStyle::default()).into_refinement());
122        self
123    }
124
125    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
126        self.disabled
127            .refine(&build(StateStyle::default()).into_refinement());
128        self
129    }
130}
131
132impl Styled for Tab {
133    fn style(&mut self) -> &mut StyleRefinement {
134        &mut self.style
135    }
136}
137
138impl ParentElement for Tab {
139    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
140        self.children.extend(elements);
141    }
142}
143
144impl InteractiveElement for Tab {
145    fn interactivity(&mut self) -> &mut Interactivity {
146        self.base.interactivity()
147    }
148}
149
150impl StatefulInteractiveElement for Tab {}
151
152impl RenderOnce for Tab {
153    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
154        let disabled = self.disabled;
155        let style = self.resolved_style();
156
157        // Join the enclosing tab list, if any. The handle is keyed by the
158        // tab's id so focus survives rerenders and controlled selection
159        // changes; the list decides which tab is the single tab stop.
160        let focus_handle = TabListScope::current().map(|registry| {
161            let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| {
162                cx.focus_handle().tab_stop(false)
163            });
164            let handle = state.read(cx).clone();
165            registry.borrow_mut().push(TabEntry {
166                state,
167                focus_handle: handle.clone(),
168                selected: self.selected,
169                disabled,
170            });
171            handle
172        });
173
174        let pointer_focus = focus_handle.clone();
175
176        self.base
177            .id(self.id)
178            .test_support()
179            .when_some(focus_handle, |this, handle| this.track_focus(&handle))
180            .role(Role::Tab)
181            // Match Button's neutral control geometry: a fixed-size tab
182            // centers ordinary content, while callers still own its size,
183            // spacing and visual treatment.
184            .flex()
185            .items_center()
186            .justify_center()
187            .line_height(relative(1.))
188            .when_some(self.accessibility_label, |this, label| {
189                this.aria_label(label)
190            })
191            .aria_selected(self.selected)
192            .when_some(self.position_in_set, |this, position| {
193                this.aria_position_in_set(position)
194            })
195            .when_some(self.size_of_set, |this, size| this.aria_size_of_set(size))
196            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
197                // Stopping propagation skips Div's automatic focus handler.
198                // A nested control may already have claimed the pointer focus.
199                if !disabled
200                    && !window.default_prevented()
201                    && let Some(handle) = pointer_focus.as_ref()
202                {
203                    window.focus(handle, cx);
204                    window.prevent_default();
205                }
206                cx.stop_propagation();
207            })
208            .when_some(
209                (!disabled).then_some(self.on_click).flatten(),
210                |this, on_click| {
211                    this.on_click(move |event, window, cx| on_click(event, window, cx))
212                },
213            )
214            .children(self.children)
215            .refine_style(&style)
216            .a11y_disabled(disabled)
217    }
218}
219
220/// An unstyled collection root for [`Tab`] elements.
221///
222/// Controlled selection and activation stay with the child tabs: the
223/// application decides which tab is selected and what activating one does.
224/// The root supplies the tab-list semantics and the keyboard contract of the
225/// ARIA tabs pattern (manual activation):
226///
227/// - The list is one tab stop. `Tab` enters it on the selected tab (the first
228///   enabled tab when none is selected) and leaves it with the next `Tab`.
229/// - Left and Right move focus to the previous or next enabled tab, wrapping
230///   at either end; in a right-to-left layout the next tab sits to the left.
231///   A vertical list ([`Tabs::axis`]) uses Up and Down instead.
232/// - Home and End move focus to the first and last enabled tab.
233/// - Enter and Space activate the focused tab, running its click handler.
234/// - Disabled tabs are skipped and never take focus from the keyboard.
235///
236/// Moving focus does not select: selection follows activation, so a
237/// controlled list never changes behind the application's back.
238#[derive(IntoElement)]
239pub struct Tabs {
240    id: ElementId,
241    base: gpui::Stateful<Div>,
242    style: StyleRefinement,
243    axis: Axis,
244    children: SmallVec<[AnyElement; 2]>,
245}
246
247impl Tabs {
248    pub fn new(id: impl Into<ElementId>) -> Self {
249        let id = id.into();
250        Self {
251            base: div().id(id.clone()),
252            style: StyleRefinement::default(),
253            axis: Axis::Horizontal,
254            children: SmallVec::new(),
255            id,
256        }
257    }
258
259    /// The direction the tabs run: horizontal (Left/Right, the default) or
260    /// vertical (Up/Down). Assistive technology hears the same orientation.
261    pub fn axis(mut self, axis: Axis) -> Self {
262        self.axis = axis;
263        self
264    }
265}
266
267/// A tab registered with its list during the list's layout, in tree order.
268struct TabEntry {
269    /// Holds the handle the tab tracks; its tab-stop flag is what the
270    /// window's tab order reads when the tab next paints.
271    state: Entity<FocusHandle>,
272    focus_handle: FocusHandle,
273    selected: bool,
274    disabled: bool,
275}
276
277type TabRegistry = Rc<RefCell<Vec<TabEntry>>>;
278
279thread_local! {
280    static TAB_LIST_STACK: RefCell<Vec<TabRegistry>> = const { RefCell::new(Vec::new()) };
281}
282
283/// Wraps a tab list so the tabs rendered while it lays out register with it.
284///
285/// `Tabs` holds its children as erased elements, and each `Tab` renders
286/// lazily while its parent lays out. Publishing the list's registry for the
287/// duration of that layout lets the tabs join it without a typed child API,
288/// so tabs nested in wrappers or lists still count, and the registry always
289/// matches what was rendered last.
290struct TabListScope {
291    registry: TabRegistry,
292    inner: AnyElement,
293}
294
295impl TabListScope {
296    fn current() -> Option<TabRegistry> {
297        TAB_LIST_STACK.with(|stack| stack.borrow().last().cloned())
298    }
299}
300
301impl Element for TabListScope {
302    type RequestLayoutState = ();
303    type PrepaintState = ();
304
305    fn id(&self) -> Option<ElementId> {
306        None
307    }
308
309    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
310        None
311    }
312
313    fn request_layout(
314        &mut self,
315        _: Option<&GlobalElementId>,
316        _: Option<&InspectorElementId>,
317        window: &mut Window,
318        cx: &mut App,
319    ) -> (LayoutId, ()) {
320        self.registry.borrow_mut().clear();
321        TAB_LIST_STACK.with(|stack| stack.borrow_mut().push(self.registry.clone()));
322        let layout_id = self.inner.request_layout(window, cx);
323        TAB_LIST_STACK.with(|stack| stack.borrow_mut().pop());
324        (layout_id, ())
325    }
326
327    fn prepaint(
328        &mut self,
329        _: Option<&GlobalElementId>,
330        _: Option<&InspectorElementId>,
331        _: Bounds<Pixels>,
332        _: &mut (),
333        window: &mut Window,
334        cx: &mut App,
335    ) {
336        sync_tab_stops(&self.registry.borrow(), window, cx);
337        self.inner.prepaint(window, cx);
338    }
339
340    fn paint(
341        &mut self,
342        _: Option<&GlobalElementId>,
343        _: Option<&InspectorElementId>,
344        _: Bounds<Pixels>,
345        _: &mut (),
346        _: &mut (),
347        window: &mut Window,
348        cx: &mut App,
349    ) {
350        self.inner.paint(window, cx);
351    }
352}
353
354/// Make exactly one enabled tab the list's tab stop: the focused tab while
355/// the list has focus, otherwise the selected tab, otherwise the first.
356fn sync_tab_stops(entries: &[TabEntry], window: &mut Window, cx: &mut App) {
357    let enabled = |entry: &&TabEntry| !entry.disabled;
358    let stop = entries
359        .iter()
360        .filter(enabled)
361        .find(|entry| entry.focus_handle.is_focused(window))
362        .or_else(|| entries.iter().filter(enabled).find(|entry| entry.selected))
363        .or_else(|| entries.iter().find(|entry| !entry.disabled))
364        .map(|entry| entry.focus_handle.clone());
365
366    let mut changed = false;
367    for entry in entries {
368        let is_stop = stop.as_ref() == Some(&entry.focus_handle);
369        entry.state.update(cx, |handle, _| {
370            if handle.tab_stop != is_stop {
371                *handle = handle.clone().tab_stop(is_stop);
372                changed = true;
373            }
374        });
375    }
376    // Tabs pick up their new flag when they next render.
377    if changed {
378        window.refresh();
379    }
380}
381
382enum Step {
383    Next,
384    Previous,
385    First,
386    Last,
387}
388
389fn handle_key_down(
390    axis: Axis,
391    registry: &TabRegistry,
392    event: &KeyDownEvent,
393    window: &mut Window,
394    cx: &mut App,
395) {
396    let modifiers = &event.keystroke.modifiers;
397    if modifiers.modified() {
398        return;
399    }
400    let rtl = LayoutDirection::global(cx).is_rtl();
401    let step = match (axis, event.keystroke.key.as_str()) {
402        (Axis::Horizontal, "left") if rtl => Step::Next,
403        (Axis::Horizontal, "left") => Step::Previous,
404        (Axis::Horizontal, "right") if rtl => Step::Previous,
405        (Axis::Horizontal, "right") => Step::Next,
406        (Axis::Vertical, "up") => Step::Previous,
407        (Axis::Vertical, "down") => Step::Next,
408        (_, "home") => Step::First,
409        (_, "end") => Step::Last,
410        _ => return,
411    };
412
413    let target = {
414        let entries = registry.borrow();
415        let Some(current) = entries
416            .iter()
417            .position(|entry| entry.focus_handle.is_focused(window))
418        else {
419            return;
420        };
421        let enabled: Vec<usize> = (0..entries.len())
422            .filter(|&ix| !entries[ix].disabled)
423            .collect();
424        let (Some(&first), Some(&last)) = (enabled.first(), enabled.last()) else {
425            return;
426        };
427        let target = match step {
428            Step::First => first,
429            Step::Last => last,
430            Step::Next => enabled
431                .iter()
432                .copied()
433                .find(|&ix| ix > current)
434                .unwrap_or(first),
435            Step::Previous => enabled
436                .iter()
437                .rev()
438                .copied()
439                .find(|&ix| ix < current)
440                .unwrap_or(last),
441        };
442        entries[target].focus_handle.clone()
443    };
444
445    window.focus(&target, cx);
446    sync_tab_stops(&registry.borrow(), window, cx);
447    cx.stop_propagation();
448}
449
450impl Styled for Tabs {
451    fn style(&mut self) -> &mut StyleRefinement {
452        &mut self.style
453    }
454}
455
456impl ParentElement for Tabs {
457    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
458        self.children.extend(elements);
459    }
460}
461
462impl InteractiveElement for Tabs {
463    fn interactivity(&mut self) -> &mut Interactivity {
464        self.base.interactivity()
465    }
466}
467
468impl StatefulInteractiveElement for Tabs {}
469
470impl RenderOnce for Tabs {
471    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
472        let Self {
473            id,
474            base,
475            style,
476            axis,
477            children,
478        } = self;
479
480        // The registry outlives the frame so the key handler sees the tabs
481        // rendered last, in the same order the user sees them.
482        let registry = window
483            .use_keyed_state(id, cx, |_, _| TabRegistry::default())
484            .read(cx)
485            .clone();
486        let key_handler = {
487            let registry = registry.clone();
488            move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
489                handle_key_down(axis, &registry, event, window, cx);
490            }
491        };
492
493        TabListScope {
494            registry,
495            inner: tab_list(base, axis)
496                .on_key_down(key_handler)
497                .children(children)
498                .refine_style(&style)
499                .into_any_element(),
500        }
501    }
502}
503
504/// The tab list's own semantics: its role and the orientation that tells
505/// assistive technology which arrow keys move between the tabs.
506fn tab_list(base: gpui::Stateful<Div>, axis: Axis) -> gpui::Stateful<Div> {
507    base.role(Role::TabList).aria_orientation(match axis {
508        Axis::Horizontal => accesskit::Orientation::Horizontal,
509        Axis::Vertical => accesskit::Orientation::Vertical,
510    })
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516    use crate::ElementExt as _;
517    use std::{
518        cell::Cell,
519        rc::Rc,
520        sync::{Arc, Mutex},
521    };
522
523    use gpui::{
524        Context, Modifiers, Render, Role, VisualTestContext, accesskit, canvas, hsla, point, px,
525    };
526
527    struct TabHarness {
528        disabled: bool,
529        clicks: Rc<Cell<usize>>,
530    }
531
532    impl Render for TabHarness {
533        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
534            let clicks = self.clicks.clone();
535            Tab::new("tab")
536                .disabled(self.disabled)
537                .size(px(100.))
538                .on_click(move |_, _, _| clicks.set(clicks.get() + 1))
539        }
540    }
541
542    fn harness(
543        cx: &mut gpui::TestAppContext,
544        disabled: bool,
545    ) -> (&mut VisualTestContext, Rc<Cell<usize>>) {
546        let clicks = Rc::new(Cell::new(0));
547        let (_, cx) = cx.add_window_view({
548            let clicks = clicks.clone();
549            move |_, _| TabHarness { disabled, clicks }
550        });
551        cx.update(|window, cx| window.draw(cx).clear(cx));
552        (cx, clicks)
553    }
554
555    #[gpui::test]
556    fn pointer_activation_and_disabled_gating_match_tabs(cx: &mut gpui::TestAppContext) {
557        let (cx, clicks) = harness(cx, false);
558        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
559        assert_eq!(clicks.get(), 1);
560
561        let (cx, clicks) = harness(cx, true);
562        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
563        assert_eq!(clicks.get(), 0);
564    }
565
566    #[gpui::test]
567    fn fixed_height_tab_centers_ordinary_child_geometry(cx: &mut gpui::TestAppContext) {
568        type Captured = Arc<
569            Mutex<(
570                Option<gpui::Bounds<gpui::Pixels>>,
571                Option<gpui::Bounds<gpui::Pixels>>,
572            )>,
573        >;
574
575        struct AlignmentProbe(Captured);
576
577        impl Render for AlignmentProbe {
578            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
579                let root_capture = self.0.clone();
580                let child_capture = self.0.clone();
581                Tab::new("alignment-tab")
582                    .w(px(120.))
583                    .h(px(40.))
584                    .child(
585                        div()
586                            .w(px(48.))
587                            .h(px(12.))
588                            .on_prepaint(move |bounds, _, _| {
589                                child_capture.lock().unwrap().1 = Some(bounds);
590                            }),
591                    )
592                    .on_prepaint(move |bounds, _, _| {
593                        root_capture.lock().unwrap().0 = Some(bounds);
594                    })
595            }
596        }
597
598        let captured = Arc::new(Mutex::new((None, None)));
599        let (_, context) = cx.add_window_view({
600            let captured = captured.clone();
601            move |_, _| AlignmentProbe(captured)
602        });
603        context.update(|window, cx| window.draw(cx).clear(cx));
604
605        let (root, child) = *captured.lock().unwrap();
606        assert_eq!(
607            child.expect("child bounds").center(),
608            root.expect("tab bounds").center()
609        );
610    }
611
612    #[gpui::test]
613    fn exposes_tab_accessibility_state(cx: &mut gpui::TestAppContext) {
614        type Captured = Arc<Mutex<Option<(accesskit::Node, accesskit::Node)>>>;
615
616        struct Probe(Captured);
617
618        impl Render for Probe {
619            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
620                let captured = self.0.clone();
621                canvas(
622                    move |_, window, cx| {
623                        let mut info = |tab: Tab| {
624                            let mut node = accesskit::Node::new(Role::Tab);
625                            tab.render(window, cx)
626                                .into_element()
627                                .write_a11y_info(&mut node);
628                            node
629                        };
630                        let selected = info(
631                            Tab::new("selected")
632                                .selected(true)
633                                .accessibility_label("Account")
634                                .on_click(|_, _, _| {}),
635                        );
636                        let disabled =
637                            info(Tab::new("disabled").disabled(true).on_click(|_, _, _| {}));
638                        *captured.lock().unwrap() = Some((selected, disabled));
639                    },
640                    |_, _, _, _| {},
641                )
642            }
643        }
644
645        let captured: Captured = Arc::new(Mutex::new(None));
646        let result = captured.clone();
647        let (_, cx) = cx.add_window_view(move |_, _| Probe(captured));
648        cx.update(|window, cx| window.draw(cx).clear(cx));
649        let (selected, disabled) = result.lock().unwrap().take().unwrap();
650
651        assert_eq!(selected.role(), Role::Tab);
652        assert_eq!(selected.label(), Some("Account"));
653        assert_eq!(selected.is_selected(), Some(true));
654        assert!(selected.supports_action(accesskit::Action::Click));
655        assert!(!disabled.supports_action(accesskit::Action::Click));
656    }
657
658    #[gpui::test]
659    fn semantic_styles_preserve_the_legacy_state_priority(_cx: &mut gpui::TestAppContext) {
660        let expected = hsla(0.3, 0.4, 0.5, 1.0);
661        let mut tab = Tab::new("tab")
662            .selected(true)
663            .disabled(true)
664            .styles(|styles| {
665                styles
666                    .selected(|style| style.opacity(0.8))
667                    .disabled(|style| style.opacity(0.5))
668            })
669            .opacity(0.9);
670
671        assert_eq!(tab.resolved_style().opacity, Some(0.5));
672        tab.style().background = Some(expected.into());
673        assert_eq!(tab.resolved_style().background, Some(expected.into()));
674    }
675
676    mod keyboard {
677        use super::*;
678        use gpui::{FocusHandle, TestAppContext};
679
680        /// Four tabs, the third disabled, between two plain focus stops.
681        struct KeyHarness {
682            axis: Axis,
683            selected: usize,
684            activated: Rc<RefCell<Vec<usize>>>,
685            before: FocusHandle,
686            after: FocusHandle,
687        }
688
689        impl Render for KeyHarness {
690            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
691                let tabs = (0..4).map(|ix| {
692                    let activated = self.activated.clone();
693                    let entity = cx.entity();
694                    Tab::new(("tab", ix))
695                        .size(px(20.))
696                        .selected(self.selected == ix)
697                        .disabled(ix == 2)
698                        .on_click(move |_, _, cx| {
699                            activated.borrow_mut().push(ix);
700                            entity.update(cx, |this, cx| {
701                                this.selected = ix;
702                                cx.notify();
703                            });
704                        })
705                });
706                div()
707                    .child(div().id("before").size(px(10.)).track_focus(&self.before))
708                    .child(Tabs::new("tabs").axis(self.axis).children(tabs))
709                    .child(div().id("after").size(px(10.)).track_focus(&self.after))
710            }
711        }
712
713        struct Fixture<'a> {
714            cx: &'a mut VisualTestContext,
715            activated: Rc<RefCell<Vec<usize>>>,
716            after: FocusHandle,
717        }
718
719        impl Fixture<'_> {
720            /// A full key press: GPUI activates a focused element on release.
721            fn press(&mut self, key: &'static str) {
722                self.cx.simulate_keystrokes(key);
723                self.cx.simulate_event(gpui::KeyUpEvent {
724                    keystroke: gpui::Keystroke::parse(key).unwrap(),
725                });
726            }
727
728            /// Activate whichever tab has focus and report its index.
729            fn focused_tab(&mut self) -> Option<usize> {
730                self.activated.borrow_mut().clear();
731                self.press("enter");
732                self.activated.borrow().last().copied()
733            }
734        }
735
736        fn fixture(cx: &mut TestAppContext, axis: Axis, selected: usize) -> Fixture<'_> {
737            let activated: Rc<RefCell<Vec<usize>>> = Rc::default();
738            let (view, cx) = cx.add_window_view({
739                let activated = activated.clone();
740                move |window, cx| {
741                    let before = cx.focus_handle().tab_stop(true);
742                    before.focus(window, cx);
743                    KeyHarness {
744                        axis,
745                        selected,
746                        activated,
747                        before,
748                        after: cx.focus_handle().tab_stop(true),
749                    }
750                }
751            });
752            let after = view.read_with(cx, |this, _| this.after.clone());
753            // The second frame applies the roving tab stop chosen by the first.
754            cx.update(|window, cx| window.draw(cx).clear(cx));
755            cx.update(|window, cx| window.draw(cx).clear(cx));
756            // Enter the list from the stop before it. `Tab` itself is bound by
757            // the window root; moving to the next tab stop is what it does.
758            cx.update(|window, cx| window.focus_next(cx));
759            Fixture {
760                cx,
761                activated,
762                after,
763            }
764        }
765
766        #[gpui::test]
767        fn tab_enters_on_the_selected_tab_and_leaves_with_one_press(cx: &mut TestAppContext) {
768            let mut f = fixture(cx, Axis::Horizontal, 1);
769            assert_eq!(f.focused_tab(), Some(1));
770
771            // Moving inside the list keeps it a single stop.
772            f.cx.simulate_keystrokes("right");
773            f.cx.update(|window, cx| {
774                window.draw(cx).clear(cx);
775                window.focus_next(cx);
776            });
777            f.cx.update(|window, _| assert!(f.after.is_focused(window)));
778        }
779
780        #[gpui::test]
781        fn without_a_selection_the_first_enabled_tab_is_the_stop(cx: &mut TestAppContext) {
782            let mut f = fixture(cx, Axis::Horizontal, usize::MAX);
783            assert_eq!(f.focused_tab(), Some(0));
784        }
785
786        #[gpui::test]
787        fn arrows_move_focus_skip_disabled_tabs_and_wrap(cx: &mut TestAppContext) {
788            let mut f = fixture(cx, Axis::Horizontal, 0);
789
790            // Moving focus alone never activates a tab.
791            f.cx.simulate_keystrokes("right");
792            assert!(f.activated.borrow().is_empty());
793            assert_eq!(f.focused_tab(), Some(1));
794
795            f.cx.simulate_keystrokes("right");
796            assert_eq!(f.focused_tab(), Some(3), "the disabled tab is skipped");
797            f.cx.simulate_keystrokes("right");
798            assert_eq!(f.focused_tab(), Some(0), "wraps past the last tab");
799            f.cx.simulate_keystrokes("left");
800            assert_eq!(f.focused_tab(), Some(3), "wraps before the first tab");
801            f.cx.simulate_keystrokes("left");
802            assert_eq!(f.focused_tab(), Some(1), "skips the disabled tab back");
803
804            // A horizontal list ignores the vertical arrows.
805            f.cx.simulate_keystrokes("down");
806            assert_eq!(f.focused_tab(), Some(1));
807        }
808
809        #[gpui::test]
810        fn home_and_end_reach_the_outer_enabled_tabs(cx: &mut TestAppContext) {
811            let mut f = fixture(cx, Axis::Horizontal, 1);
812            f.cx.simulate_keystrokes("end");
813            assert_eq!(f.focused_tab(), Some(3));
814            f.cx.simulate_keystrokes("home");
815            assert_eq!(f.focused_tab(), Some(0));
816        }
817
818        #[gpui::test]
819        fn space_activates_and_focus_survives_the_selection_rerender(cx: &mut TestAppContext) {
820            let mut f = fixture(cx, Axis::Horizontal, 0);
821            f.cx.simulate_keystrokes("right");
822            f.press("space");
823            assert_eq!(*f.activated.borrow(), vec![1]);
824
825            // The click handler selected tab 1 and rerendered the list; focus
826            // stays put and keeps roving from there.
827            f.cx.run_until_parked();
828            f.cx.simulate_keystrokes("right");
829            assert_eq!(f.focused_tab(), Some(3));
830        }
831
832        #[gpui::test]
833        fn a_vertical_list_roves_with_up_and_down(cx: &mut TestAppContext) {
834            let mut f = fixture(cx, Axis::Vertical, 0);
835            f.cx.simulate_keystrokes("right");
836            assert_eq!(f.focused_tab(), Some(0), "Left/Right do not move a column");
837            f.cx.simulate_keystrokes("down");
838            assert_eq!(f.focused_tab(), Some(1));
839            f.cx.simulate_keystrokes("up up");
840            assert_eq!(f.focused_tab(), Some(3));
841        }
842
843        #[gpui::test]
844        fn horizontal_arrows_follow_the_global_rtl_direction(cx: &mut TestAppContext) {
845            let mut f = fixture(cx, Axis::Horizontal, 0);
846            f.cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
847            f.cx.simulate_keystrokes("left");
848            assert_eq!(f.focused_tab(), Some(1), "the next tab sits to the left");
849            f.cx.simulate_keystrokes("right");
850            assert_eq!(f.focused_tab(), Some(0));
851        }
852    }
853
854    #[test]
855    fn tabs_expose_tab_list_role_and_orientation() {
856        for (axis, orientation) in [
857            (Axis::Horizontal, accesskit::Orientation::Horizontal),
858            (Axis::Vertical, accesskit::Orientation::Vertical),
859        ] {
860            let list = tab_list(div().id("tabs"), axis);
861            let mut node = accesskit::Node::new(Role::TabList);
862            list.write_a11y_info(&mut node);
863            assert_eq!(list.a11y_role(), Some(Role::TabList));
864            assert_eq!(node.orientation(), Some(orientation));
865        }
866    }
867}