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 {#[default] None, Selected, Both}
6#[derive(Clone,Copy)]
7pub(crate) struct SwitchLayout {pub min_width:f32,pub padding:f32,pub thumb_text_padding:f32}
8impl Default for SwitchLayout {fn default()->Self{Self{min_width:52.0,padding:4.0,thumb_text_padding:4.0}}}
9pub(crate) fn switch_widths(texts:Option<(&str,&str)>,metrics:crate::TextMetrics,layout:SwitchLayout)->(f32,f32) {
10    let text_min=texts.map(|(on,off)|{let style=TextStyle{size:9.0,..TextStyle::default()};(metrics.width(on,style).max(metrics.width(off,style))+2.0*layout.thumb_text_padding).max(24.0)}).unwrap_or(0.0);
11    (text_min,(2.0*text_min+4.0).max(layout.min_width).max(52.0))
12}
13
14impl Frame<'_> {
15    pub fn switch(&mut self, id: u64, label: &str, value: &mut bool, enabled: bool) -> Response {
16        self.switch_impl(id, label, value, enabled, false, false, SwitchIconMode::None, [[None;2];2],None,SwitchLayout::default())
17    }
18    /// Switch with the control following its label, as in an Android Switch view.
19    pub fn switch_trailing(&mut self, id: u64, label: &str, value: &mut bool, enabled: bool) -> Response {
20        self.switch_impl(id, label, value, enabled, true, false, SwitchIconMode::None, [[None;2];2],None,SwitchLayout::default())
21    }
22    /// Android-style trailing switch with layout-direction-aware placement.
23    pub fn switch_trailing_directional(&mut self, id: u64, label: &str, value: &mut bool, enabled: bool, rtl: bool) -> Response {
24        self.switch_impl(id, label, value, enabled, !rtl, rtl, SwitchIconMode::None, [[None;2];2],None,SwitchLayout::default())
25    }
26    /// Switch with optional selected and unselected icons.
27    pub fn switch_with_icons(&mut self,id:u64,label:&str,value:&mut bool,enabled:bool,icons:SwitchIconMode)->Response {self.switch_impl(id,label,value,enabled,false,false,icons,[[None;2];2],None,SwitchLayout::default())}
28    /// Directional switch with optional icons and configurable control placement.
29    pub fn switch_with_icons_directional(&mut self,id:u64,label:&str,value:&mut bool,enabled:bool,trailing:bool,rtl:bool,icons:SwitchIconMode)->Response {self.switch_impl(id,label,value,enabled,trailing,rtl,icons,[[None;2];2],None,SwitchLayout::default())}
30    pub(crate) fn switch_trailing_tinted(&mut self,id:u64,label:&str,value:&mut bool,enabled:bool,rtl:bool,tints:[[Option<Color>;2];2],texts:Option<(&str,&str)>,layout:SwitchLayout)->Response {self.switch_impl(id,label,value,enabled,!rtl,rtl,SwitchIconMode::None,tints,texts,layout)}
31    fn switch_impl(&mut self, id: u64, label: &str, value: &mut bool, enabled: bool, trailing: bool, rtl: bool, icons:SwitchIconMode, tints:[[Option<Color>;2];2], texts:Option<(&str,&str)>, layout:SwitchLayout) -> Response {
32        let b = self.allocate(36.0);
33        let mut r = self.interact(id, b, enabled);
34        if r.clicked {
35            *value = !*value;
36            r.changed = true;
37        }
38        let a = self.animate_geometry(id, 3, f32::from(*value), f32::from(*value));
39        let t = self.ui.theme;
40        let (text_min_width,preferred_width)=switch_widths(texts,self.ui.text_metrics,layout);
41        let track_width=preferred_width.min(b.width.max(0.0));
42        let track = Rect {
43            x: if trailing { (b.x + b.width - track_width).max(b.x) } else { b.x },
44            y: b.y + 2.0,
45            width: track_width,
46            height: 32.0,
47        };
48        let disabled = t.background.mix(t.text, 0.12);
49        let edge = tints[1][usize::from(*value)].unwrap_or(if r.enabled {
50            t.outline.mix(t.primary, a)
51        } else {
52            disabled
53        });
54        let fill = tints[1][usize::from(*value)].unwrap_or(if r.enabled {
55            t.surface_highest.mix(t.primary, a)
56        } else {
57            disabled
58        });
59        self.rect(track, 16.0, edge);
60        self.rect(track.inset(2.0), 14.0, fill);
61        let icon_visible=match icons {SwitchIconMode::None=>false,SwitchIconMode::Selected=>*value,SwitchIconMode::Both=>true};
62        let base_size=if icons==SwitchIconMode::Both {24.0}else{16.0+8.0*a};
63        let pressed_target=f32::from(r.enabled&&r.pressed);
64        let press=self.ui.motion.css_tween(id,220,pressed_target,0.0,crate::timing::TweenSpec::new(0.1,crate::timing::Easing::Linear),crate::timing::TweenSpec::new(0.25,crate::timing::Easing::Standard));
65        let diameter=base_size+(28.0-base_size)*press;
66        let thumb_width=diameter.max(text_min_width).min((track.width-4.0).max(0.0));
67        let start_center=if texts.is_some(){track.x+2.0+thumb_width/2.0}else{track.x+16.0};
68        let travel=if texts.is_some(){(track.width-4.0-thumb_width).max(0.0)}else{(track.width-32.0).max(0.0)};
69        let center_x=start_center+travel*if rtl{1.0-a}else{a};
70        let thumb=Rect{x:center_x-thumb_width/2.0,y:track.y+16.0-diameter/2.0,width:thumb_width,height:diameter};
71        let hover = self.animate(id, 0, f32::from(r.hovered), 0.0);
72        let ink = Rect {
73            x: center_x - 20.0,
74            y: track.y - 4.0,
75            width: 40.0,
76            height: 40.0,
77        };
78        if r.enabled && (hover > 0.001 || r.focused && self.ui.keyboard_focus) {
79            self.rect(
80                ink,
81                20.0,
82                (if *value{t.primary}else{t.text}).opacity(if r.focused && self.ui.keyboard_focus {
83                    0.12
84                } else {
85                    0.08 * hover
86                }),
87            );
88        }
89        self.ink(Response { bounds: ink, ..r }, 20.0, if *value{t.primary}else{t.text});
90        let handle = tints[0][usize::from(*value)].unwrap_or(if r.enabled {
91            t.outline.mix(t.on_primary, a)
92        } else if *value {t.background} else {t.text.opacity(0.38)});
93        self.rect(thumb, diameter/2.0, handle);
94        if let Some((on,off))=texts {
95            let text=if a>0.5 {on}else{off};
96            self.commands.push(DrawCommand::PushClip(thumb.intersect(self.clip)));
97            self.styled_text(thumb,text,t.on_surface_variant.opacity(if r.enabled{1.0}else{0.38}),TextStyle{size:9.0,align:1,..TextStyle::default()});
98            self.commands.push(DrawCommand::PopClip);
99        }
100        let mark = if r.enabled {
101            t.surface_highest.mix(t.on_primary_container, a)
102        } else if *value {t.text.opacity(0.38)} else {t.surface_highest.opacity(0.38)};
103        if icon_visible {
104            let cx=thumb.x+thumb.width/2.0;let cy=thumb.y+thumb.height/2.0;
105            if *value {self.paint_line([cx-5.0,cy],[cx-2.0,cy+3.0],1.5,mark);self.paint_line([cx-2.0,cy+3.0],[cx+5.0,cy-4.0],1.5,mark);}
106            else {self.paint_line([cx-4.0,cy-4.0],[cx+4.0,cy+4.0],1.5,mark);self.paint_line([cx+4.0,cy-4.0],[cx-4.0,cy+4.0],1.5,mark);}
107        }
108        self.styled_text(
109            Rect {
110                x: if trailing { b.x } else { b.x + track_width + layout.padding },
111                width: (b.width - track_width - layout.padding).max(0.0),
112                ..b
113            },
114            label,
115            t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
116            TextStyle {
117                size: 14.0,
118                align: if rtl { 2 } else { 0 },
119                letter_spacing: 0.25,
120                ..TextStyle::default()
121            },
122        );
123        self.focus_ring(r);
124        self.semantic(
125            r,
126            Role::Switch,
127            label,
128            *value,
129            Some(if *value {
130                CheckState::Checked
131            } else {
132                CheckState::Unchecked
133            }),
134            None,
135            None,
136        );
137        r
138    }
139}
140
141#[cfg(test)]
142#[path = "switch.spec.rs"]
143mod tests;