Skip to main content

gpui_material_components/selection/
radio.rs

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