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

PdfPreview.android.tsx

87 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.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file))),
35 Effect.interruptible,
36 ),
37 (file) => Effect.sync(file.dispose),
38 ),
39 ).pipe(Atom.withLabel(`android-pdf-preview:${uri}`)),
40);
41​
42export function PdfPreview(props: { readonly uri: string }) {
43 const atom = preparedPdfAtom(props.uri);
44 const prepared = useAtomValue(atom);
45 const refresh = useAtomRefresh(atom);
46 // A render failure belongs to the downloaded copy that failed; Retry replaces it.
47 const [unrenderable, setUnrenderable] = useState<unknown>(null);
48 const file = prepared._tag === "Success" && !prepared.waiting ? prepared.value : null;
49 const error =
50 file !== null && unrenderable === file
51 ? "The PDF could not be rendered. It may be damaged or password protected."
52 : prepared._tag === "Failure" && !prepared.waiting
53 ? Option.getOrElse(AsyncResult.error(prepared), () => "The PDF could not be loaded.")
54 : null;
55 const localUri = file?.uri ?? null;
56​
57 if (error) {
58 return (
59 <View className="flex-1 gap-4 bg-card">
60 <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>
61 <View className="items-center">
62 <ControlPill label="Try again" variant="pill" onPress={refresh} />
63 </View>
64 </View>
65 );
66 }
67 if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;
68​
69 return (
70 <Pdf
71 source={{ uri: localUri }}
72 page={pdfInitialPage(props.uri)}
73 fitPolicy={0}
74 trustAllCerts={false}
75 enableAnnotationRendering
76 enableDoubleTapZoom
77 onPressLink={(href) => {
78 const url = pdfLinkUrl(href, props.uri);
79 if (url !== null) void tryOpenExternalUrl(url, "file-preview");
80 }}
81 onError={() => {
82 setUnrenderable(file);
83 }}
84 style={{ flex: 1, width: "100%" }}
85 />
86 );