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                .component("iced_cube::button");
259            if !enabled {
260                annotated = annotated.disabled(true);
261            }
262            if let Some(name) = name {
263                annotated = annotated.name(name);
264            }
265            annotated.into()
266        };
267        element
268    }
269}
270
271fn status_for(enabled: bool) -> Status {
272    if enabled {
273        Status::Active
274    } else {
275        Status::Disabled
276    }
277}
278
279/// Background, foreground and border colours for a variant in a state.
280#[derive(Debug, Clone, Copy, PartialEq)]
281pub struct Colours {
282    pub background: Option<iced::Color>,
283    pub foreground: iced::Color,
284    pub border: Option<iced::Color>,
285}
286
287/// Resolves the colours of a variant for a given interaction state.
288pub fn colours(tokens: &Tokens, variant: Variant, status: Status) -> Colours {
289    let hover = matches!(status, Status::Hovered | Status::Pressed);
290    let pressed = status == Status::Pressed;
291    let emphasise = |base: iced::Color| {
292        let amount = if pressed { 0.2 } else { 0.1 };
293        let target = if tokens.is_dark {
294            iced::Color::BLACK
295        } else {
296            iced::Color::WHITE
297        };
298        if hover {
299            mix(base, target, amount)
300        } else {
301            base
302        }
303    };
304
305    let colours = match variant {
306        Variant::Primary => Colours {
307            background: Some(emphasise(tokens.primary)),
308            foreground: tokens.primary_foreground,
309            border: None,
310        },
311        Variant::Secondary => Colours {
312            background: Some(if hover {
313                mix(tokens.secondary, tokens.border, 0.5)
314            } else {
315                tokens.secondary
316            }),
317            foreground: tokens.secondary_foreground,
318            border: None,
319        },
320        Variant::Destructive => Colours {
321            background: Some(emphasise(tokens.destructive)),
322            foreground: tokens.destructive_foreground,
323            border: None,
324        },
325        // Transparent at rest, so it takes the colour of whatever surface
326        // it sits on, such as a dialog or popover.
327        Variant::Outline => Colours {
328            background: hover.then_some(tokens.accent),
329            foreground: tokens.foreground,
330            border: Some(tokens.border),
331        },
332        Variant::Ghost => Colours {
333            background: hover.then_some(tokens.accent),
334            foreground: tokens.foreground,
335            border: None,
336        },
337        Variant::Link => Colours {
338            background: None,
339            foreground: if hover {
340                mix(tokens.primary, tokens.foreground, 0.3)
341            } else {
342                tokens.primary
343            },
344            border: None,
345        },
346    };
347
348    if status != Status::Disabled {
349        return colours;
350    }
351    Colours {
352        background: colours.background.map(|c| fade(c, 0.5)),
353        foreground: fade(colours.foreground, 0.5),
354        border: colours.border.map(|c| fade(c, 0.5)),
355    }
356}
357
358/// The iced button style for a variant in a state.
359pub fn style(tokens: &Tokens, variant: Variant, status: Status) -> widget::button::Style {
360    let colours = colours(tokens, variant, status);
361    widget::button::Style {
362        background: colours.background.map(Background::Color),
363        text_color: colours.foreground,
364        border: Border {
365            color: colours.border.unwrap_or(iced::Color::TRANSPARENT),
366            width: if colours.border.is_some() { 1.0 } else { 0.0 },
367            radius: radius::MD.into(),
368        },
369        shadow: Shadow::default(),
370        snap: true,
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::theme::{dark, light};
378
379    const STATES: [Status; 4] = [
380        Status::Active,
381        Status::Hovered,
382        Status::Pressed,
383        Status::Disabled,
384    ];
385
386    #[test]
387    fn default_builder_is_primary_medium_and_disabled() {
388        let b: Button<'_, ()> = button("Save");
389        assert_eq!(b.variant, Variant::Primary);
390        assert_eq!(b.size, Size::Md);
391        assert_eq!(b.align_x, Alignment::Center);
392        assert!(!b.is_enabled());
393    }
394
395    #[test]
396    fn align_x_is_kept() {
397        let b: Button<'_, ()> = button("General").align_x(Alignment::Start);
398        assert_eq!(b.align_x, Alignment::Start);
399        let b: Button<'_, ()> = button("General").align_x(iced::alignment::Horizontal::Right);
400        assert_eq!(b.align_x, Alignment::End);
401    }
402
403    #[test]
404    fn links_have_no_side_padding_and_the_rest_keep_their_size() {
405        for size in Size::ALL {
406            assert_eq!(padding_x(size, Variant::Link), 0.0);
407            for variant in Variant::ALL.into_iter().filter(|v| *v != Variant::Link) {
408                assert_eq!(padding_x(size, variant), size.metrics().padding_x);
409            }
410        }
411    }
412
413    #[test]
414    fn on_press_enables_and_on_press_maybe_none_disables() {
415        assert!(button::<u8>("Go").on_press(1).is_enabled());
416        assert!(
417            !button::<u8>("Go")
418                .on_press(1)
419                .on_press_maybe(None)
420                .is_enabled()
421        );
422    }
423
424    #[test]
425    fn sizes_grow_monotonically() {
426        let heights = [Size::Sm, Size::Md, Size::Lg].map(|s| s.metrics().height);
427        assert!(heights.windows(2).all(|w| w[0] < w[1]));
428    }
429
430    #[test]
431    fn hover_changes_background_for_filled_variants() {
432        let tokens = Tokens::of(&light());
433        for variant in [
434            Variant::Primary,
435            Variant::Secondary,
436            Variant::Destructive,
437            Variant::Outline,
438            Variant::Ghost,
439        ] {
440            let active = colours(&tokens, variant, Status::Active);
441            let hovered = colours(&tokens, variant, Status::Hovered);
442            assert_ne!(active.background, hovered.background, "{variant:?}");
443        }
444    }
445
446    #[test]
447    fn pressed_is_stronger_than_hovered_for_primary() {
448        let tokens = Tokens::of(&light());
449        let hovered = colours(&tokens, Variant::Primary, Status::Hovered);
450        let pressed = colours(&tokens, Variant::Primary, Status::Pressed);
451        assert_ne!(hovered.background, pressed.background);
452    }
453
454    #[test]
455    fn disabled_halves_alpha_for_every_variant() {
456        for theme in [light(), dark()] {
457            let tokens = Tokens::of(&theme);
458            for variant in Variant::ALL {
459                let active = colours(&tokens, variant, Status::Active);
460                let disabled = colours(&tokens, variant, Status::Disabled);
461                assert!((disabled.foreground.a - active.foreground.a * 0.5).abs() < 1e-6);
462            }
463        }
464    }
465
466    #[test]
467    fn only_outline_has_a_border() {
468        let tokens = Tokens::of(&dark());
469        for variant in Variant::ALL {
470            for status in STATES {
471                let style = style(&tokens, variant, status);
472                assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
473            }
474        }
475    }
476
477    #[test]
478    fn outline_ghost_and_link_are_transparent_at_rest() {
479        for theme in [light(), dark()] {
480            let tokens = Tokens::of(&theme);
481            for variant in [Variant::Outline, Variant::Ghost, Variant::Link] {
482                for status in [Status::Active, Status::Disabled] {
483                    let background = colours(&tokens, variant, status).background;
484                    assert!(background.is_none(), "{variant:?} {status:?}");
485                }
486            }
487        }
488    }
489}