Skip to main content

arc_ui/data/
avatar.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/avatar/avatar.tsx` & `.module.css`
3//!
4//! P2 Component #22: `avatar`
5//!
6//! - Sizes: `Sm` (28px), `Md` (36px), `Lg` (48px), `Xl` (88px).
7//! - Renders initials fallback or image (`img(src)`), plus an optional presence dot (`Online` /
8//!   `Offline`) that springs in (`scale 0.6 -> 1.0` on `motion.spring.snappy`).
9
10use std::time::Duration;
11
12use arc_motion::{arc_spring, arc_transition, is_reduced_motion};
13use arc_tokens::{ActiveArcTheme as _, Radii, Typography};
14use gpui_kit::{
15    App, ElementId, IntoElement, ObjectFit, ParentElement, RenderOnce, SharedString, Styled,
16    Window, base::StyledExt as _, div, img, prelude::*, px,
17};
18
19/// Diameter preset for [`Avatar`].
20#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
21pub enum AvatarSize {
22    Sm,
23    #[default]
24    Md,
25    Lg,
26    Xl,
27}
28
29impl AvatarSize {
30    pub const fn px_size(self) -> f32 {
31        match self {
32            Self::Sm => 28.0,
33            Self::Md => 36.0,
34            Self::Lg => 48.0,
35            Self::Xl => 88.0,
36        }
37    }
38}
39
40/// Optional online presence dot for [`Avatar`].
41#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42pub enum AvatarStatus {
43    Online,
44    Offline,
45}
46
47/// Extracts up to two uppercase initials from a person's display name.
48pub fn initials_for(name: &str) -> String {
49    name.split_whitespace()
50        .take(2)
51        .filter_map(|part| part.chars().next())
52        .flat_map(char::to_uppercase)
53        .collect()
54}
55
56/// Arc `Avatar` — circular user photo or initials with optional spring-animated status dot.
57#[derive(IntoElement)]
58pub struct Avatar {
59    id: ElementId,
60    name: SharedString,
61    src: Option<SharedString>,
62    size: AvatarSize,
63    status: Option<AvatarStatus>,
64    ring_border: bool,
65}
66
67impl Avatar {
68    pub fn new(id: impl Into<ElementId>, name: impl Into<SharedString>) -> Self {
69        Self {
70            id: id.into(),
71            name: name.into(),
72            src: None,
73            size: AvatarSize::Md,
74            status: None,
75            ring_border: false,
76        }
77    }
78
79    pub fn src(mut self, src: impl Into<SharedString>) -> Self {
80        self.src = Some(src.into());
81        self
82    }
83
84    pub fn src_opt(mut self, src: Option<SharedString>) -> Self {
85        self.src = src;
86        self
87    }
88
89    pub fn size(mut self, size: AvatarSize) -> Self {
90        self.size = size;
91        self
92    }
93
94    pub fn status(mut self, status: AvatarStatus) -> Self {
95        self.status = Some(status);
96        self
97    }
98
99    pub fn status_opt(mut self, status: Option<AvatarStatus>) -> Self {
100        self.status = status;
101        self
102    }
103
104    /// Draws the thicker `2px surface` separation ring used inside [`crate::AvatarGroup`].
105    pub fn ring_border(mut self, ring: bool) -> Self {
106        self.ring_border = ring;
107        self
108    }
109}
110
111impl RenderOnce for Avatar {
112    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
113        let theme = cx.arc_theme().clone();
114        let colors = theme.colors;
115        let motion = theme.motion;
116        let reduced = is_reduced_motion(cx);
117
118        let dim = self.size.px_size();
119        let font_sz = match self.size {
120            AvatarSize::Sm => px(10.0),
121            AvatarSize::Md => Typography::TEXT_XS,
122            AvatarSize::Lg => Typography::TEXT_SM,
123            AvatarSize::Xl => Typography::TEXT_XL,
124        };
125        let (dot_sz, dot_inset) = match self.size {
126            AvatarSize::Sm => (8.0, 0.0),
127            AvatarSize::Md => (10.0, 0.0),
128            AvatarSize::Lg => (12.0, 0.0),
129            AvatarSize::Xl => (14.0, 4.0),
130        };
131
132        let has_status = self.status.is_some();
133        let dot_scale = if reduced {
134            if has_status { 1.0 } else { 0.6 }
135        } else {
136            arc_spring(
137                (self.id.clone(), "status-scale"),
138                if has_status { 1.0 } else { 0.6 },
139                motion.spring.snappy,
140                window,
141                cx,
142            )
143        };
144        let dot_op = arc_transition(
145            (self.id.clone(), "status-op"),
146            if has_status { 1.0 } else { 0.0 },
147            if reduced {
148                Duration::ZERO
149            } else {
150                motion.duration.fast
151            },
152            motion.ease.standard,
153            window,
154            cx,
155        );
156
157        let initials = initials_for(&self.name);
158        let status_bg = match self.status {
159            Some(AvatarStatus::Online) => colors.success,
160            Some(AvatarStatus::Offline) | None => colors.text_muted,
161        };
162
163        div()
164            .id(self.id)
165            .relative()
166            .flex_none()
167            .w(px(dim))
168            .h(px(dim))
169            .rounded(Radii::PILL)
170            .when(self.ring_border, |this| {
171                this.border_2().border_color(colors.surface)
172            })
173            .when(!self.ring_border, |this| {
174                this.border_1().border_color(colors.border)
175            })
176            .bg(colors.surface_muted)
177            .flex()
178            .items_center()
179            .justify_center()
180            .text_size(font_sz)
181            .font_medium()
182            .text_color(colors.foreground)
183            .child(if let Some(src) = self.src {
184                div()
185                    .size_full()
186                    .rounded(Radii::PILL)
187                    .overflow_hidden()
188                    .child(
189                        img(src)
190                            .size_full()
191                            .rounded(Radii::PILL)
192                            .object_fit(ObjectFit::Cover),
193                    )
194            } else {
195                div().child(initials)
196            })
197            .when(has_status || dot_op > 0.02, |this| {
198                let sz = (dot_sz * dot_scale).max(4.0);
199                this.child(
200                    div()
201                        .absolute()
202                        .right(px(dot_inset))
203                        .bottom(px(dot_inset))
204                        .w(px(sz))
205                        .h(px(sz))
206                        .rounded(Radii::PILL)
207                        .border_2()
208                        .border_color(colors.surface)
209                        .bg(status_bg)
210                        .opacity(dot_op.clamp(0.0, 1.0)),
211                )
212            })
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
219    use gpui_kit::{Context, Render, TestAppContext, div, px, test::TestWindowExt as _};
220
221    use super::*;
222
223    struct AvatarHost {
224        status: Option<AvatarStatus>,
225    }
226
227    impl Render for AvatarHost {
228        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
229            div()
230                .w(px(320.0))
231                .p(Spacing::S4)
232                .flex()
233                .gap(Spacing::S3)
234                .child(
235                    Avatar::new("av-1", "Elia Kuratli")
236                        .size(AvatarSize::Lg)
237                        .status_opt(self.status),
238                )
239        }
240    }
241
242    #[test]
243    fn initials_extracts_up_to_two_uppercase_chars() {
244        assert_eq!(initials_for("Elia Kuratli"), "EK");
245        assert_eq!(initials_for("Ada"), "A");
246        assert_eq!(initials_for("Grace Brewster Hopper"), "GB");
247        assert_eq!(initials_for("  "), "");
248    }
249
250    #[gpui_kit::test]
251    fn avatar_renders_and_toggles_status_dot(cx: &mut TestAppContext) {
252        cx.update(|cx| {
253            gpui_kit::init(cx);
254            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
255        });
256        let (view, cx) = cx.add_window_view(|_, _| AvatarHost {
257            status: Some(AvatarStatus::Online),
258        });
259
260        cx.update(|window, cx| {
261            window.render_frame(cx);
262            view.update(cx, |v, cx| {
263                v.status = Some(AvatarStatus::Offline);
264                cx.notify();
265            });
266            window.render_frame(cx);
267            view.update(cx, |v, cx| {
268                v.status = None;
269                cx.notify();
270            });
271            window.render_frame(cx);
272        });
273    }
274}