fix(media): enable zoom in/out, pinch, double-tap and gesture controls in modules (Issue #34)

This commit is contained in:
ShivaniKhaire 2026-10-01 13:44:53 +05:30
parent 02682595c8
commit 5aaf74903d
4 changed files with 381 additions and 261 deletions

View File

@ -232,7 +232,7 @@ const styles = StyleSheet.create({
slide: { height: 290, alignItems: "center", justifyContent: "center" },
image: { width: "100%", height: "100%", backgroundColor: Colors.surface },
loadingOverlay: {
...StyleSheet.absoluteFillObject,
...StyleSheet.absoluteFill,
alignItems: "center",
justifyContent: "center",
backgroundColor: Colors.surface,

View File

@ -10,13 +10,14 @@ import {
View,
ViewToken,
} from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { SafeAreaView } from "react-native-safe-area-context";
import { useAuthStore } from "@/store/auth.store";
import { Colors } from "@/theme/colors";
import type { ContentMediaItem } from "../types/media.types";
import { mediaLabel } from "./media-source";
import { ZoomableImage } from "./ZoomableImage";
import { ZoomableImage, type ZoomableImageRef } from "./ZoomableImage";
interface FullScreenMediaViewerProps {
visible: boolean;
@ -32,6 +33,7 @@ export function FullScreenMediaViewer({
onClose,
}: FullScreenMediaViewerProps) {
const listRef = useRef<FlatList<ContentMediaItem>>(null);
const zoomableRefs = useRef<{ [index: number]: ZoomableImageRef | null }>({});
const { width, height } = useWindowDimensions();
const accessToken = useAuthStore((state) => state.accessToken);
const [activeIndex, setActiveIndex] = useState(initialIndex);
@ -61,6 +63,18 @@ export function FullScreenMediaViewer({
const active = images[activeIndex];
const handleZoomIn = () => {
zoomableRefs.current[activeIndex]?.zoomIn();
};
const handleZoomOut = () => {
zoomableRefs.current[activeIndex]?.zoomOut();
};
const handleResetZoom = () => {
zoomableRefs.current[activeIndex]?.resetZoom();
};
return (
<Modal
visible={visible}
@ -69,63 +83,106 @@ export function FullScreenMediaViewer({
statusBarTranslucent
onRequestClose={onClose}
>
<SafeAreaView style={styles.root}>
<View style={styles.toolbar}>
<Text style={styles.counter} accessibilityLiveRegion="polite">
{activeIndex + 1} / {images.length}
</Text>
<Pressable
onPress={onClose}
hitSlop={16}
accessibilityRole="button"
accessibilityLabel="Close image viewer"
style={({ pressed }) => [styles.closeButton, pressed && styles.pressed]}
>
<Ionicons name="close" size={28} color={Colors.white} />
</Pressable>
</View>
<GestureHandlerRootView style={styles.modalRoot}>
<SafeAreaView style={styles.root}>
<View style={styles.toolbar}>
<Text style={styles.counter} accessibilityLiveRegion="polite">
{activeIndex + 1} / {images.length}
</Text>
<FlatList
ref={listRef}
data={images}
horizontal
pagingEnabled
scrollEnabled={!zoomed}
showsHorizontalScrollIndicator={false}
keyExtractor={(item) => item.id}
initialScrollIndex={Math.min(initialIndex, Math.max(images.length - 1, 0))}
getItemLayout={(_data, index) => ({ length: width, offset: width * index, index })}
onScrollToIndexFailed={(info) => {
requestAnimationFrame(() => {
listRef.current?.scrollToOffset({ offset: info.index * width, animated: false });
});
}}
viewabilityConfig={{ itemVisiblePercentThreshold: 60 }}
onViewableItemsChanged={onViewableItemsChanged}
renderItem={({ item, index }) => (
<ZoomableImage
item={item}
accessToken={accessToken}
width={width}
height={Math.max(height - 150, 320)}
active={index === activeIndex}
onZoomStateChange={index === activeIndex ? setZoomed : undefined}
/>
)}
/>
<View style={styles.toolbarActions}>
<Pressable
onPress={handleZoomIn}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel="Zoom in"
style={({ pressed }) => [styles.toolButton, pressed && styles.pressed]}
>
<Ionicons name="add" size={22} color={Colors.white} />
</Pressable>
<View style={styles.footer}>
<Text numberOfLines={2} style={styles.caption}>
{mediaLabel(active, activeIndex)}
</Text>
<Text style={styles.hint}>Pinch or double-tap to zoom</Text>
</View>
</SafeAreaView>
<Pressable
onPress={handleZoomOut}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel="Zoom out"
style={({ pressed }) => [styles.toolButton, pressed && styles.pressed]}
>
<Ionicons name="remove" size={22} color={Colors.white} />
</Pressable>
{zoomed && (
<Pressable
onPress={handleResetZoom}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel="Reset zoom"
style={({ pressed }) => [styles.toolButton, pressed && styles.pressed]}
>
<Ionicons name="refresh-outline" size={20} color={Colors.white} />
</Pressable>
)}
<Pressable
onPress={onClose}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel="Close image viewer"
style={({ pressed }) => [styles.closeButton, pressed && styles.pressed]}
>
<Ionicons name="close" size={24} color={Colors.white} />
</Pressable>
</View>
</View>
<FlatList
ref={listRef}
data={images}
horizontal
pagingEnabled
scrollEnabled={!zoomed}
showsHorizontalScrollIndicator={false}
keyExtractor={(item) => item.id}
initialScrollIndex={Math.min(initialIndex, Math.max(images.length - 1, 0))}
getItemLayout={(_data, index) => ({ length: width, offset: width * index, index })}
onScrollToIndexFailed={(info) => {
requestAnimationFrame(() => {
listRef.current?.scrollToOffset({ offset: info.index * width, animated: false });
});
}}
viewabilityConfig={{ itemVisiblePercentThreshold: 60 }}
onViewableItemsChanged={onViewableItemsChanged}
renderItem={({ item, index }) => (
<ZoomableImage
ref={(instance) => {
zoomableRefs.current[index] = instance;
}}
item={item}
accessToken={accessToken}
width={width}
height={Math.max(height - 150, 320)}
active={index === activeIndex}
onZoomStateChange={index === activeIndex ? setZoomed : undefined}
/>
)}
/>
<View style={styles.footer}>
<Text numberOfLines={2} style={styles.caption}>
{mediaLabel(active, activeIndex)}
</Text>
<Text style={styles.hint}>
Pinch, double-tap, or use +/- to zoom · Drag to pan
</Text>
</View>
</SafeAreaView>
</GestureHandlerRootView>
</Modal>
);
}
const styles = StyleSheet.create({
modalRoot: { flex: 1, backgroundColor: Colors.black },
root: { flex: 1, backgroundColor: Colors.black },
toolbar: {
height: 56,
@ -136,13 +193,27 @@ const styles = StyleSheet.create({
justifyContent: "space-between",
},
counter: { color: Colors.white, fontSize: 15, fontWeight: "700" },
closeButton: {
width: 44,
height: 44,
borderRadius: 22,
toolbarActions: {
flexDirection: "row",
alignItems: "center",
gap: 8,
},
toolButton: {
width: 38,
height: 38,
borderRadius: 19,
alignItems: "center",
justifyContent: "center",
backgroundColor: "rgba(255,255,255,0.12)",
backgroundColor: "rgba(255,255,255,0.14)",
},
closeButton: {
width: 38,
height: 38,
borderRadius: 19,
alignItems: "center",
justifyContent: "center",
backgroundColor: "rgba(255,255,255,0.22)",
marginLeft: 4,
},
pressed: { opacity: 0.65 },
footer: {

View File

@ -1,4 +1,12 @@
import React, { memo, useEffect, useMemo, useState } from "react";
import React, {
forwardRef,
memo,
useCallback,
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";
@ -17,7 +25,13 @@ const MIN_SCALE = 1;
const MAX_SCALE = 4;
const DOUBLE_TAP_SCALE = 2.5;
interface ZoomableImageProps {
export interface ZoomableImageRef {
zoomIn: () => void;
zoomOut: () => void;
resetZoom: () => void;
}
export interface ZoomableImageProps {
item: ContentMediaItem;
accessToken: string | null;
width: number;
@ -31,185 +45,231 @@ function clamp(value: number, min: number, max: number): number {
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);
export const ZoomableImage = memo(
forwardRef<ZoomableImageRef, 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 [isZoomed, setIsZoomed] = useState(false);
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 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;
const sourceUri =
source && typeof source === "object" && !Array.isArray(source)
? source.uri ?? null
: null;
useEffect(() => {
setFailed(false);
setLoading(Boolean(sourceUri));
}, [sourceUri]);
useEffect(() => {
setFailed(false);
setLoading(Boolean(sourceUri));
}, [sourceUri]);
const notifyZoom = (zoomed: boolean) => {
setIsZoomed(zoomed);
onZoomStateChange?.(zoomed);
};
const notifyZoom = useCallback(
(zoomed: boolean) => {
setIsZoomed(zoomed);
onZoomStateChange?.(zoomed);
},
[onZoomStateChange],
);
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;
const reset = useCallback(() => {
"worklet";
scale.value = withTiming(1);
savedScale.value = 1;
translateX.value = 0;
translateY.value = 0;
translateX.value = withTiming(0);
translateY.value = withTiming(0);
savedX.value = 0;
savedY.value = 0;
setIsZoomed(false);
onZoomStateChange?.(false);
}
}, [active, onZoomStateChange, savedScale, savedX, savedY, scale, translateX, translateY]);
}, [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);
useImperativeHandle(
ref,
() => ({
zoomIn: () => {
const nextScale = Math.min(savedScale.value + 0.75, MAX_SCALE);
scale.value = withTiming(nextScale);
savedScale.value = nextScale;
notifyZoom(true);
},
zoomOut: () => {
const nextScale = Math.max(savedScale.value - 0.75, MIN_SCALE);
scale.value = withTiming(nextScale);
savedScale.value = nextScale;
if (nextScale <= 1.01) {
reset();
notifyZoom(false);
} else {
const maxX = ((nextScale - 1) * width) / 2;
const maxY = ((nextScale - 1) * height) / 2;
const nextX = Math.min(Math.max(savedX.value, -maxX), maxX);
const nextY = Math.min(Math.max(savedY.value, -maxY), maxY);
translateX.value = withTiming(nextX);
translateY.value = withTiming(nextY);
savedX.value = nextX;
savedY.value = nextY;
notifyZoom(true);
}
},
resetZoom: () => {
reset();
notifyZoom(false);
},
}),
[height, notifyZoom, reset, savedScale, savedX, savedY, scale, translateX, translateY, width],
);
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 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;
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);
} else {
runOnJS(notifyZoom)(true);
}
});
const gesture = Gesture.Race(doubleTap, Gesture.Simultaneous(pinch, pan));
const pan = Gesture.Pan()
.enabled(isZoomed)
.minDistance(8)
.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 animatedStyle = useAnimatedStyle(() => ({
transform: [
{ translateX: translateX.value },
{ translateY: translateY.value },
{ scale: scale.value },
],
}));
const doubleTap = Gesture.Tap()
.numberOfTaps(2)
.maxDuration(300)
.onEnd((_event, success) => {
if (!success) return;
if (scale.value > 1.05) {
reset();
runOnJS(notifyZoom)(false);
} else {
scale.value = withTiming(DOUBLE_TAP_SCALE);
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>
);
}
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>
{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>
);
}
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
}),
(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({
@ -222,7 +282,7 @@ const styles = StyleSheet.create({
imageWrap: { width: "100%", height: "100%" },
image: { width: "100%", height: "100%" },
loader: {
...StyleSheet.absoluteFillObject,
...StyleSheet.absoluteFill,
zIndex: 2,
alignItems: "center",
justifyContent: "center",

View File

@ -1,53 +1,42 @@
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { Image } from "expo-image";
import React, { useMemo } from "react";
import { ContentMediaGallery } from "../../media/ContentMediaGallery";
import { useRelationalContentMedia } from "../../media/ContentMediaContext";
import type { ContentMediaItem } from "../../types/media.types";
import { asString } from "../helpers/value";
export function ImageGallery({ images }: { images: Record<string, unknown>[] }) {
const relationalMedia = useRelationalContentMedia();
if (relationalMedia.length > 0) {
return <ContentMediaGallery media={relationalMedia} title="Visual reference" />;
}
const mappedMedia: ContentMediaItem[] = useMemo(() => {
if (relationalMedia.length > 0) return relationalMedia;
const visible = images.filter((item) => asString(item.image_path).trim().length > 0);
if (!visible.length) return null;
const visible = (images ?? []).filter(
(item) => asString(item.image_path).trim().length > 0,
);
return (
<View style={styles.root}>
{visible.map((item, index) => {
const path = asString(item.image_path);
const name = asString(item.image_name);
return (
<View key={`${path}-${index}`} style={styles.item}>
<View style={styles.imageFrame}>
<Image source={{ uri: path }} contentFit="contain" style={styles.image} />
</View>
{name ? <Text style={styles.caption}>{name}</Text> : null}
</View>
);
})}
</View>
);
return visible.map((item, index) => {
const path = asString(item.image_path).trim();
const name = asString(item.image_name).trim();
return {
id: `img-${index}-${path}`,
media_asset_id: `asset-${index}`,
media_role: "gallery",
usage_type: "illustration",
sort_order: index,
caption: name || null,
alt_text: name || "Module illustration",
mime_type: null,
width: null,
height: null,
url: path,
storage_key: null,
requires_auth: false,
};
});
}, [relationalMedia, images]);
if (!mappedMedia.length) return null;
return <ContentMediaGallery media={mappedMedia} title="Visual reference" />;
}
const styles = StyleSheet.create({
root: { gap: 14 },
item: { gap: 7 },
imageFrame: {
overflow: "hidden",
borderRadius: 18,
backgroundColor: "#F4F7F5",
borderWidth: 1,
borderColor: "#DDE7E1",
},
image: { width: "100%", height: 270 },
caption: {
fontSize: 13,
lineHeight: 19,
color: "#64748B",
textAlign: "center",
},
});