import React, { memo, useEffect, useMemo, useState } from "react";
import { ActivityIndicator, StyleSheet, Text, View } from "react-native";
import { Image } from "expo-image";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import Animated, {
runOnJS,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { Colors } from "@/theme/colors";
import type { ContentMediaItem } from "../types/media.types";
import { buildMediaImageSourceFromValues } from "./media-source";
const MIN_SCALE = 1;
const MAX_SCALE = 4;
const DOUBLE_TAP_SCALE = 2.5;
interface ZoomableImageProps {
item: ContentMediaItem;
accessToken: string | null;
width: number;
height: number;
active: boolean;
onZoomStateChange?: (zoomed: boolean) => void;
}
function clamp(value: number, min: number, max: number): number {
"worklet";
return Math.min(Math.max(value, min), max);
}
export const ZoomableImage = memo(function ZoomableImage({
item,
accessToken,
width,
height,
active,
onZoomStateChange,
}: ZoomableImageProps) {
const scale = useSharedValue(1);
const savedScale = useSharedValue(1);
const translateX = useSharedValue(0);
const translateY = useSharedValue(0);
const savedX = useSharedValue(0);
const savedY = useSharedValue(0);
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [isZoomed, setIsZoomed] = useState(false);
const source = useMemo(
() =>
buildMediaImageSourceFromValues(
item.url,
item.storage_key,
item.requires_auth,
accessToken,
),
[item.url, item.storage_key, item.requires_auth, accessToken],
);
const sourceUri =
source && typeof source === "object" && !Array.isArray(source)
? source.uri ?? null
: null;
useEffect(() => {
setFailed(false);
setLoading(Boolean(sourceUri));
}, [sourceUri]);
const notifyZoom = (zoomed: boolean) => {
setIsZoomed(zoomed);
onZoomStateChange?.(zoomed);
};
const reset = () => {
"worklet";
scale.value = withTiming(1);
savedScale.value = 1;
translateX.value = withTiming(0);
translateY.value = withTiming(0);
savedX.value = 0;
savedY.value = 0;
};
useEffect(() => {
if (!active) {
scale.value = 1;
savedScale.value = 1;
translateX.value = 0;
translateY.value = 0;
savedX.value = 0;
savedY.value = 0;
setIsZoomed(false);
onZoomStateChange?.(false);
}
}, [active, onZoomStateChange, savedScale, savedX, savedY, scale, translateX, translateY]);
const pinch = Gesture.Pinch()
.onBegin(() => {
runOnJS(notifyZoom)(true);
})
.onUpdate((event) => {
scale.value = clamp(savedScale.value * event.scale, MIN_SCALE, MAX_SCALE);
})
.onEnd(() => {
savedScale.value = scale.value;
if (scale.value <= 1.01) {
reset();
runOnJS(notifyZoom)(false);
}
});
const pan = Gesture.Pan()
.enabled(isZoomed)
.maxPointers(1)
.onUpdate((event) => {
if (scale.value <= 1) return;
const maxX = ((scale.value - 1) * width) / 2;
const maxY = ((scale.value - 1) * height) / 2;
translateX.value = clamp(savedX.value + event.translationX, -maxX, maxX);
translateY.value = clamp(savedY.value + event.translationY, -maxY, maxY);
})
.onEnd(() => {
savedX.value = translateX.value;
savedY.value = translateY.value;
});
const doubleTap = Gesture.Tap()
.numberOfTaps(2)
.maxDuration(250)
.onEnd((_event, success) => {
if (!success) return;
if (scale.value > 1.01) {
reset();
runOnJS(notifyZoom)(false);
} else {
scale.value = withTiming(DOUBLE_TAP_SCALE);
savedScale.value = DOUBLE_TAP_SCALE;
runOnJS(notifyZoom)(true);
}
});
const gesture = Gesture.Race(doubleTap, Gesture.Simultaneous(pinch, pan));
const animatedStyle = useAnimatedStyle(() => ({
transform: [
{ translateX: translateX.value },
{ translateY: translateY.value },
{ scale: scale.value },
],
}));
if (!source) {
return (
Image unavailable
No media URL is available for this image.
);
}
return (
{loading && !failed ? (
) : null}
{failed ? (
Unable to load image
Check your connection and try again.
) : (
setLoading(false)}
onError={(error) => {
console.warn("Failed to load ZoomableImage:", source, error);
setLoading(false);
setFailed(true);
}}
/>
)}
);;
}, (previous, next) =>
previous.item.id === next.item.id &&
previous.item.url === next.item.url &&
previous.item.storage_key === next.item.storage_key &&
previous.item.requires_auth === next.item.requires_auth &&
previous.accessToken === next.accessToken &&
previous.width === next.width &&
previous.height === next.height &&
previous.active === next.active &&
previous.onZoomStateChange === next.onZoomStateChange
);
const styles = StyleSheet.create({
frame: {
overflow: "hidden",
alignItems: "center",
justifyContent: "center",
backgroundColor: Colors.black,
},
imageWrap: { width: "100%", height: "100%" },
image: { width: "100%", height: "100%" },
loader: {
...StyleSheet.absoluteFillObject,
zIndex: 2,
alignItems: "center",
justifyContent: "center",
},
error: {
paddingHorizontal: 24,
alignItems: "center",
justifyContent: "center",
},
errorTitle: { color: Colors.white, fontSize: 16, fontWeight: "700" },
errorText: { marginTop: 6, color: "#C7C7C7", fontSize: 13, textAlign: "center" },
});