Skip to main content

gpui_component/
radio.rs

1use std::rc::Rc;
2
3use crate::{
4    ActiveTheme, AxisExt, Sizable, Size, StyledExt, checkbox::checkbox_check_icon, h_flex,
5    text::Text, tooltip::ComponentTooltip, v_flex,
6};
7use crate::{StyleSized as _, ThemeStyled as _};
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    /// Alias for [`Self::on_change`]. The last callback registered with either name wins.
111    pub fn on_click(self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
112        self.on_change(handler)
113    }
114
115    /// Handle a requested checked value from pointer or keyboard activation.
116    ///
117    /// This is a controlled value: the owner must write the requested value and
118    /// call `cx.notify()` to render it. Disabled controls do not call the handler.
119    /// This and [`Self::on_click`] share one callback; chaining them replaces
120    /// the previous handler instead of calling both.
121    pub fn on_change(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
122        self.on_click = Some(Rc::new(handler));
123        self
124    }
125}
126
127impl Sizable for Radio {
128    fn with_size(mut self, size: impl Into<Size>) -> Self {
129        self.size = size.into();
130        self
131    }
132}
133
134impl crate::FocusableExt for Radio {
135    fn focus_ring(mut self, enabled: bool) -> Self {
136        self.focus_ring_enabled = enabled;
137        self
138    }
139
140    fn is_focus_ring_enabled(&self) -> bool {
141        self.focus_ring_enabled
142    }
143}
144
145impl Styled for Radio {
146    fn style(&mut self) -> &mut gpui::StyleRefinement {
147        &mut self.style
148    }
149}
150
151impl InteractiveElement for Radio {
152    fn interactivity(&mut self) -> &mut gpui::Interactivity {
153        self.base.interactivity()
154    }
155}
156
157impl StatefulInteractiveElement for Radio {}
158
159impl ParentElement for Radio {
160    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
161        self.children.extend(elements);
162    }
163}
164
165impl RenderOnce for Radio {
166    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
167        let checked = self.checked;
168        let has_content = self.label.is_some() || !self.children.is_empty();
169        let indicator_size = rems(match self.size {
170            Size::XSmall => 0.75,
171            Size::Small => 0.875,
172            Size::Large => 1.125,
173            _ => 1.,
174        });
175        let focus_handle = window
176            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
177            .read(cx)
178            .clone();
179        let is_focused = focus_handle.is_focused(window);
180        let disabled = self.disabled;
181        let accessibility_label = self
182            .accessibility_label
183            .clone()
184            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
185
186        let (border_color, bg) = if checked {
187            (cx.theme().primary, cx.theme().primary)
188        } else {
189            (cx.theme().input, cx.theme().input.opacity(0.5))
190        };
191        let (border_color, bg) = if disabled {
192            (border_color.opacity(0.5), bg.opacity(0.5))
193        } else {
194            (border_color, bg)
195        };
196
197        self.base
198            .id(self.id.clone())
199            .checked(self.checked)
200            .disabled(self.disabled)
201            .track_focus(&focus_handle)
202            .tab_stop(self.tab_stop)
203            .tab_index(self.tab_index)
204            .when_some(accessibility_label, |this, label| {
205                this.accessibility_label(label)
206            })
207            .when_some(
208                self.position_in_set.zip(self.size_of_set),
209                |this, (position, size)| this.set_position(position, size),
210            )
211            .h_flex()
212            .gap_x_2()
213            .text_color(cx.theme().foreground)
214            .items_start()
215            .line_height(relative(1.))
216            .rounded(cx.theme().radius * 0.5)
217            .when(is_focused && self.focus_ring_enabled, |this| {
218                this.focus_ring_style(window, cx)
219            })
220            .map(|this| match self.size {
221                Size::Size(_) => this,
222                size => this.input_text_size(size),
223            })
224            .refine_style(&self.style)
225            .child(
226                div()
227                    .relative()
228                    .size(indicator_size)
229                    // Center on the first 1.25em line, including when the label wraps.
230                    .when(has_content, |this| this.mt(indicator_size * 0.125))
231                    .flex_shrink_0()
232                    .rounded_full_style(cx)
233                    .border_1()
234                    .border_color(border_color)
235                    .map(|this| match self.checked {
236                        false => this.bg(cx.theme().input_background()),
237                        true if disabled => this.bg(bg),
238                        true => this.bg(cx.theme().tokens.primary),
239                    })
240                    .child(checkbox_check_icon(
241                        self.id, self.size, checked, disabled, window, cx,
242                    )),
243            )
244            .when(!self.children.is_empty() || self.label.is_some(), |this| {
245                this.child(
246                    v_flex()
247                        .w_full()
248                        .line_height(relative(1.25))
249                        .gap_1()
250                        .when_some(self.label, |this, label| {
251                            this.child(
252                                div()
253                                    .size_full()
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}