Skip to main content

gpui_component/
radio.rs

1use std::rc::Rc;
2
3use crate::ThemeStyled as _;
4use crate::{
5    ActiveTheme, AxisExt, Sizable, Size, StyledExt, checkbox::checkbox_check_icon, h_flex,
6    text::Text, tooltip::ComponentTooltip, v_flex,
7};
8use gpui::ColorExt as _;
9use gpui::{
10    AnyElement, App, Axis, ElementId, InteractiveElement, IntoElement, ParentElement, RenderOnce,
11    SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div,
12    prelude::FluentBuilder, relative, rems,
13};
14use gpui_base::{Radio as BaseRadio, RadioGroup as BaseRadioGroup};
15
16/// A Radio element.
17///
18/// This is not included the Radio group implementation, you can manage the group by yourself.
19#[derive(IntoElement)]
20pub struct Radio {
21    base: BaseRadio,
22    style: StyleRefinement,
23    id: ElementId,
24    label: Option<Text>,
25    /// The announced name, when the visible label is not it.
26    accessibility_label: Option<SharedString>,
27    children: Vec<AnyElement>,
28    checked: bool,
29    disabled: bool,
30    tab_stop: bool,
31    tab_index: isize,
32    size: Size,
33    on_click: Option<Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
34    tooltip: ComponentTooltip,
35    position_in_set: Option<usize>,
36    size_of_set: Option<usize>,
37    focus_ring_enabled: bool,
38}
39
40impl Radio {
41    /// Create a new Radio element with the given id.
42    pub fn new(id: impl Into<ElementId>) -> Self {
43        let id = id.into();
44        Self {
45            base: BaseRadio::new(id.clone()),
46            id,
47            style: StyleRefinement::default(),
48            label: None,
49            accessibility_label: None,
50            children: Vec::new(),
51            checked: false,
52            disabled: false,
53            tab_index: 0,
54            tab_stop: true,
55            size: Size::default(),
56            on_click: None,
57            tooltip: ComponentTooltip::default(),
58            position_in_set: None,
59            size_of_set: None,
60            focus_ring_enabled: true,
61        }
62    }
63
64    /// Set tooltip text for the radio.
65    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
66        self.tooltip.text = Some((tooltip.into(), None));
67        self
68    }
69
70    /// Set the label of the Radio element.
71    pub fn label(mut self, label: impl Into<Text>) -> Self {
72        self.label = Some(label.into());
73        self
74    }
75
76    /// Set the name a screen reader announces, when the visible label is not
77    /// it.
78    ///
79    /// A radio's name comes from its [`label`](Self::label) by default. Setting
80    /// this replaces the announced name without changing what is displayed.
81    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
82        self.accessibility_label = Some(label.into());
83        self
84    }
85
86    /// Set the checked state of the Radio element, default is `false`.
87    pub fn checked(mut self, checked: bool) -> Self {
88        self.checked = checked;
89        self
90    }
91
92    /// Set the disabled state of the Radio element, default is `false`.
93    pub fn disabled(mut self, disabled: bool) -> Self {
94        self.disabled = disabled;
95        self
96    }
97
98    /// Set the tab index for the Radio element, default is `0`.
99    pub fn tab_index(mut self, tab_index: isize) -> Self {
100        self.tab_index = tab_index;
101        self
102    }
103
104    /// Set the tab stop for the Radio element, default is `true`.
105    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
106        self.tab_stop = tab_stop;
107        self
108    }
109
110    /// Add on_click handler when the Radio is clicked.
111    ///
112    /// The `&bool` parameter is the **new checked state**.
113    pub fn on_click(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
114        self.on_click = Some(Rc::new(handler));
115        self
116    }
117}
118
119impl Sizable for Radio {
120    fn with_size(mut self, size: impl Into<Size>) -> Self {
121        self.size = size.into();
122        self
123    }
124}
125
126impl crate::FocusableExt for Radio {
127    fn focus_ring(mut self, enabled: bool) -> Self {
128        self.focus_ring_enabled = enabled;
129        self
130    }
131
132    fn is_focus_ring_enabled(&self) -> bool {
133        self.focus_ring_enabled
134    }
135}
136
137impl Styled for Radio {
138    fn style(&mut self) -> &mut gpui::StyleRefinement {
139        &mut self.style
140    }
141}
142
143impl InteractiveElement for Radio {
144    fn interactivity(&mut self) -> &mut gpui::Interactivity {
145        self.base.interactivity()
146    }
147}
148
149impl StatefulInteractiveElement for Radio {}
150
151impl ParentElement for Radio {
152    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
153        self.children.extend(elements);
154    }
155}
156
157impl RenderOnce for Radio {
158    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
159        let checked = self.checked;
160        let focus_handle = window
161            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
162            .read(cx)
163            .clone();
164        let is_focused = focus_handle.is_focused(window);
165        let disabled = self.disabled;
166        let accessibility_label = self
167            .accessibility_label
168            .clone()
169            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
170
171        let (border_color, bg) = if checked {
172            (cx.theme().primary, cx.theme().primary)
173        } else {
174            (cx.theme().input, cx.theme().input.opacity(0.5))
175        };
176        let (border_color, bg) = if disabled {
177            (border_color.opacity(0.5), bg.opacity(0.5))
178        } else {
179            (border_color, bg)
180        };
181
182        self.base
183            .id(self.id.clone())
184            .checked(self.checked)
185            .disabled(self.disabled)
186            .track_focus(&focus_handle)
187            .tab_stop(self.tab_stop)
188            .tab_index(self.tab_index)
189            .when_some(accessibility_label, |this, label| {
190                this.accessibility_label(label)
191            })
192            .when_some(
193                self.position_in_set.zip(self.size_of_set),
194                |this, (position, size)| this.set_position(position, size),
195            )
196            .h_flex()
197            .gap_x_2()
198            .text_color(cx.theme().foreground)
199            .items_start()
200            .line_height(relative(1.))
201            .rounded(cx.theme().radius * 0.5)
202            .when(is_focused && self.focus_ring_enabled, |this| {
203                this.focus_ring_style(window, cx)
204            })
205            .map(|this| match self.size {
206                Size::XSmall => this.text_xs(),
207                Size::Small => this.text_sm(),
208                Size::Medium => this.text_base(),
209                Size::Large => this.text_lg(),
210                _ => this,
211            })
212            .refine_style(&self.style)
213            .child(
214                div()
215                    .relative()
216                    .map(|this| match self.size {
217                        Size::XSmall => this.size_3(),
218                        Size::Small => this.size_3p5(),
219                        Size::Medium => this.size_4(),
220                        Size::Large => this.size(rems(1.125)),
221                        _ => this.size_4(),
222                    })
223                    .flex_shrink_0()
224                    .rounded_full_style(cx)
225                    .border_1()
226                    .border_color(border_color)
227                    .map(|this| match self.checked {
228                        false => this.bg(cx.theme().input_background()),
229                        true if disabled => this.bg(bg),
230                        true => this.bg(cx.theme().tokens.primary),
231                    })
232                    .child(checkbox_check_icon(
233                        self.id, self.size, checked, disabled, window, cx,
234                    )),
235            )
236            .when(!self.children.is_empty() || self.label.is_some(), |this| {
237                this.child(
238                    v_flex()
239                        .w_full()
240                        .line_height(relative(1.2))
241                        .gap_1()
242                        .when_some(self.label, |this, label| {
243                            this.child(
244                                div()
245                                    .size_full()
246                                    .line_height(relative(1.))
247                                    .when(self.disabled, |this| {
248                                        this.text_color(cx.theme().muted_foreground)
249                                    })
250                                    .child(label),
251                            )
252                        })
253                        .children(self.children),
254                )
255            })
256            .on_mouse_down(gpui::MouseButton::Left, |_, window, _| {
257                window.prevent_default()
258            })
259            .when_some(self.on_click.clone(), |this, on_click| {
260                this.on_change(move |next, _, window, cx| {
261                    window.prevent_default();
262                    on_click(&next, window, cx);
263                })
264            })
265            .map(|this| self.tooltip.apply(this))
266    }
267}
268
269/// A Radio group element.
270#[derive(IntoElement)]
271pub struct RadioGroup {
272    id: ElementId,
273    style: StyleRefinement,
274    radios: Vec<Radio>,
275    layout: Axis,
276    selected_index: Option<usize>,
277    disabled: bool,
278    on_click: Option<Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>>,
279}
280
281impl RadioGroup {
282    fn new(id: impl Into<ElementId>) -> Self {
283        Self {
284            id: id.into(),
285            style: StyleRefinement::default().flex_1(),
286            on_click: None,
287            layout: Axis::Vertical,
288            selected_index: None,
289            disabled: false,
290            radios: vec![],
291        }
292    }
293
294    /// Create a new Radio group with default Vertical layout.
295    pub fn vertical(id: impl Into<ElementId>) -> Self {
296        Self::new(id)
297    }
298
299    /// Create a new Radio group with Horizontal layout.
300    pub fn horizontal(id: impl Into<ElementId>) -> Self {
301        Self::new(id).layout(Axis::Horizontal)
302    }
303
304    /// Set the layout of the Radio group. Default is `Axis::Vertical`.
305    pub fn layout(mut self, layout: Axis) -> Self {
306        self.layout = layout;
307        self
308    }
309
310    // Add on_click handler when selected index changes.
311    //
312    // The `&usize` parameter is the selected index.
313    pub fn on_click(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
314        self.on_click = Some(Rc::new(handler));
315        self
316    }
317
318    /// Set the selected index.
319    pub fn selected_index(mut self, index: Option<usize>) -> Self {
320        self.selected_index = index;
321        self
322    }
323
324    /// Set the disabled state.
325    pub fn disabled(mut self, disabled: bool) -> Self {
326        self.disabled = disabled;
327        self
328    }
329
330    /// Add a child Radio element.
331    pub fn child(mut self, child: impl Into<Radio>) -> Self {
332        self.radios.push(child.into());
333        self
334    }
335
336    /// Add multiple child Radio elements.
337    pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Radio>>) -> Self {
338        self.radios.extend(children.into_iter().map(Into::into));
339        self
340    }
341}
342
343impl Styled for RadioGroup {
344    fn style(&mut self) -> &mut StyleRefinement {
345        &mut self.style
346    }
347}
348
349impl From<&'static str> for Radio {
350    fn from(label: &'static str) -> Self {
351        Self::new(label).label(label)
352    }
353}
354
355impl From<SharedString> for Radio {
356    fn from(label: SharedString) -> Self {
357        Self::new(label.clone()).label(label)
358    }
359}
360
361impl From<String> for Radio {
362    fn from(label: String) -> Self {
363        Self::new(SharedString::from(label.clone())).label(SharedString::from(label))
364    }
365}
366
367impl RenderOnce for RadioGroup {
368    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
369        let on_click = self.on_click;
370        let disabled = self.disabled;
371        let selected_ix = self.selected_index;
372
373        let base = if self.layout.is_vertical() {
374            v_flex()
375        } else {
376            h_flex().w_full().flex_wrap()
377        };
378
379        let total = self.radios.len();
380        BaseRadioGroup::new(self.id)
381            .axis(self.layout)
382            .refine_style(&self.style)
383            .child(
384                base.gap_3()
385                    .children(self.radios.into_iter().enumerate().map(|(ix, mut radio)| {
386                        let checked = selected_ix == Some(ix);
387
388                        radio.id = ix.into();
389                        radio.position_in_set = Some(ix + 1);
390                        radio.size_of_set = Some(total);
391                        radio.disabled(disabled).checked(checked).when_some(
392                            on_click.clone(),
393                            |this, on_click| {
394                                this.on_click(move |_, window, cx| on_click(&ix, window, cx))
395                            },
396                        )
397                    })),
398            )
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn an_explicit_accessibility_label_replaces_the_visible_one() {
408        let plain = Radio::new("automatic").label("Automatic");
409        assert_eq!(plain.accessibility_label, None);
410        assert!(matches!(
411            &plain.label,
412            Some(Text::String(label)) if label.as_ref() == "Automatic"
413        ));
414
415        let named = Radio::new("automatic")
416            .label("Automatic")
417            .accessibility_label("Choose automatic mode");
418        assert_eq!(
419            named.accessibility_label.as_deref(),
420            Some("Choose automatic mode"),
421            "an explicit name must win over the visible label"
422        );
423        assert!(
424            matches!(
425                &named.label,
426                Some(Text::String(label)) if label.as_ref() == "Automatic"
427            ),
428            "and must not change what is drawn"
429        );
430    }
431}