Skip to main content

gpui_material_components/
chip.rs

1mod group;
2mod render;
3
4pub use group::{ChipGroup, ChipGroupItem, ChipGroupSelection};
5
6use std::rc::Rc;
7
8use gpui::{
9    AnyElement, App, ElementId, Entity, FocusHandle, Hsla, IntoElement, Pixels, SharedString,
10    Window, px,
11};
12use gpui_material_foundation::InteractionSource;
13use gpui_material_theme::Elevation;
14
15use crate::SemanticTone;
16use crate::action::{Activate, Change};
17use crate::button_style::{
18    ButtonBorder, ButtonElevations, ButtonPadding, ButtonShapes, finite_length,
19};
20
21/// Material 3 chip category controlling selection, avatar, and trailing-action behavior.
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
23pub enum ChipVariant {
24    /// Action chip representing a smart or automated contextual action (default).
25    #[default]
26    Assist,
27    /// Toggleable chip for filtering content, with optional selection checkmark and removal action.
28    Filter,
29    /// Compact representation of user input (such as a contact or tag) supporting an avatar and removal action.
30    Input,
31    /// Action chip presenting dynamically generated suggestions.
32    Suggestion,
33}
34
35/// Per-slot pigments for one chip state. Omitted fields retain the defaults.
36#[derive(Clone, Copy, Debug, Default, PartialEq)]
37pub struct ChipStateColors {
38    /// Container background color.
39    pub container: Option<Hsla>,
40    /// Label text color.
41    pub label: Option<Hsla>,
42    /// Leading icon tint color.
43    pub leading: Option<Hsla>,
44    /// Trailing icon or remove-button tint color.
45    pub trailing: Option<Hsla>,
46    /// Outline border color.
47    pub border: Option<Hsla>,
48}
49
50/// Enabled, selected, and disabled chip pigments. Disabled-selected fields fall
51/// back to disabled overrides. Selection applies to Filter and Input chips.
52#[derive(Clone, Copy, Debug, Default, PartialEq)]
53pub struct ChipColors {
54    /// Colors when enabled and unselected.
55    pub enabled: ChipStateColors,
56    /// Colors when enabled and selected.
57    pub selected: ChipStateColors,
58    /// Colors when disabled and unselected.
59    pub disabled: ChipStateColors,
60    /// Colors when disabled and selected.
61    pub disabled_selected: ChipStateColors,
62}
63
64impl ChipColors {
65    fn for_state(self, disabled: bool, selected: bool) -> ChipStateColors {
66        match (disabled, selected) {
67            (false, false) => self.enabled,
68            (false, true) => self.selected,
69            (true, false) => self.disabled,
70            (true, true) => ChipStateColors {
71                container: self.disabled_selected.container.or(self.disabled.container),
72                label: self.disabled_selected.label.or(self.disabled.label),
73                leading: self.disabled_selected.leading.or(self.disabled.leading),
74                trailing: self.disabled_selected.trailing.or(self.disabled.trailing),
75                border: self.disabled_selected.border.or(self.disabled.border),
76            },
77        }
78    }
79}
80
81/// Optional shadows for each state. Disabled and dragged take precedence over
82/// press, keyboard focus, hover, and rest.
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
84pub struct ChipElevations {
85    /// Elevation while resting.
86    pub resting: Option<Elevation>,
87    /// Elevation while pressed.
88    pub pressed: Option<Elevation>,
89    /// Elevation while keyboard focus is visible.
90    pub focused: Option<Elevation>,
91    /// Elevation while hovered.
92    pub hovered: Option<Elevation>,
93    /// Elevation while dragged.
94    pub dragged: Option<Elevation>,
95    /// Elevation while disabled.
96    pub disabled: Option<Elevation>,
97}
98
99impl ChipElevations {
100    fn button(self) -> ButtonElevations {
101        ButtonElevations {
102            resting: self.resting,
103            pressed: self.pressed,
104            focused: self.focused,
105            hovered: self.hovered,
106            disabled: self.disabled,
107        }
108    }
109}
110
111/// A Material chip. Filter and Input chips request controlled selection changes.
112/// Filter and Input chips can expose a separate removal action with its own focus.
113#[derive(IntoElement)]
114pub struct Chip {
115    id: ElementId,
116    label: SharedString,
117    variant: ChipVariant,
118    selected: bool,
119    elevated: bool,
120    disabled: bool,
121    tonal: bool,
122    tone: SemanticTone,
123    dragged: bool,
124    content: Option<AnyElement>,
125    leading: Option<AnyElement>,
126    avatar: Option<AnyElement>,
127    trailing: Option<AnyElement>,
128    shapes: ButtonShapes,
129    colors: ChipColors,
130    border: Option<ButtonBorder>,
131    elevations: ChipElevations,
132    spacing: Pixels,
133    padding: Option<ButtonPadding>,
134    focus: Option<FocusHandle>,
135    tab_stop: bool,
136    interaction_source: Option<Entity<InteractionSource>>,
137    on_activate: Option<Activate>,
138    on_change: Option<Change>,
139    remove: Option<(SharedString, Activate)>,
140}
141
142impl Chip {
143    /// Creates a chip with the default [`ChipVariant::Assist`] variant.
144    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
145        Self {
146            id: id.into(),
147            label: label.into(),
148            variant: ChipVariant::default(),
149            selected: false,
150            elevated: false,
151            disabled: false,
152            tonal: false,
153            tone: SemanticTone::Default,
154            dragged: false,
155            content: None,
156            leading: None,
157            avatar: None,
158            trailing: None,
159            shapes: ButtonShapes::default(),
160            colors: ChipColors::default(),
161            border: None,
162            elevations: ChipElevations::default(),
163            spacing: px(8.),
164            padding: None,
165            focus: None,
166            tab_stop: true,
167            interaction_source: None,
168            on_activate: None,
169            on_change: None,
170            remove: None,
171        }
172    }
173
174    /// Creates an Assist chip.
175    pub fn assist(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
176        Self::new(id, label).variant(ChipVariant::Assist)
177    }
178
179    /// Creates a Filter chip.
180    pub fn filter(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
181        Self::new(id, label).variant(ChipVariant::Filter)
182    }
183
184    /// Creates an Input chip.
185    pub fn input(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
186        Self::new(id, label).variant(ChipVariant::Input)
187    }
188
189    /// Creates a Suggestion chip.
190    pub fn suggestion(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
191        Self::new(id, label).variant(ChipVariant::Suggestion)
192    }
193
194    /// Sets the chip category. Defaults to [`ChipVariant::Assist`].
195    pub fn variant(mut self, variant: ChipVariant) -> Self {
196        self.variant = variant;
197        self
198    }
199
200    /// Applies a Material 3 semantic tone shortcut for enabled and selected states.
201    /// Explicit `.colors` / `.border` overrides and disabled states still take precedence.
202    pub fn tone(mut self, tone: SemanticTone) -> Self {
203        self.tone = tone;
204        self
205    }
206
207    /// Sets the controlled selected state (used by [`ChipVariant::Filter`] and [`ChipVariant::Input`]).
208    pub fn selected(mut self, selected: bool) -> Self {
209        self.selected = selected;
210        self
211    }
212
213    /// Switches between flat outlined appearance (`false`, default) and elevated surface with shadow (`true`).
214    pub fn elevated(mut self, elevated: bool) -> Self {
215        self.elevated = elevated;
216        self
217    }
218
219    /// Disables pointer, keyboard, and removal interactions when `true`.
220    pub fn disabled(mut self, disabled: bool) -> Self {
221        self.disabled = disabled;
222        self
223    }
224
225    /// Selects the expressive Tonal defaults for Filter, elevated Filter, and Input.
226    pub fn tonal(mut self, tonal: bool) -> Self {
227        self.tonal = tonal;
228        self
229    }
230
231    /// Supplies visual label content. The constructor's label names the action.
232    pub fn content(mut self, content: impl IntoElement) -> Self {
233        self.content = Some(content.into_any_element());
234        self
235    }
236
237    /// Sets a decorative leading icon in the chip's leading slot.
238    pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
239        self.leading = Some(icon.into_any_element());
240        self
241    }
242
243    /// Sets the Input chip's circular avatar, taking precedence over its leading icon.
244    pub fn avatar(mut self, avatar: impl IntoElement) -> Self {
245        self.avatar = Some(avatar.into_any_element());
246        self
247    }
248
249    /// Sets visual trailing content for Assist, Filter, or Input. With an
250    /// independent removal action this is that button's visual content.
251    pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
252        self.trailing = Some(trailing.into_any_element());
253        self
254    }
255
256    /// Overrides state-specific corner shapes.
257    pub fn shapes(mut self, shapes: ButtonShapes) -> Self {
258        self.shapes = shapes;
259        self
260    }
261
262    /// Overrides container, label, icon, and border colors per state.
263    pub fn colors(mut self, colors: ChipColors) -> Self {
264        self.colors = colors;
265        self
266    }
267
268    /// Overrides the chip's outline stroke width and color.
269    pub fn border(mut self, border: ButtonBorder) -> Self {
270        self.border = Some(border);
271        self
272    }
273
274    /// Overrides drop-shadow elevation levels per interaction state.
275    pub fn elevations(mut self, elevations: ChipElevations) -> Self {
276        self.elevations = elevations;
277        self
278    }
279
280    /// Reflects caller-owned drag state and cancels pending pointer activation.
281    pub fn dragged(mut self, dragged: bool) -> Self {
282        self.dragged = dragged;
283        self
284    }
285
286    /// Sets horizontal spacing between leading, label, and trailing slots in logical pixels. Defaults to `8 px`.
287    pub fn spacing(mut self, spacing: Pixels) -> Self {
288        self.spacing = finite_length(spacing);
289        self
290    }
291
292    /// Overrides logical inner padding around the chip's slots.
293    pub fn content_padding(mut self, padding: ButtonPadding) -> Self {
294        self.padding = Some(ButtonPadding {
295            top: finite_length(padding.top),
296            end: finite_length(padding.end),
297            bottom: finite_length(padding.bottom),
298            start: finite_length(padding.start),
299        });
300        self
301    }
302
303    /// Attaches a caller-owned focus handle to the primary chip action.
304    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
305        self.focus = Some(focus.clone());
306        self
307    }
308
309    pub(crate) fn tab_stop(mut self, tab_stop: bool) -> Self {
310        self.tab_stop = tab_stop;
311        self
312    }
313
314    /// Observes the primary chip action under the constructor's chip ID.
315    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
316        self.interaction_source = Some(source.clone());
317        self
318    }
319
320    /// Invoked when an Assist or Suggestion chip is activated.
321    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
322        self.on_activate = Some(Rc::new(handler));
323        self
324    }
325
326    /// Invoked with the requested next selected state when a Filter or Input chip is toggled.
327    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
328        self.on_change = Some(Rc::new(handler));
329        self
330    }
331
332    /// Adds an independent removal action to a Filter or Input chip.
333    /// The optional restoration target is focused before calling the owner.
334    /// The owner can pass the next chip or a stable control outside the group.
335    pub fn on_remove(
336        mut self,
337        name: impl Into<SharedString>,
338        restore: Option<FocusHandle>,
339        handler: impl Fn(&mut Window, &mut App) + 'static,
340    ) -> Self {
341        self.remove = Some((
342            name.into(),
343            Rc::new(move |window, cx| {
344                if let Some(restore) = &restore {
345                    restore.focus(window, cx);
346                }
347                handler(window, cx);
348            }),
349        ));
350        self
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn chip_variant_shorthands_and_tone_configure_expected_fields() {
360        assert_eq!(Chip::assist("c1", "Assist").variant, ChipVariant::Assist);
361        assert_eq!(Chip::filter("c2", "Filter").variant, ChipVariant::Filter);
362        assert_eq!(Chip::input("c3", "Input").variant, ChipVariant::Input);
363        assert_eq!(
364            Chip::suggestion("c4", "Suggest").variant,
365            ChipVariant::Suggestion
366        );
367        let toned = Chip::filter("c5", "Danger").tone(SemanticTone::Danger);
368        assert_eq!(toned.tone, SemanticTone::Danger);
369    }
370}