Skip to main content

iced_cube/layout/
card.rs

1//! Raised surfaces that group related content.
2
3use iced::widget::{column, container, text};
4use iced::{Background, Border, Color, Element, Length, Shadow, Vector};
5
6use crate::theme::{Tokens, fade, heading, mix, space, supporting, text_size};
7
8/// Headings break inside a word only when the word alone is wider than the
9/// card, so they never run past the border.
10const HEADER_WRAPPING: text::Wrapping = text::Wrapping::WordOrGlyph;
11
12/// A card builder. Convert it into an [`Element`] to render.
13pub struct Card<'a, Message> {
14    title: Option<text::Fragment<'a>>,
15    description: Option<text::Fragment<'a>>,
16    body: Option<Element<'a, Message>>,
17    footer: Option<Element<'a, Message>>,
18    width: Length,
19}
20
21impl<Message> std::fmt::Debug for Card<'_, Message> {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        f.debug_struct("Card")
24            .field("title", &self.title)
25            .field("description", &self.description)
26            .field("body", &self.body.is_some())
27            .field("footer", &self.footer.is_some())
28            .field("width", &self.width)
29            .finish()
30    }
31}
32
33/// Creates an empty card. Add a header, body and footer with the builder.
34pub fn card<'a, Message>() -> Card<'a, Message> {
35    Card {
36        title: None,
37        description: None,
38        body: None,
39        footer: None,
40        width: Length::Shrink,
41    }
42}
43
44impl<'a, Message> Card<'a, Message> {
45    /// Sets the heading.
46    pub fn title(mut self, title: impl text::IntoFragment<'a>) -> Self {
47        self.title = Some(title.into_fragment());
48        self
49    }
50
51    /// Sets the muted line under the heading.
52    pub fn description(mut self, description: impl text::IntoFragment<'a>) -> Self {
53        self.description = Some(description.into_fragment());
54        self
55    }
56
57    /// Sets the main content.
58    pub fn body(mut self, body: impl Into<Element<'a, Message>>) -> Self {
59        self.body = Some(body.into());
60        self
61    }
62
63    /// Sets the content under the body, usually a row of buttons.
64    pub fn footer(mut self, footer: impl Into<Element<'a, Message>>) -> Self {
65        self.footer = Some(footer.into());
66        self
67    }
68
69    pub fn width(mut self, width: impl Into<Length>) -> Self {
70        self.width = width.into();
71        self
72    }
73
74    /// Whether the card has a title or description.
75    pub fn has_header(&self) -> bool {
76        self.title.is_some() || self.description.is_some()
77    }
78}
79
80impl<'a, Message: 'a> From<Card<'a, Message>> for Element<'a, Message> {
81    fn from(card: Card<'a, Message>) -> Self {
82        let has_header = card.has_header();
83        #[cfg(feature = "icedwright")]
84        let (name, about) = (card.title.clone(), card.description.clone());
85        let mut sections = column![].spacing(space::LG).width(Length::Fill);
86
87        if has_header {
88            let mut header = column![].spacing(space::XS);
89            if let Some(title) = card.title {
90                header = header.push(heading(title, text_size::LG).wrapping(HEADER_WRAPPING));
91            }
92            if let Some(description) = card.description {
93                header = header.push(supporting(description).wrapping(HEADER_WRAPPING));
94            }
95            sections = sections.push(header);
96        }
97        if let Some(body) = card.body {
98            sections = sections.push(body);
99        }
100        if let Some(footer) = card.footer {
101            sections = sections.push(footer);
102        }
103
104        // Content wider than the card is cut at the border, not drawn over it.
105        let element: Element<'a, Message> = container(sections)
106            .padding(space::XL)
107            .width(card.width)
108            .clip(true)
109            .style(|theme| style(&Tokens::of(theme)))
110            .into();
111        #[cfg(feature = "icedwright")]
112        let element = {
113            let mut annotated = icedwright_probe::semantic(element)
114                .role(icedwright_probe::role::Region)
115                .component("iced_cube::card");
116            if let Some(name) = name {
117                annotated = annotated.name(name);
118            }
119            if let Some(about) = about {
120                annotated = annotated.description(about);
121            }
122            annotated.into()
123        };
124        element
125    }
126}
127
128/// Colours of a card's surface.
129#[derive(Debug, Clone, Copy, PartialEq)]
130pub struct Colours {
131    pub background: Color,
132    pub border: Color,
133    pub shadow: Color,
134}
135
136/// Resolves the card colours. In dark themes the surface is lifted slightly
137/// above the page background.
138pub fn colours(tokens: &Tokens) -> Colours {
139    if tokens.is_dark {
140        let background = mix(tokens.background, tokens.foreground, 0.055);
141        return Colours {
142            background,
143            border: mix(background, tokens.border, 0.65),
144            shadow: fade(tokens.background, 0.5),
145        };
146    }
147    Colours {
148        background: tokens.background,
149        border: mix(tokens.background, tokens.border, 0.65),
150        shadow: fade(tokens.foreground, 0.08),
151    }
152}
153
154/// The container style for a card.
155pub fn style(tokens: &Tokens) -> container::Style {
156    let colours = colours(tokens);
157    container::Style {
158        text_color: Some(tokens.foreground),
159        background: Some(Background::Color(colours.background)),
160        border: Border {
161            color: colours.border,
162            width: 1.0,
163            radius: 12.0.into(),
164        },
165        shadow: Shadow {
166            color: colours.shadow,
167            offset: Vector::new(0.0, 4.0),
168            blur_radius: 16.0,
169        },
170        snap: true,
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use crate::theme::{Config, dark, light};
178
179    fn luminance(color: Color) -> f32 {
180        0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b
181    }
182
183    #[test]
184    fn default_builder_is_empty_and_shrinks() {
185        let c: Card<'_, ()> = card();
186        assert!(!c.has_header());
187        assert!(c.body.is_none());
188        assert!(c.footer.is_none());
189        assert_eq!(c.width, Length::Shrink);
190    }
191
192    #[test]
193    fn title_or_description_makes_a_header() {
194        assert!(card::<()>().title("Team").has_header());
195        assert!(card::<()>().description("Members").has_header());
196    }
197
198    #[test]
199    fn dark_surface_is_lighter_than_background() {
200        let tokens = Tokens::of(&dark());
201        let colours = colours(&tokens);
202        assert!(luminance(colours.background) > luminance(tokens.background));
203    }
204
205    #[test]
206    fn dark_cards_stay_between_the_page_and_floating_surfaces() {
207        for theme in [
208            dark(),
209            Config::dark()
210                .background(iced::color!(0x18202b))
211                .foreground(iced::color!(0xe3e9f3))
212                .build(),
213        ] {
214            let tokens = Tokens::of(&theme);
215            let card = colours(&tokens);
216            assert!(luminance(card.background) > luminance(tokens.background));
217            assert!(luminance(card.background) < luminance(tokens.popover));
218            assert!(luminance(card.shadow) < luminance(card.background));
219            assert!(card.shadow.a > 0.0);
220        }
221    }
222
223    #[test]
224    fn light_surface_matches_background_and_casts_a_shadow() {
225        let tokens = Tokens::of(&light());
226        let colours = colours(&tokens);
227        assert_eq!(colours.background, tokens.background);
228        assert!(colours.shadow.a > 0.0);
229    }
230
231    #[test]
232    fn border_is_subtle_but_visible() {
233        for theme in [light(), dark()] {
234            let tokens = Tokens::of(&theme);
235            let colours = colours(&tokens);
236            assert_ne!(colours.border, colours.background);
237            let contrast = (luminance(colours.border) - luminance(colours.background)).abs();
238            assert!(contrast < 0.2, "{contrast}");
239            assert_eq!(style(&tokens).border.width, 1.0);
240        }
241    }
242}