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
192        let glyph = move |glyph: Glyph| -> Element<'a, Message> {
193            themed(glyph, metrics.icon, opacity(enabled), move |theme| {
194                let tokens = Tokens::of(theme);
195                if variant == Variant::Link {
196                    return tokens.foreground;
197                }
198                colours(&tokens, variant, status_for(enabled)).foreground
199            })
200            .into()
201        };
202
203        let mut content = row![].spacing(8).align_y(Alignment::Center);
204        if let Some(leading) = button.leading {
205            content = content.push(glyph(leading));
206        }
207        if let Some(label) = button.label {
208            content = content.push(
209                text(label)
210                    .size(metrics.text)
211                    .wrapping(text::Wrapping::None),
212            );
213        }
214        if let Some(trailing) = button.trailing {
215            content = content.push(glyph(trailing));
216        }
217
218        #[allow(deprecated)]
219        let (width, padding) = match button.size {
220            Size::Icon => (
221                Length::Fixed(metrics.height),
222                Padding::from((metrics.height - metrics.icon) / 2.0),
223            ),
224            _ => (
225                button.width,
226                Padding::from([0.0, padding_x(button.size, variant)]),
227            ),
228        };
229
230        let on_activate = button
231            .on_press
232            .clone()
233            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
234        let control = natural(after_touch(
235            widget::button(
236                widget::container(content)
237                    .height(Length::Fill)
238                    .align_y(Alignment::Center)
239                    .align_x(button.align_x)
240                    .width(Length::Fill),
241            )
242            .width(width)
243            .height(Length::Fixed(metrics.height))
244            .padding(padding)
245            .on_press_maybe(button.on_press)
246            .style(move |theme, status| style(&Tokens::of(theme), variant, status)),
247        ));
248        focusable(control, on_activate, Ring::around(radius::MD)).into()
249    }
250}
251
252fn status_for(enabled: bool) -> Status {
253    if enabled {
254        Status::Active
255    } else {
256        Status::Disabled
257    }
258}
259
260/// Background, foreground and border colours for a variant in a state.
261#[derive(Debug, Clone, Copy, PartialEq)]
262pub struct Colours {
263    pub background: Option<iced::Color>,
264    pub foreground: iced::Color,
265    pub border: Option<iced::Color>,
266}
267
268/// Resolves the colours of a variant for a given interaction state.
269pub fn colours(tokens: &Tokens, variant: Variant, status: Status) -> Colours {
270    let hover = matches!(status, Status::Hovered | Status::Pressed);
271    let pressed = status == Status::Pressed;
272    let emphasise = |base: iced::Color| {
273        let amount = if pressed { 0.2 } else { 0.1 };
274        let target = if tokens.is_dark {
275            iced::Color::BLACK
276        } else {
277            iced::Color::WHITE
278        };
279        if hover {
280            mix(base, target, amount)
281        } else {
282            base
283        }
284    };
285
286    let colours = match variant {
287        Variant::Primary => Colours {
288            background: Some(emphasise(tokens.primary)),
289            foreground: tokens.primary_foreground,
290            border: None,
291        },
292        Variant::Secondary => Colours {
293            background: Some(if hover {
294                mix(tokens.secondary, tokens.border, 0.5)
295            } else {
296                tokens.secondary
297            }),
298            foreground: tokens.secondary_foreground,
299            border: None,
300        },
301        Variant::Destructive => Colours {
302            background: Some(emphasise(tokens.destructive)),
303            foreground: tokens.destructive_foreground,
304            border: None,
305        },
306        // Transparent at rest, so it takes the colour of whatever surface
307        // it sits on, such as a dialog or popover.
308        Variant::Outline => Colours {
309            background: hover.then_some(tokens.accent),
310            foreground: tokens.foreground,
311            border: Some(tokens.border),
312        },
313        Variant::Ghost => Colours {
314            background: hover.then_some(tokens.accent),
315            foreground: tokens.foreground,
316            border: None,
317        },
318        Variant::Link => Colours {
319            background: None,
320            foreground: if hover {
321                mix(tokens.primary, tokens.foreground, 0.3)
322            } else {
323                tokens.primary
324            },
325            border: None,
326        },
327    };
328
329    if status != Status::Disabled {
330        return colours;
331    }
332    Colours {
333        background: colours.background.map(|c| fade(c, 0.5)),
334        foreground: fade(colours.foreground, 0.5),
335        border: colours.border.map(|c| fade(c, 0.5)),
336    }
337}
338
339/// The iced button style for a variant in a state.
340pub fn style(tokens: &Tokens, variant: Variant, status: Status) -> widget::button::Style {
341    let colours = colours(tokens, variant, status);
342    widget::button::Style {
343        background: colours.background.map(Background::Color),
344        text_color: colours.foreground,
345        border: Border {
346            color: colours.border.unwrap_or(iced::Color::TRANSPARENT),
347            width: if colours.border.is_some() { 1.0 } else { 0.0 },
348            radius: radius::MD.into(),
349        },
350        shadow: Shadow::default(),
351        snap: true,
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use crate::theme::{dark, light};
359
360    const STATES: [Status; 4] = [
361        Status::Active,
362        Status::Hovered,
363        Status::Pressed,
364        Status::Disabled,
365    ];
366
367    #[test]
368    fn default_builder_is_primary_medium_and_disabled() {
369        let b: Button<'_, ()> = button("Save");
370        assert_eq!(b.variant, Variant::Primary);
371        assert_eq!(b.size, Size::Md);
372        assert_eq!(b.align_x, Alignment::Center);
373        assert!(!b.is_enabled());
374    }
375
376    #[test]
377    fn align_x_is_kept() {
378        let b: Button<'_, ()> = button("General").align_x(Alignment::Start);
379        assert_eq!(b.align_x, Alignment::Start);
380        let b: Button<'_, ()> = button("General").align_x(iced::alignment::Horizontal::Right);
381        assert_eq!(b.align_x, Alignment::End);
382    }
383
384    #[test]
385    fn links_have_no_side_padding_and_the_rest_keep_their_size() {
386        for size in Size::ALL {
387            assert_eq!(padding_x(size, Variant::Link), 0.0);
388            for variant in Variant::ALL.into_iter().filter(|v| *v != Variant::Link) {
389                assert_eq!(padding_x(size, variant), size.metrics().padding_x);
390            }
391        }
392    }
393
394    #[test]
395    fn on_press_enables_and_on_press_maybe_none_disables() {
396        assert!(button::<u8>("Go").on_press(1).is_enabled());
397        assert!(
398            !button::<u8>("Go")
399                .on_press(1)
400                .on_press_maybe(None)
401                .is_enabled()
402        );
403    }
404
405    #[test]
406    fn sizes_grow_monotonically() {
407        let heights = [Size::Sm, Size::Md, Size::Lg].map(|s| s.metrics().height);
408        assert!(heights.windows(2).all(|w| w[0] < w[1]));
409    }
410
411    #[test]
412    fn hover_changes_background_for_filled_variants() {
413        let tokens = Tokens::of(&light());
414        for variant in [
415            Variant::Primary,
416            Variant::Secondary,
417            Variant::Destructive,
418            Variant::Outline,
419            Variant::Ghost,
420        ] {
421            let active = colours(&tokens, variant, Status::Active);
422            let hovered = colours(&tokens, variant, Status::Hovered);
423            assert_ne!(active.background, hovered.background, "{variant:?}");
424        }
425    }
426
427    #[test]
428    fn pressed_is_stronger_than_hovered_for_primary() {
429        let tokens = Tokens::of(&light());
430        let hovered = colours(&tokens, Variant::Primary, Status::Hovered);
431        let pressed = colours(&tokens, Variant::Primary, Status::Pressed);
432        assert_ne!(hovered.background, pressed.background);
433    }
434
435    #[test]
436    fn disabled_halves_alpha_for_every_variant() {
437        for theme in [light(), dark()] {
438            let tokens = Tokens::of(&theme);
439            for variant in Variant::ALL {
440                let active = colours(&tokens, variant, Status::Active);
441                let disabled = colours(&tokens, variant, Status::Disabled);
442                assert!((disabled.foreground.a - active.foreground.a * 0.5).abs() < 1e-6);
443            }
444        }
445    }
446
447    #[test]
448    fn only_outline_has_a_border() {
449        let tokens = Tokens::of(&dark());
450        for variant in Variant::ALL {
451            for status in STATES {
452                let style = style(&tokens, variant, status);
453                assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
454            }
455        }
456    }
457
458    #[test]
459    fn outline_ghost_and_link_are_transparent_at_rest() {
460        for theme in [light(), dark()] {
461            let tokens = Tokens::of(&theme);
462            for variant in [Variant::Outline, Variant::Ghost, Variant::Link] {
463                for status in [Status::Active, Status::Disabled] {
464                    let background = colours(&tokens, variant, status).background;
465                    assert!(background.is_none(), "{variant:?} {status:?}");
466                }
467            }
468        }
469    }
470}