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" }, slide: { height: 290, alignItems: "center", justifyContent: "center" },
image: { width: "100%", height: "100%", backgroundColor: Colors.surface }, image: { width: "100%", height: "100%", backgroundColor: Colors.surface },
loadingOverlay: { loadingOverlay: {
...StyleSheet.absoluteFillObject, ...StyleSheet.absoluteFill,
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
backgroundColor: Colors.surface, backgroundColor: Colors.surface,

View File

@ -10,13 +10,14 @@ import {
View, View,
ViewToken, ViewToken,
} from "react-native"; } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { SafeAreaView } from "react-native-safe-area-context"; import { SafeAreaView } from "react-native-safe-area-context";
import { useAuthStore } from "@/store/auth.store"; import { useAuthStore } from "@/store/auth.store";
import { Colors } from "@/theme/colors"; import { Colors } from "@/theme/colors";
import type { ContentMediaItem } from "../types/media.types"; import type { ContentMediaItem } from "../types/media.types";
import { mediaLabel } from "./media-source"; import { mediaLabel } from "./media-source";
import { ZoomableImage } from "./ZoomableImage"; import { ZoomableImage, type ZoomableImageRef } from "./ZoomableImage";
interface FullScreenMediaViewerProps { interface FullScreenMediaViewerProps {
visible: boolean; visible: boolean;
@ -32,6 +33,7 @@ export function FullScreenMediaViewer({
onClose, onClose,
}: FullScreenMediaViewerProps) { }: FullScreenMediaViewerProps) {
const listRef = useRef<FlatList<ContentMediaItem>>(null); const listRef = useRef<FlatList<ContentMediaItem>>(null);
const zoomableRefs = useRef<{ [index: number]: ZoomableImageRef | null }>({});
const { width, height } = useWindowDimensions(); const { width, height } = useWindowDimensions();
const accessToken = useAuthStore((state) => state.accessToken); const accessToken = useAuthStore((state) => state.accessToken);
const [activeIndex, setActiveIndex] = useState(initialIndex); const [activeIndex, setActiveIndex] = useState(initialIndex);
@ -61,6 +63,18 @@ export function FullScreenMediaViewer({
const active = images[activeIndex]; const active = images[activeIndex];
const handleZoomIn = () => {
zoomableRefs.current[activeIndex]?.zoomIn();
};
const handleZoomOut = () => {
zoomableRefs.current[activeIndex]?.zoomOut();
};
const handleResetZoom = () => {
zoomableRefs.current[activeIndex]?.resetZoom();
};
return ( return (
<Modal <Modal
visible={visible} visible={visible}
@ -69,21 +83,57 @@ export function FullScreenMediaViewer({
statusBarTranslucent statusBarTranslucent
onRequestClose={onClose} onRequestClose={onClose}
> >
<GestureHandlerRootView style={styles.modalRoot}>
<SafeAreaView style={styles.root}> <SafeAreaView style={styles.root}>
<View style={styles.toolbar}> <View style={styles.toolbar}>
<Text style={styles.counter} accessibilityLiveRegion="polite"> <Text style={styles.counter} accessibilityLiveRegion="polite">
{activeIndex + 1} / {images.length} {activeIndex + 1} / {images.length}
</Text> </Text>
<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>
<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 <Pressable
onPress={onClose} onPress={onClose}
hitSlop={16} hitSlop={8}
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel="Close image viewer" accessibilityLabel="Close image viewer"
style={({ pressed }) => [styles.closeButton, pressed && styles.pressed]} style={({ pressed }) => [styles.closeButton, pressed && styles.pressed]}
> >
<Ionicons name="close" size={28} color={Colors.white} /> <Ionicons name="close" size={24} color={Colors.white} />
</Pressable> </Pressable>
</View> </View>
</View>
<FlatList <FlatList
ref={listRef} ref={listRef}
@ -104,6 +154,9 @@ export function FullScreenMediaViewer({
onViewableItemsChanged={onViewableItemsChanged} onViewableItemsChanged={onViewableItemsChanged}
renderItem={({ item, index }) => ( renderItem={({ item, index }) => (
<ZoomableImage <ZoomableImage
ref={(instance) => {
zoomableRefs.current[index] = instance;
}}
item={item} item={item}
accessToken={accessToken} accessToken={accessToken}
width={width} width={width}
@ -118,14 +171,18 @@ export function FullScreenMediaViewer({
<Text numberOfLines={2} style={styles.caption}> <Text numberOfLines={2} style={styles.caption}>
{mediaLabel(active, activeIndex)} {mediaLabel(active, activeIndex)}
</Text> </Text>
<Text style={styles.hint}>Pinch or double-tap to zoom</Text> <Text style={styles.hint}>
Pinch, double-tap, or use +/- to zoom · Drag to pan
</Text>
</View> </View>
</SafeAreaView> </SafeAreaView>
</GestureHandlerRootView>
</Modal> </Modal>
); );
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
modalRoot: { flex: 1, backgroundColor: Colors.black },
root: { flex: 1, backgroundColor: Colors.black }, root: { flex: 1, backgroundColor: Colors.black },
toolbar: { toolbar: {
height: 56, height: 56,
@ -136,13 +193,27 @@ const styles = StyleSheet.create({
justifyContent: "space-between", justifyContent: "space-between",
}, },
counter: { color: Colors.white, fontSize: 15, fontWeight: "700" }, counter: { color: Colors.white, fontSize: 15, fontWeight: "700" },
closeButton: { toolbarActions: {
width: 44, flexDirection: "row",
height: 44, alignItems: "center",
borderRadius: 22, gap: 8,
},
toolButton: {
width: 38,
height: 38,
borderRadius: 19,
alignItems: "center", alignItems: "center",
justifyContent: "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 }, pressed: { opacity: 0.65 },
footer: { 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 { ActivityIndicator, StyleSheet, Text, View } from "react-native";
import { Image } from "expo-image"; import { Image } from "expo-image";
import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { Gesture, GestureDetector } from "react-native-gesture-handler";
@ -17,7 +25,13 @@ const MIN_SCALE = 1;
const MAX_SCALE = 4; const MAX_SCALE = 4;
const DOUBLE_TAP_SCALE = 2.5; const DOUBLE_TAP_SCALE = 2.5;
interface ZoomableImageProps { export interface ZoomableImageRef {
zoomIn: () => void;
zoomOut: () => void;
resetZoom: () => void;
}
export interface ZoomableImageProps {
item: ContentMediaItem; item: ContentMediaItem;
accessToken: string | null; accessToken: string | null;
width: number; width: number;
@ -31,14 +45,18 @@ function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max); return Math.min(Math.max(value, min), max);
} }
export const ZoomableImage = memo(function ZoomableImage({ export const ZoomableImage = memo(
forwardRef<ZoomableImageRef, ZoomableImageProps>(function ZoomableImage(
{
item, item,
accessToken, accessToken,
width, width,
height, height,
active, active,
onZoomStateChange, onZoomStateChange,
}: ZoomableImageProps) { },
ref,
) {
const scale = useSharedValue(1); const scale = useSharedValue(1);
const savedScale = useSharedValue(1); const savedScale = useSharedValue(1);
const translateX = useSharedValue(0); const translateX = useSharedValue(0);
@ -71,12 +89,15 @@ export const ZoomableImage = memo(function ZoomableImage({
setLoading(Boolean(sourceUri)); setLoading(Boolean(sourceUri));
}, [sourceUri]); }, [sourceUri]);
const notifyZoom = (zoomed: boolean) => { const notifyZoom = useCallback(
(zoomed: boolean) => {
setIsZoomed(zoomed); setIsZoomed(zoomed);
onZoomStateChange?.(zoomed); onZoomStateChange?.(zoomed);
}; },
[onZoomStateChange],
);
const reset = () => { const reset = useCallback(() => {
"worklet"; "worklet";
scale.value = withTiming(1); scale.value = withTiming(1);
savedScale.value = 1; savedScale.value = 1;
@ -84,7 +105,43 @@ export const ZoomableImage = memo(function ZoomableImage({
translateY.value = withTiming(0); translateY.value = withTiming(0);
savedX.value = 0; savedX.value = 0;
savedY.value = 0; savedY.value = 0;
}; }, [savedScale, savedX, savedY, scale, translateX, translateY]);
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(() => { useEffect(() => {
if (!active) { if (!active) {
@ -111,12 +168,14 @@ export const ZoomableImage = memo(function ZoomableImage({
if (scale.value <= 1.01) { if (scale.value <= 1.01) {
reset(); reset();
runOnJS(notifyZoom)(false); runOnJS(notifyZoom)(false);
} else {
runOnJS(notifyZoom)(true);
} }
}); });
const pan = Gesture.Pan() const pan = Gesture.Pan()
.enabled(isZoomed) .enabled(isZoomed)
.maxPointers(1) .minDistance(8)
.onUpdate((event) => { .onUpdate((event) => {
if (scale.value <= 1) return; if (scale.value <= 1) return;
const maxX = ((scale.value - 1) * width) / 2; const maxX = ((scale.value - 1) * width) / 2;
@ -131,10 +190,10 @@ export const ZoomableImage = memo(function ZoomableImage({
const doubleTap = Gesture.Tap() const doubleTap = Gesture.Tap()
.numberOfTaps(2) .numberOfTaps(2)
.maxDuration(250) .maxDuration(300)
.onEnd((_event, success) => { .onEnd((_event, success) => {
if (!success) return; if (!success) return;
if (scale.value > 1.01) { if (scale.value > 1.05) {
reset(); reset();
runOnJS(notifyZoom)(false); runOnJS(notifyZoom)(false);
} else { } else {
@ -144,7 +203,7 @@ export const ZoomableImage = memo(function ZoomableImage({
} }
}); });
const gesture = Gesture.Race(doubleTap, Gesture.Simultaneous(pinch, pan)); const gesture = Gesture.Exclusive(doubleTap, Gesture.Simultaneous(pinch, pan));
const animatedStyle = useAnimatedStyle(() => ({ const animatedStyle = useAnimatedStyle(() => ({
transform: [ transform: [
@ -199,8 +258,9 @@ export const ZoomableImage = memo(function ZoomableImage({
</GestureDetector> </GestureDetector>
)} )}
</View> </View>
);; );
}, (previous, next) => }),
(previous, next) =>
previous.item.id === next.item.id && previous.item.id === next.item.id &&
previous.item.url === next.item.url && previous.item.url === next.item.url &&
previous.item.storage_key === next.item.storage_key && previous.item.storage_key === next.item.storage_key &&
@ -209,7 +269,7 @@ export const ZoomableImage = memo(function ZoomableImage({
previous.width === next.width && previous.width === next.width &&
previous.height === next.height && previous.height === next.height &&
previous.active === next.active && previous.active === next.active &&
previous.onZoomStateChange === next.onZoomStateChange previous.onZoomStateChange === next.onZoomStateChange,
); );
const styles = StyleSheet.create({ const styles = StyleSheet.create({
@ -222,7 +282,7 @@ const styles = StyleSheet.create({
imageWrap: { width: "100%", height: "100%" }, imageWrap: { width: "100%", height: "100%" },
image: { width: "100%", height: "100%" }, image: { width: "100%", height: "100%" },
loader: { loader: {
...StyleSheet.absoluteFillObject, ...StyleSheet.absoluteFill,
zIndex: 2, zIndex: 2,
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",

View File

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