Skip to main content

gpui_material_components/
avatar.rs

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/// 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
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/// A circular or rounded Material avatar displaying initials, an icon, an image, or custom content.
105#[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    /// Displays trimmed, uppercased 1–2 character initials with typography scaled to the avatar size.
119    pub fn initials(text: impl Into<SharedString>) -> Self {
120        Self::with_content(AvatarContent::Initials(format_initials(&text.into())))
121    }
122
123    /// Displays a decorative icon sized proportionally to the avatar.
124    pub fn icon(icon: impl IntoElement) -> Self {
125        Self::with_content(AvatarContent::Icon(icon.into_any_element()))
126    }
127
128    /// Displays an image cropped with `ObjectFit::Cover` and clipped to the avatar shape.
129    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    /// Displays arbitrary caller-supplied visual content clipped to the avatar shape.
137    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    /// Supplies repeatable fallback visual content for `Avatar::image` while loading or if loading fails.
155    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    /// Sets the avatar diameter preset or custom pixel size. Defaults to `AvatarSize::Medium` (40 px).
163    pub fn size(mut self, size: AvatarSize) -> Self {
164        self.size = size;
165        self
166    }
167
168    /// Sets the avatar shape. Defaults to `AvatarShape::Circle`.
169    pub fn shape(mut self, shape: AvatarShape) -> Self {
170        self.shape = shape;
171        self
172    }
173
174    /// Resolves container and content pigments from the window theme's semantic color roles.
175    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    /// Overrides container, content, and border pigments directly.
182    pub fn colors(mut self, colors: AvatarColors) -> Self {
183        self.colors = colors;
184        self
185    }
186
187    /// Draws an inner border stroke around the avatar perimeter in logical pixels.
188    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    /// Exposes the avatar as a named `Role::Image` for assistive technology without adding a focus stop.
199    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/// An overlapping horizontal stack of [`Avatar`] items with surface-matched cutout rings
366/// and an optional `+N` overflow indicator.
367#[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    /// Creates an overlapping stack from an iterator of [`Avatar`] items.
384    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    /// Applies a uniform diameter across all member avatars and the overflow indicator.
401    /// Defaults to `AvatarSize::Medium` (40 px).
402    pub fn size(mut self, size: AvatarSize) -> Self {
403        self.size = size;
404        self
405    }
406
407    /// Limits the number of displayed member avatars before appending a `+N` overflow indicator.
408    pub fn max_visible(mut self, count: usize) -> Self {
409        self.max_visible = Some(count);
410        self
411    }
412
413    /// Sets the positive overlap distance between adjacent avatars in logical pixels.
414    /// Defaults to 25% of the resolved diameter and is clamped to `[0, diameter - 1]`.
415    pub fn overlap(mut self, pixels: Pixels) -> Self {
416        self.overlap = Some(pixels);
417        self
418    }
419
420    /// Sets the surface-matched cutout ring width around each avatar in logical pixels.
421    /// Defaults to `2 px`. Set to `0 px` to omit the ring.
422    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    /// Overrides the cutout ring with an explicit color. Takes precedence over `.ring_role`.
433    pub fn ring_color(mut self, color: impl Into<Hsla>) -> Self {
434        self.ring_color = Some(color.into());
435        self
436    }
437
438    /// Resolves the cutout ring color from the window theme's semantic color role.
439    /// Defaults to `ColorRole::Surface`.
440    pub fn ring_role(mut self, role: ColorRole) -> Self {
441        self.ring_role = role;
442        self.ring_color = None;
443        self
444    }
445
446    /// Overrides container, content, and border pigments on the `+N` overflow indicator.
447    /// Omitted fields use `SurfaceContainerHighest` / `OnSurfaceVariant`.
448    pub fn overflow_colors(mut self, colors: AvatarColors) -> Self {
449        self.overflow_colors = colors;
450        self
451    }
452
453    /// Replaces the default `+N` text inside the overflow avatar with custom visual content.
454    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    /// Exposes a summary `Role::Group` accessible label for the avatar stack without adding focus stops.
463    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}