Skip to main content

iced_cube/feedback/
avatar.rs

1//! A small picture of a person or team, with initials when there is no
2//! image.
3//!
4//! [`avatar`] takes a name and shows its [`initials`] on a muted
5//! background. Add an [`image`](Avatar::image) to show a picture instead,
6//! and a [`presence`](Avatar::presence) dot for online status.
7//! [`avatar_group`] overlaps several avatars and counts the ones left over.
8//!
9//! Images are drawn from an [`image::Handle`]. Handles built from pixels
10//! (`Handle::from_rgba`) work as they are; to load PNG or JPEG files, enable
11//! iced's `image` feature in your app. iced's GPU renderer crops images to
12//! the avatar's shape; its software fallback draws them with square corners.
13
14use iced::widget::{Stack, container, image, space, text};
15use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Theme};
16
17use crate::icon::{Glyph, themed};
18use crate::lucide;
19use crate::natural::natural;
20use crate::theme::{Tokens, mix, radius, semibold};
21
22/// Avatar dimensions.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
24pub enum Size {
25    Sm,
26    #[default]
27    Md,
28    Lg,
29    Xl,
30}
31
32impl Size {
33    pub const ALL: [Size; 4] = [Size::Sm, Size::Md, Size::Lg, Size::Xl];
34
35    /// Diameter, initials text size, icon size and presence dot diameter.
36    pub const fn metrics(self) -> Metrics {
37        match self {
38            Size::Sm => Metrics {
39                diameter: 24.0,
40                text: 10.0,
41                icon: 14.0,
42                dot: 8.0,
43            },
44            Size::Md => Metrics {
45                diameter: 32.0,
46                text: 12.0,
47                icon: 16.0,
48                dot: 10.0,
49            },
50            Size::Lg => Metrics {
51                diameter: 40.0,
52                text: 14.0,
53                icon: 20.0,
54                dot: 12.0,
55            },
56            Size::Xl => Metrics {
57                diameter: 56.0,
58                text: 18.0,
59                icon: 28.0,
60                dot: 14.0,
61            },
62        }
63    }
64}
65
66/// Resolved dimensions for a [`Size`].
67#[derive(Debug, Clone, Copy, PartialEq)]
68pub struct Metrics {
69    pub diameter: f32,
70    pub text: f32,
71    pub icon: f32,
72    pub dot: f32,
73}
74
75/// The outline of an avatar.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
77pub enum Shape {
78    /// For people.
79    #[default]
80    Circle,
81    /// Rounded corners, for teams, organisations and bots.
82    Square,
83}
84
85impl Shape {
86    pub const ALL: [Shape; 2] = [Shape::Circle, Shape::Square];
87
88    /// The corner radius at a diameter.
89    pub fn radius(self, diameter: f32) -> f32 {
90        match self {
91            Shape::Circle => diameter / 2.0,
92            Shape::Square => (diameter / 5.0).clamp(radius::SM, radius::LG),
93        }
94    }
95}
96
97/// Whether someone is available, drawn as a dot on the avatar's corner.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub enum Presence {
100    Online,
101    Away,
102    Busy,
103    Offline,
104}
105
106impl Presence {
107    pub const ALL: [Presence; 4] = [
108        Presence::Online,
109        Presence::Away,
110        Presence::Busy,
111        Presence::Offline,
112    ];
113}
114
115/// Up to two initials for a name: the first letters of its first and last
116/// words, in upper case. One word gives one letter, and an empty name none.
117pub fn initials(name: &str) -> String {
118    let mut words = name
119        .split_whitespace()
120        .filter_map(|word| word.chars().find(|c| c.is_alphanumeric()));
121    let Some(first) = words.next() else {
122        return String::new();
123    };
124    let mut initials: String = first.to_uppercase().collect();
125    if let Some(last) = words.next_back() {
126        initials.extend(last.to_uppercase());
127    }
128    initials
129}
130
131/// An avatar builder. Convert it into an [`Element`] to render.
132#[derive(Debug, Clone)]
133pub struct Avatar {
134    initials: String,
135    image: Option<image::Handle>,
136    icon: Option<Glyph>,
137    size: Size,
138    shape: Shape,
139    presence: Option<Presence>,
140    #[cfg(feature = "icedwright")]
141    name: String,
142}
143
144/// Creates an avatar showing the [`initials`] of `name`. A name with no
145/// letters shows a person icon instead.
146pub fn avatar(name: impl AsRef<str>) -> Avatar {
147    Avatar {
148        #[cfg(feature = "icedwright")]
149        name: name.as_ref().to_owned(),
150        initials: initials(name.as_ref()),
151        image: None,
152        icon: None,
153        size: Size::default(),
154        shape: Shape::default(),
155        presence: None,
156    }
157}
158
159impl Avatar {
160    /// Shows a picture instead of the initials, cropped to fill the shape.
161    pub fn image(mut self, handle: impl Into<image::Handle>) -> Self {
162        self.image = Some(handle.into());
163        self
164    }
165
166    /// Shows an icon instead of the initials, such as a bot for an
167    /// automated account. An image still takes precedence.
168    pub fn icon(mut self, glyph: Glyph) -> Self {
169        self.icon = Some(glyph);
170        self
171    }
172
173    pub fn size(mut self, size: Size) -> Self {
174        self.size = size;
175        self
176    }
177
178    pub fn shape(mut self, shape: Shape) -> Self {
179        self.shape = shape;
180        self
181    }
182
183    pub fn presence(mut self, presence: Presence) -> Self {
184        self.presence = Some(presence);
185        self
186    }
187
188    pub fn initials(&self) -> &str {
189        &self.initials
190    }
191
192    /// What the avatar shows.
193    pub fn content(&self) -> Content<'_> {
194        if let Some(handle) = &self.image {
195            return Content::Image(handle);
196        }
197        if let Some(glyph) = self.icon {
198            return Content::Icon(glyph);
199        }
200        if self.initials.is_empty() {
201            return Content::Icon(lucide!(User));
202        }
203        Content::Initials(&self.initials)
204    }
205}
206
207/// What an [`Avatar`] shows, in order of preference.
208#[derive(Debug, Clone, Copy, PartialEq)]
209pub enum Content<'a> {
210    Image(&'a image::Handle),
211    Icon(Glyph),
212    Initials(&'a str),
213}
214
215impl<'a, Message: 'a> From<Avatar> for Element<'a, Message> {
216    fn from(avatar: Avatar) -> Self {
217        render(avatar, false)
218    }
219}
220
221/// Reports an avatar as an image named after its person.
222#[cfg(feature = "icedwright")]
223fn annotate<'a, Message: 'a>(
224    element: Element<'a, Message>,
225    name: String,
226    presence: Option<Presence>,
227) -> Element<'a, Message> {
228    let mut annotated = icedwright_probe::semantic(element)
229        .role(icedwright_probe::role::Image)
230        .name(name)
231        .component("iced_cube::avatar");
232    if let Some(presence) = presence {
233        annotated = annotated.prop("presence", format!("{presence:?}").to_lowercase());
234    }
235    annotated.into()
236}
237
238/// Draws an avatar, with a ring in the background colour when it overlaps
239/// others in a group.
240fn render<'a, Message: 'a>(avatar: Avatar, ring: bool) -> Element<'a, Message> {
241    let metrics = avatar.size.metrics();
242    let shape = avatar.shape;
243    let diameter = metrics.diameter;
244    let corner = shape.radius(diameter);
245
246    let face: Element<'a, Message> = match avatar.content() {
247        Content::Image(handle) => image(handle.clone())
248            .width(diameter)
249            .height(diameter)
250            .content_fit(iced::ContentFit::Cover)
251            .border_radius(corner)
252            .into(),
253        Content::Icon(glyph) => themed(glyph, metrics.icon, 1.0, |theme| {
254            Tokens::of(theme).muted_foreground
255        })
256        .into(),
257        Content::Initials(initials) => text(initials.to_owned())
258            .size(metrics.text)
259            .font(semibold())
260            .wrapping(text::Wrapping::None)
261            .into(),
262    };
263
264    let ring_width = if ring { RING } else { 0.0 };
265    let side = diameter + 2.0 * ring_width;
266    let face = container(face)
267        .center(Length::Fixed(side))
268        .padding(ring_width)
269        .style(move |theme: &Theme| style(&Tokens::of(theme), shape, diameter, ring));
270
271    #[cfg(feature = "icedwright")]
272    let annotate = {
273        let (name, presence) = (avatar.name, avatar.presence);
274        move |element| annotate(element, name, presence)
275    };
276    #[cfg(not(feature = "icedwright"))]
277    let annotate = |element| element;
278
279    // The outer container shrinks to its fixed-size content, so `natural`
280    // keeps the avatar whole in a narrower parent.
281    let Some(presence) = avatar.presence else {
282        return annotate(natural(container(face)));
283    };
284    annotate(natural(container(
285        Stack::with_children([
286            face.into(),
287            container(dot(presence, metrics.dot))
288                .align_right(Length::Fixed(side))
289                .align_bottom(Length::Fixed(side))
290                .into(),
291        ])
292        .width(side)
293        .height(side),
294    )))
295}
296
297fn dot<'a, Message: 'a>(presence: Presence, diameter: f32) -> Element<'a, Message> {
298    container(space())
299        .width(diameter)
300        .height(diameter)
301        .style(move |theme: &Theme| dot_style(&Tokens::of(theme), presence))
302        .into()
303}
304
305/// Width of the ring around an avatar in a group, in the background colour,
306/// so overlapping avatars stay apart. The ring and the presence dot's ring
307/// are drawn in the page background, so they suit avatars on the page
308/// rather than on a raised card.
309pub const RING: f32 = 2.0;
310
311/// The fill behind initials and icons: the muted surface, lifted a little
312/// in dark themes, where muted sits too close to the background for an
313/// avatar's edge, or the ring between overlapping avatars, to show.
314pub fn fill(tokens: &Tokens) -> Color {
315    if tokens.is_dark {
316        mix(tokens.muted, tokens.foreground, DARK_LIFT)
317    } else {
318        tokens.muted
319    }
320}
321
322const DARK_LIFT: f32 = 0.06;
323
324/// The container style of an avatar: the [`fill`] behind initials and
325/// icons, with a ring in the background colour when `ring` is set.
326pub fn style(tokens: &Tokens, shape: Shape, diameter: f32, ring: bool) -> container::Style {
327    let ring_width = if ring { RING } else { 0.0 };
328    container::Style {
329        text_color: Some(tokens.muted_foreground),
330        background: Some(Background::Color(fill(tokens))),
331        border: Border {
332            color: if ring {
333                tokens.background
334            } else {
335                Color::TRANSPARENT
336            },
337            width: ring_width,
338            radius: shape.radius(diameter + 2.0 * ring_width).into(),
339        },
340        ..container::Style::default()
341    }
342}
343
344/// The colour of a presence dot.
345pub fn presence_colour(tokens: &Tokens, presence: Presence) -> Color {
346    match presence {
347        Presence::Online => tokens.success,
348        Presence::Away => tokens.warning,
349        Presence::Busy => tokens.destructive,
350        Presence::Offline => tokens.muted_foreground,
351    }
352}
353
354/// The presence dot, ringed in the background colour so it stands off the
355/// picture behind it.
356pub fn dot_style(tokens: &Tokens, presence: Presence) -> container::Style {
357    container::Style {
358        background: Some(Background::Color(presence_colour(tokens, presence))),
359        border: Border {
360            color: tokens.background,
361            width: RING,
362            radius: radius::FULL.into(),
363        },
364        ..container::Style::default()
365    }
366}
367
368/// A row of overlapping avatars. Convert it into an [`Element`] to render.
369#[derive(Debug, Clone)]
370pub struct AvatarGroup {
371    avatars: Vec<Avatar>,
372    size: Size,
373    max: Option<usize>,
374}
375
376/// Overlaps `avatars` from left to right, each one ringed in the
377/// background colour.
378pub fn avatar_group(avatars: impl IntoIterator<Item = Avatar>) -> AvatarGroup {
379    AvatarGroup {
380        avatars: avatars.into_iter().collect(),
381        size: Size::default(),
382        max: None,
383    }
384}
385
386impl AvatarGroup {
387    /// The size of every avatar in the group, replacing their own.
388    pub fn size(mut self, size: Size) -> Self {
389        self.size = size;
390        self
391    }
392
393    /// Shows at most `max` avatars. When there are more, the last place
394    /// shows a count of the rest, such as "+3", so the group never takes
395    /// more than `max` places.
396    pub fn max_items(mut self, max: usize) -> Self {
397        self.max = Some(max);
398        self
399    }
400
401    /// How many avatars are shown, and how many the count stands in for.
402    pub fn visible(&self) -> (usize, usize) {
403        overflow(self.avatars.len(), self.max)
404    }
405}
406
407/// Splits `len` avatars into the number shown and the number counted, for
408/// at most `max` places. The count takes one of the places, and at least
409/// one avatar is always shown.
410pub fn overflow(len: usize, max: Option<usize>) -> (usize, usize) {
411    let Some(max) = max else {
412        return (len, 0);
413    };
414    let max = max.max(2);
415    if len <= max {
416        return (len, 0);
417    }
418    (max - 1, len - (max - 1))
419}
420
421/// How far each avatar in a group sits from the one before it: a fifth of
422/// the face is covered, plus the ring, so initials stay readable.
423pub fn step(size: Size) -> f32 {
424    (size.metrics().diameter * 0.8 + RING).round()
425}
426
427impl<'a, Message: 'a> From<AvatarGroup> for Element<'a, Message> {
428    fn from(group: AvatarGroup) -> Self {
429        let (shown, rest) = group.visible();
430        let size = group.size;
431        let metrics = size.metrics();
432        let side = metrics.diameter + 2.0 * RING;
433        let step = step(size);
434
435        let mut faces: Vec<Element<'a, Message>> = group
436            .avatars
437            .into_iter()
438            .take(shown)
439            .map(|avatar| render(avatar.size(size), true))
440            .collect();
441        if rest > 0 {
442            faces.push(count(rest, size));
443        }
444
445        let places = faces.len();
446        let width = if places == 0 {
447            0.0
448        } else {
449            side + step * (places - 1) as f32
450        };
451        let layers = faces.into_iter().enumerate().map(|(index, face)| {
452            container(face)
453                .padding(Padding::ZERO.left(step * index as f32))
454                .into()
455        });
456        let element = natural(container(
457            Stack::with_children(layers).width(width).height(side),
458        ));
459        #[cfg(feature = "icedwright")]
460        let element = icedwright_probe::semantic(element)
461            .role(icedwright_probe::role::Group)
462            .component("iced_cube::avatar_group")
463            .into();
464        element
465    }
466}
467
468/// The "+N" place at the end of a group.
469fn count<'a, Message: 'a>(rest: usize, size: Size) -> Element<'a, Message> {
470    let metrics = size.metrics();
471    let side = metrics.diameter + 2.0 * RING;
472    container(
473        text(format!("+{rest}"))
474            .size(metrics.text)
475            .font(semibold())
476            .wrapping(text::Wrapping::None)
477            .align_x(Alignment::Center),
478    )
479    .center(Length::Fixed(side))
480    .padding(RING)
481    .style(move |theme: &Theme| style(&Tokens::of(theme), Shape::Circle, metrics.diameter, true))
482    .into()
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use crate::theme::{dark, light};
489
490    #[test]
491    fn initials_take_the_first_and_last_words() {
492        assert_eq!(initials("Ada Lovelace"), "AL");
493        assert_eq!(initials("grace brewster murray hopper"), "GH");
494        assert_eq!(initials("  Linus  "), "L");
495        assert_eq!(initials("émile zola"), "ÉZ");
496        assert_eq!(initials("(Ops) Team"), "OT");
497        assert_eq!(initials(""), "");
498        assert_eq!(initials("   "), "");
499        assert_eq!(initials("- -"), "");
500    }
501
502    #[test]
503    fn builder_defaults() {
504        let a = avatar("Ada Lovelace");
505        assert_eq!(a.initials(), "AL");
506        assert_eq!(a.size, Size::Md);
507        assert_eq!(a.shape, Shape::Circle);
508        assert_eq!(a.presence, None);
509        assert_eq!(a.content(), Content::Initials("AL"));
510    }
511
512    #[test]
513    fn content_prefers_image_then_icon_then_initials() {
514        let handle = image::Handle::from_rgba(1, 1, vec![0, 0, 0, 255]);
515        let bot = lucide!(Bot);
516        let a = avatar("Build bot").icon(bot);
517        assert_eq!(a.content(), Content::Icon(bot));
518        let a = a.image(handle.clone());
519        assert_eq!(a.content(), Content::Image(&handle));
520        assert_eq!(avatar("").content(), Content::Icon(lucide!(User)));
521    }
522
523    #[test]
524    fn builder_sets_size_shape_and_presence() {
525        let a = avatar("Ops")
526            .size(Size::Xl)
527            .shape(Shape::Square)
528            .presence(Presence::Busy);
529        assert_eq!(a.size, Size::Xl);
530        assert_eq!(a.shape, Shape::Square);
531        assert_eq!(a.presence, Some(Presence::Busy));
532    }
533
534    #[test]
535    fn sizes_grow_monotonically() {
536        let metrics = Size::ALL.map(Size::metrics);
537        for pair in metrics.windows(2) {
538            assert!(pair[0].diameter < pair[1].diameter);
539            assert!(pair[0].text < pair[1].text);
540            assert!(pair[0].dot < pair[1].dot);
541        }
542    }
543
544    #[test]
545    fn circles_are_round_and_squares_have_modest_corners() {
546        for size in Size::ALL {
547            let diameter = size.metrics().diameter;
548            assert_eq!(Shape::Circle.radius(diameter), diameter / 2.0);
549            let square = Shape::Square.radius(diameter);
550            assert!((radius::SM..=radius::LG).contains(&square), "{size:?}");
551        }
552    }
553
554    #[test]
555    fn avatars_sit_on_the_muted_surface_and_ring_only_in_groups() {
556        for theme in [light(), dark()] {
557            let tokens = Tokens::of(&theme);
558            for shape in Shape::ALL {
559                let alone = style(&tokens, shape, 32.0, false);
560                let ringed = style(&tokens, shape, 32.0, true);
561                assert_eq!(alone.background, Some(Background::Color(fill(&tokens))));
562                assert_eq!(alone.text_color, Some(tokens.muted_foreground));
563                assert_eq!(alone.border.width, 0.0);
564                assert_eq!(ringed.border.width, RING);
565                assert_eq!(ringed.border.color, tokens.background);
566            }
567        }
568    }
569
570    fn lightness(colour: Color) -> f32 {
571        colour.r + colour.g + colour.b
572    }
573
574    #[test]
575    fn the_ring_stands_out_against_the_fill_in_both_themes() {
576        for theme in [light(), dark()] {
577            let tokens = Tokens::of(&theme);
578            let ringed = style(&tokens, Shape::Circle, 32.0, true);
579            assert_eq!(ringed.border.color, tokens.background);
580            let gap = (lightness(fill(&tokens)) - lightness(tokens.background)).abs();
581            assert!(gap > 0.35, "dark: {} gap {gap}", tokens.is_dark);
582        }
583    }
584
585    #[test]
586    fn presence_uses_status_tokens() {
587        for theme in [light(), dark()] {
588            let tokens = Tokens::of(&theme);
589            assert_eq!(presence_colour(&tokens, Presence::Online), tokens.success);
590            assert_eq!(presence_colour(&tokens, Presence::Away), tokens.warning);
591            assert_eq!(presence_colour(&tokens, Presence::Busy), tokens.destructive);
592            assert_eq!(
593                presence_colour(&tokens, Presence::Offline),
594                tokens.muted_foreground
595            );
596            for presence in Presence::ALL {
597                let style = dot_style(&tokens, presence);
598                assert_eq!(style.border.color, tokens.background);
599                assert_eq!(style.border.radius, radius::FULL.into());
600            }
601        }
602    }
603
604    #[test]
605    fn overflow_keeps_the_group_within_its_places() {
606        assert_eq!(overflow(3, None), (3, 0));
607        assert_eq!(overflow(3, Some(3)), (3, 0));
608        assert_eq!(overflow(5, Some(3)), (2, 3));
609        assert_eq!(overflow(5, Some(0)), (1, 4));
610        assert_eq!(overflow(0, Some(3)), (0, 0));
611        for len in 0..10 {
612            for max in 2..6 {
613                let (shown, rest) = overflow(len, Some(max));
614                assert_eq!(shown + rest, len);
615                assert!(shown + usize::from(rest > 0) <= max);
616            }
617        }
618    }
619
620    #[test]
621    fn group_avatars_overlap_by_a_fifth_of_their_face() {
622        for size in Size::ALL {
623            let diameter = size.metrics().diameter;
624            let step = step(size);
625            assert!(step < diameter + 2.0 * RING, "{size:?} overlaps");
626            assert!(step >= diameter * 0.8, "{size:?} keeps initials clear");
627        }
628    }
629
630    #[test]
631    fn group_builder() {
632        let group = avatar_group(["A", "B", "C", "D"].map(avatar))
633            .size(Size::Sm)
634            .max_items(3);
635        assert_eq!(group.size, Size::Sm);
636        assert_eq!(group.visible(), (2, 2));
637        assert_eq!(avatar_group([avatar("A")]).visible(), (1, 0));
638    }
639}