Skip to main content

gpui_deck/
radio_group.rs

1//! Exclusive selection with one tab stop and application-owned presentation.
2//! Derived from GPUI Kit v0.9.0's radio primitives; GPUI Deck adds retained
3//! group selection, roving focus, keyboard navigation, and group-level semantics.
4
5use gpui::{
6    AnyElement, App, Axis, Context, ElementId, Entity, EventEmitter, FocusHandle,
7    InteractiveElement, Interactivity, IntoElement, KeyBinding, MouseButton, ParentElement,
8    RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Toggled,
9    Window, accesskit, div, prelude::FluentBuilder as _,
10};
11
12use crate::{
13    StyledExt as _, TestSupportExt as _,
14    a11y_disabled::A11yDisabledExt as _,
15    actions::{SelectDown, SelectLeft, SelectRight, SelectUp},
16};
17
18const CONTEXT: &str = "RadioGroup";
19
20pub(crate) fn init(cx: &mut App) {
21    cx.bind_keys([
22        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
23        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
24        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
25        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
26    ]);
27}
28
29/// One option in a radio group's fixed, ordered collection. Values must be unique.
30#[derive(Clone, Debug)]
31pub struct RadioItem {
32    value: SharedString,
33    label: SharedString,
34    disabled: bool,
35}
36
37impl RadioItem {
38    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
39        Self {
40            value: value.into(),
41            label: label.into(),
42            disabled: false,
43        }
44    }
45
46    pub fn disabled(mut self, disabled: bool) -> Self {
47        self.disabled = disabled;
48        self
49    }
50
51    pub fn value(&self) -> &SharedString {
52        &self.value
53    }
54
55    pub fn label(&self) -> &SharedString {
56        &self.label
57    }
58
59    pub fn is_disabled(&self) -> bool {
60        self.disabled
61    }
62}
63
64/// Emitted once when a user selects a different value.
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub enum RadioGroupEvent {
67    Change(SharedString),
68}
69
70/// Retained exclusive selection and focus for one rendered radio group.
71///
72/// Tab enters at the selected option, or the first enabled option when nothing
73/// is selected. Arrow keys select and focus the next enabled option, wrapping at
74/// either end. Space/Enter or a pointer click select without deselecting an
75/// already selected option. Disabled options are skipped. Application value
76/// updates preserve a focused option until Tab exits; reentry uses the selection.
77pub struct RadioGroupState {
78    items: Vec<RadioItem>,
79    selected: Option<usize>,
80    disabled: bool,
81    focus: Vec<FocusHandle>,
82}
83
84impl RadioGroupState {
85    pub fn new(items: impl IntoIterator<Item = RadioItem>, cx: &mut Context<Self>) -> Self {
86        let items: Vec<_> = items.into_iter().collect();
87        for (ix, item) in items.iter().enumerate() {
88            assert!(
89                items[..ix].iter().all(|other| other.value != item.value),
90                "RadioItem values must be unique"
91            );
92        }
93        let focus = items.iter().map(|_| cx.focus_handle()).collect();
94        Self {
95            items,
96            selected: None,
97            disabled: false,
98            focus,
99        }
100    }
101
102    /// Selects an enabled value before the state is first rendered.
103    /// An unknown or disabled value leaves the group unselected.
104    pub fn default_value(mut self, value: impl AsRef<str>) -> Self {
105        self.selected = self
106            .items
107            .iter()
108            .position(|item| item.value.as_ref() == value.as_ref() && !item.disabled);
109        self
110    }
111
112    pub fn items(&self) -> &[RadioItem] {
113        &self.items
114    }
115
116    pub fn selected_index(&self) -> Option<usize> {
117        self.selected
118    }
119
120    pub fn selected_item(&self) -> Option<&RadioItem> {
121        self.selected.map(|ix| &self.items[ix])
122    }
123
124    /// Sets or clears the selected value without emitting Change or moving focus.
125    ///
126    /// Unknown or disabled options are rejected without changing the selection.
127    /// Returns whether the value was accepted, including an unchanged value.
128    /// Application updates remain available while the group itself is disabled.
129    pub fn set_selected_value(
130        &mut self,
131        value: Option<&str>,
132        window: &mut Window,
133        cx: &mut Context<Self>,
134    ) -> bool {
135        let selected = match value {
136            Some(value) => {
137                let Some(index) = self
138                    .items
139                    .iter()
140                    .position(|item| item.value.as_ref() == value && !item.disabled)
141                else {
142                    return false;
143                };
144                Some(index)
145            }
146            None => None,
147        };
148        if self.selected != selected {
149            self.selected = selected;
150            cx.notify();
151            window.refresh();
152        }
153        true
154    }
155
156    pub fn is_disabled(&self) -> bool {
157        self.disabled
158    }
159
160    /// The stable focus handle of an option in this state's fixed collection.
161    pub fn option_focus_handle(&self, index: usize) -> &FocusHandle {
162        &self.focus[index]
163    }
164
165    /// Disables the group while retaining its value. An option already holding
166    /// focus stays in the focus tree so Tab/Shift-Tab can leave the group.
167    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
168        if self.disabled == disabled {
169            return;
170        }
171        self.disabled = disabled;
172        cx.notify();
173        window.refresh();
174    }
175
176    fn tab_stop_index(&self, window: &Window) -> Option<usize> {
177        if self.disabled {
178            return None;
179        }
180        self.focus
181            .iter()
182            .position(|focus| focus.is_focused(window))
183            .filter(|&index| !self.items[index].disabled)
184            .or(self.selected)
185            .or_else(|| self.items.iter().position(|item| !item.disabled))
186    }
187
188    fn select(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
189        if self.disabled || self.items[index].disabled {
190            return;
191        }
192        self.focus[index].focus(window, cx);
193        if self.selected == Some(index) {
194            return;
195        }
196        self.selected = Some(index);
197        cx.emit(RadioGroupEvent::Change(self.items[index].value.clone()));
198        cx.notify();
199        window.refresh();
200    }
201
202    fn move_selection(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
203        if self.disabled {
204            return;
205        }
206        // Only the option holding focus owns this command. A consumer may put
207        // other content in the group without giving it radio keyboard behavior.
208        let Some(current) = self.focus.iter().position(|focus| focus.is_focused(window)) else {
209            cx.propagate();
210            return;
211        };
212        let len = self.items.len();
213        if let Some(next) = (1..=len)
214            .map(|step| {
215                if forward {
216                    (current + step) % len
217                } else {
218                    (current + len - step) % len
219                }
220            })
221            .find(|&ix| !self.items[ix].disabled)
222        {
223            self.select(next, window, cx);
224        }
225    }
226}
227
228impl EventEmitter<RadioGroupEvent> for RadioGroupState {}
229
230/// An unstyled radio group. Render one [`RadioOption`] for every item, in order,
231/// using this group's state. Children supply presentation; the group supplies
232/// exclusive selection, keyboard navigation, and accessibility semantics.
233#[derive(IntoElement)]
234pub struct RadioGroup {
235    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
236    state: Entity<RadioGroupState>,
237    label: Option<SharedString>,
238    field: crate::FieldMetadata,
239    axis: Axis,
240    direction: Option<crate::Direction>,
241    style: StyleRefinement,
242    children: Vec<AnyElement>,
243}
244
245impl RadioGroup {
246    pub fn new(id: impl Into<ElementId>, state: &Entity<RadioGroupState>) -> Self {
247        Self {
248            base: div().id(id).test_support(),
249            state: state.clone(),
250            label: None,
251            field: crate::FieldMetadata::default(),
252            axis: Axis::Vertical,
253            direction: None,
254            style: StyleRefinement::default(),
255            children: Vec::new(),
256        }
257    }
258
259    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
260        self.label = Some(label.into());
261        self
262    }
263
264    /// Sets semantic orientation, without imposing layout. Both pairs of arrow
265    /// keys navigate the fixed option order in either orientation.
266    /// Overrides the inherited logical direction for horizontal arrows.
267    pub fn direction(mut self, direction: crate::Direction) -> Self {
268        self.direction = Some(direction);
269        self
270    }
271
272    /// Applies a [`crate::ControlField`]'s label, description, required and
273    /// invalid metadata to this control's native node. The field label takes
274    /// precedence over `accessibility_label`; required and invalid apply to the group.
275    pub fn field(mut self, metadata: crate::FieldMetadata) -> Self {
276        self.field = metadata;
277        self
278    }
279
280    pub fn axis(mut self, axis: Axis) -> Self {
281        self.axis = axis;
282        self
283    }
284}
285
286impl Styled for RadioGroup {
287    fn style(&mut self) -> &mut StyleRefinement {
288        &mut self.style
289    }
290}
291
292impl ParentElement for RadioGroup {
293    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
294        self.children.extend(elements);
295    }
296}
297
298impl InteractiveElement for RadioGroup {
299    fn interactivity(&mut self) -> &mut Interactivity {
300        self.base.interactivity()
301    }
302}
303
304impl StatefulInteractiveElement for RadioGroup {}
305
306impl RenderOnce for RadioGroup {
307    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
308        let direction = self
309            .direction
310            .unwrap_or_else(|| crate::Direction::current(cx));
311        let disabled = self.state.read(cx).disabled;
312        let up_state = self.state.clone();
313        let down_state = self.state.clone();
314        let left_state = self.state.clone();
315        let right_state = self.state;
316        let field = self.field;
317
318        self.base
319            .role(Role::RadioGroup)
320            .aria_orientation(match self.axis {
321                Axis::Horizontal => accesskit::Orientation::Horizontal,
322                Axis::Vertical => accesskit::Orientation::Vertical,
323            })
324            .when_some(field.label.or(self.label), |this, label| {
325                this.aria_label(label)
326            })
327            .when_some(field.description, |this, description| {
328                this.aria_description(description)
329            })
330            .key_context(CONTEXT)
331            .on_action(move |_: &SelectUp, window, cx| {
332                up_state.update(cx, |state, cx| state.move_selection(false, window, cx));
333            })
334            .on_action(move |_: &SelectDown, window, cx| {
335                down_state.update(cx, |state, cx| state.move_selection(true, window, cx));
336            })
337            .on_action(move |_: &SelectLeft, window, cx| {
338                left_state.update(cx, |state, cx| {
339                    state.move_selection(direction.horizontal_forward(false), window, cx)
340                });
341            })
342            .on_action(move |_: &SelectRight, window, cx| {
343                right_state.update(cx, |state, cx| {
344                    state.move_selection(direction.horizontal_forward(true), window, cx)
345                });
346            })
347            .children(self.children)
348            .refine_style(&self.style)
349            .a11y_form(disabled, field.required, field.invalid)
350    }
351}
352
353/// One unstyled radio option. Its state supplies the label, checked state, focus,
354/// and activation; applications provide the visual indicator and other content.
355#[derive(IntoElement)]
356pub struct RadioOption {
357    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
358    state: Entity<RadioGroupState>,
359    index: usize,
360    style: StyleRefinement,
361    children: Vec<AnyElement>,
362}
363
364impl RadioOption {
365    /// `index` must identify an item in the enclosing group's state.
366    pub fn new(state: &Entity<RadioGroupState>, index: usize) -> Self {
367        Self {
368            base: div().id(("radio-option", index)).test_support(),
369            state: state.clone(),
370            index,
371            style: StyleRefinement::default(),
372            children: Vec::new(),
373        }
374    }
375}
376
377impl Styled for RadioOption {
378    fn style(&mut self) -> &mut StyleRefinement {
379        &mut self.style
380    }
381}
382
383impl ParentElement for RadioOption {
384    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
385        self.children.extend(elements);
386    }
387}
388
389impl InteractiveElement for RadioOption {
390    fn interactivity(&mut self) -> &mut Interactivity {
391        self.base.interactivity()
392    }
393}
394
395impl StatefulInteractiveElement for RadioOption {}
396
397impl RenderOnce for RadioOption {
398    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
399        let model = self.state.read(cx);
400        let item = model
401            .items
402            .get(self.index)
403            .expect("RadioOption index must identify an item");
404        let disabled = model.disabled || item.disabled;
405        let checked = model.selected == Some(self.index);
406        let tab_stop = model.tab_stop_index(window) == Some(self.index);
407        let focus = model.option_focus_handle(self.index).clone();
408        let label = item.label.clone();
409        let size = model.items.len();
410        let index = self.index;
411        let click_state = self.state;
412
413        self.base
414            .role(Role::RadioButton)
415            .aria_label(label)
416            .aria_toggled(if checked {
417                Toggled::True
418            } else {
419                Toggled::False
420            })
421            .aria_position_in_set(index + 1)
422            .aria_size_of_set(size)
423            .when(!disabled || focus.is_focused(window), |this| {
424                this.track_focus(&focus.tab_stop(tab_stop))
425            })
426            .when(disabled, |this| {
427                this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
428            })
429            .when(!disabled, |this| {
430                this.on_click(move |_, window, cx| {
431                    click_state.update(cx, |state, cx| state.select(index, window, cx));
432                })
433            })
434            .children(self.children)
435            .refine_style(&self.style)
436            .a11y_disabled(disabled)
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    use std::{cell::RefCell, rc::Rc};
443
444    use gpui::{
445        AppContext as _, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
446        Subscription, TestAppContext, VisualTestContext, point, px,
447    };
448
449    use super::*;
450    use crate::{Button, Root};
451
452    struct Harness {
453        state: Entity<RadioGroupState>,
454        before: FocusHandle,
455        after: FocusHandle,
456        _subscription: Subscription,
457    }
458
459    impl Render for Harness {
460        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
461            let options = self
462                .state
463                .read(cx)
464                .items()
465                .iter()
466                .enumerate()
467                .map(|(ix, item)| {
468                    RadioOption::new(&self.state, ix)
469                        .w_full()
470                        .h(px(32.))
471                        .child(item.label().clone())
472                });
473            div()
474                .w(px(240.))
475                .flex()
476                .flex_col()
477                .child(
478                    Button::new("before")
479                        .track_focus(&self.before)
480                        .w_full()
481                        .h(px(32.))
482                        .child("Before"),
483                )
484                .child(
485                    RadioGroup::new("group", &self.state)
486                        .accessibility_label("Size")
487                        .flex()
488                        .flex_col()
489                        .children(options),
490                )
491                .child(
492                    Button::new("after")
493                        .track_focus(&self.after)
494                        .w_full()
495                        .h(px(32.))
496                        .child("After"),
497                )
498        }
499    }
500
501    fn items() -> Vec<RadioItem> {
502        vec![
503            RadioItem::new("small", "Small"),
504            RadioItem::new("unavailable", "Unavailable").disabled(true),
505            RadioItem::new("medium", "Medium"),
506            RadioItem::new("large", "Large"),
507        ]
508    }
509
510    type Changes = Rc<RefCell<Vec<SharedString>>>;
511
512    fn harness<'a>(
513        cx: &'a mut TestAppContext,
514        items: Vec<RadioItem>,
515        value: Option<&'static str>,
516    ) -> (&'a mut VisualTestContext, Entity<Harness>, Changes) {
517        cx.update(crate::init);
518        let (root, cx) = cx.add_window_view(move |window, cx| {
519            let content = cx.new(|cx| {
520                let state = cx.new(|cx| {
521                    let state = RadioGroupState::new(items, cx);
522                    if let Some(value) = value {
523                        state.default_value(value)
524                    } else {
525                        state
526                    }
527                });
528                let subscription = cx.observe(&state, |_, _, cx| cx.notify());
529                Harness {
530                    state,
531                    before: cx.focus_handle().tab_stop(true),
532                    after: cx.focus_handle().tab_stop(true),
533                    _subscription: subscription,
534                }
535            });
536            Root::new(content, window, cx)
537        });
538        let view = root
539            .read_with(cx, |root, _| root.view().clone())
540            .downcast::<Harness>()
541            .unwrap();
542        let changes = Rc::new(RefCell::new(Vec::new()));
543        cx.update(|window, cx| {
544            let state = view.read(cx).state.clone();
545            let changes = changes.clone();
546            cx.subscribe(&state, move |_, event: &RadioGroupEvent, _| {
547                let RadioGroupEvent::Change(value) = event;
548                changes.borrow_mut().push(value.clone());
549            })
550            .detach();
551            window.activate_window();
552            let before = view.read(cx).before.clone();
553            before.focus(window, cx);
554            window.draw(cx).clear(cx);
555        });
556        cx.run_until_parked();
557        (cx, view, changes)
558    }
559
560    fn draw(cx: &mut VisualTestContext) {
561        cx.update(|window, cx| window.draw(cx).clear(cx));
562    }
563
564    fn press(cx: &mut VisualTestContext, key: &str) {
565        let keystroke =
566            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
567        cx.simulate_event(KeyDownEvent {
568            keystroke: keystroke.clone(),
569            is_held: false,
570            prefer_character_input: false,
571        });
572        cx.simulate_event(KeyUpEvent { keystroke });
573        draw(cx);
574    }
575
576    fn assert_option(cx: &mut VisualTestContext, view: &Entity<Harness>, index: usize) {
577        cx.update(|window, cx| {
578            let state = view.read(cx).state.read(cx);
579            assert_eq!(state.selected_index(), Some(index));
580            assert!(state.option_focus_handle(index).is_focused(window));
581        });
582    }
583
584    #[gpui::test]
585    fn arrows_wrap_skip_disabled_and_keep_one_tab_stop(cx: &mut TestAppContext) {
586        let (cx, view, changes) = harness(cx, items(), Some("medium"));
587        cx.simulate_keystrokes("tab");
588        draw(cx);
589        assert_option(cx, &view, 2);
590        assert!(changes.borrow().is_empty());
591
592        for (key, index) in [
593            ("right", 3),
594            ("down", 0),
595            ("right", 2),
596            ("left", 0),
597            ("up", 3),
598        ] {
599            cx.simulate_keystrokes(key);
600            draw(cx);
601            assert_option(cx, &view, index);
602        }
603        assert_eq!(
604            *changes.borrow(),
605            ["large", "small", "medium", "small", "large"].map(SharedString::from)
606        );
607
608        cx.simulate_keystrokes("tab");
609        draw(cx);
610        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
611        cx.simulate_keystrokes("shift-tab");
612        draw(cx);
613        assert_option(cx, &view, 3);
614        cx.simulate_keystrokes("shift-tab");
615        draw(cx);
616        cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
617        cx.simulate_keystrokes("tab");
618        draw(cx);
619        assert_option(cx, &view, 3);
620        assert_eq!(changes.borrow().len(), 5);
621    }
622
623    #[gpui::test]
624    fn pointer_and_native_activation_select_once_without_deselecting(cx: &mut TestAppContext) {
625        let (cx, view, changes) = harness(cx, items(), None);
626        cx.simulate_keystrokes("tab");
627        draw(cx);
628        cx.update(|window, cx| {
629            let state = view.read(cx).state.read(cx);
630            assert_eq!(state.selected_index(), None);
631            assert!(state.option_focus_handle(0).is_focused(window));
632        });
633        press(cx, "space");
634        assert_option(cx, &view, 0);
635        press(cx, "space");
636        press(cx, "enter");
637        assert_eq!(*changes.borrow(), [SharedString::from("small")]);
638
639        // Each row is 32px high, following the 32px "Before" button.
640        cx.simulate_click(point(px(12.), px(112.)), Modifiers::default());
641        draw(cx);
642        assert_option(cx, &view, 2);
643        cx.simulate_click(point(px(12.), px(112.)), Modifiers::default());
644        draw(cx);
645        cx.simulate_click(point(px(12.), px(80.)), Modifiers::default());
646        draw(cx);
647        assert_option(cx, &view, 2);
648        assert_eq!(
649            *changes.borrow(),
650            [SharedString::from("small"), SharedString::from("medium")]
651        );
652    }
653
654    #[gpui::test]
655    fn programmatic_selection_preserves_focus_and_validates_without_user_events(
656        cx: &mut TestAppContext,
657    ) {
658        let (cx, view, changes) = harness(cx, items(), Some("small"));
659        cx.update(|window, cx| {
660            let state = view.read(cx).state.clone();
661            state.update(cx, |state, cx| {
662                assert!(state.set_selected_value(Some("large"), window, cx));
663                assert!(!state.set_selected_value(Some("missing"), window, cx));
664                assert!(!state.set_selected_value(Some("unavailable"), window, cx));
665                assert_eq!(state.selected_index(), Some(3));
666            });
667            assert!(view.read(cx).before.is_focused(window));
668        });
669        draw(cx);
670        cx.simulate_keystrokes("tab");
671        draw(cx);
672        assert_option(cx, &view, 3);
673
674        cx.update(|window, cx| {
675            let state = view.read(cx).state.clone();
676            state.update(cx, |state, cx| {
677                assert!(state.set_selected_value(Some("small"), window, cx));
678                assert!(state.set_selected_value(Some("small"), window, cx));
679                assert!(state.option_focus_handle(3).is_focused(window));
680            });
681            for index in [0, 3] {
682                let option = RadioOption::new(&state, index)
683                    .render(window, cx)
684                    .into_element();
685                let mut node = accesskit::Node::new(option.a11y_role().unwrap());
686                option.write_a11y_info(&mut node);
687                assert_eq!(
688                    node.toggled(),
689                    Some(if index == 0 {
690                        Toggled::True
691                    } else {
692                        Toggled::False
693                    })
694                );
695            }
696        });
697        draw(cx);
698        // An application update keeps one Tab stop while another option is focused.
699        cx.simulate_keystrokes("tab");
700        draw(cx);
701        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
702        cx.simulate_keystrokes("shift-tab");
703        draw(cx);
704        assert_option(cx, &view, 0);
705
706        cx.update(|window, cx| {
707            let state = view.read(cx).state.clone();
708            state.update(cx, |state, cx| {
709                assert!(state.set_selected_value(None, window, cx));
710                assert_eq!(state.selected_index(), None);
711                assert!(state.option_focus_handle(0).is_focused(window));
712                state.set_disabled(true, window, cx);
713                assert!(state.set_selected_value(Some("medium"), window, cx));
714                assert_eq!(state.selected_index(), Some(2));
715                assert!(state.option_focus_handle(0).is_focused(window));
716            });
717        });
718        draw(cx);
719        cx.simulate_keystrokes("tab");
720        draw(cx);
721        cx.update(|window, cx| {
722            assert!(view.read(cx).after.is_focused(window));
723            let state = view.read(cx).state.clone();
724            state.update(cx, |state, cx| state.set_disabled(false, window, cx));
725        });
726        draw(cx);
727        cx.simulate_keystrokes("shift-tab");
728        draw(cx);
729        assert_option(cx, &view, 2);
730        assert!(changes.borrow().is_empty());
731    }
732
733    #[gpui::test]
734    fn disabling_a_focused_group_preserves_exit_and_skips_it_on_reentry(cx: &mut TestAppContext) {
735        for backwards in [false, true] {
736            let (cx, view, changes) = harness(cx, items(), Some("small"));
737            cx.simulate_keystrokes("tab");
738            draw(cx);
739            cx.update(|window, cx| {
740                let state = view.read(cx).state.clone();
741                state.update(cx, |state, cx| state.set_disabled(true, window, cx));
742            });
743            draw(cx);
744            press(cx, "space");
745            press(cx, "enter");
746            cx.simulate_keystrokes("right");
747            draw(cx);
748            cx.simulate_click(point(px(12.), px(112.)), Modifiers::default());
749            draw(cx);
750            assert_option(cx, &view, 0);
751            assert!(changes.borrow().is_empty());
752
753            cx.simulate_keystrokes(if backwards { "shift-tab" } else { "tab" });
754            draw(cx);
755            cx.update(|window, cx| {
756                let view = view.read(cx);
757                let expected = if backwards { &view.before } else { &view.after };
758                assert!(expected.is_focused(window));
759            });
760            cx.simulate_keystrokes(if backwards { "tab" } else { "shift-tab" });
761            draw(cx);
762            cx.update(|window, cx| {
763                let view = view.read(cx);
764                let expected = if backwards { &view.after } else { &view.before };
765                assert!(expected.is_focused(window));
766                let state = view.state.clone();
767                state.update(cx, |state, cx| state.set_disabled(false, window, cx));
768            });
769            draw(cx);
770            cx.simulate_keystrokes(if backwards { "shift-tab" } else { "tab" });
771            draw(cx);
772            assert_option(cx, &view, 0);
773        }
774    }
775
776    #[gpui::test]
777    fn empty_and_all_disabled_groups_have_no_tab_stop(cx: &mut TestAppContext) {
778        for items in [
779            Vec::new(),
780            vec![RadioItem::new("only", "Only").disabled(true)],
781        ] {
782            let (cx, view, changes) = harness(cx, items, None);
783            cx.simulate_keystrokes("tab");
784            draw(cx);
785            cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
786            cx.simulate_keystrokes("shift-tab");
787            draw(cx);
788            cx.update(|window, cx| {
789                assert!(view.read(cx).before.is_focused(window));
790                assert!(view.read(cx).state.read(cx).selected_item().is_none());
791            });
792            assert!(changes.borrow().is_empty());
793        }
794    }
795
796    #[cfg(feature = "test-support")]
797    #[gpui::test]
798    fn group_and_options_expose_names_checked_and_disabled_state(cx: &mut TestAppContext) {
799        let (cx, view, _) = harness(cx, items(), Some("medium"));
800        cx.update(|window, _| {
801            let group = crate::test_support::find(window, &[], &"group".into()).unwrap();
802            assert_eq!(group.role(), Some(Role::RadioGroup));
803            assert_eq!(group.label(), Some("Size"));
804            for (index, label) in ["Small", "Unavailable", "Medium", "Large"]
805                .iter()
806                .enumerate()
807            {
808                let option =
809                    crate::test_support::find(window, &[], &("radio-option", index).into())
810                        .unwrap();
811                assert_eq!(option.role(), Some(Role::RadioButton));
812                assert_eq!(option.label(), Some(*label));
813                assert_eq!(option.checked(), Some(index == 2));
814                assert_eq!(option.disabled(), (index == 1).then_some(true));
815            }
816        });
817        cx.update(|window, cx| {
818            let state = view.read(cx).state.clone();
819            state.update(cx, |state, cx| state.set_disabled(true, window, cx));
820        });
821        draw(cx);
822        cx.update(|window, _| {
823            assert_eq!(
824                crate::test_support::find(window, &[], &"group".into())
825                    .unwrap()
826                    .disabled(),
827                Some(true)
828            );
829            for index in 0usize..4 {
830                assert_eq!(
831                    crate::test_support::find(window, &[], &("radio-option", index).into())
832                        .unwrap()
833                        .disabled(),
834                    Some(true)
835                );
836            }
837        });
838    }
839}