vn-verdnaturachat/app/containers/Avatar.js

81 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-04-18 20:57:35 +00:00
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import FastImage from 'react-native-fast-image';
const formatUrl = (url, baseUrl, uriSize, avatarAuthURLFragment) => (
`${ baseUrl }${ url }?format=png&width=${ uriSize }&height=${ uriSize }${ avatarAuthURLFragment }`
);
2019-04-18 20:57:35 +00:00
const Avatar = React.memo(({
text, size, baseUrl, borderRadius, style, avatar, type, children, userId, token
}) => {
const avatarStyle = {
width: size,
height: size,
borderRadius
};
2019-04-18 20:57:35 +00:00
if (!text && !avatar) {
return null;
}
2019-04-18 20:57:35 +00:00
const room = type === 'd' ? text : `@${ text }`;
2017-09-01 20:20:34 +00:00
2019-04-18 20:57:35 +00:00
// Avoid requesting several sizes by having only two sizes on cache
const uriSize = size === 100 ? 100 : 50;
2017-09-01 20:20:34 +00:00
2019-04-18 20:57:35 +00:00
let avatarAuthURLFragment = '';
if (userId && token) {
avatarAuthURLFragment = `&rc_token=${ token }&rc_uid=${ userId }`;
}
2018-12-05 20:52:08 +00:00
let uri;
if (avatar) {
uri = avatar.includes('http') ? avatar : formatUrl(avatar, baseUrl, uriSize, avatarAuthURLFragment);
} else {
uri = formatUrl(`/avatar/${ room }`, baseUrl, uriSize, avatarAuthURLFragment);
}
2019-04-18 20:57:35 +00:00
const image = (
<FastImage
style={avatarStyle}
source={{
uri,
priority: FastImage.priority.high
}}
/>
);
2019-04-18 20:57:35 +00:00
return (
<View style={[avatarStyle, style]}>
{image}
{children}
</View>
);
});
2019-04-18 20:57:35 +00:00
Avatar.propTypes = {
baseUrl: PropTypes.string.isRequired,
style: PropTypes.any,
2019-04-18 20:57:35 +00:00
text: PropTypes.string,
avatar: PropTypes.string,
size: PropTypes.number,
borderRadius: PropTypes.number,
type: PropTypes.string,
children: PropTypes.object,
userId: PropTypes.string,
token: PropTypes.string
};
2018-12-05 20:52:08 +00:00
2019-04-18 20:57:35 +00:00
Avatar.defaultProps = {
text: '',
size: 25,
type: 'd',
borderRadius: 4
};
2019-04-18 20:57:35 +00:00
export default Avatar;