Skip to main content

gpui_base/
radio.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ClickEvent, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
5    IntoElement, ParentElement, Refineable as _, RenderOnce, Role, SharedString, Stateful,
6    StatefulInteractiveElement, StyleRefinement, Styled, Toggled, Window, div,
7    prelude::FluentBuilder as _,
8};
9use smallvec::SmallVec;
10
11use crate::{
12    StateStyle, StyledExt as _, TestSupportExt as _,
13    a11y_disabled::A11yDisabledExt as _,
14    radio_group::{ChangeHandler, RadioEntry, RadioRegistry},
15};
16
17/// An unstyled radio control that owns activation, focus, and accessibility behavior.
18///
19/// The application owns its indicator, label, layout, colors, and state styling.
20/// Selection is controlled through [`Radio::checked`]; activating an unchecked
21/// radio requests `true` through [`Radio::on_change`].
22#[derive(IntoElement)]
23pub struct Radio {
24    id: ElementId,
25    base: Stateful<Div>,
26    style: StyleRefinement,
27    semantic_styles: RadioStyles,
28    checked: bool,
29    disabled: bool,
30    children: SmallVec<[AnyElement; 2]>,
31    on_change: Option<ChangeHandler>,
32    accessibility_label: Option<SharedString>,
33    tab_index: isize,
34    tab_stop: bool,
35    provided_focus_handle: Option<FocusHandle>,
36    position_in_set: Option<usize>,
37    size_of_set: Option<usize>,
38}
39
40/// Semantic root styles supported by [`Radio`].
41#[derive(Default)]
42pub struct RadioStyles {
43    checked: StyleRefinement,
44    disabled: StyleRefinement,
45}
46
47impl RadioStyles {
48    pub fn checked(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
49        self.checked
50            .refine(&build(StateStyle::default()).into_refinement());
51        self
52    }
53
54    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
55        self.disabled
56            .refine(&build(StateStyle::default()).into_refinement());
57        self
58    }
59}
60
61impl Radio {
62    pub fn new(id: impl Into<ElementId>) -> Self {
63        let id = id.into();
64        Self {
65            base: div().id(id.clone()),
66            id,
67            style: StyleRefinement::default(),
68            semantic_styles: RadioStyles::default(),
69            checked: false,
70            disabled: false,
71            children: SmallVec::new(),
72            on_change: None,
73            accessibility_label: None,
74            tab_index: 0,
75            tab_stop: true,
76            provided_focus_handle: None,
77            position_in_set: None,
78            size_of_set: None,
79        }
80    }
81
82    /// Updates the element identity used when the radio is rendered.
83    ///
84    /// A group that assigns positional ids after construction needs this so
85    /// each radio keeps a distinct element identity.
86    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
87        let id = id.into();
88        self.base.interactivity().element_id = Some(id.clone());
89        self.id = id;
90        self
91    }
92
93    pub fn checked(mut self, checked: bool) -> Self {
94        self.checked = checked;
95        self
96    }
97
98    pub fn disabled(mut self, disabled: bool) -> Self {
99        self.disabled = disabled;
100        self
101    }
102
103    /// Configures application-owned styles for the radio's semantic states.
104    pub fn styles(mut self, build: impl FnOnce(RadioStyles) -> RadioStyles) -> Self {
105        self.semantic_styles = build(self.semantic_styles);
106        self
107    }
108
109    fn resolved_style(&self) -> StyleRefinement {
110        crate::state_style::resolve_style(
111            &self.style,
112            [
113                self.checked.then_some(&self.semantic_styles.checked),
114                self.disabled.then_some(&self.semantic_styles.disabled),
115            ]
116            .into_iter()
117            .flatten(),
118        )
119    }
120
121    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
122        self.accessibility_label = Some(label.into());
123        self
124    }
125
126    /// Handles a requested selection change.
127    ///
128    /// The callback receives `true`. Activating an already checked radio is a
129    /// no-op because a radio cannot deselect itself.
130    pub fn on_change(
131        mut self,
132        handler: impl Fn(bool, &ClickEvent, &mut Window, &mut App) + 'static,
133    ) -> Self {
134        self.on_change = Some(Rc::new(handler));
135        self
136    }
137
138    /// Uses a caller-owned focus handle instead of creating keyed state.
139    ///
140    /// A styled radio needs this to draw its own focus ring from the same
141    /// handle the primitive tracks.
142    pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
143        self.provided_focus_handle = Some(focus_handle.clone());
144        self
145    }
146
147    /// Sets this radio's one-based position and its group's total size, so
148    /// assistive technology can announce "option 2 of 5".
149    pub fn set_position(mut self, position: usize, size: usize) -> Self {
150        self.position_in_set = Some(position);
151        self.size_of_set = Some(size);
152        self
153    }
154
155    pub fn tab_index(mut self, tab_index: isize) -> Self {
156        self.tab_index = tab_index;
157        self
158    }
159
160    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
161        self.tab_stop = tab_stop;
162        self
163    }
164
165    fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
166        self.provided_focus_handle.clone().unwrap_or_else(|| {
167            window
168                .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
169                .read(cx)
170                .clone()
171        })
172    }
173}
174
175impl Styled for Radio {
176    fn style(&mut self) -> &mut StyleRefinement {
177        &mut self.style
178    }
179}
180
181impl ParentElement for Radio {
182    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
183        self.children.extend(elements);
184    }
185}
186
187impl InteractiveElement for Radio {
188    fn interactivity(&mut self) -> &mut Interactivity {
189        self.base.interactivity()
190    }
191}
192
193impl StatefulInteractiveElement for Radio {}
194
195impl RenderOnce for Radio {
196    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
197        let focus_handle = self.focus_handle(window, cx);
198        let disabled = self.disabled;
199        let checked = self.checked;
200        let style = self.resolved_style();
201        let on_change = self.on_change;
202
203        // Join the enclosing radio group, if any. The group owns the single
204        // tab stop and the arrow keys, so it overrides this radio's own
205        // tab order settings.
206        let (tab_index, tab_stop) = match RadioRegistry::current() {
207            Some(registry) => {
208                let mut registry = registry.borrow_mut();
209                registry.register(RadioEntry {
210                    focus_handle: focus_handle.clone(),
211                    checked,
212                    disabled,
213                    on_change: on_change.clone(),
214                });
215                (0, registry.is_stop(&focus_handle))
216            }
217            None => (self.tab_index, self.tab_stop),
218        };
219
220        self.base
221            .test_support()
222            .role(Role::RadioButton)
223            .aria_toggled(if checked {
224                Toggled::True
225            } else {
226                Toggled::False
227            })
228            // A radio is both "toggled" and "selected"; different assistive
229            // technology reads one or the other, so state both rather than
230            // making callers choose.
231            .aria_selected(checked)
232            .when_some(self.accessibility_label, |this, label| {
233                this.aria_label(label)
234            })
235            .when_some(self.position_in_set, |this, position| {
236                this.aria_position_in_set(position)
237            })
238            .when_some(self.size_of_set, |this, size| this.aria_size_of_set(size))
239            // Keep the current focus in the dispatch tree when activation
240            // disables this control, so Tab can still leave in either direction.
241            .when(!disabled || focus_handle.is_focused(window), |this| {
242                this.track_focus(
243                    &focus_handle
244                        .tab_index(tab_index)
245                        .tab_stop(tab_stop && !disabled),
246                )
247            })
248            .when_some(
249                (!disabled && !checked).then_some(on_change).flatten(),
250                |this, on_change| {
251                    this.on_click(move |event, window, cx| {
252                        on_change(!checked, event, window, cx);
253                    })
254                },
255            )
256            .children(self.children)
257            .refine_style(&style)
258            .a11y_disabled(disabled)
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use std::{
266        cell::Cell,
267        rc::Rc,
268        sync::{Arc, Mutex},
269    };
270
271    use gpui::{
272        Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
273        TestAppContext, VisualTestContext, accesskit, canvas, point, px,
274    };
275
276    #[test]
277    fn semantic_state_styles_are_available_to_applications() {
278        let _ = Radio::new("states").styles(|styles| {
279            styles
280                .checked(|style| style.opacity(0.8))
281                .disabled(|style| {
282                    style
283                        .opacity(0.5)
284                        .when(true, |style| style.border_1())
285                        .when_some(Some(0.4), |style, opacity| style.opacity(opacity))
286                        .when_none(&None::<f32>, |style| style.rounded_sm())
287                })
288        });
289    }
290
291    #[test]
292    fn semantic_root_styles_follow_radio_priority() {
293        let styled = |radio: Radio| {
294            radio.styles(|styles| {
295                styles
296                    .checked(|style| style.opacity(0.8))
297                    .disabled(|style| style.opacity(0.5))
298            })
299        };
300
301        assert_eq!(styled(Radio::new("normal")).resolved_style().opacity, None);
302        assert_eq!(
303            styled(Radio::new("checked").checked(true))
304                .resolved_style()
305                .opacity,
306            Some(0.8)
307        );
308        assert_eq!(
309            styled(Radio::new("checked-disabled").checked(true).disabled(true))
310                .resolved_style()
311                .opacity,
312            Some(0.5)
313        );
314        assert_eq!(
315            styled(
316                Radio::new("state-over-instance")
317                    .checked(true)
318                    .disabled(true)
319                    .opacity(0.9),
320            )
321            .resolved_style()
322            .opacity,
323            Some(0.5)
324        );
325    }
326
327    struct RadioHarness {
328        checked: bool,
329        disabled: bool,
330        changes: Rc<Cell<usize>>,
331        keyboard_changes: Rc<Cell<usize>>,
332    }
333
334    impl Render for RadioHarness {
335        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
336            let changes = self.changes.clone();
337            let keyboard_changes = self.keyboard_changes.clone();
338            Radio::new("radio")
339                .checked(self.checked)
340                .disabled(self.disabled)
341                .size(px(100.))
342                .on_change(move |checked, event, _, _| {
343                    assert!(checked);
344                    changes.set(changes.get() + 1);
345                    if matches!(event, ClickEvent::Keyboard(_)) {
346                        keyboard_changes.set(keyboard_changes.get() + 1);
347                    }
348                })
349        }
350    }
351
352    fn harness(
353        cx: &mut TestAppContext,
354        checked: bool,
355        disabled: bool,
356    ) -> (&mut VisualTestContext, Rc<Cell<usize>>, Rc<Cell<usize>>) {
357        let changes = Rc::new(Cell::new(0));
358        let keyboard_changes = Rc::new(Cell::new(0));
359        let (_, cx) = cx.add_window_view({
360            let changes = changes.clone();
361            let keyboard_changes = keyboard_changes.clone();
362            move |_, _| RadioHarness {
363                checked,
364                disabled,
365                changes,
366                keyboard_changes,
367            }
368        });
369        cx.update(|window, cx| window.draw(cx).clear(cx));
370        (cx, changes, keyboard_changes)
371    }
372
373    #[gpui::test]
374    fn pointer_and_keyboard_activation_fire_once(cx: &mut TestAppContext) {
375        let (cx, changes, keyboard_changes) = harness(cx, false, false);
376        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
377        assert_eq!(changes.get(), 1);
378
379        changes.set(0);
380        cx.update(|window, cx| window.draw(cx).clear(cx));
381        for key in ["enter", "space"] {
382            let keystroke = Keystroke::parse(key).unwrap();
383            cx.simulate_event(KeyDownEvent {
384                keystroke: keystroke.clone(),
385                is_held: false,
386                prefer_character_input: false,
387            });
388            cx.simulate_event(KeyUpEvent { keystroke });
389        }
390        assert_eq!(changes.get(), 2);
391        assert_eq!(keyboard_changes.get(), 2);
392    }
393
394    #[gpui::test]
395    fn checked_and_disabled_radios_are_inert(cx: &mut TestAppContext) {
396        for (checked, disabled) in [(true, false), (false, true)] {
397            let (cx, changes, _) = harness(cx, checked, disabled);
398            cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
399            cx.simulate_keystrokes("enter space");
400            assert_eq!(changes.get(), 0);
401        }
402    }
403
404    #[gpui::test]
405    fn accessibility_exposes_role_state_and_action(cx: &mut TestAppContext) {
406        type Captured = Arc<Mutex<Option<accesskit::Node>>>;
407        struct Probe(Captured);
408        impl Render for Probe {
409            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
410                let captured = self.0.clone();
411                canvas(
412                    move |_, window, cx| {
413                        let mut node = accesskit::Node::new(Role::RadioButton);
414                        Radio::new("probe")
415                            .checked(true)
416                            .accessibility_label("Choice")
417                            .render(window, cx)
418                            .into_element()
419                            .write_a11y_info(&mut node);
420                        *captured.lock().unwrap() = Some(node);
421                    },
422                    |_, _, _, _| {},
423                )
424            }
425        }
426        let captured: Captured = Arc::new(Mutex::new(None));
427        let result = captured.clone();
428        let (_, cx) = cx.add_window_view(move |_, _| Probe(captured));
429        cx.update(|window, cx| window.draw(cx).clear(cx));
430        let node = result.lock().unwrap().take().unwrap();
431        assert_eq!(node.role(), Role::RadioButton);
432        assert_eq!(node.label(), Some("Choice"));
433        assert_eq!(node.toggled(), Some(Toggled::True));
434        assert!(!node.supports_action(accesskit::Action::Click));
435    }
436}