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        #[cfg(feature = "icedwright")]
216        let name = label.clone();
217        let foreground = move |theme: &iced::Theme| colours(&Tokens::of(theme), variant).foreground;
218
219        let leading_element = matches!(leading, Leading::Element(_));
220        let mut content = row![].spacing(GAP).align_y(Alignment::Center);
221        match leading {
222            Leading::None => {}
223            Leading::Icon(glyph) => {
224                content = content.push(themed(glyph, metrics.icon, 1.0, foreground));
225            }
226            Leading::Element(element) => content = content.push(element),
227        }
228        content = content.push(
229            text(label)
230                .size(metrics.text)
231                .wrapping(text::Wrapping::None),
232        );
233
234        let removable = on_remove.is_some();
235        if let Some(message) = on_remove {
236            let remove = button(themed(crate::lucide!(X), metrics.remove, 1.0, foreground))
237                .padding(REMOVE_PADDING)
238                .on_press(message)
239                .style(move |theme, status| remove_style(&Tokens::of(theme), variant, status));
240            let mut remove = container(remove);
241            if let Some(key) = &key {
242                remove = remove.id(remove_id(key));
243            }
244            #[cfg(feature = "icedwright")]
245            let remove = icedwright_probe::semantic(remove)
246                .role(icedwright_probe::role::Button)
247                .name(format!("Remove {name}"))
248                .component("iced_cube::chip");
249            content = content.push(remove);
250        }
251
252        let element = natural(
253            container(content)
254                .height(Length::Fixed(metrics.height))
255                .align_y(Alignment::Center)
256                .padding(metrics.padding(leading_element, removable))
257                .style(move |theme| style(&Tokens::of(theme), variant)),
258        );
259        #[cfg(feature = "icedwright")]
260        let element = icedwright_probe::semantic(element)
261            .role(icedwright_probe::role::Group)
262            .name(name)
263            .component("iced_cube::chip")
264            .into();
265        element
266    }
267}
268
269/// The chip's container style: the badge style of the same variant.
270pub fn style(tokens: &Tokens, variant: Variant) -> container::Style {
271    badge::style(tokens, variant)
272}
273
274/// The x button style: clear until hovered or pressed, then a faint circle
275/// of the chip's foreground colour.
276pub fn remove_style(tokens: &Tokens, variant: Variant, status: button::Status) -> button::Style {
277    let foreground = colours(tokens, variant).foreground;
278    let background = match status {
279        button::Status::Hovered => Some(fade(foreground, 0.15)),
280        button::Status::Pressed => Some(fade(foreground, 0.25)),
281        button::Status::Active | button::Status::Disabled => None,
282    };
283    button::Style {
284        background: background.map(Background::Color),
285        text_color: foreground,
286        border: Border {
287            radius: radius::FULL.into(),
288            ..Border::default()
289        },
290        shadow: Shadow::default(),
291        snap: true,
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::theme::{dark, light};
299
300    const STATUSES: [button::Status; 4] = [
301        button::Status::Active,
302        button::Status::Hovered,
303        button::Status::Pressed,
304        button::Status::Disabled,
305    ];
306
307    #[test]
308    fn default_builder_is_a_secondary_medium_chip_without_x() {
309        let c: Chip<'_, ()> = chip("Ada");
310        assert_eq!(c.variant, Variant::Secondary);
311        assert_eq!(c.size, Size::Md);
312        assert!(matches!(c.leading, Leading::None));
313        assert!(c.key.is_none());
314        assert!(!c.is_removable());
315    }
316
317    #[test]
318    fn builder_keeps_its_options() {
319        let c = chip("Ada")
320            .variant(Variant::Outline)
321            .size(Size::Sm)
322            .icon(crate::lucide!(User))
323            .id("ada")
324            .on_remove(1);
325        assert_eq!(c.variant, Variant::Outline);
326        assert_eq!(c.size, Size::Sm);
327        assert!(matches!(c.leading, Leading::Icon(glyph) if glyph.name() == "user"));
328        assert_eq!(c.key.as_deref(), Some("ada"));
329        assert_eq!(c.on_remove, Some(1));
330        assert!(!c.on_remove_maybe(None).is_removable());
331    }
332
333    #[test]
334    fn leading_element_replaces_the_icon_and_back() {
335        let c: Chip<'_, ()> = chip("Ada").icon(crate::lucide!(User)).leading(text("A"));
336        assert!(matches!(c.leading, Leading::Element(_)));
337        let c = c.icon(crate::lucide!(User));
338        assert!(matches!(c.leading, Leading::Icon(_)));
339    }
340
341    #[test]
342    fn small_chips_match_badges_and_sizes_grow() {
343        let sm = Size::Sm.metrics();
344        let md = Size::Md.metrics();
345        assert_eq!(sm.text, text_size::XS);
346        assert_eq!(sm.icon, 12.0);
347        assert!(md.height > sm.height);
348        assert!(md.text > sm.text);
349        for size in Size::ALL {
350            let metrics = size.metrics();
351            assert!(
352                metrics.remove + 2.0 * REMOVE_PADDING < metrics.height,
353                "{size:?}"
354            );
355        }
356    }
357
358    #[test]
359    fn padding_tightens_beside_an_element_and_the_x() {
360        let metrics = Size::Md.metrics();
361        let plain = metrics.padding(false, false);
362        assert_eq!((plain.left, plain.right), (10.0, 10.0));
363        let both = metrics.padding(true, true);
364        assert!(both.left < plain.left && both.right < plain.right);
365    }
366
367    #[test]
368    fn chips_use_the_badge_style_of_their_variant() {
369        for theme in [light(), dark()] {
370            let tokens = Tokens::of(&theme);
371            for variant in Variant::ALL {
372                assert_eq!(style(&tokens, variant), badge::style(&tokens, variant));
373                assert_eq!(style(&tokens, variant).border.radius, radius::FULL.into());
374            }
375        }
376    }
377
378    #[test]
379    fn the_x_is_clear_until_hovered_or_pressed() {
380        for theme in [light(), dark()] {
381            let tokens = Tokens::of(&theme);
382            for variant in Variant::ALL {
383                let foreground = colours(&tokens, variant).foreground;
384                for status in STATUSES {
385                    let style = remove_style(&tokens, variant, status);
386                    assert_eq!(style.text_color, foreground, "{variant:?} {status:?}");
387                    let filled =
388                        matches!(status, button::Status::Hovered | button::Status::Pressed);
389                    assert_eq!(style.background.is_some(), filled, "{variant:?} {status:?}");
390                }
391                let hovered = remove_style(&tokens, variant, button::Status::Hovered);
392                let pressed = remove_style(&tokens, variant, button::Status::Pressed);
393                assert_ne!(hovered.background, pressed.background, "{variant:?}");
394            }
395        }
396    }
397
398    #[test]
399    fn remove_ids_differ_by_key() {
400        assert_eq!(remove_id("ada"), remove_id("ada"));
401        assert_ne!(remove_id("ada"), remove_id("bob"));
402    }
403}