Skip to main content

hypersig_ui/
avatar.rs

1//! Avatars: a round picture of a person, with their initials in its place.
2
3use hypersig::IntoHref;
4use hypersig::html::{El, Node, Role, attr, img, span};
5use hypersig::style::value::{
6    AlignItems, Display, FontWeight, JustifyContent, ObjectFit, Overflow, Position, VerticalAlign,
7    px, raw, rem,
8};
9use hypersig::style::{PseudoElement, Style};
10
11use crate::token;
12
13/// A round picture of the person `name`, or `initials` where there is none.
14///
15/// The avatar is a `role="img"` named `name`, so a screen reader reads the
16/// name once and nothing inside it. Without [`Avatar::picture`] it shows
17/// `initials`. With one, it shows the picture, and where the picture fails
18/// to load, the `::after` of the broken `<img>` draws `initials` over it.
19/// Chrome draws that `::after`. A browser that draws no `::after` on a
20/// broken image shows its own marker for one there instead.
21///
22/// ```
23/// use hypersig::{SafeUrl, Signals};
24/// use hypersig_ui::Avatar;
25/// use serde::{Deserialize, Serialize};
26///
27/// #[derive(Signals, Serialize, Deserialize)]
28/// struct Team {}
29///
30/// const ADA: SafeUrl = SafeUrl::new("https://example.com/ada.png");
31///
32/// let ada = Avatar::<Team>::new("Ada Lovelace", "AL").picture(ADA);
33/// let html = ada.render().render();
34/// assert!(html.contains(r#"aria-label="Ada Lovelace""#));
35/// assert!(html.contains(r#"alt="AL""#));
36/// ```
37#[derive(Debug)]
38pub struct Avatar<S> {
39    name: String,
40    initials: String,
41    picture: Option<El<S>>,
42}
43
44impl<S> Avatar<S> {
45    /// An avatar of `name` that shows `initials`.
46    #[must_use]
47    pub fn new(name: impl Into<String>, initials: impl Into<String>) -> Self {
48        Self {
49            name: name.into(),
50            initials: initials.into(),
51            picture: None,
52        }
53    }
54
55    /// Shows the picture at `url` in place of the initials.
56    #[must_use]
57    pub fn picture(mut self, url: impl IntoHref<S>) -> Self {
58        self.picture = Some(img().src(url));
59        self
60    }
61
62    /// The avatar, as a `<span>`.
63    #[must_use]
64    pub fn render(self) -> El<S> {
65        let avatar = span()
66            .role(Role::Img)
67            .attr(attr::ARIA_LABEL, self.name)
68            .css(avatar_style());
69        match self.picture {
70            Some(picture) => {
71                avatar.child(picture.attr(attr::ALT, self.initials).css(picture_style()))
72            }
73            None => avatar.text(self.initials),
74        }
75    }
76}
77
78impl<S> From<Avatar<S>> for El<S> {
79    fn from(avatar: Avatar<S>) -> Self {
80        avatar.render()
81    }
82}
83
84impl<S> From<Avatar<S>> for Node<S> {
85    fn from(avatar: Avatar<S>) -> Self {
86        avatar.render().into()
87    }
88}
89
90fn avatar_style() -> Style {
91    Style::new()
92        .position(Position::Relative)
93        .display(Display::InlineFlex)
94        .align_items(AlignItems::Center)
95        .justify_content(JustifyContent::Center)
96        .flex_shrink(0.0)
97        .vertical_align(VerticalAlign::Middle)
98        .width(rem(2))
99        .height(rem(2))
100        .overflow(Overflow::Hidden)
101        .border_radius(px(999))
102        .background_color(token::muted().var())
103        .color(token::muted_foreground().var())
104        .font_size(rem(0.875))
105        .font_weight(FontWeight::Number(500.0))
106}
107
108/// The picture, filling the circle. Its `::after`, which a browser draws
109/// only for an image that failed to load, covers the broken image with the
110/// `alt` text.
111fn picture_style() -> Style {
112    Style::new()
113        .position(Position::Relative)
114        .display(Display::Block)
115        .width(raw("100%"))
116        .height(raw("100%"))
117        .object_fit(ObjectFit::Cover)
118        .pseudo(
119            PseudoElement::After,
120            Style::new()
121                .content(raw("attr(alt)"))
122                .position(Position::Absolute)
123                .inset(px(0))
124                .display(Display::Flex)
125                .align_items(AlignItems::Center)
126                .justify_content(JustifyContent::Center)
127                .background_color(token::muted().var())
128                .color(token::muted_foreground().var()),
129        )
130}
131
132#[cfg(test)]
133mod tests {
134    use super::Avatar;
135
136    struct Team;
137
138    #[test]
139    fn without_a_picture_it_shows_the_initials() {
140        let html = Avatar::<Team>::new("Grace Hopper", "GH").render().render();
141        assert!(html.contains(r#"role="img""#));
142        assert!(html.contains(">GH</span>"));
143        assert!(!html.contains("<img"));
144    }
145}