From 64fbc89b3612d457f8271948cad69eb13f90281d Mon Sep 17 00:00:00 2001 From: ShivaniKhaire Date: Thu, 1 Oct 2026 15:55:27 +0530 Subject: [PATCH] fix(media): fix image operations, gestures, and zoom controls in modules (Issue #34) --- .../content/media/ContentMediaGallery.tsx | 4 +- .../content/media/FullScreenMediaViewer.tsx | 182 ++++++--- src/features/content/media/ZoomableImage.tsx | 367 ++++++++++-------- src/features/content/media/media-source.ts | 2 +- .../content/renderers/shared/ImageGallery.tsx | 39 +- 5 files changed, 363 insertions(+), 231 deletions(-) diff --git a/src/features/content/media/ContentMediaGallery.tsx b/src/features/content/media/ContentMediaGallery.tsx index 48d6b9b..ce0939b 100644 --- a/src/features/content/media/ContentMediaGallery.tsx +++ b/src/features/content/media/ContentMediaGallery.tsx @@ -31,7 +31,7 @@ function sortMedia(media: ContentMediaItem[]): ContentMediaItem[] { .sort((a, b) => { if (a.media_role === "primary" && b.media_role !== "primary") return -1; if (b.media_role === "primary" && a.media_role !== "primary") return 1; - return a.sort_order - b.sort_order || a.id.localeCompare(b.id); + return (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.id.localeCompare(b.id); }); } @@ -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 as object), alignItems: "center", justifyContent: "center", backgroundColor: Colors.surface, diff --git a/src/features/content/media/FullScreenMediaViewer.tsx b/src/features/content/media/FullScreenMediaViewer.tsx index 44ed5e9..93db4e5 100644 --- a/src/features/content/media/FullScreenMediaViewer.tsx +++ b/src/features/content/media/FullScreenMediaViewer.tsx @@ -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 ZoomableImageHandle } from "./ZoomableImage"; interface FullScreenMediaViewerProps { visible: boolean; @@ -32,6 +33,7 @@ export function FullScreenMediaViewer({ onClose, }: FullScreenMediaViewerProps) { const listRef = useRef>(null); + const imageRefs = useRef>(new Map()); const { width, height } = useWindowDimensions(); const accessToken = useAuthStore((state) => state.accessToken); const [activeIndex, setActiveIndex] = useState(initialIndex); @@ -61,6 +63,24 @@ export function FullScreenMediaViewer({ const active = images[activeIndex]; + const handleZoomIn = () => { + if (active) { + imageRefs.current.get(active.id)?.zoomIn(); + } + }; + + const handleZoomOut = () => { + if (active) { + imageRefs.current.get(active.id)?.zoomOut(); + } + }; + + const handleResetZoom = () => { + if (active) { + imageRefs.current.get(active.id)?.resetZoom(); + } + }; + return ( - - - - {activeIndex + 1} / {images.length} - - [styles.closeButton, pressed && styles.pressed]} - > - - - + + + + + {activeIndex + 1} / {images.length} + - 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 }) => ( - - )} - /> + + [styles.controlButton, pressed && styles.pressed]} + > + + - - - {mediaLabel(active, activeIndex)} - - Pinch or double-tap to zoom - - + [styles.controlButton, pressed && styles.pressed]} + > + + + + [styles.controlButton, pressed && styles.pressed]} + > + + + + + [styles.closeButton, pressed && styles.pressed]} + > + + + + + 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 }) => ( + { + if (handle) { + imageRefs.current.set(item.id, handle); + } else { + imageRefs.current.delete(item.id); + } + }} + item={item} + accessToken={accessToken} + width={width} + height={Math.max(height - 150, 320)} + active={index === activeIndex} + onZoomStateChange={index === activeIndex ? setZoomed : undefined} + /> + )} + /> + + + + {mediaLabel(active, activeIndex)} + + + Pinch, double-tap, or use +/- to zoom ยท Drag to pan + + + + ); } const styles = StyleSheet.create({ + modalRoot: { flex: 1, backgroundColor: Colors.black }, root: { flex: 1, backgroundColor: Colors.black }, toolbar: { height: 56, @@ -136,6 +201,21 @@ const styles = StyleSheet.create({ justifyContent: "space-between", }, counter: { color: Colors.white, fontSize: 15, fontWeight: "700" }, + controlsGroup: { + flexDirection: "row", + alignItems: "center", + backgroundColor: "rgba(255,255,255,0.12)", + borderRadius: 20, + paddingHorizontal: 4, + gap: 4, + }, + controlButton: { + width: 36, + height: 36, + borderRadius: 18, + alignItems: "center", + justifyContent: "center", + }, closeButton: { width: 44, height: 44, diff --git a/src/features/content/media/ZoomableImage.tsx b/src/features/content/media/ZoomableImage.tsx index 876b218..edddfca 100644 --- a/src/features/content/media/ZoomableImage.tsx +++ b/src/features/content/media/ZoomableImage.tsx @@ -1,4 +1,11 @@ -import React, { memo, useEffect, useMemo, useState } from "react"; +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"; @@ -16,6 +23,13 @@ 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; @@ -31,185 +45,216 @@ 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(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 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 = (zoomed: boolean) => { + 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; + const reset = () => { + "worklet"; + scale.value = withTiming(1, { duration: 250 }); savedScale.value = 1; - translateX.value = 0; - translateY.value = 0; + translateX.value = withTiming(0, { duration: 250 }); + translateY.value = withTiming(0, { duration: 250 }); 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); + 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 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); + } + }); - const gesture = Gesture.Race(doubleTap, Gesture.Simultaneous(pinch, pan)); + 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 animatedStyle = useAnimatedStyle(() => ({ - transform: [ - { translateX: translateX.value }, - { translateY: translateY.value }, - { scale: scale.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 ( + + + Image unavailable + No media URL is available for this image. + + + ); + } - if (!source) { return ( - - Image unavailable - No media URL is available for this image. - + {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); + }} + /> + + + )} ); - } - - 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 + }), + (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 +267,7 @@ const styles = StyleSheet.create({ imageWrap: { width: "100%", height: "100%" }, image: { width: "100%", height: "100%" }, loader: { - ...StyleSheet.absoluteFillObject, + ...(StyleSheet.absoluteFill as object), zIndex: 2, alignItems: "center", justifyContent: "center", diff --git a/src/features/content/media/media-source.ts b/src/features/content/media/media-source.ts index d2e3a8b..cda8d78 100644 --- a/src/features/content/media/media-source.ts +++ b/src/features/content/media/media-source.ts @@ -82,7 +82,7 @@ export function mediaLabel(item: ContentMediaItem, index: number): string { return ( item.alt_text?.trim() || item.caption?.trim() || - item.usage_type.replace(/_/g, " ").trim() || + (item.usage_type ? item.usage_type.replace(/_/g, " ").trim() : "") || `Image ${index + 1}` ); } diff --git a/src/features/content/renderers/shared/ImageGallery.tsx b/src/features/content/renderers/shared/ImageGallery.tsx index f18e3a0..0f641de 100644 --- a/src/features/content/renderers/shared/ImageGallery.tsx +++ b/src/features/content/renderers/shared/ImageGallery.tsx @@ -5,6 +5,8 @@ import { ContentMediaGallery } from "../../media/ContentMediaGallery"; import { useRelationalContentMedia } from "../../media/ContentMediaContext"; import { asString } from "../helpers/value"; +import type { ContentMediaItem } from "../../types/media.types"; + export function ImageGallery({ images }: { images: Record[] }) { const relationalMedia = useRelationalContentMedia(); @@ -15,22 +17,27 @@ export function ImageGallery({ images }: { images: Record[] }) const visible = images.filter((item) => asString(item.image_path).trim().length > 0); if (!visible.length) return null; - return ( - - {visible.map((item, index) => { - const path = asString(item.image_path); - const name = asString(item.image_name); - return ( - - - - - {name ? {name} : null} - - ); - })} - - ); + const fallbackMedia: ContentMediaItem[] = visible.map((item, index) => { + const path = asString(item.image_path).trim(); + const name = asString(item.image_name).trim(); + return { + id: `${path}-${index}`, + media_asset_id: `${path}-${index}`, + media_role: index === 0 ? "primary" : "gallery", + usage_type: "visual_reference", + sort_order: index, + caption: name || null, + alt_text: name || "Module image", + mime_type: "image/jpeg", + width: null, + height: null, + url: path, + storage_key: null, + requires_auth: false, + }; + }); + + return ; } const styles = StyleSheet.create({ -- 2.34.1