Skip to main content

gpui_component/
radio.rs

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