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        let mut toggler = widget::toggler(is_on)
79            .size(TRACK_HEIGHT)
80            .text_size(text_size::SM)
81            .spacing(spacing::SM)
82            .style(|theme, status| style(&Tokens::of(theme), status));
83        if let Some(label) = switch.label {
84            toggler = toggler.label(label);
85        }
86        let on_toggle: Option<Rc<dyn Fn(bool) -> Message + 'a>> = switch.on_toggle.map(Rc::from);
87        let on_activate = on_toggle.clone().map(|on_toggle| {
88            Box::new(move || on_toggle(Action::Toggle.apply(is_on)))
89                as Box<dyn Fn() -> Message + 'a>
90        });
91        if let Some(on_toggle) = on_toggle {
92            toggler = toggler.on_toggle(move |value| on_toggle(value));
93        }
94        focusable(
95            toggler,
96            on_activate,
97            Ring {
98                first_child: true,
99                ..Ring::around(radius::FULL)
100            },
101        )
102        .into()
103    }
104}
105
106/// Track, thumb and label colours of a switch.
107#[derive(Debug, Clone, Copy, PartialEq)]
108pub struct Colours {
109    pub track: Color,
110    pub thumb: Color,
111    pub label: Color,
112}
113
114/// Resolves the colours of a switch for an interaction status.
115pub fn colours(tokens: &Tokens, status: Status) -> Colours {
116    let (is_on, hover, disabled) = match status {
117        Status::Active { is_toggled } => (is_toggled, false, false),
118        Status::Hovered { is_toggled } => (is_toggled, true, false),
119        Status::Disabled { is_toggled } => (is_toggled, false, true),
120    };
121
122    let off_track = mix(tokens.border, tokens.foreground, 0.1);
123    let track = match (is_on, hover) {
124        (true, false) => tokens.primary,
125        (true, true) => mix(tokens.primary, tokens.background, 0.15),
126        (false, false) => off_track,
127        (false, true) => mix(off_track, tokens.foreground, 0.15),
128    };
129    // A dark thumb disappears into a dark off track, so dark themes draw
130    // the off thumb in the foreground colour.
131    let thumb = if tokens.is_dark && !is_on {
132        tokens.foreground
133    } else {
134        tokens.background
135    };
136    let colours = Colours {
137        track,
138        thumb,
139        label: tokens.foreground,
140    };
141
142    if !disabled {
143        return colours;
144    }
145    Colours {
146        track: fade(colours.track, 0.5),
147        thumb: mix(colours.thumb, tokens.background, 0.5),
148        label: fade(colours.label, 0.5),
149    }
150}
151
152/// The iced toggler style for a status.
153pub fn style(tokens: &Tokens, status: Status) -> widget::toggler::Style {
154    let colours = colours(tokens, status);
155    widget::toggler::Style {
156        background: Background::Color(colours.track),
157        background_border_width: 0.0,
158        background_border_color: Color::TRANSPARENT,
159        foreground: Background::Color(colours.thumb),
160        foreground_border_width: 0.0,
161        foreground_border_color: Color::TRANSPARENT,
162        text_color: Some(colours.label),
163        border_radius: None,
164        padding_ratio: 0.1,
165    }
166}
167
168/// What a switch keyboard shortcut does. Useful when the app tracks
169/// which switch is current.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
171pub enum Action {
172    Toggle,
173}
174
175impl Action {
176    /// The value to send through the switch's `on_toggle` message.
177    pub fn apply(self, is_on: bool) -> bool {
178        match self {
179            Action::Toggle => !is_on,
180        }
181    }
182}
183
184impl keys::Action for Action {
185    const ALL: &'static [Self] = &[Action::Toggle];
186
187    fn defaults() -> Keymap<Self> {
188        default_keymap()
189    }
190
191    fn name(self) -> &'static str {
192        "Toggle"
193    }
194
195    fn description(self) -> &'static str {
196        "Turns the current switch on or off."
197    }
198}
199
200/// The default switch shortcuts:
201///
202/// | Keys | Action |
203/// | --- | --- |
204/// | `Space` | [`Action::Toggle`] |
205pub fn default_keymap() -> Keymap<Action> {
206    Keymap::new().bind(Chord::named(Named::Space), Action::Toggle)
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use crate::theme::{dark, light};
213
214    #[test]
215    fn toggle_flips_the_value() {
216        assert!(Action::Toggle.apply(false));
217        assert!(!Action::Toggle.apply(true));
218    }
219
220    #[test]
221    fn default_keymap_and_overrides() {
222        let space = iced::keyboard::Key::Named(Named::Space);
223        let keymap = default_keymap();
224        assert_eq!(
225            keymap.resolve(&space, Default::default()),
226            Some(Action::Toggle)
227        );
228        let custom = keymap
229            .unbind(&Chord::named(Named::Space))
230            .bind("T".parse().unwrap(), Action::Toggle);
231        assert_eq!(custom.resolve(&space, Default::default()), None);
232        assert_eq!(
233            custom.resolve(
234                &iced::keyboard::Key::Character("t".into()),
235                Default::default()
236            ),
237            Some(Action::Toggle)
238        );
239    }
240
241    fn statuses(is_toggled: bool) -> [Status; 3] {
242        [
243            Status::Active { is_toggled },
244            Status::Hovered { is_toggled },
245            Status::Disabled { is_toggled },
246        ]
247    }
248
249    #[test]
250    fn default_builder_is_unlabelled_and_disabled() {
251        let s: Switch<'_, ()> = switch(true);
252        assert!(s.is_on());
253        assert!(s.label.is_none());
254        assert!(!s.is_enabled());
255    }
256
257    #[test]
258    fn on_toggle_enables_and_maybe_none_disables() {
259        assert!(switch::<bool>(false).on_toggle(|v| v).is_enabled());
260        let s = switch::<bool>(false).on_toggle_maybe(None::<fn(bool) -> bool>);
261        assert!(!s.is_enabled());
262    }
263
264    #[test]
265    fn on_track_is_primary_and_off_track_is_not() {
266        for theme in [light(), dark()] {
267            let tokens = Tokens::of(&theme);
268            let on = colours(&tokens, Status::Active { is_toggled: true });
269            let off = colours(&tokens, Status::Active { is_toggled: false });
270            assert_eq!(on.track, tokens.primary);
271            assert_ne!(off.track, tokens.primary);
272            assert_eq!(on.thumb, tokens.background);
273        }
274    }
275
276    #[test]
277    fn hover_changes_the_track() {
278        for theme in [light(), dark()] {
279            let tokens = Tokens::of(&theme);
280            for is_toggled in [false, true] {
281                let active = colours(&tokens, Status::Active { is_toggled });
282                let hovered = colours(&tokens, Status::Hovered { is_toggled });
283                assert_ne!(active.track, hovered.track);
284            }
285        }
286    }
287
288    #[test]
289    fn disabled_fades_track_and_label() {
290        for theme in [light(), dark()] {
291            let tokens = Tokens::of(&theme);
292            for is_toggled in [false, true] {
293                let active = colours(&tokens, Status::Active { is_toggled });
294                let disabled = colours(&tokens, Status::Disabled { is_toggled });
295                assert!((disabled.track.a - active.track.a * 0.5).abs() < 1e-6);
296                assert!((disabled.label.a - active.label.a * 0.5).abs() < 1e-6);
297            }
298        }
299    }
300
301    fn luminance(colour: Color) -> f32 {
302        let channel = |c: f32| {
303            if c <= 0.04045 {
304                c / 12.92
305            } else {
306                ((c + 0.055) / 1.055).powf(2.4)
307            }
308        };
309        0.2126 * channel(colour.r) + 0.7152 * channel(colour.g) + 0.0722 * channel(colour.b)
310    }
311
312    /// The contrast ratio of two opaque colours, from 1 to 21.
313    fn contrast(a: Color, b: Color) -> f32 {
314        let (a, b) = (luminance(a), luminance(b));
315        (a.max(b) + 0.05) / (a.min(b) + 0.05)
316    }
317
318    #[test]
319    fn the_off_thumb_stands_out_from_the_off_track_in_dark_themes() {
320        let tokens = Tokens::of(&dark());
321        for status in [
322            Status::Active { is_toggled: false },
323            Status::Hovered { is_toggled: false },
324        ] {
325            let off = colours(&tokens, status);
326            assert_eq!(off.thumb, tokens.foreground);
327            let ratio = contrast(off.thumb, off.track);
328            assert!(ratio >= 4.5, "{status:?}: {ratio}");
329        }
330        let on = colours(&tokens, Status::Active { is_toggled: true });
331        assert!(contrast(on.thumb, on.track) >= 4.5);
332    }
333
334    #[test]
335    fn the_light_theme_keeps_a_background_thumb_in_both_states() {
336        let tokens = Tokens::of(&light());
337        for is_toggled in [false, true] {
338            for status in statuses(is_toggled) {
339                assert_eq!(colours(&tokens, status).thumb, tokens.background);
340            }
341            let active = colours(&tokens, Status::Active { is_toggled });
342            assert!(contrast(active.thumb, active.track) > 1.2, "{is_toggled}");
343        }
344    }
345
346    #[test]
347    fn a_disabled_dark_off_thumb_is_dimmed_towards_the_background() {
348        let tokens = Tokens::of(&dark());
349        let active = colours(&tokens, Status::Active { is_toggled: false });
350        let disabled = colours(&tokens, Status::Disabled { is_toggled: false });
351        assert_eq!(disabled.thumb, mix(active.thumb, tokens.background, 0.5));
352        assert!(luminance(disabled.thumb) < luminance(active.thumb));
353        assert!(luminance(disabled.thumb) > luminance(tokens.background));
354    }
355
356    #[test]
357    fn every_status_has_a_round_track_and_label_colour() {
358        let tokens = Tokens::of(&dark());
359        for status in statuses(true).into_iter().chain(statuses(false)) {
360            let style = style(&tokens, status);
361            assert!(style.border_radius.is_none());
362            assert!(style.text_color.is_some());
363        }
364    }
365}