gpui-deck 0.0.4

Headless GPUI primitives with application-owned presentation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
//! Tabs with automatic or manual activation, roving focus, and active-only panels.
//! Derived from GPUI Kit v0.9.0's tab primitive; GPUI Deck adds retained
//! selection, keyboard navigation, focus activation, and panel lifecycle.

use gpui::{
    AnyElement, App, Axis, Context, ElementId, Entity, EntityId, EventEmitter, FocusHandle,
    InteractiveElement, Interactivity, IntoElement, KeyBinding, MouseButton, ParentElement,
    RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
    Subscription, Window, accesskit, div, prelude::FluentBuilder as _,
};

use crate::{
    StyledExt as _, TestSupportExt as _,
    a11y_disabled::A11yDisabledExt as _,
    actions::{SelectDown, SelectFirst, SelectLast, SelectLeft, SelectRight, SelectUp},
};

const CONTEXT: &str = "TabList";

pub(crate) fn init(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("left", SelectLeft, Some("TabList && axis == horizontal")),
        KeyBinding::new("right", SelectRight, Some("TabList && axis == horizontal")),
        KeyBinding::new("up", SelectUp, Some("TabList && axis == vertical")),
        KeyBinding::new("down", SelectDown, Some("TabList && axis == vertical")),
        KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
        KeyBinding::new("end", SelectLast, Some(CONTEXT)),
    ]);
}

/// One tab in a fixed, ordered collection. Values must be unique.
#[derive(Clone, Debug)]
pub struct TabItem {
    value: SharedString,
    label: SharedString,
    disabled: bool,
}

impl TabItem {
    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            disabled: false,
        }
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn value(&self) -> &SharedString {
        &self.value
    }

    pub fn label(&self) -> &SharedString {
        &self.label
    }

    pub fn is_disabled(&self) -> bool {
        self.disabled
    }
}

/// Emitted once after a different enabled tab becomes selected.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TabsEvent {
    Change(SharedString),
}

/// Retained selection and focus for one tab list and its panels in one window.
///
/// The first enabled tab starts selected. Moving focus to another enabled tab
/// activates it by default, including arrow-key and accessibility/programmatic
/// focus. [`Self::manual_activation`] separates focus movement from activation.
/// The application keeps panel data in its own retained entities; an inactive
/// [`TabPanel`] contributes no element, focus stop, or accessibility node.
pub struct TabsState {
    items: Vec<TabItem>,
    selected: Option<usize>,
    cursor: Option<usize>,
    manual_activation: bool,
    tab_focus: Vec<FocusHandle>,
    panel_focus: Vec<FocusHandle>,
    focus_subscriptions: Vec<Subscription>,
}

impl TabsState {
    pub fn new(items: impl IntoIterator<Item = TabItem>, cx: &mut Context<Self>) -> Self {
        let items: Vec<_> = items.into_iter().collect();
        for (ix, item) in items.iter().enumerate() {
            assert!(
                items[..ix].iter().all(|other| other.value != item.value),
                "TabItem values must be unique"
            );
        }
        let selected = items.iter().position(|item| !item.disabled);
        let tab_focus = items.iter().map(|_| cx.focus_handle()).collect();
        let panel_focus = items.iter().map(|_| cx.focus_handle()).collect();
        Self {
            items,
            selected,
            cursor: selected,
            manual_activation: false,
            tab_focus,
            panel_focus,
            focus_subscriptions: Vec::new(),
        }
    }

    /// Requires a click, Enter, or Space to activate a focused tab.
    ///
    /// Set this before the state is first rendered. Arrow keys, Home/End, and
    /// programmatic or accessibility focus only move the one Tab entry; they
    /// leave the selected panel mounted. Tab re-enters at the last focused tab,
    /// initially the selected tab.
    pub fn manual_activation(mut self) -> Self {
        self.manual_activation = true;
        self
    }

