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
//! Exclusive selection with one tab stop and application-owned presentation.
//! Derived from GPUI Kit v0.9.0's radio primitives; GPUI Deck adds retained
//! group selection, roving focus, keyboard navigation, and group-level semantics.

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

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

const CONTEXT: &str = "RadioGroup";

pub(crate) fn init(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
    ]);
}

/// One option in a radio group's fixed, ordered collection. Values must be unique.
#[derive(Clone, Debug)]
pub struct RadioItem {
    value: SharedString,
    label: SharedString,
    disabled: bool,
}

impl RadioItem {
    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 when a user selects a different value.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RadioGroupEvent {
    Change(SharedString),
}

/// Retained exclusive selection and focus for one rendered radio group.
///
/// Tab enters at the selected option, or the first enabled option when nothing
/// is selected. Arrow keys select and focus the next enabled option, wrapping at
/// either end. Space/Enter or a pointer click select without deselecting an
/// already selected option. Disabled options are skipped. Application value
/// updates preserve a focused option until Tab exits; reentry uses the selection.
pub struct RadioGroupState {
    items: Vec<RadioItem>,
    selected: Option<usize>,
    disabled: bool,
    focus: Vec<FocusHandle>,
}

impl RadioGroupState {
    pub fn new(items: impl IntoIterator<Item = RadioItem>, 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),
                "RadioItem values must be unique"
            );
        }
        let focus = items.iter().map(|_| cx.focus_handle()).collect();
        Self {
            items,
            selected: None,
            disabled: false,
            focus,
        }
    }

    /// Selects an enabled value before the state is first rendered.
    /// An unknown or disabled value leaves the group unselected.
    pub fn default_value(mut self, value: impl AsRef<str>) -> Self {
        self.selected = self
            .items
            .iter()
            .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled);
        self
    }

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

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

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

    /// Sets or clears the selected value without emitting Change or moving focus.
    ///
    /// Unknown or disabled options are rejected without changing the selection.
    /// Returns whether the value was accepted, including an unchanged value.
    /// Application updates remain available while the group itself is disabled.
    pub fn set_selected_value(
        &mut self,
        value: Option<&str>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        let selected = match value {
            Some(value) => {
                let Some(index) = self
                    .items
                    .iter()
                    .position(|item| item.value.as_ref() == value && !item.disabled)
                else {
                    return false;
                };
                Some(index)
            }
            None => None,
        };
        if self.selected != selected {
            self.selected = selected;
            cx.notify();
            window.refresh();
        }
        true
    }

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

    /// The stable focus handle of an option in this state's fixed collection.
    pub fn option_focus_handle(&self, index: usize) -> &FocusHandle {
        &self.focus[index]
    }

    /// Disables the group while retaining its value. An option already holding
    /// focus stays in the focus tree so Tab/Shift-Tab can leave the group.
    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled == disabled {
            return;
        }
        self.disabled = disabled;
        cx.notify();
        window.refresh();
    }

    fn tab_stop_index(&self, window: &Window) -> Option<usize> {
        if self.disabled {
            return None;
        }
        self.focus
            .iter()
            .position(|focus| focus.is_focused(window))
            .filter(|&index| !self.items[index].disabled)
            .or(self.selected)
            .or_else(|| self.items.iter().position(|item| !item.disabled))
    }

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

    fn move_selection(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled {
            return;
        }
        // Only the option holding focus owns this command. A consumer may put
        // other content in the group without giving it radio keyboard behavior.
        let Some(current) = self.focus.iter().position(|focus| focus.is_focused(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(|&ix| !self.items[ix].disabled)
        {
            self.select(next, window, cx);
        }
    }
}

impl EventEmitter<RadioGroupEvent> for RadioGroupState {}

/// An unstyled radio group. Render one [`RadioOption`] for every item, in order,
/// using this group's state. Children supply presentation; the group supplies
/// exclusive selection, keyboard navigation, and accessibility semantics.
#[derive(IntoElement)]
pub struct RadioGroup {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<RadioGroupState>,
    label: Option<SharedString>,
    field: crate::FieldMetadata,
    axis: Axis,
    direction: Option<crate::Direction>,
    style: StyleRefinement,
    children: Vec<AnyElement>,
}

impl RadioGroup {
    pub fn new(id: impl Into<ElementId>, state: &Entity<RadioGroupState>) -> Self {
        Self {
            base: div().id(id).test_support(),
            state: state.clone(),
            label: None,
            field: crate::FieldMetadata::default(),
            axis: Axis::Vertical,
            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
    }

    /// Sets semantic orientation, without imposing layout. Both pairs of arrow
    /// keys navigate the fixed option order in either orientation.
    /// Overrides the inherited logical direction for horizontal arrows.
    pub fn direction(mut self, direction: crate::Direction) -> Self {
        self.direction = Some(direction);
        self
    }

    /// Applies a [`crate::ControlField`]'s label, description, required and
    /// invalid metadata to this control's native node. The field label takes
    /// precedence over `accessibility_label`; required and invalid apply to the group.
    pub fn field(mut self, metadata: crate::FieldMetadata) -> Self {
        self.field = metadata;
        self
    }

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

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

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

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

impl StatefulInteractiveElement for RadioGroup {}

impl RenderOnce for RadioGroup {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let direction = self
            .direction
            .unwrap_or_else(|| crate::Direction::current(cx));
        let disabled = self.state.read(cx).disabled;
        let up_state = self.state.clone();
        let down_state = self.state.clone();
        let left_state = self.state.clone();
        let right_state = self.state;
        let field = self.field;

        self.base
            .role(Role::RadioGroup)
            .aria_orientation(match self.axis {
                Axis::Horizontal => accesskit::Orientation::Horizontal,
                Axis::Vertical => accesskit::Orientation::Vertical,
            })
            .when_some(field.label.or(self.label), |this, label| {
                this.aria_label(label)
            })
            .when_some(field.description, |this, description| {
                this.aria_description(description)
            })
            .key_context(CONTEXT)
            .on_action(move |_: &SelectUp, window, cx| {
                up_state.update(cx, |state, cx| state.move_selection(false, window, cx));
            })
            .on_action(move |_: &SelectDown, window, cx| {
                down_state.update(cx, |state, cx| state.move_selection(true, window, cx));
            })
            .on_action(move |_: &SelectLeft, window, cx| {
                left_state.update(cx, |state, cx| {
                    state.move_selection(direction.horizontal_forward(false), window, cx)
                });
            })
            .on_action(move |_: &SelectRight, window, cx| {
                right_state.update(cx, |state, cx| {
                    state.move_selection(direction.horizontal_forward(true), window, cx)
                });
            })
            .children(self.children)
            .refine_style(&self.style)
            .a11y_form(disabled, field.required, field.invalid)
    }
}

/// One unstyled radio option. Its state supplies the label, checked state, focus,
/// and activation; applications provide the visual indicator and other content.
#[derive(IntoElement)]
pub struct RadioOption {
    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
    state: Entity<RadioGroupState>,
    index: usize,
    style: StyleRefinement,
    children: Vec<AnyElement>,
}

impl RadioOption {
    /// `index` must identify an item in the enclosing group's state.
    pub fn new(state: &Entity<RadioGroupState>, index: usize) -> Self {
        Self {
            base: div().id(("radio-option", index)).test_support(),
            state: state.clone(),
            index,
            style: StyleRefinement::default(),
            children: Vec::new(),
        }
    }
}

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

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

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

impl StatefulInteractiveElement for RadioOption {}

impl RenderOnce for RadioOption {
    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("RadioOption index must identify an item");
        let disabled = model.disabled || item.disabled;
        let checked = model.selected == Some(self.index);
        let tab_stop = model.tab_stop_index(window) == Some(self.index);
        let focus = model.option_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::RadioButton)
            .aria_label(label)
            .aria_toggled(if checked {
                Toggled::True
            } else {
                Toggled::False
            })
            .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))
            })
            .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)
    }
}

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

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

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

    struct Harness {
        state: Entity<RadioGroupState>,
        before: FocusHandle,
        after: FocusHandle,
        _subscription: Subscription,
    }

    impl Render for Harness {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let options = self
                .state
                .read(cx)
                .items()
                .iter()
                .enumerate()
                .map(|(ix, item)| {
                    RadioOption::new(&self.state, ix)
                        .w_full()
                        .h(px(32.))
                        .child(item.label().clone())
                });
            div()
                .w(px(240.))
                .flex()
                .flex_col()
                .child(
                    Button::new("before")
                        .track_focus(&self.before)
                        .w_full()
                        .h(px(32.))
                        .child("Before"),
                )
                .child(
                    RadioGroup::new("group", &self.state)
                        .accessibility_label("Size")
                        .flex()
                        .flex_col()
                        .children(options),
                )
                .child(
                    Button::new("after")
                        .track_focus(&self.after)
                        .w_full()
                        .h(px(32.))
                        .child("After"),
                )
        }
    }

    fn items() -> Vec<RadioItem> {
        vec![
            RadioItem::new("small", "Small"),
            RadioItem::new("unavailable", "Unavailable").disabled(true),
            RadioItem::new("medium", "Medium"),
            RadioItem::new("large", "Large"),
        ]
    }

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

    fn harness<'a>(
        cx: &'a mut TestAppContext,
        items: Vec<RadioItem>,
        value: Option<&'static str>,
    ) -> (&'a 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 = RadioGroupState::new(items, cx);
                    if let Some(value) = value {
                        state.default_value(value)
                    } else {
                        state
                    }
                });
                let subscription = cx.observe(&state, |_, _, cx| cx.notify());
                Harness {
                    state,
                    before: cx.focus_handle().tab_stop(true),
                    after: cx.focus_handle().tab_stop(true),
                    _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: &RadioGroupEvent, _| {
                let RadioGroupEvent::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_option(cx: &mut VisualTestContext, view: &Entity<Harness>, index: usize) {
        cx.update(|window, cx| {
            let state = view.read(cx).state.read(cx);
            assert_eq!(state.selected_index(), Some(index));
            assert!(state.option_focus_handle(index).is_focused(window));
        });
    }

    #[gpui::test]
    fn arrows_wrap_skip_disabled_and_keep_one_tab_stop(cx: &mut TestAppContext) {
        let (cx, view, changes) = harness(cx, items(), Some("medium"));
        cx.simulate_keystrokes("tab");
        draw(cx);
        assert_option(cx, &view, 2);
        assert!(changes.borrow().is_empty());

        for (key, index) in [
            ("right", 3),
            ("down", 0),
            ("right", 2),
            ("left", 0),
            ("up", 3),
        ] {
            cx.simulate_keystrokes(key);
            draw(cx);
            assert_option(cx, &view, index);
        }
        assert_eq!(
            *changes.borrow(),
            ["large", "small", "medium", "small", "large"].map(SharedString::from)
        );

        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        assert_option(cx, &view, 3);
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
        cx.simulate_keystrokes("tab");
        draw(cx);
        assert_option(cx, &view, 3);
        assert_eq!(changes.borrow().len(), 5);
    }

    #[gpui::test]
    fn pointer_and_native_activation_select_once_without_deselecting(cx: &mut TestAppContext) {
        let (cx, view, changes) = harness(cx, items(), None);
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| {
            let state = view.read(cx).state.read(cx);
            assert_eq!(state.selected_index(), None);
            assert!(state.option_focus_handle(0).is_focused(window));
        });
        press(cx, "space");
        assert_option(cx, &view, 0);
        press(cx, "space");
        press(cx, "enter");
        assert_eq!(*changes.borrow(), [SharedString::from("small")]);

        // Each row is 32px high, following the 32px "Before" button.
        cx.simulate_click(point(px(12.), px(112.)), Modifiers::default());
        draw(cx);
        assert_option(cx, &view, 2);
        cx.simulate_click(point(px(12.), px(112.)), Modifiers::default());
        draw(cx);
        cx.simulate_click(point(px(12.), px(80.)), Modifiers::default());
        draw(cx);
        assert_option(cx, &view, 2);
        assert_eq!(
            *changes.borrow(),
            [SharedString::from("small"), SharedString::from("medium")]
        );
    }

    #[gpui::test]
    fn programmatic_selection_preserves_focus_and_validates_without_user_events(
        cx: &mut TestAppContext,
    ) {
        let (cx, view, changes) = harness(cx, items(), Some("small"));
        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            state.update(cx, |state, cx| {
                assert!(state.set_selected_value(Some("large"), window, cx));
                assert!(!state.set_selected_value(Some("missing"), window, cx));
                assert!(!state.set_selected_value(Some("unavailable"), window, cx));
                assert_eq!(state.selected_index(), Some(3));
            });
            assert!(view.read(cx).before.is_focused(window));
        });
        draw(cx);
        cx.simulate_keystrokes("tab");
        draw(cx);
        assert_option(cx, &view, 3);

        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            state.update(cx, |state, cx| {
                assert!(state.set_selected_value(Some("small"), window, cx));
                assert!(state.set_selected_value(Some("small"), window, cx));
                assert!(state.option_focus_handle(3).is_focused(window));
            });
            for index in [0, 3] {
                let option = RadioOption::new(&state, index)
                    .render(window, cx)
                    .into_element();
                let mut node = accesskit::Node::new(option.a11y_role().unwrap());
                option.write_a11y_info(&mut node);
                assert_eq!(
                    node.toggled(),
                    Some(if index == 0 {
                        Toggled::True
                    } else {
                        Toggled::False
                    })
                );
            }
        });
        draw(cx);
        // An application update keeps one Tab stop while another option is focused.
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        assert_option(cx, &view, 0);

        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            state.update(cx, |state, cx| {
                assert!(state.set_selected_value(None, window, cx));
                assert_eq!(state.selected_index(), None);
                assert!(state.option_focus_handle(0).is_focused(window));
                state.set_disabled(true, window, cx);
                assert!(state.set_selected_value(Some("medium"), window, cx));
                assert_eq!(state.selected_index(), Some(2));
                assert!(state.option_focus_handle(0).is_focused(window));
            });
        });
        draw(cx);
        cx.simulate_keystrokes("tab");
        draw(cx);
        cx.update(|window, cx| {
            assert!(view.read(cx).after.is_focused(window));
            let state = view.read(cx).state.clone();
            state.update(cx, |state, cx| state.set_disabled(false, window, cx));
        });
        draw(cx);
        cx.simulate_keystrokes("shift-tab");
        draw(cx);
        assert_option(cx, &view, 2);
        assert!(changes.borrow().is_empty());
    }

    #[gpui::test]
    fn disabling_a_focused_group_preserves_exit_and_skips_it_on_reentry(cx: &mut TestAppContext) {
        for backwards in [false, true] {
            let (cx, view, changes) = harness(cx, items(), Some("small"));
            cx.simulate_keystrokes("tab");
            draw(cx);
            cx.update(|window, cx| {
                let state = view.read(cx).state.clone();
                state.update(cx, |state, cx| state.set_disabled(true, window, cx));
            });
            draw(cx);
            press(cx, "space");
            press(cx, "enter");
            cx.simulate_keystrokes("right");
            draw(cx);
            cx.simulate_click(point(px(12.), px(112.)), Modifiers::default());
            draw(cx);
            assert_option(cx, &view, 0);
            assert!(changes.borrow().is_empty());

            cx.simulate_keystrokes(if backwards { "shift-tab" } else { "tab" });
            draw(cx);
            cx.update(|window, cx| {
                let view = view.read(cx);
                let expected = if backwards { &view.before } else { &view.after };
                assert!(expected.is_focused(window));
            });
            cx.simulate_keystrokes(if backwards { "tab" } else { "shift-tab" });
            draw(cx);
            cx.update(|window, cx| {
                let view = view.read(cx);
                let expected = if backwards { &view.after } else { &view.before };
                assert!(expected.is_focused(window));
                let state = view.state.clone();
                state.update(cx, |state, cx| state.set_disabled(false, window, cx));
            });
            draw(cx);
            cx.simulate_keystrokes(if backwards { "shift-tab" } else { "tab" });
            draw(cx);
            assert_option(cx, &view, 0);
        }
    }

    #[gpui::test]
    fn empty_and_all_disabled_groups_have_no_tab_stop(cx: &mut TestAppContext) {
        for items in [
            Vec::new(),
            vec![RadioItem::new("only", "Only").disabled(true)],
        ] {
            let (cx, view, changes) = harness(cx, items, None);
            cx.simulate_keystrokes("tab");
            draw(cx);
            cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
            cx.simulate_keystrokes("shift-tab");
            draw(cx);
            cx.update(|window, cx| {
                assert!(view.read(cx).before.is_focused(window));
                assert!(view.read(cx).state.read(cx).selected_item().is_none());
            });
            assert!(changes.borrow().is_empty());
        }
    }

    #[cfg(feature = "test-support")]
    #[gpui::test]
    fn group_and_options_expose_names_checked_and_disabled_state(cx: &mut TestAppContext) {
        let (cx, view, _) = harness(cx, items(), Some("medium"));
        cx.update(|window, _| {
            let group = crate::test_support::find(window, &[], &"group".into()).unwrap();
            assert_eq!(group.role(), Some(Role::RadioGroup));
            assert_eq!(group.label(), Some("Size"));
            for (index, label) in ["Small", "Unavailable", "Medium", "Large"]
                .iter()
                .enumerate()
            {
                let option =
                    crate::test_support::find(window, &[], &("radio-option", index).into())
                        .unwrap();
                assert_eq!(option.role(), Some(Role::RadioButton));
                assert_eq!(option.label(), Some(*label));
                assert_eq!(option.checked(), Some(index == 2));
                assert_eq!(option.disabled(), (index == 1).then_some(true));
            }
        });
        cx.update(|window, cx| {
            let state = view.read(cx).state.clone();
            state.update(cx, |state, cx| state.set_disabled(true, window, cx));
        });
        draw(cx);
        cx.update(|window, _| {
            assert_eq!(
                crate::test_support::find(window, &[], &"group".into())
                    .unwrap()
                    .disabled(),
                Some(true)
            );
            for index in 0usize..4 {
                assert_eq!(
                    crate::test_support::find(window, &[], &("radio-option", index).into())
                        .unwrap()
                        .disabled(),
                    Some(true)
                );
            }
        });
    }
}