Skip to main content

iced_cube/primitives/
fab.rs

1//! A floating action button: the one main action of a screen, drawn raised
2//! above the content.
3//!
4//! A fab does not position itself. Place it over the content with an iced
5//! `stack` and a container aligned to a corner:
6//!
7//! ```no_run
8//! use iced::widget::{container, stack, text};
9//! use iced::Length;
10//! use iced_cube::{fab, lucide};
11//!
12//! #[derive(Debug, Clone)]
13//! enum Message { New }
14//!
15//! let screen: iced::Element<'_, Message> = stack![
16//!     text("The list"),
17//!     container(fab(lucide!(Plus)).label("New note").on_press(Message::New))
18//!         .width(Length::Fill)
19//!         .height(Length::Fill)
20//!         .align_right(Length::Fill)
21//!         .align_bottom(Length::Fill)
22//!         .padding(16),
23//! ]
24//! .into();
25//! ```
26
27use iced::widget::{self, button::Status, container, row, text};
28use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Shadow, Vector};
29
30use crate::after_touch::after_touch;
31use crate::icon::{Glyph, opacity, themed};
32use crate::natural::natural;
33use crate::overlay::tooltip::{Position, tooltip};
34use crate::primitives::button::{self, Variant};
35use crate::theme::{Tokens, fade, text_size};
36
37/// Height of a fab, and the side of an icon-only one.
38pub const SIZE: f32 = 56.0;
39/// Corner radius.
40pub const RADIUS: f32 = 16.0;
41/// Icon size.
42pub const ICON: f32 = 24.0;
43/// Horizontal padding of an extended fab.
44pub const PADDING_X: f32 = 16.0;
45
46/// A fab builder. Convert it into an [`Element`] to render.
47///
48/// A fab without a message is rendered disabled.
49#[derive(Debug)]
50pub struct Fab<'a, Message> {
51    glyph: Glyph,
52    label: Option<text::Fragment<'a>>,
53    tooltip: Option<text::Fragment<'a>>,
54    id: Option<widget::Id>,
55    on_press: Option<Message>,
56}
57
58/// Creates a square fab showing `glyph`.
59pub fn fab<'a, Message>(glyph: Glyph) -> Fab<'a, Message> {
60    Fab {
61        glyph,
62        label: None,
63        tooltip: None,
64        id: None,
65        on_press: None,
66    }
67}
68
69impl<'a, Message> Fab<'a, Message> {
70    /// Shows a label beside the icon, making the fab an extended pill.
71    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
72        self.label = Some(label.into_fragment());
73        self
74    }
75
76    /// Names the action of an icon-only fab, such as "New note", shown as a
77    /// tooltip on hover. An extended fab already shows its label and
78    /// ignores this.
79    pub fn tooltip(mut self, tooltip: impl text::IntoFragment<'a>) -> Self {
80        self.tooltip = Some(tooltip.into_fragment());
81        self
82    }
83
84    /// Sets a widget id, for finding the fab in tests.
85    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
86        self.id = Some(id.into());
87        self
88    }
89
90    pub fn on_press(mut self, message: Message) -> Self {
91        self.on_press = Some(message);
92        self
93    }
94
95    pub fn on_press_maybe(mut self, message: Option<Message>) -> Self {
96        self.on_press = message;
97        self
98    }
99
100    pub fn is_enabled(&self) -> bool {
101        self.on_press.is_some()
102    }
103
104    pub fn is_extended(&self) -> bool {
105        self.label.is_some()
106    }
107}
108
109impl<'a, Message: Clone + 'a> From<Fab<'a, Message>> for Element<'a, Message> {
110    fn from(fab: Fab<'a, Message>) -> Self {
111        let Fab {
112            glyph,
113            label,
114            tooltip: hint,
115            id,
116            on_press,
117        } = fab;
118        let enabled = on_press.is_some();
119        let resting = if enabled {
120            Status::Active
121        } else {
122            Status::Disabled
123        };
124        let icon = themed(glyph, ICON, opacity(enabled), move |theme| {
125            style(&Tokens::of(theme), resting).text_color
126        });
127
128        let extended = label.is_some();
129        #[cfg(feature = "icedwright")]
130        let name = label.clone();
131        let content: Element<'a, Message> = match label {
132            Some(label) => row![
133                icon,
134                text(label)
135                    .size(text_size::SM)
136                    .font(crate::theme::semibold())
137                    .wrapping(text::Wrapping::None)
138            ]
139            .spacing(12)
140            .align_y(Alignment::Center)
141            .into(),
142            None => icon.into(),
143        };
144
145        let (width, padding) = if extended {
146            (Length::Shrink, Padding::from([0.0, PADDING_X]))
147        } else {
148            (Length::Fixed(SIZE), Padding::from((SIZE - ICON) / 2.0))
149        };
150
151        let button = widget::button(
152            container(content)
153                .height(Length::Fill)
154                .align_y(Alignment::Center)
155                .align_x(Alignment::Center),
156        )
157        .width(width)
158        .height(Length::Fixed(SIZE))
159        .padding(padding)
160        .on_press_maybe(on_press)
161        .style(|theme, status| style(&Tokens::of(theme), status));
162
163        let mut element: Element<'a, Message> = match id {
164            Some(id) => container(after_touch(button)).id(id).into(),
165            None => after_touch(button),
166        };
167        #[cfg(feature = "icedwright")]
168        {
169            use icedwright_probe::{role, semantic};
170            let mut annotated = semantic(element)
171                .role(role::Button)
172                .component("iced_cube::fab");
173            if !enabled {
174                annotated = annotated.disabled(true);
175            }
176            match (&name, &hint) {
177                (Some(name), _) => annotated = annotated.name(name.clone()),
178                (None, Some(hint)) => {
179                    annotated = annotated.name(hint.clone()).tooltip(hint.clone());
180                }
181                (None, None) => {}
182            }
183            element = annotated.into();
184        }
185        if let (Some(hint), false) = (hint, extended) {
186            element = tooltip(element, hint).position(Position::Left).into();
187        }
188        natural(element)
189    }
190}
191
192/// The shadow under a fab, deeper while hovered and shallower while
193/// pressed, as if it moved towards the finger.
194pub fn shadow(tokens: &Tokens, status: Status) -> Shadow {
195    let alpha = if tokens.is_dark { 0.5 } else { 0.18 };
196    let (offset, blur) = match status {
197        Status::Hovered => (6.0, 16.0),
198        Status::Pressed => (2.0, 6.0),
199        Status::Active | Status::Disabled => (4.0, 12.0),
200    };
201    Shadow {
202        color: fade(Color::BLACK, alpha),
203        offset: Vector::new(0.0, offset),
204        blur_radius: blur,
205    }
206}
207
208/// The iced button style of a fab: primary colours, a large radius and a
209/// soft shadow. A disabled fab is faded and flat.
210pub fn style(tokens: &Tokens, status: Status) -> widget::button::Style {
211    let colours = button::colours(tokens, Variant::Primary, status);
212    widget::button::Style {
213        background: colours.background.map(Background::Color),
214        text_color: colours.foreground,
215        border: Border {
216            color: Color::TRANSPARENT,
217            width: 0.0,
218            radius: RADIUS.into(),
219        },
220        shadow: if status == Status::Disabled {
221            Shadow::default()
222        } else {
223            shadow(tokens, status)
224        },
225        snap: true,
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::theme::{dark, light};
233
234    const STATES: [Status; 4] = [
235        Status::Active,
236        Status::Hovered,
237        Status::Pressed,
238        Status::Disabled,
239    ];
240
241    #[test]
242    fn builder_defaults() {
243        let f: Fab<'_, u8> = fab(crate::lucide!(Plus));
244        assert!(!f.is_enabled());
245        assert!(!f.is_extended());
246        assert!(fab::<u8>(crate::lucide!(Plus)).label("New").is_extended());
247        assert!(fab::<u8>(crate::lucide!(Plus)).on_press(1).is_enabled());
248        assert!(
249            !fab::<u8>(crate::lucide!(Plus))
250                .on_press(1)
251                .on_press_maybe(None)
252                .is_enabled()
253        );
254    }
255
256    #[test]
257    fn colours_are_the_primary_button_in_every_state() {
258        for theme in [light(), dark()] {
259            let tokens = Tokens::of(&theme);
260            for status in STATES {
261                let style = style(&tokens, status);
262                let primary = button::colours(&tokens, Variant::Primary, status);
263                assert_eq!(style.background, primary.background.map(Background::Color));
264                assert_eq!(style.text_color, primary.foreground);
265                assert_eq!(style.border.radius, RADIUS.into());
266            }
267        }
268    }
269
270    #[test]
271    fn hovered_and_pressed_differ_from_rest() {
272        let tokens = Tokens::of(&light());
273        let rest = style(&tokens, Status::Active);
274        let hovered = style(&tokens, Status::Hovered);
275        let pressed = style(&tokens, Status::Pressed);
276        assert_ne!(rest.background, hovered.background);
277        assert_ne!(hovered.background, pressed.background);
278        assert!(hovered.shadow.blur_radius > rest.shadow.blur_radius);
279        assert!(pressed.shadow.blur_radius < rest.shadow.blur_radius);
280    }
281
282    #[test]
283    fn only_a_disabled_fab_is_flat_and_dark_shadows_are_stronger() {
284        let light = Tokens::of(&light());
285        let dark = Tokens::of(&dark());
286        assert_eq!(style(&light, Status::Disabled).shadow, Shadow::default());
287        assert!(style(&light, Status::Active).shadow.color.a > 0.0);
288        assert!(
289            style(&dark, Status::Active).shadow.color.a
290                > style(&light, Status::Active).shadow.color.a
291        );
292    }
293}