    /// Selects an enabled value before the state is first rendered.
    ///
    /// # Panics
    /// Panics if `value` does not identify an enabled item in this collection.
    pub fn default_value(mut self, value: impl AsRef<str>) -> Self {
        self.selected = Some(
            self.items
                .iter()
                .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled)
                .expect("TabsState default_value must identify an enabled TabItem"),
        );
        self.cursor = self.selected;
        self
    }

    pub fn items(&self) -> &[TabItem] {
        &self.items
    }

    pub fn selected_index(&self) -> Option<usize> {
        self.selected
    }

    pub fn selected_item(&self) -> Option<&TabItem> {
        self.selected.map(|index| &self.items[index])
    }

    /// Selects an enabled item without moving keyboard focus.
    ///
    /// Returns `true` when the selection changes. Missing, disabled, and
    /// already-selected values return `false` without emitting a change.
    /// The caller owns focus when removing the previously selected content.
    /// In manual mode this preserves the last focused tab as the list's Tab entry.
    pub fn select_value(
        &mut self,
        value: impl AsRef<str>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        let Some(index) = self
            .items
            .iter()
            .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled)
        else {
            return false;
        };
        if self.selected == Some(index) {
            return false;
        }
        self.selected = Some(index);
        cx.emit(TabsEvent::Change(self.items[index].value.clone()));
        cx.notify();
        window.refresh();
        true
    }

    /// The stable focus handle of a tab in the fixed collection.
    pub fn tab_focus_handle(&self, index: usize) -> &FocusHandle {
        &self.tab_focus[index]
    }

    /// The stable scope handle of a panel. Only the selected panel is rendered.
    pub fn panel_focus_handle(&self, index: usize) -> &FocusHandle {
        &self.panel_focus[index]
    }

    fn bind_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if !self.focus_subscriptions.is_empty() {
            return;
        }
        self.focus_subscriptions = self
            .tab_focus
            .iter()
            .enumerate()
            .map(|(index, focus)| {
                cx.on_focus(focus, window, move |_, window, cx| {
                    // Focus notifications occur while drawing. Apply the focus
                    // cursor and any automatic activation after that draw.
                    cx.defer_in(window, move |state, window, cx| {
                        if state.tab_focus[index].is_focused(window) {
                            state.focus_tab(index, window, cx);
                        }
                    });
                })
            })
            .collect();
    }

    fn focus_tab(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if !self.manual_activation {
            self.select(index, window, cx);
            return;
        }
        if self.items[index].disabled {
            return;
        }
        self.tab_focus[index].focus(window, cx);
        if self.cursor != Some(index) {
            self.cursor = Some(index);
            cx.notify();
            window.refresh();
        }
    }

    fn select(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if self.items[index].disabled {
            return;
        }
        self.tab_focus[index].focus(window, cx);
        let cursor_changed = self.cursor != Some(index);
        self.cursor = Some(index);
        if self.selected == Some(index) {
            if cursor_changed {
                cx.notify();
                window.refresh();
            }
            return;
        }
        self.selected = Some(index);
        cx.emit(TabsEvent::Change(self.items[index].value.clone()));
        cx.notify();
        window.refresh();
    }

    fn focused_index(&self, window: &Window) -> Option<usize> {
        self.tab_focus
            .iter()
            .position(|focus| focus.is_focused(window))
    }

    fn move_focus(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
        let Some(current) = self.focused_index(window) else {
            cx.propagate();
            return;
        };
        let len = self.items.len();
        if let Some(next) = (1..=len)
            .map(|step| {
                if forward {
                    (current + step) % len
                } else {
                    (current + len - step) % len
                }
            })
            .find(|&index| !self.items[index].disabled)
        {
            self.focus_tab(next, window, cx);
        }
    }

    fn focus_edge(&mut self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
        if self.focused_index(window).is_none() {
            cx.propagate();
            return;
        }
        let index = if last {
            self.items.iter().rposition(|item| !item.disabled)
        } else {
            self.items.iter().position(|item| !item.disabled)
        };
        if let Some(index) = index {
            self.focus_tab(index, window, cx);
        }
    }
}

impl EventEmitter<TabsEvent> for TabsState {}

// Parts remain distinct when multiple tab states render as siblings without a
// dedicated wrapper. These are GPUI element IDs, not accessibility relation IDs.
fn part_id(state: EntityId, part: &'static str, index: usize) -> ElementId {
    (ElementId::from((part, state)), index.to_string()).into()
}

