Skip to main content

gpui_base/
checkbox.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ClickEvent, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
5    IntoElement, ParentElement, Refineable as _, RenderOnce, Role, SharedString, Stateful,
6    StatefulInteractiveElement, StyleRefinement, Styled, Toggled, Window, div,
7    prelude::FluentBuilder as _,
8};
9use smallvec::SmallVec;
10
11use crate::{
12    RoleOverride, StateStyle, StyledExt as _, TestSupportExt as _,
13    a11y_disabled::A11yDisabledExt as _,
14};
15
16type ChangeHandler = Rc<dyn Fn(CheckboxState, &ClickEvent, &mut Window, &mut App)>;
17
18/// The semantic value exposed by an unstyled [`Checkbox`].
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub enum CheckboxState {
21    #[default]
22    Unchecked,
23    Checked,
24    Indeterminate,
25}
26
27impl CheckboxState {
28    fn toggled(self) -> Toggled {
29        match self {
30            Self::Unchecked => Toggled::False,
31            Self::Checked => Toggled::True,
32            Self::Indeterminate => Toggled::Mixed,
33        }
34    }
35
36    fn activated(self) -> Self {
37        match self {
38            Self::Unchecked | Self::Indeterminate => Self::Checked,
39            Self::Checked => Self::Unchecked,
40        }
41    }
42}
43
44/// An unstyled checkbox that owns toggle, focus, keyboard, and accessibility behavior.
45///
46/// The application owns all layout and visual state rendering. Child elements can
47/// present the check mark, indeterminate mark, label, or any other design-system UI.
48#[derive(IntoElement)]
49pub struct Checkbox {
50    id: ElementId,
51    base: Stateful<Div>,
52    style: StyleRefinement,
53    semantic_styles: CheckboxStyles,
54    state: CheckboxState,
55    disabled: bool,
56    children: SmallVec<[AnyElement; 2]>,
57    on_change: Option<ChangeHandler>,
58    accessibility_label: Option<SharedString>,
59    tab_index: isize,
60    tab_stop: bool,
61    provided_focus_handle: Option<FocusHandle>,
62    role: RoleOverride,
63}
64
65impl Checkbox {
66    /// Creates an unchecked checkbox with a stable element identifier.
67    pub fn new(id: impl Into<ElementId>) -> Self {
68        let id = id.into();
69        Self {
70            base: div().id(id.clone()),
71            id,
72            style: StyleRefinement::default(),
73            semantic_styles: CheckboxStyles::default(),
74            state: CheckboxState::Unchecked,
75            disabled: false,
76            children: SmallVec::new(),
77            on_change: None,
78            accessibility_label: None,
79            tab_index: 0,
80            tab_stop: true,
81            provided_focus_handle: None,
82            role: RoleOverride::Implicit,
83        }
84    }
85    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
86        self.role = role.into();
87        self
88    }
89
90    /// Sets the controlled semantic state.
91    pub fn state(mut self, state: CheckboxState) -> Self {
92        self.state = state;
93        self
94    }
95
96    /// Sets the checked state, clearing any indeterminate state.
97    pub fn checked(self, checked: bool) -> Self {
98        self.state(if checked {
99            CheckboxState::Checked
100        } else {
101            CheckboxState::Unchecked
102        })
103    }
104
105    /// Sets or clears the indeterminate state.
106    ///
107    /// Clearing indeterminate leaves the checkbox unchecked. Applications with a
108    /// controlled value can call [`Self::state`] when another fallback is desired.
109    pub fn indeterminate(self, indeterminate: bool) -> Self {
110        if indeterminate {
111            self.state(CheckboxState::Indeterminate)
112        } else if self.state == CheckboxState::Indeterminate {
113            self.state(CheckboxState::Unchecked)
114        } else {
115            self
116        }
117    }
118
119    /// Sets whether pointer and keyboard activation are ignored.
120    pub fn disabled(mut self, disabled: bool) -> Self {
121        self.disabled = disabled;
122        self
123    }
124
125    /// Defines application-owned styles for the checkbox's semantic states.
126    pub fn styles(mut self, build: impl FnOnce(CheckboxStyles) -> CheckboxStyles) -> Self {
127        self.semantic_styles = build(self.semantic_styles);
128        self
129    }
130
131    /// Sets the label exposed to accessibility clients.
132    ///
133    /// A checkbox without text children has no accessible name, so set this
134    /// whenever it is drawn without visible text.
135    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
136        self.accessibility_label = Some(label.into());
137        self
138    }
139
140    /// Handles an activation with the next controlled state.
141    ///
142    /// An indeterminate checkbox becomes checked when activated. The activating
143    /// [`ClickEvent`] is reported so callers can read its modifiers, for example
144    /// to extend a selection.
145    pub fn on_change(
146        mut self,
147        handler: impl Fn(CheckboxState, &ClickEvent, &mut Window, &mut App) + 'static,
148    ) -> Self {
149        self.on_change = Some(Rc::new(handler));
150        self
151    }
152
153    /// Sets the focus traversal index. The default is `0`.
154    pub fn tab_index(mut self, tab_index: isize) -> Self {
155        self.tab_index = tab_index;
156        self
157    }
158
159    /// Sets whether this checkbox participates in keyboard focus traversal.
160    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
161        self.tab_stop = tab_stop;
162        self
163    }
164
165    /// Uses a caller-owned focus handle instead of creating keyed state.
166    pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
167        self.provided_focus_handle = Some(focus_handle.clone());
168        self
169    }
170
171    fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
172        self.provided_focus_handle.clone().unwrap_or_else(|| {
173            window
174                .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
175                .read(cx)
176                .clone()
177        })
178    }
179
180    fn resolved_style(&self) -> StyleRefinement {
181        crate::state_style::resolve_style(
182            &self.style,
183            [
184                match self.state {
185                    CheckboxState::Unchecked => None,
186                    CheckboxState::Checked => Some(&self.semantic_styles.checked),
187                    CheckboxState::Indeterminate => Some(&self.semantic_styles.indeterminate),
188                },
189                self.disabled.then_some(&self.semantic_styles.disabled),
190            ]
191            .into_iter()
192            .flatten(),
193        )
194    }
195}
196
197/// Semantic styles supported by [`Checkbox`].
198#[derive(Default)]
199pub struct CheckboxStyles {
200    checked: StyleRefinement,
201    indeterminate: StyleRefinement,
202    disabled: StyleRefinement,
203}
204
205impl CheckboxStyles {
206    /// Refines the root style when the checkbox is checked.
207    pub fn checked(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
208        self.checked
209            .refine(&build(StateStyle::default()).into_refinement());
210        self
211    }
212
213    /// Refines the root style when the checkbox is indeterminate.
214    pub fn indeterminate(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
215        self.indeterminate
216            .refine(&build(StateStyle::default()).into_refinement());
217        self
218    }
219
220    /// Refines the root style when the checkbox is disabled.
221    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
222        self.disabled
223            .refine(&build(StateStyle::default()).into_refinement());
224        self
225    }
226}
227
228/// An unstyled checkbox indicator part with typed checkbox-state projection.
229///
230/// This renders its `Div` directly. Applications own its geometry, visual
231/// presentation, and children.
232#[derive(IntoElement)]
233pub struct CheckboxIndicator {
234    base: Div,
235    style: StyleRefinement,
236    semantic_styles: CheckboxIndicatorStyles,
237    state: CheckboxState,
238    disabled: bool,
239    children: SmallVec<[AnyElement; 1]>,
240}
241
242/// Semantic styles supported by [`CheckboxIndicator`].
243#[derive(Default)]
244pub struct CheckboxIndicatorStyles {
245    checked: StyleRefinement,
246    indeterminate: StyleRefinement,
247    disabled: StyleRefinement,
248}
249
250impl CheckboxIndicatorStyles {
251    pub fn checked(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
252        self.checked
253            .refine(&build(StateStyle::default()).into_refinement());
254        self
255    }
256
257    pub fn indeterminate(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
258        self.indeterminate
259            .refine(&build(StateStyle::default()).into_refinement());
260        self
261    }
262
263    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
264        self.disabled
265            .refine(&build(StateStyle::default()).into_refinement());
266        self
267    }
268}
269
270impl CheckboxIndicator {
271    pub fn new() -> Self {
272        Self {
273            base: div(),
274            style: StyleRefinement::default(),
275            semantic_styles: CheckboxIndicatorStyles::default(),
276            state: CheckboxState::Unchecked,
277            disabled: false,
278            children: SmallVec::new(),
279        }
280    }
281
282    pub fn state(mut self, state: CheckboxState) -> Self {
283        self.state = state;
284        self
285    }
286
287    pub fn checked(self, checked: bool) -> Self {
288        self.state(if checked {
289            CheckboxState::Checked
290        } else {
291            CheckboxState::Unchecked
292        })
293    }
294
295    pub fn disabled(mut self, disabled: bool) -> Self {
296        self.disabled = disabled;
297        self
298    }
299
300    pub fn styles(
301        mut self,
302        build: impl FnOnce(CheckboxIndicatorStyles) -> CheckboxIndicatorStyles,
303    ) -> Self {
304        self.semantic_styles = build(self.semantic_styles);
305        self
306    }
307
308    fn resolved_style(&self) -> StyleRefinement {
309        crate::state_style::resolve_style(
310            &self.style,
311            [
312                match self.state {
313                    CheckboxState::Unchecked => None,
314                    CheckboxState::Checked => Some(&self.semantic_styles.checked),
315                    CheckboxState::Indeterminate => Some(&self.semantic_styles.indeterminate),
316                },
317                self.disabled.then_some(&self.semantic_styles.disabled),
318            ]
319            .into_iter()
320            .flatten(),
321        )
322    }
323}
324
325impl Default for CheckboxIndicator {
326    fn default() -> Self {
327        Self::new()
328    }
329}
330
331impl Styled for CheckboxIndicator {
332    fn style(&mut self) -> &mut StyleRefinement {
333        &mut self.style
334    }
335}
336
337impl ParentElement for CheckboxIndicator {
338    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
339        self.children.extend(elements);
340    }
341}
342
343impl RenderOnce for CheckboxIndicator {
344    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
345        let style = self.resolved_style();
346        self.base.children(self.children).refine_style(&style)
347    }
348}
349
350impl Styled for Checkbox {
351    fn style(&mut self) -> &mut StyleRefinement {
352        &mut self.style
353    }
354}
355
356impl ParentElement for Checkbox {
357    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
358        self.children.extend(elements);
359    }
360}
361
362impl InteractiveElement for Checkbox {
363    fn interactivity(&mut self) -> &mut Interactivity {
364        self.base.interactivity()
365    }
366}
367
368impl StatefulInteractiveElement for Checkbox {}
369
370impl RenderOnce for Checkbox {
371    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
372        let focus_handle = self.focus_handle(window, cx);
373        let disabled = self.disabled;
374        let next_state = self.state.activated();
375        let style = self.resolved_style();
376        let on_change = self.on_change;
377
378        self.base
379            .test_support()
380            .when_some(self.role.resolve(|| Role::CheckBox), |this, role| {
381                this.role(role)
382            })
383            .aria_toggled(self.state.toggled())
384            .when_some(self.accessibility_label, |this, label| {
385                this.aria_label(label)
386            })
387            // Keep the current focus in the dispatch tree when activation
388            // disables this control, so Tab can still leave in either direction.
389            .when(!disabled || focus_handle.is_focused(window), |this| {
390                this.track_focus(
391                    &focus_handle
392                        .tab_index(self.tab_index)
393                        .tab_stop(self.tab_stop && !disabled),
394                )
395            })
396            .when_some(
397                (!disabled).then_some(on_change).flatten(),
398                |this, on_change| {
399                    this.on_click(move |event, window, cx| {
400                        on_change(next_state, event, window, cx);
401                    })
402                },
403            )
404            .children(self.children)
405            .refine_style(&style)
406            .a11y_disabled(disabled)
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413    use std::{
414        cell::{Cell, RefCell},
415        rc::Rc,
416        sync::{Arc, Mutex},
417    };
418
419    use gpui::{
420        Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render,
421        TestAppContext, VisualTestContext, accesskit, canvas, point, px,
422    };
423
424    #[test]
425    fn indicator_projects_state_styles_over_the_instance_layer() {
426        let checked_color = gpui::hsla(0.6, 0.7, 0.5, 1.0);
427        let disabled_color = gpui::hsla(0.1, 0.2, 0.3, 0.5);
428
429        let indicator = |state, disabled| {
430            CheckboxIndicator::new()
431                .state(state)
432                .disabled(disabled)
433                .styles(|styles| {
434                    styles
435                        .checked(|style| style.border_color(checked_color))
436                        .indeterminate(|style| style.opacity(0.7))
437                        .disabled(|style| style.border_color(disabled_color))
438                })
439        };
440
441        assert_eq!(
442            indicator(CheckboxState::Checked, false)
443                .resolved_style()
444                .border_color,
445            Some(checked_color)
446        );
447        assert_eq!(
448            indicator(CheckboxState::Checked, true)
449                .resolved_style()
450                .border_color,
451            Some(disabled_color)
452        );
453        assert_eq!(
454            indicator(CheckboxState::Indeterminate, false)
455                .resolved_style()
456                .opacity,
457            Some(0.7)
458        );
459        assert_eq!(
460            indicator(CheckboxState::Checked, true)
461                .border_color(checked_color)
462                .resolved_style()
463                .border_color,
464            Some(disabled_color)
465        );
466    }
467
468    struct CheckboxHarness {
469        state: CheckboxState,
470        disabled: bool,
471        changes: Rc<RefCell<Vec<CheckboxState>>>,
472        parent_clicks: Rc<Cell<usize>>,
473    }
474
475    impl Render for CheckboxHarness {
476        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
477            let changes = self.changes.clone();
478            let parent_clicks = self.parent_clicks.clone();
479            div()
480                .id("checkbox-parent")
481                .tab_group()
482                .size(px(100.))
483                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
484                .child(
485                    Checkbox::new("checkbox")
486                        .state(self.state)
487                        .disabled(self.disabled)
488                        .size_full()
489                        .on_change(move |state, _, _, _| changes.borrow_mut().push(state)),
490                )
491        }
492    }
493
494    fn harness(
495        cx: &mut TestAppContext,
496        state: CheckboxState,
497        disabled: bool,
498    ) -> (
499        &mut VisualTestContext,
500        Rc<RefCell<Vec<CheckboxState>>>,
501        Rc<Cell<usize>>,
502    ) {
503        let changes = Rc::new(RefCell::new(Vec::new()));
504        let parent_clicks = Rc::new(Cell::new(0));
505        let (_, cx) = cx.add_window_view({
506            let changes = changes.clone();
507            let parent_clicks = parent_clicks.clone();
508            move |_, _| CheckboxHarness {
509                state,
510                disabled,
511                changes,
512                parent_clicks,
513            }
514        });
515        cx.update(|window, cx| window.draw(cx).clear(cx));
516        (cx, changes, parent_clicks)
517    }
518
519    #[gpui::test]
520    fn pointer_activation_emits_the_next_state_once(cx: &mut TestAppContext) {
521        let (cx, changes, _) = harness(cx, CheckboxState::Unchecked, false);
522        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
523        assert_eq!(&*changes.borrow(), &[CheckboxState::Checked]);
524    }
525
526    #[gpui::test]
527    fn indeterminate_activation_becomes_checked(cx: &mut TestAppContext) {
528        let (cx, changes, _) = harness(cx, CheckboxState::Indeterminate, false);
529        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
530        assert_eq!(&*changes.borrow(), &[CheckboxState::Checked]);
531    }
532
533    #[gpui::test]
534    fn enter_and_space_each_emit_once(cx: &mut TestAppContext) {
535        let (cx, changes, _) = harness(cx, CheckboxState::Checked, false);
536        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
537        changes.borrow_mut().clear();
538        cx.update(|window, cx| {
539            assert!(window.focused(cx).is_some());
540            window.draw(cx).clear(cx);
541        });
542
543        for key in ["enter", "space"] {
544            let keystroke = Keystroke::parse(key).unwrap();
545            cx.simulate_event(KeyDownEvent {
546                keystroke: keystroke.clone(),
547                is_held: false,
548                prefer_character_input: false,
549            });
550            cx.simulate_event(KeyUpEvent { keystroke });
551        }
552
553        assert_eq!(
554            &*changes.borrow(),
555            &[CheckboxState::Unchecked, CheckboxState::Unchecked]
556        );
557    }
558
559    #[gpui::test]
560    fn disabled_checkbox_is_inert_and_allows_pointer_events_to_bubble(cx: &mut TestAppContext) {
561        let (cx, changes, parent_clicks) = harness(cx, CheckboxState::Unchecked, true);
562        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
563        cx.update(|window, cx| window.focus_next(cx));
564        cx.simulate_keystrokes("enter space");
565        assert!(changes.borrow().is_empty());
566        assert_eq!(parent_clicks.get(), 1);
567    }
568
569    #[test]
570    fn controlled_state_and_styling_are_application_owned() {
571        let _ = Checkbox::new("states")
572            .checked(true)
573            .indeterminate(true)
574            .styles(|styles| {
575                styles
576                    .checked(|style| style.opacity(0.8))
577                    .indeterminate(|style| style.opacity(0.7))
578                    .disabled(|style| style.when(true, |style| style.opacity(0.5)))
579            })
580            .hover(|style| style.opacity(0.9))
581            .active(|style| style.opacity(0.8))
582            .focus_visible(|style| style.opacity(0.7));
583    }
584
585    #[test]
586    fn semantic_root_styles_follow_checkbox_priority() {
587        let styles = |checkbox: Checkbox| {
588            checkbox.styles(|styles| {
589                styles
590                    .checked(|style| style.opacity(0.8))
591                    .indeterminate(|style| style.opacity(0.7))
592                    .disabled(|style| style.opacity(0.5))
593            })
594        };
595
596        assert_eq!(
597            styles(Checkbox::new("normal")).resolved_style().opacity,
598            None
599        );
600        assert_eq!(
601            styles(Checkbox::new("checked").checked(true))
602                .resolved_style()
603                .opacity,
604            Some(0.8)
605        );
606        assert_eq!(
607            styles(Checkbox::new("indeterminate").indeterminate(true))
608                .resolved_style()
609                .opacity,
610            Some(0.7)
611        );
612        assert_eq!(
613            styles(Checkbox::new("disabled").disabled(true))
614                .resolved_style()
615                .opacity,
616            Some(0.5)
617        );
618        assert_eq!(
619            styles(
620                Checkbox::new("checked-disabled")
621                    .checked(true)
622                    .disabled(true),
623            )
624            .resolved_style()
625            .opacity,
626            Some(0.5)
627        );
628
629        let checked_color = gpui::hsla(0.6, 0.7, 0.5, 1.0);
630        let combined = Checkbox::new("combined")
631            .checked(true)
632            .disabled(true)
633            .styles(|styles| {
634                styles
635                    .checked(|style| style.border_color(checked_color))
636                    .disabled(|style| style.opacity(0.5))
637            })
638            .resolved_style();
639        assert_eq!(combined.border_color, Some(checked_color));
640        assert_eq!(combined.opacity, Some(0.5));
641
642        let state_over_instance = styles(
643            Checkbox::new("state-over-instance")
644                .checked(true)
645                .disabled(true)
646                .opacity(0.9),
647        );
648        assert_eq!(state_over_instance.resolved_style().opacity, Some(0.5));
649    }
650
651    #[gpui::test]
652    fn accessibility_exposes_role_label_and_all_toggle_states(cx: &mut TestAppContext) {
653        type Captured = Arc<Mutex<Option<[accesskit::Node; 4]>>>;
654
655        struct A11yProbe {
656            captured: Captured,
657        }
658
659        impl Render for A11yProbe {
660            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
661                let captured = self.captured.clone();
662                canvas(
663                    move |_, window, cx| {
664                        let mut info = |checkbox: Checkbox| {
665                            let mut node = accesskit::Node::new(Role::CheckBox);
666                            checkbox
667                                .render(window, cx)
668                                .into_element()
669                                .write_a11y_info(&mut node);
670                            node
671                        };
672                        *captured.lock().unwrap() = Some([
673                            info(
674                                Checkbox::new("unchecked")
675                                    .accessibility_label("Remember me")
676                                    .on_change(|_, _, _, _| {}),
677                            ),
678                            info(
679                                Checkbox::new("checked")
680                                    .checked(true)
681                                    .on_change(|_, _, _, _| {}),
682                            ),
683                            info(
684                                Checkbox::new("mixed")
685                                    .indeterminate(true)
686                                    .on_change(|_, _, _, _| {}),
687                            ),
688                            info(
689                                Checkbox::new("disabled")
690                                    .disabled(true)
691                                    .on_change(|_, _, _, _| {}),
692                            ),
693                        ]);
694                    },
695                    |_, _, _, _| {},
696                )
697            }
698        }
699
700        let captured: Captured = Arc::new(Mutex::new(None));
701        let result = captured.clone();
702        let (_, cx) = cx.add_window_view(move |_, _| A11yProbe { captured });
703        cx.update(|window, cx| window.draw(cx).clear(cx));
704        let [unchecked, checked, mixed, disabled] = result.lock().unwrap().take().unwrap();
705
706        assert_eq!(unchecked.role(), Role::CheckBox);
707        assert_eq!(unchecked.label(), Some("Remember me"));
708        assert_eq!(unchecked.toggled(), Some(Toggled::False));
709        assert_eq!(checked.toggled(), Some(Toggled::True));
710        assert_eq!(mixed.toggled(), Some(Toggled::Mixed));
711        assert!(unchecked.supports_action(accesskit::Action::Click));
712        assert!(!disabled.supports_action(accesskit::Action::Click));
713    }
714}