Skip to main content

iced_cube/primitives/
switch.rs

1//! On/off switches for settings that apply immediately.
2//!
3//! An enabled switch takes keyboard focus from iced's focus operations,
4//! such as a dialog's Tab order. While focused its track rings and Space
5//! or Enter turns it on or off.
6
7use std::rc::Rc;
8
9use iced::keyboard::key::Named;
10use iced::widget::{self, toggler::Status};
11use iced::{Background, Color, Element};
12
13use crate::focus::{Ring, focusable};
14use crate::keys::{self, Chord, Keymap};
15use crate::theme::{Tokens, fade, mix, radius, space as spacing, text_size};
16
17/// Height of the switch track in logical pixels. The track is twice as wide.
18pub const TRACK_HEIGHT: f32 = 20.0;
19
20/// A switch builder. Convert it into an [`Element`] to render.
21///
22/// A switch without a message is rendered disabled.
23pub struct Switch<'a, Message> {
24    is_on: bool,
25    label: Option<widget::text::Fragment<'a>>,
26    on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>,
27}
28
29impl<Message> std::fmt::Debug for Switch<'_, Message> {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("Switch")
32            .field("is_on", &self.is_on)
33            .field("label", &self.label)
34            .field("enabled", &self.on_toggle.is_some())
35            .finish()
36    }
37}
38
39/// Creates a switch that is on when `is_on` is true.
40pub fn switch<'a, Message>(is_on: bool) -> Switch<'a, Message> {
41    Switch {
42        is_on,
43        label: None,
44        on_toggle: None,
45    }
46}
47
48impl<'a, Message> Switch<'a, Message> {
49    pub fn label(mut self, label: impl widget::text::IntoFragment<'a>) -> Self {
50        self.label = Some(label.into_fragment());
51        self
52    }
53
54    /// Sets the message for a click. It receives the new value.
55    pub fn on_toggle(mut self, on_toggle: impl Fn(bool) -> Message + 'a) -> Self {
56        self.on_toggle = Some(Box::new(on_toggle));
57        self
58    }
59
60    /// Like [`Switch::on_toggle`], but `None` disables the switch.
61    pub fn on_toggle_maybe(mut self, on_toggle: Option<impl Fn(bool) -> Message + 'a>) -> Self {
62        self.on_toggle = on_toggle.map(|f| Box::new(f) as Box<dyn Fn(bool) -> Message + 'a>);
63        self
64    }
65
66    pub fn is_on(&self) -> bool {
67        self.is_on
68    }
69
70    pub fn is_enabled(&self) -> bool {
71        self.on_toggle.is_some()
72    }
73}
74
75impl<'a, Message: 'a> From<Switch<'a, Message>> for Element<'a, Message> {
76    fn from(switch: Switch<'a, Message>) -> Self {
77        let is_on = switch.is_on;
78        #[cfg(feature = "icedwright")]
79        let (name, enabled) = (switch.label.clone(), switch.on_toggle.is_some());
80        let mut toggler = widget::toggler(is_on)
81            .size(TRACK_HEIGHT)
82            .text_size(text_size::SM)
83            .spacing(spacing::SM)
84            .style(|theme, status| style(&Tokens::of(theme), status));
85        if let Some(label) = switch.label {
86            toggler = toggler.label(label);
87        }
88        let on_toggle: Option<Rc<dyn Fn(bool) -> Message + 'a>> = switch.on_toggle.map(Rc::from);
89        let on_activate = on_toggle.clone().map(|on_toggle| {
90            Box::new(move || on_toggle(Action::Toggle.apply(is_on)))
91                as Box<dyn Fn() -> Message + 'a>
92        });
93        if let Some(on_toggle) = on_toggle {
94            toggler = toggler.on_toggle(move |value| on_toggle(value));
95        }
96        let element: Element<'a, Message> = focusable(
97            toggler,
98            on_activate,
99            Ring {
100                first_child: true,
101                ..Ring::around(radius::FULL)
102            },
103        )
104        .into();
105        #[cfg(feature = "icedwright")]
106        let element = {
107            use icedwright_probe::{role, semantic};
108            let mut annotated = semantic(element)
109                .role(role::Switch)
110                .checked(is_on)
111                .component("iced_cube::switch");
112            if !enabled {
113                annotated = annotated.disabled(true);
114            }
115            if let Some(name) = name {
116                annotated = annotated.name(name);
117            }
118            annotated.into()
119        };
120        element
121    }
122}
123
124/// Track, thumb and label colours of a switch.
125#[derive(Debug, Clone, Copy, PartialEq)]
126pub struct Colours {
127    pub track: Color,
128    pub thumb: Color,
129    pub label: Color,
130}
131
132/// Resolves the colours of a switch for an interaction status.
133pub fn colours(tokens: &Tokens, status: Status) -> Colours {
134    let (is_on, hover, disabled) = match status {
135        Status::Active { is_toggled } => (is_toggled, false, false),
136        Status::Hovered { is_toggled } => (is_toggled, true, false),
137        Status::Disabled { is_toggled } => (is_toggled, false, true),
138    };
139
140    let off_track = mix(tokens.border, tokens.foreground, 0.1);
141    let track = match (is_on, hover) {
142        (true, false) => tokens.primary,
143        (true, true) => mix(tokens.primary, tokens.background, 0.15),
144        (false, false) => off_track,
145        (false, true) => mix(off_track, tokens.foreground, 0.15),
146    };
147    // A dark thumb disappears into a dark off track, so dark themes draw
148    // the off thumb in the foreground colour.
149    let thumb = if tokens.is_dark && !is_on {
150        tokens.foreground
151    } else {
152        tokens.background
153    };
154    let colours = Colours {
155        track,
156        thumb,
157        label: tokens.foreground,
158    };
159
160    if !disabled {
161        return colours;
162    }
163    Colours {
164        track: fade(colours.track, 0.5),
165        thumb: mix(colours.thumb, tokens.background, 0.5),
166        label: fade(colours.label, 0.5),
167    }
168}
169
170/// The iced toggler style for a status.
171pub fn style(tokens: &Tokens, status: Status) -> widget::toggler::Style {
172    let colours = colours(tokens, status);
173    widget::toggler::Style {
174        background: Background::Color(colours.track),
175        background_border_width: 0.0,
176        background_border_color: Color::TRANSPARENT,
177        foreground: Background::Color(colours.thumb),
178        foreground_border_width: 0.0,
179        foreground_border_color: Color::TRANSPARENT,
180        text_color: Some(colours.label),
181        border_radius: None,
182        padding_ratio: 0.1,
183    }
184}
185
186/// What a switch keyboard shortcut does. Useful when the app tracks
187/// which switch is current.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub enum Action {
190    Toggle,
191}
192
193impl Action {
194    /// The value to send through the switch's `on_toggle` message.
195    pub fn apply(self, is_on: bool) -> bool {
196        match self {
197            Action::Toggle => !is_on,
198        }
199    }
200}
201
202impl keys::Action for Action {
203    const ALL: &'static [Self] = &[Action::Toggle];
204
205    fn defaults() -> Keymap<Self> {
206        default_keymap()
207    }
208
209    fn name(self) -> &'static str {
210        "Toggle"
211    }
212
213    fn description(self) -> &'static str {
214        "Turns the current switch on or off."
215    }
216}
217
218/// The default switch shortcuts:
219///
220/// | Keys | Action |
221/// | --- | --- |
222/// | `Space` | [`Action::Toggle`] |
223pub fn default_keymap() -> Keymap<Action> {
224    Keymap::new().bind(Chord::named(Named::Space), Action::Toggle)
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use crate::theme::{dark, light};
231
232    #[test]
233    fn toggle_flips_the_value() {
234        assert!(Action::Toggle.apply(false));
235        assert!(!Action::Toggle.apply(true));
236    }
237
238    #[test]
239    fn default_keymap_and_overrides() {
240        let space = iced::keyboard::Key::Named(Named::Space);
241        let keymap = default_keymap();
242        assert_eq!(
243            keymap.resolve(&space, Default::default()),
244            Some(Action::Toggle)
245        );
246        let custom = keymap
247            .unbind(&Chord::named(Named::Space))
248            .bind("T".parse().unwrap(), Action::Toggle);
249        assert_eq!(custom.resolve(&space, Default::default()), None);
250        assert_eq!(
251            custom.resolve(
252                &iced::keyboard::Key::Character("t".into()),
253                Default::default()
254            ),
255            Some(Action::Toggle)
256        );
257    }
258
259    fn statuses(is_toggled: bool) -> [Status; 3] {
260        [
261            Status::Active { is_toggled },
262            Status::Hovered { is_toggled },
263            Status::Disabled { is_toggled },
264        ]
265    }
266
267    #[test]
268    fn default_builder_is_unlabelled_and_disabled() {
269        let s: Switch<'_, ()> = switch(true);
270        assert!(s.is_on());
271        assert!(s.label.is_none());
272        assert!(!s.is_enabled());
273    }
274
275    #[test]
276    fn on_toggle_enables_and_maybe_none_disables() {
277        assert!(switch::<bool>(false).on_toggle(|v| v).is_enabled());
278        let s = switch::<bool>(false).on_toggle_maybe(None::<fn(bool) -> bool>);
279        assert!(!s.is_enabled());
280    }
281
282    #[test]
283    fn on_track_is_primary_and_off_track_is_not() {
284        for theme in [light(), dark()] {
285            let tokens = Tokens::of(&theme);
286            let on = colours(&tokens, Status::Active { is_toggled: true });
287            let off = colours(&tokens, Status::Active { is_toggled: false });
288            assert_eq!(on.track, tokens.primary);
289            assert_ne!(off.track, tokens.primary);
290            assert_eq!(on.thumb, tokens.background);
291        }
292    }
293
294    #[test]
295    fn hover_changes_the_track() {
296        for theme in [light(), dark()] {
297            let tokens = Tokens::of(&theme);
298            for is_toggled in [false, true] {
299                let active = colours(&tokens, Status::Active { is_toggled });
300                let hovered = colours(&tokens, Status::Hovered { is_toggled });
301                assert_ne!(active.track, hovered.track);
302            }
303        }
304    }
305
306    #[test]
307    fn disabled_fades_track_and_label() {
308        for theme in [light(), dark()] {
309            let tokens = Tokens::of(&theme);
310            for is_toggled in [false, true] {
311                let active = colours(&tokens, Status::Active { is_toggled });
312                let disabled = colours(&tokens, Status::Disabled { is_toggled });
313                assert!((disabled.track.a - active.track.a * 0.5).abs() < 1e-6);
314                assert!((disabled.label.a - active.label.a * 0.5).abs() < 1e-6);
315            }
316        }
317    }
318
319    fn luminance(colour: Color) -> f32 {
320        let channel = |c: f32| {
321            if c <= 0.04045 {
322                c / 12.92
323            } else {
324                ((c + 0.055) / 1.055).powf(2.4)
325            }
326        };
327        0.2126 * channel(colour.r) + 0.7152 * channel(colour.g) + 0.0722 * channel(colour.b)
328    }
329
330    /// The contrast ratio of two opaque colours, from 1 to 21.
331    fn contrast(a: Color, b: Color) -> f32 {
332        let (a, b) = (luminance(a), luminance(b));
333        (a.max(b) + 0.05) / (a.min(b) + 0.05)
334    }
335
336    #[test]
337    fn the_off_thumb_stands_out_from_the_off_track_in_dark_themes() {
338        let tokens = Tokens::of(&dark());
339        for status in [
340            Status::Active { is_toggled: false },
341            Status::Hovered { is_toggled: false },
342        ] {
343            let off = colours(&tokens, status);
344            assert_eq!(off.thumb, tokens.foreground);
345            let ratio = contrast(off.thumb, off.track);
346            assert!(ratio >= 4.5, "{status:?}: {ratio}");
347        }
348        let on = colours(&tokens, Status::Active { is_toggled: true });
349        assert!(contrast(on.thumb, on.track) >= 4.5);
350    }
351
352    #[test]
353    fn the_light_theme_keeps_a_background_thumb_in_both_states() {
354        let tokens = Tokens::of(&light());
355        for is_toggled in [false, true] {
356            for status in statuses(is_toggled) {
357                assert_eq!(colours(&tokens, status).thumb, tokens.background);
358            }
359            let active = colours(&tokens, Status::Active { is_toggled });
360            assert!(contrast(active.thumb, active.track) > 1.2, "{is_toggled}");
361        }
362    }
363
364    #[test]
365    fn a_disabled_dark_off_thumb_is_dimmed_towards_the_background() {
366        let tokens = Tokens::of(&dark());
367        let active = colours(&tokens, Status::Active { is_toggled: false });
368        let disabled = colours(&tokens, Status::Disabled { is_toggled: false });
369        assert_eq!(disabled.thumb, mix(active.thumb, tokens.background, 0.5));
370        assert!(luminance(disabled.thumb) < luminance(active.thumb));
371        assert!(luminance(disabled.thumb) > luminance(tokens.background));
372    }
373
374    #[test]
375    fn every_status_has_a_round_track_and_label_colour() {
376        let tokens = Tokens::of(&dark());
377        for status in statuses(true).into_iter().chain(statuses(false)) {
378            let style = style(&tokens, status);
379            assert!(style.border_radius.is_none());
380            assert!(style.text_color.is_some());
381        }
382    }
383}