/// The unstyled list of tab triggers. Render one [`Tab`] per item in order.
///
/// The default horizontal list uses Left/Right. A vertical list uses Up/Down.
/// Home/End focus the first/last enabled tab. Focus also activates by default;
/// manual activation waits for a click, Enter, or Space. Other-axis arrows are
/// left to the enclosing application. Axis sets semantics and keys, not layout.
#[derive(IntoElement)]
pub struct TabList {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<TabsState>,
    label: Option<SharedString>,
    axis: Axis,
    direction: Option<crate::Direction>,
    style: StyleRefinement,
    children: Vec<AnyElement>,
}

impl TabList {
    pub fn new(id: impl Into<ElementId>, state: &Entity<TabsState>) -> Self {
        Self {
            base: div().id(id).test_support(),
            state: state.clone(),
            label: None,
            axis: Axis::Horizontal,
            direction: None,
            style: StyleRefinement::default(),
            children: Vec::new(),
        }
    }

    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Overrides the inherited logical direction for horizontal arrows.
    pub fn direction(mut self, direction: crate::Direction) -> Self {
        self.direction = Some(direction);
        self
    }

    pub fn axis(mut self, axis: Axis) -> Self {
        self.axis = axis;
        self
    }
}

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

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

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

impl StatefulInteractiveElement for TabList {}

impl RenderOnce for TabList {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let direction = self
            .direction
            .unwrap_or_else(|| crate::Direction::current(cx));
        self.state
            .update(cx, |state, cx| state.bind_focus(window, cx));
        let previous_state = self.state.clone();
        let next_state = self.state.clone();
        let first_state = self.state.clone();
        let last_state = self.state;
        let base = self
            .base
            .role(Role::TabList)
            .when_some(self.label, |this, label| this.aria_label(label))
            .on_action(move |_: &SelectFirst, window, cx| {
                first_state.update(cx, |state, cx| state.focus_edge(false, window, cx));
            })
            .on_action(move |_: &SelectLast, window, cx| {
                last_state.update(cx, |state, cx| state.focus_edge(true, window, cx));
            });

        match self.axis {
            Axis::Horizontal => base
                .aria_orientation(accesskit::Orientation::Horizontal)
                .key_context("TabList axis=horizontal")
                .on_action(move |_: &SelectLeft, window, cx| {
                    previous_state.update(cx, |state, cx| {
                        state.move_focus(direction.horizontal_forward(false), window, cx)
                    });
                })
                .on_action(move |_: &SelectRight, window, cx| {
                    next_state.update(cx, |state, cx| {
                        state.move_focus(direction.horizontal_forward(true), window, cx)
                    });
                }),
            Axis::Vertical => base
                .aria_orientation(accesskit::Orientation::Vertical)
                .key_context("TabList axis=vertical")
                .on_action(move |_: &SelectUp, window, cx| {
                    previous_state.update(cx, |state, cx| state.move_focus(false, window, cx));
                })
                .on_action(move |_: &SelectDown, window, cx| {
                    next_state.update(cx, |state, cx| state.move_focus(true, window, cx));
                }),
        }
        .children(self.children)
        .refine_style(&self.style)
    }
}

/// An unstyled trigger for one tab. The state owns its label, selection and
/// focus. Applications supply its visual content and state styling.
#[derive(IntoElement)]
pub struct Tab {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<TabsState>,
    index: usize,
    style: StyleRefinement,
    children: Vec<AnyElement>,
}

impl Tab {
    /// `index` must identify an item in the enclosing tab list's state.
    pub fn new(state: &Entity<TabsState>, index: usize) -> Self {
        Self {
            base: div()
                .id(part_id(state.entity_id(), "tab", index))
                .test_support(),
            state: state.clone(),
            index,
            style: StyleRefinement::default(),
            children: Vec::new(),
        }
    }
}

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

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

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

impl StatefulInteractiveElement for Tab {}

