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