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, CheckboxState, LogicalStyledExt as _, 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    indeterminate: 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            indeterminate: false,
51            disabled: false,
52            size: Size::default(),
53            on_click: None,
54            tab_stop: true,
55            tab_index: 0,
56            tooltip: ComponentTooltip::default(),
57            role: RoleOverride::default(),
58            focus_ring_enabled: true,
59        }
60    }
61
62    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
63        self.role = role.into();
64        self
65    }
66
67    /// Set tooltip text for the checkbox.
68    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
69        self.tooltip.text = Some((tooltip.into(), None));
70        self
71    }
72
73    /// Overrides how long the pointer must rest before the tooltip shows.
74    ///
75    /// Defaults to [`gpui_base::TooltipDefaults::show_delay`].
76    pub fn tooltip_show_delay(mut self, delay: Duration) -> Self {
77        self.tooltip.show_delay = Some(delay);
78        self
79    }
80
81    /// Set the label for the checkbox.
82    pub fn label(mut self, label: impl Into<Text>) -> Self {
83        self.label = Some(label.into());
84        self
85    }
86
87    /// Set the name a screen reader announces, overriding the visible label.
88    ///
89    /// This does not change the label drawn on screen. A checkbox without a
90    /// [`label`](Self::label) or text children has no accessible name, so set this
91    /// whenever the checkbox is drawn without visible text.
92    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
93        self.accessibility_label = Some(label.into());
94        self
95    }
96
97    /// Set the checked state for the checkbox.
98    pub fn checked(mut self, checked: bool) -> Self {
99        self.checked = checked;
100        self
101    }
102
103    /// Show the mixed state, for example on a checkbox that selects a group
104    /// whose items are only partly checked. Default is false.
105    ///
106    /// While set, the checkbox draws a dash instead of the check mark and
107    /// reports the mixed state to assistive technology, whatever
108    /// [`checked`](Self::checked) says. Activating it requests `true`.
109    pub fn indeterminate(mut self, indeterminate: bool) -> Self {
110        self.indeterminate = indeterminate;
111        self
112    }
113
114    /// Alias for [`Self::on_change`]. The last callback registered with either name wins.
115    pub fn on_click(self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
116        self.on_change(handler)
117    }
118
119    /// Handle a requested checked value from pointer or keyboard activation.
120    ///
121    /// This is a controlled value: the owner must write the requested value and
122    /// call `cx.notify()` to render it. Disabled controls do not call the handler.
123    /// This and [`Self::on_click`] share one callback; chaining them replaces
124    /// the previous handler instead of calling both.
125    pub fn on_change(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
126        self.on_click = Some(Rc::new(handler));
127        self
128    }
129
130    /// Set the tab stop for the checkbox, default is true.
131    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
132        self.tab_stop = tab_stop;
133        self
134    }
135
136    /// Set the tab index for the checkbox, default is 0.
137    pub fn tab_index(mut self, tab_index: isize) -> Self {
138        self.tab_index = tab_index;
139        self
140    }
141}
142
143impl InteractiveElement for Checkbox {
144    fn interactivity(&mut self) -> &mut gpui::Interactivity {
145        self.base.interactivity()
146    }
147}
148impl StatefulInteractiveElement for Checkbox {}
149
150impl Styled for Checkbox {
151    fn style(&mut self) -> &mut gpui::StyleRefinement {
152        &mut self.style
153    }
154}
155
156impl Disableable for Checkbox {
157    fn disabled(mut self, disabled: bool) -> Self {
158        self.disabled = disabled;
159        self
160    }
161}
162
163impl crate::FocusableExt for Checkbox {
164    fn focus_ring(mut self, enabled: bool) -> Self {
165        self.focus_ring_enabled = enabled;
166        self
167    }
168
169    fn is_focus_ring_enabled(&self) -> bool {
170        self.focus_ring_enabled
171    }
172}
173
174impl Selectable for Checkbox {
175    fn selected(self, selected: bool) -> Self {
176        self.checked(selected)
177    }
178
179    fn is_selected(&self) -> bool {
180        self.checked
181    }
182}
183
184impl ParentElement for Checkbox {
185    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
186        self.children.extend(elements);
187    }
188}
189
190impl Sizable for Checkbox {
191    fn with_size(mut self, size: impl Into<Size>) -> Self {
192        self.size = size.into();
193        self
194    }
195}
196
197/// Draws the mark inside a checkbox or radio indicator.
198///
199/// `mark` is the icon to show, or `None` to fade the last shown one out.
200pub(crate) fn checkbox_check_icon(
201    id: ElementId,
202    size: Size,
203    mark: Option<IconName>,
204    disabled: bool,
205    window: &mut Window,
206    cx: &mut App,
207) -> impl IntoElement {
208    let mark = mark.map(IconNamed::path);
209    let shown = window.use_keyed_state(
210        ElementId::NamedChild(id.clone().into(), "mark-icon".into()),
211        cx,
212        |_, _| mark.clone().unwrap_or_else(|| IconName::Check.path()),
213    );
214    if let Some(mark) = &mark
215        && shown.read(cx) != mark
216    {
217        shown.update(cx, |shown, _| *shown = mark.clone());
218    }
219    let path = shown.read(cx).clone();
220    // The mark keeps its path while the spring is still fading it out. Guarding
221    // the path on `checked` alone unmounted the glyph the moment the box was
222    // cleared, so only the fade-in was ever visible.
223    let opacity = spring(
224        (id, "mark"),
225        if mark.is_some() { 1. } else { 0. },
226        cx.theme().motion_tokens().spring_control,
227        window,
228        cx,
229    );
230    let color = if disabled {
231        cx.theme().primary_foreground.opacity(0.5)
232    } else {
233        cx.theme().primary_foreground
234    };
235
236    svg()
237        .absolute()
238        .top_px()
239        .left_px()
240        .map(|this| match size {
241            Size::XSmall => this.size_2(),
242            Size::Small => this.size_2p5(),
243            Size::Medium => this.size_3(),
244            Size::Large => this.size_3p5(),
245            _ => this.size_3(),
246        })
247        .text_color(color)
248        .when(opacity > 0., |this| {
249            this.path(crate::resolve_icon_path(path, cx))
250                .opacity(opacity)
251        })
252}
253
254impl RenderOnce for Checkbox {
255    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
256        let state = if self.indeterminate {
257            CheckboxState::Indeterminate
258        } else if self.checked {
259            CheckboxState::Checked
260        } else {
261            CheckboxState::Unchecked
262        };
263        let filled = state != CheckboxState::Unchecked;
264        let has_content = self.label.is_some() || !self.children.is_empty();
265        let indicator_size = rems(match self.size {
266            Size::XSmall => 0.75,
267            Size::Small => 0.875,
268            Size::Large => 1.125,
269            _ => 1.,
270        });
271
272        let base = self.base;
273        let children = self.children;
274        let accessibility_label = self
275            .accessibility_label
276            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
277        let on_click = self.on_click.clone();
278        let focus_handle = window
279            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
280            .read(cx)
281            .clone();
282        let is_focused = focus_handle.is_focused(window);
283
284        let unchecked_border = cx.theme().input;
285        let checked_color = cx.theme().primary;
286        let disabled_indicator_color = if filled {
287            checked_color.opacity(0.5)
288        } else {
289            unchecked_border.opacity(0.5)
290        };
291        let radius = cx.theme().radius.min(px(4.));
292        let disabled_text_color = cx.theme().muted_foreground;
293        let instance_style = self.style.clone();
294        base.role(self.role)
295            .state(state)
296            .disabled(self.disabled)
297            .styles(|styles| {
298                styles.disabled(|style| {
299                    style
300                        .text_color(disabled_text_color)
301                        .refine_style(&instance_style)
302                })
303            })
304            .tab_stop(self.tab_stop)
305            .tab_index(self.tab_index)
306            .track_focus(&focus_handle)
307            .when_some(accessibility_label, |this, label| {
308                this.accessibility_label(label)
309            })
310            .when_some(on_click, |this, on_click| {
311                this.on_change(move |next, _, window, cx| {
312                    window.prevent_default();
313                    on_click(&(next == CheckboxState::Checked), window, cx);
314                })
315            })
316            .h_flex()
317            // The indicator leads, on the start edge.
318            .flex_row_dir(cx)
319            .gap_2()
320            .items_start()
321            .line_height(relative(1.))
322            .text_color(cx.theme().foreground)
323            .map(|this| match self.size {
324                Size::Size(_) => this,
325                size => this.input_text_size(size),
326            })
327            .rounded(cx.theme().radius * 0.5)
328            .when(is_focused && self.focus_ring_enabled, |this| {
329                this.focus_ring_style(window, cx)
330            })
331            .refine_style(&self.style)
332            .child(
333                CheckboxIndicator::new()
334                    .state(state)
335                    .disabled(self.disabled)
336                    .relative()
337                    .size(indicator_size)
338                    // Center on the first 1.25em line, including when the label wraps.
339                    .when(has_content, |this| this.mt(indicator_size * 0.125))
340                    .flex_shrink_0()
341                    .border_1()
342                    .rounded(radius)
343                    .when(!filled, |this| {
344                        this.bg(cx.theme().input_background())
345                            .when(!self.disabled, |this| this.border_color(unchecked_border))
346                    })
347                    .styles(|styles| {
348                        styles
349                            .checked(|style| {
350                                style
351                                    .border_color(checked_color)
352                                    .bg(cx.theme().tokens.primary)
353                            })
354                            .indeterminate(|style| {
355                                style
356                                    .border_color(checked_color)
357                                    .bg(cx.theme().tokens.primary)
358                            })
359                            .disabled(|style| {
360                                style
361                                    .border_color(disabled_indicator_color)
362                                    .when(filled, |style| style.bg(disabled_indicator_color))
363                            })
364                    })
365                    .child(checkbox_check_icon(
366                        self.id,
367                        self.size,
368                        match state {
369                            CheckboxState::Checked => Some(IconName::Check),
370                            CheckboxState::Indeterminate => Some(IconName::Minus),
371                            CheckboxState::Unchecked => None,
372                        },
373                        self.disabled,
374                        window,
375                        cx,
376                    )),
377            )
378            .when(self.label.is_some() || !children.is_empty(), |this| {
379                this.child(
380                    v_flex()
381                        .flex_1()
382                        .overflow_hidden()
383                        .line_height(relative(1.25))
384                        .gap_1()
385                        .map(|this| {
386                            if let Some(label) = self.label {
387                                this.child(
388                                    div()
389                                        .size_full()
390                                        .text_color(cx.theme().foreground)
391                                        .when(self.disabled, |this| {
392                                            this.text_color(cx.theme().muted_foreground)
393                                        })
394                                        .child(label),
395                                )
396                            } else {
397                                this
398                            }
399                        })
400                        .children(children),
401                )
402            })
403            .on_mouse_down(MouseButton::Left, |_, window, _| {
404                // Preserve the legacy Checkbox behavior: pointer presses do
405                // not move focus, including while disabled.
406                window.prevent_default();
407            })
408            .map(|this| self.tooltip.apply(this))
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use std::{cell::Cell, rc::Rc};
415
416    use gpui::{
417        Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext,
418        VisualTestContext, point,
419    };
420
421    use super::*;
422
423    #[test]
424    fn an_explicit_accessibility_label_replaces_the_visible_one() {
425        let plain = Checkbox::new("remember").label("Remember me");
426        assert_eq!(plain.accessibility_label, None);
427
428        let named = Checkbox::new("remember")
429            .label("Remember me")
430            .accessibility_label("Remember this account");
431        assert_eq!(
432            named.accessibility_label.as_deref(),
433            Some("Remember this account"),
434            "an explicit name must win over the visible label"
435        );
436        assert!(
437            matches!(named.label.as_ref(), Some(Text::String(label)) if label.as_ref() == "Remember me"),
438            "and must not change what is drawn"
439        );
440    }
441
442    struct CheckboxHarness {
443        disabled: bool,
444        clicks: Rc<Cell<usize>>,
445        parent_clicks: Rc<Cell<usize>>,
446    }
447
448    impl Render for CheckboxHarness {
449        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
450            let clicks = self.clicks.clone();
451            let parent_clicks = self.parent_clicks.clone();
452            div()
453                .id("checkbox-parent")
454                .tab_group()
455                .size(px(100.))
456                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
457                .child(
458                    Checkbox::new("checkbox")
459                        .disabled(self.disabled)
460                        .size_full()
461                        .on_click(move |checked, _, _| {
462                            assert!(*checked);
463                            clicks.set(clicks.get() + 1);
464                        }),
465                )
466        }
467    }
468
469    fn harness(
470        cx: &mut TestAppContext,
471        disabled: bool,
472    ) -> (&mut VisualTestContext, Rc<Cell<usize>>, Rc<Cell<usize>>) {
473        cx.update(crate::init);
474        let clicks = Rc::new(Cell::new(0));
475        let parent_clicks = Rc::new(Cell::new(0));
476        let (_, cx) = cx.add_window_view({
477            let clicks = clicks.clone();
478            let parent_clicks = parent_clicks.clone();
479            move |_, _| CheckboxHarness {
480                disabled,
481                clicks,
482                parent_clicks,
483            }
484        });
485        cx.update(|window, cx| window.draw(cx).clear(cx));
486        (cx, clicks, parent_clicks)
487    }
488
489    fn activate_key(cx: &mut VisualTestContext, key: &str) {
490        let keystroke =
491            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
492        cx.simulate_event(KeyDownEvent {
493            keystroke: keystroke.clone(),
494            is_held: false,
495            prefer_character_input: false,
496        });
497        cx.simulate_event(KeyUpEvent { keystroke });
498    }
499
500    #[gpui::test]
501    fn facade_pointer_activation_fires_once_without_moving_focus(cx: &mut TestAppContext) {
502        let (cx, clicks, _) = harness(cx, false);
503        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
504
505        assert_eq!(clicks.get(), 1);
506        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
507    }
508
509    #[gpui::test]
510    fn facade_supports_tab_enter_and_space(cx: &mut TestAppContext) {
511        let (cx, clicks, _) = harness(cx, false);
512        cx.update(|window, cx| window.focus_next(cx));
513        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
514
515        activate_key(cx, "enter");
516        activate_key(cx, "space");
517
518        assert_eq!(clicks.get(), 2);
519    }
520
521    #[gpui::test]
522    fn facade_disabled_is_inert_and_pointer_activation_bubbles(cx: &mut TestAppContext) {
523        let (cx, clicks, parent_clicks) = harness(cx, true);
524        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
525
526        assert_eq!(clicks.get(), 0);
527        assert_eq!(parent_clicks.get(), 1);
528        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
529    }
530
531    #[gpui::test]
532    fn facade_prepaints_label_and_custom_content_through_the_base_slot(cx: &mut TestAppContext) {
533        struct ContentHarness;
534
535        impl Render for ContentHarness {
536            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
537                Checkbox::new("content-checkbox")
538                    .label("Remember me")
539                    .child(
540                        div()
541                            .debug_selector(|| "checkbox-custom-content".into())
542                            .child("Additional detail"),
543                    )
544            }
545        }
546
547        cx.update(crate::init);
548        let (_, cx) = cx.add_window_view(|_, _| ContentHarness);
549        cx.update(|window, cx| window.draw(cx).clear(cx));
550
551        let bounds = cx
552            .debug_bounds("checkbox-custom-content")
553            .expect("custom content must prepaint through the Base child seam");
554        assert!(bounds.size.width > px(0.));
555        assert!(bounds.size.height > px(0.));
556    }
557
558    #[gpui::test]
559    fn the_check_mark_asks_the_icon_resolver_for_its_path(cx: &mut TestAppContext) {
560        struct CheckedHarness;
561
562        impl Render for CheckedHarness {
563            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
564                Checkbox::new("checked").checked(true)
565            }
566        }
567
568        let asked = Rc::new(std::cell::RefCell::new(Vec::<String>::new()));
569        cx.update(|cx| {
570            crate::init(cx);
571            cx.set_reduce_motion(true);
572            let asked = asked.clone();
573            crate::set_icon_resolver(cx, move |path, _| {
574                asked.borrow_mut().push(path.to_string());
575                None
576            });
577        });
578        let (_, cx) = cx.add_window_view(|_, _| CheckedHarness);
579        cx.update(|window, cx| window.draw(cx).clear(cx));
580
581        assert!(
582            asked.borrow().contains(&IconName::Check.path().to_string()),
583            "the check mark must be drawn from the resolved path"
584        );
585    }
586
587    #[gpui::test]
588    fn an_indeterminate_checkbox_draws_a_dash(cx: &mut TestAppContext) {
589        struct MixedHarness;
590
591        impl Render for MixedHarness {
592            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
593                Checkbox::new("mixed").checked(true).indeterminate(true)
594            }
595        }
596
597        let asked = Rc::new(std::cell::RefCell::new(Vec::<String>::new()));
598        cx.update(|cx| {
599            crate::init(cx);
600            cx.set_reduce_motion(true);
601            let asked = asked.clone();
602            crate::set_icon_resolver(cx, move |path, _| {
603                asked.borrow_mut().push(path.to_string());
604                None
605            });
606        });
607        let (_, cx) = cx.add_window_view(|_, _| MixedHarness);
608        cx.update(|window, cx| window.draw(cx).clear(cx));
609
610        let asked = asked.borrow();
611        assert!(asked.contains(&IconName::Minus.path().to_string()));
612        assert!(
613            !asked.contains(&IconName::Check.path().to_string()),
614            "the mixed state replaces the check mark"
615        );
616    }
617
618    #[gpui::test]
619    fn activating_an_indeterminate_checkbox_requests_checked(cx: &mut TestAppContext) {
620        struct MixedHarness {
621            requested: Rc<Cell<Option<bool>>>,
622        }
623
624        impl Render for MixedHarness {
625            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
626                let requested = self.requested.clone();
627                div().size(px(100.)).child(
628                    Checkbox::new("mixed")
629                        .size_full()
630                        .checked(true)
631                        .indeterminate(true)
632                        .on_change(move |checked, _, _| requested.set(Some(*checked))),
633                )
634            }
635        }
636
637        cx.update(crate::init);
638        let requested = Rc::new(Cell::new(None));
639        let (_, cx) = cx.add_window_view({
640            let requested = requested.clone();
641            move |_, _| MixedHarness { requested }
642        });
643        cx.update(|window, cx| window.draw(cx).clear(cx));
644        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
645
646        assert_eq!(requested.get(), Some(true));
647    }
648
649    #[cfg(feature = "test-support")]
650    #[gpui::test]
651    fn indeterminate_reports_the_mixed_state_over_checked(cx: &mut TestAppContext) {
652        struct MixedHarness;
653
654        impl Render for MixedHarness {
655            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
656                div()
657                    .child(
658                        Checkbox::new("mixed")
659                            .label("All files")
660                            .checked(true)
661                            .indeterminate(true),
662                    )
663                    .child(
664                        Checkbox::new("cleared")
665                            .label("One file")
666                            .checked(true)
667                            .indeterminate(false),
668                    )
669            }
670        }
671
672        cx.update(crate::init);
673        let (_, cx) = cx.add_window_view(|_, _| MixedHarness);
674        cx.update(|window, cx| window.draw(cx).clear(cx));
675
676        cx.update(|window, _| {
677            let find = |id: &'static str| {
678                gpui_base::test_support::find(window, &[], &ElementId::from(id))
679                    .expect("the checkbox is observed")
680            };
681            let mixed = find("mixed");
682            assert_eq!(mixed.indeterminate(), Some(true));
683            assert_eq!(mixed.checked(), Some(false));
684            let cleared = find("cleared");
685            assert_eq!(cleared.indeterminate(), Some(false));
686            assert_eq!(cleared.checked(), Some(true));
687        });
688    }
689}