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: Element<'a, Message> =
110            focusable(circle, on_activate, Ring::around(radius::FULL)).into();
111        // The circle carries the annotation, so the focus it reports is the
112        // radio's. The label is its name.
113        #[cfg(feature = "icedwright")]
114        let circle: Element<'a, Message> = {
115            use icedwright_probe::{role, semantic};
116            let mut annotated = semantic(circle)
117                .role(role::RadioButton)
118                .name(radio.label.clone())
119                .checked(selected)
120                .component("iced_cube::radio");
121            if radio.on_select.is_none() {
122                annotated = annotated.disabled(true);
123            }
124            annotated.into()
125        };
126        let label = text(radio.label)
127            .size(text_size::SM)
128            .style(move |theme: &Theme| text::Style {
129                color: Some(colours(&Tokens::of(theme), selected, resting).label),
130            });
131        let label = match radio.on_select {
132            Some(message) => mouse_area(label)
133                .on_press(message)
134                .interaction(mouse::Interaction::Pointer),
135            None => mouse_area(label),
136        };
137
138        row![circle, label]
139            .spacing(spacing::SM)
140            .align_y(Alignment::Center)
141            .into()
142    }
143}
144
145/// A set of radios for the options of one value.
146///
147/// A group without a message renders every radio disabled.
148pub struct RadioGroup<'a, V, Message> {
149    options: Vec<V>,
150    selected: Option<V>,
151    direction: Direction,
152    on_select: Option<Box<dyn Fn(V) -> Message + 'a>>,
153}
154
155impl<V: std::fmt::Debug, Message> std::fmt::Debug for RadioGroup<'_, V, Message> {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.debug_struct("RadioGroup")
158            .field("options", &self.options)
159            .field("selected", &self.selected)
160            .field("direction", &self.direction)
161            .field("enabled", &self.on_select.is_some())
162            .finish()
163    }
164}
165
166/// Creates a group with one radio per option, labelled with its `Display` text.
167pub fn radio_group<'a, V, Message>(
168    options: impl IntoIterator<Item = V>,
169    selected: Option<V>,
170) -> RadioGroup<'a, V, Message>
171where
172    V: Copy + Eq + ToString,
173{
174    RadioGroup {
175        options: options.into_iter().collect(),
176        selected,
177        direction: Direction::default(),
178        on_select: None,
179    }
180}
181
182impl<'a, V, Message> RadioGroup<'a, V, Message> {
183    pub fn direction(mut self, direction: Direction) -> Self {
184        self.direction = direction;
185        self
186    }
187
188    /// Sets the message emitted with the option that was clicked.
189    pub fn on_select(mut self, on_select: impl Fn(V) -> Message + 'a) -> Self {
190        self.on_select = Some(Box::new(on_select));
191        self
192    }
193
194    pub fn is_enabled(&self) -> bool {
195        self.on_select.is_some()
196    }
197}
198
199impl<'a, V, Message> From<RadioGroup<'a, V, Message>> for Element<'a, Message>
200where
201    V: Copy + Eq + ToString + 'a,
202    Message: Clone + 'a,
203{
204    fn from(group: RadioGroup<'a, V, Message>) -> Self {
205        let on_select = group.on_select;
206        let radios = group.options.into_iter().map(|value| {
207            let mut radio = radio(value.to_string(), value, group.selected);
208            radio.on_select = on_select.as_ref().map(|f| f(value));
209            Element::from(radio)
210        });
211
212        let element: Element<'a, Message> = match group.direction {
213            Direction::Vertical => column(radios).spacing(spacing::MD).into(),
214            Direction::Horizontal => row(radios)
215                .spacing(spacing::XL)
216                .align_y(Alignment::Center)
217                .wrap()
218                .into(),
219        };
220        #[cfg(feature = "icedwright")]
221        let element = icedwright_probe::semantic(element)
222            .role(icedwright_probe::role::RadioGroup)
223            .component("iced_cube::radio_group")
224            .into();
225        element
226    }
227}
228
229/// Colours of a radio for its selection and interaction status.
230#[derive(Debug, Clone, Copy, PartialEq)]
231pub struct Colours {
232    pub background: Color,
233    pub border: Color,
234    pub dot: Color,
235    pub label: Color,
236}
237
238/// Resolves the colours of a radio.
239pub fn colours(tokens: &Tokens, selected: bool, status: Status) -> Colours {
240    let hover = matches!(status, Status::Hovered | Status::Pressed);
241    let pressed = status == Status::Pressed;
242
243    let border = match (selected, hover) {
244        (true, _) => tokens.primary,
245        (false, true) => mix(tokens.border, tokens.foreground, 0.6),
246        (false, false) => mix(tokens.border, tokens.foreground, 0.3),
247    };
248    let colours = Colours {
249        background: if pressed {
250            tokens.accent
251        } else {
252            Color::TRANSPARENT
253        },
254        border,
255        dot: tokens.primary,
256        label: tokens.foreground,
257    };
258
259    if status != Status::Disabled {
260        return colours;
261    }
262    Colours {
263        background: fade(colours.background, 0.5),
264        border: fade(colours.border, 0.5),
265        dot: fade(colours.dot, 0.5),
266        label: fade(colours.label, 0.5),
267    }
268}
269
270/// The iced button style used for the radio circle.
271pub fn style(tokens: &Tokens, selected: bool, status: Status) -> widget::button::Style {
272    let colours = colours(tokens, selected, status);
273    widget::button::Style {
274        background: Some(Background::Color(colours.background)),
275        text_color: colours.label,
276        border: Border {
277            color: colours.border,
278            width: 1.0,
279            radius: radius::FULL.into(),
280        },
281        shadow: Shadow::default(),
282        snap: true,
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use crate::theme::{dark, light};
290
291    const STATES: [Status; 4] = [
292        Status::Active,
293        Status::Hovered,
294        Status::Pressed,
295        Status::Disabled,
296    ];
297
298    #[test]
299    fn radio_is_selected_only_for_its_own_value() {
300        let r: Radio<'_, u8, ()> = radio("One", 1, Some(1));
301        assert!(r.is_selected());
302        let r: Radio<'_, u8, ()> = radio("One", 1, Some(2));
303        assert!(!r.is_selected());
304        let r: Radio<'_, u8, ()> = radio("One", 1, None);
305        assert!(!r.is_selected());
306    }
307
308    #[test]
309    fn radio_without_message_is_disabled() {
310        let r: Radio<'_, u8, u8> = radio("One", 1, None);
311        assert!(!r.is_enabled());
312        assert_eq!(r.on_select(|v| v * 10).on_select, Some(10));
313    }
314
315    #[test]
316    fn group_defaults_to_vertical_and_disabled() {
317        let g: RadioGroup<'_, u8, ()> = radio_group([1, 2, 3], None);
318        assert_eq!(g.direction, Direction::Vertical);
319        assert_eq!(g.options, vec![1, 2, 3]);
320        assert!(!g.is_enabled());
321        assert!(g.on_select(|_| ()).is_enabled());
322    }
323
324    #[test]
325    fn selected_border_uses_primary_in_every_enabled_status() {
326        for theme in [light(), dark()] {
327            let tokens = Tokens::of(&theme);
328            for status in [Status::Active, Status::Hovered, Status::Pressed] {
329                assert_eq!(colours(&tokens, true, status).border, tokens.primary);
330            }
331        }
332    }
333
334    #[test]
335    fn hover_strengthens_the_unselected_border() {
336        for theme in [light(), dark()] {
337            let tokens = Tokens::of(&theme);
338            let active = colours(&tokens, false, Status::Active);
339            let hovered = colours(&tokens, false, Status::Hovered);
340            assert_ne!(active.border, hovered.border);
341        }
342    }
343
344    #[test]
345    fn pressing_fills_the_background() {
346        let tokens = Tokens::of(&light());
347        for selected in [false, true] {
348            assert_eq!(
349                colours(&tokens, selected, Status::Pressed).background,
350                tokens.accent
351            );
352        }
353    }
354
355    #[test]
356    fn disabled_halves_alpha() {
357        for theme in [light(), dark()] {
358            let tokens = Tokens::of(&theme);
359            for selected in [false, true] {
360                let active = colours(&tokens, selected, Status::Active);
361                let disabled = colours(&tokens, selected, Status::Disabled);
362                assert!((disabled.dot.a - active.dot.a * 0.5).abs() < 1e-6);
363                assert!((disabled.label.a - active.label.a * 0.5).abs() < 1e-6);
364            }
365        }
366    }
367
368    #[test]
369    fn every_style_is_a_circle() {
370        for theme in [light(), dark()] {
371            let tokens = Tokens::of(&theme);
372            for selected in [false, true] {
373                for status in STATES {
374                    let style = style(&tokens, selected, status);
375                    assert_eq!(style.border.radius, radius::FULL.into());
376                    assert_eq!(style.border.width, 1.0);
377                }
378            }
379        }
380    }
381}