All files / packages/ui/src/components/Avatar index.tsx

100% Statements 24/24
85.29% Branches 29/34
100% Functions 9/9
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                                                    3x                   12x 12x   12x   12x 11x     12x 33x         33x         12x 11x         12x 12x 11x               12x 11x             12x 12x 11x       12x         1x                   12x                                                             11x                                                                                
import { memo, useEffect, useMemo, useState } from "react";
import Animated, {
  interpolateColor,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated";
import { ImageSourcePropType, Pressable, Text, View } from "react-native";
 
import { CachedImage } from "@repo/ui/components/CachedImage";
import { makeStyles } from "@repo/ui/themes/makeStyles";
import { useTheme } from "@repo/ui/themes/ThemeContext";
import { Theme } from "@repo/ui/themes/types";
import { textStyles } from "@repo/ui/themes/typography";
 
interface Props {
  uri?: string;
  source?: ImageSourcePropType;
  name?: string;
  size?: number;
  selected?: boolean;
  onPress?: () => void;
  showName?: boolean;
  numberOfLines?: number;
}
 
export const Avatar = memo(function Avatar({
  uri,
  source,
  name,
  size = 64,
  selected = false,
  onPress,
  showName = false,
  numberOfLines = 2,
}: Props) {
  const { theme } = useTheme();
  const styles = useStyles();
 
  const progress = useSharedValue(selected ? 1 : 0);
 
  useEffect(() => {
    progress.value = withTiming(selected ? 1 : 0, { duration: 250 });
  }, [selected, progress]);
 
  const animatedRingStyle = useAnimatedStyle(() => {
    const borderColor = interpolateColor(
      progress.value,
      [0, 1],
      [theme.colors.white, theme.colors.border.avatarSelected],
    );
    return {
      borderColor,
    };
  }, [theme.colors.white, theme.colors.border.avatarSelected, progress]);
 
  const dynamicAvatarStyle = useMemo(
    () => ({ width: size, height: size, borderRadius: size / 2 }),
    [size],
  );
 
  // Inner ring sits inside the 3px primary border (3px each side = 6px total)
  const innerSize = size - 6;
  const dynamicInnerRingStyle = useMemo(
    () => ({
      width: innerSize,
      height: innerSize,
      borderRadius: innerSize / 2,
    }),
    [innerSize],
  );
 
  const imageSource = useMemo(
    () => (uri ? { uri, priority: "normal" as const, cache: "immutable" as const } : null),
    [uri],
  );
 
  // A broken avatar URL (dead host, deleted file) must degrade to the letter
  // fallback instead of an empty circle. Reset when the uri changes so a new
  // (possibly valid) avatar gets a fresh attempt.
  const [imageFailed, setImageFailed] = useState(false);
  useEffect(() => {
    setImageFailed(false);
  }, [uri]);
 
  const content =
    !imageFailed && (imageSource || source) ? (
      <CachedImage
        source={imageSource ?? source!}
        style={dynamicAvatarStyle}
        resizeMode="cover"
        onError={() => setImageFailed(true)}
      />
    ) : (
      <View style={[styles.fallback, dynamicAvatarStyle]}>
        <Text style={[styles.initial, { fontSize: size * 0.35 }]}>
          {name?.charAt(0).toUpperCase()}
        </Text>
      </View>
    );
 
  return (
    <Pressable
      onPress={onPress}
      style={styles.wrapper}
      accessibilityRole={onPress ? "button" : "image"}
      accessibilityLabel={name || "Avatar"}
      accessibilityState={onPress ? { selected } : undefined}
    >
      {/* Outer Ring */}
      <Animated.View style={[dynamicAvatarStyle, styles.ring, animatedRingStyle]}>
        {/* Always rendered so CachedImage never unmounts on selection toggle */}
        <View
          style={[
            dynamicInnerRingStyle,
            styles.innerWhiteRing,
            selected ? null : styles.innerWhiteRingHidden,
          ]}
        >
          {content}
        </View>
      </Animated.View>
 
      {showName && name && (
        <Text numberOfLines={numberOfLines} style={styles.name}>
          {name}
        </Text>
      )}
    </Pressable>
  );
});
 
const useStyles = makeStyles((theme: Theme) => ({
  wrapper: {
    alignItems: "center",
  },
 
  ring: {
    alignItems: "center",
    justifyContent: "center",
    overflow: "hidden",
    borderWidth: 3,
  },
 
  innerWhiteRing: {
    overflow: "hidden",
    alignItems: "center",
    justifyContent: "center",
  },
 
  innerWhiteRingHidden: {},
 
  fallback: {
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: theme.colors.gray30,
  },
 
  initial: {
    fontWeight: "600",
    color: theme.colors.white,
  },
 
  name: {
    marginTop: theme.metrics.spacing[2],
    fontSize: theme.metrics.textSize[14],
    lineHeight: theme.isNewTheme ? 18 : undefined,
    textAlign: "center",
    color: theme.isNewTheme ? theme.colors.text.secondary : theme.colors.text.primary,
    ...(theme.isNewTheme ? textStyles.content.medium : textStyles.content.semiBold),
  },
}));