Skip to main content

iced_cube/primitives/
button.rs

1//! Buttons with consistent variants, sizes and states.
2
3use iced::widget::{self, button::Status, row, text};
4use iced::{Alignment, Background, Border, Element, Length, Padding, Shadow};
5
6use crate::after_touch::after_touch;
7use crate::focus::{Ring, focusable};
8use crate::icon::{Glyph, opacity, themed};
9use crate::natural::natural;
10use crate::theme::{Tokens, fade, mix, radius, text_size};
11
12/// Visual emphasis of a button.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14pub enum Variant {
15    #[default]
16    Primary,
17    Secondary,
18    Destructive,
19    Outline,
20    Ghost,
21    Link,
22}
23
24impl Variant {
25    pub const ALL: [Variant; 6] = [
26        Variant::Primary,
27        Variant::Secondary,
28        Variant::Destructive,
29        Variant::Outline,
30        Variant::Ghost,
31        Variant::Link,
32    ];
33}
34
35/// Button dimensions.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
37pub enum Size {
38    Sm,
39    #[default]
40    Md,
41    Lg,
42    /// Square, for icon-only buttons.
43    #[deprecated(note = "use icon_button")]
44    Icon,
45}
46
47impl Size {
48    pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
49
50    /// Height, horizontal padding, text size and icon size.
51    #[allow(deprecated)]
52    pub const fn metrics(self) -> Metrics {
53        match self {
54            Size::Sm => Metrics {
55                height: 32.0,
56                padding_x: 12.0,
57                text: text_size::SM,
58                icon: 14.0,
59            },
60            Size::Md => Metrics {
61                height: 36.0,
62                padding_x: 16.0,
63                text: text_size::SM,
64                icon: 16.0,
65            },
66            Size::Lg => Metrics {
67                height: 40.0,
68                padding_x: 24.0,
69                text: text_size::MD,
70                icon: 18.0,
71            },
72            Size::Icon => Metrics {
73                height: 36.0,
74                padding_x: 0.0,
75                text: text_size::SM,
76                icon: 16.0,
77            },
78        }
79    }
80}
81
82/// Horizontal padding inside a button. A link has none, so its text lines
83/// up with the content around it, such as a card's body above its footer.
84pub fn padding_x(size: Size, variant: Variant) -> f32 {
85    if variant == Variant::Link {
86        return 0.0;
87    }
88    size.metrics().padding_x
89}
90
91/// Resolved dimensions for a [`Size`].
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub struct Metrics {
94    pub height: f32,
95    pub padding_x: f32,
96    pub text: f32,
97    pub icon: f32,
98}
99
100/// A button builder. Convert it into an [`Element`] to render.
101///
102/// A button without a message is rendered disabled.
103///
104/// An enabled button takes part in iced's focus operations, such as a
105/// dialog's Tab order. While it has keyboard focus it draws a ring and
106/// Enter or Space presses it. A pointer press never focuses it.
107#[derive(Debug)]
108pub struct Button<'a, Message> {
109    label: Option<text::Fragment<'a>>,
110    leading: Option<Glyph>,
111    trailing: Option<Glyph>,
112    variant: Variant,
113    size: Size,
114    width: Length,
115    align_x: Alignment,
116    on_press: Option<Message>,
117}
118
119/// Creates a button with a text label.
120pub fn button<'a, Message>(label: impl text::IntoFragment<'a>) -> Button<'a, Message> {
121    Button {
122        label: Some(label.into_fragment()),
123        leading: None,
124        trailing: None,
125        variant: Variant::default(),
126        size: Size::default(),
127        width: Length::Shrink,
128        align_x: Alignment::Center,
129        on_press: None,
130    }
131}
132
133#[cfg(feature = "icon-button")]
134pub use super::icon_button::icon_button;
135
136impl<'a, Message> Button<'a, Message> {
137    pub fn variant(mut self, variant: Variant) -> Self {
138        self.variant = variant;
139        self
140    }
141
142    pub fn size(mut self, size: Size) -> Self {
143        self.size = size;
144        self
145    }
146
147    /// Adds an icon before the label.
148    pub fn icon(mut self, glyph: Glyph) -> Self {
149        self.leading = Some(glyph);
150        self
151    }
152
153    /// Adds an icon after the label.
154    pub fn trailing_icon(mut self, glyph: Glyph) -> Self {
155        self.trailing = Some(glyph);
156        self
157    }
158
159    pub fn width(mut self, width: impl Into<Length>) -> Self {
160        self.width = width.into();
161        self
162    }
163
164    /// Where the icon and label sit when the button is wider than they
165    /// are, such as a full-width button in a list. Centred by default.
166    pub fn align_x(mut self, alignment: impl Into<Alignment>) -> Self {
167        self.align_x = alignment.into();
168        self
169    }
170
171    pub fn on_press(mut self, message: Message) -> Self {
172        self.on_press = Some(message);
173        self
174    }
175
176    pub fn on_press_maybe(mut self, message: Option<Message>) -> Self {
177        self.on_press = message;
178        self
179    }
180
181    pub fn is_enabled(&self) -> bool {
182        self.on_press.is_some()
183    }
184}
185
186impl<'a, Message: Clone + 'a> From<Button<'a, Message>> for Element<'a, Message> {
187    fn from(button: Button<'a, Message>) -> Self {
188        let metrics = button.size.metrics();
189        let variant = button.variant;
190        let enabled = button.is_enabled();
191        #[cfg(feature = "icedwright")]
192        let name = button.label.clone();
193
194        let glyph = move |glyph: Glyph| -> Element<'a, Message> {
195            themed(glyph, metrics.icon, opacity(enabled), move |theme| {
196                let tokens = Tokens::of(theme);
197                if variant == Variant::Link {
198                    return tokens.foreground;
199                }
200                colours(&tokens, variant, status_for(enabled)).foreground
201            })
202            .into()
203        };
204
205        let mut content = row![].spacing(8).align_y(Alignment::Center);
206        if let Some(leading) = button.leading {
207            content = content.push(glyph(leading));
208        }
209        if let Some(label) = button.label {
210            content = content.push(
211                text(label)
212                    .size(metrics.text)
213                    .wrapping(text::Wrapping::None),
214            );
215        }
216        if let Some(trailing) = button.trailing {
217            content = content.push(glyph(trailing));
218        }
219
220        #[allow(deprecated)]
221        let (width, padding) = match button.size {
222            Size::Icon => (
223                Length::Fixed(metrics.height),
224                Padding::from((metrics.height - metrics.icon) / 2.0),
225            ),
226            _ => (
227                button.width,
228                Padding::from([0.0, padding_x(button.size, variant)]),
229            ),
230        };
231
232        let on_activate = button
233            .on_press
234            .clone()
235            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
236        let control = natural(after_touch(
237            widget::button(
238                widget::container(content)
239                    .height(Length::Fill)
240                    .align_y(Alignment::Center)
241                    .align_x(button.align_x)
242                    .width(Length::Fill),
243            )
244            .width(width)
245            .height(Length::Fixed(metrics.height))
246            .padding(padding)
247            .on_press_maybe(button.on_press)
248            .style(move |theme, status| style(&Tokens::of(theme), variant, status)),
249        ));
250        let element: Element<'a, Message> =
251            focusable(control, on_activate, Ring::around(radius::MD)).into();
252        #[cfg(feature = "icedwright")]
253        let element = {
254            use icedwright_probe::{role, semantic};
255            let mut annotated = semantic(element)
256                .role(role::Button)
257                .text_size(metrics.text)
258                .disabled(!enabled)
259                .component("iced_cube::button");
260            if let Some(name) = name {
261                annotated = annotated.name(name);
262            }
263            annotated.into()
264        };
265        element
266    }
267}
268
269fn status_for(enabled: bool) -> Status {
270    if enabled {
271        Status::Active
272    } else {
273        Status::Disabled
274    }
275}
276
277/// Background, foreground and border colours for a variant in a state.
278#[derive(Debug, Clone, Copy, PartialEq)]
279pub struct Colours {
280    pub background: Option<iced::Color>,
281    pub foreground: iced::Color,
282    pub border: Option<iced::Color>,
283}
284
285/// Resolves the colours of a variant for a given interaction state.
286pub fn colours(tokens: &Tokens, variant: Variant, status: Status) -> Colours {
287    let hover = matches!(status, Status::Hovered | Status::Pressed);
288    let pressed = status == Status::Pressed;
289    let emphasise = |base: iced::Color| {
290        let amount = if pressed { 0.2 } else { 0.1 };
291        let target = if tokens.is_dark {
292            iced::Color::BLACK
293        } else {
294            iced::Color::WHITE
295        };
296        if hover {
297            mix(base, target, amount)
298        } else {
299            base
300        }
301    };
302
303    let colours = match variant {
304        Variant::Primary => Colours {
305            background: Some(emphasise(tokens.primary)),
306            foreground: tokens.primary_foreground,
307            border: None,
308        },
309        Variant::Secondary => Colours {
310            background: Some(if hover {
311                mix(tokens.secondary, tokens.border, 0.5)
312            } else {
313                tokens.secondary
314            }),
315            foreground: tokens.secondary_foreground,
316            border: None,
317        },
318        Variant::Destructive => Colours {
319            background: Some(emphasise(tokens.destructive)),
320            foreground: tokens.destructive_foreground,
321            border: None,
322        },
323        // Transparent at rest, so it takes the colour of whatever surface
324        // it sits on, such as a dialog or popover.
325        Variant::Outline => Colours {
326            background: hover.then_some(tokens.accent),
327            foreground: tokens.foreground,
328            border: Some(tokens.border),
329        },
330        Variant::Ghost => Colours {
331            background: hover.then_some(tokens.accent),
332            foreground: tokens.foreground,
333            border: None,
334        },
335        Variant::Link => Colours {
336            background: None,
337            foreground: if hover {
338                mix(tokens.primary, tokens.foreground, 0.3)
339            } else {
340                tokens.primary
341            },
342            border: None,
343        },
344    };
345
346    if status != Status::Disabled {
347        return colours;
348    }
349    Colours {
350        background: colours.background.map(|c| fade(c, 0.5)),
351        foreground: fade(colours.foreground, 0.5),
352        border: colours.border.map(|c| fade(c, 0.5)),
353    }
354}
355
356/// The iced button style for a variant in a state.
357pub fn style(tokens: &Tokens, variant: Variant, status: Status) -> widget::button::Style {
358    let colours = colours(tokens, variant, status);
359    widget::button::Style {
360        background: colours.background.map(Background::Color),
361        text_color: colours.foreground,
362        border: Border {
363            color: colours.border.unwrap_or(iced::Color::TRANSPARENT),
364            width: if colours.border.is_some() { 1.0 } else { 0.0 },
365            radius: radius::MD.into(),
366        },
367        shadow: Shadow::default(),
368        snap: true,
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375    use crate::theme::{dark, light};
376
377    const STATES: [Status; 4] = [
378        Status::Active,
379        Status::Hovered,
380        Status::Pressed,
381        Status::Disabled,
382    ];
383
384    #[test]
385    fn default_builder_is_primary_medium_and_disabled() {
386        let b: Button<'_, ()> = button("Save");
387        assert_eq!(b.variant, Variant::Primary);
388        assert_eq!(b.size, Size::Md);
389        assert_eq!(b.align_x, Alignment::Center);
390        assert!(!b.is_enabled());
391    }
392
393    #[test]
394    fn align_x_is_kept() {
395        let b: Button<'_, ()> = button("General").align_x(Alignment::Start);
396        assert_eq!(b.align_x, Alignment::Start);
397        let b: Button<'_, ()> = button("General").align_x(iced::alignment::Horizontal::Right);
398        assert_eq!(b.align_x, Alignment::End);
399    }
400
401    #[test]
402    fn links_have_no_side_padding_and_the_rest_keep_their_size() {
403        for size in Size::ALL {
404            assert_eq!(padding_x(size, Variant::Link), 0.0);
405            for variant in Variant::ALL.into_iter().filter(|v| *v != Variant::Link) {
406                assert_eq!(padding_x(size, variant), size.metrics().padding_x);
407            }
408        }
409    }
410
411    #[test]
412    fn on_press_enables_and_on_press_maybe_none_disables() {
413        assert!(button::<u8>("Go").on_press(1).is_enabled());
414        assert!(
415            !button::<u8>("Go")
416                .on_press(1)
417                .on_press_maybe(None)
418                .is_enabled()
419        );
420    }
421
422    #[test]
423    fn sizes_grow_monotonically() {
424        let heights = [Size::Sm, Size::Md, Size::Lg].map(|s| s.metrics().height);
425        assert!(heights.windows(2).all(|w| w[0] < w[1]));
426    }
427
428    #[test]
429    fn hover_changes_background_for_filled_variants() {
430        let tokens = Tokens::of(&light());
431        for variant in [
432            Variant::Primary,
433            Variant::Secondary,
434            Variant::Destructive,
435            Variant::Outline,
436            Variant::Ghost,
437        ] {
438            let active = colours(&tokens, variant, Status::Active);
439            let hovered = colours(&tokens, variant, Status::Hovered);
440            assert_ne!(active.background, hovered.background, "{variant:?}");
441        }
442    }
443
444    #[test]
445    fn pressed_is_stronger_than_hovered_for_primary() {
446        let tokens = Tokens::of(&light());
447        let hovered = colours(&tokens, Variant::Primary, Status::Hovered);
448        let pressed = colours(&tokens, Variant::Primary, Status::Pressed);
449        assert_ne!(hovered.background, pressed.background);
450    }
451
452    #[test]
453    fn disabled_halves_alpha_for_every_variant() {
454        for theme in [light(), dark()] {
455            let tokens = Tokens::of(&theme);
456            for variant in Variant::ALL {
457                let active = colours(&tokens, variant, Status::Active);
458                let disabled = colours(&tokens, variant, Status::Disabled);
459                assert!((disabled.foreground.a - active.foreground.a * 0.5).abs() < 1e-6);
460            }
461        }
462    }
463
464    #[test]
465    fn only_outline_has_a_border() {
466        let tokens = Tokens::of(&dark());
467        for variant in Variant::ALL {
468            for status in STATES {
469                let style = style(&tokens, variant, status);
470                assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
471            }
472        }
473    }
474
475    #[test]
476    fn outline_ghost_and_link_are_transparent_at_rest() {
477        for theme in [light(), dark()] {
478            let tokens = Tokens::of(&theme);
479            for variant in [Variant::Outline, Variant::Ghost, Variant::Link] {
480                for status in [Status::Active, Status::Disabled] {
481                    let background = colours(&tokens, variant, status).background;
482                    assert!(background.is_none(), "{variant:?} {status:?}");
483                }
484            }
485        }
486    }
487}