Skip to main content

gpui_material_components/
chip.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, FocusHandle, InteractiveElement, IntoElement, ParentElement,
5    RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder, px,
6};
7use gpui_material_foundation::{animate, color, window_material_theme};
8use gpui_material_theme::{
9    ColorRole, CornerRole, Direction, Elevation, MotionKind, MotionSpeed, TypeRole,
10    TypographyEmphasis,
11};
12
13use crate::action::{
14    Action, ActionControl, ActionStyle, Activate, Change, DisabledStyle, icon_slot,
15};
16use crate::{Icon, IconName};
17
18#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
19pub enum ChipVariant {
20    #[default]
21    Assist,
22    Filter,
23    Input,
24    Suggestion,
25}
26
27/// A Material chip. Filter and Input chips request controlled selection changes.
28/// Filter and Input chips can expose a separate removal action with its own focus.
29#[derive(IntoElement)]
30pub struct Chip {
31    id: ElementId,
32    label: SharedString,
33    variant: ChipVariant,
34    selected: bool,
35    elevated: bool,
36    disabled: bool,
37    leading: Option<AnyElement>,
38    on_activate: Option<Activate>,
39    on_change: Option<Change>,
40    remove: Option<(SharedString, Activate)>,
41}
42
43impl Chip {
44    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
45        Self {
46            id: id.into(),
47            label: label.into(),
48            variant: ChipVariant::default(),
49            selected: false,
50            elevated: false,
51            disabled: false,
52            leading: None,
53            on_activate: None,
54            on_change: None,
55            remove: None,
56        }
57    }
58
59    pub fn variant(mut self, variant: ChipVariant) -> Self {
60        self.variant = variant;
61        self
62    }
63
64    pub fn selected(mut self, selected: bool) -> Self {
65        self.selected = selected;
66        self
67    }
68
69    pub fn elevated(mut self, elevated: bool) -> Self {
70        self.elevated = elevated;
71        self
72    }
73
74    pub fn disabled(mut self, disabled: bool) -> Self {
75        self.disabled = disabled;
76        self
77    }
78
79    pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
80        self.leading = Some(icon.into_any_element());
81        self
82    }
83
84    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
85        self.on_activate = Some(Rc::new(handler));
86        self
87    }
88
89    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
90        self.on_change = Some(Rc::new(handler));
91        self
92    }
93
94    /// Adds an independent removal action to a Filter or Input chip.
95    /// The optional restoration target is focused before calling the owner.
96    /// The owner can pass the next chip or a stable control outside the group.
97    pub fn on_remove(
98        mut self,
99        name: impl Into<SharedString>,
100        restore: Option<FocusHandle>,
101        handler: impl Fn(&mut Window, &mut App) + 'static,
102    ) -> Self {
103        self.remove = Some((
104            name.into(),
105            Rc::new(move |window, cx| {
106                if let Some(restore) = &restore {
107                    restore.focus(window, cx);
108                }
109                handler(window, cx);
110            }),
111        ));
112        self
113    }
114}
115
116impl RenderOnce for Chip {
117    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
118        use ColorRole::*;
119        let selectable = matches!(self.variant, ChipVariant::Filter | ChipVariant::Input);
120        let selected = selectable && self.selected;
121        let elevated = self.elevated && self.variant != ChipVariant::Input;
122        let background = if selected {
123            Some(SecondaryContainer)
124        } else if elevated {
125            Some(SurfaceContainerLow)
126        } else {
127            None
128        };
129        let foreground = if selected {
130            OnSecondaryContainer
131        } else if self.variant == ChipVariant::Assist {
132            OnSurface
133        } else {
134            OnSurfaceVariant
135        };
136        let theme = window_material_theme(window, cx).clone();
137        let direction = theme.layout.direction;
138        let split = selectable && self.remove.is_some();
139        let on_surface = color(theme.colors.color(OnSurface));
140        let theme_color = |role| color(theme.colors.color(role));
141        let idle = if elevated {
142            theme_color(SurfaceContainerLow)
143        } else {
144            theme_color(SecondaryContainer).opacity(0.)
145        };
146        let effects = theme.motion.spec(
147            MotionKind::Effects,
148            MotionSpeed::Fast,
149            cx.reduce_motion() || self.disabled,
150        );
151        let selection = if selectable {
152            animate(
153                (self.id.clone(), "chip-tint"),
154                f32::from(selected),
155                effects,
156                window,
157                cx,
158            )
159            .clamp(0., 1.)
160        } else {
161            0.
162        };
163        let container = if self.disabled {
164            on_surface.opacity(if background.is_some() { 0.12 } else { 0. })
165        } else {
166            crate::motion::mix(idle, theme_color(SecondaryContainer), selection)
167        };
168        let border = if self.disabled {
169            on_surface.opacity(0.12)
170        } else {
171            theme_color(OutlineVariant)
172        };
173        let outline_opacity = if elevated { 0. } else { 1. - selection };
174        let height = px(theme.layout.density.visual_size(32.));
175        let radius = px(CornerRole::Small.shape().radii(32., 32., direction)[0]);
176        let style = ActionStyle {
177            background: background.filter(|_| !split),
178            background_color: (!split).then_some(container),
179            foreground,
180            disabled: DisabledStyle {
181                foreground: OnSurface,
182                background: background.filter(|_| !split).map(|_| (OnSurface, 0.12)),
183                outline: (OnSurface, 0.12),
184            },
185            height: 32.,
186            min_width: 0.,
187            corner: CornerRole::Small,
188            pressed_corner: CornerRole::Small,
189            selected_corner: None,
190            corner_motion: (MotionKind::Spatial, MotionSpeed::Fast),
191            outline: f32::from(!split && !elevated && !selected),
192            elevation: if elevated {
193                Elevation::Level1
194            } else {
195                Elevation::Level0
196            },
197            hover_elevation: if elevated {
198                Elevation::Level2
199            } else if selected && self.variant == ChipVariant::Filter {
200                Elevation::Level1
201            } else {
202                Elevation::Level0
203            },
204        };
205        let filter_mark = if self.variant == ChipVariant::Filter && self.leading.is_none() {
206            selection
207        } else {
208            0.
209        };
210        let leading_tint = if self.disabled {
211            on_surface.opacity(0.38)
212        } else {
213            theme_color(match (self.variant, selected) {
214                (ChipVariant::Input, false) => OnSurfaceVariant,
215                (ChipVariant::Filter, true) => OnSecondaryContainer,
216                _ => Primary,
217            })
218        };
219        let leading = self
220            .leading
221            .map(|icon| {
222                div()
223                    .text_color(leading_tint)
224                    .child(icon_slot(icon, 18.))
225                    .into_any_element()
226            })
227            .or_else(|| {
228                (filter_mark > 0.).then(|| {
229                    div()
230                        .w(px(26. * filter_mark))
231                        .flex_none()
232                        .overflow_hidden()
233                        .opacity(filter_mark)
234                        .child(icon_slot(
235                            Icon::new(IconName::Check).into_any_element(),
236                            18.,
237                        ))
238                        .into_any_element()
239                })
240            });
241        // Label edges have 16 dp; an icon consumes the outer 8 dp. The
242        // generated filter check animates both its slot and its leading inset.
243        let start_padding = if filter_mark > 0. {
244            16. - 8. * filter_mark
245        } else if leading.is_some() {
246            8.
247        } else {
248            16.
249        };
250        let end_padding = if split { 8. } else { 16. };
251        let content = div()
252            .flex()
253            .items_center()
254            .min_w_0()
255            .when(
256                self.variant != ChipVariant::Filter || filter_mark == 0.,
257                |row| row.gap(px(8.)),
258            )
259            .pl(px(if direction == Direction::Rtl {
260                end_padding
261            } else {
262                start_padding
263            }))
264            .pr(px(if direction == Direction::Rtl {
265                start_padding
266            } else {
267                end_padding
268            }))
269            .text_size(px(14.))
270            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
271            .children(leading)
272            .child(crate::text::single_line(
273                self.label.clone(),
274                TypeRole::LabelLarge.style(TypographyEmphasis::Baseline),
275                1.,
276                style.foreground(self.disabled, window, cx),
277                (None, 1., 1.),
278                window,
279                cx,
280            ));
281        let action = if selectable {
282            Action::Toggle {
283                selected,
284                on_change: self.on_change,
285            }
286        } else {
287            Action::Invoke(self.on_activate)
288        };
289        let row = div()
290            .id(self.id.clone())
291            .relative()
292            .flex()
293            .min_w_0()
294            .items_center()
295            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
296            .when(split, |row| {
297                row.child(
298                    div()
299                        .absolute()
300                        .left_0()
301                        .right_0()
302                        .top(gpui::relative(0.5))
303                        .mt(-height / 2.)
304                        .h(height)
305                        .rounded(radius)
306                        .bg(container)
307                        .when(outline_opacity > 0., |surface| {
308                            surface
309                                .border_1()
310                                .border_color(border.opacity(outline_opacity))
311                        }),
312                )
313            })
314            .child(
315                ActionControl {
316                    id: ElementId::from((self.id.clone(), "activate")),
317                    label: self.label,
318                    focus: None,
319                    disabled: self.disabled,
320                    action,
321                    style,
322                    content: content.into_any_element(),
323                }
324                .render(window, cx),
325            );
326        if let (true, Some((label, on_remove))) = (selectable, self.remove) {
327            row.child(
328                ActionControl {
329                    id: ElementId::from((self.id, "remove")),
330                    label,
331                    focus: None,
332                    disabled: self.disabled,
333                    action: Action::Invoke(Some(on_remove)),
334                    style: ActionStyle {
335                        background: None,
336                        background_color: None,
337                        foreground,
338                        disabled: DisabledStyle {
339                            foreground: OnSurface,
340                            background: None,
341                            outline: (OnSurface, 0.12),
342                        },
343                        height: 32.,
344                        min_width: 32.,
345                        corner: CornerRole::Small,
346                        pressed_corner: CornerRole::Small,
347                        selected_corner: None,
348                        corner_motion: (
349                            gpui_material_theme::MotionKind::Spatial,
350                            gpui_material_theme::MotionSpeed::Fast,
351                        ),
352                        outline: 0.,
353                        elevation: Elevation::Level0,
354                        hover_elevation: Elevation::Level0,
355                    },
356                    content: icon_slot(Icon::new(IconName::Close).into_any_element(), 18.)
357                        .into_any_element(),
358                }
359                .render(window, cx),
360            )
361        } else {
362            row
363        }
364    }
365}