acupedia-mobile-ui/src/features/content/media/ZoomableImage.tsx

283 lines
8.0 KiB
TypeScript

import React, {
forwardRef,
memo,
useEffect,
useImperativeHandle,
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;
const SCALE_STEP = 0.75;
export interface ZoomableImageHandle {
zoomIn: () => void;
zoomOut: () => void;
resetZoom: () => void;
}
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(
forwardRef<ZoomableImageHandle, ZoomableImageProps>(function ZoomableImage(
{
item,
accessToken,
width,
height,
active,
onZoomStateChange,
},
ref,
) {
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 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) => {
onZoomStateChange?.(zoomed);
};
const reset = () => {
"worklet";
scale.value = withTiming(1, { duration: 250 });
savedScale.value = 1;
translateX.value = withTiming(0, { duration: 250 });
translateY.value = withTiming(0, { duration: 250 });
savedX.value = 0;
savedY.value = 0;
};
useImperativeHandle(
ref,
() => ({
zoomIn: () => {
const next = Math.min(savedScale.value + SCALE_STEP, MAX_SCALE);
savedScale.value = next;
scale.value = withTiming(next, { duration: 250 });
notifyZoom(next > 1.01);
},
zoomOut: () => {
const next = Math.max(savedScale.value - SCALE_STEP, MIN_SCALE);
savedScale.value = next;
scale.value = withTiming(next, { duration: 250 });
if (next <= 1.01) {
translateX.value = withTiming(0, { duration: 250 });
translateY.value = withTiming(0, { duration: 250 });
savedX.value = 0;
savedY.value = 0;
notifyZoom(false);
}
},
resetZoom: () => {
reset();
notifyZoom(false);
},
}),
[],
);
useEffect(() => {
if (!active) {
scale.value = 1;
savedScale.value = 1;
translateX.value = 0;
translateY.value = 0;
savedX.value = 0;
savedY.value = 0;
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()
.minDistance(8)
.maxPointers(1)
.onUpdate((event) => {
if (scale.value <= 1.01) return;
const maxX = Math.max(0, ((scale.value - 1) * width) / 2);
const maxY = Math.max(0, ((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, { duration: 250 });
savedScale.value = DOUBLE_TAP_SCALE;
runOnJS(notifyZoom)(true);
}
});
const gesture = Gesture.Exclusive(doubleTap, Gesture.Simultaneous(pinch, pan));
const animatedStyle = useAnimatedStyle(() => ({
transform: [
{ translateX: translateX.value },
{ translateY: translateY.value },
{ scale: scale.value },
],
}));
if (!source) {
return (
<View style={[styles.frame, { width, height }]}>
<View style={styles.error}>
<Text style={styles.errorTitle}>Image unavailable</Text>
<Text style={styles.errorText}>No media URL is available for this image.</Text>
</View>
</View>
);
}
return (
<View style={[styles.frame, { width, height }]}>
{loading && !failed ? (
<View style={styles.loader} pointerEvents="none">
<ActivityIndicator size="large" color={Colors.white} />
</View>
) : null}
{failed ? (
<View style={styles.error}>
<Text style={styles.errorTitle}>Unable to load image</Text>
<Text style={styles.errorText}>Check your connection and try again.</Text>
</View>
) : (
<GestureDetector gesture={gesture}>
<Animated.View style={[styles.imageWrap, animatedStyle]}>
<Image
source={source}
contentFit="contain"
style={styles.image}
accessible
accessibilityRole="image"
accessibilityLabel={item.alt_text || item.caption || "Content image"}
onLoad={() => setLoading(false)}
onError={(error) => {
console.warn("Failed to load ZoomableImage:", source, error);
setLoading(false);
setFailed(true);
}}
/>
</Animated.View>
</GestureDetector>
)}
</View>
);
}),
(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.absoluteFill as object),
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" },
});