1use gpui::{
6 AnyElement, App, Axis, Context, ElementId, Entity, EntityId, EventEmitter, FocusHandle,
7 InteractiveElement, Interactivity, IntoElement, KeyBinding, MouseButton, ParentElement,
8 RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
9 Subscription, Window, accesskit, div, prelude::FluentBuilder as _,
10};
11
12use crate::{
13 StyledExt as _, TestSupportExt as _,
14 a11y_disabled::A11yDisabledExt as _,
15 actions::{SelectDown, SelectFirst, SelectLast, SelectLeft, SelectRight, SelectUp},
16};
17
18const CONTEXT: &str = "TabList";
19
20pub(crate) fn init(cx: &mut App) {
21 cx.bind_keys([
22 KeyBinding::new("left", SelectLeft, Some("TabList && axis == horizontal")),
23 KeyBinding::new("right", SelectRight, Some("TabList && axis == horizontal")),
24 KeyBinding::new("up", SelectUp, Some("TabList && axis == vertical")),
25 KeyBinding::new("down", SelectDown, Some("TabList && axis == vertical")),
26 KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
27 KeyBinding::new("end", SelectLast, Some(CONTEXT)),
28 ]);
29}
30
31#[derive(Clone, Debug)]
33pub struct TabItem {
34 value: SharedString,
35 label: SharedString,
36 disabled: bool,
37}
38
39impl TabItem {
40 pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
41 Self {
42 value: value.into(),
43 label: label.into(),
44 disabled: false,
45 }
46 }
47
48 pub fn disabled(mut self, disabled: bool) -> Self {
49 self.disabled = disabled;
50 self
51 }
52
53 pub fn value(&self) -> &SharedString {
54 &self.value
55 }
56
57 pub fn label(&self) -> &SharedString {
58 &self.label
59 }
60
61 pub fn is_disabled(&self) -> bool {
62 self.disabled
63 }
64}
65
66#[derive(Clone, Debug, Eq, PartialEq)]
68pub enum TabsEvent {
69 Change(SharedString),
70}
71
72pub struct TabsState {
80 items: Vec<TabItem>,
81 selected: Option<usize>,
82 cursor: Option<usize>,
83 manual_activation: bool,
84 tab_focus: Vec<FocusHandle>,
85 panel_focus: Vec<FocusHandle>,
86 focus_subscriptions: Vec<Subscription>,
87}
88
89impl TabsState {
90 pub fn new(items: impl IntoIterator<Item = TabItem>, cx: &mut Context<Self>) -> Self {
91 let items: Vec<_> = items.into_iter().collect();
92 for (ix, item) in items.iter().enumerate() {
93 assert!(
94 items[..ix].iter().all(|other| other.value != item.value),
95 "TabItem values must be unique"
96 );
97 }
98 let selected = items.iter().position(|item| !item.disabled);
99 let tab_focus = items.iter().map(|_| cx.focus_handle()).collect();
100 let panel_focus = items.iter().map(|_| cx.focus_handle()).collect();
101 Self {
102 items,
103 selected,
104 cursor: selected,
105 manual_activation: false,
106 tab_focus,
107 panel_focus,
108 focus_subscriptions: Vec::new(),
109 }
110 }
111
112 pub fn manual_activation(mut self) -> Self {
119 self.manual_activation = true;
120 self
121 }
122
123 pub fn default_value(mut self, value: impl AsRef<str>) -> Self {
128 self.selected = Some(
129 self.items
130 .iter()
131 .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled)
132 .expect("TabsState default_value must identify an enabled TabItem"),
133 );
134 self.cursor = self.selected;
135 self
136 }
137
138 pub fn items(&self) -> &[TabItem] {
139 &self.items
140 }
141
142 pub fn selected_index(&self) -> Option<usize> {
143 self.selected
144 }
145
146 pub fn selected_item(&self) -> Option<&TabItem> {
147 self.selected.map(|index| &self.items[index])
148 }
149
150 pub fn select_value(
157 &mut self,
158 value: impl AsRef<str>,
159 window: &mut Window,
160 cx: &mut Context<Self>,
161 ) -> bool {
162 let Some(index) = self
163 .items
164 .iter()
165 .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled)
166 else {
167 return false;
168 };
169 if self.selected == Some(index) {
170 return false;
171 }
172 self.selected = Some(index);
173 cx.emit(TabsEvent::Change(self.items[index].value.clone()));
174 cx.notify();
175 window.refresh();
176 true
177 }
178
179 pub fn tab_focus_handle(&self, index: usize) -> &FocusHandle {
181 &self.tab_focus[index]
182 }
183
184 pub fn panel_focus_handle(&self, index: usize) -> &FocusHandle {
186 &self.panel_focus[index]
187 }
188
189 fn bind_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
190 if !self.focus_subscriptions.is_empty() {
191 return;
192 }
193 self.focus_subscriptions = self
194 .tab_focus
195 .iter()
196 .enumerate()
197 .map(|(index, focus)| {
198 cx.on_focus(focus, window, move |_, window, cx| {
199 cx.defer_in(window, move |state, window, cx| {
202 if state.tab_focus[index].is_focused(window) {
203 state.focus_tab(index, window, cx);
204 }
205 });
206 })
207 })
208 .collect();
209 }
210
211 fn focus_tab(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
212 if !self.manual_activation {
213 self.select(index, window, cx);
214 return;
215 }
216 if self.items[index].disabled {
217 return;
218 }
219 self.tab_focus[index].focus(window, cx);
220 if self.cursor != Some(index) {
221 self.cursor = Some(index);
222 cx.notify();
223 window.refresh();
224 }
225 }
226
227 fn select(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
228 if self.items[index].disabled {
229 return;
230 }
231 self.tab_focus[index].focus(window, cx);
232 let cursor_changed = self.cursor != Some(index);
233 self.cursor = Some(index);
234 if self.selected == Some(index) {
235 if cursor_changed {
236 cx.notify();
237 window.refresh();
238 }
239 return;
240 }
241 self.selected = Some(index);
242 cx.emit(TabsEvent::Change(self.items[index].value.clone()));
243 cx.notify();
244 window.refresh();
245 }
246
247 fn focused_index(&self, window: &Window) -> Option<usize> {
248 self.tab_focus
249 .iter()
250 .position(|focus| focus.is_focused(window))
251 }
252
253 fn move_focus(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
254 let Some(current) = self.focused_index(window) else {
255 cx.propagate();
256 return;
257 };
258 let len = self.items.len();
259 if let Some(next) = (1..=len)
260 .map(|step| {
261 if forward {
262 (current + step) % len
263 } else {
264 (current + len - step) % len
265 }
266 })
267 .find(|&index| !self.items[index].disabled)
268 {
269 self.focus_tab(next, window, cx);
270 }
271 }
272
273 fn focus_edge(&mut self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
274 if self.focused_index(window).is_none() {
275 cx.propagate();
276 return;
277 }
278 let index = if last {
279 self.items.iter().rposition(|item| !item.disabled)
280 } else {
281 self.items.iter().position(|item| !item.disabled)
282 };
283 if let Some(index) = index {
284 self.focus_tab(index, window, cx);
285 }
286 }
287}
288
289impl EventEmitter<TabsEvent> for TabsState {}
290
291fn part_id(state: EntityId, part: &'static str, index: usize) -> ElementId {
294 (ElementId::from((part, state)), index.to_string()).into()
295}
296
297#[derive(IntoElement)]
304pub struct TabList {
305 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
306 state: Entity<TabsState>,
307 label: Option<SharedString>,
308 axis: Axis,
309 direction: Option<crate::Direction>,
310 style: StyleRefinement,
311 children: Vec<AnyElement>,
312}
313
314impl TabList {
315 pub fn new(id: impl Into<ElementId>, state: &Entity<TabsState>) -> Self {
316 Self {
317 base: div().id(id).test_support(),
318 state: state.clone(),
319 label: None,
320 axis: Axis::Horizontal,
321 direction: None,
322 style: StyleRefinement::default(),
323 children: Vec::new(),
324 }
325 }
326
327 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
328 self.label = Some(label.into());
329 self
330 }
331
332 pub fn direction(mut self, direction: crate::Direction) -> Self {
334 self.direction = Some(direction);
335 self
336 }
337
338 pub fn axis(mut self, axis: Axis) -> Self {
339 self.axis = axis;
340 self
341 }
342}
343
344impl Styled for TabList {
345 fn style(&mut self) -> &mut StyleRefinement {
346 &mut self.style
347 }
348}
349
350impl ParentElement for TabList {
351 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
352 self.children.extend(elements);
353 }
354}
355
356impl InteractiveElement for TabList {
357 fn interactivity(&mut self) -> &mut Interactivity {
358 self.base.interactivity()
359 }
360}
361
362impl StatefulInteractiveElement for TabList {}
363
364impl RenderOnce for TabList {
365 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
366 let direction = self
367 .direction
368 .unwrap_or_else(|| crate::Direction::current(cx));
369 self.state
370 .update(cx, |state, cx| state.bind_focus(window, cx));
371 let previous_state = self.state.clone();
372 let next_state = self.state.clone();
373 let first_state = self.state.clone();
374 let last_state = self.state;
375 let base = self
376 .base
377 .role(Role::TabList)
378 .when_some(self.label, |this, label| this.aria_label(label))
379 .on_action(move |_: &SelectFirst, window, cx| {
380 first_state.update(cx, |state, cx| state.focus_edge(false, window, cx));
381 })
382 .on_action(move |_: &SelectLast, window, cx| {
383 last_state.update(cx, |state, cx| state.focus_edge(true, window, cx));
384 });
385
386 match self.axis {
387 Axis::Horizontal => base
388 .aria_orientation(accesskit::Orientation::Horizontal)
389 .key_context("TabList axis=horizontal")
390 .on_action(move |_: &SelectLeft, window, cx| {
391 previous_state.update(cx, |state, cx| {
392 state.move_focus(direction.horizontal_forward(false), window, cx)
393 });
394 })
395 .on_action(move |_: &SelectRight, window, cx| {
396 next_state.update(cx, |state, cx| {
397 state.move_focus(direction.horizontal_forward(true), window, cx)
398 });
399 }),
400 Axis::Vertical => base
401 .aria_orientation(accesskit::Orientation::Vertical)
402 .key_context("TabList axis=vertical")
403 .on_action(move |_: &SelectUp, window, cx| {
404 previous_state.update(cx, |state, cx| state.move_focus(false, window, cx));
405 })
406 .on_action(move |_: &SelectDown, window, cx| {
407 next_state.update(cx, |state, cx| state.move_focus(true, window, cx));
408 }),
409 }
410 .children(self.children)
411 .refine_style(&self.style)
412 }
413}
414
415#[derive(IntoElement)]
418pub struct Tab {
419 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
420 state: Entity<TabsState>,
421 index: usize,
422 style: StyleRefinement,
423 children: Vec<AnyElement>,
424}
425
426impl Tab {
427 pub fn new(state: &Entity<TabsState>, index: usize) -> Self {
429 Self {
430 base: div()
431 .id(part_id(state.entity_id(), "tab", index))
432 .test_support(),
433 state: state.clone(),
434 index,
435 style: StyleRefinement::default(),
436 children: Vec::new(),
437 }
438 }
439}
440
441impl Styled for Tab {
442 fn style(&mut self) -> &mut StyleRefinement {
443 &mut self.style
444 }
445}
446
447impl ParentElement for Tab {
448 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
449 self.children.extend(elements);
450 }
451}
452
453impl InteractiveElement for Tab {
454 fn interactivity(&mut self) -> &mut Interactivity {
455 self.base.interactivity()
456 }
457}
458
459impl StatefulInteractiveElement for Tab {}
460
461impl RenderOnce for Tab {
462 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
463 let model = self.state.read(cx);
464 let item = model
465 .items
466 .get(self.index)
467 .expect("Tab index must identify an item");
468 let disabled = item.disabled;
469 let selected = model.selected == Some(self.index);
470 let tab_stop = if model.manual_activation {
471 model.cursor == Some(self.index)
472 } else {
473 selected
474 };
475 let focus = model.tab_focus_handle(self.index).clone();
476 let label = item.label.clone();
477 let size = model.items.len();
478 let index = self.index;
479 let click_state = self.state;
480
481 self.base
482 .role(Role::Tab)
483 .aria_label(label)
484 .aria_selected(selected)
485 .aria_position_in_set(index + 1)
486 .aria_size_of_set(size)
487 .when(!disabled || focus.is_focused(window), |this| {
488 this.track_focus(&focus.tab_stop(tab_stop && !disabled))
489 })
490 .when(disabled, |this| {
491 this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
492 })
493 .when(!disabled, |this| {
494 this.on_click(move |_, window, cx| {
495 click_state.update(cx, |state, cx| state.select(index, window, cx));
496 })
497 })
498 .children(self.children)
499 .refine_style(&self.style)
500 .a11y_disabled(disabled)
501 }
502}
503
504#[derive(IntoElement)]
514pub struct TabPanel {
515 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
516 state: Entity<TabsState>,
517 index: usize,
518 tab_stop: bool,
519 style: StyleRefinement,
520 children: Vec<AnyElement>,
521}
522
523impl TabPanel {
524 pub fn new(state: &Entity<TabsState>, index: usize) -> Self {
526 Self {
527 base: div()
528 .id(part_id(state.entity_id(), "tab-panel", index))
529 .test_support(),
530 state: state.clone(),
531 index,
532 tab_stop: false,
533 style: StyleRefinement::default(),
534 children: Vec::new(),
535 }
536 }
537
538 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
539 self.tab_stop = tab_stop;
540 self
541 }
542}
543
544impl Styled for TabPanel {
545 fn style(&mut self) -> &mut StyleRefinement {
546 &mut self.style
547 }
548}
549
550impl ParentElement for TabPanel {
551 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
552 self.children.extend(elements);
553 }
554}
555
556impl InteractiveElement for TabPanel {
557 fn interactivity(&mut self) -> &mut Interactivity {
558 self.base.interactivity()
559 }
560}
561
562impl StatefulInteractiveElement for TabPanel {}
563
564impl RenderOnce for TabPanel {
565 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
566 let model = self.state.read(cx);
567 let item = model
568 .items
569 .get(self.index)
570 .expect("TabPanel index must identify an item");
571 if model.selected != Some(self.index) {
572 return gpui::Empty.into_any_element();
573 }
574 let focus = model.panel_focus_handle(self.index).clone();
575 self.base
576 .role(Role::TabPanel)
577 .aria_label(item.label.clone())
578 .track_focus(&focus.tab_stop(self.tab_stop))
579 .children(self.children)
580 .refine_style(&self.style)
581 .into_any_element()
582 }
583}
584
585#[cfg(test)]
586mod tests {
587 use std::{cell::RefCell, rc::Rc};
588
589 use gpui::{
590 AppContext as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext,
591 VisualTestContext, point, px,
592 };
593
594 use super::*;
595 use crate::{Button, Root};
596
597 struct Harness {
598 state: Entity<TabsState>,
599 axis: Axis,
600 direction: crate::Direction,
601 before: FocusHandle,
602 panel_button: FocusHandle,
603 last_button: FocusHandle,
604 after: FocusHandle,
605 unhandled_keys: Rc<RefCell<Vec<String>>>,
606 _subscription: Subscription,
607 }
608
609 impl Render for Harness {
610 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
611 let unhandled_keys = self.unhandled_keys.clone();
612 let tabs = self
613 .state
614 .read(cx)
615 .items()
616 .iter()
617 .enumerate()
618 .map(|(index, item)| {
619 Tab::new(&self.state, index)
620 .debug_selector(move || format!("tab-{index}"))
621 .w(px(120.))
622 .h(px(32.))
623 .child(item.label().clone())
624 });
625 div()
626 .w(px(480.))
627 .flex()
628 .flex_col()
629 .on_key_down(move |event, _, _| {
630 unhandled_keys
631 .borrow_mut()
632 .push(event.keystroke.key.clone());
633 })
634 .child(
635 Button::new("before")
636 .track_focus(&self.before)
637 .h(px(32.))
638 .child("Before"),
639 )
640 .child(
641 TabList::new("tabs", &self.state)
642 .axis(self.axis)
643 .direction(self.direction)
644 .accessibility_label("Sections")
645 .flex()
646 .when(self.axis == Axis::Vertical, |this| this.flex_col())
647 .children(tabs),
648 )
649 .children((0..self.state.read(cx).items().len()).map(|index| {
650 TabPanel::new(&self.state, index)
651 .tab_stop(index == 2)
652 .h(px(40.))
653 .child(match index {
654 0 => Button::new("panel-button")
655 .accessibility_label("Panel action")
656 .track_focus(&self.panel_button)
657 .h(px(32.))
658 .child("Panel action")
659 .into_any_element(),
660 3 => Button::new("last-button")
661 .track_focus(&self.last_button)
662 .h(px(32.))
663 .child("Last action")
664 .into_any_element(),
665 _ => div().child("Panel text").into_any_element(),
666 })
667 }))
668 .child(
669 Button::new("after")
670 .track_focus(&self.after)
671 .h(px(32.))
672 .child("After"),
673 )
674 }
675 }
676
677 type Changes = Rc<RefCell<Vec<SharedString>>>;
678
679 fn items() -> Vec<TabItem> {
680 vec![
681 TabItem::new("general", "General"),
682 TabItem::new("disabled", "Unavailable").disabled(true),
683 TabItem::new("help", "Help"),
684 TabItem::new("advanced", "Advanced"),
685 ]
686 }
687
688 fn harness(
689 cx: &mut TestAppContext,
690 axis: Axis,
691 items: Vec<TabItem>,
692 manual_activation: bool,
693 ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
694 cx.update(crate::init);
695 let (root, cx) = cx.add_window_view(move |window, cx| {
696 let content = cx.new(|cx| {
697 let state = cx.new(|cx| {
698 let state = TabsState::new(items, cx);
699 if manual_activation {
700 state.manual_activation()
701 } else {
702 state
703 }
704 });
705 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
706 Harness {
707 state,
708 axis,
709 direction: crate::Direction::Ltr,
710 before: cx.focus_handle().tab_stop(true),
711 panel_button: cx.focus_handle().tab_stop(true),
712 last_button: cx.focus_handle().tab_stop(true),
713 after: cx.focus_handle().tab_stop(true),
714 unhandled_keys: Rc::new(RefCell::new(Vec::new())),
715 _subscription: subscription,
716 }
717 });
718 Root::new(content, window, cx)
719 });
720 let view = root
721 .read_with(cx, |root, _| root.view().clone())
722 .downcast::<Harness>()
723 .unwrap();
724 let changes = Rc::new(RefCell::new(Vec::new()));
725 cx.update(|window, cx| {
726 let state = view.read(cx).state.clone();
727 let changes = changes.clone();
728 cx.subscribe(&state, move |_, event: &TabsEvent, _| {
729 let TabsEvent::Change(value) = event;
730 changes.borrow_mut().push(value.clone());
731 })
732 .detach();
733 window.activate_window();
734 let before = view.read(cx).before.clone();
735 before.focus(window, cx);
736 window.draw(cx).clear(cx);
737 });
738 cx.run_until_parked();
739 (cx, view, changes)
740 }
741
742 fn draw(cx: &mut VisualTestContext) {
743 cx.update(|window, cx| window.draw(cx).clear(cx));
744 }
745
746 fn press(cx: &mut VisualTestContext, key: &str) {
747 let keystroke =
748 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
749 cx.simulate_event(KeyDownEvent {
750 keystroke: keystroke.clone(),
751 is_held: false,
752 prefer_character_input: false,
753 });
754 cx.simulate_event(KeyUpEvent { keystroke });
755 draw(cx);
756 }
757
758 fn assert_tab(cx: &mut VisualTestContext, view: &Entity<Harness>, index: usize) {
759 assert_selection_and_focus(cx, view, index, index);
760 }
761
762 fn assert_selection_and_focus(
763 cx: &mut VisualTestContext,
764 view: &Entity<Harness>,
765 selected: usize,
766 focused: usize,
767 ) {
768 cx.update(|window, cx| {
769 let state = view.read(cx).state.read(cx);
770 assert_eq!(state.selected_index(), Some(selected));
771 assert!(state.tab_focus_handle(focused).is_focused(window));
772 });
773 }
774
775 #[gpui::test]
776 fn programmatic_selection_preserves_focus_and_emits_only_real_changes(cx: &mut TestAppContext) {
777 let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
778 cx.update(|window, cx| {
779 let state = view.read(cx).state.clone();
780 assert!(view.read(cx).before.is_focused(window));
781 assert!(state.update(cx, |state, cx| state.select_value("help", window, cx)));
782 assert_eq!(state.read(cx).selected_index(), Some(2));
783 assert!(view.read(cx).before.is_focused(window));
784 });
785 draw(cx);
786 cx.run_until_parked();
787 draw(cx);
788 cx.update(|window, cx| {
789 assert_eq!(view.read(cx).state.read(cx).selected_index(), Some(2));
790 assert!(view.read(cx).before.is_focused(window));
791 });
792 assert_eq!(*changes.borrow(), [SharedString::from("help")]);
793
794 cx.update(|window, cx| {
795 let state = view.read(cx).state.clone();
796 for value in ["help", "missing", "disabled"] {
797 assert!(!state.update(cx, |state, cx| state.select_value(value, window, cx)));
798 assert_eq!(state.read(cx).selected_index(), Some(2));
799 assert!(view.read(cx).before.is_focused(window));
800 }
801 });
802 draw(cx);
803 cx.run_until_parked();
804 draw(cx);
805 assert_eq!(*changes.borrow(), [SharedString::from("help")]);
806
807 cx.update(|window, cx| {
808 let state = view.read(cx).state.clone();
809 assert!(state.update(cx, |state, cx| state.select_value("general", window, cx)));
810 assert_eq!(state.read(cx).selected_index(), Some(0));
811 assert!(view.read(cx).before.is_focused(window));
812 });
813 draw(cx);
814 cx.run_until_parked();
815 draw(cx);
816 cx.update(|window, cx| {
817 assert_eq!(view.read(cx).state.read(cx).selected_index(), Some(0));
818 assert!(view.read(cx).before.is_focused(window));
819 });
820 assert_eq!(
821 *changes.borrow(),
822 [SharedString::from("help"), SharedString::from("general")]
823 );
824 }
825
826 #[gpui::test]
827 fn horizontal_navigation_wraps_skips_disabled_and_preserves_other_axis(
828 cx: &mut TestAppContext,
829 ) {
830 let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
831 cx.simulate_keystrokes("tab");
832 draw(cx);
833 assert_tab(cx, &view, 0);
834
835 for (key, index) in [
836 ("left", 3),
837 ("home", 0),
838 ("right", 2),
839 ("end", 3),
840 ("right", 0),
841 ] {
842 cx.simulate_keystrokes(key);
843 draw(cx);
844 assert_tab(cx, &view, index);
845 }
846 assert_eq!(
847 *changes.borrow(),
848 ["advanced", "general", "help", "advanced", "general"].map(SharedString::from)
849 );
850 cx.update(|_, cx| view.read(cx).unhandled_keys.borrow_mut().clear());
851 cx.simulate_keystrokes("up down");
852 draw(cx);
853 assert_tab(cx, &view, 0);
854 cx.update(|_, cx| {
855 assert_eq!(*view.read(cx).unhandled_keys.borrow(), ["up", "down"]);
856 });
857
858 cx.simulate_keystrokes("tab");
859 draw(cx);
860 cx.update(|window, cx| assert!(view.read(cx).panel_button.is_focused(window)));
861 cx.simulate_keystrokes("tab");
862 draw(cx);
863 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
864 cx.simulate_keystrokes("shift-tab shift-tab");
865 draw(cx);
866 assert_tab(cx, &view, 0);
867 cx.simulate_keystrokes("shift-tab");
868 draw(cx);
869 cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
870 }
871
872 #[gpui::test]
873 fn vertical_navigation_and_text_panel_focus_follow_their_contract(cx: &mut TestAppContext) {
874 let (cx, view, changes) = harness(cx, Axis::Vertical, items(), false);
875 cx.simulate_keystrokes("tab down");
876 draw(cx);
877 assert_tab(cx, &view, 2);
878 cx.update(|_, cx| view.read(cx).unhandled_keys.borrow_mut().clear());
879 cx.simulate_keystrokes("left right");
880 draw(cx);
881 assert_tab(cx, &view, 2);
882 cx.update(|_, cx| {
883 assert_eq!(*view.read(cx).unhandled_keys.borrow(), ["left", "right"]);
884 });
885 cx.simulate_keystrokes("tab");
886 draw(cx);
887 cx.update(|window, cx| {
888 assert!(
889 view.read(cx)
890 .state
891 .read(cx)
892 .panel_focus_handle(2)
893 .is_focused(window)
894 );
895 assert!(!view.read(cx).panel_button.is_focused(window));
896 });
897 cx.simulate_keystrokes("tab");
898 draw(cx);
899 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
900 cx.simulate_keystrokes("shift-tab shift-tab");
901 draw(cx);
902 assert_tab(cx, &view, 2);
903 cx.simulate_keystrokes("up");
904 draw(cx);
905 assert_tab(cx, &view, 0);
906 assert_eq!(
907 *changes.borrow(),
908 [SharedString::from("help"), SharedString::from("general")]
909 );
910 }
911
912 #[gpui::test]
913 fn pointer_and_native_activation_do_not_duplicate_selection(cx: &mut TestAppContext) {
914 let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
915 cx.simulate_keystrokes("tab");
916 draw(cx);
917 press(cx, "space");
918 press(cx, "enter");
919 assert!(changes.borrow().is_empty());
920 cx.simulate_click(point(px(250.), px(48.)), Modifiers::default());
922 draw(cx);
923 assert_tab(cx, &view, 2);
924 cx.simulate_click(point(px(250.), px(48.)), Modifiers::default());
925 draw(cx);
926 assert_tab(cx, &view, 2);
927 cx.simulate_click(point(px(130.), px(48.)), Modifiers::default());
928 draw(cx);
929 press(cx, "space");
930 press(cx, "enter");
931 assert_tab(cx, &view, 2);
932 assert_eq!(*changes.borrow(), [SharedString::from("help")]);
933 }
934
935 #[gpui::test]
936 fn direct_focus_activates_and_unmounts_previous_panel(cx: &mut TestAppContext) {
937 let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
938 cx.simulate_keystrokes("tab tab");
939 draw(cx);
940 cx.update(|window, cx| {
941 assert!(view.read(cx).panel_button.is_focused(window));
942 let focus = view.read(cx).state.read(cx).tab_focus_handle(3).clone();
943 focus.focus(window, cx);
944 });
945 draw(cx);
946 cx.run_until_parked();
947 draw(cx);
948 assert_tab(cx, &view, 3);
949 assert_eq!(*changes.borrow(), [SharedString::from("advanced")]);
950 cx.simulate_keystrokes("tab");
951 draw(cx);
952 cx.update(|window, cx| {
953 assert!(view.read(cx).last_button.is_focused(window));
954 assert!(!view.read(cx).panel_button.is_focused(window));
955 });
956 }
957
958 #[gpui::test]
959 fn manual_navigation_waits_for_native_activation_and_preserves_one_tab_entry(
960 cx: &mut TestAppContext,
961 ) {
962 let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), true);
963 view.update(cx, |view, cx| {
964 view.direction = crate::Direction::Rtl;
965 cx.notify();
966 });
967 draw(cx);
968 cx.simulate_keystrokes("tab");
969 draw(cx);
970 for (key, focused) in [
971 ("right", 3),
972 ("home", 0),
973 ("left", 2),
974 ("end", 3),
975 ("left", 0),
976 ("left", 2),
977 ] {
978 cx.simulate_keystrokes(key);
979 draw(cx);
980 assert_selection_and_focus(cx, &view, 0, focused);
981 }
982 assert!(changes.borrow().is_empty());
983 cx.simulate_keystrokes("tab");
984 draw(cx);
985 cx.update(|window, cx| assert!(view.read(cx).panel_button.is_focused(window)));
986 cx.simulate_keystrokes("shift-tab");
987 draw(cx);
988 assert_selection_and_focus(cx, &view, 0, 2);
989
990 #[cfg(feature = "test-support")]
991 cx.update(|window, cx| {
992 let state = view.read(cx).state.clone();
993 let focused =
994 crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab", 2))
995 .unwrap();
996 assert_eq!(focused.selected(), Some(false));
997 assert!(
998 crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 0))
999 .is_some()
1000 );
1001 assert!(
1002 crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 2))
1003 .is_none()
1004 );
1005 });
1006 press(cx, "enter");
1007 assert_tab(cx, &view, 2);
1008 press(cx, "enter");
1009 cx.simulate_keystrokes("end");
1010 draw(cx);
1011 assert_selection_and_focus(cx, &view, 2, 3);
1012 press(cx, "space");
1013 assert_tab(cx, &view, 3);
1014 let general = cx.debug_bounds("tab-0").unwrap().center();
1015 cx.simulate_click(general, Modifiers::default());
1016 draw(cx);
1017 assert_tab(cx, &view, 0);
1018 let disabled = cx.debug_bounds("tab-1").unwrap().center();
1019 cx.simulate_click(disabled, Modifiers::default());
1020 draw(cx);
1021 assert_tab(cx, &view, 0);
1022 assert_eq!(
1023 *changes.borrow(),
1024 ["help", "advanced", "general"].map(SharedString::from)
1025 );
1026 }
1027
1028 #[gpui::test]
1029 fn manual_direct_focus_and_selection_preserve_their_separate_targets(cx: &mut TestAppContext) {
1030 let (cx, view, changes) = harness(cx, Axis::Vertical, items(), true);
1031 cx.update(|window, cx| {
1032 let focus = view.read(cx).state.read(cx).tab_focus_handle(3).clone();
1033 focus.focus(window, cx);
1034 });
1035 draw(cx);
1036 cx.run_until_parked();
1037 draw(cx);
1038 assert_selection_and_focus(cx, &view, 0, 3);
1039 cx.simulate_keystrokes("up");
1040 draw(cx);
1041 assert_selection_and_focus(cx, &view, 0, 2);
1042 cx.update(|_, cx| view.read(cx).unhandled_keys.borrow_mut().clear());
1043 cx.simulate_keystrokes("left right");
1044 draw(cx);
1045 assert_selection_and_focus(cx, &view, 0, 2);
1046 cx.update(|window, cx| {
1047 assert_eq!(*view.read(cx).unhandled_keys.borrow(), ["left", "right"]);
1048 let state = view.read(cx).state.clone();
1049 assert!(state.update(cx, |state, cx| state.select_value("advanced", window, cx)));
1050 });
1051 draw(cx);
1052 cx.run_until_parked();
1053 draw(cx);
1054 assert_selection_and_focus(cx, &view, 3, 2);
1055 cx.simulate_keystrokes("tab");
1056 draw(cx);
1057 cx.update(|window, cx| {
1058 assert!(view.read(cx).last_button.is_focused(window));
1059 assert!(!view.read(cx).panel_button.is_focused(window));
1060 assert!(
1061 view.read(cx)
1062 .state
1063 .read(cx)
1064 .panel_focus_handle(3)
1065 .contains_focused(window, cx)
1066 );
1067 });
1068 cx.simulate_keystrokes("shift-tab");
1069 draw(cx);
1070 assert_selection_and_focus(cx, &view, 3, 2);
1071 assert_eq!(*changes.borrow(), [SharedString::from("advanced")]);
1072 }
1073
1074 #[gpui::test]
1075 fn empty_all_disabled_and_single_enabled_collections_are_well_defined(cx: &mut TestAppContext) {
1076 for items in [
1077 Vec::new(),
1078 vec![TabItem::new("disabled", "Unavailable").disabled(true)],
1079 ] {
1080 let (cx, view, changes) = harness(cx, Axis::Horizontal, items, false);
1081 cx.simulate_keystrokes("tab");
1082 draw(cx);
1083 cx.update(|window, cx| {
1084 assert!(view.read(cx).after.is_focused(window));
1085 assert!(view.read(cx).state.read(cx).selected_index().is_none());
1086 });
1087 cx.simulate_keystrokes("shift-tab");
1088 draw(cx);
1089 cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
1090 assert!(changes.borrow().is_empty());
1091 }
1092 let (cx, view, changes) = harness(
1093 cx,
1094 Axis::Horizontal,
1095 vec![TabItem::new("only", "Only")],
1096 false,
1097 );
1098 cx.simulate_keystrokes("tab right left home end");
1099 draw(cx);
1100 assert_tab(cx, &view, 0);
1101 assert!(changes.borrow().is_empty());
1102 }
1103
1104 #[cfg(feature = "test-support")]
1105 #[gpui::test]
1106 fn accessibility_exposes_only_active_panel_and_selected_tab(cx: &mut TestAppContext) {
1107 let (cx, view, _) = harness(cx, Axis::Horizontal, items(), false);
1108 cx.update(|window, cx| {
1109 let state = view.read(cx).state.clone();
1110 let list = crate::test_support::find(window, &[], &"tabs".into()).unwrap();
1111 assert_eq!(list.role(), Some(Role::TabList));
1112 assert_eq!(list.label(), Some("Sections"));
1113 for (index, item) in state.read(cx).items().iter().enumerate() {
1114 let tab = crate::test_support::find(
1115 window,
1116 &[],
1117 &part_id(state.entity_id(), "tab", index),
1118 )
1119 .unwrap();
1120 assert_eq!(tab.role(), Some(Role::Tab));
1121 assert_eq!(tab.label(), Some(item.label().as_ref()));
1122 assert_eq!(tab.selected(), Some(index == 0));
1123 assert_eq!(tab.disabled(), (index == 1).then_some(true));
1124 }
1125 let panels: Vec<_> = crate::test_support::snapshots(window)
1126 .into_iter()
1127 .filter(|item| item.role() == Some(Role::TabPanel))
1128 .collect();
1129 assert_eq!(panels.len(), 1);
1130 assert_eq!(panels[0].label(), Some("General"));
1131 });
1132 cx.simulate_keystrokes("tab right");
1133 draw(cx);
1134 cx.update(|window, cx| {
1135 let state = view.read(cx).state.clone();
1136 assert!(
1137 crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 0))
1138 .is_none()
1139 );
1140 assert!(crate::test_support::find(window, &[], &"panel-button".into()).is_none());
1141 let panel =
1142 crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 2))
1143 .unwrap();
1144 assert_eq!(panel.role(), Some(Role::TabPanel));
1145 assert_eq!(panel.label(), Some("Help"));
1146 let tab = crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab", 2))
1147 .unwrap();
1148 assert_eq!(tab.selected(), Some(true));
1149 });
1150 }
1151}