261 lines
8.8 KiB
TypeScript
261 lines
8.8 KiB
TypeScript
import { Ionicons } from "@expo/vector-icons";
|
|
import React, { memo, useEffect, useMemo, useRef, useState } from "react";
|
|
import {
|
|
ActivityIndicator,
|
|
FlatList,
|
|
NativeScrollEvent,
|
|
NativeSyntheticEvent,
|
|
Pressable,
|
|
StyleSheet,
|
|
Text,
|
|
useWindowDimensions,
|
|
View,
|
|
} from "react-native";
|
|
import { Image } from "expo-image";
|
|
|
|
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 ?? 0) - (b.sort_order ?? 0) || 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 <Image> 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 (
|
|
<View style={[styles.slide, { width }]}>
|
|
<View style={styles.failedBox}>
|
|
<Ionicons name="image-outline" size={34} color={Colors.textSecondary} />
|
|
<Text style={styles.failedText}>Image unavailable</Text>
|
|
<Text style={styles.failedDetail}>No media URL is available for this image.</Text>
|
|
</View>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<View style={[styles.slide, { width }]}>
|
|
{failed ? (
|
|
<View style={styles.failedBox}>
|
|
<Ionicons name="image-outline" size={34} color={Colors.textSecondary} />
|
|
<Text style={styles.failedText}>Image unavailable</Text>
|
|
</View>
|
|
) : (
|
|
<>
|
|
<Image
|
|
source={source}
|
|
style={styles.image}
|
|
contentFit="contain"
|
|
accessible
|
|
accessibilityRole="image"
|
|
accessibilityLabel={item.alt_text || item.caption || "Content image"}
|
|
onLoad={() => setLoading(false)}
|
|
onError={(error) => {
|
|
console.warn("Failed to load GalleryImage:", source, error);
|
|
setLoading(false);
|
|
setFailed(true);
|
|
}}
|
|
/>
|
|
{loading ? (
|
|
<View style={styles.loadingOverlay} pointerEvents="none">
|
|
<ActivityIndicator color={Colors.primary} />
|
|
</View>
|
|
) : null}
|
|
</>
|
|
)}
|
|
</View>
|
|
);
|
|
}, (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<number | null>(null);
|
|
const listRef = useRef<FlatList<ContentMediaItem>>(null);
|
|
|
|
if (!items.length) return null;
|
|
|
|
const handleMomentumEnd = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
|
const next = Math.round(event.nativeEvent.contentOffset.x / carouselWidth);
|
|
setActiveIndex(Math.min(Math.max(next, 0), items.length - 1));
|
|
};
|
|
|
|
return (
|
|
<View style={styles.root}>
|
|
<View style={styles.headingRow}>
|
|
<Text style={styles.title}>{title}</Text>
|
|
<Text style={styles.count}>{activeIndex + 1} / {items.length}</Text>
|
|
</View>
|
|
|
|
<View style={[styles.carousel, { width: carouselWidth }]}>
|
|
<FlatList
|
|
ref={listRef}
|
|
data={items}
|
|
horizontal
|
|
pagingEnabled
|
|
bounces={false}
|
|
showsHorizontalScrollIndicator={false}
|
|
keyExtractor={(item) => item.id}
|
|
getItemLayout={(_data, index) => ({
|
|
length: carouselWidth,
|
|
offset: carouselWidth * index,
|
|
index,
|
|
})}
|
|
onMomentumScrollEnd={handleMomentumEnd}
|
|
renderItem={({ item, index }) => (
|
|
<Pressable
|
|
onPress={() => setViewerIndex(index)}
|
|
accessibilityRole="button"
|
|
accessibilityLabel={`Open ${mediaLabel(item, index)} in full screen`}
|
|
>
|
|
<GalleryImage item={item} width={carouselWidth} />
|
|
<View style={styles.zoomBadge} pointerEvents="none">
|
|
<Ionicons name="expand-outline" size={18} color={Colors.white} />
|
|
<Text style={styles.zoomText}>View & zoom</Text>
|
|
</View>
|
|
</Pressable>
|
|
)}
|
|
/>
|
|
</View>
|
|
|
|
{items[activeIndex]?.caption || items[activeIndex]?.alt_text ? (
|
|
<Text style={styles.caption}>{mediaLabel(items[activeIndex], activeIndex)}</Text>
|
|
) : null}
|
|
|
|
{items.length > 1 ? (
|
|
<View style={styles.dots} accessibilityElementsHidden>
|
|
{items.map((item, index) => (
|
|
<Pressable
|
|
key={item.id}
|
|
onPress={() => {
|
|
setActiveIndex(index);
|
|
listRef.current?.scrollToIndex({ index, animated: true });
|
|
}}
|
|
hitSlop={6}
|
|
>
|
|
<View style={[styles.dot, index === activeIndex && styles.dotActive]} />
|
|
</Pressable>
|
|
))}
|
|
</View>
|
|
) : null}
|
|
|
|
<FullScreenMediaViewer
|
|
visible={viewerIndex !== null}
|
|
images={items}
|
|
initialIndex={viewerIndex ?? 0}
|
|
onClose={() => setViewerIndex(null)}
|
|
/>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
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.absoluteFill as object),
|
|
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 },
|
|
});
|