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

PdfPreview.android.tsx

88 lines3.3 KB

1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import { Atom, AsyncResult } from "effect/reactivity";
5import { useState } from "react";
6import { View } from "react-native";
7import Pdf from "react-native-pdf-jsi";
8​
9import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";
10import { pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "../lib/pdfPreview";
11import { tryOpenExternalUrl } from "../lib/openExternalUrl";
12import { ControlPill } from "./ui/ControlPill";
13​
14const preparedPdfAtom = Atom.family((uri: string) =>
15 Atom.make(
16 // The downloaded copy lives as long as a viewer reads it; Retry refreshes the atom,
17 // which closes the scope and discards the copy before downloading again. Acquisition
18 // stays interruptible so closing the viewer aborts the download.
19 Effect.acquireRelease(
20 Effect.tryPromise({
21 try: (signal) => {
22 const prepared = preparePdfPreview(uri, signal);
23 // An interrupt can land after the copy exists but before acquireRelease owns it.
24 signal.addEventListener("abort", () => {
25 void prepared.then(
26 (file) => file?.dispose(),
27 () => undefined,
28 );
29 });
30 return prepared;
31 },
32 catch: (cause) => (cause instanceof Error ? cause.message : "The PDF could not be loaded."),
33 }).pipe(
34 Effect.filterOrElse(
35 (file) => file !== null,
36 () => Effect.interrupt,
37 ),
38 Effect.interruptible,
39 ),
40 (file) => Effect.sync(file.dispose),
41 ),
42 ).pipe(Atom.withLabel(`android-pdf-preview:${uri}`)),
43);
44​
45export function PdfPreview(props: { readonly uri: string }) {
46 const atom = preparedPdfAtom(props.uri);
47 const prepared = useAtomValue(atom);
48 const refresh = useAtomRefresh(atom);
49 // A render failure belongs to the downloaded copy that failed; Retry replaces it.
50 const [unrenderable, setUnrenderable] = useState<unknown>(null);
51 const file = prepared._tag === "Success" && !prepared.waiting ? prepared.value : null;
52 const error =
53 file !== null && unrenderable === file
54 ? "The PDF could not be rendered. It may be damaged or password protected."
55 : prepared._tag === "Failure" && !prepared.waiting
56 ? Option.getOrElse(AsyncResult.error(prepared), () => "The PDF could not be loaded.")
57 : null;
58 const localUri = file?.uri ?? null;
59​
60 if (error) {
61 return (
62 <View className="flex-1 gap-4 bg-card">
63 <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>
64 <View className="items-center">
65 <ControlPill label="Try again" variant="pill" onPress={refresh} />
66 </View>
67 </View>
68 );
69 }
70 if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;
71​
72 return (
73 <Pdf
74 source={{ uri: localUri }}
75 initialPage={pdfInitialPage(props.uri) - 1}
76 enableAnnotationRendering
77 enableDoubleTapZoom
78 onLinkPress={({ url: href }) => {
79 const url = pdfLinkUrl(href, props.uri);
80 if (url !== null) void tryOpenExternalUrl(url, "file-preview");
81 }}
82 onError={() => {
83 setUnrenderable(file);
84 }}
85 style={{ flex: 1, width: "100%" }}
86 />
87 );