aboutsummaryrefslogtreecommitdiffstats
path: root/apps/mobile/components/ui/Avatar.tsx
blob: 923c634ebcd7d8f5bdc1300ced03f04e3cc30d09 (plain) (blame)
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
import * as React from "react";
import { Image, View } from "react-native";
import { Text } from "@/components/ui/Text";
import { useAssetUrl } from "@/lib/hooks";
import { cn } from "@/lib/utils";

interface AvatarProps {
  image?: string | null;
  name?: string | null;
  size?: number;
  className?: string;
  imageClassName?: string;
  fallbackClassName?: string;
}

function isExternalUrl(url: string) {
  return url.startsWith("http://") || url.startsWith("https://");
}

export function Avatar({
  image,
  name,
  size = 40,
  className,
  imageClassName,
  fallbackClassName,
}: AvatarProps) {
  const [imageError, setImageError] = React.useState(false);
  const assetUrl = useAssetUrl(image ?? "");

  const imageUrl = React.useMemo(() => {
    if (!image) return null;
    return isExternalUrl(image)
      ? {
          uri: image,
        }
      : assetUrl;
  }, [image]);

  React.useEffect(() => {
    setImageError(false);
  }, [image]);

  const initials = React.useMemo(() => {
    if (!name) return "U";
    return name.charAt(0).toUpperCase();
  }, [name]);

  const showFallback = !imageUrl || imageError;

  return (
    <View
      className={cn("overflow-hidden bg-black", className)}
      style={{
        width: size,
        height: size,
        borderRadius: size / 2,
      }}
    >
      {showFallback ? (
        <View
          className={cn(
            "flex h-full w-full items-center justify-center bg-black",
            fallbackClassName,
          )}
        >
          <Text
            className="text-white"
            style={{
              fontSize: size * 0.4,
              lineHeight: size * 0.4,
              textAlign: "center",
            }}
          >
            {initials}
          </Text>
        </View>
      ) : (
        <Image
          source={imageUrl}
          className={cn("h-full w-full", imageClassName)}
          style={{ resizeMode: "cover" }}
          onError={() => setImageError(true)}
        />
      )}
    </View>
  );
}