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

FilePreviewModal.android.tsx

230 lines7.9 KB

1import { T, useGT } from "gt-react-native";
2​
3import { Button } from "./Button";
4import * as Dialog from "./Dialog";
5import { createContext, useContext, useEffect, useEffectEvent, useRef } from "react";
6import { Modal, View } from "react-native";
7import ImageViewing from "react-native-image-viewing";
8import { useSafeAreaInsets } from "react-native-safe-area-context";
9​
10import { openAttachmentInViewer } from "../../lib/attachmentDownload";
11import { nativeSvgPreviewUri } from "../../lib/svgDataUrl";
12import { useMediaActions } from "../../state/mediaActions";
13import type {
14 FilePreviewImages,
15 FilePreviewModalProps,
16 FilePreviewViewerProps,
17 ResolvedFilePreviewDocument,
18} from "./FilePreviewModal.types";
19import { FilePreviewSession } from "./FilePreviewSession";
20import { MediaPreviewHeader } from "../MediaPreviewHeader";
21​
22export type {
23 FilePreviewItem,
24 FilePreviewSource,
25 ResolvedFilePreviewSource,
26} from "./FilePreviewModal.types";
27import { PdfPreview } from "../PdfPreview";
28import { SheetHeader } from "./SheetHeader";
29import { AppText as Text } from "./AppText";
30​
31function PdfDocumentPreview(props: {
32 readonly source: ResolvedFilePreviewDocument;
33 readonly onRequestClose: () => void;
34}) {
35 const gt = useGT();
36 const insets = useSafeAreaInsets();
37 const media = useMediaActions(props.source.actionsSource);
38 const save = media.actions.find((action) => action.id === "save");
39 return (
40 <Modal
41 animationType="slide"
42 onRequestClose={props.onRequestClose}
43 statusBarTranslucent
44 navigationBarTranslucent
45 >
46 <View
47 className="flex-1 bg-card"
48 style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
49 >
50 <SheetHeader
51 presentation="inline"
52 title={props.source.name ?? gt`PDF`}
53 onClose={props.onRequestClose}
54 actions={
55 save
56 ? [
57 {
58 accessibilityLabel: gt`Save or share`,
59 icon: "square.and.arrow.up",
60 disabled: save.disabled,
61 loading: media.sharing,
62 onPress: () => void save.run(),
63 },
64 ]
65 : []
66 }
67 />
68 <PdfPreview uri={props.source.uri} />
69 </View>
70 </Modal>
71 );
73​
74function DocumentPreview(props: {
75 readonly source: ResolvedFilePreviewDocument;
76 readonly onRequestClose: () => void;
77 readonly onOpenError?: (error: unknown) => void;
78}) {
79 const gt = useGT();
80 const { uri, name } = props.source;
81 const onRequestClose = useEffectEvent(props.onRequestClose);
82 const onOpenError = useEffectEvent((error: unknown) => {
83 if (props.onOpenError) props.onOpenError(error);
84 else
85 Dialog.alert(
86 gt`Could not open document`,
87 gt`A compatible viewer must be installed. Check your connection and try again.`,
88 );
89 });
90 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the attachment in an external viewer and aborts the open on cleanup
91 useEffect(() => {
92 const controller = new AbortController();
93 const input = {
94 uri,
95 attachment: {
96 name: name ?? "Document",
97 mimeType:
98 props.source.mimeType ??
99 (props.source.kind === "pdf" ? "application/pdf" : "application/octet-stream"),
100 },
101 signal: controller.signal,
102 };
103 const opened = openAttachmentInViewer(input);
104 void opened
105 .catch((error: unknown) => {
106 if (!controller.signal.aborted) onOpenError(error);
107 })
108 .finally(() => {
109 if (!controller.signal.aborted) onRequestClose();
110 });
111 return () => controller.abort();
112 }, [uri, name, props.source.mimeType, props.source.kind]);
113 return (
114 <Modal transparent animationType="fade" onRequestClose={props.onRequestClose}>
115 <View className="flex-1 items-center justify-center bg-backdrop p-6">
116 <View className="w-full max-w-sm gap-4 rounded-2xl bg-sheet-solid p-6">
117 <Text className="font-t3-semibold text-foreground">
118 <T>Opening document…</T>
119 </Text>
120 <Text className="text-foreground-muted" numberOfLines={2}>
121 {name ?? gt`Document`}
122 </Text>
123 <View className="items-end">
124 <Button label={gt`Cancel`} tone="text" onPress={props.onRequestClose} />
125 </View>
126 </View>
127 </View>
128 </Modal>
129 );
131​
132type ImagePreviewProps = {
133 readonly source: FilePreviewImages;
134 readonly onRequestClose: () => void;
135};
136​
137const ImagePreviewContext = createContext<
138 (ImagePreviewProps & { readonly getSaveImageSignal: () => AbortSignal }) | null
139>(null);
140​
141// Keyed by page so swiping away clears the busy state and aborts pending share preparation.
142function ImagePreviewHeader(header: { readonly imageIndex: number }) {
143 return <ImagePreviewPageHeader key={header.imageIndex} imageIndex={header.imageIndex} />;
145​
146function ImagePreviewPageHeader(header: { readonly imageIndex: number }) {
147 const props = useContext(ImagePreviewContext)!;
148 const source = props.source.images[header.imageIndex];
149 const gt = useGT();
150 const insets = useSafeAreaInsets();
151 const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose, {
152 getSaveImageSignal: props.getSaveImageSignal,
153 });
154 return (
155 <View className="bg-black/70" style={{ paddingTop: insets.top }}>
156 <MediaPreviewHeader
157 title={source?.name ?? gt`Image`}
158 media={mediaActions}
159 closeAccessibilityLabel={gt`Close image`}
160 onClose={props.onRequestClose}
161 />
162 </View>
163 );
165​
166// Images still resolving show the viewer's loading page, and remount by key once their URL arrives.
167function imageViewingProps(source: FilePreviewImages) {
168 return {
169 images: source.images.map(({ uri }) => (uri ? { uri: nativeSvgPreviewUri(uri) } : {})),
170 keyExtractor: (_: unknown, index: number) => source.images[index]?.uri ?? `pending:${index}`,
171 // Stays fixed: react-native-image-viewing remounts the Modal and replays its fade when it changes.
172 imageIndex: source.selectedIndex,
173 };
175​
176function ImagePreview(props: ImagePreviewProps) {
177 const saveController = useRef<AbortController | null>(null);
178 const getSaveImageSignal = () => {
179 if (saveController.current === null) {
180 saveController.current = new AbortController();
181 }
182 return saveController.current.signal;
183 };
184 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- saves survive a page change but stop when the gallery unmounts
185 useEffect(
186 () => () => {
187 saveController.current?.abort();
188 saveController.current = null;
189 },
190 [],
191 );
192 return (
193 <ImagePreviewContext value={{ ...props, getSaveImageSignal }}>
194 <ImageViewing
195 {...imageViewingProps(props.source)}
196 visible
197 presentationStyle="fullScreen"
198 onRequestClose={props.onRequestClose}
199 swipeToCloseEnabled={false}
200 doubleTapToZoomEnabled
201 HeaderComponent={ImagePreviewHeader}
202 />
203 </ImagePreviewContext>
204 );
206​
207function AndroidFilePreview(props: FilePreviewViewerProps) {
208 const { source } = props;
209 if (source.kind === "pdf") return <PdfDocumentPreview {...props} source={source} />;
210 if (source.kind !== "image") return <DocumentPreview {...props} source={source} />;
211 const selected = source.images[source.selectedIndex]!;
212 const images = source.images.filter((image) => !image.failed);
213 const gallery = { ...source, images, selectedIndex: images.indexOf(selected) };
214 if (selected.actionsSource)
215 return <ImagePreview source={gallery} onRequestClose={props.onRequestClose} />;
216 return (
217 <ImageViewing
218 {...imageViewingProps(gallery)}
219 visible
220 onRequestClose={props.onRequestClose}
221 swipeToCloseEnabled={false}
222 doubleTapToZoomEnabled
223 />
224 );
226​
227/** Shows images, PDFs and documents full screen. */
228export function FilePreviewModal(props: FilePreviewModalProps) {
229 return <FilePreviewSession {...props} progressiveGallery={false} Viewer={AndroidFilePreview} />;