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

100% Statements 36/36
100% Branches 18/18
100% Functions 11/11
100% Lines 33/33

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                                                                  4x 11x   4x           4x           4x             4x               11x 11x 11x 11x   11x 11x 1x 1x     10x                           10x 10x 10x       11x 1x 1x       1x 1x     11x 1x 1x 1x     11x 11x   10x                         11x                                   4x   10x                
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import FastImage from "react-native-fast-image";
import {
  Animated,
  ImageSourcePropType,
  StyleProp,
  StyleSheet,
  View,
  ViewStyle,
} from "react-native";
 
import { makeStyles } from "@repo/ui/themes/makeStyles";
 
type Priority = "low" | "normal" | "high";
type CachePolicy = "immutable" | "web" | "cacheOnly";
type ResizeMode = "contain" | "cover" | "stretch" | "center";
 
export interface NetworkSource {
  uri: string;
  headers?: Record<string, string>;
  priority?: Priority;
  cache?: CachePolicy;
}
 
export interface CachedImageProps {
  source: NetworkSource | ImageSourcePropType;
  style?: StyleProp<ViewStyle>;
  resizeMode?: ResizeMode;
  placeholderColor?: string;
  onLoad?: () => void;
  onError?: () => void;
}
 
const isNetworkSource = (s: CachedImageProps["source"]): s is NetworkSource =>
  typeof s === "object" && s !== null && !Array.isArray(s) && "uri" in (s as object);
 
const PRIORITY_MAP = {
  low: FastImage.priority.low,
  normal: FastImage.priority.normal,
  high: FastImage.priority.high,
} as const;
 
const CACHE_MAP = {
  immutable: FastImage.cacheControl.immutable,
  web: FastImage.cacheControl.web,
  cacheOnly: FastImage.cacheControl.cacheOnly,
} as const;
 
const RESIZE_MODE_MAP = {
  contain: FastImage.resizeMode.contain,
  cover: FastImage.resizeMode.cover,
  stretch: FastImage.resizeMode.stretch,
  center: FastImage.resizeMode.center,
} as const;
 
export const CachedImage = memo(function CachedImage({
  source,
  style,
  resizeMode = "cover",
  placeholderColor = "#E1E9EE",
  onLoad,
  onError,
}: CachedImageProps) {
  const styles = useStyles();
  const [showShimmer, setShowShimmer] = useState(true);
  const shimmerAnim = useRef(new Animated.Value(1)).current;
  const pulseRef = useRef<Animated.CompositeAnimation | null>(null);
 
  useEffect(() => {
    if (!showShimmer) {
      pulseRef.current?.stop();
      return;
    }
 
    pulseRef.current = Animated.loop(
      Animated.sequence([
        Animated.timing(shimmerAnim, {
          toValue: 0.4,
          duration: 700,
          useNativeDriver: true,
        }),
        Animated.timing(shimmerAnim, {
          toValue: 1,
          duration: 700,
          useNativeDriver: true,
        }),
      ]),
    );
    pulseRef.current.start();
    return () => {
      pulseRef.current?.stop();
    };
  }, [shimmerAnim, showShimmer]);
 
  const handleLoad = useCallback(() => {
    pulseRef.current?.stop();
    Animated.timing(shimmerAnim, {
      toValue: 0,
      duration: 250,
      useNativeDriver: true,
    }).start(() => setShowShimmer(false));
    onLoad?.();
  }, [onLoad, shimmerAnim]);
 
  const handleError = useCallback(() => {
    pulseRef.current?.stop();
    setShowShimmer(false);
    onError?.();
  }, [onError]);
 
  const networkSource = isNetworkSource(source) ? source : null;
  const fastSource = useMemo(
    () =>
      networkSource
        ? {
            uri: networkSource.uri,
            headers: networkSource.headers,
            priority: PRIORITY_MAP[networkSource.priority ?? "normal"],
            cache: CACHE_MAP[networkSource.cache ?? "immutable"],
          }
        : (source as ImageSourcePropType),
    // primitives from networkSource fields are stable; object identity from local asset is stable
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [networkSource?.uri, networkSource?.priority, networkSource?.cache, networkSource, source],
  );
 
  return (
    <View style={[styles.container, style]}>
      <FastImage
        source={fastSource as any}
        style={StyleSheet.absoluteFillObject}
        resizeMode={RESIZE_MODE_MAP[resizeMode]}
        onLoad={handleLoad}
        onError={handleError}
      />
      {showShimmer && (
        <Animated.View
          style={[styles.shimmer, { backgroundColor: placeholderColor, opacity: shimmerAnim }]}
        />
      )}
    </View>
  );
});
 
export const preloadImages = (uris: string[]) => FastImage.preload(uris.map((uri) => ({ uri })));
 
const useStyles = makeStyles(() => ({
  container: {
    overflow: "hidden",
  },
  shimmer: {
    ...StyleSheet.absoluteFillObject,
  },
}));