Open History to see the last commit
1import { useEffect, useRef, useState } from "react";
2import { View } from "react-native";
3import Pdf from "react-native-pdf-jsi";
4
5import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";
6import { pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "../lib/pdfPreview";
7import { tryOpenExternalUrl } from "../lib/openExternalUrl";
8import { ControlPill } from "./ui/ControlPill";
9
10function NativePdfPreview(props: { readonly uri: string; readonly onRetry: () => void }) {
11 const [localUri, setLocalUri] = useState<string | null>(null);
12 const [error, setError] = useState<string | null>(null);
13 const cached = useRef<Awaited<ReturnType<typeof preparePdfPreview>>>(null);
14
15 useEffect(() => {
16 const controller = new AbortController();
17 void preparePdfPreview(props.uri, controller.signal)
18 .then((file) => {
19 if (controller.signal.aborted) file?.dispose();
20 else {
21 cached.current = file;
22 setLocalUri(file?.uri ?? null);
23 }
24 })
25 .catch((cause: unknown) => {
26 if (!controller.signal.aborted) {
27 setError(cause instanceof Error ? cause.message : "The PDF could not be loaded.");
28 }
29 });
30 return () => {
31 controller.abort();
32 cached.current?.dispose();
33 cached.current = null;
34 };
35 }, [props.uri]);
36
37 if (error) {
38 return (
39 <View className="flex-1 gap-4 bg-card">
40 <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>
41 <View className="items-center">
42 <ControlPill label="Try again" variant="pill" onPress={props.onRetry} />
43 </View>
44 </View>
45 );
46 }
47 if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;
48
49 return (
50 <Pdf
51 source={{ uri: localUri }}
52 page={pdfInitialPage(props.uri)}
53 fitPolicy={0}
54 trustAllCerts={false}
55 enableAnnotationRendering
56 enableDoubleTapZoom
57 onPressLink={(href) => {
58 const url = pdfLinkUrl(href, props.uri);
59 if (url !== null) void tryOpenExternalUrl(url, "file-preview");
60 }}
61 onError={() => {
62 cached.current?.dispose();
63 cached.current = null;
64 setError("The PDF could not be rendered. It may be damaged or password protected.");
65 }}
66 style={{ flex: 1, width: "100%" }}
67 />
68 );
69}
70
71export function PdfPreview(props: { readonly uri: string }) {
72 const [attempt, setAttempt] = useState(0);
73 return (
74 <NativePdfPreview
75 key={`${props.uri}:${attempt}`}
76 uri={props.uri}
77 onRetry={() => setAttempt((value) => value + 1)}
78 />
79 );
80}