Skip to main content

gpui_component/
checkbox.rs

1use std::rc::Rc;
2
3use crate::{
4    ActiveTheme, Disableable, IconName, RoleOverride, Selectable, Sizable, Size, icon::IconNamed,
5    text::Text, tooltip::ComponentTooltip, v_flex,
6};
7use crate::{StyledExt as _, ThemeStyled as _};
8use gpui::{
9    AnyElement, App, ElementId, InteractiveElement, IntoElement, MouseButton, ParentElement,
10    RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div,
11    prelude::FluentBuilder as _, px, relative, rems, svg,
12};
13use gpui_base::{CheckboxIndicator, spring};
14
15/// A Checkbox element.
16#[derive(IntoElement)]
17pub struct Checkbox {
18    id: ElementId,
19    base: gpui_base::Checkbox,
20    style: StyleRefinement,
21    // `Text` is legacy presentation state. During render it is composed into
22    // the Base Checkbox child seam together with application children.
23    label: Option<Text>,
24    accessibility_label: Option<SharedString>,
25    children: Vec<AnyElement>,
26    checked: bool,
27    disabled: bool,
28    size: Size,
29    tab_stop: bool,
30    tab_index: isize,
31    on_click: Option<Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
32    tooltip: ComponentTooltip,
33    role: RoleOverride,
34    focus_ring_enabled: bool,
35}
36
37impl Checkbox {
38    /// Create a new Checkbox with the given id.
39    pub fn new(id: impl Into<ElementId>) -> Self {
40        let id = id.into();
41        Self {
42            id: id.clone(),
43            base: gpui_base::Checkbox::new(id),
44            style: StyleRefinement::default(),
45            label: None,
46            accessibility_label: None,
47            children: Vec::new(),
48            checked: false,
49            disabled: false,
50            size: Size::default(),
51            on_click: None,
52            tab_stop: true,
53            tab_index: 0,
54            tooltip: ComponentTooltip::default(),
55            role: RoleOverride::default(),
56            focus_ring_enabled: true,
57        }
58    }
59
60    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
61        self.role = role.into();
62        self
63    }
64
65    /// Set tooltip text for the checkbox.
66    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
67        self.tooltip.text = Some((tooltip.into(), None));
68        self
69    }
70
71    /// Set the label for the checkbox.
72    pub fn label(mut self, label: impl Into<Text>) -> Self {
73        self.label = Some(label.into());
74        self
75    }
76
77    /// Set the name a screen reader announces, overriding the visible label.
78    ///
79    /// This does not change the label drawn on screen.
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 for the checkbox.
86    pub fn checked(mut self, checked: bool) -> Self {
87        self.checked = checked;
88        self
89    }
90
91    /// Alias for [`Self::on_change`]. The last callback registered with either name wins.
92    pub fn on_click(self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
93        self.on_change(handler)
94    }
95
96    /// Handle a requested checked value from pointer or keyboard activation.
97    ///
98    /// This is a controlled value: the owner must write the requested value and
99    /// call `cx.notify()` to render it. Disabled controls do not call the handler.
100    /// This and [`Self::on_click`] share one callback; chaining them replaces
101    /// the previous handler instead of calling both.
102    pub fn on_change(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
103        self.on_click = Some(Rc::new(handler));
104        self
105    }
106
107    /// Set the tab stop for the checkbox, default is true.
108    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
109        self.tab_stop = tab_stop;
110        self
111    }
112
113    /// Set the tab index for the checkbox, default is 0.
114    pub fn tab_index(mut self, tab_index: isize) -> Self {
115        self.tab_index = tab_index;
116        self
117    }
118}
119
120impl InteractiveElement for Checkbox {
121    fn interactivity(&mut self) -> &mut gpui::Interactivity {
122        self.base.interactivity()
123    }
124}
125impl StatefulInteractiveElement for Checkbox {}
126
127impl Styled for Checkbox {
128    fn style(&mut self) -> &mut gpui::StyleRefinement {
129        &mut self.style
130    }
131}
132
133impl Disableable for Checkbox {
134    fn disabled(mut self, disabled: bool) -> Self {
135        self.disabled = disabled;
136        self
137    }
138}
139
140impl crate::FocusableExt for Checkbox {
141    fn focus_ring(mut self, enabled: bool) -> Self {
142        self.focus_ring_enabled = enabled;
143        self
144    }
145
146    fn is_focus_ring_enabled(&self) -> bool {
147        self.focus_ring_enabled
148    }
149}
150
151impl Selectable for Checkbox {
152    fn selected(self, selected: bool) -> Self {
153        self.checked(selected)
154    }
155
156    fn is_selected(&self) -> bool {
157        self.checked
158    }
159}
160
161impl ParentElement for Checkbox {
162    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
163        self.children.extend(elements);
164    }
165}
166
167impl Sizable for Checkbox {
168    fn with_size(mut self, size: impl Into<Size>) -> Self {
169        self.size = size.into();
170        self
171    }
172}
173
174pub(crate) fn checkbox_check_icon(
175    id: ElementId,
176    size: Size,
177    checked: bool,
178    disabled: bool,
179    window: &mut Window,
180    cx: &mut App,
181) -> impl IntoElement {
182    // The mark keeps its path while the spring is still fading it out. Guarding
183    // the path on `checked` alone unmounted the glyph the moment the box was
184    // cleared, so only the fade-in was ever visible.
185    let opacity = spring(
186        (id, "mark"),
187        if checked { 1. } else { 0. },
188        cx.theme().motion_tokens().spring_control,
189        window,
190        cx,
191    );
192    let color = if disabled {
193        cx.theme().primary_foreground.opacity(0.5)
194    } else {
195        cx.theme().primary_foreground
196    };
197
198    svg()
199        .absolute()
200        .top_px()
201        .left_px()
202        .map(|this| match size {
203            Size::XSmall => this.size_2(),
204            Size::Small => this.size_2p5(),
205            Size::Medium => this.size_3(),
206            Size::Large => this.size_3p5(),
207            _ => this.size_3(),
208        })
209        .text_color(color)
210        .when(opacity > 0., |this| {
211            this.path(IconName::Check.path()).opacity(opacity)
212        })
213}
214
215impl RenderOnce for Checkbox {
216    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
217        let checked = self.checked;
218
219        let base = self.base;
220        let children = self.children;
221        let accessibility_label = self
222            .accessibility_label
223            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
224        let on_click = self.on_click.clone();
225        let focus_handle = window
226            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
227            .read(cx)
228            .clone();
229        let is_focused = focus_handle.is_focused(window);
230
231        let unchecked_border = cx.theme().input;
232        let checked_color = cx.theme().primary;
233        let disabled_indicator_color = if checked {
234            checked_color.opacity(0.5)
235        } else {
236            unchecked_border.opacity(0.5)
237        };
238        let radius = cx.theme().radius.min(px(4.));
239        let disabled_text_color = cx.theme().muted_foreground;
240        let instance_style = self.style.clone();
241        base.role(self.role)
242            .checked(checked)
243            .disabled(self.disabled)
244            .styles(|styles| {
245                styles.disabled(|style| {
246                    style
247                        .text_color(disabled_text_color)
248                        .refine_style(&instance_style)
249                })
250            })
251            .tab_stop(self.tab_stop)
252            .tab_index(self.tab_index)
253            .track_focus(&focus_handle)
254            .when_some(accessibility_label, |this, label| {
255                this.accessibility_label(label)
256            })
257            .when_some(on_click, |this, on_click| {
258                this.on_change(move |_, _, window, cx| {
259                    window.prevent_default();
260                    on_click(&!checked, window, cx);
261                })
262            })
263            .h_flex()
264            .gap_2()
265            .items_start()
266            .line_height(relative(1.))
267            .text_color(cx.theme().foreground)
268            .map(|this| match self.size {
269                Size::XSmall => this.text_xs(),
270                Size::Small => this.text_sm(),
271                Size::Medium => this.text_base(),
272                Size::Large => this.text_lg(),
273                _ => this,
274            })
275            .rounded(cx.theme().radius * 0.5)
276            .when(is_focused && self.focus_ring_enabled, |this| {
277                this.focus_ring_style(window, cx)
278            })
279            .refine_style(&self.style)
280            .child(
281                CheckboxIndicator::new()
282                    .checked(checked)
283                    .disabled(self.disabled)
284                    .relative()
285                    .map(|this| match self.size {
286                        Size::XSmall => this.size_3(),
287                        Size::Small => this.size_3p5(),
288                        Size::Medium => this.size_4(),
289                        Size::Large => this.size(rems(1.125)),
290                        _ => this.size_4(),
291                    })
292                    .flex_shrink_0()
293                    .border_1()
294                    .rounded(radius)
295                    .when(!checked, |this| {
296                        this.bg(cx.theme().input_background())
297                            .when(!self.disabled, |this| this.border_color(unchecked_border))
298                    })
299                    .styles(|styles| {
300                        styles
301                            .checked(|style| {
302                                style
303                                    .border_color(checked_color)
304                                    .bg(cx.theme().tokens.primary)
305                            })
306                            .disabled(|style| {
307                                style
308                                    .border_color(disabled_indicator_color)
309                                    .when(checked, |style| style.bg(disabled_indicator_color))
310                            })
311                    })
312                    .child(checkbox_check_icon(
313                        self.id,
314                        self.size,
315                        checked,
316                        self.disabled,
317                        window,
318                        cx,
319                    )),
320            )
321            .when(self.label.is_some() || !children.is_empty(), |this| {
322                this.child(
323                    v_flex()
324                        .flex_1()
325                        .overflow_hidden()
326                        .line_height(relative(1.2))
327                        .gap_1()
328                        .map(|this| {
329                            if let Some(label) = self.label {
330                                this.child(
331                                    div()
332                                        .size_full()
333                                        .text_color(cx.theme().foreground)
334                                        .when(self.disabled, |this| {
335                                            this.text_color(cx.theme().muted_foreground)
336                                        })
337                                        .line_height(relative(1.))
338                                        .child(label),
339                                )
340                            } else {
341                                this
342                            }
343                        })
344                        .children(children),
345                )
346            })
347            .on_mouse_down(MouseButton::Left, |_, window, _| {
348                // Preserve the legacy Checkbox behavior: pointer presses do
349                // not move focus, including while disabled.
350                window.prevent_default();
351            })
352            .map(|this| self.tooltip.apply(this))
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use std::{cell::Cell, rc::Rc};
359
360    use gpui::{
361        Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext,
362        VisualTestContext, point,
363    };
364
365    use super::*;
366
367    #[test]
368    fn an_explicit_accessibility_label_replaces_the_visible_one() {
369        let plain = Checkbox::new("remember").label("Remember me");
370        assert_eq!(plain.accessibility_label, None);
371
372        let named = Checkbox::new("remember")
373            .label("Remember me")
374            .accessibility_label("Remember this account");
375        assert_eq!(
376            named.accessibility_label.as_deref(),
377            Some("Remember this account"),
378            "an explicit name must win over the visible label"
379        );
380        assert!(
381            matches!(named.label.as_ref(), Some(Text::String(label)) if label.as_ref() == "Remember me"),
382            "and must not change what is drawn"
383        );
384    }
385
386    struct CheckboxHarness {
387        disabled: bool,
388        clicks: Rc<Cell<usize>>,
389        parent_clicks: Rc<Cell<usize>>,
390    }
391
392    impl Render for CheckboxHarness {
393        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
394            let clicks = self.clicks.clone();
395            let parent_clicks = self.parent_clicks.clone();
396            div()
397                .id("checkbox-parent")
398                .tab_group()
399                .size(px(100.))
400                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
401                .child(
402                    Checkbox::new("checkbox")
403                        .disabled(self.disabled)
404                        .size_full()
405                        .on_click(move |checked, _, _| {
406                            assert!(*checked);
407                            clicks.set(clicks.get() + 1);
408                        }),
409                )
410        }
411    }
412
413    fn harness(
414        cx: &mut TestAppContext,
415        disabled: bool,
416    ) -> (&mut VisualTestContext, Rc<Cell<usize>>, Rc<Cell<usize>>) {
417        cx.update(crate::init);
418        let clicks = Rc::new(Cell::new(0));
419        let parent_clicks = Rc::new(Cell::new(0));
420        let (_, cx) = cx.add_window_view({
421            let clicks = clicks.clone();
422            let parent_clicks = parent_clicks.clone();
423            move |_, _| CheckboxHarness {
424                disabled,
425                clicks,
426                parent_clicks,
427            }
428        });
429        cx.update(|window, cx| window.draw(cx).clear(cx));
430        (cx, clicks, parent_clicks)
431    }
432
433    fn activate_key(cx: &mut VisualTestContext, key: &str) {
434        let keystroke = Keystroke::parse(key).unwrap();
435        cx.simulate_event(KeyDownEvent {
436            keystroke: keystroke.clone(),
437            is_held: false,
438            prefer_character_input: false,
439        });
440        cx.simulate_event(KeyUpEvent { keystroke });
441    }
442
443    #[gpui::test]
444    fn facade_pointer_activation_fires_once_without_moving_focus(cx: &mut TestAppContext) {
445        let (cx, clicks, _) = harness(cx, false);
446        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
447
448        assert_eq!(clicks.get(), 1);
449        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
450    }
451
452    #[gpui::test]
453    fn facade_supports_tab_enter_and_space(cx: &mut TestAppContext) {
454        let (cx, clicks, _) = harness(cx, false);
455        cx.update(|window, cx| window.focus_next(cx));
456        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
457
458        activate_key(cx, "enter");
459        activate_key(cx, "space");
460
461        assert_eq!(clicks.get(), 2);
462    }
463
464    #[gpui::test]
465    fn facade_disabled_is_inert_and_pointer_activation_bubbles(cx: &mut TestAppContext) {
466        let (cx, clicks, parent_clicks) = harness(cx, true);
467        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
468
469        assert_eq!(clicks.get(), 0);
470        assert_eq!(parent_clicks.get(), 1);
471        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
472    }
473
474    #[gpui::test]
475    fn facade_prepaints_label_and_custom_content_through_the_base_slot(cx: &mut TestAppContext) {
476        struct ContentHarness;
477
478        impl Render for ContentHarness {
479            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
480                Checkbox::new("content-checkbox")
481                    .label("Remember me")
482                    .child(
483                        div()
484                            .debug_selector(|| "checkbox-custom-content".into())
485                            .child("Additional detail"),
486                    )
487            }
488        }
489
490        cx.update(crate::init);
491        let (_, cx) = cx.add_window_view(|_, _| ContentHarness);
492        cx.update(|window, cx| window.draw(cx).clear(cx));
493
494        let bounds = cx
495            .debug_bounds("checkbox-custom-content")
496            .expect("custom content must prepaint through the Base child seam");
497        assert!(bounds.size.width > px(0.));
498        assert!(bounds.size.height > px(0.));
499    }
500}