Skip to content

Commit 606ded4

Browse files
committed
fix(files): load PDFs in browser previews
1 parent a9c9c7c commit 606ded4

21 files changed

Lines changed: 1000 additions & 47 deletions

‎apps/mobile/app.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,7 @@ const config: ExpoConfig = {
317317
},
318318
plugins: [
319319
"expo-asset",
320+
"react-native-pdf-jsi",
320321
[
321322
"expo-font",
322323
{

‎apps/mobile/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
"@noble/curves": "catalog:",
5858
"@pierre/diffs": "catalog:",
5959
"@react-native-ai/apple": "0.12.0",
60+
"@react-native-async-storage/async-storage": "3.1.1",
6061
"@react-native-menu/menu": "^2.0.0",
6162
"@react-navigation/elements": "2.9.45",
6263
"@react-navigation/native": "7.5.1",
@@ -121,10 +122,12 @@
121122
"react": "19.3.0",
122123
"react-dom": "19.3.0",
123124
"react-native": "0.88.0",
125+
"react-native-blob-util": "0.25.1",
124126
"react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.13.tgz",
125127
"react-native-gesture-handler": "~3.3.0",
126128
"react-native-image-viewing": "^0.2.2",
127129
"react-native-keyboard-controller": "1.22.7",
130+
"react-native-pdf-jsi": "4.4.2",
128131
"react-native-reanimated": "4.7.1",
129132
"react-native-safe-area-context": "~5.10.1",
130133
"react-native-screens": "file:deps/react-native-screens-5.0.0-t3.27.tgz",

‎apps/mobile/src/components/FilePreview.tsx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,43 @@ import * as Dialog from "./ui/Dialog";
22
import { useEffect, useEffectEvent } from "react";
33
import { Modal, Pressable, View } from "react-native";
44
import ImageViewing from "react-native-image-viewing";
5+
import { useSafeAreaInsets } from "react-native-safe-area-context";
56

67
import { openAttachmentInViewer } from "../lib/attachmentDownload";
78
import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
89
import { MediaImagePreview } from "./MediaImagePreview";
10+
import { PdfPreview } from "./PdfPreview";
11+
import { ControlPill } from "./ui/ControlPill";
912
import { AppText as Text } from "./ui/AppText";
1013

14+
function PdfDocumentPreview(props: {
15+
readonly source: ResolvedFilePreviewSource;
16+
readonly onRequestClose: () => void;
17+
}) {
18+
const insets = useSafeAreaInsets();
19+
return (
20+
<Modal
21+
animationType="slide"
22+
onRequestClose={props.onRequestClose}
23+
statusBarTranslucent
24+
navigationBarTranslucent
25+
>
26+
<View
27+
className="flex-1 bg-card"
28+
style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
29+
>
30+
<View className="flex-row items-center gap-3 border-b border-border px-4 py-2">
31+
<Text className="flex-1 font-t3-semibold text-foreground" numberOfLines={1}>
32+
{props.source.name ?? "PDF"}
33+
</Text>
34+
<ControlPill label="Close" variant="pill" onPress={props.onRequestClose} />
35+
</View>
36+
<PdfPreview uri={props.source.uri} />
37+
</View>
38+
</Modal>
39+
);
40+
}
41+
1142
function DocumentPreview(props: {
1243
readonly source: ResolvedFilePreviewSource;
1344
readonly onRequestClose: () => void;
@@ -71,6 +102,7 @@ export function FilePreview(props: {
71102
readonly onRequestClose: () => void;
72103
readonly onOpenError?: (error: unknown) => void;
73104
}) {
105+
if (props.source.kind === "pdf") return <PdfDocumentPreview {...props} />;
74106
if (props.source.kind !== "image") return <DocumentPreview {...props} />;
75107
if (props.source.actionsSource) return <MediaImagePreview {...props} />;
76108
return (
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { useEffect, useState } from "react";
2+
import { View } from "react-native";
3+
import Pdf from "react-native-pdf-jsi";
4+
5+
import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";
6+
import { pdfInitialPage, preparePdfPreview } from "../lib/pdfPreview";
7+
import { ControlPill } from "./ui/ControlPill";
8+
9+
function NativePdfPreview(props: { readonly uri: string; readonly onRetry: () => void }) {
10+
const [localUri, setLocalUri] = useState<string | null>(null);
11+
const [error, setError] = useState<string | null>(null);
12+
13+
useEffect(() => {
14+
const controller = new AbortController();
15+
let cached: Awaited<ReturnType<typeof preparePdfPreview>> = null;
16+
void preparePdfPreview(props.uri, controller.signal)
17+
.then((file) => {
18+
cached = file;
19+
if (controller.signal.aborted) file?.dispose();
20+
else setLocalUri(file?.uri ?? null);
21+
})
22+
.catch((cause: unknown) => {
23+
if (!controller.signal.aborted) {
24+
setError(cause instanceof Error ? cause.message : "The PDF could not be loaded.");
25+
}
26+
});
27+
return () => {
28+
controller.abort();
29+
cached?.dispose();
30+
};
31+
}, [props.uri]);
32+
33+
if (error) {
34+
return (
35+
<View className="flex-1 gap-4 bg-card">
36+
<FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>
37+
<View className="items-center">
38+
<ControlPill label="Try again" variant="pill" onPress={props.onRetry} />
39+
</View>
40+
</View>
41+
);
42+
}
43+
if (localUri === null) return <FilePreviewLoading message="Loading PDF..." background="card" />;
44+
45+
return (
46+
<Pdf
47+
source={{ uri: localUri }}
48+
page={pdfInitialPage(props.uri)}
49+
fitPolicy={0}
50+
trustAllCerts={false}
51+
enableAnnotationRendering
52+
enableDoubleTapZoom
53+
onError={() =>
54+
setError("The PDF could not be rendered. It may be damaged or password protected.")
55+
}
56+
style={{ flex: 1, width: "100%" }}
57+
/>
58+
);
59+
}
60+
61+
export function PdfPreview(props: { readonly uri: string }) {
62+
const [attempt, setAttempt] = useState(0);
63+
return (
64+
<NativePdfPreview
65+
key={`${props.uri}:${attempt}`}
66+
uri={props.uri}
67+
onRetry={() => setAttempt((value) => value + 1)}
68+
/>
69+
);
70+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { useState } from "react";
2+
import { View } from "react-native";
3+
import { WebView } from "react-native-webview";
4+
5+
import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback";
6+
7+
export function PdfPreview(props: { readonly uri: string }) {
8+
const [error, setError] = useState<string | null>(null);
9+
return (
10+
<View className="flex-1 bg-card">
11+
{error ? <FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice> : null}
12+
<WebView
13+
source={{ uri: props.uri }}
14+
originWhitelist={["*"]}
15+
automaticallyAdjustContentInsets={false}
16+
contentInsetAdjustmentBehavior="never"
17+
startInLoadingState
18+
onError={(event) =>
19+
setError(event.nativeEvent.description || "The PDF could not be loaded.")
20+
}
21+
onHttpError={(event) =>
22+
setError(`The server returned HTTP ${event.nativeEvent.statusCode}.`)
23+
}
24+
renderLoading={() => <FilePreviewLoading message="Loading PDF..." background="card" />}
25+
style={{ flex: 1, backgroundColor: "transparent" }}
26+
/>
27+
</View>
28+
);
29+
}
Lines changed: 86 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,107 @@
1-
import { useState } from "react";
2-
import { View } from "react-native";
1+
import { useEffect, useState } from "react";
2+
import { BackHandler, Platform, View } from "react-native";
33
import { WebView } from "react-native-webview";
4+
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
45

56
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
67
import { AppText as Text } from "../../components/ui/AppText";
78
import { FilePreviewLoading } from "./FilePreviewFeedback";
89
import { LoadingStrip } from "../../components/ui/LoadingStrip";
10+
import { PdfPreview } from "../../components/PdfPreview";
11+
import { ControlPill } from "../../components/ui/ControlPill";
12+
import { isPdfPreviewUri } from "../../lib/pdfPreview";
13+
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
914

1015
export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {
16+
if (props.uri === null) {
17+
return <FilePreviewLoading message="Preparing preview..." background="card" />;
18+
}
19+
return <DocumentWebPreview key={props.uri} uri={props.uri} />;
20+
}
21+
22+
function DocumentWebPreview(props: { readonly uri: string }) {
23+
const insets = useSafeAreaInsets();
24+
const columnMetrics = useNativeColumnLayoutMetrics();
25+
const pdfTopInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
1126
const [loadProgress, setLoadProgress] = useState(0);
1227
const [loadError, setLoadError] = useState<string | null>(null);
28+
const [linkedPdf, setLinkedPdf] = useState<string | null>(null);
1329

14-
if (props.uri === null) {
15-
return <FilePreviewLoading message="Preparing preview..." background="card" />;
30+
useEffect(() => {
31+
if (linkedPdf === null) return;
32+
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
33+
setLinkedPdf(null);
34+
return true;
35+
});
36+
return () => subscription.remove();
37+
}, [linkedPdf]);
38+
39+
if (isPdfPreviewUri(props.uri)) {
40+
return (
41+
<View className="flex-1" style={{ paddingTop: pdfTopInset }}>
42+
<PdfPreview uri={props.uri} />
43+
</View>
44+
);
1645
}
1746

1847
return (
1948
<View className="relative flex-1 bg-card">
20-
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
21-
{loadError ? (
22-
<View className="border-b border-border bg-card px-4 py-2">
23-
<Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>
24-
<Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>
49+
{linkedPdf ? (
50+
<View className="flex-1" style={{ paddingTop: pdfTopInset }}>
51+
<PdfPreview key={linkedPdf} uri={linkedPdf} />
52+
<SafeAreaView edges={["bottom"]} className="border-t border-border px-4 py-2">
53+
<ControlPill
54+
label="Back to document"
55+
variant="pill"
56+
onPress={() => setLinkedPdf(null)}
57+
/>
58+
</SafeAreaView>
2559
</View>
2660
) : null}
27-
<WebView
28-
source={{ uri: props.uri }}
29-
originWhitelist={["*"]}
30-
allowsBackForwardNavigationGestures
31-
allowsFullscreenVideo
32-
setSupportMultipleWindows={false}
33-
startInLoadingState
34-
onLoadProgress={(event) => {
35-
setLoadProgress(event.nativeEvent.progress);
36-
}}
37-
onLoadStart={() => {
38-
setLoadProgress(0.05);
39-
setLoadError(null);
40-
}}
41-
onLoadEnd={() => {
42-
setLoadProgress(0);
43-
}}
44-
onError={(event) => {
45-
setLoadProgress(0);
46-
setLoadError(event.nativeEvent.description || "The file could not be rendered.");
47-
}}
48-
renderLoading={() => (
49-
<View className="absolute inset-0 items-center justify-center bg-card">
50-
<AppActivityIndicator />
61+
<View className="flex-1" style={linkedPdf ? { display: "none" } : undefined}>
62+
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
63+
{loadError ? (
64+
<View className="border-b border-border bg-card px-4 py-2">
65+
<Text className="text-xs font-t3-bold text-foreground">Preview failed</Text>
66+
<Text className="mt-0.5 text-xs leading-snug text-foreground-muted">{loadError}</Text>
5167
</View>
52-
)}
53-
style={{ flex: 1, backgroundColor: "transparent" }}
54-
/>
68+
) : null}
69+
<WebView
70+
source={{ uri: props.uri }}
71+
originWhitelist={["*"]}
72+
allowsBackForwardNavigationGestures
73+
allowsFullscreenVideo
74+
setSupportMultipleWindows={false}
75+
onShouldStartLoadWithRequest={(request) => {
76+
if (request.isTopFrame !== false && isPdfPreviewUri(request.url)) {
77+
setLinkedPdf(request.url);
78+
return false;
79+
}
80+
return true;
81+
}}
82+
startInLoadingState
83+
onLoadProgress={(event) => {
84+
setLoadProgress(event.nativeEvent.progress);
85+
}}
86+
onLoadStart={() => {
87+
setLoadProgress(0.05);
88+
setLoadError(null);
89+
}}
90+
onLoadEnd={() => {
91+
setLoadProgress(0);
92+
}}
93+
onError={(event) => {
94+
setLoadProgress(0);
95+
setLoadError(event.nativeEvent.description || "The file could not be rendered.");
96+
}}
97+
renderLoading={() => (
98+
<View className="absolute inset-0 items-center justify-center bg-card">
99+
<AppActivityIndicator />
100+
</View>
101+
)}
102+
style={{ flex: 1, backgroundColor: "transparent" }}
103+
/>
104+
</View>
55105
</View>
56106
);
57107
}

0 commit comments

Comments
 (0)