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