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