Skip to main content

iced_cube/primitives/
icon_button.rs

1//! Square, icon-only buttons with a label and an optional pressed state.
2//!
3//! Icon buttons share their [`Size`] and colours with
4//! [`button`](fn@crate::primitives::button), and every button variant except
5//! `Link`. A pressed icon button stays highlighted, which suits toolbar
6//! toggles such as bold or italic.
7
8use iced::widget::{self, button::Status, container, text};
9use iced::{Background, Border, Element, Length, Padding, Shadow};
10
11use crate::after_touch::after_touch;
12use crate::focus::{Ring, focusable};
13use crate::icon::{Glyph, opacity, themed};
14use crate::overlay::tooltip::{Position, tooltip};
15use crate::primitives::button::{self, Colours, Size};
16use crate::theme::{Tokens, fade, mix, radius};
17
18/// Visual emphasis of an icon button.
19///
20/// These are the text button variants without `Link`, which needs text to
21/// read as a link and on an icon alone looks just like `Ghost`.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
23pub enum Variant {
24    Primary,
25    Secondary,
26    Destructive,
27    Outline,
28    #[default]
29    Ghost,
30}
31
32impl Variant {
33    pub const ALL: [Variant; 5] = [
34        Variant::Primary,
35        Variant::Secondary,
36        Variant::Destructive,
37        Variant::Outline,
38        Variant::Ghost,
39    ];
40
41    /// The text button variant with the same colours.
42    pub const fn button(self) -> button::Variant {
43        match self {
44            Variant::Primary => button::Variant::Primary,
45            Variant::Secondary => button::Variant::Secondary,
46            Variant::Destructive => button::Variant::Destructive,
47            Variant::Outline => button::Variant::Outline,
48            Variant::Ghost => button::Variant::Ghost,
49        }
50    }
51}
52
53impl From<Variant> for button::Variant {
54    fn from(variant: Variant) -> Self {
55        variant.button()
56    }
57}
58
59/// An icon button builder. Convert it into an [`Element`] to render.
60///
61/// An icon button without a message is rendered disabled.
62///
63/// Like [`button`](fn@crate::primitives::button), an enabled icon button
64/// takes keyboard focus from iced's focus operations, rings while focused
65/// and is pressed with Enter or Space. Focus also shows its tooltip.
66#[derive(Debug)]
67pub struct IconButton<'a, Message> {
68    glyph: Glyph,
69    label: Option<text::Fragment<'a>>,
70    tooltip: Option<Position>,
71    variant: Variant,
72    size: Size,
73    pressed: bool,
74    id: Option<widget::Id>,
75    on_press: Option<Message>,
76}
77
78/// Creates a square ghost button showing `glyph`.
79pub fn icon_button<'a, Message>(glyph: Glyph) -> IconButton<'a, Message> {
80    IconButton {
81        glyph,
82        label: None,
83        tooltip: Some(Position::default()),
84        variant: Variant::Ghost,
85        size: Size::Md,
86        pressed: false,
87        id: None,
88        on_press: None,
89    }
90}
91
92impl<'a, Message> IconButton<'a, Message> {
93    /// Names the action, such as "Bold". The label shows as a tooltip on
94    /// hover unless [`tooltip`](Self::tooltip) turns it off.
95    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
96        self.label = Some(label.into_fragment());
97        self
98    }
99
100    /// Where the label's tooltip appears, or `None` to never show it.
101    /// Defaults to above the button.
102    pub fn tooltip(mut self, position: Option<Position>) -> Self {
103        self.tooltip = position;
104        self
105    }
106
107    pub fn variant(mut self, variant: Variant) -> Self {
108        self.variant = variant;
109        self
110    }
111
112    /// The side length follows the button [`Size`]: `Sm` is 32 pixels,
113    /// `Md` is 36 and `Lg` is 40.
114    pub fn size(mut self, size: Size) -> Self {
115        self.size = size;
116        self
117    }
118
119    /// Draws the button as switched on, for toggles in a toolbar.
120    pub fn pressed(mut self, pressed: bool) -> Self {
121        self.pressed = pressed;
122        self
123    }
124
125    /// Sets a widget id, for clicking the button in tests or focusing it
126    /// with iced's `focus` operation.
127    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
128        self.id = Some(id.into());
129        self
130    }
131
132    pub fn on_press(mut self, message: Message) -> Self {
133        self.on_press = Some(message);
134        self
135    }
136
137    pub fn on_press_maybe(mut self, message: Option<Message>) -> Self {
138        self.on_press = message;
139        self
140    }
141
142    pub fn is_enabled(&self) -> bool {
143        self.on_press.is_some()
144    }
145
146    pub fn is_pressed(&self) -> bool {
147        self.pressed
148    }
149
150    /// The label, if one is set.
151    pub fn label_text(&self) -> Option<&str> {
152        self.label.as_deref()
153    }
154}
155
156impl<'a, Message: Clone + 'a> From<IconButton<'a, Message>> for Element<'a, Message> {
157    fn from(icon_button: IconButton<'a, Message>) -> Self {
158        let IconButton {
159            glyph,
160            label,
161            tooltip: position,
162            variant,
163            size,
164            pressed,
165            id,
166            on_press,
167        } = icon_button;
168        let metrics = size.metrics();
169        let enabled = on_press.is_some();
170        let resting = if enabled {
171            Status::Active
172        } else {
173            Status::Disabled
174        };
175
176        let glyph = themed(glyph, metrics.icon, opacity(enabled), move |theme| {
177            colours(&Tokens::of(theme), variant, pressed, resting).foreground
178        });
179
180        let on_activate = on_press
181            .clone()
182            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
183        let button = widget::button(glyph)
184            .width(Length::Fixed(metrics.height))
185            .height(Length::Fixed(metrics.height))
186            .padding(Padding::from((metrics.height - metrics.icon) / 2.0))
187            .on_press_maybe(on_press)
188            .style(move |theme, status| style(&Tokens::of(theme), variant, pressed, status));
189        let mut button = focusable(after_touch(button), on_activate, Ring::around(radius::MD));
190        button.id = id.clone();
191
192        let mut element: Element<'a, Message> = match id {
193            Some(id) => container(button).id(id).into(),
194            None => button.into(),
195        };
196        if let (Some(label), Some(position)) = (label, position) {
197            element = tooltip(element, label).position(position).into();
198        }
199        element
200    }
201}
202
203/// Colours of an icon button, switched on or off, in a state.
204///
205/// A pressed button looks held down at rest and darkens a little more on
206/// hover, so it reads as on in every state.
207pub fn colours(tokens: &Tokens, variant: Variant, pressed: bool, status: Status) -> Colours {
208    let variant = variant.button();
209    if !pressed {
210        return button::colours(tokens, variant, status);
211    }
212
213    let held = button::colours(tokens, variant, Status::Pressed);
214    match status {
215        Status::Active => held,
216        Status::Hovered | Status::Pressed => Colours {
217            background: held
218                .background
219                .map(|background| mix(background, tokens.foreground, 0.08)),
220            ..held
221        },
222        Status::Disabled => Colours {
223            background: held.background.map(|c| fade(c, 0.5)),
224            foreground: fade(held.foreground, 0.5),
225            border: held.border.map(|c| fade(c, 0.5)),
226        },
227    }
228}
229
230/// The iced button style of an icon button, switched on or off, in a state.
231pub fn style(
232    tokens: &Tokens,
233    variant: Variant,
234    pressed: bool,
235    status: Status,
236) -> widget::button::Style {
237    let colours = colours(tokens, variant, pressed, status);
238    widget::button::Style {
239        background: colours.background.map(Background::Color),
240        text_color: colours.foreground,
241        border: Border {
242            color: colours.border.unwrap_or(iced::Color::TRANSPARENT),
243            width: if colours.border.is_some() { 1.0 } else { 0.0 },
244            radius: radius::MD.into(),
245        },
246        shadow: Shadow::default(),
247        snap: true,
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::theme::{dark, light};
255
256    const STATES: [Status; 4] = [
257        Status::Active,
258        Status::Hovered,
259        Status::Pressed,
260        Status::Disabled,
261    ];
262
263    #[test]
264    fn defaults_to_a_medium_ghost_button_that_is_off_and_disabled() {
265        let b: IconButton<'_, ()> = icon_button(crate::lucide!(Plus));
266        assert_eq!(b.variant, Variant::Ghost);
267        assert_eq!(b.size, Size::Md);
268        assert!(!b.is_pressed());
269        assert!(!b.is_enabled());
270        assert!(b.label_text().is_none());
271        assert_eq!(b.tooltip, Some(Position::Top));
272    }
273
274    #[test]
275    fn builder_sets_every_option() {
276        let b = icon_button::<u8>(crate::lucide!(Bold))
277            .label("Bold")
278            .tooltip(None)
279            .variant(Variant::Outline)
280            .size(Size::Sm)
281            .pressed(true)
282            .on_press(1);
283        assert_eq!(b.label_text(), Some("Bold"));
284        assert!(b.tooltip.is_none());
285        assert_eq!(b.variant, Variant::Outline);
286        assert_eq!(b.size, Size::Sm);
287        assert!(b.is_pressed());
288        assert!(b.is_enabled());
289        assert!(!b.on_press_maybe(None).is_enabled());
290    }
291
292    #[test]
293    fn unpressed_matches_the_button_colours() {
294        for theme in [light(), dark()] {
295            let tokens = Tokens::of(&theme);
296            for variant in Variant::ALL {
297                for status in STATES {
298                    assert_eq!(
299                        colours(&tokens, variant, false, status),
300                        button::colours(&tokens, variant.into(), status),
301                        "{variant:?} {status:?}"
302                    );
303                }
304            }
305        }
306    }
307
308    #[test]
309    fn variants_map_to_every_button_variant_but_link() {
310        let mapped = Variant::ALL.map(Variant::button);
311        assert!(!mapped.contains(&button::Variant::Link));
312        for variant in button::Variant::ALL {
313            assert_eq!(
314                mapped.contains(&variant),
315                variant != button::Variant::Link,
316                "{variant:?}"
317            );
318        }
319    }
320
321    #[test]
322    fn pressed_ghost_and_outline_use_the_accent_at_rest() {
323        for theme in [light(), dark()] {
324            let tokens = Tokens::of(&theme);
325            for variant in [Variant::Ghost, Variant::Outline] {
326                let on = colours(&tokens, variant, true, Status::Active);
327                assert_eq!(on.background, Some(tokens.accent), "{variant:?}");
328                assert_ne!(
329                    on.background,
330                    colours(&tokens, variant, false, Status::Active).background
331                );
332            }
333        }
334    }
335
336    #[test]
337    fn pressed_differs_from_unpressed_at_rest_for_filled_variants() {
338        for theme in [light(), dark()] {
339            let tokens = Tokens::of(&theme);
340            for variant in [
341                Variant::Primary,
342                Variant::Secondary,
343                Variant::Destructive,
344                Variant::Outline,
345                Variant::Ghost,
346            ] {
347                assert_ne!(
348                    colours(&tokens, variant, true, Status::Active).background,
349                    colours(&tokens, variant, false, Status::Active).background,
350                    "{variant:?}"
351                );
352            }
353        }
354    }
355
356    #[test]
357    fn hovering_a_pressed_button_darkens_it() {
358        for theme in [light(), dark()] {
359            let tokens = Tokens::of(&theme);
360            for variant in [Variant::Ghost, Variant::Outline, Variant::Primary] {
361                let rest = colours(&tokens, variant, true, Status::Active);
362                for status in [Status::Hovered, Status::Pressed] {
363                    let active = colours(&tokens, variant, true, status);
364                    assert_ne!(active.background, rest.background, "{variant:?} {status:?}");
365                    assert_eq!(active.foreground, rest.foreground);
366                }
367            }
368        }
369    }
370
371    #[test]
372    fn disabled_pressed_keeps_the_on_look_at_half_alpha() {
373        for theme in [light(), dark()] {
374            let tokens = Tokens::of(&theme);
375            for variant in Variant::ALL {
376                let on = colours(&tokens, variant, true, Status::Active);
377                let disabled = colours(&tokens, variant, true, Status::Disabled);
378                assert!((disabled.foreground.a - on.foreground.a * 0.5).abs() < 1e-6);
379                assert_eq!(
380                    disabled.background.map(|c| c.a),
381                    on.background.map(|c| c.a * 0.5)
382                );
383            }
384        }
385    }
386
387    #[test]
388    fn only_outline_has_a_border_in_every_state() {
389        let tokens = Tokens::of(&light());
390        for variant in Variant::ALL {
391            for pressed in [false, true] {
392                for status in STATES {
393                    let style = style(&tokens, variant, pressed, status);
394                    assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
395                    assert_eq!(style.border.radius, radius::MD.into());
396                }
397            }
398        }
399    }
400}