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::{StyleSized as _, StyledExt as _, ThemeStyled as _};
8use gpui::ColorExt as _;
9use gpui::{
10    AnyElement, App, ElementId, InteractiveElement, IntoElement, MouseButton, ParentElement,
11    RenderOnce, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, div,
12    prelude::FluentBuilder as _, px, relative, rems, svg,
13};
14use gpui_base::{CheckboxIndicator, spring};
15
16/// A Checkbox element.
17#[derive(IntoElement)]
18pub struct Checkbox {
19    id: ElementId,
20    base: gpui_base::Checkbox,
21    style: StyleRefinement,
22    // `Text` is legacy presentation state. During render it is composed into
23    // the Base Checkbox child seam together with application children.
24    label: Option<Text>,
25    accessibility_label: Option<SharedString>,
26    children: Vec<AnyElement>,
27    checked: bool,
28    disabled: bool,
29    size: Size,
30    tab_stop: bool,
31    tab_index: isize,
32    on_click: Option<Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
33    tooltip: ComponentTooltip,
34    role: RoleOverride,
35    focus_ring_enabled: bool,
36}
37
38impl Checkbox {
39    /// Create a new Checkbox with the given id.
40    pub fn new(id: impl Into<ElementId>) -> Self {
41        let id = id.into();
42        Self {
43            id: id.clone(),
44            base: gpui_base::Checkbox::new(id),
45            style: StyleRefinement::default(),
46            label: None,
47            accessibility_label: None,
48            children: Vec::new(),
49            checked: false,
50            disabled: false,
51            size: Size::default(),
52            on_click: None,
53            tab_stop: true,
54            tab_index: 0,
55            tooltip: ComponentTooltip::default(),
56            role: RoleOverride::default(),
57            focus_ring_enabled: true,
58        }
59    }
60
61    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
62        self.role = role.into();
63        self
64    }
65
66    /// Set tooltip text for the checkbox.
67    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
68        self.tooltip.text = Some((tooltip.into(), None));
69        self
70    }
71
72    /// Set the label for the checkbox.
73    pub fn label(mut self, label: impl Into<Text>) -> Self {
74        self.label = Some(label.into());
75        self
76    }
77
78    /// Set the name a screen reader announces, overriding the visible label.
79    ///
80    /// This does not change the label drawn on screen.
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 for the checkbox.
87    pub fn checked(mut self, checked: bool) -> Self {
88        self.checked = checked;
89        self
90    }
91
92    /// Alias for [`Self::on_change`]. The last callback registered with either name wins.
93    pub fn on_click(self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
94        self.on_change(handler)
95    }
96
97    /// Handle a requested checked value from pointer or keyboard activation.
98    ///
99    /// This is a controlled value: the owner must write the requested value and
100    /// call `cx.notify()` to render it. Disabled controls do not call the handler.
101    /// This and [`Self::on_click`] share one callback; chaining them replaces
102    /// the previous handler instead of calling both.
103    pub fn on_change(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
104        self.on_click = Some(Rc::new(handler));
105        self
106    }
107
108    /// Set the tab stop for the checkbox, default is true.
109    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
110        self.tab_stop = tab_stop;
111        self
112    }
113
114    /// Set the tab index for the checkbox, default is 0.
115    pub fn tab_index(mut self, tab_index: isize) -> Self {
116        self.tab_index = tab_index;
117        self
118    }
119}
120
121impl InteractiveElement for Checkbox {
122    fn interactivity(&mut self) -> &mut gpui::Interactivity {
123        self.base.interactivity()
124    }
125}
126impl StatefulInteractiveElement for Checkbox {}
127
128impl Styled for Checkbox {
129    fn style(&mut self) -> &mut gpui::StyleRefinement {
130        &mut self.style
131    }
132}
133
134impl Disableable for Checkbox {
135    fn disabled(mut self, disabled: bool) -> Self {
136        self.disabled = disabled;
137        self
138    }
139}
140
141impl crate::FocusableExt for Checkbox {
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 Selectable for Checkbox {
153    fn selected(self, selected: bool) -> Self {
154        self.checked(selected)
155    }
156
157    fn is_selected(&self) -> bool {
158        self.checked
159    }
160}
161
162impl ParentElement for Checkbox {
163    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
164        self.children.extend(elements);
165    }
166}
167
168impl Sizable for Checkbox {
169    fn with_size(mut self, size: impl Into<Size>) -> Self {
170        self.size = size.into();
171        self
172    }
173}
174
175pub(crate) fn checkbox_check_icon(
176    id: ElementId,
177    size: Size,
178    checked: bool,
179    disabled: bool,
180    window: &mut Window,
181    cx: &mut App,
182) -> impl IntoElement {
183    // The mark keeps its path while the spring is still fading it out. Guarding
184    // the path on `checked` alone unmounted the glyph the moment the box was
185    // cleared, so only the fade-in was ever visible.
186    let opacity = spring(
187        (id, "mark"),
188        if checked { 1. } else { 0. },
189        cx.theme().motion_tokens().spring_control,
190        window,
191        cx,
192    );
193    let color = if disabled {
194        cx.theme().primary_foreground.opacity(0.5)
195    } else {
196        cx.theme().primary_foreground
197    };
198
199    svg()
200        .absolute()
201        .top_px()
202        .left_px()
203        .map(|this| match size {
204            Size::XSmall => this.size_2(),
205            Size::Small => this.size_2p5(),
206            Size::Medium => this.size_3(),
207            Size::Large => this.size_3p5(),
208            _ => this.size_3(),
209        })
210        .text_color(color)
211        .when(opacity > 0., |this| {
212            this.path(IconName::Check.path()).opacity(opacity)
213        })
214}
215
216impl RenderOnce for Checkbox {
217    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
218        let checked = self.checked;
219        let has_content = self.label.is_some() || !self.children.is_empty();
220        let indicator_size = rems(match self.size {
221            Size::XSmall => 0.75,
222            Size::Small => 0.875,
223            Size::Large => 1.125,
224            _ => 1.,
225        });
226
227        let base = self.base;
228        let children = self.children;
229        let accessibility_label = self
230            .accessibility_label
231            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
232        let on_click = self.on_click.clone();
233        let focus_handle = window
234            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
235            .read(cx)
236            .clone();
237        let is_focused = focus_handle.is_focused(window);
238
239        let unchecked_border = cx.theme().input;
240        let checked_color = cx.theme().primary;
241        let disabled_indicator_color = if checked {
242            checked_color.opacity(0.5)
243        } else {
244            unchecked_border.opacity(0.5)
245        };
246        let radius = cx.theme().radius.min(px(4.));
247        let disabled_text_color = cx.theme().muted_foreground;
248        let instance_style = self.style.clone();
249        base.role(self.role)
250            .checked(checked)
251            .disabled(self.disabled)
252            .styles(|styles| {
253                styles.disabled(|style| {
254                    style
255                        .text_color(disabled_text_color)
256                        .refine_style(&instance_style)
257                })
258            })
259            .tab_stop(self.tab_stop)
260            .tab_index(self.tab_index)
261            .track_focus(&focus_handle)
262            .when_some(accessibility_label, |this, label| {
263                this.accessibility_label(label)
264            })
265            .when_some(on_click, |this, on_click| {
266                this.on_change(move |_, _, window, cx| {
267                    window.prevent_default();
268                    on_click(&!checked, window, cx);
269                })
270            })
271            .h_flex()
272            .gap_2()
273            .items_start()
274            .line_height(relative(1.))
275            .text_color(cx.theme().foreground)
276            .map(|this| match self.size {
277                Size::Size(_) => this,
278                size => this.input_text_size(size),
279            })
280            .rounded(cx.theme().radius * 0.5)
281            .when(is_focused && self.focus_ring_enabled, |this| {
282                this.focus_ring_style(window, cx)
283            })
284            .refine_style(&self.style)
285            .child(
286                CheckboxIndicator::new()
287                    .checked(checked)
288                    .disabled(self.disabled)
289                    .relative()
290                    .size(indicator_size)
291                    // Center on the first 1.25em line, including when the label wraps.
292                    .when(has_content, |this| this.mt(indicator_size * 0.125))
293                    .flex_shrink_0()
294                    .border_1()
295                    .rounded(radius)
296                    .when(!checked, |this| {
297                        this.bg(cx.theme().input_background())
298                            .when(!self.disabled, |this| this.border_color(unchecked_border))
299                    })
300                    .styles(|styles| {
301                        styles
302                            .checked(|style| {
303                                style
304                                    .border_color(checked_color)
305                                    .bg(cx.theme().tokens.primary)
306                            })
307                            .disabled(|style| {
308                                style
309                                    .border_color(disabled_indicator_color)
310                                    .when(checked, |style| style.bg(disabled_indicator_color))
311                            })
312                    })
313                    .child(checkbox_check_icon(
314                        self.id,
315                        self.size,
316                        checked,
317                        self.disabled,
318                        window,
319                        cx,
320                    )),
321            )
322            .when(self.label.is_some() || !children.is_empty(), |this| {
323                this.child(
324                    v_flex()
325                        .flex_1()
326                        .overflow_hidden()
327                        .line_height(relative(1.25))
328                        .gap_1()
329                        .map(|this| {
330                            if let Some(label) = self.label {
331                                this.child(
332                                    div()
333                                        .size_full()
334                                        .text_color(cx.theme().foreground)
335                                        .when(self.disabled, |this| {
336                                            this.text_color(cx.theme().muted_foreground)
337                                        })
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}