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