UNPKG

maisonsport-common-ui

Version:

Suite of styled-components to be consumed by the React-Native App and by the Web (via React-Native for Web)

84 lines (72 loc) 2.17 kB
/* eslint-disable no-console */ import React, { useState } from 'react'; import { Image } from 'react-native'; import PropTypes from 'prop-types'; import { ThemeProvider } from 'styled-components/native'; import md5 from 'crypto-js/md5'; import Theme from '../../theme'; import { getRandomColor } from '../../util/functions'; import Box from '../../atoms/Box'; import Text from '../../atoms/Text'; export const avatarContainerTestID = 'avatar-container'; export const avatarContentTestID = 'avatar-content'; export const avatarImageTestID = 'avatar-image'; function getGravatarUrl(email = null) { if (!email) { return null; } const hashedEmail = md5(email.trim().toLowerCase()); return `https://www.gravatar.com/avatar/${hashedEmail}?d=404`; } function Avatar({ name, size, url, email, }) { const avatarSource = { uri: url || getGravatarUrl(email) }; const [showAsImage, setShowAsImage] = useState(!!avatarSource.uri); const names = name.split(' '); const initials = (names.length > 2 ? [ names[0], names[1], names[names.length - 1], ] : [ names[0], names[1], ]).filter(Boolean).map(([initial]) => initial.toUpperCase()).join(''); return ( <ThemeProvider theme={Theme}> <Box testID={avatarContainerTestID} noWrapTheme width={size} height={size} backgroundColor={getRandomColor(name)} borderRadius={size} alignItems="center" justifyContent="center"> {showAsImage ? ( <Image testID={avatarImageTestID} source={avatarSource} onError={() => { setShowAsImage(false); }} style={{ width: size, height: size, borderRadius: size, }} /> ) : ( <Text testID={avatarContentTestID} noWrapTheme variant="h3" color="white" margin={0} padding={0}>{initials}</Text> )} </Box> </ThemeProvider> ); } Avatar.defaultProps = { size: 40, url: '', email: '', }; Avatar.propTypes = { name: PropTypes.string.isRequired, size: PropTypes.number, url: PropTypes.string, email: PropTypes.string, }; export default Avatar;