Skip to main content

iced_cube/feedback/
chip.rs

1//! Compact pills for chosen values, such as guests or tags, with an
2//! optional x button that removes them.
3//!
4//! Chips share the [badge](mod@crate::feedback::badge) colours and are
5//! [`Variant::Secondary`] by default. Give a chip [`Chip::on_remove`] to
6//! draw the x, and [`Chip::id`] to find that x in tests through
7//! [`remove_id`].
8//!
9//! ```no_run
10//! use iced::Element;
11//! use iced_cube::feedback::chip::chip;
12//!
13//! #[derive(Debug, Clone)]
14//! enum Message {
15//!     Remove(usize),
16//! }
17//!
18//! fn guests(names: &[&str]) -> Element<'static, Message> {
19//!     iced::widget::row(names.iter().enumerate().map(|(index, name)| {
20//!         chip(name.to_string())
21//!             .on_remove(Message::Remove(index))
22//!             .into()
23//!     }))
24//!     .spacing(4)
25//!     .wrap()
26//!     .into()
27//! }
28//! ```
29
30use std::fmt;
31
32use iced::widget::{self, button, container, row, text};
33use iced::{Alignment, Background, Border, Element, Length, Padding, Shadow};
34
35pub use crate::feedback::badge::Variant;
36use crate::feedback::badge::{self, colours};
37use crate::icon::{Glyph, themed};
38use crate::natural::natural;
39use crate::theme::{Tokens, fade, radius, text_size};
40
41/// Space between the leading icon or element, the label and the x.
42const GAP: f32 = 4.0;
43/// Padding around the x glyph inside its round button.
44const REMOVE_PADDING: f32 = 1.0;
45
46/// Chip dimensions. [`Size::Sm`] matches a badge.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
48pub enum Size {
49    Sm,
50    #[default]
51    Md,
52}
53
54impl Size {
55    pub const ALL: [Size; 2] = [Size::Sm, Size::Md];
56
57    /// Height, horizontal padding, text size, icon size and x size.
58    pub const fn metrics(self) -> Metrics {
59        match self {
60            Size::Sm => Metrics {
61                height: 20.0,
62                padding_x: 10.0,
63                text: text_size::XS,
64                icon: 12.0,
65                remove: 12.0,
66            },
67            Size::Md => Metrics {
68                height: 26.0,
69                padding_x: 10.0,
70                text: text_size::SM,
71                icon: 14.0,
72                remove: 14.0,
73            },
74        }
75    }
76}
77
78/// Resolved dimensions for a [`Size`].
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct Metrics {
81    pub height: f32,
82    pub padding_x: f32,
83    pub text: f32,
84    pub icon: f32,
85    pub remove: f32,
86}
87
88impl Metrics {
89    /// The chip's padding: less on the left beside a leading element, so an
90    /// avatar sits in the curve, and less on the right beside the x.
91    pub fn padding(self, leading_element: bool, removable: bool) -> Padding {
92        Padding {
93            top: 0.0,
94            bottom: 0.0,
95            left: if leading_element { 1.0 } else { self.padding_x },
96            right: if removable { 3.0 } else { self.padding_x },
97        }
98    }
99}
100
101/// The widget id of the x button of the chip with [`Chip::id`] `key`.
102pub fn remove_id(key: &str) -> widget::Id {
103    widget::Id::from(format!("iced-cube-chip-remove-{key}"))
104}
105
106enum Leading<'a, Message> {
107    None,
108    Icon(Glyph),
109    Element(Element<'a, Message>),
110}
111
112/// A chip builder. Convert it into an [`Element`] to render.
113///
114/// A chip without [`on_remove`](Chip::on_remove) has no x button.
115pub struct Chip<'a, Message> {
116    label: text::Fragment<'a>,
117    leading: Leading<'a, Message>,
118    variant: Variant,
119    size: Size,
120    key: Option<String>,
121    on_remove: Option<Message>,
122}
123
124/// Creates a chip with a text label.
125pub fn chip<'a, Message>(label: impl text::IntoFragment<'a>) -> Chip<'a, Message> {
126    Chip {
127        label: label.into_fragment(),
128        leading: Leading::None,
129        variant: Variant::Secondary,
130        size: Size::default(),
131        key: None,
132        on_remove: None,
133    }
134}
135
136impl<Message: fmt::Debug> fmt::Debug for Chip<'_, Message> {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        let leading = match &self.leading {
139            Leading::None => "none",
140            Leading::Icon(_) => "icon",
141            Leading::Element(_) => "element",
142        };
143        f.debug_struct("Chip")
144            .field("label", &self.label)
145            .field("leading", &leading)
146            .field("variant", &self.variant)
147            .field("size", &self.size)
148            .field("key", &self.key)
149            .field("on_remove", &self.on_remove)
150            .finish()
151    }
152}
153
154impl<'a, Message> Chip<'a, Message> {
155    /// Defaults to [`Variant::Secondary`].
156    pub fn variant(mut self, variant: Variant) -> Self {
157        self.variant = variant;
158        self
159    }
160
161    /// Defaults to [`Size::Md`].
162    pub fn size(mut self, size: Size) -> Self {
163        self.size = size;
164        self
165    }
166
167    /// Adds an icon before the label. Replaces any leading element.
168    pub fn icon(mut self, glyph: Glyph) -> Self {
169        self.leading = Leading::Icon(glyph);
170        self
171    }
172
173    /// Adds an element before the label, such as a small avatar, laid out at
174    /// its own size against the chip's left edge. Replaces any icon.
175    pub fn leading(mut self, element: impl Into<Element<'a, Message>>) -> Self {
176        self.leading = Leading::Element(element.into());
177        self
178    }
179
180    /// A key, unique on screen, that gives the x button the widget id
181    /// [`remove_id`]`(key)`, to find or click it in tests.
182    pub fn id(mut self, key: impl Into<String>) -> Self {
183        self.key = Some(key.into());
184        self
185    }
186
187    /// Draws an x button after the label that sends `message` when pressed.
188    pub fn on_remove(mut self, message: Message) -> Self {
189        self.on_remove = Some(message);
190        self
191    }
192
193    /// Like [`on_remove`](Self::on_remove); `None` leaves the x out.
194    pub fn on_remove_maybe(mut self, message: Option<Message>) -> Self {
195        self.on_remove = message;
196        self
197    }
198
199    pub fn is_removable(&self) -> bool {
200        self.on_remove.is_some()
201    }
202}
203
204impl<'a, Message: Clone + 'a> From<Chip<'a, Message>> for Element<'a, Message> {
205    fn from(chip: Chip<'a, Message>) -> Self {
206        let Chip {
207            label,
208            leading,
209            variant,
210            size,
211            key,
212            on_remove,
213        } = chip;
214        let metrics = size.metrics();
215        let foreground = move |theme: &iced::Theme| colours(&Tokens::of(theme), variant).foreground;
216
217        let leading_element = matches!(leading, Leading::Element(_));
218        let mut content = row![].spacing(GAP).align_y(Alignment::Center);
219        match leading {
220            Leading::None => {}
221            Leading::Icon(glyph) => {
222                content = content.push(themed(glyph, metrics.icon, 1.0, foreground));
223            }
224            Leading::Element(element) => content = content.push(element),
225        }
226        content = content.push(
227            text(label)
228                .size(metrics.text)
229                .wrapping(text::Wrapping::None),
230        );
231
232        let removable = on_remove.is_some();
233        if let Some(message) = on_remove {
234            let remove = button(themed(crate::lucide!(X), metrics.remove, 1.0, foreground))
235                .padding(REMOVE_PADDING)
236                .on_press(message)
237                .style(move |theme, status| remove_style(&Tokens::of(theme), variant, status));
238            let mut remove = container(remove);
239            if let Some(key) = &key {
240                remove = remove.id(remove_id(key));
241            }
242            content = content.push(remove);
243        }
244
245        natural(
246            container(content)
247                .height(Length::Fixed(metrics.height))
248                .align_y(Alignment::Center)
249                .padding(metrics.padding(leading_element, removable))
250                .style(move |theme| style(&Tokens::of(theme), variant)),
251        )
252    }
253}
254
255/// The chip's container style: the badge style of the same variant.
256pub fn style(tokens: &Tokens, variant: Variant) -> container::Style {
257    badge::style(tokens, variant)
258}
259
260/// The x button style: clear until hovered or pressed, then a faint circle
261/// of the chip's foreground colour.
262pub fn remove_style(tokens: &Tokens, variant: Variant, status: button::Status) -> button::Style {
263    let foreground = colours(tokens, variant).foreground;
264    let background = match status {
265        button::Status::Hovered => Some(fade(foreground, 0.15)),
266        button::Status::Pressed => Some(fade(foreground, 0.25)),
267        button::Status::Active | button::Status::Disabled => None,
268    };
269    button::Style {
270        background: background.map(Background::Color),
271        text_color: foreground,
272        border: Border {
273            radius: radius::FULL.into(),
274            ..Border::default()
275        },
276        shadow: Shadow::default(),
277        snap: true,
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::theme::{dark, light};
285
286    const STATUSES: [button::Status; 4] = [
287        button::Status::Active,
288        button::Status::Hovered,
289        button::Status::Pressed,
290        button::Status::Disabled,
291    ];
292
293    #[test]
294    fn default_builder_is_a_secondary_medium_chip_without_x() {
295        let c: Chip<'_, ()> = chip("Ada");
296        assert_eq!(c.variant, Variant::Secondary);
297        assert_eq!(c.size, Size::Md);
298        assert!(matches!(c.leading, Leading::None));
299        assert!(c.key.is_none());
300        assert!(!c.is_removable());
301    }
302
303    #[test]
304    fn builder_keeps_its_options() {
305        let c = chip("Ada")
306            .variant(Variant::Outline)
307            .size(Size::Sm)
308            .icon(crate::lucide!(User))
309            .id("ada")
310            .on_remove(1);
311        assert_eq!(c.variant, Variant::Outline);
312        assert_eq!(c.size, Size::Sm);
313        assert!(matches!(c.leading, Leading::Icon(glyph) if glyph.name() == "user"));
314        assert_eq!(c.key.as_deref(), Some("ada"));
315        assert_eq!(c.on_remove, Some(1));
316        assert!(!c.on_remove_maybe(None).is_removable());
317    }
318
319    #[test]
320    fn leading_element_replaces_the_icon_and_back() {
321        let c: Chip<'_, ()> = chip("Ada").icon(crate::lucide!(User)).leading(text("A"));
322        assert!(matches!(c.leading, Leading::Element(_)));
323        let c = c.icon(crate::lucide!(User));
324        assert!(matches!(c.leading, Leading::Icon(_)));
325    }
326
327    #[test]
328    fn small_chips_match_badges_and_sizes_grow() {
329        let sm = Size::Sm.metrics();
330        let md = Size::Md.metrics();
331        assert_eq!(sm.text, text_size::XS);
332        assert_eq!(sm.icon, 12.0);
333        assert!(md.height > sm.height);
334        assert!(md.text > sm.text);
335        for size in Size::ALL {
336            let metrics = size.metrics();
337            assert!(
338                metrics.remove + 2.0 * REMOVE_PADDING < metrics.height,
339                "{size:?}"
340            );
341        }
342    }
343
344    #[test]
345    fn padding_tightens_beside_an_element_and_the_x() {
346        let metrics = Size::Md.metrics();
347        let plain = metrics.padding(false, false);
348        assert_eq!((plain.left, plain.right), (10.0, 10.0));
349        let both = metrics.padding(true, true);
350        assert!(both.left < plain.left && both.right < plain.right);
351    }
352
353    #[test]
354    fn chips_use_the_badge_style_of_their_variant() {
355        for theme in [light(), dark()] {
356            let tokens = Tokens::of(&theme);
357            for variant in Variant::ALL {
358                assert_eq!(style(&tokens, variant), badge::style(&tokens, variant));
359                assert_eq!(style(&tokens, variant).border.radius, radius::FULL.into());
360            }
361        }
362    }
363
364    #[test]
365    fn the_x_is_clear_until_hovered_or_pressed() {
366        for theme in [light(), dark()] {
367            let tokens = Tokens::of(&theme);
368            for variant in Variant::ALL {
369                let foreground = colours(&tokens, variant).foreground;
370                for status in STATUSES {
371                    let style = remove_style(&tokens, variant, status);
372                    assert_eq!(style.text_color, foreground, "{variant:?} {status:?}");
373                    let filled =
374                        matches!(status, button::Status::Hovered | button::Status::Pressed);
375                    assert_eq!(style.background.is_some(), filled, "{variant:?} {status:?}");
376                }
377                let hovered = remove_style(&tokens, variant, button::Status::Hovered);
378                let pressed = remove_style(&tokens, variant, button::Status::Pressed);
379                assert_ne!(hovered.background, pressed.background, "{variant:?}");
380            }
381        }
382    }
383
384    #[test]
385    fn remove_ids_differ_by_key() {
386        assert_eq!(remove_id("ada"), remove_id("ada"));
387        assert_ne!(remove_id("ada"), remove_id("bob"));
388    }
389}