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