forked from avishayil/react-native-user-avatar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
110 lines (105 loc) · 2.63 KB
/
Copy pathindex.js
File metadata and controls
110 lines (105 loc) · 2.63 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import React from 'react';
import { View, Image, Text } from 'react-native';
import initials from 'initials';
// 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.PureComponent {
render() {
let {
src,
name,
color,
textColor = '#fff',
colors = defaultColors,
size = 32,
containerStyle,
imageStyle,
defaultName,
radius = 0.5,
} = this.props;
if (!name) throw new Error('Avatar requires a name');
if (typeof size !== 'number') size = parseInt(size);
let abbr = initials(name);
if (name.startsWith('+')) {
abbr = `+${abbr}`;
}
if (!abbr) abbr = defaultName;
if (isNaN(radius)) radius = 0.5;
const borderRadius = size * radius;
const imageLocalStyle = {
borderRadius,
};
const localStyle = {
borderRadius,
borderWidth: 1,
borderColor: 'transparent',
justifyContent: 'center',
alignItems: 'center',
};
let colorStyle = {};
let inner;
if (src) {
const sizeStyle = {
width: size,
height: size,
};
const props = {
style: [imageLocalStyle, sizeStyle, imageStyle],
source: { uri: src },
};
inner = React.createElement(this.props.component || Image, props);
} else {
let background;
if (color) {
background = color;
} else {
// pick a deterministic color from the list
let i = sumChars(name) % colors.length;
background = colors[i];
}
colorStyle = { backgroundColor: background };
const textContainerStyle = {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
};
// TODO if i set this style to height instead of minHeight, react-native black screens, wtf
const minSizeStyle = {
minHeight: size,
minWidth: size,
};
inner = (
<View style={[textContainerStyle, minSizeStyle]}>
<Text
style={{
color: textColor,
}}
adjustsFontSizeToFit={true}
maxFontSizeMultiplier={1}
>
{abbr}
</Text>
</View>
);
}
return (
<View style={[localStyle, colorStyle, containerStyle]}>{inner}</View>
);
}
}
module.exports = UserAvatar;