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::{
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        let has_content = self.label.is_some() || !self.children.is_empty();
219        let indicator_size = rems(match self.size {
220            Size::XSmall => 0.75,
221            Size::Small => 0.875,
222            Size::Large => 1.125,
223            _ => 1.,
224        });
225
226        let base = self.base;
227        let children = self.children;
228        let accessibility_label = self
229            .accessibility_label
230            .or_else(|| self.label.as_ref().map(|label| label.get_text(cx)));
231        let on_click = self.on_click.clone();
232        let focus_handle = window
233            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
234            .read(cx)
235            .clone();
236        let is_focused = focus_handle.is_focused(window);
237
238        let unchecked_border = cx.theme().input;
239        let checked_color = cx.theme().primary;
240        let disabled_indicator_color = if checked {
241            checked_color.opacity(0.5)
242        } else {
243            unchecked_border.opacity(0.5)
244        };
245        let radius = cx.theme().radius.min(px(4.));
246        let disabled_text_color = cx.theme().muted_foreground;
247        let instance_style = self.style.clone();
248        base.role(self.role)
249            .checked(checked)
250            .disabled(self.disabled)
251            .styles(|styles| {
252                styles.disabled(|style| {
253                    style
254                        .text_color(disabled_text_color)
255                        .refine_style(&instance_style)
256                })
257            })
258            .tab_stop(self.tab_stop)
259            .tab_index(self.tab_index)
260            .track_focus(&focus_handle)
261            .when_some(accessibility_label, |this, label| {
262                this.accessibility_label(label)
263            })
264            .when_some(on_click, |this, on_click| {
265                this.on_change(move |_, _, window, cx| {
266                    window.prevent_default();
267                    on_click(&!checked, window, cx);
268                })
269            })
270            .h_flex()
271            .gap_2()
272            .items_start()
273            .line_height(relative(1.))
274            .text_color(cx.theme().foreground)
275            .map(|this| match self.size {
276                Size::Size(_) => this,
277                size => this.input_text_size(size),
278            })
279            .rounded(cx.theme().radius * 0.5)
280            .when(is_focused && self.focus_ring_enabled, |this| {
281                this.focus_ring_style(window, cx)
282            })
283            .refine_style(&self.style)
284            .child(
285                CheckboxIndicator::new()
286                    .checked(checked)
287                    .disabled(self.disabled)
288                    .relative()
289                    .size(indicator_size)
290                    // Center on the first 1.25em line, including when the label wraps.
291                    .when(has_content, |this| this.mt(indicator_size * 0.125))
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.25))
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                                        .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}