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

FilePreview.tsx

52 lines1.7 KB

1import { useEffect, useEffectEvent } from "react";
2import { Alert } from "react-native";
3import ImageViewing from "react-native-image-viewing";
4​
5import { downloadAndShareAttachment, shareLocalAttachment } from "../lib/attachmentDownload";
6import type { ResolvedFilePreviewSource } from "./FilePreviewModal";
7​
8function PdfPreview(props: {
9 readonly source: ResolvedFilePreviewSource;
10 readonly onRequestClose: () => void;
11}) {
12 const { uri, name } = props.source;
13 const onRequestClose = useEffectEvent(props.onRequestClose);
14 useEffect(() => {
15 const controller = new AbortController();
16 const input = {
17 attachment: { name: name ?? "Document.pdf", mimeType: "application/pdf" },
18 signal: controller.signal,
19 };
20 // Android's system chooser supplies the installed PDF apps.
21 const opened =
22 uri.startsWith("file:") || uri.startsWith("content:")
23 ? shareLocalAttachment({ ...input, uri })
24 : downloadAndShareAttachment({ ...input, url: uri });
25 void opened
26 .catch(() => {
27 if (!controller.signal.aborted) Alert.alert("Could not open PDF", "Please try again.");
28 })
29 .finally(() => {
30 if (!controller.signal.aborted) onRequestClose();
31 });
32 return () => controller.abort();
33 }, [uri, name]);
34 return null;
36​
37export function FilePreview(props: {
38 readonly source: ResolvedFilePreviewSource;
39 readonly onRequestClose: () => void;
40}) {
41 if (props.source.kind === "pdf") return <PdfPreview {...props} />;
42 return (
43 <ImageViewing
44 images={[{ uri: props.source.uri }]}
45 imageIndex={0}
46 visible
47 onRequestClose={props.onRequestClose}
48 swipeToCloseEnabled
49 doubleTapToZoomEnabled
50 />
51 );