Skip to main content

bhoo/systems/material/
switch.rs

1use crate::*;
2
3/// Material switch icon visibility.
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum SwitchIconMode {
6    #[default]
7    None,
8    Selected,
9    Both,
10}
11#[derive(Clone, Copy)]
12pub(crate) struct SwitchLayout {
13    pub min_width: f32,
14    pub padding: f32,
15    pub thumb_text_padding: f32,
16}
17impl Default for SwitchLayout {
18    fn default() -> Self {
19        Self {
20            min_width: 52.0,
21            padding: 4.0,
22            thumb_text_padding: 4.0,
23        }
24    }
25}
26pub(crate) fn switch_widths(
27    texts: Option<(&str, &str)>,
28    metrics: crate::TextMetrics,
29    layout: SwitchLayout,
30) -> (f32, f32) {
31    let text_min = texts
32        .map(|(on, off)| {
33            let style = TextStyle {
34                size: 9.0,
35                ..TextStyle::default()
36            };
37            (metrics.width(on, style).max(metrics.width(off, style))
38                + 2.0 * layout.thumb_text_padding)
39                .max(24.0)
40        })
41        .unwrap_or(0.0);
42    (
43        text_min,
44        (2.0 * text_min + 4.0).max(layout.min_width).max(52.0),
45    )
46}
47
48impl Frame<'_> {
49    /// Paint an animated switch inside a custom control's track bounds.
50    /// Colors are ordered unchecked, then checked. The caller owns input.
51    pub fn switch_indicator(
52        &mut self,
53        id: u64,
54        track: Rect,
55        checked: bool,
56        track_colors: [Color; 2],
57        thumb_colors: [Color; 2],
58    ) {
59        let checked = f32::from(checked);
60        let position = self
61            .animate_geometry(id, 222, checked, checked)
62            .clamp(0.0, 1.0);
63        self.paint_rect(
64            track,
65            track.height * 0.5,
66            track_colors[0].mix(track_colors[1], position),
67        );
68        let diameter = track.height * (18.0 + 4.0 * position) / 28.0;
69        let inset = track.height * (5.0 - 2.0 * position) / 28.0;
70        let travel = (track.width - diameter - 2.0 * inset).max(0.0);
71        let thumb = Rect {
72            x: track.x + inset + travel * position,
73            y: track.y + (track.height - diameter) * 0.5,
74            width: diameter,
75            height: diameter,
76        };
77        self.paint_rect(
78            thumb,
79            diameter * 0.5,
80            thumb_colors[0].mix(thumb_colors[1], position),
81        );
82    }
83
84    pub fn switch(&mut self, id: u64, label: &str, value: &mut bool, enabled: bool) -> Response {
85        self.switch_impl(
86            id,
87            label,
88            value,
89            enabled,
90            false,
91            false,
92            SwitchIconMode::None,
93            [[None; 2]; 2],
94            None,
95            SwitchLayout::default(),
96        )
97    }
98    /// Switch with the control following its label, as in an Android Switch view.
99    pub fn switch_trailing(
100        &mut self,
101        id: u64,
102        label: &str,
103        value: &mut bool,
104        enabled: bool,
105    ) -> Response {
106        self.switch_impl(
107            id,
108            label,
109            value,
110            enabled,
111            true,
112            false,
113            SwitchIconMode::None,
114            [[None; 2]; 2],
115            None,
116            SwitchLayout::default(),
117        )
118    }
119    /// Android-style trailing switch with layout-direction-aware placement.
120    pub fn switch_trailing_directional(
121        &mut self,
122        id: u64,
123        label: &str,
124        value: &mut bool,
125        enabled: bool,
126        rtl: bool,
127    ) -> Response {
128        self.switch_impl(
129            id,
130            label,
131            value,
132            enabled,
133            !rtl,
134            rtl,
135            SwitchIconMode::None,
136            [[None; 2]; 2],
137            None,
138            SwitchLayout::default(),
139        )
140    }
141    /// Switch with optional selected and unselected icons.
142    pub fn switch_with_icons(
143        &mut self,
144        id: u64,
145        label: &str,
146        value: &mut bool,
147        enabled: bool,
148        icons: SwitchIconMode,
149    ) -> Response {
150        self.switch_impl(
151            id,
152            label,
153            value,
154            enabled,
155            false,
156            false,
157            icons,
158            [[None; 2]; 2],
159            None,
160            SwitchLayout::default(),
161        )
162    }
163    /// Directional switch with optional icons and configurable control placement.
164    pub fn switch_with_icons_directional(
165        &mut self,
166        id: u64,
167        label: &str,
168        value: &mut bool,
169        enabled: bool,
170        trailing: bool,
171        rtl: bool,
172        icons: SwitchIconMode,
173    ) -> Response {
174        self.switch_impl(
175            id,
176            label,
177            value,
178            enabled,
179            trailing,
180            rtl,
181            icons,
182            [[None; 2]; 2],
183            None,
184            SwitchLayout::default(),
185        )
186    }
187    pub(crate) fn switch_trailing_tinted(
188        &mut self,
189        id: u64,
190        label: &str,
191        value: &mut bool,
192        enabled: bool,
193        rtl: bool,
194        tints: [[Option<Color>; 2]; 2],
195        texts: Option<(&str, &str)>,
196        layout: SwitchLayout,
197    ) -> Response {
198        self.switch_impl(
199            id,
200            label,
201            value,
202            enabled,
203            !rtl,
204            rtl,
205            SwitchIconMode::None,
206            tints,
207            texts,
208            layout,
209        )
210    }
211    fn switch_impl(
212        &mut self,
213        id: u64,
214        label: &str,
215        value: &mut bool,
216        enabled: bool,
217        trailing: bool,
218        rtl: bool,
219        icons: SwitchIconMode,
220        tints: [[Option<Color>; 2]; 2],
221        texts: Option<(&str, &str)>,
222        layout: SwitchLayout,
223    ) -> Response {
224        let b = self.allocate(36.0);
225        let mut r = self.interact(id, b, enabled);
226        if r.clicked {
227            *value = !*value;
228            r.changed = true;
229        }
230        let a = self.animate_geometry(id, 3, f32::from(*value), f32::from(*value));
231        let t = self.ui.theme;
232        let (text_min_width, preferred_width) = switch_widths(texts, self.ui.text_metrics, layout);
233        let track_width = preferred_width.min(b.width.max(0.0));
234        let track = Rect {
235            x: if trailing {
236                (b.x + b.width - track_width).max(b.x)
237            } else {
238                b.x
239            },
240            y: b.y + 2.0,
241            width: track_width,
242            height: 32.0,
243        };
244        let disabled = t.background.mix(t.text, 0.12);
245        let edge = tints[1][usize::from(*value)].unwrap_or(if r.enabled {
246            t.outline.mix(t.primary, a)
247        } else {
248            disabled
249        });
250        let fill = tints[1][usize::from(*value)].unwrap_or(if r.enabled {
251            t.surface_highest.mix(t.primary, a)
252        } else {
253            disabled
254        });
255        self.rect(track, 16.0, edge);
256        self.rect(track.inset(2.0), 14.0, fill);
257        let icon_visible = match icons {
258            SwitchIconMode::None => false,
259            SwitchIconMode::Selected => *value,
260            SwitchIconMode::Both => true,
261        };
262        let base_size = if icons == SwitchIconMode::Both {
263            24.0
264        } else {
265            16.0 + 8.0 * a
266        };
267        let pressed_target = f32::from(r.enabled && r.pressed);
268        let press = self.ui.motion.css_tween(
269            id,
270            220,
271            pressed_target,
272            0.0,
273            crate::timing::TweenSpec::new(0.1, crate::timing::Easing::Linear),
274            crate::timing::TweenSpec::new(0.25, crate::timing::Easing::Standard),
275        );
276        let diameter = base_size + (28.0 - base_size) * press;
277        let thumb_width = diameter
278            .max(text_min_width)
279            .min((track.width - 4.0).max(0.0));
280        let start_center = if texts.is_some() {
281            track.x + 2.0 + thumb_width / 2.0
282        } else {
283            track.x + 16.0
284        };
285        let travel = if texts.is_some() {
286            (track.width - 4.0 - thumb_width).max(0.0)
287        } else {
288            (track.width - 32.0).max(0.0)
289        };
290        let center_x = start_center + travel * if rtl { 1.0 - a } else { a };
291        let thumb = Rect {
292            x: center_x - thumb_width / 2.0,
293            y: track.y + 16.0 - diameter / 2.0,
294            width: thumb_width,
295            height: diameter,
296        };
297        let hover = self.animate(id, 0, f32::from(r.hovered), 0.0);
298        let ink = Rect {
299            x: center_x - 20.0,
300            y: track.y - 4.0,
301            width: 40.0,
302            height: 40.0,
303        };
304        if r.enabled && (hover > 0.001 || r.focused && self.ui.keyboard_focus) {
305            self.rect(
306                ink,
307                20.0,
308                (if *value { t.primary } else { t.text }).opacity(
309                    if r.focused && self.ui.keyboard_focus {
310                        0.12
311                    } else {
312                        0.08 * hover
313                    },
314                ),
315            );
316        }
317        self.ink(
318            Response { bounds: ink, ..r },
319            20.0,
320            if *value { t.primary } else { t.text },
321        );
322        let handle = tints[0][usize::from(*value)].unwrap_or(if r.enabled {
323            t.outline.mix(t.on_primary, a)
324        } else if *value {
325            t.background
326        } else {
327            t.text.opacity(0.38)
328        });
329        self.rect(thumb, diameter / 2.0, handle);
330        if let Some((on, off)) = texts {
331            let text = if a > 0.5 { on } else { off };
332            self.commands
333                .push(DrawCommand::PushClip(thumb.intersect(self.clip)));
334            self.styled_text(
335                thumb,
336                text,
337                t.on_surface_variant
338                    .opacity(if r.enabled { 1.0 } else { 0.38 }),
339                TextStyle {
340                    size: 9.0,
341                    align: 1,
342                    ..TextStyle::default()
343                },
344            );
345            self.commands.push(DrawCommand::PopClip);
346        }
347        let mark = if r.enabled {
348            t.surface_highest.mix(t.on_primary_container, a)
349        } else if *value {
350            t.text.opacity(0.38)
351        } else {
352            t.surface_highest.opacity(0.38)
353        };
354        if icon_visible {
355            let cx = thumb.x + thumb.width / 2.0;
356            let cy = thumb.y + thumb.height / 2.0;
357            if *value {
358                self.paint_line([cx - 5.0, cy], [cx - 2.0, cy + 3.0], 1.5, mark);
359                self.paint_line([cx - 2.0, cy + 3.0], [cx + 5.0, cy - 4.0], 1.5, mark);
360            } else {
361                self.paint_line([cx - 4.0, cy - 4.0], [cx + 4.0, cy + 4.0], 1.5, mark);
362                self.paint_line([cx + 4.0, cy - 4.0], [cx - 4.0, cy + 4.0], 1.5, mark);
363            }
364        }
365        self.styled_text(
366            Rect {
367                x: if trailing {
368                    b.x
369                } else {
370                    b.x + track_width + layout.padding
371                },
372                width: (b.width - track_width - layout.padding).max(0.0),
373                ..b
374            },
375            label,
376            t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
377            TextStyle {
378                size: 14.0,
379                align: if rtl { 2 } else { 0 },
380                letter_spacing: 0.25,
381                ..TextStyle::default()
382            },
383        );
384        self.focus_ring(r);
385        self.semantic(
386            r,
387            Role::Switch,
388            label,
389            *value,
390            Some(if *value {
391                CheckState::Checked
392            } else {
393                CheckState::Unchecked
394            }),
395            None,
396            None,
397        );
398        r
399    }
400}
401
402#[cfg(test)]
403#[path = "switch.spec.rs"]
404mod tests;