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