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 has_content = self.label.is_some() || !self.children.is_empty();
168        let indicator_size = rems(match self.size {
169            Size::XSmall => 0.75,
170            Size::Small => 0.875,
171            Size::Large => 1.125,
172            _ => 1.,
173        });
174        let focus_handle = window
175            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
176            .read(cx)
177            .clone();
178        let is_focused = focus_handle.is_focused(window);
179        let disabled = self.disabled;
180        let accessibility_label = self
181            .accessibility_label
182            .clone()
183            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
184
185        let (border_color, bg) = if checked {
186            (cx.theme().primary, cx.theme().primary)
187        } else {
188            (cx.theme().input, cx.theme().input.opacity(0.5))
189        };
190        let (border_color, bg) = if disabled {
191            (border_color.opacity(0.5), bg.opacity(0.5))
192        } else {
193            (border_color, bg)
194        };
195
196        self.base
197            .id(self.id.clone())
198            .checked(self.checked)
199            .disabled(self.disabled)
200            .track_focus(&focus_handle)
201            .tab_stop(self.tab_stop)
202            .tab_index(self.tab_index)
203            .when_some(accessibility_label, |this, label| {
204                this.accessibility_label(label)
205            })
206            .when_some(
207                self.position_in_set.zip(self.size_of_set),
208                |this, (position, size)| this.set_position(position, size),
209            )
210            .h_flex()
211            .gap_x_2()
212            .text_color(cx.theme().foreground)
213            .items_start()
214            .line_height(relative(1.))
215            .rounded(cx.theme().radius * 0.5)
216            .when(is_focused && self.focus_ring_enabled, |this| {
217                this.focus_ring_style(window, cx)
218            })
219            .map(|this| match self.size {
220                Size::XSmall => this.text_xs(),
221                Size::Small => this.text_sm(),
222                Size::Medium => this.text_base(),
223                Size::Large => this.text_lg(),
224                _ => this,
225            })
226            .refine_style(&self.style)
227            .child(
228                div()
229                    .relative()
230                    .size(indicator_size)
231                    // Center on the first 1.25em line, including when the label wraps.
232                    .when(has_content, |this| this.mt(indicator_size * 0.125))
233                    .flex_shrink_0()
234                    .rounded_full_style(cx)
235                    .border_1()
236                    .border_color(border_color)
237                    .map(|this| match self.checked {
238                        false => this.bg(cx.theme().input_background()),
239                        true if disabled => this.bg(bg),
240                        true => this.bg(cx.theme().tokens.primary),
241                    })
242                    .child(checkbox_check_icon(
243                        self.id, self.size, checked, disabled, window, cx,
244                    )),
245            )
246            .when(!self.children.is_empty() || self.label.is_some(), |this| {
247                this.child(
248                    v_flex()
249                        .w_full()
250                        .line_height(relative(1.25))
251                        .gap_1()
252                        .when_some(self.label, |this, label| {
253                            this.child(
254                                div()
255                                    .size_full()
256                                    .when(self.disabled, |this| {
257                                        this.text_color(cx.theme().muted_foreground)
258                                    })
259                                    .child(label),
260                            )
261                        })
262                        .children(self.children),
263                )
264            })
265            .on_mouse_down(gpui::MouseButton::Left, |_, window, _| {
266                window.prevent_default()
267            })
268            .when_some(self.on_click.clone(), |this, on_click| {
269                this.on_change(move |next, _, window, cx| {
270                    window.prevent_default();
271                    on_click(&next, window, cx);
272                })
273            })
274            .map(|this| self.tooltip.apply(this))
275    }
276}
277
278/// A Radio group element.
279#[derive(IntoElement)]
280pub struct RadioGroup {
281    id: ElementId,
282    style: StyleRefinement,
283    radios: Vec<Radio>,
284    layout: Axis,
285    selected_index: Option<usize>,
286    disabled: bool,
287    on_click: Option<Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>>,
288}
289
290impl RadioGroup {
291    /// Creates a radio group with vertical layout and no selected item.
292    pub fn new(id: impl Into<ElementId>) -> Self {
293        Self {
294            id: id.into(),
295            style: StyleRefinement::default().flex_1(),
296            on_click: None,
297            layout: Axis::Vertical,
298            selected_index: None,
299            disabled: false,
300            radios: vec![],
301        }
302    }
303
304    /// Create a new Radio group with default Vertical layout.
305    pub fn vertical(id: impl Into<ElementId>) -> Self {
306        Self::new(id)
307    }
308
309    /// Create a new Radio group with Horizontal layout.
310    pub fn horizontal(id: impl Into<ElementId>) -> Self {
311        Self::new(id).layout(Axis::Horizontal)
312    }
313
314    /// Set the layout of the Radio group. Default is `Axis::Vertical`.
315    pub fn layout(mut self, layout: Axis) -> Self {
316        self.layout = layout;
317        self
318    }
319
320    /// Alias for [`Self::on_change`]. The last callback registered with either name wins.
321    pub fn on_click(self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
322        self.on_change(handler)
323    }
324
325    /// Handle a requested selected index from pointer or keyboard activation.
326    ///
327    /// This is a controlled value: the owner must write the requested value and
328    /// call `cx.notify()` to render it. Disabled controls do not call the handler.
329    /// This and [`Self::on_click`] share one callback; chaining them replaces
330    /// the previous handler instead of calling both.
331    pub fn on_change(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
332        self.on_click = Some(Rc::new(handler));
333        self
334    }
335
336    /// Set the selected index.
337    pub fn selected_index(mut self, index: Option<usize>) -> Self {
338        self.selected_index = index;
339        self
340    }
341
342    /// Set the disabled state.
343    pub fn disabled(mut self, disabled: bool) -> Self {
344        self.disabled = disabled;
345        self
346    }
347
348    /// Add a child Radio element.
349    pub fn child(mut self, child: impl Into<Radio>) -> Self {
350        self.radios.push(child.into());
351        self
352    }
353
354    /// Add multiple child Radio elements.
355    pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Radio>>) -> Self {
356        self.radios.extend(children.into_iter().map(Into::into));
357        self
358    }
359}
360
361impl Styled for RadioGroup {
362    fn style(&mut self) -> &mut StyleRefinement {
363        &mut self.style
364    }
365}
366
367impl From<&'static str> for Radio {
368    fn from(label: &'static str) -> Self {
369        Self::new(label).label(label)
370    }
371}
372
373impl From<SharedString> for Radio {
374    fn from(label: SharedString) -> Self {
375        Self::new(label.clone()).label(label)
376    }
377}
378
379impl From<String> for Radio {
380    fn from(label: String) -> Self {
381        Self::new(SharedString::from(label.clone())).label(SharedString::from(label))
382    }
383}
384
385impl RenderOnce for RadioGroup {
386    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
387        let on_click = self.on_click;
388        let disabled = self.disabled;
389        let selected_ix = self.selected_index;
390
391        let base = if self.layout.is_vertical() {
392            v_flex()
393        } else {
394            h_flex().w_full().flex_wrap()
395        };
396
397        let total = self.radios.len();
398        BaseRadioGroup::new(self.id)
399            .axis(self.layout)
400            .refine_style(&self.style)
401            .child(
402                base.gap_3()
403                    .children(self.radios.into_iter().enumerate().map(|(ix, mut radio)| {
404                        let checked = selected_ix == Some(ix);
405
406                        radio.id = ix.into();
407                        radio.position_in_set = Some(ix + 1);
408                        radio.size_of_set = Some(total);
409                        radio.disabled(disabled).checked(checked).when_some(
410                            on_click.clone(),
411                            |this, on_click| {
412                                this.on_click(move |_, window, cx| on_click(&ix, window, cx))
413                            },
414                        )
415                    })),
416            )
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    #[test]
425    fn an_explicit_accessibility_label_replaces_the_visible_one() {
426        let plain = Radio::new("automatic").label("Automatic");
427        assert_eq!(plain.accessibility_label, None);
428        assert!(matches!(
429            &plain.label,
430            Some(Text::String(label)) if label.as_ref() == "Automatic"
431        ));
432
433        let named = Radio::new("automatic")
434            .label("Automatic")
435            .accessibility_label("Choose automatic mode");
436        assert_eq!(
437            named.accessibility_label.as_deref(),
438            Some("Choose automatic mode"),
439            "an explicit name must win over the visible label"
440        );
441        assert!(
442            matches!(
443                &named.label,
444                Some(Text::String(label)) if label.as_ref() == "Automatic"
445            ),
446            "and must not change what is drawn"
447        );
448    }
449}