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