Skip to main content

gpui_material_components/selection/
radio.rs

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