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