Skip to main content

gpui_material_components/
avatar.rs

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