Skip to main content

gpui_material_components/selection/
checkbox.rs

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