Skip to main content

gpui_deck/
checkbox.rs

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