1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 AnyElement, App, ElementId, Hsla, ImageSource, InteractiveElement, IntoElement, ObjectFit,
5 ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
6 StyledImage, Window, div, img, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{color, current_material_theme, text_style};
10use gpui_material_theme::{ColorRole, CornerShape, TypeRole, TypographyEmphasis};
11
12#[derive(Clone, Copy, Debug, Default, PartialEq)]
14pub enum AvatarSize {
15 ExtraSmall,
16 Small,
17 #[default]
18 Medium,
19 Large,
20 ExtraLarge,
21 Custom(Pixels),
22}
23
24impl AvatarSize {
25 pub fn pixels(self) -> Pixels {
27 match self {
28 Self::ExtraSmall => px(24.),
29 Self::Small => px(32.),
30 Self::Medium => px(40.),
31 Self::Large => px(48.),
32 Self::ExtraLarge => px(64.),
33 Self::Custom(size) => {
34 let value = f32::from(size);
35 if value.is_finite() && value > 0. {
36 size
37 } else {
38 px(40.)
39 }
40 }
41 }
42 }
43
44 fn typography_role(self) -> TypeRole {
45 let side = f32::from(self.pixels());
46 if side < 28. {
47 TypeRole::LabelSmall
48 } else if side < 36. {
49 TypeRole::LabelMedium
50 } else if side < 44. {
51 TypeRole::TitleSmall
52 } else if side < 56. {
53 TypeRole::TitleMedium
54 } else {
55 TypeRole::HeadlineSmall
56 }
57 }
58
59 fn icon_size(self) -> Pixels {
60 let side = f32::from(self.pixels());
61 px((side * 0.55).round().clamp(12., side))
62 }
63}
64
65#[derive(Clone, Copy, Debug, Default, PartialEq)]
67pub enum AvatarShape {
68 #[default]
69 Circle,
70 Rounded(CornerShape),
71}
72
73#[derive(Clone, Copy, Debug, Default, PartialEq)]
75pub struct AvatarColors {
76 pub container: Option<Hsla>,
77 pub content: Option<Hsla>,
78 pub border: Option<Hsla>,
79}
80
81enum AvatarContent {
82 Initials(SharedString),
83 Icon(AnyElement),
84 Image {
85 source: ImageSource,
86 fallback: Option<AnyElement>,
87 },
88 Custom(AnyElement),
89}
90
91#[derive(IntoElement)]
93pub struct Avatar {
94 content: AvatarContent,
95 size: AvatarSize,
96 shape: AvatarShape,
97 container_role: ColorRole,
98 content_role: ColorRole,
99 colors: AvatarColors,
100 border_width: Pixels,
101 accessible_label: Option<(ElementId, SharedString)>,
102}
103
104impl Avatar {
105 pub fn initials(text: impl Into<SharedString>) -> Self {
107 Self::with_content(AvatarContent::Initials(format_initials(&text.into())))
108 }
109
110 pub fn icon(icon: impl IntoElement) -> Self {
112 Self::with_content(AvatarContent::Icon(icon.into_any_element()))
113 }
114
115 pub fn image(source: impl Into<ImageSource>) -> Self {
117 Self::with_content(AvatarContent::Image {
118 source: source.into(),
119 fallback: None,
120 })
121 }
122
123 pub fn custom(content: impl IntoElement) -> Self {
125 Self::with_content(AvatarContent::Custom(content.into_any_element()))
126 }
127
128 fn with_content(content: AvatarContent) -> Self {
129 Self {
130 content,
131 size: AvatarSize::default(),
132 shape: AvatarShape::default(),
133 container_role: ColorRole::PrimaryContainer,
134 content_role: ColorRole::OnPrimaryContainer,
135 colors: AvatarColors::default(),
136 border_width: px(0.),
137 accessible_label: None,
138 }
139 }
140
141 pub fn fallback(mut self, fallback: impl IntoElement) -> Self {
143 if let AvatarContent::Image { fallback: slot, .. } = &mut self.content {
144 *slot = Some(fallback.into_any_element());
145 }
146 self
147 }
148
149 pub fn size(mut self, size: AvatarSize) -> Self {
151 self.size = size;
152 self
153 }
154
155 pub fn shape(mut self, shape: AvatarShape) -> Self {
157 self.shape = shape;
158 self
159 }
160
161 pub fn color_role(mut self, container: ColorRole, content: ColorRole) -> Self {
163 self.container_role = container;
164 self.content_role = content;
165 self
166 }
167
168 pub fn colors(mut self, colors: AvatarColors) -> Self {
170 self.colors = colors;
171 self
172 }
173
174 pub fn border(mut self, width: Pixels) -> Self {
176 let value = f32::from(width);
177 self.border_width = if value.is_finite() && value >= 0. {
178 width
179 } else {
180 px(0.)
181 };
182 self
183 }
184
185 pub fn accessible_label(
187 mut self,
188 id: impl Into<ElementId>,
189 label: impl Into<SharedString>,
190 ) -> Self {
191 self.accessible_label = Some((id.into(), label.into()));
192 self
193 }
194}
195
196fn format_initials(text: &str) -> SharedString {
197 let trimmed = text.trim();
198 if trimmed.is_empty() {
199 return SharedString::default();
200 }
201 let mut words = trimmed.split_whitespace();
202 let first = words.next().unwrap_or_default();
203 if let Some(second) = words.next() {
204 let mut out = String::new();
205 if let Some(ch) = first.chars().next() {
206 out.extend(ch.to_uppercase());
207 }
208 if let Some(ch) = second.chars().next() {
209 out.extend(ch.to_uppercase());
210 }
211 return out.into();
212 }
213 let mut out = String::new();
214 for ch in first.chars().take(2) {
215 out.extend(ch.to_uppercase());
216 }
217 out.into()
218}
219
220fn resolve_radii(
221 shape: AvatarShape,
222 side: Pixels,
223 direction: gpui_material_theme::Direction,
224) -> [Pixels; 4] {
225 match shape {
226 AvatarShape::Circle => [side * 0.5; 4],
227 AvatarShape::Rounded(corners) => {
228 let extent = f32::from(side);
229 corners.radii(extent, extent, direction).map(px)
230 }
231 }
232}
233
234impl RenderOnce for Avatar {
235 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
236 let theme = current_material_theme(window, cx);
237 let side = self.size.pixels();
238 let direction = theme.layout.direction;
239 let [tl, tr, br, bl] = resolve_radii(self.shape, side, direction);
240 let container_color = self
241 .colors
242 .container
243 .unwrap_or_else(|| color(theme.colors.color(self.container_role)));
244 let content_color = self
245 .colors
246 .content
247 .unwrap_or_else(|| color(theme.colors.color(self.content_role)));
248 let border_color = self
249 .colors
250 .border
251 .unwrap_or_else(|| color(theme.colors.color(ColorRole::OutlineVariant)));
252 let typography = self
253 .size
254 .typography_role()
255 .style(TypographyEmphasis::Baseline);
256 let icon_size = self.size.icon_size();
257
258 let base = div()
259 .relative()
260 .flex_none()
261 .size(side)
262 .overflow_hidden()
263 .rounded_tl(tl)
264 .rounded_tr(tr)
265 .rounded_br(br)
266 .rounded_bl(bl)
267 .bg(container_color)
268 .text_color(content_color)
269 .flex()
270 .items_center()
271 .justify_center();
272
273 let body = match self.content {
274 AvatarContent::Initials(text) => base.child(crate::text::single_line(
275 text,
276 typography,
277 1.,
278 content_color,
279 (None, 1., 1.),
280 window,
281 cx,
282 )),
283 AvatarContent::Icon(icon) => base.text_size(icon_size).child(icon),
284 AvatarContent::Image { source, fallback } => {
285 let mut image = img(source)
286 .size_full()
287 .object_fit(ObjectFit::Cover)
288 .rounded_tl(tl)
289 .rounded_tr(tr)
290 .rounded_br(br)
291 .rounded_bl(bl);
292 if let Some(fallback) = fallback {
293 let slot = Rc::new(RefCell::new(Some(fallback)));
294 let loading_slot = slot.clone();
295 let error_slot = slot;
296 image = image
297 .with_loading(move || {
298 div()
299 .size_full()
300 .flex()
301 .items_center()
302 .justify_center()
303 .children(loading_slot.borrow_mut().take())
304 .into_any_element()
305 })
306 .with_fallback(move || {
307 div()
308 .size_full()
309 .flex()
310 .items_center()
311 .justify_center()
312 .children(error_slot.borrow_mut().take())
313 .into_any_element()
314 });
315 }
316 text_style(base, typography, 1., window, cx).child(image)
317 }
318 AvatarContent::Custom(content) => {
319 text_style(base, typography, 1., window, cx).child(content)
320 }
321 };
322
323 let body = body.when(self.border_width > px(0.), |avatar| {
324 avatar.child(
325 div()
326 .absolute()
327 .inset_0()
328 .rounded_tl(tl)
329 .rounded_tr(tr)
330 .rounded_br(br)
331 .rounded_bl(bl)
332 .border(self.border_width)
333 .border_color(border_color),
334 )
335 });
336
337 if let Some((id, label)) = self.accessible_label {
338 body.id(id)
339 .test_support()
340 .role(Role::Image)
341 .aria_label(label)
342 .into_any_element()
343 } else {
344 body.into_any_element()
345 }
346 }
347}
348
349type OverflowContent = Box<dyn FnOnce(usize) -> AnyElement>;
350
351const DEFAULT_RING_WIDTH: Pixels = px(2.);
352
353#[derive(IntoElement)]
356pub struct AvatarGroup {
357 id: ElementId,
358 avatars: Vec<Avatar>,
359 size: AvatarSize,
360 max_visible: Option<usize>,
361 overlap: Option<Pixels>,
362 ring_width: Pixels,
363 ring_role: ColorRole,
364 ring_color: Option<Hsla>,
365 overflow_colors: AvatarColors,
366 overflow_content: Option<OverflowContent>,
367 accessible_label: Option<SharedString>,
368}
369
370impl AvatarGroup {
371 pub fn new(id: impl Into<ElementId>, avatars: impl IntoIterator<Item = Avatar>) -> Self {
373 Self {
374 id: id.into(),
375 avatars: avatars.into_iter().collect(),
376 size: AvatarSize::default(),
377 max_visible: None,
378 overlap: None,
379 ring_width: DEFAULT_RING_WIDTH,
380 ring_role: ColorRole::Surface,
381 ring_color: None,
382 overflow_colors: AvatarColors::default(),
383 overflow_content: None,
384 accessible_label: None,
385 }
386 }
387
388 pub fn size(mut self, size: AvatarSize) -> Self {
391 self.size = size;
392 self
393 }
394
395 pub fn max_visible(mut self, count: usize) -> Self {
397 self.max_visible = Some(count);
398 self
399 }
400
401 pub fn overlap(mut self, pixels: Pixels) -> Self {
404 self.overlap = Some(pixels);
405 self
406 }
407
408 pub fn ring_width(mut self, pixels: Pixels) -> Self {
411 let value = f32::from(pixels);
412 self.ring_width = if value.is_finite() && value >= 0. {
413 pixels
414 } else {
415 px(0.)
416 };
417 self
418 }
419
420 pub fn ring_color(mut self, color: impl Into<Hsla>) -> Self {
422 self.ring_color = Some(color.into());
423 self
424 }
425
426 pub fn ring_role(mut self, role: ColorRole) -> Self {
429 self.ring_role = role;
430 self.ring_color = None;
431 self
432 }
433
434 pub fn overflow_colors(mut self, colors: AvatarColors) -> Self {
437 self.overflow_colors = colors;
438 self
439 }
440
441 pub fn overflow_content<E: IntoElement>(
443 mut self,
444 content: impl FnOnce(usize) -> E + 'static,
445 ) -> Self {
446 self.overflow_content = Some(Box::new(move |count| content(count).into_any_element()));
447 self
448 }
449
450 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
452 self.accessible_label = Some(label.into());
453 self
454 }
455}
456
457fn max_overlap_for_diameter(diameter: f32) -> f32 {
458 if diameter > 1. { diameter - 1. } else { 0. }
459}
460
461fn default_overlap(size: AvatarSize) -> Pixels {
462 let diameter = f32::from(size.pixels());
463 px((diameter * 0.25)
464 .round()
465 .clamp(0., max_overlap_for_diameter(diameter)))
466}
467
468fn resolve_overlap(size: AvatarSize, overlap: Option<Pixels>) -> Pixels {
469 let diameter = f32::from(size.pixels());
470 let upper = max_overlap_for_diameter(diameter);
471 match overlap {
472 Some(value) => {
473 let raw = f32::from(value);
474 if raw.is_finite() {
475 px(raw.clamp(0., upper))
476 } else {
477 default_overlap(size)
478 }
479 }
480 None => default_overlap(size),
481 }
482}
483
484fn split_visible(total: usize, max_visible: Option<usize>) -> (usize, usize) {
485 match max_visible {
486 Some(limit) if total > limit => (limit, total - limit),
487 _ => (total, 0),
488 }
489}
490
491impl RenderOnce for AvatarGroup {
492 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
493 let theme = current_material_theme(window, cx);
494 let direction = theme.layout.direction;
495 let is_rtl = direction == gpui_material_theme::Direction::Rtl;
496 let side = self.size.pixels();
497 let overlap = resolve_overlap(self.size, self.overlap);
498 let ring_width = self.ring_width;
499 let ring_color = self
500 .ring_color
501 .unwrap_or_else(|| color(theme.colors.color(self.ring_role)));
502 let (visible_count, overflow_count) = split_visible(self.avatars.len(), self.max_visible);
503 let overflow_shape = self
504 .avatars
505 .first()
506 .map_or(AvatarShape::Circle, |avatar| avatar.shape);
507
508 let mut items: Vec<Avatar> = self
509 .avatars
510 .into_iter()
511 .take(visible_count)
512 .map(|mut avatar| {
513 avatar.size = self.size;
514 avatar
515 })
516 .collect();
517
518 if overflow_count > 0 {
519 let overflow_avatar = match self.overflow_content {
520 Some(render) => Avatar::custom(render(overflow_count)),
521 None => Avatar::with_content(AvatarContent::Initials(
522 format!("+{overflow_count}").into(),
523 )),
524 }
525 .size(self.size)
526 .shape(overflow_shape)
527 .color_role(
528 ColorRole::SurfaceContainerHighest,
529 ColorRole::OnSurfaceVariant,
530 )
531 .colors(self.overflow_colors);
532 items.push(overflow_avatar);
533 }
534
535 let mut row = div()
536 .id(self.id)
537 .test_support()
538 .flex()
539 .flex_row()
540 .items_center()
541 .when(is_rtl, Styled::flex_row_reverse)
542 .when_some(self.accessible_label, |row, label| {
543 row.role(Role::Group).aria_label(label)
544 });
545
546 for (index, avatar) in items.into_iter().enumerate() {
547 let [tl, tr, br, bl] = resolve_radii(avatar.shape, side, direction);
548 let slot = if ring_width > px(0.) {
549 let outer_side = side + ring_width * 2.;
550 let [otl, otr, obr, obl] = match avatar.shape {
551 AvatarShape::Circle => [outer_side * 0.5; 4],
552 AvatarShape::Rounded(_) => [
553 tl + ring_width,
554 tr + ring_width,
555 br + ring_width,
556 bl + ring_width,
557 ],
558 };
559 div()
560 .flex_none()
561 .size(outer_side)
562 .flex()
563 .items_center()
564 .justify_center()
565 .bg(ring_color)
566 .border(ring_width)
567 .border_color(ring_color)
568 .rounded_tl(otl)
569 .rounded_tr(otr)
570 .rounded_br(obr)
571 .rounded_bl(obl)
572 .child(avatar)
573 } else {
574 div().flex_none().size(side).child(avatar)
575 };
576 let slot = if index > 0 && overlap > px(0.) {
577 if is_rtl {
578 slot.mr(-overlap)
579 } else {
580 slot.ml(-overlap)
581 }
582 } else {
583 slot
584 };
585 row = row.child(slot);
586 }
587
588 row
589 }
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595 use gpui_material_theme::Direction;
596
597 #[test]
598 fn initials_formatting_trims_uppercases_and_bounds_length() {
599 assert_eq!(format_initials("Ada Lovelace"), "AL");
600 assert_eq!(format_initials(" grace hopper "), "GH");
601 assert_eq!(format_initials("al"), "AL");
602 assert_eq!(format_initials("a"), "A");
603 assert_eq!(format_initials("Alice"), "AL");
604 assert_eq!(format_initials(" "), "");
605 }
606
607 #[test]
608 fn avatar_size_presets_and_typography_scale_monotonically() {
609 assert_eq!(AvatarSize::ExtraSmall.pixels(), px(24.));
610 assert_eq!(AvatarSize::Small.pixels(), px(32.));
611 assert_eq!(AvatarSize::Medium.pixels(), px(40.));
612 assert_eq!(AvatarSize::Large.pixels(), px(48.));
613 assert_eq!(AvatarSize::ExtraLarge.pixels(), px(64.));
614 assert_eq!(AvatarSize::Custom(px(52.)).pixels(), px(52.));
615 assert_eq!(AvatarSize::Custom(px(-4.)).pixels(), px(40.));
616 assert_eq!(AvatarSize::Custom(px(f32::NAN)).pixels(), px(40.));
617
618 assert_eq!(
619 AvatarSize::ExtraSmall.typography_role(),
620 TypeRole::LabelSmall
621 );
622 assert_eq!(AvatarSize::Small.typography_role(), TypeRole::LabelMedium);
623 assert_eq!(AvatarSize::Medium.typography_role(), TypeRole::TitleSmall);
624 assert_eq!(AvatarSize::Large.typography_role(), TypeRole::TitleMedium);
625 assert_eq!(
626 AvatarSize::ExtraLarge.typography_role(),
627 TypeRole::HeadlineSmall
628 );
629 }
630
631 #[test]
632 fn rounded_avatar_shape_mirrors_asymmetric_corners_in_rtl() {
633 let shape = AvatarShape::Rounded(CornerShape::Radii([12., 4., 8., 2.]));
634 let ltr = resolve_radii(shape, px(40.), Direction::Ltr);
635 let rtl = resolve_radii(shape, px(40.), Direction::Rtl);
636 assert_eq!(ltr, [px(12.), px(4.), px(8.), px(2.)]);
637 assert_eq!(rtl, [px(4.), px(12.), px(2.), px(8.)]);
638 }
639
640 #[test]
641 fn avatar_group_overlap_defaults_and_clamps_within_diameter() {
642 assert_eq!(resolve_overlap(AvatarSize::ExtraSmall, None), px(6.));
643 assert_eq!(resolve_overlap(AvatarSize::Small, None), px(8.));
644 assert_eq!(resolve_overlap(AvatarSize::Medium, None), px(10.));
645 assert_eq!(resolve_overlap(AvatarSize::Large, None), px(12.));
646 assert_eq!(resolve_overlap(AvatarSize::ExtraLarge, None), px(16.));
647
648 assert_eq!(resolve_overlap(AvatarSize::Medium, Some(px(14.))), px(14.));
649 assert_eq!(resolve_overlap(AvatarSize::Medium, Some(px(-5.))), px(0.));
650 assert_eq!(resolve_overlap(AvatarSize::Medium, Some(px(80.))), px(39.));
651 assert_eq!(
652 resolve_overlap(AvatarSize::Medium, Some(px(f32::NAN))),
653 px(10.)
654 );
655 assert_eq!(
656 resolve_overlap(AvatarSize::Medium, Some(px(f32::INFINITY))),
657 px(10.)
658 );
659 }
660
661 #[test]
662 fn avatar_group_split_visible_computes_overflow_counts() {
663 assert_eq!(split_visible(5, None), (5, 0));
664 assert_eq!(split_visible(5, Some(3)), (3, 2));
665 assert_eq!(split_visible(3, Some(3)), (3, 0));
666 assert_eq!(split_visible(2, Some(5)), (2, 0));
667 assert_eq!(split_visible(4, Some(0)), (0, 4));
668 assert_eq!(split_visible(0, Some(0)), (0, 0));
669 }
670}