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        #[cfg(feature = "icedwright")]
176        let (name, enabled) = (label.clone(), message.is_some());
177        let on_activate = message
178            .clone()
179            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
180        let control = natural(button(
181            label,
182            icon,
183            pressed,
184            size.metrics(),
185            Length::Shrink,
186            message,
187            move |tokens, status| style(tokens, variant, pressed, status),
188        ));
189        let element: Element<'a, Message> =
190            focusable(control, on_activate, Ring::around(radius::MD)).into();
191        #[cfg(feature = "icedwright")]
192        let element = annotate(element, name, pressed, enabled, "iced_cube::toggle");
193        element
194    }
195}
196
197/// Reports a toggle button, named by its label, with its pressed state.
198#[cfg(feature = "icedwright")]
199pub(crate) fn annotate<'a, Message: 'a>(
200    element: Element<'a, Message>,
201    name: text::Fragment<'a>,
202    pressed: bool,
203    enabled: bool,
204    kind: &'static str,
205) -> Element<'a, Message> {
206    use icedwright_probe::{role, semantic};
207    let mut annotated = semantic(element)
208        .role(role::ToggleButton)
209        .name(name)
210        .pressed(pressed)
211        .component(kind);
212    if !enabled {
213        annotated = annotated.disabled(true);
214    }
215    annotated.into()
216}
217
218/// Renders the toggle button itself, so a group can draw its items with
219/// their own borders and corners. A width other than shrink centres the
220/// content.
221pub(crate) fn button<'a, Message: Clone + 'a>(
222    label: impl text::IntoFragment<'a>,
223    icon: Option<Glyph>,
224    pressed: bool,
225    metrics: Metrics,
226    width: Length,
227    message: Option<Message>,
228    style: impl Fn(&Tokens, Status) -> widget::button::Style + 'a,
229) -> Element<'a, Message> {
230    let enabled = message.is_some();
231    let resting = if enabled {
232        Status::Active
233    } else {
234        Status::Disabled
235    };
236
237    let mut content = row![].spacing(6).align_y(Alignment::Center);
238    if let Some(glyph) = icon {
239        content = content.push(themed(
240            glyph,
241            metrics.icon,
242            opacity(enabled),
243            move |theme| colours(&Tokens::of(theme), pressed, resting).foreground,
244        ));
245    }
246    content = content.push(
247        text(label)
248            .size(metrics.text)
249            .wrapping(text::Wrapping::None),
250    );
251
252    let inner = widget::container(content)
253        .height(Length::Fill)
254        .align_y(Alignment::Center);
255    let inner = if width == Length::Shrink {
256        inner
257    } else {
258        inner.width(Length::Fill).align_x(Alignment::Center)
259    };
260    after_touch(
261        widget::button(inner)
262            .width(width)
263            .height(Length::Fixed(metrics.height))
264            .padding(Padding::from([0.0, metrics.padding_x]))
265            .on_press_maybe(message)
266            .style(move |theme, status| style(&Tokens::of(theme), status)),
267    )
268}
269
270/// Background and foreground colours of a toggle, on or off, in a state.
271#[derive(Debug, Clone, Copy, PartialEq)]
272pub struct Colours {
273    pub background: Option<Color>,
274    pub foreground: Color,
275}
276
277/// Resolves the colours of a toggle. Off, it is muted and takes a fill
278/// halfway to the accent on hover, keeping its muted text; on, it takes
279/// the accent with full-strength text and darkens a little on hover, so
280/// a hovered toggle never looks pressed.
281pub fn colours(tokens: &Tokens, pressed: bool, status: Status) -> Colours {
282    let hover = matches!(status, Status::Hovered | Status::Pressed);
283    let colours = match (pressed, hover) {
284        (true, false) => Colours {
285            background: Some(tokens.accent),
286            foreground: tokens.accent_foreground,
287        },
288        (true, true) => Colours {
289            background: Some(mix(tokens.accent, tokens.foreground, 0.08)),
290            foreground: tokens.accent_foreground,
291        },
292        (false, true) => Colours {
293            background: Some(mix(tokens.background, tokens.accent, 0.5)),
294            foreground: tokens.muted_foreground,
295        },
296        (false, false) => Colours {
297            background: None,
298            foreground: tokens.muted_foreground,
299        },
300    };
301
302    if status != Status::Disabled {
303        return colours;
304    }
305    Colours {
306        background: colours.background.map(|c| fade(c, 0.5)),
307        foreground: fade(colours.foreground, 0.5),
308    }
309}
310
311/// The iced button style of a toggle.
312pub fn style(
313    tokens: &Tokens,
314    variant: Variant,
315    pressed: bool,
316    status: Status,
317) -> widget::button::Style {
318    let colours = colours(tokens, pressed, status);
319    let outline = variant == Variant::Outline;
320    let border = if status == Status::Disabled {
321        fade(tokens.border, 0.5)
322    } else {
323        tokens.border
324    };
325    widget::button::Style {
326        background: colours.background.map(Background::Color),
327        text_color: colours.foreground,
328        border: Border {
329            color: if outline { border } else { Color::TRANSPARENT },
330            width: if outline { 1.0 } else { 0.0 },
331            radius: radius::MD.into(),
332        },
333        shadow: Shadow::default(),
334        snap: true,
335    }
336}
337
338/// What a toggle keyboard shortcut does.
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
340pub enum Action {
341    Toggle,
342}
343
344impl Action {
345    /// The pressed state to send through the toggle's `on_toggle` message.
346    pub fn apply(self, pressed: bool) -> bool {
347        match self {
348            Action::Toggle => !pressed,
349        }
350    }
351}
352
353impl keys::Action for Action {
354    const ALL: &'static [Self] = &[Action::Toggle];
355
356    fn defaults() -> Keymap<Self> {
357        default_keymap()
358    }
359
360    fn name(self) -> &'static str {
361        match self {
362            Action::Toggle => "Toggle",
363        }
364    }
365
366    fn description(self) -> &'static str {
367        match self {
368            Action::Toggle => "Switches the toggle on or off.",
369        }
370    }
371}
372
373/// The default toggle shortcuts:
374///
375/// | Keys | Action |
376/// | --- | --- |
377/// | `Space` | [`Action::Toggle`] |
378///
379/// Shortcuts are app-wide, so an app with several toggles binds each one
380/// its own chord, such as `Ctrl+B` for a bold toggle.
381pub fn default_keymap() -> Keymap<Action> {
382    Keymap::new().bind(Chord::named(Named::Space), Action::Toggle)
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use crate::theme::{dark, light};
389
390    const STATES: [Status; 4] = [
391        Status::Active,
392        Status::Hovered,
393        Status::Pressed,
394        Status::Disabled,
395    ];
396
397    #[test]
398    fn defaults_to_an_off_medium_toggle_that_is_disabled() {
399        let t: Toggle<'_, bool> = toggle("Bold");
400        assert_eq!(t.variant, Variant::Default);
401        assert_eq!(t.size, Size::Md);
402        assert!(t.icon.is_none());
403        assert!(!t.is_pressed());
404        assert!(!t.is_enabled());
405    }
406
407    #[test]
408    fn builder_sets_every_option() {
409        let t = toggle("Grid")
410            .icon(crate::lucide!(Grid3x3))
411            .pressed(true)
412            .variant(Variant::Outline)
413            .size(Size::Lg)
414            .on_toggle(|on| on);
415        assert_eq!(t.icon.map(Glyph::name), Some("grid-3x3"));
416        assert!(t.is_pressed());
417        assert!(t.is_enabled());
418        assert_eq!(t.variant, Variant::Outline);
419        assert!(
420            !toggle("Grid")
421                .on_toggle_maybe(None::<fn(bool) -> bool>)
422                .is_enabled()
423        );
424        assert!(
425            toggle("Grid")
426                .on_toggle_maybe(Some(|on: bool| on))
427                .is_enabled()
428        );
429        assert_eq!(t.size, Size::Lg);
430    }
431
432    #[test]
433    fn sizes_grow_monotonically() {
434        let heights = Size::ALL.map(|size| size.metrics().height);
435        assert!(heights.windows(2).all(|w| w[0] < w[1]));
436        let icons = Size::ALL.map(|size| size.metrics().icon);
437        assert!(icons.windows(2).all(|w| w[0] < w[1]));
438    }
439
440    #[test]
441    fn on_takes_the_accent_and_off_is_transparent_at_rest() {
442        for theme in [light(), dark()] {
443            let tokens = Tokens::of(&theme);
444            let on = colours(&tokens, true, Status::Active);
445            let off = colours(&tokens, false, Status::Active);
446            assert_eq!(on.background, Some(tokens.accent));
447            assert_eq!(on.foreground, tokens.accent_foreground);
448            assert_eq!(off.background, None);
449            assert_eq!(off.foreground, tokens.muted_foreground);
450        }
451    }
452
453    #[test]
454    fn hover_changes_the_background_on_and_off() {
455        for theme in [light(), dark()] {
456            let tokens = Tokens::of(&theme);
457            for pressed in [false, true] {
458                let rest = colours(&tokens, pressed, Status::Active);
459                for status in [Status::Hovered, Status::Pressed] {
460                    let hovered = colours(&tokens, pressed, status);
461                    assert_ne!(hovered.background, rest.background, "{pressed} {status:?}");
462                    assert!(hovered.background.is_some());
463                }
464            }
465        }
466    }
467
468    fn distance(a: Color, b: Color) -> f32 {
469        (a.r - b.r).abs() + (a.g - b.g).abs() + (a.b - b.b).abs()
470    }
471
472    #[test]
473    fn hovering_an_off_toggle_is_lighter_than_pressing_it() {
474        for theme in [light(), dark()] {
475            let tokens = Tokens::of(&theme);
476            let pressed = colours(&tokens, true, Status::Active);
477            let hovered = colours(&tokens, false, Status::Hovered);
478            let (Some(pressed_fill), Some(hovered_fill)) = (pressed.background, hovered.background)
479            else {
480                panic!("both fill");
481            };
482            let pressed_lift = distance(pressed_fill, tokens.background);
483            let hovered_lift = distance(hovered_fill, tokens.background);
484            assert!(hovered_lift > 0.0, "{}", tokens.is_dark);
485            assert!(hovered_lift < pressed_lift * 0.6, "{}", tokens.is_dark);
486            assert_ne!(hovered.foreground, pressed.foreground);
487            assert_eq!(hovered.foreground, tokens.muted_foreground);
488        }
489    }
490
491    #[test]
492    fn on_and_off_differ_in_every_enabled_state() {
493        let tokens = Tokens::of(&light());
494        for status in [Status::Active, Status::Hovered, Status::Pressed] {
495            assert_ne!(
496                colours(&tokens, true, status),
497                colours(&tokens, false, status),
498                "{status:?}"
499            );
500        }
501    }
502
503    #[test]
504    fn disabled_keeps_the_look_at_half_alpha() {
505        for theme in [light(), dark()] {
506            let tokens = Tokens::of(&theme);
507            for pressed in [false, true] {
508                let rest = colours(&tokens, pressed, Status::Active);
509                let disabled = colours(&tokens, pressed, Status::Disabled);
510                assert!((disabled.foreground.a - rest.foreground.a * 0.5).abs() < 1e-6);
511                assert_eq!(
512                    disabled.background.map(|c| c.a),
513                    rest.background.map(|c| c.a * 0.5)
514                );
515            }
516        }
517    }
518
519    #[test]
520    fn only_outline_has_a_border_in_every_state() {
521        let tokens = Tokens::of(&dark());
522        for variant in Variant::ALL {
523            for pressed in [false, true] {
524                for status in STATES {
525                    let style = style(&tokens, variant, pressed, status);
526                    assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
527                    assert_eq!(style.border.radius, radius::MD.into());
528                }
529            }
530        }
531    }
532
533    #[test]
534    fn toggle_action_flips_the_state() {
535        assert!(Action::Toggle.apply(false));
536        assert!(!Action::Toggle.apply(true));
537    }
538
539    #[test]
540    fn default_keymap_and_overrides() {
541        let space = iced::keyboard::Key::Named(Named::Space);
542        let keymap = default_keymap();
543        assert_eq!(
544            keymap.resolve(&space, Default::default()),
545            Some(Action::Toggle)
546        );
547        assert_eq!(Keymap::<Action>::defaults(), keymap);
548
549        let bold: Chord = "Ctrl+B".parse().unwrap();
550        let custom = keymap
551            .unbind(&Chord::named(Named::Space))
552            .bind(bold.clone(), Action::Toggle);
553        assert_eq!(custom.resolve(&space, Default::default()), None);
554        assert_eq!(
555            custom.resolve(bold.key(), bold.modifiers()),
556            Some(Action::Toggle)
557        );
558        assert!(custom.unbind_action(&Action::Toggle).is_empty());
559    }
560}