Skip to main content

arc_ui/data/
avatar_group.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/avatar-group/avatar-group.tsx` & `.module.css`
3//!
4//! P2 Component #23: `avatar-group`
5//!
6//! - Composes [`Avatar`] with `-6px` overlap and `2px surface` separation rings.
7//! - Hovering an avatar floats a pill tooltip above it without shifting any neighbor.
8//! - Overflow chip (`+N`) tracks growth/shrink direction and animates count updates smoothly.
9
10use std::time::Duration;
11
12use arc_motion::{BlurFallback, arc_transition, is_reduced_motion};
13use arc_tokens::{ActiveArcTheme as _, Radii, Typography};
14use gpui_kit::{
15    App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window,
16    base::StyledExt as _, div, prelude::*, px,
17};
18
19use super::avatar::{Avatar, AvatarSize, AvatarStatus};
20
21/// One member rendered inside an [`AvatarGroup`].
22#[derive(Clone)]
23pub struct AvatarGroupMember {
24    pub name: SharedString,
25    pub src: Option<SharedString>,
26    pub status: Option<AvatarStatus>,
27}
28
29impl AvatarGroupMember {
30    pub fn new(name: impl Into<SharedString>) -> Self {
31        Self {
32            name: name.into(),
33            src: None,
34            status: None,
35        }
36    }
37
38    pub fn src(mut self, src: impl Into<SharedString>) -> Self {
39        self.src = Some(src.into());
40        self
41    }
42
43    pub fn status(mut self, status: AvatarStatus) -> Self {
44        self.status = Some(status);
45        self
46    }
47}
48
49#[derive(Clone, Default)]
50struct AvatarGroupInternal {
51    hovered_idx: Option<usize>,
52    last_overflow: usize,
53    overflow_direction: f32,
54    overflow_gen: u64,
55}
56
57/// Arc `AvatarGroup` — overlapping team avatar stack with hover nameplates and animated `+N` overflow.
58#[derive(IntoElement)]
59pub struct AvatarGroup {
60    id: ElementId,
61    members: Vec<AvatarGroupMember>,
62    max: usize,
63    size: AvatarSize,
64    label: SharedString,
65}
66
67impl AvatarGroup {
68    pub fn new(id: impl Into<ElementId>) -> Self {
69        Self {
70            id: id.into(),
71            members: Vec::new(),
72            max: 4,
73            size: AvatarSize::Md,
74            label: "Team members".into(),
75        }
76    }
77
78    pub fn member(mut self, member: AvatarGroupMember) -> Self {
79        self.members.push(member);
80        self
81    }
82
83    pub fn members(mut self, members: impl IntoIterator<Item = AvatarGroupMember>) -> Self {
84        self.members.extend(members);
85        self
86    }
87
88    pub fn max(mut self, max: usize) -> Self {
89        self.max = max;
90        self
91    }
92
93    pub fn size(mut self, size: AvatarSize) -> Self {
94        self.size = match size {
95            AvatarSize::Xl => AvatarSize::Lg,
96            other => other,
97        };
98        self
99    }
100
101    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
102        self.label = label.into();
103        self
104    }
105}
106
107impl RenderOnce for AvatarGroup {
108    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
109        let theme = cx.arc_theme().clone();
110        let colors = theme.colors;
111        let motion = theme.motion;
112        let reduced = is_reduced_motion(cx);
113
114        let visible_count = self.members.len().min(self.max);
115        let overflow = self.members.len().saturating_sub(visible_count);
116
117        let state_id =
118            ElementId::NamedChild(self.id.clone().into(), "__arc-avatar-group-state".into());
119        let internal = window.use_keyed_state(state_id, cx, |_, _| AvatarGroupInternal {
120            hovered_idx: None,
121            last_overflow: overflow,
122            overflow_direction: 1.0,
123            overflow_gen: 0,
124        });
125
126        if internal.read(cx).last_overflow != overflow {
127            internal.update(cx, |s, _| {
128                s.overflow_direction = if overflow < s.last_overflow {
129                    -1.0
130                } else {
131                    1.0
132                };
133                s.last_overflow = overflow;
134                s.overflow_gen = s.overflow_gen.wrapping_add(1);
135            });
136        }
137        let snap = internal.read(cx).clone();
138
139        let dim = self.size.px_size();
140        let overflow_font = match self.size {
141            AvatarSize::Sm => px(10.0),
142            AvatarSize::Md => Typography::TEXT_XS,
143            AvatarSize::Lg | AvatarSize::Xl => Typography::TEXT_SM,
144        };
145
146        let mut row = div()
147            .id(self.id.clone())
148            .h(px(dim))
149            .pl(px(6.0))
150            .flex()
151            .flex_row()
152            .items_center();
153
154        for (idx, member) in self.members.into_iter().take(visible_count).enumerate() {
155            let hovered = snap.hovered_idx == Some(idx);
156            let tip_p = arc_transition(
157                (self.id.clone(), format!("tip-{idx}")),
158                if hovered { 1.0 } else { 0.0 },
159                if reduced {
160                    Duration::ZERO
161                } else {
162                    motion.duration.fast
163                },
164                motion.ease.standard,
165                window,
166                cx,
167            );
168            let int_hover = internal.clone();
169            let member_name = member.name.clone();
170
171            let slot = div()
172                .id(ElementId::NamedChild(
173                    self.id.clone().into(),
174                    SharedString::from(format!("slot-{idx}")),
175                ))
176                .relative()
177                .flex_none()
178                .h(px(dim))
179                .ml(px(-6.0))
180                .flex()
181                .items_center()
182                .on_hover(move |is_in, window, cx| {
183                    int_hover.update(cx, |s, _| {
184                        if *is_in {
185                            s.hovered_idx = Some(idx);
186                        } else if s.hovered_idx == Some(idx) {
187                            s.hovered_idx = None;
188                        }
189                    });
190                    window.refresh();
191                })
192                .child(
193                    Avatar::new(
194                        ElementId::NamedChild(
195                            self.id.clone().into(),
196                            SharedString::from(format!("av-{idx}")),
197                        ),
198                        member.name,
199                    )
200                    .src_opt(member.src)
201                    .status_opt(member.status)
202                    .size(self.size)
203                    .ring_border(true),
204                )
205                .when(hovered || tip_p > 0.02, |this| {
206                    let y_lift = if reduced { 0.0 } else { (1.0 - tip_p) * 3.0 };
207                    this.child(
208                        div()
209                            .absolute()
210                            .bottom(px(dim + 8.0 - y_lift))
211                            .left_0()
212                            .px(px(8.0))
213                            .py(px(3.0))
214                            .rounded(Radii::PILL)
215                            .bg(colors.foreground)
216                            .text_color(colors.background)
217                            .text_size(Typography::TEXT_XS)
218                            .font_medium()
219                            .opacity(tip_p.clamp(0.0, 1.0))
220                            .whitespace_nowrap()
221                            .child(member_name),
222                    )
223                });
224
225            row = row.child(slot);
226        }
227
228        if overflow > 0 {
229            let count_p = if snap.overflow_gen == 0 || reduced {
230                1.0
231            } else {
232                arc_transition(
233                    (self.id.clone(), format!("ov-{}", snap.overflow_gen)),
234                    1.0,
235                    motion.duration.standard,
236                    motion.ease.enter,
237                    window,
238                    cx,
239                )
240            };
241            let blur = BlurFallback::evaluate(motion.blur.subtle * (1.0 - count_p), reduced);
242            let y_shift = if reduced {
243                0.0
244            } else {
245                (1.0 - count_p) * 5.0 * snap.overflow_direction
246            };
247
248            row = row.child(
249                div()
250                    .relative()
251                    .flex_none()
252                    .ml(px(-6.0))
253                    .w(px(dim))
254                    .h(px(dim))
255                    .rounded(Radii::PILL)
256                    .border_2()
257                    .border_color(colors.surface)
258                    .bg(colors.surface_muted)
259                    .overflow_hidden()
260                    .flex()
261                    .items_center()
262                    .justify_center()
263                    .text_size(overflow_font)
264                    .font_medium()
265                    .text_color(colors.text_secondary)
266                    .child(
267                        div()
268                            .mt(px(y_shift))
269                            .opacity((count_p * blur.opacity_multiplier).clamp(0.0, 1.0))
270                            .child(format!("+{overflow}")),
271                    ),
272            );
273        }
274
275        let _ = self.label;
276        row
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
283    use gpui_kit::{Context, Render, TestAppContext, div, px, test::TestWindowExt as _};
284
285    use super::*;
286
287    struct GroupHost {
288        count: usize,
289    }
290
291    impl Render for GroupHost {
292        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
293            let all = [
294                AvatarGroupMember::new("Ada Lovelace").status(AvatarStatus::Online),
295                AvatarGroupMember::new("Elia Kuratli").status(AvatarStatus::Online),
296                AvatarGroupMember::new("Grace Hopper"),
297                AvatarGroupMember::new("Alan Turing").status(AvatarStatus::Offline),
298                AvatarGroupMember::new("Linus Torvalds"),
299                AvatarGroupMember::new("Barbara Liskov"),
300            ];
301            div().w(px(400.0)).p(Spacing::S4).child(
302                AvatarGroup::new("team")
303                    .max(4)
304                    .members(all.into_iter().take(self.count)),
305            )
306        }
307    }
308
309    #[gpui_kit::test]
310    fn avatar_group_renders_and_updates_overflow_cleanly(cx: &mut TestAppContext) {
311        cx.update(|cx| {
312            gpui_kit::init(cx);
313            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
314        });
315        let (view, cx) = cx.add_window_view(|_, _| GroupHost { count: 4 });
316
317        cx.update(|window, cx| {
318            window.render_frame(cx);
319            view.update(cx, |v, cx| {
320                v.count = 6;
321                cx.notify();
322            });
323            window.render_frame(cx);
324            view.update(cx, |v, cx| {
325                v.count = 3;
326                cx.notify();
327            });
328            window.render_frame(cx);
329        });
330    }
331}