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