1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 AnyElement, App, BorderStyle, Corners, ElementId, Entity, FocusHandle, Hsla,
5 InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Styled,
6 Window, canvas, div, point, prelude::FluentBuilder, px, quad,
7};
8use gpui_material_foundation::{
9 InteractionSource, InteractionState, animate, color, elevation_shadows, window_material_theme,
10};
11use gpui_material_theme::{
12 ColorRole, CornerRole, Direction, Elevation, MotionKind, MotionSpeed, TypeRole,
13 TypographyEmphasis,
14};
15
16use crate::action::{
17 Action, ActionControl, ActionLayout, ActionStyle, Activate, Change, DisabledStyle, icon_slot,
18 interpolated_corners,
19};
20use crate::button_style::{ButtonStyle, finite_length};
21use crate::{
22 ButtonBorder, ButtonColors, ButtonElevations, ButtonPadding, ButtonShapes, Icon, IconName,
23};
24
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub enum ChipVariant {
27 #[default]
28 Assist,
29 Filter,
30 Input,
31 Suggestion,
32}
33
34#[derive(Clone, Copy, Debug, Default, PartialEq)]
36pub struct ChipStateColors {
37 pub container: Option<Hsla>,
38 pub label: Option<Hsla>,
39 pub leading: Option<Hsla>,
40 pub trailing: Option<Hsla>,
41 pub border: Option<Hsla>,
42}
43
44#[derive(Clone, Copy, Debug, Default, PartialEq)]
47pub struct ChipColors {
48 pub enabled: ChipStateColors,
49 pub selected: ChipStateColors,
50 pub disabled: ChipStateColors,
51 pub disabled_selected: ChipStateColors,
52}
53
54impl ChipColors {
55 fn for_state(self, disabled: bool, selected: bool) -> ChipStateColors {
56 match (disabled, selected) {
57 (false, false) => self.enabled,
58 (false, true) => self.selected,
59 (true, false) => self.disabled,
60 (true, true) => ChipStateColors {
61 container: self.disabled_selected.container.or(self.disabled.container),
62 label: self.disabled_selected.label.or(self.disabled.label),
63 leading: self.disabled_selected.leading.or(self.disabled.leading),
64 trailing: self.disabled_selected.trailing.or(self.disabled.trailing),
65 border: self.disabled_selected.border.or(self.disabled.border),
66 },
67 }
68 }
69}
70
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74pub struct ChipElevations {
75 pub resting: Option<Elevation>,
76 pub pressed: Option<Elevation>,
77 pub focused: Option<Elevation>,
78 pub hovered: Option<Elevation>,
79 pub dragged: Option<Elevation>,
80 pub disabled: Option<Elevation>,
81}
82
83impl ChipElevations {
84 fn button(self) -> ButtonElevations {
85 ButtonElevations {
86 resting: self.resting,
87 pressed: self.pressed,
88 focused: self.focused,
89 hovered: self.hovered,
90 disabled: self.disabled,
91 }
92 }
93}
94
95#[derive(IntoElement)]
98pub struct Chip {
99 id: ElementId,
100 label: SharedString,
101 variant: ChipVariant,
102 selected: bool,
103 elevated: bool,
104 disabled: bool,
105 tonal: bool,
106 dragged: bool,
107 content: Option<AnyElement>,
108 leading: Option<AnyElement>,
109 avatar: Option<AnyElement>,
110 trailing: Option<AnyElement>,
111 shapes: ButtonShapes,
112 colors: ChipColors,
113 border: Option<ButtonBorder>,
114 elevations: ChipElevations,
115 spacing: Pixels,
116 padding: Option<ButtonPadding>,
117 interaction_source: Option<Entity<InteractionSource>>,
118 on_activate: Option<Activate>,
119 on_change: Option<Change>,
120 remove: Option<(SharedString, Activate)>,
121}
122
123impl Chip {
124 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
125 Self {
126 id: id.into(),
127 label: label.into(),
128 variant: ChipVariant::default(),
129 selected: false,
130 elevated: false,
131 disabled: false,
132 tonal: false,
133 dragged: false,
134 content: None,
135 leading: None,
136 avatar: None,
137 trailing: None,
138 shapes: ButtonShapes::default(),
139 colors: ChipColors::default(),
140 border: None,
141 elevations: ChipElevations::default(),
142 spacing: px(8.),
143 padding: None,
144 interaction_source: None,
145 on_activate: None,
146 on_change: None,
147 remove: None,
148 }
149 }
150
151 pub fn variant(mut self, variant: ChipVariant) -> Self {
152 self.variant = variant;
153 self
154 }
155
156 pub fn selected(mut self, selected: bool) -> Self {
157 self.selected = selected;
158 self
159 }
160
161 pub fn elevated(mut self, elevated: bool) -> Self {
162 self.elevated = elevated;
163 self
164 }
165
166 pub fn disabled(mut self, disabled: bool) -> Self {
167 self.disabled = disabled;
168 self
169 }
170
171 pub fn tonal(mut self, tonal: bool) -> Self {
173 self.tonal = tonal;
174 self
175 }
176
177 pub fn content(mut self, content: impl IntoElement) -> Self {
179 self.content = Some(content.into_any_element());
180 self
181 }
182
183 pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
184 self.leading = Some(icon.into_any_element());
185 self
186 }
187
188 pub fn avatar(mut self, avatar: impl IntoElement) -> Self {
190 self.avatar = Some(avatar.into_any_element());
191 self
192 }
193
194 pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
197 self.trailing = Some(trailing.into_any_element());
198 self
199 }
200
201 pub fn shapes(mut self, shapes: ButtonShapes) -> Self {
202 self.shapes = shapes;
203 self
204 }
205
206 pub fn colors(mut self, colors: ChipColors) -> Self {
207 self.colors = colors;
208 self
209 }
210
211 pub fn border(mut self, border: ButtonBorder) -> Self {
212 self.border = Some(border);
213 self
214 }
215
216 pub fn elevations(mut self, elevations: ChipElevations) -> Self {
217 self.elevations = elevations;
218 self
219 }
220
221 pub fn dragged(mut self, dragged: bool) -> Self {
223 self.dragged = dragged;
224 self
225 }
226
227 pub fn spacing(mut self, spacing: Pixels) -> Self {
228 self.spacing = finite_length(spacing);
229 self
230 }
231
232 pub fn content_padding(mut self, padding: ButtonPadding) -> Self {
233 self.padding = Some(ButtonPadding {
234 top: finite_length(padding.top),
235 end: finite_length(padding.end),
236 bottom: finite_length(padding.bottom),
237 start: finite_length(padding.start),
238 });
239 self
240 }
241
242 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
244 self.interaction_source = Some(source.clone());
245 self
246 }
247
248 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
249 self.on_activate = Some(Rc::new(handler));
250 self
251 }
252
253 pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
254 self.on_change = Some(Rc::new(handler));
255 self
256 }
257
258 pub fn on_remove(
262 mut self,
263 name: impl Into<SharedString>,
264 restore: Option<FocusHandle>,
265 handler: impl Fn(&mut Window, &mut App) + 'static,
266 ) -> Self {
267 self.remove = Some((
268 name.into(),
269 Rc::new(move |window, cx| {
270 if let Some(restore) = &restore {
271 restore.focus(window, cx);
272 }
273 handler(window, cx);
274 }),
275 ));
276 self
277 }
278}
279
280impl RenderOnce for Chip {
281 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
282 use ColorRole::*;
283 let selectable = matches!(self.variant, ChipVariant::Filter | ChipVariant::Input);
284 let selected = selectable && self.selected;
285 let tonal = selectable && self.tonal;
286 let elevated = self.elevated && self.variant != ChipVariant::Input;
287 let split = selectable && self.remove.is_some();
288 let theme = window_material_theme(window, cx).clone();
289 let direction = theme.layout.direction;
290 let theme_color = |role| color(theme.colors.color(role));
291 let on_surface = theme_color(OnSurface);
292 let colors = self.colors.for_state(self.disabled, selected);
293 let foreground = if selected {
294 OnSecondaryContainer
295 } else if self.variant == ChipVariant::Assist {
296 OnSurface
297 } else {
298 OnSurfaceVariant
299 };
300 let label_color = colors.label.unwrap_or_else(|| {
301 if self.disabled {
302 on_surface.opacity(0.38)
303 } else {
304 theme_color(foreground)
305 }
306 });
307 let leading_color = colors.leading.unwrap_or_else(|| {
308 if self.disabled {
309 on_surface.opacity(0.38)
310 } else {
311 theme_color(match (self.variant, selected, tonal) {
312 (ChipVariant::Input, false, _) | (ChipVariant::Filter, false, true) => {
313 OnSurfaceVariant
314 }
315 (ChipVariant::Filter, true, _) => OnSecondaryContainer,
316 _ => Primary,
317 })
318 }
319 });
320 let trailing_color = colors.trailing.unwrap_or_else(|| {
321 if self.disabled {
322 on_surface.opacity(0.38)
323 } else if selected {
324 theme_color(OnSecondaryContainer)
325 } else {
326 theme_color(OnSurfaceVariant)
327 }
328 });
329 let effects = theme.motion.spec(
330 MotionKind::Effects,
331 MotionSpeed::Fast,
332 cx.reduce_motion() || self.disabled,
333 );
334 let selection = if selectable {
335 animate(
336 (self.id.clone(), "chip-tint"),
337 f32::from(selected),
338 effects,
339 window,
340 cx,
341 )
342 .clamp(0., 1.)
343 } else {
344 0.
345 };
346 let idle = self.colors.enabled.container.unwrap_or_else(|| {
347 if elevated {
348 theme_color(SurfaceContainerLow)
349 } else {
350 theme_color(SecondaryContainer).opacity(0.)
351 }
352 });
353 let checked = self
354 .colors
355 .selected
356 .container
357 .unwrap_or_else(|| theme_color(SecondaryContainer));
358 let container = if self.disabled {
359 colors
360 .container
361 .unwrap_or_else(|| on_surface.opacity(if selected || elevated { 0.12 } else { 0. }))
362 } else if selection == 0. {
363 idle
364 } else if selection == 1. {
365 checked
366 } else {
367 crate::motion::mix(idle, checked, selection)
368 };
369 let border_color = colors
370 .border
371 .or(self.border.map(|border| border.color))
372 .unwrap_or_else(|| {
373 if self.disabled {
374 on_surface.opacity(0.12)
375 } else {
376 theme_color(OutlineVariant)
377 }
378 });
379 let border_width = self
380 .border
381 .map_or(px(f32::from(!elevated && !selected)), |border| {
382 finite_length(border.width)
383 });
384 let style = ActionStyle {
385 background: None,
386 background_color: None,
387 foreground,
388 disabled: DisabledStyle {
389 foreground: OnSurface,
390 background: None,
391 outline: (OnSurface, 0.12),
392 },
393 height: 32.,
394 min_width: 0.,
395 corner: if tonal {
396 CornerRole::Medium
397 } else {
398 CornerRole::Small
399 },
400 pressed_corner: CornerRole::Small,
401 selected_corner: if tonal {
402 Some(CornerRole::Full)
403 } else if selectable && self.shapes.checked.is_some() {
404 Some(CornerRole::Small)
405 } else {
406 None
407 },
408 corner_motion: (MotionKind::Spatial, MotionSpeed::Fast),
409 outline: 0.,
410 elevation: if elevated {
411 Elevation::Level1
412 } else {
413 Elevation::Level0
414 },
415 hover_elevation: if elevated {
416 Elevation::Level2
417 } else if selected && self.variant == ChipVariant::Filter {
418 Elevation::Level1
419 } else {
420 Elevation::Level0
421 },
422 };
423 let dragged_elevation = self.elevations.dragged.or(Some(Elevation::Level4));
424 let layout = ActionLayout {
425 tab_stop: true,
426 dragged: self.dragged,
427 dragged_elevation: (!split).then_some(dragged_elevation).flatten(),
428 appearance: ButtonStyle {
429 shapes: self.shapes,
430 colors: action_colors(
431 label_color,
432 if split {
433 gpui::transparent_black()
434 } else {
435 container
436 },
437 ),
438 border: (!split).then_some(ButtonBorder {
439 width: border_width,
440 color: border_color,
441 }),
442 elevations: if split {
443 ButtonElevations::default()
444 } else {
445 self.elevations.button()
446 },
447 },
448 ..Default::default()
449 };
450
451 let avatar = (self.variant == ChipVariant::Input)
452 .then_some(self.avatar)
453 .flatten();
454 let has_avatar = avatar.is_some();
455 let filter_mark = if self.variant == ChipVariant::Filter && self.leading.is_none() {
456 selection
457 } else {
458 0.
459 };
460 let leading = avatar
461 .map(|avatar| {
462 div()
463 .size(px(24.))
464 .flex_none()
465 .rounded_full()
466 .overflow_hidden()
467 .text_color(leading_color)
468 .child(icon_slot(avatar, 24.))
469 .into_any_element()
470 })
471 .or_else(|| {
472 self.leading.map(|leading| {
473 div()
474 .flex_none()
475 .text_color(leading_color)
476 .child(icon_slot(leading, 18.))
477 .into_any_element()
478 })
479 })
480 .or_else(|| {
481 (filter_mark > 0.).then(|| {
482 div()
483 .w((px(18.) + self.spacing) * filter_mark)
484 .flex_none()
485 .overflow_hidden()
486 .opacity(filter_mark)
487 .text_color(leading_color)
488 .when(direction == Direction::Rtl, |slot| {
489 slot.flex().justify_end()
490 })
491 .child(icon_slot(
492 Icon::new(IconName::Check).into_any_element(),
493 18.,
494 ))
495 .into_any_element()
496 })
497 });
498 let trailing = self
499 .trailing
500 .filter(|_| self.variant != ChipVariant::Suggestion)
501 .map(|content| {
502 div()
503 .flex_none()
504 .text_color(trailing_color)
505 .text_size(px(18.))
506 .child(content)
507 .into_any_element()
508 });
509 let padding = self.padding.unwrap_or_else(|| ButtonPadding {
510 start: px(if has_avatar {
511 4.
512 } else if filter_mark > 0. {
513 16. - 8. * filter_mark
514 } else if leading.is_some() {
515 8.
516 } else {
517 16.
518 }),
519 end: if split {
520 self.spacing
521 } else if trailing.is_some() {
522 px(8.)
523 } else {
524 px(16.)
525 },
526 ..Default::default()
527 });
528 let label = self.content.unwrap_or_else(|| {
529 crate::text::single_line(
530 self.label.clone(),
531 TypeRole::LabelLarge.style(TypographyEmphasis::Baseline),
532 1.,
533 label_color,
534 (None, 1., 1.),
535 window,
536 cx,
537 )
538 .into_any_element()
539 });
540 let row = div()
541 .id(self.id.clone())
542 .relative()
543 .flex()
544 .min_w_0()
545 .items_center()
546 .when(direction == Direction::Rtl, Styled::flex_row_reverse);
547 let (trailing, remove_content) = if split {
548 (None, trailing)
549 } else {
550 (trailing, None)
551 };
552 let content = div()
553 .relative()
554 .flex()
555 .items_center()
556 .min_w_0()
557 .text_size(px(14.))
558 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
559 .pt(padding.top)
560 .pb(padding.bottom);
561 let mut content = logical_edges(
562 content,
563 padding.start,
564 if split { self.spacing } else { padding.end },
565 direction,
566 )
567 .children(leading)
568 .when(filter_mark == 0., |row| row.gap(self.spacing))
569 .child(label)
570 .children(trailing.map(|trailing| {
571 if filter_mark > 0. {
572 logical_edges(div(), self.spacing, px(0.), direction)
573 .child(trailing)
574 .into_any_element()
575 } else {
576 trailing
577 }
578 }));
579 let visual_height = Rc::new(Cell::new(px(theme
580 .layout
581 .density
582 .visual_size(style.height))));
583 if split {
584 content = content.child(measure_height(visual_height.clone()));
585 }
586 let primary = ActionControl {
587 id: ElementId::from((self.id.clone(), "activate")),
588 label: self.label,
589 focus: None,
590 disabled: self.disabled,
591 action: if selectable {
592 Action::Toggle {
593 selected,
594 on_change: self.on_change,
595 }
596 } else {
597 Action::Invoke(self.on_activate)
598 },
599 style: if split {
600 split_action_style(style, 0.)
601 } else {
602 style
603 },
604 content: content.into_any_element(),
605 };
606 let tracker = self
607 .interaction_source
608 .as_ref()
609 .map(|source| InteractionSource::track(source, &self.id, window, cx));
610 if let Some((label, on_remove)) = self.remove.filter(|_| selectable) {
611 let remove = ActionControl {
612 id: ElementId::from((self.id.clone(), "remove")),
613 label,
614 focus: None,
615 disabled: self.disabled,
616 action: Action::Invoke(Some(on_remove)),
617 style: split_action_style(style, 32.),
618 content: logical_edges(
619 div().relative().pt(padding.top).pb(padding.bottom),
620 px(0.),
621 self.padding.map_or(px(0.), |padding| padding.end),
622 direction,
623 )
624 .child(remove_content.unwrap_or_else(|| {
625 icon_slot(Icon::new(IconName::Close).into_any_element(), 18.).into_any_element()
626 }))
627 .child(measure_height(visual_height.clone()))
628 .into_any_element(),
629 };
630 let primary_state = primary.interaction_snapshot(self.dragged, window, cx);
631 let remove_state = remove.interaction_snapshot(self.dragged, window, cx);
632 let mut interaction = primary_state;
633 interaction.hovered |= remove_state.hovered;
634 interaction.pressed |= remove_state.pressed;
635 interaction.focus_visible |= remove_state.focus_visible;
636 let surface = SplitSurface {
637 id: self.id,
638 style,
639 layout,
640 direction,
641 selected,
642 container,
643 border: ButtonBorder {
644 width: border_width,
645 color: border_color,
646 },
647 elevations: self.elevations.button(),
648 dragged_elevation,
649 visual_height,
650 }
651 .render(interaction, window, cx);
652 row.child(surface)
653 .child(primary.render_with_tracker(1., layout, tracker, window, cx))
654 .child(remove.render_with_tracker(
655 1.,
656 ActionLayout {
657 appearance: ButtonStyle {
658 colors: action_colors(trailing_color, gpui::transparent_black()),
659 ..Default::default()
660 },
661 ..layout
662 },
663 None,
664 window,
665 cx,
666 ))
667 } else {
668 row.child(primary.render_with_tracker(1., layout, tracker, window, cx))
669 }
670 }
671}
672
673fn logical_edges(
674 element: gpui::Div,
675 start: Pixels,
676 end: Pixels,
677 direction: Direction,
678) -> gpui::Div {
679 if direction == Direction::Rtl {
680 element.pl(end).pr(start)
681 } else {
682 element.pl(start).pr(end)
683 }
684}
685
686fn action_colors(label: Hsla, container: Hsla) -> ButtonColors {
687 ButtonColors {
688 container: Some(container),
689 content: Some(label),
690 disabled_container: Some(container),
691 disabled_content: Some(label),
692 checked_container: Some(container),
693 checked_content: Some(label),
694 }
695}
696
697fn split_action_style(style: ActionStyle, min_width: f32) -> ActionStyle {
698 ActionStyle {
699 min_width,
700 elevation: Elevation::Level0,
701 hover_elevation: Elevation::Level0,
702 ..style
703 }
704}
705
706fn measure_height(height: Rc<Cell<Pixels>>) -> gpui::Canvas<()> {
707 canvas(
708 move |bounds, _, _| height.set(height.get().max(bounds.size.height)),
709 |_, (), _, _| {},
710 )
711 .absolute()
712 .inset_0()
713}
714
715struct SplitSurface {
717 id: ElementId,
718 style: ActionStyle,
719 layout: ActionLayout,
720 direction: Direction,
721 selected: bool,
722 container: Hsla,
723 border: ButtonBorder,
724 elevations: ButtonElevations,
725 dragged_elevation: Option<Elevation>,
726 visual_height: Rc<Cell<Pixels>>,
727}
728
729impl SplitSurface {
730 fn render(
731 self,
732 state: InteractionState,
733 window: &mut Window,
734 cx: &mut App,
735 ) -> impl IntoElement {
736 let theme = window_material_theme(window, cx);
737 let shadow = color(theme.colors.color(ColorRole::Shadow));
738 let effects = theme
739 .motion
740 .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion());
741 let spatial = theme
742 .motion
743 .spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion());
744 let pressed = animate(
745 (self.id.clone(), "chip-press"),
746 f32::from(state.pressed),
747 spatial,
748 window,
749 cx,
750 )
751 .clamp(0., 1.);
752 let selected = if self.style.selected_corner.is_some() {
753 animate(
754 (self.id.clone(), "chip-selection"),
755 f32::from(self.selected),
756 spatial,
757 window,
758 cx,
759 )
760 .clamp(0., 1.)
761 } else {
762 0.
763 };
764 let default_elevation = if state.disabled {
765 Elevation::Level0
766 } else if state.hovered && !state.pressed {
767 self.style.hover_elevation
768 } else {
769 self.style.elevation
770 };
771 let elevation = if state.dragged {
772 self.dragged_elevation
773 } else {
774 self.elevations.for_state(state)
775 }
776 .unwrap_or(default_elevation);
777 let elevation = animate(
778 (self.id.clone(), "chip-elevation"),
779 elevation.dp(),
780 effects,
781 window,
782 cx,
783 )
784 .max(0.);
785 let outline = animate(
786 (self.id.clone(), "chip-outline"),
787 f32::from(self.border.width),
788 effects,
789 window,
790 cx,
791 )
792 .max(0.);
793 canvas(
794 |_, _, _| (),
795 move |mut bounds, (), window, _| {
796 let height = self.visual_height.get().min(bounds.size.height);
797 bounds.origin += point(px(0.), (bounds.size.height - height) / 2.);
798 bounds.size.height = height;
799 let shape =
800 interpolated_corners(bounds, self.style, selected, pressed, 1., self.layout);
801 let [top_left, top_right, bottom_right, bottom_left] = shape
802 .radii(
803 f32::from(bounds.size.width),
804 f32::from(bounds.size.height),
805 self.direction,
806 )
807 .map(px);
808 let radii = Corners {
809 top_left,
810 top_right,
811 bottom_right,
812 bottom_left,
813 };
814 if elevation > 0. {
815 window.paint_drop_shadows(
816 bounds,
817 radii,
818 &elevation_shadows(elevation, 1., shadow),
819 );
820 }
821 if self.container.a > 0. || outline > 0. {
822 window.paint_quad(quad(
823 bounds,
824 radii,
825 self.container,
826 px(outline),
827 if outline > 0. {
828 self.border.color
829 } else {
830 gpui::transparent_black()
831 },
832 BorderStyle::Solid,
833 ));
834 }
835 },
836 )
837 .absolute()
838 .inset_0()
839 }
840}