Skip to main content

gpui_material_components/selection/
checkbox.rs

1use gpui::StatefulInteractiveElement;
2use std::rc::Rc;
3
4use gpui::{
5    AccessibleAction, App, BorderStyle, Bounds, ContentMask, ElementId, Entity, FocusHandle, Hsla,
6    InteractiveElement, IntoElement, ParentElement, Path, PathBuilder, PathStyle, Pixels,
7    RenderOnce, Rgba, SharedString, StrokeOptions, Styled, Window, canvas, div, point,
8    prelude::FluentBuilder, px, quad,
9};
10use gpui_base::{Checkbox as BaseCheckbox, TestSupportExt};
11use gpui_material_foundation::{
12    InteractionSource, animate, control_feedback::activate_feedback, current_material_theme,
13};
14use gpui_material_theme::{ColorRole, MotionKind, MotionSpec, MotionSpeed};
15
16use super::{
17    base::{BoundValueAction, SelectionControlBase},
18    focus_style, selection_target, selection_tone, tone,
19};
20
21/// The semantic checked state of a controlled [`Checkbox`].
22#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
23pub enum CheckboxState {
24    /// Not selected (default).
25    #[default]
26    Unchecked,
27    /// Selected.
28    Checked,
29    /// Partially selected (mixed), typically derived from child states via [`Checkbox::aggregate`].
30    Indeterminate,
31}
32
33impl CheckboxState {
34    /// Returns `true` when the state is [`CheckboxState::Checked`].
35    pub const fn is_checked(self) -> bool {
36        matches!(self, Self::Checked)
37    }
38
39    /// Returns `true` when the state is [`CheckboxState::Indeterminate`].
40    pub const fn is_indeterminate(self) -> bool {
41        matches!(self, Self::Indeterminate)
42    }
43
44    /// Returns the next state requested when the user activates the checkbox.
45    ///
46    /// Both [`CheckboxState::Unchecked`] and [`CheckboxState::Indeterminate`]
47    /// transition to [`CheckboxState::Checked`]; [`CheckboxState::Checked`]
48    /// transitions to [`CheckboxState::Unchecked`].
49    pub const fn next(self) -> Self {
50        match self {
51            Self::Unchecked | Self::Indeterminate => Self::Checked,
52            Self::Checked => Self::Unchecked,
53        }
54    }
55
56    pub(crate) const fn to_base(self) -> gpui_base::CheckboxState {
57        match self {
58            Self::Unchecked => gpui_base::CheckboxState::Unchecked,
59            Self::Checked => gpui_base::CheckboxState::Checked,
60            Self::Indeterminate => gpui_base::CheckboxState::Indeterminate,
61        }
62    }
63
64    pub(crate) const fn from_base(state: gpui_base::CheckboxState) -> Self {
65        match state {
66            gpui_base::CheckboxState::Unchecked => Self::Unchecked,
67            gpui_base::CheckboxState::Checked => Self::Checked,
68            gpui_base::CheckboxState::Indeterminate => Self::Indeterminate,
69        }
70    }
71}
72
73impl From<bool> for CheckboxState {
74    fn from(checked: bool) -> Self {
75        if checked {
76            Self::Checked
77        } else {
78            Self::Unchecked
79        }
80    }
81}
82
83type CheckboxChange = Rc<dyn Fn(CheckboxState, &mut Window, &mut App)>;
84
85/// Optional pigments for one checkbox state. Unset fields use the window theme.
86#[derive(Clone, Copy, Debug, Default, PartialEq)]
87pub struct CheckboxStateColors {
88    /// Stroke color of the checkmark or indeterminate dash.
89    pub checkmark: Option<Hsla>,
90    /// Interior fill color of the 18 dp checkbox square.
91    pub box_color: Option<Hsla>,
92    /// Outline stroke color of the checkbox square.
93    pub border: Option<Hsla>,
94}
95
96/// Per-instance checkbox colors. Disabled entries take precedence over error entries.
97#[derive(Clone, Copy, Debug, Default, PartialEq)]
98pub struct CheckboxColors {
99    /// Colors when enabled and unchecked.
100    pub unchecked: CheckboxStateColors,
101    /// Colors when enabled and checked.
102    pub checked: CheckboxStateColors,
103    /// Colors when enabled and indeterminate (mixed).
104    pub indeterminate: CheckboxStateColors,
105    /// Colors when enabled, in error state, and unchecked.
106    pub error_unchecked: CheckboxStateColors,
107    /// Colors when enabled, in error state, and checked.
108    pub error_checked: CheckboxStateColors,
109    /// Colors when enabled, in error state, and indeterminate.
110    pub error_indeterminate: CheckboxStateColors,
111    /// Colors when disabled and unchecked.
112    pub disabled_unchecked: CheckboxStateColors,
113    /// Colors when disabled and checked.
114    pub disabled_checked: CheckboxStateColors,
115    /// Colors when disabled and indeterminate.
116    pub disabled_indeterminate: CheckboxStateColors,
117}
118
119impl CheckboxColors {
120    fn for_state(self, state: CheckboxState, error: bool, disabled: bool) -> CheckboxStateColors {
121        use CheckboxState::{Checked, Indeterminate, Unchecked};
122        match (disabled, error, state) {
123            (true, _, Unchecked) => self.disabled_unchecked,
124            (true, _, Checked) => self.disabled_checked,
125            (true, _, Indeterminate) => self.disabled_indeterminate,
126            (false, true, Unchecked) => self.error_unchecked,
127            (false, true, Checked) => self.error_checked,
128            (false, true, Indeterminate) => self.error_indeterminate,
129            (false, false, Unchecked) => self.unchecked,
130            (false, false, Checked) => self.checked,
131            (false, false, Indeterminate) => self.indeterminate,
132        }
133    }
134}
135
136const CHECKBOX_SIZE: f32 = 18.;
137const CHECKBOX_STROKE: f32 = 2.;
138
139/// Controlled Material checkbox. Mixed activation requests Checked.
140#[derive(IntoElement)]
141pub struct Checkbox {
142    base: SelectionControlBase,
143    state: CheckboxState,
144    error: bool,
145    colors: CheckboxColors,
146    checkmark_stroke: StrokeOptions,
147    outline_stroke: Pixels,
148    on_change: Option<CheckboxChange>,
149}
150
151impl Checkbox {
152    /// Creates a controlled checkbox with an element ID, accessible/visible label, and current state.
153    pub fn new(
154        id: impl Into<ElementId>,
155        label: impl Into<SharedString>,
156        state: CheckboxState,
157    ) -> Self {
158        Self {
159            base: SelectionControlBase::new(id, label),
160            state,
161            error: false,
162            colors: CheckboxColors::default(),
163            checkmark_stroke: StrokeOptions {
164                line_width: CHECKBOX_STROKE,
165                ..StrokeOptions::default()
166            },
167            outline_stroke: px(CHECKBOX_STROKE),
168            on_change: None,
169        }
170    }
171
172    #[cfg(feature = "surfaces")]
173    pub(crate) fn decorative(mut self, decorative: bool) -> Self {
174        self.base.decorative(decorative);
175        self
176    }
177
178    /// Controls whether the visible label is rendered. Defaults to `true`.
179    /// When `false`, the constructor's label remains the accessible name and the trailing gap is omitted.
180    pub fn show_label(mut self, show: bool) -> Self {
181        self.base.show_label(show);
182        self
183    }
184
185    /// Replaces the visible label while keeping the constructor's label as the accessible name.
186    pub fn label_content(mut self, content: impl IntoElement) -> Self {
187        self.base.label_content(content);
188        self
189    }
190
191    /// Marks the checkbox as invalid, applying error styling and `aria-invalid` semantics when enabled.
192    pub fn error(mut self, error: bool) -> Self {
193        self.error = error;
194        self
195    }
196
197    /// Disables pointer, keyboard, and accessibility interaction when `true`.
198    pub fn disabled(mut self, disabled: bool) -> Self {
199        self.base.disabled(disabled);
200        self
201    }
202
203    /// Overrides checkmark, box fill, and border colors per checkbox state.
204    pub fn colors(mut self, colors: CheckboxColors) -> Self {
205        self.colors = colors;
206        self
207    }
208
209    /// Sets the uniform path stroke used for the checkmark and the mixed mark.
210    pub fn checkmark_stroke(mut self, stroke: StrokeOptions) -> Self {
211        self.checkmark_stroke = stroke;
212        self
213    }
214
215    /// Sets the width of the rounded box outline. Zero omits the outline.
216    pub fn outline_stroke(mut self, width: Pixels) -> Self {
217        self.outline_stroke = width;
218        self
219    }
220
221    /// Uses the caller's focus handle instead of an internal keyed handle.
222    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
223        self.base.track_focus(focus);
224        self
225    }
226
227    /// Reports pointer, keyboard and disabled feedback to a caller-owned source.
228    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
229        self.base.interaction_source(source);
230        self
231    }
232
233    /// Invoked with the requested next [`CheckboxState`] when toggled by pointer, keyboard, or assistive technology.
234    pub fn on_change(
235        mut self,
236        handler: impl Fn(CheckboxState, &mut Window, &mut App) + 'static,
237    ) -> Self {
238        self.on_change = Some(Rc::new(handler));
239        self
240    }
241
242    /// Derives a parent value from its children. An empty set is unchecked.
243    pub fn aggregate(children: impl IntoIterator<Item = CheckboxState>) -> CheckboxState {
244        let mut children = children.into_iter();
245        let first = children.next().unwrap_or_default();
246        if children.all(|child| child == first) {
247            first
248        } else {
249            CheckboxState::Indeterminate
250        }
251    }
252}
253
254impl RenderOnce for Checkbox {
255    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
256        let disabled = self.base.disabled;
257        let checked = self.state != CheckboxState::Unchecked;
258        let accent = if self.error && !disabled {
259            tone(ColorRole::Error, window, cx)
260        } else {
261            selection_tone(checked, disabled, window, cx)
262        };
263        let on_accent = tone(
264            if disabled {
265                ColorRole::Surface
266            } else if self.error {
267                ColorRole::OnError
268            } else {
269                ColorRole::OnPrimary
270            },
271            window,
272            cx,
273        );
274        let theme = current_material_theme(window, cx);
275        let motion = theme.motion;
276        let direction = theme.layout.direction;
277        let density = theme.layout.density;
278        let reduced = disabled || cx.reduce_motion();
279        let effects = motion.spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
280        let spatial = motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
281        let draw = animate(
282            (self.base.id.clone(), "check-draw"),
283            f32::from(checked),
284            spatial,
285            window,
286            cx,
287        )
288        .clamp(0., 1.);
289        let mixed = animate(
290            (self.base.id.clone(), "check-shape"),
291            f32::from(self.state == CheckboxState::Indeterminate),
292            effects,
293            window,
294            cx,
295        )
296        .clamp(0., 1.);
297        let inactive = if self.error && !disabled {
298            accent
299        } else {
300            selection_tone(false, disabled, window, cx)
301        };
302        let (box_color, border, mark) = resolve_checkbox_colors(
303            &self.base.id,
304            self.colors,
305            self.state,
306            self.error,
307            disabled,
308            accent,
309            inactive,
310            on_accent,
311            effects,
312            window,
313            cx,
314        );
315        let mark_stroke = checkbox_mark_stroke(self.checkmark_stroke);
316        let outline = px(checkbox_stroke_width(
317            self.outline_stroke.into(),
318            CHECKBOX_SIZE * 0.5,
319        ));
320        let indicator = canvas(
321            |_, _, _| (),
322            move |bounds, _, window, _| {
323                window.paint_quad(quad(
324                    bounds,
325                    px(2.),
326                    box_color,
327                    outline,
328                    if outline == px(0.) {
329                        gpui::transparent_black()
330                    } else {
331                        border
332                    },
333                    BorderStyle::Solid,
334                ));
335                if let Some(path) = checkbox_mark(bounds, draw, mixed, mark_stroke) {
336                    window.with_content_mask(Some(ContentMask { bounds }), |window| {
337                        window.paint_path(path, mark);
338                    });
339                }
340            },
341        )
342        .size(px(CHECKBOX_SIZE))
343        .flex_none();
344        if self.base.decorative {
345            return div()
346                .id(self.base.id)
347                .test_support()
348                .flex_none()
349                .size(px(24.))
350                .flex()
351                .items_center()
352                .justify_center()
353                .child(indicator)
354                .into_any_element();
355        }
356        let interaction = self.base.prepare_interaction(None, window, cx);
357        let group = self.base.group_name("material-checkbox");
358        let target = selection_target(
359            group.clone(),
360            indicator,
361            accent,
362            !disabled,
363            interaction.ripple.clone(),
364            direction,
365            density,
366            cx.reduce_motion(),
367        );
368        let click_ripple = interaction.ripple.clone();
369        let label = self.base.label.clone();
370        let control = BaseCheckbox::new(self.base.id.clone())
371            .track_focus(&interaction.focus)
372            .state(self.state.to_base())
373            .when(self.error && !disabled, |control| {
374                control.a11y_synthetic_children(|node| {
375                    node.parent_node()
376                        .set_invalid(gpui::accesskit::Invalid::True);
377                })
378            })
379            .disabled(disabled)
380            .accessibility_label(label)
381            .group(group)
382            .border_2()
383            .border_color(gpui::transparent_black())
384            .rounded_md()
385            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
386            .child(self.base.render_row(direction, target, window, cx));
387        let control = interaction.attach_feedback(control);
388        if disabled {
389            return control.into_any_element();
390        }
391        match self.on_change {
392            Some(handler) => {
393                let next = self.state.next();
394                let bound = BoundValueAction::new(next, handler, window, cx);
395                let a11y_bound = bound.clone();
396                control
397                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
398                        a11y_bound.invoke_default(window, cx);
399                    })
400                    .on_change(move |value, event, window, cx| {
401                        cx.stop_propagation();
402                        activate_feedback(event, &click_ripple, window, cx);
403                        bound.invoke(CheckboxState::from_base(value), window, cx);
404                    })
405                    .into_any_element()
406            }
407            None => control
408                .on_change(move |_, event, window, cx| {
409                    cx.stop_propagation();
410                    activate_feedback(event, &click_ripple, window, cx);
411                })
412                .into_any_element(),
413        }
414    }
415}
416
417#[allow(clippy::too_many_arguments)]
418fn resolve_checkbox_colors(
419    id: &ElementId,
420    colors: CheckboxColors,
421    state: CheckboxState,
422    error: bool,
423    disabled: bool,
424    accent: Hsla,
425    inactive: Hsla,
426    on_accent: Hsla,
427    effects: MotionSpec,
428    window: &mut Window,
429    cx: &mut App,
430) -> (Hsla, Hsla, Hsla) {
431    let checked = state != CheckboxState::Unchecked;
432    if colors == CheckboxColors::default() {
433        let fill = animate(
434            (id.clone(), "check-fill"),
435            f32::from(checked),
436            effects,
437            window,
438            cx,
439        )
440        .clamp(0., 1.);
441        (
442            accent.opacity(fill),
443            crate::control_style::mix_color(inactive, accent, fill),
444            on_accent,
445        )
446    } else {
447        let colors = colors.for_state(state, error, disabled);
448        let mut sample = |name, color| {
449            animate_checkbox_color((id.clone(), name).into(), color, effects, window, cx)
450        };
451        (
452            sample(
453                "check-box-color",
454                colors
455                    .box_color
456                    .unwrap_or(accent.opacity(f32::from(checked))),
457            ),
458            sample(
459                "check-border-color",
460                colors
461                    .border
462                    .unwrap_or(if checked { accent } else { inactive }),
463            ),
464            sample("check-mark-color", colors.checkmark.unwrap_or(on_accent)),
465        )
466    }
467}
468
469fn checkbox_stroke_width(width: f32, max: f32) -> f32 {
470    if width.is_finite() && width >= 0. {
471        width.min(max)
472    } else {
473        CHECKBOX_STROKE
474    }
475}
476
477fn checkbox_mark_stroke(mut stroke: StrokeOptions) -> StrokeOptions {
478    stroke.line_width = checkbox_stroke_width(stroke.line_width, CHECKBOX_SIZE);
479    if !stroke.miter_limit.is_finite() || stroke.miter_limit < 1. {
480        stroke.miter_limit = StrokeOptions::default().miter_limit;
481    }
482    stroke
483}
484
485fn checkbox_mark(
486    bounds: Bounds<Pixels>,
487    draw: f32,
488    mixed: f32,
489    stroke: StrokeOptions,
490) -> Option<Path> {
491    if draw == 0. || stroke.line_width == 0. {
492        return None;
493    }
494    let side = bounds.size.width;
495    let start = point(side * 0.2, side * 0.5);
496    let knee = point(side * (0.4 + 0.1 * mixed), side * (0.7 - 0.2 * mixed));
497    let end = point(side * 0.8, side * (0.3 + 0.2 * mixed));
498    let first = f32::from(knee.x - start.x).hypot(f32::from(knee.y - start.y));
499    let second = f32::from(end.x - knee.x).hypot(f32::from(end.y - knee.y));
500    let distance = (first + second) * draw;
501    let mut path = PathBuilder::default().with_style(PathStyle::Stroke(stroke));
502    path.move_to(bounds.origin + start);
503    if distance <= first {
504        path.line_to(bounds.origin + start + (knee - start) * (distance / first));
505    } else {
506        path.line_to(bounds.origin + knee);
507        path.line_to(bounds.origin + knee + (end - knee) * ((distance - first) / second));
508    }
509    path.build().ok()
510}
511
512fn animate_checkbox_color(
513    id: ElementId,
514    color: Hsla,
515    spec: MotionSpec,
516    window: &mut Window,
517    cx: &mut App,
518) -> Hsla {
519    let target = Rgba::from(color);
520    let mut sample = |channel, value| animate((id.clone(), channel), value, spec, window, cx);
521    let current = Rgba {
522        r: sample("red", target.r),
523        g: sample("green", target.g),
524        b: sample("blue", target.b),
525        a: sample("alpha", target.a),
526    };
527    if current == target {
528        color
529    } else {
530        current.into()
531    }
532}
533
534#[cfg(test)]
535mod checkbox_tests {
536    use super::*;
537    use gpui::size;
538
539    #[test]
540    fn checkbox_state_is_material_owned_and_preserves_helpers_and_base_roundtrip() {
541        assert_ne!(
542            std::any::TypeId::of::<CheckboxState>(),
543            std::any::TypeId::of::<gpui_base::CheckboxState>()
544        );
545        assert_eq!(CheckboxState::default(), CheckboxState::Unchecked);
546        assert_eq!(CheckboxState::from(false), CheckboxState::Unchecked);
547        assert_eq!(CheckboxState::from(true), CheckboxState::Checked);
548        assert!(!CheckboxState::Unchecked.is_checked());
549        assert!(CheckboxState::Checked.is_checked());
550        assert!(!CheckboxState::Indeterminate.is_checked());
551        assert!(CheckboxState::Indeterminate.is_indeterminate());
552        assert_eq!(CheckboxState::Unchecked.next(), CheckboxState::Checked);
553        assert_eq!(CheckboxState::Indeterminate.next(), CheckboxState::Checked);
554        assert_eq!(CheckboxState::Checked.next(), CheckboxState::Unchecked);
555        assert_eq!(Checkbox::aggregate([]), CheckboxState::Unchecked);
556        assert_eq!(
557            Checkbox::aggregate([CheckboxState::Checked, CheckboxState::Checked]),
558            CheckboxState::Checked
559        );
560        assert_eq!(
561            Checkbox::aggregate([CheckboxState::Checked, CheckboxState::Unchecked]),
562            CheckboxState::Indeterminate
563        );
564        for state in [
565            CheckboxState::Unchecked,
566            CheckboxState::Checked,
567            CheckboxState::Indeterminate,
568        ] {
569            assert_eq!(CheckboxState::from_base(state.to_base()), state);
570        }
571    }
572
573    #[test]
574    fn checkbox_mark_strokes_fit_and_draw_checked_and_mixed_geometry() {
575        let bounds = Bounds::new(
576            point(px(0.), px(0.)),
577            size(px(CHECKBOX_SIZE), px(CHECKBOX_SIZE)),
578        );
579        let default = checkbox_mark_stroke(StrokeOptions {
580            line_width: 2.,
581            ..StrokeOptions::default()
582        });
583        let wide = checkbox_mark_stroke(StrokeOptions {
584            line_width: 4.,
585            ..StrokeOptions::default()
586        });
587        assert_eq!(default.line_width, 2.);
588        assert_eq!(wide.line_width, 4.);
589        assert!(checkbox_mark(bounds, 1., 1., default).is_some());
590        assert!(checkbox_mark(bounds, 1., 1., wide).is_some());
591        assert!(checkbox_mark(bounds, 1., 0., default).is_some());
592        assert!(checkbox_mark(bounds, 1., 0., wide).is_some());
593        assert!(checkbox_mark(bounds, 0., 0., wide).is_none());
594        assert!(
595            checkbox_mark(
596                bounds,
597                1.,
598                0.,
599                StrokeOptions {
600                    line_width: 0.,
601                    ..wide
602                }
603            )
604            .is_none()
605        );
606        assert_eq!(checkbox_stroke_width(f32::MAX, CHECKBOX_SIZE * 0.5), 9.);
607        for invalid in [-1., f32::NAN, f32::INFINITY] {
608            assert_eq!(checkbox_stroke_width(invalid, CHECKBOX_SIZE * 0.5), 2.);
609            assert_eq!(
610                checkbox_mark_stroke(StrokeOptions {
611                    line_width: invalid,
612                    ..wide
613                })
614                .line_width,
615                2.
616            );
617        }
618    }
619}