Skip to main content

iced_cube/primitives/
toggle.rs

1//! Two-state buttons that stay pressed while an option is on.
2//!
3//! A toggle is a button with a pressed state, for options such as "Bold" or
4//! "Show grid" that sit among other buttons rather than in a form. The app
5//! owns the bool and flips it in `on_toggle`, as with a switch. For a set of
6//! toggles where one or several can be on, use
7//! [`toggle_group`](mod@crate::primitives::toggle_group).
8//!
9//! An enabled toggle takes keyboard focus from iced's focus operations,
10//! rings while focused and flips with Space or Enter.
11
12use iced::keyboard::key::Named;
13use iced::widget::{self, button::Status, row, text};
14use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Shadow};
15
16use crate::after_touch::after_touch;
17use crate::focus::{Ring, focusable};
18use crate::icon::{Glyph, opacity, themed};
19use crate::keys::{self, Chord, Keymap};
20use crate::natural::natural;
21use crate::theme::{Tokens, fade, mix, radius, text_size};
22
23/// How a toggle looks while it is off.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
25pub enum Variant {
26    /// Transparent until hovered or pressed.
27    #[default]
28    Default,
29    /// A bordered button, so the toggle reads as a control at rest.
30    Outline,
31}
32
33impl Variant {
34    pub const ALL: [Variant; 2] = [Variant::Default, Variant::Outline];
35}
36
37/// Toggle dimensions.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
39pub enum Size {
40    Sm,
41    #[default]
42    Md,
43    Lg,
44}
45
46impl Size {
47    pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
48
49    /// Height, horizontal padding, text size and icon size.
50    pub const fn metrics(self) -> Metrics {
51        match self {
52            Size::Sm => Metrics {
53                height: 32.0,
54                padding_x: 10.0,
55                text: text_size::SM,
56                icon: 14.0,
57            },
58            Size::Md => Metrics {
59                height: 36.0,
60                padding_x: 12.0,
61                text: text_size::SM,
62                icon: 16.0,
63            },
64            Size::Lg => Metrics {
65                height: 40.0,
66                padding_x: 16.0,
67                text: text_size::MD,
68                icon: 18.0,
69            },
70        }
71    }
72}
73
74/// Resolved dimensions for a [`Size`].
75#[derive(Debug, Clone, Copy, PartialEq)]
76pub struct Metrics {
77    pub height: f32,
78    pub padding_x: f32,
79    pub text: f32,
80    pub icon: f32,
81}
82
83/// A toggle builder. Convert it into an [`Element`] to render.
84///
85/// A toggle without [`on_toggle`](Toggle::on_toggle) is rendered disabled.
86pub struct Toggle<'a, Message> {
87    label: text::Fragment<'a>,
88    icon: Option<Glyph>,
89    pressed: bool,
90    variant: Variant,
91    size: Size,
92    on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>,
93}
94
95/// Creates a toggle with a text label, switched off.
96pub fn toggle<'a, Message>(label: impl text::IntoFragment<'a>) -> Toggle<'a, Message> {
97    Toggle {
98        label: label.into_fragment(),
99        icon: None,
100        pressed: false,
101        variant: Variant::default(),
102        size: Size::default(),
103        on_toggle: None,
104    }
105}
106
107impl<Message> std::fmt::Debug for Toggle<'_, Message> {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("Toggle")
110            .field("label", &self.label)
111            .field("icon", &self.icon)
112            .field("pressed", &self.pressed)
113            .field("variant", &self.variant)
114            .field("size", &self.size)
115            .field("enabled", &self.on_toggle.is_some())
116            .finish()
117    }
118}
119
120impl<'a, Message> Toggle<'a, Message> {
121    /// Adds an icon before the label.
122    pub fn icon(mut self, glyph: Glyph) -> Self {
123        self.icon = Some(glyph);
124        self
125    }
126
127    /// Whether the toggle is on.
128    pub fn pressed(mut self, pressed: bool) -> Self {
129        self.pressed = pressed;
130        self
131    }
132
133    pub fn variant(mut self, variant: Variant) -> Self {
134        self.variant = variant;
135        self
136    }
137
138    pub fn size(mut self, size: Size) -> Self {
139        self.size = size;
140        self
141    }
142
143    /// Sets the message for a click, built from the new pressed state.
144    pub fn on_toggle(mut self, on_toggle: impl Fn(bool) -> Message + 'a) -> Self {
145        self.on_toggle = Some(Box::new(on_toggle));
146        self
147    }
148
149    /// Sets the message for a click, or disables the toggle with `None`.
150    pub fn on_toggle_maybe(mut self, on_toggle: Option<impl Fn(bool) -> Message + 'a>) -> Self {
151        self.on_toggle = on_toggle.map(|f| Box::new(f) as Box<dyn Fn(bool) -> Message + 'a>);
152        self
153    }
154
155    pub fn is_pressed(&self) -> bool {
156        self.pressed
157    }
158
159    pub fn is_enabled(&self) -> bool {
160        self.on_toggle.is_some()
161    }
162}
163
164impl<'a, Message: Clone + 'a> From<Toggle<'a, Message>> for Element<'a, Message> {
165    fn from(toggle: Toggle<'a, Message>) -> Self {
166        let Toggle {
167            label,
168            icon,
169            pressed,
170            variant,
171            size,
172            on_toggle,
173        } = toggle;
174        let message = on_toggle.map(|on_toggle| on_toggle(!pressed));
175        let on_activate = message
176            .clone()
177            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
178        let control = natural(button(
179            label,
180            icon,
181            pressed,
182            size.metrics(),
183            Length::Shrink,
184            message,
185            move |tokens, status| style(tokens, variant, pressed, status),
186        ));
187        focusable(control, on_activate, Ring::around(radius::MD)).into()
188    }
189}
190
191/// Renders the toggle button itself, so a group can draw its items with
192/// their own borders and corners. A width other than shrink centres the
193/// content.
194pub(crate) fn button<'a, Message: Clone + 'a>(
195    label: impl text::IntoFragment<'a>,
196    icon: Option<Glyph>,
197    pressed: bool,
198    metrics: Metrics,
199    width: Length,
200    message: Option<Message>,
201    style: impl Fn(&Tokens, Status) -> widget::button::Style + 'a,
202) -> Element<'a, Message> {
203    let enabled = message.is_some();
204    let resting = if enabled {
205        Status::Active
206    } else {
207        Status::Disabled
208    };
209
210    let mut content = row![].spacing(6).align_y(Alignment::Center);
211    if let Some(glyph) = icon {
212        content = content.push(themed(
213            glyph,
214            metrics.icon,
215            opacity(enabled),
216            move |theme| colours(&Tokens::of(theme), pressed, resting).foreground,
217        ));
218    }
219    content = content.push(
220        text(label)
221            .size(metrics.text)
222            .wrapping(text::Wrapping::None),
223    );
224
225    let inner = widget::container(content)
226        .height(Length::Fill)
227        .align_y(Alignment::Center);
228    let inner = if width == Length::Shrink {
229        inner
230    } else {
231        inner.width(Length::Fill).align_x(Alignment::Center)
232    };
233    after_touch(
234        widget::button(inner)
235            .width(width)
236            .height(Length::Fixed(metrics.height))
237            .padding(Padding::from([0.0, metrics.padding_x]))
238            .on_press_maybe(message)
239            .style(move |theme, status| style(&Tokens::of(theme), status)),
240    )
241}
242
243/// Background and foreground colours of a toggle, on or off, in a state.
244#[derive(Debug, Clone, Copy, PartialEq)]
245pub struct Colours {
246    pub background: Option<Color>,
247    pub foreground: Color,
248}
249
250/// Resolves the colours of a toggle. Off, it is muted and takes a fill
251/// halfway to the accent on hover, keeping its muted text; on, it takes
252/// the accent with full-strength text and darkens a little on hover, so
253/// a hovered toggle never looks pressed.
254pub fn colours(tokens: &Tokens, pressed: bool, status: Status) -> Colours {
255    let hover = matches!(status, Status::Hovered | Status::Pressed);
256    let colours = match (pressed, hover) {
257        (true, false) => Colours {
258            background: Some(tokens.accent),
259            foreground: tokens.accent_foreground,
260        },
261        (true, true) => Colours {
262            background: Some(mix(tokens.accent, tokens.foreground, 0.08)),
263            foreground: tokens.accent_foreground,
264        },
265        (false, true) => Colours {
266            background: Some(mix(tokens.background, tokens.accent, 0.5)),
267            foreground: tokens.muted_foreground,
268        },
269        (false, false) => Colours {
270            background: None,
271            foreground: tokens.muted_foreground,
272        },
273    };
274
275    if status != Status::Disabled {
276        return colours;
277    }
278    Colours {
279        background: colours.background.map(|c| fade(c, 0.5)),
280        foreground: fade(colours.foreground, 0.5),
281    }
282}
283
284/// The iced button style of a toggle.
285pub fn style(
286    tokens: &Tokens,
287    variant: Variant,
288    pressed: bool,
289    status: Status,
290) -> widget::button::Style {
291    let colours = colours(tokens, pressed, status);
292    let outline = variant == Variant::Outline;
293    let border = if status == Status::Disabled {
294        fade(tokens.border, 0.5)
295    } else {
296        tokens.border
297    };
298    widget::button::Style {
299        background: colours.background.map(Background::Color),
300        text_color: colours.foreground,
301        border: Border {
302            color: if outline { border } else { Color::TRANSPARENT },
303            width: if outline { 1.0 } else { 0.0 },
304            radius: radius::MD.into(),
305        },
306        shadow: Shadow::default(),
307        snap: true,
308    }
309}
310
311/// What a toggle keyboard shortcut does.
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
313pub enum Action {
314    Toggle,
315}
316
317impl Action {
318    /// The pressed state to send through the toggle's `on_toggle` message.
319    pub fn apply(self, pressed: bool) -> bool {
320        match self {
321            Action::Toggle => !pressed,
322        }
323    }
324}
325
326impl keys::Action for Action {
327    const ALL: &'static [Self] = &[Action::Toggle];
328
329    fn defaults() -> Keymap<Self> {
330        default_keymap()
331    }
332
333    fn name(self) -> &'static str {
334        match self {
335            Action::Toggle => "Toggle",
336        }
337    }
338
339    fn description(self) -> &'static str {
340        match self {
341            Action::Toggle => "Switches the toggle on or off.",
342        }
343    }
344}
345
346/// The default toggle shortcuts:
347///
348/// | Keys | Action |
349/// | --- | --- |
350/// | `Space` | [`Action::Toggle`] |
351///
352/// Shortcuts are app-wide, so an app with several toggles binds each one
353/// its own chord, such as `Ctrl+B` for a bold toggle.
354pub fn default_keymap() -> Keymap<Action> {
355    Keymap::new().bind(Chord::named(Named::Space), Action::Toggle)
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361    use crate::theme::{dark, light};
362
363    const STATES: [Status; 4] = [
364        Status::Active,
365        Status::Hovered,
366        Status::Pressed,
367        Status::Disabled,
368    ];
369
370    #[test]
371    fn defaults_to_an_off_medium_toggle_that_is_disabled() {
372        let t: Toggle<'_, bool> = toggle("Bold");
373        assert_eq!(t.variant, Variant::Default);
374        assert_eq!(t.size, Size::Md);
375        assert!(t.icon.is_none());
376        assert!(!t.is_pressed());
377        assert!(!t.is_enabled());
378    }
379
380    #[test]
381    fn builder_sets_every_option() {
382        let t = toggle("Grid")
383            .icon(crate::lucide!(Grid3x3))
384            .pressed(true)
385            .variant(Variant::Outline)
386            .size(Size::Lg)
387            .on_toggle(|on| on);
388        assert_eq!(t.icon.map(Glyph::name), Some("grid-3x3"));
389        assert!(t.is_pressed());
390        assert!(t.is_enabled());
391        assert_eq!(t.variant, Variant::Outline);
392        assert!(
393            !toggle("Grid")
394                .on_toggle_maybe(None::<fn(bool) -> bool>)
395                .is_enabled()
396        );
397        assert!(
398            toggle("Grid")
399                .on_toggle_maybe(Some(|on: bool| on))
400                .is_enabled()
401        );
402        assert_eq!(t.size, Size::Lg);
403    }
404
405    #[test]
406    fn sizes_grow_monotonically() {
407        let heights = Size::ALL.map(|size| size.metrics().height);
408        assert!(heights.windows(2).all(|w| w[0] < w[1]));
409        let icons = Size::ALL.map(|size| size.metrics().icon);
410        assert!(icons.windows(2).all(|w| w[0] < w[1]));
411    }
412
413    #[test]
414    fn on_takes_the_accent_and_off_is_transparent_at_rest() {
415        for theme in [light(), dark()] {
416            let tokens = Tokens::of(&theme);
417            let on = colours(&tokens, true, Status::Active);
418            let off = colours(&tokens, false, Status::Active);
419            assert_eq!(on.background, Some(tokens.accent));
420            assert_eq!(on.foreground, tokens.accent_foreground);
421            assert_eq!(off.background, None);
422            assert_eq!(off.foreground, tokens.muted_foreground);
423        }
424    }
425
426    #[test]
427    fn hover_changes_the_background_on_and_off() {
428        for theme in [light(), dark()] {
429            let tokens = Tokens::of(&theme);
430            for pressed in [false, true] {
431                let rest = colours(&tokens, pressed, Status::Active);
432                for status in [Status::Hovered, Status::Pressed] {
433                    let hovered = colours(&tokens, pressed, status);
434                    assert_ne!(hovered.background, rest.background, "{pressed} {status:?}");
435                    assert!(hovered.background.is_some());
436                }
437            }
438        }
439    }
440
441    fn distance(a: Color, b: Color) -> f32 {
442        (a.r - b.r).abs() + (a.g - b.g).abs() + (a.b - b.b).abs()
443    }
444
445    #[test]
446    fn hovering_an_off_toggle_is_lighter_than_pressing_it() {
447        for theme in [light(), dark()] {
448            let tokens = Tokens::of(&theme);
449            let pressed = colours(&tokens, true, Status::Active);
450            let hovered = colours(&tokens, false, Status::Hovered);
451            let (Some(pressed_fill), Some(hovered_fill)) = (pressed.background, hovered.background)
452            else {
453                panic!("both fill");
454            };
455            let pressed_lift = distance(pressed_fill, tokens.background);
456            let hovered_lift = distance(hovered_fill, tokens.background);
457            assert!(hovered_lift > 0.0, "{}", tokens.is_dark);
458            assert!(hovered_lift < pressed_lift * 0.6, "{}", tokens.is_dark);
459            assert_ne!(hovered.foreground, pressed.foreground);
460            assert_eq!(hovered.foreground, tokens.muted_foreground);
461        }
462    }
463
464    #[test]
465    fn on_and_off_differ_in_every_enabled_state() {
466        let tokens = Tokens::of(&light());
467        for status in [Status::Active, Status::Hovered, Status::Pressed] {
468            assert_ne!(
469                colours(&tokens, true, status),
470                colours(&tokens, false, status),
471                "{status:?}"
472            );
473        }
474    }
475
476    #[test]
477    fn disabled_keeps_the_look_at_half_alpha() {
478        for theme in [light(), dark()] {
479            let tokens = Tokens::of(&theme);
480            for pressed in [false, true] {
481                let rest = colours(&tokens, pressed, Status::Active);
482                let disabled = colours(&tokens, pressed, Status::Disabled);
483                assert!((disabled.foreground.a - rest.foreground.a * 0.5).abs() < 1e-6);
484                assert_eq!(
485                    disabled.background.map(|c| c.a),
486                    rest.background.map(|c| c.a * 0.5)
487                );
488            }
489        }
490    }
491
492    #[test]
493    fn only_outline_has_a_border_in_every_state() {
494        let tokens = Tokens::of(&dark());
495        for variant in Variant::ALL {
496            for pressed in [false, true] {
497                for status in STATES {
498                    let style = style(&tokens, variant, pressed, status);
499                    assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
500                    assert_eq!(style.border.radius, radius::MD.into());
501                }
502            }
503        }
504    }
505
506    #[test]
507    fn toggle_action_flips_the_state() {
508        assert!(Action::Toggle.apply(false));
509        assert!(!Action::Toggle.apply(true));
510    }
511
512    #[test]
513    fn default_keymap_and_overrides() {
514        let space = iced::keyboard::Key::Named(Named::Space);
515        let keymap = default_keymap();
516        assert_eq!(
517            keymap.resolve(&space, Default::default()),
518            Some(Action::Toggle)
519        );
520        assert_eq!(Keymap::<Action>::defaults(), keymap);
521
522        let bold: Chord = "Ctrl+B".parse().unwrap();
523        let custom = keymap
524            .unbind(&Chord::named(Named::Space))
525            .bind(bold.clone(), Action::Toggle);
526        assert_eq!(custom.resolve(&space, Default::default()), None);
527        assert_eq!(
528            custom.resolve(bold.key(), bold.modifiers()),
529            Some(Action::Toggle)
530        );
531        assert!(custom.unbind_action(&Action::Toggle).is_empty());
532    }
533}