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