1import * as React from 'react';
2import { Image, StyleProp, StyleSheet, Text, TouchableOpacity, ViewStyle } from 'react-native';
3
4import Colors from '../../constants/Colors';
5
6type Props = {
7  image: (() => void) | string | any;
8  onPress: () => void;
9  name: string;
10  style: StyleProp<ViewStyle>;
11};
12export default function Avatar({ image, name = '', style, onPress }: Props) {
13  const getImage = (): JSX.Element => {
14    if (typeof image === 'string') {
15      return <Image style={styles.image} source={{ uri: image }} />;
16    } else if (typeof image === 'function') {
17      return image();
18    }
19    return <Image source={{}} />;
20  };
21
22  const getInitials = () => {
23    const _name = name.toUpperCase().split(' ');
24    let initials;
25    if (_name.length === 1) {
26      initials = `${_name[0].charAt(0)}`;
27    } else if (_name.length > 1) {
28      initials = `${_name[0].charAt(0)}${_name[1].charAt(0)}`;
29    } else {
30      initials = '';
31    }
32    return initials;
33  };
34
35  return (
36    <TouchableOpacity
37      disabled={!onPress}
38      onPress={() => onPress?.()}
39      style={[styles.container, style]}>
40      {image ? getImage() : <Text style={styles.text}>{getInitials()}</Text>}
41    </TouchableOpacity>
42  );
43}
44
45const DEFAULT_SIZE = 120;
46
47const styles = StyleSheet.create({
48  container: {
49    justifyContent: 'center',
50    alignItems: 'center',
51    width: DEFAULT_SIZE,
52    aspectRatio: 1,
53    borderRadius: DEFAULT_SIZE / 2,
54    overflow: 'hidden',
55    backgroundColor: Colors.secondaryText,
56  },
57  avatarTransparent: {
58    backgroundColor: '#B8B8B8',
59  },
60  image: {
61    resizeMode: 'cover',
62    width: '100%',
63    height: '100%',
64  },
65  text: {
66    color: 'white',
67    fontSize: DEFAULT_SIZE * 0.35,
68    backgroundColor: 'transparent',
69    fontWeight: 'bold',
70  },
71});
72