-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
94 lines (79 loc) · 2.04 KB
/
index.js
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
const React = require('react');
const initials = require('initials');
const addPx = require('add-px');
const contrast = require('contrast');
// from https://flatuicolors.com/
const defaultColors = [
'#2ecc71', // emerald
'#3498db', // peter river
'#8e44ad', // wisteria
'#e67e22', // carrot
'#e74c3c', // alizarin
'#1abc9c', // turquoise
'#2c3e50', // midnight blue
];
function sumChars(str) {
let sum = 0;
for(let i = 0; i < str.length; i++) {
sum += str.charCodeAt(i);
}
return sum;
}
class UserAvatar extends React.Component {
render() {
let {
borderRadius='100%',
src,
srcset,
name,
color,
colors=defaultColors,
size,
style,
onClick,
className
} = this.props;
if (!name) throw new Error('UserAvatar requires a name');
const abbr = initials(name);
size = addPx(size);
const imageStyle = {
display: 'block',
borderRadius
};
const innerStyle = {
lineHeight: size,
textAlign: 'center',
borderRadius
};
if (size) {
imageStyle.width = innerStyle.width = innerStyle.maxWidth = size;
imageStyle.height = innerStyle.height = innerStyle.maxHeight = size;
}
let inner, classes = [className, 'UserAvatar'];
if (src || srcset) {
inner = <img className="UserAvatar--img" style={imageStyle} src={src} srcSet={srcset} alt={name} />
} else {
let background;
if (color) {
background = color;
} else {
// pick a deterministic color from the list
let i = sumChars(name) % colors.length;
background = colors[i];
}
innerStyle.backgroundColor = background;
inner = abbr;
}
if (innerStyle.backgroundColor) {
classes.push(`UserAvatar--${contrast(innerStyle.backgroundColor)}`);
}
return (
<div aria-label={name} className={classes.join(' ')} style={style}>
<div className="UserAvatar--inner" style={innerStyle}>
{inner}
</div>
</div>
)
}
}
module.exports = UserAvatar;