Skip to main content

next_rust_ui/
avatar.rs

1//! Avatars: an image in a circle, with initials when there is no image.
2
3use next_rust_view::{Attr, Element, Node, View};
4
5use crate::button::common_methods;
6use crate::{Color, Extra, Radius, Size, apply, attr, root, styled};
7
8/// A user picture. Without `src`, or when the image fails to load, it shows
9/// the initials of `name`.
10///
11/// ```
12/// # use next_rust_ui::*; use next_rust_view::*;
13/// let html = render_static(Avatar![name = "Ada Lovelace", size = Size::Lg, bordered = true]);
14/// assert!(html.contains(r#"<span class="nr-avatar-fallback" aria-hidden="true">AL</span>"#));
15/// ```
16#[derive(Default)]
17pub struct Avatar {
18    src: Option<String>,
19    name: Option<String>,
20    initials: Option<String>,
21    size: Size,
22    radius: Option<Radius>,
23    color: Color,
24    bordered: bool,
25    unstyled: bool,
26    extra: Extra,
27}
28
29impl Avatar {
30    pub fn new() -> Self {
31        Self { color: Color::Default, ..Self::default() }
32    }
33    common_methods!();
34
35    /// Add an attribute to the outer element, or content shown instead of
36    /// the initials (an icon).
37    pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
38        self.extra.push(part);
39        self
40    }
41    /// Image URL.
42    pub fn src(mut self, v: impl Into<String>) -> Self {
43        self.src = Some(v.into());
44        self
45    }
46    /// The person's name: the image's alt text and the source of the initials.
47    pub fn name(mut self, v: impl Into<String>) -> Self {
48        self.name = Some(v.into());
49        self
50    }
51    /// Text shown without an image (defaults to the initials of `name`).
52    pub fn initials(mut self, v: impl Into<String>) -> Self {
53        self.initials = Some(v.into());
54        self
55    }
56    pub fn size(mut self, v: Size) -> Self {
57        self.size = v;
58        self
59    }
60    /// Rounding (a circle by default).
61    pub fn radius(mut self, v: Radius) -> Self {
62        self.radius = Some(v);
63        self
64    }
65    /// Color of the ring and of the initials' background.
66    pub fn color(mut self, v: Color) -> Self {
67        self.color = v;
68        self
69    }
70    /// A ring around the avatar.
71    pub fn bordered(mut self, v: bool) -> Self {
72        self.bordered = v;
73        self
74    }
75}
76
77/// Initials of a name: "Ada Lovelace" → "AL", "ada" → "A".
78fn initials_of(name: &str) -> String {
79    let words: Vec<&str> = name.split_whitespace().collect();
80    let first = |w: &str| w.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default();
81    match words.as_slice() {
82        [] => String::new(),
83        [one] => first(one),
84        [a, .., b] => first(a) + &first(b),
85    }
86}
87
88impl View for Avatar {
89    fn into_node(self) -> Node {
90        let (class, attrs, children) = self.extra.split();
91        let size = format!("nr-avatar-{}", self.size.suffix());
92        let classes = [
93            "nr-avatar",
94            &size,
95            self.color.class(),
96            self.radius.map(Radius::class).unwrap_or(""),
97            if self.bordered { "nr-avatar-bordered" } else { "" },
98        ];
99        let mut el = root("span", &classes, self.unstyled, class);
100        match (&self.src, &self.name) {
101            (Some(_), _) => {}
102            (None, Some(name)) => {
103                el.set_attr(attr("role", "img"));
104                el.set_attr(attr("aria-label", name.clone()));
105            }
106            (None, None) => {}
107        }
108        apply(&mut el, attrs);
109        let fallback: Node = if children.is_empty() {
110            self.initials.clone().or_else(|| self.name.as_deref().map(initials_of)).unwrap_or_default().into_node()
111        } else {
112            Node::Fragment(children)
113        };
114        el.children.push(
115            Element::new("span")
116                .with(attr("class", "nr-avatar-fallback"))
117                .with(attr("aria-hidden", "true"))
118                .with(fallback)
119                .into_node(),
120        );
121        if let Some(src) = self.src {
122            // `data-nr-ui`: the script hides the image if it fails to load.
123            el.set_attr(attr("data-nr-ui", "avatar"));
124            el.children.push(
125                Element::new_void("img")
126                    .with(attr("class", "nr-avatar-img"))
127                    .with(attr("src", src))
128                    .with(attr("alt", self.name.unwrap_or_default()))
129                    .with(attr("loading", "lazy"))
130                    .with(attr("decoding", "async"))
131                    .into_node(),
132            );
133        }
134        styled(el)
135    }
136}
137
138/// Values accepted inside `AvatarGroup![..]`.
139pub trait AvatarGroupPart {
140    fn add_to(self, group: &mut AvatarGroup);
141}
142impl AvatarGroupPart for Avatar {
143    fn add_to(self, group: &mut AvatarGroup) {
144        group.avatars.push(self);
145    }
146}
147impl AvatarGroupPart for Vec<Avatar> {
148    fn add_to(self, group: &mut AvatarGroup) {
149        group.avatars.extend(self);
150    }
151}
152impl AvatarGroupPart for Attr {
153    fn add_to(self, group: &mut AvatarGroup) {
154        group.extra.push(self);
155    }
156}
157
158/// Overlapping avatars, with a `+N` count past `max`.
159#[derive(Default)]
160pub struct AvatarGroup {
161    avatars: Vec<Avatar>,
162    max: Option<usize>,
163    total: Option<usize>,
164    size: Size,
165    unstyled: bool,
166    extra: Extra,
167}
168
169impl AvatarGroup {
170    pub fn new() -> Self {
171        Self::default()
172    }
173    common_methods!();
174
175    /// Add avatars or attributes for the group.
176    pub fn with(mut self, part: impl AvatarGroupPart) -> Self {
177        part.add_to(&mut self);
178        self
179    }
180    /// Show at most this many avatars.
181    pub fn max(mut self, v: usize) -> Self {
182        self.max = Some(v);
183        self
184    }
185    /// Total number of people, when more exist than were given.
186    pub fn total(mut self, v: usize) -> Self {
187        self.total = Some(v);
188        self
189    }
190    pub fn size(mut self, v: Size) -> Self {
191        self.size = v;
192        self
193    }
194}
195
196impl View for AvatarGroup {
197    fn into_node(self) -> Node {
198        let (class, attrs, _) = self.extra.split();
199        let mut el = root("div", &["nr-avatar-group"], self.unstyled, class);
200        el.set_attr(attr("role", "group"));
201        apply(&mut el, attrs);
202        let total = self.total.unwrap_or(self.avatars.len()).max(self.avatars.len());
203        let shown = self.max.unwrap_or(usize::MAX).min(self.avatars.len());
204        for avatar in self.avatars.into_iter().take(shown) {
205            el.children.push(avatar.size(self.size).bordered(true).into_node());
206        }
207        if total > shown {
208            let rest = format!("+{}", total - shown);
209            el.children.push(
210                Avatar::new()
211                    .size(self.size)
212                    .bordered(true)
213                    .initials(rest)
214                    .with(attr("aria-label", format!("{} more", total - shown)))
215                    .into_node(),
216            );
217        }
218        styled(el)
219    }
220}