Skip to main content

gpui_material_components/
chip.rs

1mod group;
2mod palette;
3mod render;
4mod split;
5
6pub use group::{ChipGroup, ChipGroupItem, ChipGroupSelection};
7
8use std::rc::Rc;
9
10use gpui::{
11    AnyElement, App, ElementId, Entity, FocusHandle, Hsla, IntoElement, Pixels, SharedString,
12    Window, px,
13};
14use gpui_material_foundation::InteractionSource;
15use gpui_material_theme::LogicalEdges;
16
17use crate::SemanticTone;
18use crate::action::{Activate, Change};
19use crate::control_style::{ControlBorder, ControlElevations, ControlShapes, finite_length};
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/// A Material chip. Filter and Input chips request controlled selection changes.
82/// Filter and Input chips can expose a separate removal action with its own focus.
83#[derive(IntoElement)]
84pub struct Chip {
85    id: ElementId,
86    label: SharedString,
87    variant: ChipVariant,
88    selected: bool,
89    elevated: bool,
90    disabled: bool,
91    tonal: bool,
92    tone: SemanticTone,
93    dragged: bool,
94    content: Option<AnyElement>,
95    leading: Option<AnyElement>,
96    avatar: Option<AnyElement>,
97    trailing: Option<AnyElement>,
98    shapes: ControlShapes,
99    colors: ChipColors,
100    border: Option<ControlBorder>,
101    elevations: ControlElevations,
102    spacing: Pixels,
103    padding: Option<LogicalEdges>,
104    focus: Option<FocusHandle>,
105    tab_stop: bool,
106    interaction_source: Option<Entity<InteractionSource>>,
107    on_activate: Option<Activate>,
108    on_change: Option<Change>,
109    remove: Option<(SharedString, Activate)>,
110}
111
112impl Chip {
113    /// Creates a chip with the default [`ChipVariant::Assist`] variant.
114    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
115        Self {
116            id: id.into(),
117            label: label.into(),
118            variant: ChipVariant::default(),
119            selected: false,
120            elevated: false,
121            disabled: false,
122            tonal: false,
123            tone: SemanticTone::Default,
124            dragged: false,
125            content: None,
126            leading: None,
127            avatar: None,
128            trailing: None,
129            shapes: ControlShapes::default(),
130            colors: ChipColors::default(),
131            border: None,
132            elevations: ControlElevations::default(),
133            spacing: px(8.),
134            padding: None,
135            focus: None,
136            tab_stop: true,
137            interaction_source: None,
138            on_activate: None,
139            on_change: None,
140            remove: None,
141        }
142    }
143
144    /// Creates an Assist chip.
145    pub fn assist(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
146        Self::new(id, label).variant(ChipVariant::Assist)
147    }
148
149    /// Creates a Filter chip.
150    pub fn filter(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
151        Self::new(id, label).variant(ChipVariant::Filter)
152    }
153
154    /// Creates an Input chip.
155    pub fn input(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
156        Self::new(id, label).variant(ChipVariant::Input)
157    }
158
159    /// Creates a Suggestion chip.
160    pub fn suggestion(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
161        Self::new(id, label).variant(ChipVariant::Suggestion)
162    }
163
164    /// Sets the chip category. Defaults to [`ChipVariant::Assist`].
165    pub fn variant(mut self, variant: ChipVariant) -> Self {
166        self.variant = variant;
167        self
168    }
169
170    /// Applies a Material 3 semantic tone shortcut for enabled and selected states.
171    /// Explicit `.colors` / `.border` overrides and disabled states still take precedence.
172    pub fn tone(mut self, tone: SemanticTone) -> Self {
173        self.tone = tone;
174        self
175    }
176
177    /// Sets the controlled selected state (used by [`ChipVariant::Filter`] and [`ChipVariant::Input`]).
178    pub fn selected(mut self, selected: bool) -> Self {
179        self.selected = selected;
180        self
181    }
182
183    /// Switches between flat outlined appearance (`false`, default) and elevated surface with shadow (`true`).
184    pub fn elevated(mut self, elevated: bool) -> Self {
185        self.elevated = elevated;
186        self
187    }
188
189    /// Disables pointer, keyboard, and removal interactions when `true`.
190    pub fn disabled(mut self, disabled: bool) -> Self {
191        self.disabled = disabled;
192        self
193    }
194
195    /// Selects the expressive Tonal defaults for Filter, elevated Filter, and Input.
196    pub fn tonal(mut self, tonal: bool) -> Self {
197        self.tonal = tonal;
198        self
199    }
200
201    /// Supplies visual label content. The constructor's label names the action.
202    pub fn content(mut self, content: impl IntoElement) -> Self {
203        self.content = Some(content.into_any_element());
204        self
205    }
206
207    /// Sets a decorative leading icon in the chip's leading slot.
208    pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
209        self.leading = Some(icon.into_any_element());
210        self
211    }
212
213    /// Sets the Input chip's circular avatar, taking precedence over its leading icon.
214    pub fn avatar(mut self, avatar: impl IntoElement) -> Self {
215        self.avatar = Some(avatar.into_any_element());
216        self
217    }
218
219    /// Sets visual trailing content for Assist, Filter, or Input. With an
220    /// independent removal action this is that button's visual content.
221    pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
222        self.trailing = Some(trailing.into_any_element());
223        self
224    }
225
226    /// Overrides state-specific corner shapes.
227    pub fn shapes(mut self, shapes: ControlShapes) -> Self {
228        self.shapes = shapes;
229        self
230    }
231
232    /// Overrides container, label, icon, and border colors per state.
233    pub fn colors(mut self, colors: ChipColors) -> Self {
234        self.colors = colors;
235        self
236    }
237
238    /// Overrides the chip's outline stroke width and color.
239    pub fn border(mut self, border: ControlBorder) -> Self {
240        self.border = Some(border);
241        self
242    }
243
244    /// Overrides drop-shadow elevation levels per interaction state.
245    pub fn elevations(mut self, elevations: ControlElevations) -> Self {
246        self.elevations = elevations;
247        self
248    }
249
250    /// Reflects caller-owned drag state and cancels pending pointer activation.
251    pub fn dragged(mut self, dragged: bool) -> Self {
252        self.dragged = dragged;
253        self
254    }
255
256    /// Sets horizontal spacing between leading, label, and trailing slots in logical pixels. Defaults to `8 px`.
257    pub fn spacing(mut self, spacing: Pixels) -> Self {
258        self.spacing = finite_length(spacing);
259        self
260    }
261
262    /// Overrides logical inner padding around the chip's slots.
263    pub fn content_padding(mut self, padding: LogicalEdges) -> Self {
264        self.padding = Some(LogicalEdges::new(
265            padding.top,
266            padding.end,
267            padding.bottom,
268            padding.start,
269        ));
270        self
271    }
272
273    /// Attaches a caller-owned focus handle to the primary chip action.
274    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
275        self.focus = Some(focus.clone());
276        self
277    }
278
279    pub(crate) fn tab_stop(mut self, tab_stop: bool) -> Self {
280        self.tab_stop = tab_stop;
281        self
282    }
283
284    /// Observes the primary chip action under the constructor's chip ID.
285    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
286        self.interaction_source = Some(source.clone());
287        self
288    }
289
290    /// Invoked when an Assist or Suggestion chip is activated.
291    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
292        self.on_activate = Some(Rc::new(handler));
293        self
294    }
295
296    /// Invoked with the requested next selected state when a Filter or Input chip is toggled.
297    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
298        self.on_change = Some(Rc::new(handler));
299        self
300    }
301
302    /// Adds an independent removal action to a Filter or Input chip.
303    /// The optional restoration target is focused before calling the owner.
304    /// The owner can pass the next chip or a stable control outside the group.
305    pub fn on_remove(
306        mut self,
307        name: impl Into<SharedString>,
308        restore: Option<FocusHandle>,
309        handler: impl Fn(&mut Window, &mut App) + 'static,
310    ) -> Self {
311        self.remove = Some((
312            name.into(),
313            Rc::new(move |window, cx| {
314                if let Some(restore) = &restore {
315                    restore.focus(window, cx);
316                }
317                handler(window, cx);
318            }),
319        ));
320        self
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn chip_variant_shorthands_and_tone_configure_expected_fields() {
330        assert_eq!(Chip::assist("c1", "Assist").variant, ChipVariant::Assist);
331        assert_eq!(Chip::filter("c2", "Filter").variant, ChipVariant::Filter);
332        assert_eq!(Chip::input("c3", "Input").variant, ChipVariant::Input);
333        assert_eq!(
334            Chip::suggestion("c4", "Suggest").variant,
335            ChipVariant::Suggestion
336        );
337        let toned = Chip::filter("c5", "Danger").tone(SemanticTone::Danger);
338        assert_eq!(toned.tone, SemanticTone::Danger);
339    }
340}