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        #[cfg(feature = "icedwright")]
197        {
198            element = annotate(element, label.clone(), pressed, enabled, position.is_some());
199        }
200        if let (Some(label), Some(position)) = (label, position) {
201            element = tooltip(element, label).position(position).into();
202        }
203        element
204    }
205}
206
207/// A plain icon button is a `Button`; one drawn pressed is a pressed
208/// `ToggleButton`. The label names it and is its tooltip when one shows.
209#[cfg(feature = "icedwright")]
210fn annotate<'a, Message: 'a>(
211    element: Element<'a, Message>,
212    label: Option<text::Fragment<'a>>,
213    pressed: bool,
214    enabled: bool,
215    tooltip: bool,
216) -> Element<'a, Message> {
217    use icedwright_probe::role::RoleKind;
218    use icedwright_probe::{Semantic, role, semantic};
219
220    fn finish<'a, Message: 'a, R: RoleKind>(
221        mut annotated: Semantic<'a, Message, iced::Theme, iced::Renderer, R>,
222        label: Option<text::Fragment<'a>>,
223        enabled: bool,
224        tooltip: bool,
225    ) -> Element<'a, Message> {
226        annotated = annotated.component("iced_cube::icon_button");
227        if !enabled {
228            annotated = annotated.disabled(true);
229        }
230        if let Some(label) = label {
231            if tooltip {
232                annotated = annotated.tooltip(label.clone());
233            }
234            annotated = annotated.name(label);
235        }
236        annotated.into()
237    }
238
239    if pressed {
240        let annotated = semantic(element).role(role::ToggleButton).pressed(true);
241        return finish(annotated, label, enabled, tooltip);
242    }
243    finish(
244        semantic(element).role(role::Button),
245        label,
246        enabled,
247        tooltip,
248    )
249}
250
251/// Colours of an icon button, switched on or off, in a state.
252///
253/// A pressed button looks held down at rest and darkens a little more on
254/// hover, so it reads as on in every state.
255pub fn colours(tokens: &Tokens, variant: Variant, pressed: bool, status: Status) -> Colours {
256    let variant = variant.button();
257    if !pressed {
258        return button::colours(tokens, variant, status);
259    }
260
261    let held = button::colours(tokens, variant, Status::Pressed);
262    match status {
263        Status::Active => held,
264        Status::Hovered | Status::Pressed => Colours {
265            background: held
266                .background
267                .map(|background| mix(background, tokens.foreground, 0.08)),
268            ..held
269        },
270        Status::Disabled => Colours {
271            background: held.background.map(|c| fade(c, 0.5)),
272            foreground: fade(held.foreground, 0.5),
273            border: held.border.map(|c| fade(c, 0.5)),
274        },
275    }
276}
277
278/// The iced button style of an icon button, switched on or off, in a state.
279pub fn style(
280    tokens: &Tokens,
281    variant: Variant,
282    pressed: bool,
283    status: Status,
284) -> widget::button::Style {
285    let colours = colours(tokens, variant, pressed, status);
286    widget::button::Style {
287        background: colours.background.map(Background::Color),
288        text_color: colours.foreground,
289        border: Border {
290            color: colours.border.unwrap_or(iced::Color::TRANSPARENT),
291            width: if colours.border.is_some() { 1.0 } else { 0.0 },
292            radius: radius::MD.into(),
293        },
294        shadow: Shadow::default(),
295        snap: true,
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use crate::theme::{dark, light};
303
304    const STATES: [Status; 4] = [
305        Status::Active,
306        Status::Hovered,
307        Status::Pressed,
308        Status::Disabled,
309    ];
310
311    #[test]
312    fn defaults_to_a_medium_ghost_button_that_is_off_and_disabled() {
313        let b: IconButton<'_, ()> = icon_button(crate::lucide!(Plus));
314        assert_eq!(b.variant, Variant::Ghost);
315        assert_eq!(b.size, Size::Md);
316        assert!(!b.is_pressed());
317        assert!(!b.is_enabled());
318        assert!(b.label_text().is_none());
319        assert_eq!(b.tooltip, Some(Position::Top));
320    }
321
322    #[test]
323    fn builder_sets_every_option() {
324        let b = icon_button::<u8>(crate::lucide!(Bold))
325            .label("Bold")
326            .tooltip(None)
327            .variant(Variant::Outline)
328            .size(Size::Sm)
329            .pressed(true)
330            .on_press(1);
331        assert_eq!(b.label_text(), Some("Bold"));
332        assert!(b.tooltip.is_none());
333        assert_eq!(b.variant, Variant::Outline);
334        assert_eq!(b.size, Size::Sm);
335        assert!(b.is_pressed());
336        assert!(b.is_enabled());
337        assert!(!b.on_press_maybe(None).is_enabled());
338    }
339
340    #[test]
341    fn unpressed_matches_the_button_colours() {
342        for theme in [light(), dark()] {
343            let tokens = Tokens::of(&theme);
344            for variant in Variant::ALL {
345                for status in STATES {
346                    assert_eq!(
347                        colours(&tokens, variant, false, status),
348                        button::colours(&tokens, variant.into(), status),
349                        "{variant:?} {status:?}"
350                    );
351                }
352            }
353        }
354    }
355
356    #[test]
357    fn variants_map_to_every_button_variant_but_link() {
358        let mapped = Variant::ALL.map(Variant::button);
359        assert!(!mapped.contains(&button::Variant::Link));
360        for variant in button::Variant::ALL {
361            assert_eq!(
362                mapped.contains(&variant),
363                variant != button::Variant::Link,
364                "{variant:?}"
365            );
366        }
367    }
368
369    #[test]
370    fn pressed_ghost_and_outline_use_the_accent_at_rest() {
371        for theme in [light(), dark()] {
372            let tokens = Tokens::of(&theme);
373            for variant in [Variant::Ghost, Variant::Outline] {
374                let on = colours(&tokens, variant, true, Status::Active);
375                assert_eq!(on.background, Some(tokens.accent), "{variant:?}");
376                assert_ne!(
377                    on.background,
378                    colours(&tokens, variant, false, Status::Active).background
379                );
380            }
381        }
382    }
383
384    #[test]
385    fn pressed_differs_from_unpressed_at_rest_for_filled_variants() {
386        for theme in [light(), dark()] {
387            let tokens = Tokens::of(&theme);
388            for variant in [
389                Variant::Primary,
390                Variant::Secondary,
391                Variant::Destructive,
392                Variant::Outline,
393                Variant::Ghost,
394            ] {
395                assert_ne!(
396                    colours(&tokens, variant, true, Status::Active).background,
397                    colours(&tokens, variant, false, Status::Active).background,
398                    "{variant:?}"
399                );
400            }
401        }
402    }
403
404    #[test]
405    fn hovering_a_pressed_button_darkens_it() {
406        for theme in [light(), dark()] {
407            let tokens = Tokens::of(&theme);
408            for variant in [Variant::Ghost, Variant::Outline, Variant::Primary] {
409                let rest = colours(&tokens, variant, true, Status::Active);
410                for status in [Status::Hovered, Status::Pressed] {
411                    let active = colours(&tokens, variant, true, status);
412                    assert_ne!(active.background, rest.background, "{variant:?} {status:?}");
413                    assert_eq!(active.foreground, rest.foreground);
414                }
415            }
416        }
417    }
418
419    #[test]
420    fn disabled_pressed_keeps_the_on_look_at_half_alpha() {
421        for theme in [light(), dark()] {
422            let tokens = Tokens::of(&theme);
423            for variant in Variant::ALL {
424                let on = colours(&tokens, variant, true, Status::Active);
425                let disabled = colours(&tokens, variant, true, Status::Disabled);
426                assert!((disabled.foreground.a - on.foreground.a * 0.5).abs() < 1e-6);
427                assert_eq!(
428                    disabled.background.map(|c| c.a),
429                    on.background.map(|c| c.a * 0.5)
430                );
431            }
432        }
433    }
434
435    #[test]
436    fn only_outline_has_a_border_in_every_state() {
437        let tokens = Tokens::of(&light());
438        for variant in Variant::ALL {
439            for pressed in [false, true] {
440                for status in STATES {
441                    let style = style(&tokens, variant, pressed, status);
442                    assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
443                    assert_eq!(style.border.radius, radius::MD.into());
444                }
445            }
446        }
447    }
448}