Skip to main content

gpui_material_components/selection/
radio.rs

1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Axis, ElementId, Entity, FocusHandle, Hsla,
5    InteractiveElement, IntoElement, ParentElement, RenderOnce, SharedString,
6    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Radio as BaseRadio, RadioGroup as BaseRadioGroup, TestSupportExt};
9use gpui_material_foundation::{
10    InteractionSource, ThemeScope, animate, current_material_theme, move_roving_focus,
11};
12use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpeed};
13
14use crate::action::{feedback_target, ripple_state, ripple_target};
15
16use super::{focus_style, row, selection_label, selection_target, selection_tone, tone};
17
18type RadioChange = Rc<dyn Fn(&ElementId, &mut Window, &mut App)>;
19
20/// Radio indicator pigments. Omitted values use the current window theme.
21#[derive(Clone, Copy, Debug, Default, PartialEq)]
22pub struct RadioColors {
23    /// Ring and inner dot color when enabled and selected.
24    pub selected: Option<Hsla>,
25    /// Ring color when enabled and unselected.
26    pub unselected: Option<Hsla>,
27    /// Ring and inner dot color when disabled and selected.
28    pub disabled_selected: Option<Hsla>,
29    /// Ring color when disabled and unselected.
30    pub disabled_unselected: Option<Hsla>,
31}
32
33impl RadioColors {
34    fn resolve(self, selected: bool, disabled: bool, window: &Window, cx: &App) -> Hsla {
35        match (selected, disabled) {
36            (true, false) => self.selected,
37            (false, false) => self.unselected,
38            (true, true) => self.disabled_selected,
39            (false, true) => self.disabled_unselected,
40        }
41        .unwrap_or_else(|| selection_tone(selected, disabled, window, cx))
42    }
43}
44
45/// A radio option. A group owns the tab stop and the caller owns selection.
46#[derive(IntoElement)]
47pub struct Radio {
48    id: ElementId,
49    label: SharedString,
50    show_label: bool,
51    label_content: Option<AnyElement>,
52    selected: bool,
53    disabled: bool,
54    on_select: Option<crate::action::Activate>,
55    colors: RadioColors,
56    focus: Option<FocusHandle>,
57    interaction_source: Option<Entity<InteractionSource>>,
58    decorative: bool,
59}
60
61impl Radio {
62    /// Creates a radio option with an element ID and visible/accessible label.
63    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
64        Self {
65            id: id.into(),
66            label: label.into(),
67            show_label: true,
68            label_content: None,
69            selected: false,
70            disabled: false,
71            on_select: None,
72            colors: RadioColors::default(),
73            focus: None,
74            interaction_source: None,
75            decorative: false,
76        }
77    }
78
79    #[cfg(feature = "surfaces")]
80    pub(crate) fn decorative(mut self, decorative: bool) -> Self {
81        self.decorative = decorative;
82        self
83    }
84
85    /// Controls whether the visible label is rendered. Defaults to `true`.
86    /// When `false`, the constructor's label remains the accessible name and the trailing gap is omitted.
87    pub fn show_label(mut self, show: bool) -> Self {
88        self.show_label = show;
89        self
90    }
91
92    /// Replaces the visible label while keeping the constructor's label as the accessible name.
93    pub fn label_content(mut self, content: impl IntoElement) -> Self {
94        self.label_content = Some(content.into_any_element());
95        self
96    }
97
98    /// Sets the controlled selected state of a standalone radio button.
99    pub fn selected(mut self, selected: bool) -> Self {
100        self.selected = selected;
101        self
102    }
103
104    /// Disables selection and keyboard focus for this option when `true`.
105    pub fn disabled(mut self, disabled: bool) -> Self {
106        self.disabled = disabled;
107        self
108    }
109
110    /// Invoked when this standalone radio option is selected.
111    pub fn on_select(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
112        self.on_select = Some(Rc::new(handler));
113        self
114    }
115
116    /// Overrides indicator colors for the four enabled and selected combinations.
117    pub fn colors(mut self, colors: RadioColors) -> Self {
118        self.colors = colors;
119        self
120    }
121
122    /// Uses the caller's focus handle instead of an internal keyed handle, both standalone and
123    /// inside a [`RadioGroup`].
124    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
125        self.focus = Some(focus.clone());
126        self
127    }
128
129    /// Observes hover, press, keyboard focus, and disabled state.
130    /// Group options are observed under their rendered, group-scoped IDs.
131    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
132        self.interaction_source = Some(source.clone());
133        self
134    }
135
136    fn render_indicator(&self, window: &mut Window, cx: &mut App) -> (Hsla, gpui::Div) {
137        let motion = current_material_theme(window, cx).motion;
138        let reduced = self.disabled || cx.reduce_motion();
139        let dot = animate(
140            (self.id.clone(), "radio-dot"),
141            f32::from(self.selected),
142            motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced),
143            window,
144            cx,
145        )
146        .clamp(0., 1.);
147        let tint = animate(
148            (self.id.clone(), "radio-color"),
149            f32::from(self.selected),
150            motion.spec(MotionKind::Effects, MotionSpeed::Fast, reduced),
151            window,
152            cx,
153        )
154        .clamp(0., 1.);
155        let accent = crate::motion::mix(
156            self.colors.resolve(false, self.disabled, window, cx),
157            self.colors.resolve(true, self.disabled, window, cx),
158            tint,
159        );
160        let indicator = div()
161            .size(px(20.))
162            .rounded_full()
163            .border_2()
164            .border_color(accent)
165            .flex()
166            .items_center()
167            .justify_center()
168            .child(div().size(px(10. * dot)).rounded_full().bg(accent));
169        (accent, indicator)
170    }
171
172    fn render_control(
173        self,
174        focus: Option<FocusHandle>,
175        position: Option<(usize, usize)>,
176        tab_stop: bool,
177        window: &mut Window,
178        cx: &mut App,
179    ) -> BaseRadio {
180        let (accent, indicator) = self.render_indicator(window, cx);
181        let direction = current_material_theme(window, cx).layout.direction;
182        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
183        let focus = focus.or(self.focus).unwrap_or_else(|| {
184            // Match Base's standalone focus ID so changing the source retains focus.
185            window
186                .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
187                .read(cx)
188                .clone()
189        });
190        let tracker = self
191            .interaction_source
192            .as_ref()
193            .map(|source| InteractionSource::track(source, &self.id, window, cx));
194        let observed = tracker.is_some();
195        ripple
196            .borrow_mut()
197            .track(!self.disabled, &focus, tracker, window, cx);
198        let group: SharedString = format!("material-radio/{}", self.id).into();
199        let radio = BaseRadio::new(self.id)
200            .when(!self.disabled, |control| {
201                if observed {
202                    feedback_target(control, ripple.clone(), true, Some(focus.clone()))
203                } else {
204                    ripple_target(control, ripple.clone())
205                }
206            })
207            .checked(self.selected)
208            .disabled(self.disabled)
209            .tab_stop(tab_stop)
210            .accessibility_label(self.label.clone())
211            .group(group.clone())
212            .border_2()
213            .border_color(gpui::transparent_black())
214            .rounded_md()
215            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
216            .child(
217                row(direction, self.show_label)
218                    .child(selection_target(
219                        group,
220                        indicator,
221                        accent,
222                        !self.disabled,
223                        ripple,
224                        direction,
225                        cx.reduce_motion(),
226                    ))
227                    .children(self.show_label.then(|| {
228                        selection_label(self.label, self.label_content, self.disabled, window, cx)
229                    })),
230            )
231            .track_focus(&focus)
232            .when_some(position, |radio, (position, size)| {
233                radio.set_position(position, size)
234            });
235        match self.on_select {
236            Some(handler) if !self.disabled => {
237                let handler = Rc::new(ThemeScope::bind_action(
238                    move |window, cx| handler(window, cx),
239                    window,
240                    cx,
241                ));
242                let select = handler.clone();
243                radio
244                    .when(!self.selected, |radio| {
245                        radio.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
246                            select(window, cx)
247                        })
248                    })
249                    .on_change(move |_, _, window, cx| handler(window, cx))
250            }
251            _ => radio,
252        }
253    }
254}
255
256impl RenderOnce for Radio {
257    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
258        if self.decorative {
259            let (_, indicator) = self.render_indicator(window, cx);
260            return div()
261                .id(self.id)
262                .test_support()
263                .flex_none()
264                .size(px(24.))
265                .flex()
266                .items_center()
267                .justify_center()
268                .child(indicator)
269                .into_any_element();
270        }
271        self.render_control(None, None, true, window, cx)
272            .into_any_element()
273    }
274}
275
276/// A controlled single-selection group with one Tab stop and directional navigation.
277#[derive(IntoElement)]
278pub struct RadioGroup {
279    id: ElementId,
280    label: SharedString,
281    selected: Option<ElementId>,
282    options: Vec<Radio>,
283    axis: Axis,
284    on_select: Option<RadioChange>,
285}
286
287impl RadioGroup {
288    /// Creates an empty vertical radio group with an element ID and accessible group label.
289    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
290        Self {
291            id: id.into(),
292            label: label.into(),
293            selected: None,
294            options: Vec::new(),
295            axis: Axis::Vertical,
296            on_select: None,
297        }
298    }
299
300    /// Sets the ID of the currently selected option.
301    pub fn selected(mut self, selected: impl Into<ElementId>) -> Self {
302        self.selected = Some(selected.into());
303        self
304    }
305
306    /// Appends [`Radio`] options to the group.
307    pub fn options(mut self, options: impl IntoIterator<Item = Radio>) -> Self {
308        self.options.extend(options);
309        self
310    }
311
312    /// Sets the layout and arrow-key navigation axis (`Axis::Vertical` by default).
313    pub fn axis(mut self, axis: Axis) -> Self {
314        self.axis = axis;
315        self
316    }
317
318    /// Invoked with the selected option's ID when selection changes via click or arrow keys.
319    pub fn on_select(
320        mut self,
321        handler: impl Fn(&ElementId, &mut Window, &mut App) + 'static,
322    ) -> Self {
323        self.on_select = Some(Rc::new(handler));
324        self
325    }
326}
327
328impl RenderOnce for RadioGroup {
329    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
330        let direction = current_material_theme(window, cx).layout.direction;
331        let current = self
332            .options
333            .iter()
334            .position(|item| !item.disabled && Some(&item.id) == self.selected.as_ref());
335        let tab_stop = current.or_else(|| self.options.iter().position(|item| !item.disabled));
336        let size = self.options.len();
337        let focus: Vec<_> = self
338            .options
339            .iter()
340            .map(|item| {
341                if let Some(focus) = &item.focus {
342                    focus.clone()
343                } else {
344                    let id = ElementId::from((self.id.clone(), "radio-focus"));
345                    window.with_id(id, |window| {
346                        window
347                            .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
348                            .read(cx)
349                            .clone()
350                    })
351                }
352            })
353            .collect();
354        let navigation: Vec<_> = self
355            .options
356            .iter()
357            .zip(&focus)
358            .map(|(item, focus)| (item.id.clone(), focus.clone(), !item.disabled))
359            .collect();
360        let change = self.on_select.clone().map(|change| {
361            let pending = Rc::new(RefCell::new(None::<ElementId>));
362            let pending_arg = pending.clone();
363            let bound = ThemeScope::bind_action(
364                move |window, cx| {
365                    if let Some(id) = pending_arg.borrow_mut().take() {
366                        change(&id, window, cx);
367                    }
368                },
369                window,
370                cx,
371            );
372            move |id: &ElementId, window: &mut Window, cx: &mut App| {
373                *pending.borrow_mut() = Some(id.clone());
374                bound(window, cx);
375            }
376        });
377        let selected = self.selected.clone();
378        let axis = self.axis;
379        let group = BaseRadioGroup::new(self.id.clone())
380            .axis(axis)
381            .aria_label(self.label)
382            .flex()
383            .gap_1()
384            .when(axis == Axis::Vertical, Styled::flex_col)
385            .when(axis == Axis::Horizontal, Styled::flex_wrap)
386            .when(
387                axis == Axis::Horizontal && direction == Direction::Rtl,
388                Styled::flex_row_reverse,
389            )
390            .on_key_down(move |event, window, cx| {
391                let items: Vec<_> = navigation
392                    .iter()
393                    .map(|(_, focus, enabled)| (focus, *enabled))
394                    .collect();
395                let Some(ix) =
396                    move_roving_focus(&items, &event.keystroke.key, axis, direction, window, cx)
397                else {
398                    return;
399                };
400                cx.stop_propagation();
401                if let Some(change) = &change
402                    && Some(&navigation[ix].0) != selected.as_ref()
403                {
404                    change(&navigation[ix].0, window, cx);
405                }
406            });
407
408        group.children(self.options.into_iter().zip(focus).enumerate().map(
409            |(ix, (mut radio, focus))| {
410                let option_id = radio.id.clone();
411                radio.id = ElementId::from((self.id.clone(), option_id.to_string()));
412                radio.selected = Some(&option_id) == self.selected.as_ref();
413                let handler = self.on_select.clone();
414                radio.on_select = handler.map(|handler| {
415                    let callback: crate::action::Activate =
416                        Rc::new(move |window, cx| handler(&option_id, window, cx));
417                    callback
418                });
419                radio.render_control(
420                    Some(focus),
421                    Some((ix + 1, size)),
422                    Some(ix) == tab_stop,
423                    window,
424                    cx,
425                )
426            },
427        ))
428    }
429}