impl RenderOnce for Tab {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let model = self.state.read(cx);
        let item = model
            .items
            .get(self.index)
            .expect("Tab index must identify an item");
        let disabled = item.disabled;
        let selected = model.selected == Some(self.index);
        let tab_stop = if model.manual_activation {
            model.cursor == Some(self.index)
        } else {
            selected
        };
        let focus = model.tab_focus_handle(self.index).clone();
        let label = item.label.clone();
        let size = model.items.len();
        let index = self.index;
        let click_state = self.state;

        self.base
            .role(Role::Tab)
            .aria_label(label)
            .aria_selected(selected)
            .aria_position_in_set(index + 1)
            .aria_size_of_set(size)
            .when(!disabled || focus.is_focused(window), |this| {
                this.track_focus(&focus.tab_stop(tab_stop && !disabled))
            })
            .when(disabled, |this| {
                this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
            })
            .when(!disabled, |this| {
                this.on_click(move |_, window, cx| {
                    click_state.update(cx, |state, cx| state.select(index, window, cx));
                })
            })
            .children(self.children)
            .refine_style(&self.style)
            .a11y_disabled(disabled)
    }
}

/// Content for one tab, mounted only while that tab is selected.
///
/// The panel's accessible name is its tab label. The pinned GPUI API cannot
/// express explicit tab/panel accessibility relationships; element IDs are not
/// substituted for native accessibility node IDs.
///
/// By default the panel scope is not a Tab stop, allowing Tab to reach its first
/// focusable child. Set [`Self::tab_stop`] to `true` for a panel whose leading content
/// should itself receive keyboard focus, such as a text-only help panel.
#[derive(IntoElement)]
pub struct TabPanel {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<TabsState>,
    index: usize,
    tab_stop: bool,
    style: StyleRefinement,
    children: Vec<AnyElement>,
}

impl TabPanel {
    /// `index` must identify the matching tab in this state's fixed collection.
    pub fn new(state: &Entity<TabsState>, index: usize) -> Self {
        Self {
            base: div()
                .id(part_id(state.entity_id(), "tab-panel", index))
                .test_support(),
            state: state.clone(),
            index,
            tab_stop: false,
            style: StyleRefinement::default(),
            children: Vec::new(),
        }
    }

    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
        self.tab_stop = tab_stop;
        self
    }
}

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

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

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

impl StatefulInteractiveElement for TabPanel {}

