Skip to main content

gpui_material_components/selection/
radio.rs

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