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    kind: Kind,
74    id: Option<widget::Id>,
75    on_press: Option<Message>,
76}
77
78/// What an icon button is for, which decides how it reports itself and
79/// whether it is drawn held down.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81enum Kind {
82    /// A plain button.
83    #[default]
84    Plain,
85    /// A toggle, on or off.
86    Toggle(bool),
87    /// Opens a menu or panel, shown or not.
88    Trigger(bool),
89}
90
91impl Kind {
92    fn is_held(self) -> bool {
93        matches!(self, Kind::Toggle(true) | Kind::Trigger(true))
94    }
95}
96
97/// Creates a square ghost button showing `glyph`.
98pub fn icon_button<'a, Message>(glyph: Glyph) -> IconButton<'a, Message> {
99    IconButton {
100        glyph,
101        label: None,
102        tooltip: Some(Position::default()),
103        variant: Variant::Ghost,
104        size: Size::Md,
105        kind: Kind::Plain,
106        id: None,
107        on_press: None,
108    }
109}
110
111impl<'a, Message> IconButton<'a, Message> {
112    /// Names the action, such as "Bold". The label shows as a tooltip on
113    /// hover unless [`tooltip`](Self::tooltip) turns it off.
114    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
115        self.label = Some(label.into_fragment());
116        self
117    }
118
119    /// Where the label's tooltip appears, or `None` to never show it.
120    /// Defaults to above the button.
121    pub fn tooltip(mut self, position: Option<Position>) -> Self {
122        self.tooltip = position;
123        self
124    }
125
126    pub fn variant(mut self, variant: Variant) -> Self {
127        self.variant = variant;
128        self
129    }
130
131    /// The side length follows the button [`Size`]: `Sm` is 32 pixels,
132    /// `Md` is 36 and `Lg` is 40.
133    pub fn size(mut self, size: Size) -> Self {
134        self.size = size;
135        self
136    }
137
138    /// Makes the button a toggle, drawn as switched on while `pressed`, for
139    /// toggles in a toolbar.
140    pub fn pressed(mut self, pressed: bool) -> Self {
141        self.kind = Kind::Toggle(pressed);
142        self
143    }
144
145    /// Makes the button the trigger of a menu or panel, drawn held down
146    /// while it is `expanded`.
147    pub fn expanded(mut self, expanded: bool) -> Self {
148        self.kind = Kind::Trigger(expanded);
149        self
150    }
151
152    /// Sets a widget id, for clicking the button in tests or focusing it
153    /// with iced's `focus` operation.
154    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
155        self.id = Some(id.into());
156        self
157    }
158
159    pub fn on_press(mut self, message: Message) -> Self {
160        self.on_press = Some(message);
161        self
162    }
163
164    pub fn on_press_maybe(mut self, message: Option<Message>) -> Self {
165        self.on_press = message;
166        self
167    }
168
169    pub fn is_enabled(&self) -> bool {
170        self.on_press.is_some()
171    }
172
173    /// Whether it is drawn held down: a toggle that is on, or a trigger
174    /// whose menu is open.
175    pub fn is_pressed(&self) -> bool {
176        self.kind.is_held()
177    }
178
179    /// Whether it is a toggle, on or off.
180    pub fn is_toggle(&self) -> bool {
181        matches!(self.kind, Kind::Toggle(_))
182    }
183
184    /// The label, if one is set.
185    pub fn label_text(&self) -> Option<&str> {
186        self.label.as_deref()
187    }
188}
189
190impl<'a, Message: Clone + 'a> From<IconButton<'a, Message>> for Element<'a, Message> {
191    fn from(icon_button: IconButton<'a, Message>) -> Self {
192        let IconButton {
193            glyph,
194            label,
195            tooltip: position,
196            variant,
197            size,
198            kind,
199            id,
200            on_press,
201        } = icon_button;
202        let pressed = kind.is_held();
203        let metrics = size.metrics();
204        let enabled = on_press.is_some();
205        let resting = if enabled {
206            Status::Active
207        } else {
208            Status::Disabled
209        };
210
211        let glyph = themed(glyph, metrics.icon, opacity(enabled), move |theme| {
212            colours(&Tokens::of(theme), variant, pressed, resting).foreground
213        });
214
215        let on_activate = on_press
216            .clone()
217            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
218        let button = widget::button(glyph)
219            .width(Length::Fixed(metrics.height))
220            .height(Length::Fixed(metrics.height))
221            .padding(Padding::from((metrics.height - metrics.icon) / 2.0))
222            .on_press_maybe(on_press)
223            .style(move |theme, status| style(&Tokens::of(theme), variant, pressed, status));
224        let mut button = focusable(after_touch(button), on_activate, Ring::around(radius::MD));
225        button.id = id.clone();
226
227        let mut element: Element<'a, Message> = match id {
228            Some(id) => container(button).id(id).into(),
229            None => button.into(),
230        };
231        #[cfg(feature = "icedwright")]
232        {
233            element = annotate(element, label.clone(), kind, enabled, position.is_some());
234        }
235        if let (Some(label), Some(position)) = (label, position) {
236            element = tooltip(element, label).position(position).into();
237        }
238        element
239    }
240}
241
242/// A plain icon button is a `Button`, a toggle is a `ToggleButton` with its
243/// pressed state and a trigger is a `Button` with its expanded state. The
244/// label names it and is its tooltip when one shows.
245#[cfg(feature = "icedwright")]
246fn annotate<'a, Message: 'a>(
247    element: Element<'a, Message>,
248    label: Option<text::Fragment<'a>>,
249    kind: Kind,
250    enabled: bool,
251    tooltip: bool,
252) -> Element<'a, Message> {
253    use icedwright_probe::role::RoleKind;
254    use icedwright_probe::{Semantic, role, semantic};
255
256    fn finish<'a, Message: 'a, R: RoleKind>(
257        mut annotated: Semantic<'a, Message, iced::Theme, iced::Renderer, R>,
258        label: Option<text::Fragment<'a>>,
259        enabled: bool,
260        tooltip: bool,
261    ) -> Element<'a, Message> {
262        annotated = annotated
263            .component("iced_cube::icon_button")
264            .disabled(!enabled);
265        if let Some(label) = label {
266            if tooltip {
267                annotated = annotated.tooltip(label.clone());
268            }
269            annotated = annotated.name(label);
270        }
271        annotated.into()
272    }
273
274    match kind {
275        Kind::Plain => finish(
276            semantic(element).role(role::Button),
277            label,
278            enabled,
279            tooltip,
280        ),
281        Kind::Toggle(pressed) => finish(
282            semantic(element).role(role::ToggleButton).pressed(pressed),
283            label,
284            enabled,
285            tooltip,
286        ),
287        Kind::Trigger(expanded) => finish(
288            semantic(element).role(role::Button).expanded(expanded),
289            label,
290            enabled,
291            tooltip,
292        ),
293    }
294}
295
296/// Colours of an icon button, switched on or off, in a state.
297///
298/// A pressed button looks held down at rest and darkens a little more on
299/// hover, so it reads as on in every state.
300pub fn colours(tokens: &Tokens, variant: Variant, pressed: bool, status: Status) -> Colours {
301    let variant = variant.button();
302    if !pressed {
303        return button::colours(tokens, variant, status);
304    }
305
306    let held = button::colours(tokens, variant, Status::Pressed);
307    match status {
308        Status::Active => held,
309        Status::Hovered | Status::Pressed => Colours {
310            background: held
311                .background
312                .map(|background| mix(background, tokens.foreground, 0.08)),
313            ..held
314        },
315        Status::Disabled => Colours {
316            background: held.background.map(|c| fade(c, 0.5)),
317            foreground: fade(held.foreground, 0.5),
318            border: held.border.map(|c| fade(c, 0.5)),
319        },
320    }
321}
322
323/// The iced button style of an icon button, switched on or off, in a state.
324pub fn style(
325    tokens: &Tokens,
326    variant: Variant,
327    pressed: bool,
328    status: Status,
329) -> widget::button::Style {
330    let colours = colours(tokens, variant, pressed, status);
331    widget::button::Style {
332        background: colours.background.map(Background::Color),
333        text_color: colours.foreground,
334        border: Border {
335            color: colours.border.unwrap_or(iced::Color::TRANSPARENT),
336            width: if colours.border.is_some() { 1.0 } else { 0.0 },
337            radius: radius::MD.into(),
338        },
339        shadow: Shadow::default(),
340        snap: true,
341    }
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use crate::theme::{dark, light};
348
349    const STATES: [Status; 4] = [
350        Status::Active,
351        Status::Hovered,
352        Status::Pressed,
353        Status::Disabled,
354    ];
355
356    #[test]
357    fn defaults_to_a_medium_ghost_button_that_is_off_and_disabled() {
358        let b: IconButton<'_, ()> = icon_button(crate::lucide!(Plus));
359        assert_eq!(b.variant, Variant::Ghost);
360        assert_eq!(b.size, Size::Md);
361        assert!(!b.is_pressed());
362        assert!(!b.is_enabled());
363        assert!(b.label_text().is_none());
364        assert_eq!(b.tooltip, Some(Position::Top));
365    }
366
367    #[test]
368    fn builder_sets_every_option() {
369        let b = icon_button::<u8>(crate::lucide!(Bold))
370            .label("Bold")
371            .tooltip(None)
372            .variant(Variant::Outline)
373            .size(Size::Sm)
374            .pressed(true)
375            .on_press(1);
376        assert_eq!(b.label_text(), Some("Bold"));
377        assert!(b.tooltip.is_none());
378        assert_eq!(b.variant, Variant::Outline);
379        assert_eq!(b.size, Size::Sm);
380        assert!(b.is_pressed());
381        assert!(b.is_enabled());
382        assert!(!b.on_press_maybe(None).is_enabled());
383    }
384
385    #[test]
386    fn a_toggle_stays_a_toggle_when_off_and_a_trigger_is_held_while_open() {
387        let plain = icon_button::<u8>(crate::lucide!(Bold));
388        assert!(!plain.is_toggle() && !plain.is_pressed());
389        let off = icon_button::<u8>(crate::lucide!(Bold)).pressed(false);
390        assert!(off.is_toggle() && !off.is_pressed());
391        let closed = icon_button::<u8>(crate::lucide!(Ellipsis)).expanded(false);
392        assert!(!closed.is_toggle() && !closed.is_pressed());
393        let open = icon_button::<u8>(crate::lucide!(Ellipsis)).expanded(true);
394        assert!(!open.is_toggle() && open.is_pressed());
395    }
396
397    #[test]
398    fn unpressed_matches_the_button_colours() {
399        for theme in [light(), dark()] {
400            let tokens = Tokens::of(&theme);
401            for variant in Variant::ALL {
402                for status in STATES {
403                    assert_eq!(
404                        colours(&tokens, variant, false, status),
405                        button::colours(&tokens, variant.into(), status),
406                        "{variant:?} {status:?}"
407                    );
408                }
409            }
410        }
411    }
412
413    #[test]
414    fn variants_map_to_every_button_variant_but_link() {
415        let mapped = Variant::ALL.map(Variant::button);
416        assert!(!mapped.contains(&button::Variant::Link));
417        for variant in button::Variant::ALL {
418            assert_eq!(
419                mapped.contains(&variant),
420                variant != button::Variant::Link,
421                "{variant:?}"
422            );
423        }
424    }
425
426    #[test]
427    fn pressed_ghost_and_outline_use_the_accent_at_rest() {
428        for theme in [light(), dark()] {
429            let tokens = Tokens::of(&theme);
430            for variant in [Variant::Ghost, Variant::Outline] {
431                let on = colours(&tokens, variant, true, Status::Active);
432                assert_eq!(on.background, Some(tokens.accent), "{variant:?}");
433                assert_ne!(
434                    on.background,
435                    colours(&tokens, variant, false, Status::Active).background
436                );
437            }
438        }
439    }
440
441    #[test]
442    fn pressed_differs_from_unpressed_at_rest_for_filled_variants() {
443        for theme in [light(), dark()] {
444            let tokens = Tokens::of(&theme);
445            for variant in [
446                Variant::Primary,
447                Variant::Secondary,
448                Variant::Destructive,
449                Variant::Outline,
450                Variant::Ghost,
451            ] {
452                assert_ne!(
453                    colours(&tokens, variant, true, Status::Active).background,
454                    colours(&tokens, variant, false, Status::Active).background,
455                    "{variant:?}"
456                );
457            }
458        }
459    }
460
461    #[test]
462    fn hovering_a_pressed_button_darkens_it() {
463        for theme in [light(), dark()] {
464            let tokens = Tokens::of(&theme);
465            for variant in [Variant::Ghost, Variant::Outline, Variant::Primary] {
466                let rest = colours(&tokens, variant, true, Status::Active);
467                for status in [Status::Hovered, Status::Pressed] {
468                    let active = colours(&tokens, variant, true, status);
469                    assert_ne!(active.background, rest.background, "{variant:?} {status:?}");
470                    assert_eq!(active.foreground, rest.foreground);
471                }
472            }
473        }
474    }
475
476    #[test]
477    fn disabled_pressed_keeps_the_on_look_at_half_alpha() {
478        for theme in [light(), dark()] {
479            let tokens = Tokens::of(&theme);
480            for variant in Variant::ALL {
481                let on = colours(&tokens, variant, true, Status::Active);
482                let disabled = colours(&tokens, variant, true, Status::Disabled);
483                assert!((disabled.foreground.a - on.foreground.a * 0.5).abs() < 1e-6);
484                assert_eq!(
485                    disabled.background.map(|c| c.a),
486                    on.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(&light());
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}