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