Skip to main content

iced_cube/primitives/
radio.rs

1//! Radio buttons for picking one option from a small set.
2//!
3//! Each enabled radio takes keyboard focus from iced's focus operations,
4//! such as a dialog's Tab order. While focused its circle rings and Space
5//! or Enter selects it.
6
7use iced::widget::{self, button::Status, column, container, mouse_area, row, space, text};
8use iced::{Alignment, Background, Border, Color, Element, Length, Shadow, Theme, mouse};
9
10use crate::focus::{Ring, focusable};
11use crate::theme::{Tokens, fade, mix, radius, space as spacing, text_size};
12
13/// Diameter of the radio circle in logical pixels.
14pub const CIRCLE_SIZE: f32 = 16.0;
15
16const DOT_SIZE: f32 = 8.0;
17
18/// How a [`RadioGroup`] lays out its options.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
20pub enum Direction {
21    #[default]
22    Vertical,
23    Horizontal,
24}
25
26impl Direction {
27    pub const ALL: [Direction; 2] = [Direction::Vertical, Direction::Horizontal];
28}
29
30/// A single radio button. Convert it into an [`Element`] to render.
31///
32/// A radio without a message is rendered disabled.
33#[derive(Debug)]
34pub struct Radio<'a, V, Message> {
35    label: text::Fragment<'a>,
36    value: V,
37    is_selected: bool,
38    on_select: Option<Message>,
39}
40
41/// Creates a radio for `value`, selected when `selected` holds the same value.
42pub fn radio<'a, V, Message>(
43    label: impl text::IntoFragment<'a>,
44    value: V,
45    selected: Option<V>,
46) -> Radio<'a, V, Message>
47where
48    V: Copy + Eq,
49{
50    Radio {
51        label: label.into_fragment(),
52        value,
53        is_selected: selected == Some(value),
54        on_select: None,
55    }
56}
57
58impl<'a, V: Copy, Message> Radio<'a, V, Message> {
59    /// Sets the message for a click, built from this radio's value.
60    pub fn on_select(mut self, on_select: impl FnOnce(V) -> Message) -> Self {
61        self.on_select = Some(on_select(self.value));
62        self
63    }
64
65    pub fn is_selected(&self) -> bool {
66        self.is_selected
67    }
68
69    pub fn is_enabled(&self) -> bool {
70        self.on_select.is_some()
71    }
72}
73
74impl<'a, V, Message: Clone + 'a> From<Radio<'a, V, Message>> for Element<'a, Message> {
75    fn from(radio: Radio<'a, V, Message>) -> Self {
76        let selected = radio.is_selected;
77        let resting = if radio.on_select.is_some() {
78            Status::Active
79        } else {
80            Status::Disabled
81        };
82
83        let dot: Element<'a, Message> = if selected {
84            container(space())
85                .width(DOT_SIZE)
86                .height(DOT_SIZE)
87                .style(move |theme: &Theme| container::Style {
88                    background: Some(Background::Color(
89                        colours(&Tokens::of(theme), selected, resting).dot,
90                    )),
91                    border: Border::default().rounded(radius::FULL),
92                    ..container::Style::default()
93                })
94                .into()
95        } else {
96            space().into()
97        };
98
99        let circle = widget::button(container(dot).center(Length::Fill))
100            .width(CIRCLE_SIZE)
101            .height(CIRCLE_SIZE)
102            .padding(0)
103            .on_press_maybe(radio.on_select.clone())
104            .style(move |theme, status| style(&Tokens::of(theme), selected, status));
105        let on_activate = radio
106            .on_select
107            .clone()
108            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
109        let circle = focusable(circle, on_activate, Ring::around(radius::FULL));
110
111        let label = text(radio.label)
112            .size(text_size::SM)
113            .style(move |theme: &Theme| text::Style {
114                color: Some(colours(&Tokens::of(theme), selected, resting).label),
115            });
116        let label = match radio.on_select {
117            Some(message) => mouse_area(label)
118                .on_press(message)
119                .interaction(mouse::Interaction::Pointer),
120            None => mouse_area(label),
121        };
122
123        row![circle, label]
124            .spacing(spacing::SM)
125            .align_y(Alignment::Center)
126            .into()
127    }
128}
129
130/// A set of radios for the options of one value.
131///
132/// A group without a message renders every radio disabled.
133pub struct RadioGroup<'a, V, Message> {
134    options: Vec<V>,
135    selected: Option<V>,
136    direction: Direction,
137    on_select: Option<Box<dyn Fn(V) -> Message + 'a>>,
138}
139
140impl<V: std::fmt::Debug, Message> std::fmt::Debug for RadioGroup<'_, V, Message> {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        f.debug_struct("RadioGroup")
143            .field("options", &self.options)
144            .field("selected", &self.selected)
145            .field("direction", &self.direction)
146            .field("enabled", &self.on_select.is_some())
147            .finish()
148    }
149}
150
151/// Creates a group with one radio per option, labelled with its `Display` text.
152pub fn radio_group<'a, V, Message>(
153    options: impl IntoIterator<Item = V>,
154    selected: Option<V>,
155) -> RadioGroup<'a, V, Message>
156where
157    V: Copy + Eq + ToString,
158{
159    RadioGroup {
160        options: options.into_iter().collect(),
161        selected,
162        direction: Direction::default(),
163        on_select: None,
164    }
165}
166
167impl<'a, V, Message> RadioGroup<'a, V, Message> {
168    pub fn direction(mut self, direction: Direction) -> Self {
169        self.direction = direction;
170        self
171    }
172
173    /// Sets the message emitted with the option that was clicked.
174    pub fn on_select(mut self, on_select: impl Fn(V) -> Message + 'a) -> Self {
175        self.on_select = Some(Box::new(on_select));
176        self
177    }
178
179    pub fn is_enabled(&self) -> bool {
180        self.on_select.is_some()
181    }
182}
183
184impl<'a, V, Message> From<RadioGroup<'a, V, Message>> for Element<'a, Message>
185where
186    V: Copy + Eq + ToString + 'a,
187    Message: Clone + 'a,
188{
189    fn from(group: RadioGroup<'a, V, Message>) -> Self {
190        let on_select = group.on_select;
191        let radios = group.options.into_iter().map(|value| {
192            let mut radio = radio(value.to_string(), value, group.selected);
193            radio.on_select = on_select.as_ref().map(|f| f(value));
194            Element::from(radio)
195        });
196
197        match group.direction {
198            Direction::Vertical => column(radios).spacing(spacing::MD).into(),
199            Direction::Horizontal => row(radios)
200                .spacing(spacing::XL)
201                .align_y(Alignment::Center)
202                .wrap()
203                .into(),
204        }
205    }
206}
207
208/// Colours of a radio for its selection and interaction status.
209#[derive(Debug, Clone, Copy, PartialEq)]
210pub struct Colours {
211    pub background: Color,
212    pub border: Color,
213    pub dot: Color,
214    pub label: Color,
215}
216
217/// Resolves the colours of a radio.
218pub fn colours(tokens: &Tokens, selected: bool, status: Status) -> Colours {
219    let hover = matches!(status, Status::Hovered | Status::Pressed);
220    let pressed = status == Status::Pressed;
221
222    let border = match (selected, hover) {
223        (true, _) => tokens.primary,
224        (false, true) => mix(tokens.border, tokens.foreground, 0.6),
225        (false, false) => mix(tokens.border, tokens.foreground, 0.3),
226    };
227    let colours = Colours {
228        background: if pressed {
229            tokens.accent
230        } else {
231            Color::TRANSPARENT
232        },
233        border,
234        dot: tokens.primary,
235        label: tokens.foreground,
236    };
237
238    if status != Status::Disabled {
239        return colours;
240    }
241    Colours {
242        background: fade(colours.background, 0.5),
243        border: fade(colours.border, 0.5),
244        dot: fade(colours.dot, 0.5),
245        label: fade(colours.label, 0.5),
246    }
247}
248
249/// The iced button style used for the radio circle.
250pub fn style(tokens: &Tokens, selected: bool, status: Status) -> widget::button::Style {
251    let colours = colours(tokens, selected, status);
252    widget::button::Style {
253        background: Some(Background::Color(colours.background)),
254        text_color: colours.label,
255        border: Border {
256            color: colours.border,
257            width: 1.0,
258            radius: radius::FULL.into(),
259        },
260        shadow: Shadow::default(),
261        snap: true,
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use crate::theme::{dark, light};
269
270    const STATES: [Status; 4] = [
271        Status::Active,
272        Status::Hovered,
273        Status::Pressed,
274        Status::Disabled,
275    ];
276
277    #[test]
278    fn radio_is_selected_only_for_its_own_value() {
279        let r: Radio<'_, u8, ()> = radio("One", 1, Some(1));
280        assert!(r.is_selected());
281        let r: Radio<'_, u8, ()> = radio("One", 1, Some(2));
282        assert!(!r.is_selected());
283        let r: Radio<'_, u8, ()> = radio("One", 1, None);
284        assert!(!r.is_selected());
285    }
286
287    #[test]
288    fn radio_without_message_is_disabled() {
289        let r: Radio<'_, u8, u8> = radio("One", 1, None);
290        assert!(!r.is_enabled());
291        assert_eq!(r.on_select(|v| v * 10).on_select, Some(10));
292    }
293
294    #[test]
295    fn group_defaults_to_vertical_and_disabled() {
296        let g: RadioGroup<'_, u8, ()> = radio_group([1, 2, 3], None);
297        assert_eq!(g.direction, Direction::Vertical);
298        assert_eq!(g.options, vec![1, 2, 3]);
299        assert!(!g.is_enabled());
300        assert!(g.on_select(|_| ()).is_enabled());
301    }
302
303    #[test]
304    fn selected_border_uses_primary_in_every_enabled_status() {
305        for theme in [light(), dark()] {
306            let tokens = Tokens::of(&theme);
307            for status in [Status::Active, Status::Hovered, Status::Pressed] {
308                assert_eq!(colours(&tokens, true, status).border, tokens.primary);
309            }
310        }
311    }
312
313    #[test]
314    fn hover_strengthens_the_unselected_border() {
315        for theme in [light(), dark()] {
316            let tokens = Tokens::of(&theme);
317            let active = colours(&tokens, false, Status::Active);
318            let hovered = colours(&tokens, false, Status::Hovered);
319            assert_ne!(active.border, hovered.border);
320        }
321    }
322
323    #[test]
324    fn pressing_fills_the_background() {
325        let tokens = Tokens::of(&light());
326        for selected in [false, true] {
327            assert_eq!(
328                colours(&tokens, selected, Status::Pressed).background,
329                tokens.accent
330            );
331        }
332    }
333
334    #[test]
335    fn disabled_halves_alpha() {
336        for theme in [light(), dark()] {
337            let tokens = Tokens::of(&theme);
338            for selected in [false, true] {
339                let active = colours(&tokens, selected, Status::Active);
340                let disabled = colours(&tokens, selected, Status::Disabled);
341                assert!((disabled.dot.a - active.dot.a * 0.5).abs() < 1e-6);
342                assert!((disabled.label.a - active.label.a * 0.5).abs() < 1e-6);
343            }
344        }
345    }
346
347    #[test]
348    fn every_style_is_a_circle() {
349        for theme in [light(), dark()] {
350            let tokens = Tokens::of(&theme);
351            for selected in [false, true] {
352                for status in STATES {
353                    let style = style(&tokens, selected, status);
354                    assert_eq!(style.border.radius, radius::FULL.into());
355                    assert_eq!(style.border.width, 1.0);
356                }
357            }
358        }
359    }
360}