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