impl RenderOnce for TabPanel {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let model = self.state.read(cx);
        let item = model
            .items
            .get(self.index)
            .expect("TabPanel index must identify an item");
        if model.selected != Some(self.index) {
            return gpui::Empty.into_any_element();
        }
        let focus = model.panel_focus_handle(self.index).clone();
        self.base
            .role(Role::TabPanel)
            .aria_label(item.label.clone())
            .track_focus(&focus.tab_stop(self.tab_stop))
            .children(self.children)
            .refine_style(&self.style)
            .into_any_element()
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, rc::Rc};

    use gpui::{
        AppContext as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext,
        VisualTestContext, point, px,
    };

    use super::*;
    use crate::{Button, Root};

    struct Harness {
        state: Entity<TabsState>,
        axis: Axis,
        direction: crate::Direction,
        before: FocusHandle,
        panel_button: FocusHandle,
        last_button: FocusHandle,
        after: FocusHandle,
        unhandled_keys: Rc<RefCell<Vec<String>>>,
        _subscription: Subscription,
    }

    impl Render for Harness {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let unhandled_keys = self.unhandled_keys.clone();
            let tabs = self
                .state
                .read(cx)
                .items()
                .iter()
                .enumerate()
                .map(|(index, item)| {
                    Tab::new(&self.state, index)
                        .debug_selector(move || format!("tab-{index}"))
                        .w(px(120.))
                        .h(px(32.))
                        .child(item.label().clone())
                });
            div()
                .w(px(480.))
                .flex()
                .flex_col()
                .on_key_down(move |event, _, _| {
                    unhandled_keys
                        .borrow_mut()
                        .push(event.keystroke.key.clone());
                })
                .child(
                    Button::new("before")
                        .track_focus(&self.before)
                        .h(px(32.))
                        .child("Before"),
                )
                .child(
                    TabList::new("tabs", &self.state)
                        .axis(self.axis)
                        .direction(self.direction)
                        .accessibility_label("Sections")
                        .flex()
                        .when(self.axis == Axis::Vertical, |this| this.flex_col())
                        .children(tabs),
                )
                .children((0..self.state.read(cx).items().len()).map(|index| {
                    TabPanel::new(&self.state, index)
                        .tab_stop(index == 2)
                        .h(px(40.))
                        .child(match index {
                            0 => Button::new("panel-button")
                                .accessibility_label("Panel action")
                                .track_focus(&self.panel_button)
                                .h(px(32.))
                                .child("Panel action")
                                .into_any_element(),
                            3 => Button::new("last-button")
                                .track_focus(&self.last_button)
                                .h(px(32.))
                                .child("Last action")
                                .into_any_element(),
                            _ => div().child("Panel text").into_any_element(),
                        })
                }))
                .child(
                    Button::new("after")
                        .track_focus(&self.after)
                        .h(px(32.))
                        .child("After"),
                )
        }
    }

    type Changes = Rc<RefCell<Vec<SharedString>>>;

    fn items() -> Vec<TabItem> {
        vec![
            TabItem::new("general", "General"),
            TabItem::new("disabled", "Unavailable").disabled(true),
            TabItem::new("help", "Help"),
            TabItem::new("advanced", "Advanced"),
        ]
    }

    fn harness(
        cx: &mut TestAppContext,
        axis: Axis,
        items: Vec<TabItem>,
        manual_activation: bool,
    ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
        cx.update(crate::init);
        let (root, cx) = cx.add_window_view(move |window, cx| {
            let content = cx.new(|cx| {
                let state = cx.new(|cx| {
                    let state = TabsState::new(items, cx);
                    if manual_activation {
                        state.manual_activation()
                    } else {
                        state
                    }
                });
                let subscription = cx.observe(&state, |_, _, cx| cx.notify());
                Harness {
                    state,
                    axis,
                    direction: crate::Direction::Ltr,
                    before: cx.focus_handle().tab_stop(true),
                    panel_button: cx.focus_handle().tab_stop(true),
                    last_button: cx.focus_handle().tab_stop(true),
                    after: cx.focus_handle().tab_stop(true),
                    unhandled_keys: Rc::new(RefCell::new(Vec::new())),
                    _subscription: subscription,
                }
            });
            Root::new(content, window, cx)
        });
        let view = root
            .read_with(cx, |root, _| root.view().clone())
            .downcast::<Harness>()
            .unwrap();
        let changes = Rc::new(RefCell::new(Vec::new()));
        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            let changes = changes.clone();
            cx.subscribe(&state, move |_, event: &TabsEvent, _| {
                let TabsEvent::Change(value) = event;
                changes.borrow_mut().push(value.clone());
            })
            .detach();
            window.activate_window();
            let before = view.read(cx).before.clone();
            before.focus(window, cx);
            window.draw(cx).clear(cx);
        });
        cx.run_until_parked();
        (cx, view, changes)
    }

    fn draw(cx: &mut VisualTestContext) {
        cx.update(|window, cx| window.draw(cx).clear(cx));
    }

    fn press(cx: &mut VisualTestContext, key: &str) {
        let keystroke =
            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
        cx.simulate_event(KeyDownEvent {
            keystroke: keystroke.clone(),
            is_held: false,
            prefer_character_input: false,
        });
        cx.simulate_event(KeyUpEvent { keystroke });
        draw(cx);
    }

    fn assert_tab(cx: &mut VisualTestContext, view: &Entity<Harness>, index: usize) {
        assert_selection_and_focus(cx, view, index, index);
    }

    fn assert_selection_and_focus(
        cx: &mut VisualTestContext,
        view: &Entity<Harness>,
        selected: usize,
        focused: usize,
    ) {
        cx.update(|window, cx| {
            let state = view.read(cx).state.read(cx);
            assert_eq!(state.selected_index(), Some(selected));
            assert!(state.tab_focus_handle(focused).is_focused(window));
        });
    }

    #[gpui::test]
    fn programmatic_selection_preserves_focus_and_emits_only_real_changes(cx: &mut TestAppContext) {
        let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            assert!(view.read(cx).before.is_focused(window));
            assert!(state.update(cx, |state, cx| state.select_value("help", window, cx)));
            assert_eq!(state.read(cx).selected_index(), Some(2));
            assert!(view.read(cx).before.is_focused(window));
        });
        draw(cx);
        cx.run_until_parked();
        draw(cx);
        cx.update(|window, cx| {
            assert_eq!(view.read(cx).state.read(cx).selected_index(), Some(2));
            assert!(view.read(cx).before.is_focused(window));
        });
        assert_eq!(*changes.borrow(), [SharedString::from("help")]);

        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            for value in ["help", "missing", "disabled"] {
                assert!(!state.update(cx, |state, cx| state.select_value(value, window, cx)));
                assert_eq!(state.read(cx).selected_index(), Some(2));
                assert!(view.read(cx).before.is_focused(window));
            }
        });
        draw(cx);
        cx.run_until_parked();
        draw(cx);
        assert_eq!(*changes.borrow(), [SharedString::from("help")]);

        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            assert!(state.update(cx, |state, cx| state.select_value("general", window, cx)));
            assert_eq!(state.read(cx).selected_index(), Some(0));
            assert!(view.read(cx).before.is_focused(window));
        });
        draw(cx);
        cx.run_until_parked();
        draw(cx);
        cx.update(|window, cx| {
            assert_eq!(view.read(cx).state.read(cx).selected_index(), Some(0));
            assert!(view.read(cx).before.is_focused(window));
        });
        assert_eq!(
            *changes.borrow(),
            [SharedString::from("help"), SharedString::from("general")]
        );
    }

    #[gpui::test]
    fn horizontal_navigation_wraps_skips_disabled_and_preserves_other_axis(
        cx: &mut TestAppContext,
    ) {
        let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
        cx.simulate_keystrokes("tab");
        draw(cx);
        assert_tab(cx, &view, 0);

        for (key, index) in [
            ("left", 3),
            ("home", 0),
            ("right", 2),
            ("end", 3),
            ("right", 0),
        ] {
            cx.simulate_keystrokes(key);
            draw(cx);
            assert_tab(cx, &view, index);
        }
        assert_eq!(
            *changes.borrow(),
            ["advanced", "general", "help", "advanced", "general"].map(SharedString::from)
        );
        cx.update(|_, cx| view.read(cx).unhandled_keys.borrow_mut().clear());
        cx.simulate_keystrokes("up down");
        draw(cx);
        assert_tab(cx, &view, 0);
        cx.update(|_, cx| {
            assert_eq!(*view.read(cx).unhandled_keys.borrow(), ["up", "down"]);
        });

        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).panel_button.is_focused(window)));
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
        cx.simulate_keystrokes("shift-tab shift-tab");
        draw(cx);
        assert_tab(cx, &view, 0);
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
    }

    #[gpui::test]
    fn vertical_navigation_and_text_panel_focus_follow_their_contract(cx: &mut TestAppContext) {
        let (cx, view, changes) = harness(cx, Axis::Vertical, items(), false);
        cx.simulate_keystrokes("tab down");
        draw(cx);
        assert_tab(cx, &view, 2);
        cx.update(|_, cx| view.read(cx).unhandled_keys.borrow_mut().clear());
        cx.simulate_keystrokes("left right");
        draw(cx);
        assert_tab(cx, &view, 2);
        cx.update(|_, cx| {
            assert_eq!(*view.read(cx).unhandled_keys.borrow(), ["left", "right"]);
        });
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| {
            assert!(
                view.read(cx)
                    .state
                    .read(cx)
                    .panel_focus_handle(2)
                    .is_focused(window)
            );
            assert!(!view.read(cx).panel_button.is_focused(window));
        });
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
        cx.simulate_keystrokes("shift-tab shift-tab");
        draw(cx);
        assert_tab(cx, &view, 2);
        cx.simulate_keystrokes("up");
        draw(cx);
        assert_tab(cx, &view, 0);
        assert_eq!(
            *changes.borrow(),
            [SharedString::from("help"), SharedString::from("general")]
        );
    }

    #[gpui::test]
    fn pointer_and_native_activation_do_not_duplicate_selection(cx: &mut TestAppContext) {
        let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
        cx.simulate_keystrokes("tab");
        draw(cx);
        press(cx, "space");
        press(cx, "enter");
        assert!(changes.borrow().is_empty());
        // Horizontal tabs occupy 120px each below the 32px "Before" button.
        cx.simulate_click(point(px(250.), px(48.)), Modifiers::default());
        draw(cx);
        assert_tab(cx, &view, 2);
        cx.simulate_click(point(px(250.), px(48.)), Modifiers::default());
        draw(cx);
        assert_tab(cx, &view, 2);
        cx.simulate_click(point(px(130.), px(48.)), Modifiers::default());
        draw(cx);
        press(cx, "space");
        press(cx, "enter");
        assert_tab(cx, &view, 2);
        assert_eq!(*changes.borrow(), [SharedString::from("help")]);
    }

    #[gpui::test]
    fn direct_focus_activates_and_unmounts_previous_panel(cx: &mut TestAppContext) {
        let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), false);
        cx.simulate_keystrokes("tab tab");
        draw(cx);
        cx.update(|window, cx| {
            assert!(view.read(cx).panel_button.is_focused(window));
            let focus = view.read(cx).state.read(cx).tab_focus_handle(3).clone();
            focus.focus(window, cx);
        });
        draw(cx);
        cx.run_until_parked();
        draw(cx);
        assert_tab(cx, &view, 3);
        assert_eq!(*changes.borrow(), [SharedString::from("advanced")]);
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| {
            assert!(view.read(cx).last_button.is_focused(window));
            assert!(!view.read(cx).panel_button.is_focused(window));
        });
    }

    #[gpui::test]
    fn manual_navigation_waits_for_native_activation_and_preserves_one_tab_entry(
        cx: &mut TestAppContext,
    ) {
        let (cx, view, changes) = harness(cx, Axis::Horizontal, items(), true);
        view.update(cx, |view, cx| {
            view.direction = crate::Direction::Rtl;
            cx.notify();
        });
        draw(cx);
        cx.simulate_keystrokes("tab");
        draw(cx);
        for (key, focused) in [
            ("right", 3),
            ("home", 0),
            ("left", 2),
            ("end", 3),
            ("left", 0),
            ("left", 2),
        ] {
            cx.simulate_keystrokes(key);
            draw(cx);
            assert_selection_and_focus(cx, &view, 0, focused);
        }
        assert!(changes.borrow().is_empty());
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).panel_button.is_focused(window)));
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        assert_selection_and_focus(cx, &view, 0, 2);

        #[cfg(feature = "test-support")]
        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            let focused =
                crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab", 2))
                    .unwrap();
            assert_eq!(focused.selected(), Some(false));
            assert!(
                crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 0))
                    .is_some()
            );
            assert!(
                crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 2))
                    .is_none()
            );
        });
        press(cx, "enter");
        assert_tab(cx, &view, 2);
        press(cx, "enter");
        cx.simulate_keystrokes("end");
        draw(cx);
        assert_selection_and_focus(cx, &view, 2, 3);
        press(cx, "space");
        assert_tab(cx, &view, 3);
        let general = cx.debug_bounds("tab-0").unwrap().center();
        cx.simulate_click(general, Modifiers::default());
        draw(cx);
        assert_tab(cx, &view, 0);
        let disabled = cx.debug_bounds("tab-1").unwrap().center();
        cx.simulate_click(disabled, Modifiers::default());
        draw(cx);
        assert_tab(cx, &view, 0);
        assert_eq!(
            *changes.borrow(),
            ["help", "advanced", "general"].map(SharedString::from)
        );
    }

    #[gpui::test]
    fn manual_direct_focus_and_selection_preserve_their_separate_targets(cx: &mut TestAppContext) {
        let (cx, view, changes) = harness(cx, Axis::Vertical, items(), true);
        cx.update(|window, cx| {
            let focus = view.read(cx).state.read(cx).tab_focus_handle(3).clone();
            focus.focus(window, cx);
        });
        draw(cx);
        cx.run_until_parked();
        draw(cx);
        assert_selection_and_focus(cx, &view, 0, 3);
        cx.simulate_keystrokes("up");
        draw(cx);
        assert_selection_and_focus(cx, &view, 0, 2);
        cx.update(|_, cx| view.read(cx).unhandled_keys.borrow_mut().clear());
        cx.simulate_keystrokes("left right");
        draw(cx);
        assert_selection_and_focus(cx, &view, 0, 2);
        cx.update(|window, cx| {
            assert_eq!(*view.read(cx).unhandled_keys.borrow(), ["left", "right"]);
            let state = view.read(cx).state.clone();
            assert!(state.update(cx, |state, cx| state.select_value("advanced", window, cx)));
        });
        draw(cx);
        cx.run_until_parked();
        draw(cx);
        assert_selection_and_focus(cx, &view, 3, 2);
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| {
            assert!(view.read(cx).last_button.is_focused(window));
            assert!(!view.read(cx).panel_button.is_focused(window));
            assert!(
                view.read(cx)
                    .state
                    .read(cx)
                    .panel_focus_handle(3)
                    .contains_focused(window, cx)
            );
        });
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        assert_selection_and_focus(cx, &view, 3, 2);
        assert_eq!(*changes.borrow(), [SharedString::from("advanced")]);
    }

    #[gpui::test]
    fn empty_all_disabled_and_single_enabled_collections_are_well_defined(cx: &mut TestAppContext) {
        for items in [
            Vec::new(),
            vec![TabItem::new("disabled", "Unavailable").disabled(true)],
        ] {
            let (cx, view, changes) = harness(cx, Axis::Horizontal, items, false);
            cx.simulate_keystrokes("tab");
            draw(cx);
            cx.update(|window, cx| {
                assert!(view.read(cx).after.is_focused(window));
                assert!(view.read(cx).state.read(cx).selected_index().is_none());
            });
            cx.simulate_keystrokes("shift-tab");
            draw(cx);
            cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
            assert!(changes.borrow().is_empty());
        }
        let (cx, view, changes) = harness(
            cx,
            Axis::Horizontal,
            vec![TabItem::new("only", "Only")],
            false,
        );
        cx.simulate_keystrokes("tab right left home end");
        draw(cx);
        assert_tab(cx, &view, 0);
        assert!(changes.borrow().is_empty());
    }

    #[cfg(feature = "test-support")]
    #[gpui::test]
    fn accessibility_exposes_only_active_panel_and_selected_tab(cx: &mut TestAppContext) {
        let (cx, view, _) = harness(cx, Axis::Horizontal, items(), false);
        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            let list = crate::test_support::find(window, &[], &"tabs".into()).unwrap();
            assert_eq!(list.role(), Some(Role::TabList));
            assert_eq!(list.label(), Some("Sections"));
            for (index, item) in state.read(cx).items().iter().enumerate() {
                let tab = crate::test_support::find(
                    window,
                    &[],
                    &part_id(state.entity_id(), "tab", index),
                )
                .unwrap();
                assert_eq!(tab.role(), Some(Role::Tab));
                assert_eq!(tab.label(), Some(item.label().as_ref()));
                assert_eq!(tab.selected(), Some(index == 0));
                assert_eq!(tab.disabled(), (index == 1).then_some(true));
            }
            let panels: Vec<_> = crate::test_support::snapshots(window)
                .into_iter()
                .filter(|item| item.role() == Some(Role::TabPanel))
                .collect();
            assert_eq!(panels.len(), 1);
            assert_eq!(panels[0].label(), Some("General"));
        });
        cx.simulate_keystrokes("tab right");
        draw(cx);
        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            assert!(
                crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 0))
                    .is_none()
            );
            assert!(crate::test_support::find(window, &[], &"panel-button".into()).is_none());
            let panel =
                crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab-panel", 2))
                    .unwrap();
            assert_eq!(panel.role(), Some(Role::TabPanel));
            assert_eq!(panel.label(), Some("Help"));
            let tab = crate::test_support::find(window, &[], &part_id(state.entity_id(), "tab", 2))
                .unwrap();
            assert_eq!(tab.selected(), Some(true));
        });
    }
}