Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MediaImagePreview.tsx

71 lines2.7 KB

1import { createContext, useContext, useState } from "react";
2import { Pressable, View } from "react-native";
3import ImageViewing from "react-native-image-viewing";
4import { useSafeAreaInsets } from "react-native-safe-area-context";
5​
6import { useMediaActions } from "../state/mediaActions";
7import { AppText } from "./ui/AppText";
8import { SymbolView } from "./ui/AppSymbol";
9import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
10import { MediaActionsMenu } from "./MediaActionsMenu";
11import { MediaSourceCaption } from "./MediaSourceCaption";
12​
13type MediaImagePreviewProps = {
14 readonly source: ResolvedFilePreviewSource;
15 readonly onRequestClose: () => void;
16};
17​
18const ImagePreviewContext = createContext<MediaImagePreviewProps | null>(null);
19​
20function ImagePreviewHeader(header: { readonly imageIndex: number }) {
21 const props = useContext(ImagePreviewContext)!;
22 const source = props.source.gallery?.[header.imageIndex] ?? props.source;
23 const insets = useSafeAreaInsets();
24 const mediaActions = useMediaActions(source.actionsSource, props.onRequestClose);
25 return (
26 <View className="bg-black/70" style={{ paddingTop: insets.top }}>
27 <View className="flex-row items-center gap-2 px-3">
28 <AppText className="flex-1 text-base text-white" numberOfLines={2}>
29 {source.name ?? "Image"}
30 </AppText>
31 <MediaActionsMenu media={mediaActions} inModal />
32 <Pressable
33 accessibilityRole="button"
34 accessibilityLabel="Close image"
35 onPress={props.onRequestClose}
36 className="min-h-11 min-w-11 items-center justify-center"
37 >
38 <SymbolView name="xmark" size={20} tintColor="#ffffff" type="monochrome" />
39 </Pressable>
40 </View>
41 <MediaSourceCaption source={mediaActions.title} />
42 </View>
43 );
45​
46export function MediaImagePreview(props: MediaImagePreviewProps) {
47 const gallery = props.source.gallery ?? [props.source];
48 // react-native-image-viewing keys its whole Modal by imageIndex, so changing it remounts the
49 // viewer and replays the Android fade over the screen behind. Keep the opening index; the
50 // header follows paging through the index the library passes it.
51 const [initialIndex] = useState(() =>
52 Math.max(
53 0,
54 gallery.findIndex((item) => item.uri === props.source.uri),
55 ),
56 );
57 return (
58 <ImagePreviewContext value={props}>
59 <ImageViewing
60 images={gallery.map((item) => ({ uri: item.uri }))}
61 imageIndex={initialIndex}
62 visible
63 presentationStyle="fullScreen"
64 onRequestClose={props.onRequestClose}
65 swipeToCloseEnabled={false}
66 doubleTapToZoomEnabled
67 HeaderComponent={ImagePreviewHeader}
68 />
69 </ImagePreviewContext>
70 );