1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use std::collections::HashMap;
use crate::{DefaultModifiers, sp};
use crate::node::{Node, NodeContainer};
use crate::Renderable;
#[derive(Debug, Clone)]
pub enum Size {
Normal,
Large,
XLarge,
}
#[derive(Debug, Clone)]
pub struct Avatar {
node: Node,
name: String,
profil_img: Option<String>,
size: Size,
}
impl Avatar {
pub fn new(name: &str, profil_img: &Option<String>) -> Self {
Self {
node: Default::default(),
name: name.to_string(),
profil_img: profil_img.clone(),
size: Size::Normal,
}
}
pub fn size(&mut self, size: Size) -> Self {
self.size = size;
self.clone()
}
}
impl NodeContainer for Avatar {
fn get_node(&mut self) -> &mut Node {
&mut self.node
}
}
impl DefaultModifiers<Avatar> for Avatar {}
impl Renderable for Avatar {
fn render(&self) -> Node {
let mut avatar = self.clone()
.add_class("avatar")
.add_class(&format!("avatar--{}", match self.size {
Size::Normal => "normal",
Size::Large => "large",
Size::XLarge => "x-large",
}));
if let Some(profile_img) = self.profil_img.clone() {
avatar = avatar.background_image(&profile_img);
} else {
let initials: Vec<char> = self.name
.clone()
.split(" ")
.filter(|word| {
!vec!["le", "de", "des", "la", "les"].contains(&word.to_lowercase().as_str())
})
.map(|part| part.chars().nth(0).unwrap_or_default())
.collect();
let text_content = initials.get(0..2)
.map(|initials| -> String {
initials.iter().collect()
})
.unwrap_or(self.name.get(0..2).unwrap_or_default().to_string());
avatar.get_node().text = Some(text_content.to_uppercase());
}
avatar.get_node().clone()
}
}
#[cfg(test)]
mod tests {
use crate::components::Avatar;
use crate::Renderable;
#[test]
fn test_different_names() {
let names = vec![
"Rémi Caillot",
"Estelle Le Marre",
"Jean-François Cano",
"remicaillot5@gmail.com"
];
for name in names {
let avatar = Avatar::new(name, &None);
println!("{} => {}", name, avatar.to_html())
}
}
}