Skip to main content

gpui_component/
checkbox.rs

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