Skip to main content

bhoo/systems/material/
radio.rs

1use crate::*;
2
3#[derive(Clone, Copy, Debug)]
4pub struct Choice<'a> {
5    pub id: u64,
6    pub label: &'a str,
7    pub enabled: bool,
8}
9
10impl Frame<'_> {
11    fn radio_indicator(&mut self,id:u64,outer:Rect,selected:bool,enabled:bool,tint:Option<Color>) {
12        use crate::timing::{Easing,TweenSpec};
13        let target=f32::from(selected);let linear=TweenSpec::new(0.05,Easing::Linear);
14        let color_progress=self.ui.motion.css_tween(id,210,target,target,linear,linear);
15        let opacity=self.ui.motion.css_tween(id,211,target,target,linear,linear);
16        let scale=self.ui.motion.css_tween(id,212,target,target,TweenSpec::new(0.3,Easing::EmphasizedDecelerate),TweenSpec::new(0.0,Easing::Linear));
17        let theme=self.ui.theme;let color=tint.unwrap_or(if enabled{theme.on_surface_variant.mix(theme.primary,color_progress)}else{theme.text.opacity(0.38)});
18        self.commands.push(DrawCommand::Outline{bounds:outer,radius:10.0,width:2.0,color});
19        let alpha=if enabled{opacity}else{target};let scale=if !enabled||!selected{1.0}else{scale};let diameter=10.0*scale;
20        if alpha>0.001&&diameter>0.001 {let dot=Rect{x:outer.x+(outer.width-diameter)/2.0,y:outer.y+(outer.height-diameter)/2.0,width:diameter,height:diameter};self.rect(dot,diameter/2.0,tint.map(|c|c.opacity(alpha)).unwrap_or(if enabled{theme.primary.opacity(alpha)}else{theme.text.opacity(0.38)}));}
21    }
22    /// Radio choice primitive. Group selection/navigation is supplied by `radio_group`.
23    pub fn radio(&mut self, id: u64, label: &str, selected: bool, enabled: bool) -> Response {
24        self.radio_directional(id, label, selected, enabled, false)
25    }
26    /// Radio choice with layout-direction-aware indicator placement.
27    pub fn radio_directional(&mut self, id: u64, label: &str, selected: bool, enabled: bool, rtl: bool) -> Response {
28        self.radio_directional_tinted(id,label,selected,enabled,rtl,None,false)
29    }
30    pub(crate) fn radio_directional_tinted(&mut self,id:u64,label:&str,selected:bool,enabled:bool,rtl:bool,tint:Option<Color>,custom_indicator:bool)->Response {
31        let b = self.allocate(40.0);
32        let r = self.interact(id, b, enabled);
33        let t = self.ui.theme;
34        let outer = Rect {
35            x: if rtl { b.x + b.width - 30.0 } else { b.x + 10.0 },
36            y: b.y + 10.0,
37            width: 20.0,
38            height: 20.0,
39        };
40        self.state_layer(
41            Response {
42                bounds: Rect {
43                    x: outer.x - 10.0,
44                    y: outer.y - 10.0,
45                    width: 40.0,
46                    height: 40.0,
47                },
48                ..r
49            },
50            20.0,
51            if selected {t.primary}else{t.on_surface_variant},
52        );
53        if !custom_indicator {self.radio_indicator(id,outer,selected,r.enabled,tint);}
54        self.styled_text(
55            Rect {
56                x: if rtl { b.x } else { b.x + 44.0 },
57                width: (b.width - 44.0).max(0.0),
58                ..b
59            },
60            label,
61            t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
62            TextStyle {
63                size: 14.0,
64                align: if rtl { 2 } else { 0 },
65                letter_spacing: 0.25,
66                ..TextStyle::default()
67            },
68        );
69        self.focus_ring(r);
70        self.semantic(
71            r,
72            Role::Radio,
73            label,
74            selected,
75            Some(if selected {
76                CheckState::Checked
77            } else {
78                CheckState::Unchecked
79            }),
80            None,
81            None,
82        );
83        r
84    }
85    /// A roving radio group: one Tab stop, arrows/Home/End select enabled choices.
86    /// Each choice has a stable semantic/motion ID distinct from the group ID.
87    pub fn radio_group(
88        &mut self,
89        id: u64,
90        label: &str,
91        choices: &[Choice<'_>],
92        selected: &mut u64,
93        enabled: bool,
94    ) -> Response {
95        self.radio_group_directional(id,label,choices,selected,enabled,false)
96    }
97    /// Radio group with mirrored indicator and label placement for right-to-left layouts.
98    pub fn radio_group_directional(&mut self,id:u64,label:&str,choices:&[Choice<'_>],selected:&mut u64,enabled:bool,rtl:bool)->Response {
99        self.label(label);
100        let b = self.allocate((52.0 * choices.len() as f32 - 12.0).max(0.0));
101        let mut r = self.interact(id, b, enabled && choices.iter().any(|c| c.enabled));
102        let previous = *selected;
103        let valid = |index: usize| choices[index].enabled;
104        let current = choices.iter().position(|c| c.id == *selected && c.enabled);
105        if current.is_none()
106            && let Some(first) = choices.iter().find(|c| c.enabled)
107        {
108            *selected = first.id;
109        }
110        if r.clicked
111            && self.input.released
112            && self.ui.capture == Capture::Pointer
113            && let Some(p) = self.input.pointer
114        {
115            let index = ((p[1] - b.y) / 52.0).floor().max(0.0) as usize;
116            if let Some(choice) = choices.get(index).filter(|c| c.enabled) {
117                *selected = choice.id;
118            } else {
119                r.clicked = false;
120            }
121        }
122        if let Some(key) = self.key_for(r) {
123            let len = choices.len();
124            let start = choices.iter().position(|c| c.id == *selected).unwrap_or(0);
125            let target = match key {
126                Key::Down => (1..=len).map(|n| (start + n) % len).find(|i| valid(*i)),
127                Key::Up => (1..=len)
128                    .map(|n| (start + len - n) % len)
129                    .find(|i| valid(*i)),
130                Key::Right if !rtl => (1..=len).map(|n| (start+n)%len).find(|i|valid(*i)),
131                Key::Left if rtl => (1..=len).map(|n| (start+n)%len).find(|i|valid(*i)),
132                Key::Left if !rtl => (1..=len).map(|n| (start+len-n)%len).find(|i|valid(*i)),
133                Key::Right if rtl => (1..=len).map(|n| (start+len-n)%len).find(|i|valid(*i)),
134                Key::Home => (0..len).find(|i| valid(*i)),
135                Key::End => (0..len).rev().find(|i| valid(*i)),
136                _ => None,
137            };
138            if let Some(index) = target {
139                *selected = choices[index].id;
140            }
141        }
142        self.semantic(r, Role::RadioGroup, label, false, None, None, None);
143        for (index, choice) in choices.iter().enumerate() {
144            assert!(self.ui.seen.insert(choice.id), "Duplicate radio choice ID");
145            let row = Rect {
146                y: b.y + index as f32 * 52.0,
147                height: 40.0,
148                ..b
149            };
150            let checked = choice.id == *selected;
151            let response = Response {
152                id: choice.id,
153                bounds: row,
154                enabled: r.enabled && choice.enabled,
155                focused: r.focused && checked,
156                ..Response::default()
157            };
158            let t = self.ui.theme;
159            let outer = Rect {
160                x: if rtl {row.x+row.width-30.0}else{row.x+10.0},
161                y: row.y + 10.0,
162                width: 20.0,
163                height: 20.0,
164            };
165            let opacity = if response.enabled { 1.0 } else { 0.38 };
166            let press = r.pressed
167                && (r.focused && self.ui.keyboard_focus && checked
168                    || self.input.pointer.is_some_and(|p| row.contains(p)));
169            self.state_layer(
170                Response {
171                    pressed: press,
172                    hovered: response.enabled
173                        && self.input.pointer.is_some_and(|p| row.contains(p)),
174                    bounds: Rect {
175                        x: outer.x - 10.0,
176                        y: outer.y - 10.0,
177                        width: 40.0,
178                        height: 40.0,
179                    },
180                    ..response
181                },
182                20.0,
183                if checked {t.primary}else{t.on_surface_variant},
184            );
185            self.radio_indicator(choice.id,outer,checked,response.enabled,None);
186            self.styled_text(
187                Rect {
188                    x: if rtl {row.x}else{row.x+44.0},
189                    width: (row.width - 44.0).max(0.0),
190                    ..row
191                },
192                choice.label,
193                t.text.opacity(opacity),
194                TextStyle {
195                    size: 14.0,
196                    align: if rtl {2}else{0},
197                    letter_spacing: 0.25,
198                    ..TextStyle::default()
199                },
200            );
201            self.focus_ring(response);
202            self.semantic(
203                response,
204                Role::Radio,
205                choice.label,
206                checked,
207                Some(if checked {
208                    CheckState::Checked
209                } else {
210                    CheckState::Unchecked
211                }),
212                None,
213                None,
214            );
215        }
216        r.changed = previous != *selected;
217        r
218    }
219}
220
221#[cfg(test)]
222#[path = "radio.spec.rs"]
223mod tests;