1use 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#[derive(Debug)]
38pub struct Avatar<S> {
39 name: String,
40 initials: String,
41 picture: Option<El<S>>,
42}
43
44impl<S> Avatar<S> {
45 #[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 #[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 #[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
108fn 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}