Skip to main content

gpui_material_components/selection/
checkbox.rs

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