import { Ionicons } from "@expo/vector-icons"; import React, { memo, useEffect, useMemo, useRef, useState } from "react"; import { ActivityIndicator, FlatList, Image, NativeScrollEvent, NativeSyntheticEvent, Pressable, StyleSheet, Text, useWindowDimensions, View, } from "react-native"; import { useAuthStore } from "@/store/auth.store"; import { Colors } from "@/theme/colors"; import { Spacing } from "@/theme/spacing"; import type { ContentMediaItem } from "../types/media.types"; import { FullScreenMediaViewer } from "./FullScreenMediaViewer"; import { buildMediaImageSourceFromValues, mediaLabel } from "./media-source"; interface ContentMediaGalleryProps { media?: ContentMediaItem[] | null; title?: string; } function sortMedia(media: ContentMediaItem[]): ContentMediaItem[] { return [...media] .filter((item) => item.url?.trim() || item.storage_key?.trim()) .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); }); } const GalleryImage = memo(function GalleryImage({ item, width, }: { item: ContentMediaItem; width: number; }) { const token = useAuthStore((state) => state.accessToken); const [loading, setLoading] = useState(true); const [failed, setFailed] = useState(false); /** * Memoize against primitive values only. * * React Query/backend hydration may replace the media object while keeping * the effective URL unchanged. Depending on the whole object would rebuild * `source`, causing React Native Web's to reload unnecessarily. */ const source = useMemo( () => buildMediaImageSourceFromValues( item.url, item.storage_key, item.requires_auth, token, ), [item.url, item.storage_key, item.requires_auth, token], ); const sourceUri = source && typeof source === "object" && !Array.isArray(source) ? source.uri ?? null : null; /** * Loading state changes only when the actual image URI changes. * Do NOT set loading=true in onLoadStart; on React Native Web that callback * may fire again after a state-driven render and can create a visual loop. */ useEffect(() => { setFailed(false); setLoading(Boolean(sourceUri)); }, [sourceUri]); if (!source) { return ( Image unavailable No media URL is available for this image. ); } return ( {failed ? ( Image unavailable ) : ( <> setLoading(false)} onError={() => { setLoading(false); setFailed(true); }} /> {loading ? ( ) : null} )} ); }, (previous, next) => previous.width === next.width && 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.item.alt_text === next.item.alt_text && previous.item.caption === next.item.caption ); export function ContentMediaGallery({ media, title = "Visual reference" }: ContentMediaGalleryProps) { const items = useMemo(() => sortMedia(media ?? []), [media]); const { width: windowWidth } = useWindowDimensions(); const carouselWidth = Math.max(windowWidth - Spacing.md * 2, 280); const [activeIndex, setActiveIndex] = useState(0); const [viewerIndex, setViewerIndex] = useState(null); const listRef = useRef>(null); if (!items.length) return null; const handleMomentumEnd = (event: NativeSyntheticEvent) => { const next = Math.round(event.nativeEvent.contentOffset.x / carouselWidth); setActiveIndex(Math.min(Math.max(next, 0), items.length - 1)); }; return ( {title} {activeIndex + 1} / {items.length} item.id} getItemLayout={(_data, index) => ({ length: carouselWidth, offset: carouselWidth * index, index, })} onMomentumScrollEnd={handleMomentumEnd} renderItem={({ item, index }) => ( setViewerIndex(index)} accessibilityRole="button" accessibilityLabel={`Open ${mediaLabel(item, index)} in full screen`} > View & zoom )} /> {items[activeIndex]?.caption || items[activeIndex]?.alt_text ? ( {mediaLabel(items[activeIndex], activeIndex)} ) : null} {items.length > 1 ? ( {items.map((item, index) => ( { setActiveIndex(index); listRef.current?.scrollToIndex({ index, animated: true }); }} hitSlop={6} > ))} ) : null} setViewerIndex(null)} /> ); } const styles = StyleSheet.create({ root: { gap: 10, marginBottom: 2 }, headingRow: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" }, title: { color: Colors.textPrimary, fontSize: 15, fontWeight: "700" }, count: { color: Colors.textSecondary, fontSize: 13, fontWeight: "600" }, carousel: { overflow: "hidden", borderRadius: 18, backgroundColor: Colors.surface, borderWidth: StyleSheet.hairlineWidth, borderColor: Colors.border, }, slide: { height: 290, alignItems: "center", justifyContent: "center" }, image: { width: "100%", height: "100%", backgroundColor: Colors.surface }, loadingOverlay: { ...StyleSheet.absoluteFillObject, alignItems: "center", justifyContent: "center", backgroundColor: Colors.surface, }, failedBox: { flex: 1, alignItems: "center", justifyContent: "center", gap: 8 }, failedText: { color: Colors.textSecondary, fontSize: 14, fontWeight: "600" }, failedDetail: { color: Colors.textSecondary, fontSize: 12, textAlign: "center", paddingHorizontal: 20 }, zoomBadge: { position: "absolute", right: 12, bottom: 12, flexDirection: "row", alignItems: "center", gap: 6, paddingHorizontal: 10, paddingVertical: 7, borderRadius: 18, backgroundColor: "rgba(0,0,0,0.58)", }, zoomText: { color: Colors.white, fontSize: 12, fontWeight: "700" }, caption: { color: Colors.textSecondary, fontSize: 13, lineHeight: 19, textAlign: "center" }, dots: { flexDirection: "row", flexWrap: "wrap", justifyContent: "center", gap: 7 }, dot: { width: 7, height: 7, borderRadius: 4, backgroundColor: Colors.border }, dotActive: { width: 18, backgroundColor: Colors.primary }, });