Skip to main content

gpui_material_components/selection/
checkbox.rs

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