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

PdfPreview.android.tsx

122 lines4.5 KB

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