Skip to main content

bhoo/systems/material/
checkbox.rs

1use crate::*;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4pub enum CheckState {
5    #[default]
6    Unchecked,
7    Checked,
8    Mixed,
9}
10
11impl Frame<'_> {
12    pub fn checkbox(
13        &mut self,
14        id: u64,
15        label: &str,
16        value: &mut CheckState,
17        enabled: bool,
18    ) -> Response {
19        self.check_control(id, label, value, enabled, true, false, false, [None;2],false)
20    }
21    /// Tri-state checkbox with an independent error visual state.
22    /// The caller supplies an accessible explanation alongside the control.
23    pub fn checkbox_with_error(
24        &mut self,
25        id: u64,
26        label: &str,
27        value: &mut CheckState,
28        enabled: bool,
29        error: bool,
30    ) -> Response {
31        self.check_control(id, label, value, enabled, true, error, false, [None;2],false)
32    }
33    #[allow(clippy::too_many_arguments)]
34    fn check_control(
35        &mut self,
36        id: u64,
37        label: &str,
38        value: &mut CheckState,
39        enabled: bool,
40        tristate: bool,
41        error: bool,
42        rtl: bool,
43        tint: [Option<Color>;2],
44        custom_indicator: bool,
45    ) -> Response {
46        let b = self.allocate(40.0);
47        let mut r = self.interact(id, b, enabled);
48        if r.clicked {
49            *value = match value {
50                CheckState::Unchecked => CheckState::Checked,
51                CheckState::Checked if tristate => CheckState::Mixed,
52                _ => CheckState::Unchecked,
53            };
54            r.changed = true;
55        }
56        let from = if self.ui.checkbox_transitions.contains_key(&id)
57            || self.ui.checkbox_transitions.len() < 4096
58        {
59            let entry = self
60                .ui
61                .checkbox_transitions
62                .entry(id)
63                .or_insert((*value, *value));
64            if entry.1 != *value {
65                *entry = (entry.1, *value);
66            }
67            entry.0
68        } else {
69            *value
70        };
71        let from_mixed = from == CheckState::Mixed && *value == CheckState::Checked;
72        let angular = self.ui.ripple_style == RippleStyle::AngularMaterial;
73        let t = self.ui.theme;
74        let selected = *value != CheckState::Unchecked;
75        use crate::timing::{Easing, TweenSpec};
76        let fill_in = TweenSpec::new(0.090, Easing::Cubic([0.0, 0.0, 0.2, 1.0]));
77        let fill_out = TweenSpec::new(0.090, Easing::Cubic([0.4, 0.0, 0.6, 1.0]));
78        let target = f32::from(selected);
79        let amount = self
80            .ui
81            .motion
82            .css_tween(id, 3, target, target, fill_in, fill_out);
83        let check_target = f32::from(*value == CheckState::Checked);
84        let check_in = if from_mixed && angular {
85            TweenSpec::new(0.180, Easing::Cubic([0.0, 0.0, 0.2, 1.0]))
86        } else if from_mixed {
87            TweenSpec::new(0.500, Easing::Cubic([0.14, 0.0, 0.0, 1.0]))
88        } else {
89            TweenSpec {
90                delay: 0.090,
91                duration: 0.090,
92                easing: Easing::Cubic([0.0, 0.0, 0.2, 1.0]),
93            }
94        };
95        let check_out = if angular && *value == CheckState::Mixed {
96            TweenSpec::new(0.090, Easing::Cubic([0.4, 0.0, 0.6, 1.0]))
97        } else {
98            TweenSpec::new(0.090, Easing::Cubic([0.4, 0.0, 1.0, 1.0]))
99        };
100        let checked_amount =
101            self.ui
102                .motion
103                .css_tween(id, 4, check_target, check_target, check_in, check_out);
104        let mixed_target = f32::from(*value == CheckState::Mixed);
105        let mixed_amount = self.ui.motion.css_tween(
106            id,
107            5,
108            mixed_target,
109            mixed_target,
110            if angular { fill_out } else { fill_in },
111            if from_mixed && !angular {
112                check_in
113            } else {
114                fill_out
115            },
116        );
117        let box_rect = Rect {
118            x: if rtl { b.x + b.width - 29.0 } else { b.x + 11.0 },
119            y: b.y + 11.0,
120            width: 18.0,
121            height: 18.0,
122        };
123        let color = tint[usize::from(selected)].unwrap_or(if r.enabled && error {
124            t.error
125        } else if r.enabled {
126            t.on_surface_variant.mix(t.primary, amount)
127        } else {
128            t.text.opacity(0.38)
129        });
130        let ink = Rect {
131            x: if rtl { b.x + b.width - 40.0 } else { b.x },
132            y: b.y,
133            width: 40.0,
134            height: 40.0,
135        };
136        let hovered = if angular {
137            r.hovered && self.input.pointer.is_some_and(|p| ink.contains(p))
138        } else {
139            r.hovered
140        };
141        let hover = self.animate(id, 0, f32::from(hovered), 0.0);
142        let focused = r.focused && (angular || self.ui.keyboard_focus);
143        let state_color = if error {
144            t.error
145        } else if angular && *value != CheckState::Checked {
146            t.text
147        } else {
148            t.primary
149        };
150        if r.enabled && (hover > 0.001 || focused) {
151            self.rect(
152                ink,
153                20.0,
154                state_color.opacity(if focused { 0.12 } else { 0.08 * hover }),
155            );
156        }
157        self.ink(Response { bounds: ink, ..r }, 20.0, state_color);
158        if !custom_indicator {
159        if amount < 0.999 {
160            // Leave the center transparent so the actual surface and state layer
161            // remain visible, including on non-default and translucent surfaces.
162            for edge in [
163                Rect {
164                    height: 2.0,
165                    ..box_rect
166                },
167                Rect {
168                    y: box_rect.y + 16.0,
169                    height: 2.0,
170                    ..box_rect
171                },
172                Rect {
173                    y: box_rect.y + 2.0,
174                    width: 2.0,
175                    height: 14.0,
176                    ..box_rect
177                },
178                Rect {
179                    x: box_rect.x + 16.0,
180                    y: box_rect.y + 2.0,
181                    width: 2.0,
182                    height: 14.0,
183                },
184            ] {
185                self.rect(edge, 1.0, color);
186            }
187        }
188        if amount > 0.001 {
189            self.rect(box_rect, 2.0, color.opacity(amount));
190        }
191        let mark = if r.enabled && error {
192            t.on_error
193        } else if r.enabled {
194            t.on_primary
195        } else {
196            t.background
197        };
198        if checked_amount > 0.001 {
199            // Angular's SVG fills the 14px content box inside the 2px border.
200            // Reveal the two path segments by length like its stroke-dashoffset.
201            let scale = 14.0 / 24.0;
202            let origin = [box_rect.x + 2.0, box_rect.y + 2.0];
203            let points = [[1.73, 12.91], [8.1, 19.28], [22.79, 4.59]];
204            let lengths = [9.0085_f32, 20.7748_f32];
205            let distance = if *value == CheckState::Mixed || (from_mixed && !angular) {
206                1.0
207            } else {
208                checked_amount
209            } * (lengths[0] + lengths[1]);
210            let p = |v: [f32; 2]| [origin[0] + v[0] * scale, origin[1] + v[1] * scale];
211            let interpolate = |a: [f32; 2], b: [f32; 2], f: f32| {
212                [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f]
213            };
214            let exiting = *value == CheckState::Unchecked;
215            let (mut path, count) = if exiting {
216                // Negative SVG dash offset erases from the beginning of the path.
217                let start = lengths[0] + lengths[1] - distance;
218                if start < lengths[0] {
219                    (
220                        [
221                            p(interpolate(points[0], points[1], start / lengths[0])),
222                            p(points[1]),
223                            p(points[2]),
224                        ],
225                        3,
226                    )
227                } else {
228                    (
229                        [
230                            p(interpolate(
231                                points[1],
232                                points[2],
233                                ((start - lengths[0]) / lengths[1]).clamp(0.0, 1.0),
234                            )),
235                            p(points[2]),
236                            [0.0; 2],
237                        ],
238                        2,
239                    )
240                }
241            } else {
242                let first = (distance / lengths[0]).clamp(0.0, 1.0);
243                let second = ((distance - lengths[0]) / lengths[1]).clamp(0.0, 1.0);
244                let mut path = [
245                    p(points[0]),
246                    p(interpolate(points[0], points[1], first)),
247                    [0.0; 2],
248                ];
249                let count = if second > 0.0 {
250                    path[2] = p(interpolate(points[1], points[2], second));
251                    3
252                } else {
253                    2
254                };
255                (path, count)
256            };
257            if *value == CheckState::Mixed || from_mixed {
258                let angle = if from_mixed && angular {
259                    (1.0 - checked_amount) * std::f32::consts::FRAC_PI_4
260                } else if from_mixed {
261                    (1.0 + 7.0 * checked_amount) * std::f32::consts::FRAC_PI_4
262                } else {
263                    (1.0 - checked_amount) * std::f32::consts::FRAC_PI_4
264                };
265                let (sin, cos) = angle.sin_cos();
266                let center = [box_rect.x + 9.0, box_rect.y + 9.0];
267                for point in path.iter_mut().take(count as usize) {
268                    let x = point[0] - center[0];
269                    let y = point[1] - center[1];
270                    *point = [center[0] + x * cos - y * sin, center[1] + x * sin + y * cos];
271                }
272            }
273            self.commands.push(DrawCommand::Polyline {
274                points: path,
275                count,
276                width: 3.12 * scale,
277                color: if exiting || *value == CheckState::Mixed || from_mixed {
278                    mark.opacity(checked_amount)
279                } else {
280                    mark
281                },
282            });
283        }
284        if mixed_amount > 0.001 {
285            let angle = if from_mixed && angular {
286                -(1.0 - mixed_amount) * std::f32::consts::FRAC_PI_4
287            } else if from_mixed {
288                (1.0 - mixed_amount) * 7.0 * std::f32::consts::FRAC_PI_4
289            } else if selected
290                && (checked_amount > 0.001 || (angular && from == CheckState::Checked))
291            {
292                -(1.0 - mixed_amount) * std::f32::consts::FRAC_PI_4
293            } else {
294                0.0
295            };
296            let (sin, cos) = angle.sin_cos();
297            let center = [box_rect.x + 9.0, box_rect.y + 9.0];
298            let scale = if angular
299                && matches!(
300                    (from, *value),
301                    (CheckState::Unchecked, CheckState::Mixed)
302                        | (CheckState::Mixed, CheckState::Unchecked)
303                ) {
304                mixed_amount
305            } else {
306                1.0
307            };
308            let offset = [7.0 * scale * cos, 7.0 * scale * sin];
309            self.commands.push(DrawCommand::Polyline {
310                points: [
311                    [center[0] - offset[0], center[1] - offset[1]],
312                    [center[0] + offset[0], center[1] + offset[1]],
313                    [0.0; 2],
314                ],
315                count: 2,
316                width: 2.0,
317                color: mark.opacity(mixed_amount),
318            });
319        }
320        }
321        self.styled_text(
322            Rect {
323                x: if rtl { b.x } else { b.x + 44.0 },
324                width: (b.width - 44.0).max(0.0),
325                ..b
326            },
327            label,
328            t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
329            TextStyle {
330                size: 14.0,
331                align: if rtl { 2 } else { 0 },
332                letter_spacing: 0.25,
333                ..TextStyle::default()
334            },
335        );
336        self.focus_ring(r);
337        self.semantic(r, Role::Checkbox, label, selected, Some(*value), None, None);
338        if let Some(node) = self.ui.semantics.last_mut() {
339            node.invalid = error;
340        }
341        r
342    }
343    /// Binary checkbox; the mixed state is never introduced by this API.
344    pub fn checkbox_bool(
345        &mut self,
346        id: u64,
347        label: &str,
348        value: &mut bool,
349        enabled: bool,
350    ) -> Response {
351        self.checkbox_bool_with_error(id, label, value, enabled, false)
352    }
353    /// Binary checkbox with a caller-controlled, independent error state.
354    pub fn checkbox_bool_with_error(
355        &mut self,
356        id: u64,
357        label: &str,
358        value: &mut bool,
359        enabled: bool,
360        error: bool,
361    ) -> Response {
362        let mut state = if *value {
363            CheckState::Checked
364        } else {
365            CheckState::Unchecked
366        };
367        let r = self.check_control(id, label, &mut state, enabled, false, error, false, [None;2],false);
368        if r.changed {
369            *value = state == CheckState::Checked;
370        }
371        r
372    }
373    /// Binary checkbox with layout-direction-aware indicator placement.
374    pub fn checkbox_bool_directional(&mut self, id:u64, label:&str, value:&mut bool, enabled:bool, rtl:bool) -> Response {
375        let mut state = if *value { CheckState::Checked } else { CheckState::Unchecked };
376        let response = self.check_control(id, label, &mut state, enabled, false, false, rtl, [None;2],false);
377        if response.changed { *value = state == CheckState::Checked; }
378        response
379    }
380    pub(crate) fn checkbox_bool_directional_tinted(&mut self,id:u64,label:&str,value:&mut bool,enabled:bool,rtl:bool,tint:[Option<Color>;2],custom_indicator:bool)->Response {
381        let mut state=if *value {CheckState::Checked}else{CheckState::Unchecked};
382        let response=self.check_control(id,label,&mut state,enabled,false,false,rtl,tint,custom_indicator);
383        if response.changed {*value=state==CheckState::Checked;}
384        response
385    }
386}
387
388#[cfg(test)]
389#[path = "checkbox.spec.rs"]
390mod tests;