Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 43 additions & 5 deletions app/pdf-viewer.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { LineIcon, SolidIcon } from "@/components/icon";
import { PageIndicator } from "@/components/page-indicator";
import { PdfNavigationSheet } from "@/components/pdf-navigation-sheet";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Screen } from "@/components/ui/screen";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Text } from "@/components/ui/text";
Expand All @@ -12,13 +13,15 @@ import * as Sharing from "expo-sharing";
import * as Sentry from "@sentry/react-native";
import { useQueryClient } from "@tanstack/react-query";
import { Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Dimensions, Platform, StyleSheet, TouchableOpacity, View } from "react-native";
import Pdf, { PdfRef, TableContent } from "react-native-pdf";
import { cn } from "@/lib/utils";
import { safeOpenURL } from "@/lib/open-url";
import { Button } from "@/components/ui/button";

const STALE_BLOB_ERROR = "Unable to resolve data for blob:";

export default function PdfViewerScreen() {
const { uri, title, urlRedirectId, productFileId, purchaseId, initialPage } = useLocalSearchParams<{
uri: string;
Expand All @@ -42,6 +45,33 @@ export default function PdfViewerScreen() {
const [pdfMounted, setPdfMounted] = useState(true);
const [pdfError, setPdfError] = useState(false);
const [pdfKey, setPdfKey] = useState(0);
const [cachedUri, setCachedUri] = useState<string | null>(null);
const [downloadError, setDownloadError] = useState(false);
const [isDownloading, setIsDownloading] = useState(true);

const downloadPdf = useCallback(() => {
let cancelled = false;
setDownloadError(false);
setCachedUri(null);
setIsDownloading(true);
File.downloadFileAsync(uri, Paths.cache, { idempotent: true })
.then((result) => {
if (!cancelled) setCachedUri(result.uri);
})
.catch((e) => {
console.error("Error downloading PDF", e);
if (!cancelled) setDownloadError(true);
})
.finally(() => {
if (!cancelled) setIsDownloading(false);
});

return () => {
cancelled = true;
};
}, [uri]);

useEffect(downloadPdf, [downloadPdf]);

const switchViewMode = (mode: "single" | "continuous") => {
// Unmount the PDF component first to let the native rendering thread finish
Expand Down Expand Up @@ -131,7 +161,7 @@ export default function PdfViewerScreen() {
),
}}
/>
{pdfError ? (
{pdfError || downloadError ? (
<View className="flex-1 items-center justify-center gap-4 px-8">
<Text className="text-center text-lg text-foreground">
Unable to load this PDF. The file may be temporarily unavailable.
Expand All @@ -140,16 +170,21 @@ export default function PdfViewerScreen() {
onPress={() => {
setPdfError(false);
setPdfKey((k) => k + 1);
if (downloadError) downloadPdf();
Comment thread
cursor[bot] marked this conversation as resolved.
Outdated
}}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
>
<Text className="text-base font-semibold text-white">Try Again</Text>
</Button>
</View>
) : !cachedUri || isDownloading ? (
<View className="flex-1 items-center justify-center">
<LoadingSpinner />
</View>
) : pdfMounted ? (
<Pdf
key={`${viewMode}-${pdfKey}`}
ref={pdfRef}
source={{ uri }}
source={{ uri: cachedUri }}
style={styles.pdf}
trustAllCerts={false}
fitPolicy={0}
Expand All @@ -164,7 +199,10 @@ export default function PdfViewerScreen() {
onPageChanged={(page) => setCurrentPage(page)}
onPressLink={(url) => safeOpenURL(url)}
onError={(error) => {
Sentry.captureException(error);
const message = error instanceof Error ? error.message : String(error);
if (!message.includes(STALE_BLOB_ERROR)) {
Sentry.captureException(error);
}
console.error("PDF Error:", error);
setPdfError(true);
}}
Expand All @@ -174,7 +212,7 @@ export default function PdfViewerScreen() {
<PdfNavigationSheet
open={showTocModal}
onOpenChange={setShowTocModal}
uri={uri}
uri={cachedUri ?? uri}
Comment thread
gumclaw marked this conversation as resolved.
tableOfContents={tableOfContents}
totalPages={totalPages}
currentPage={currentPage}
Expand Down
34 changes: 29 additions & 5 deletions tests/app/pdf-viewer.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fireEvent, screen } from "@testing-library/react-native";
import { fireEvent, screen, waitFor } from "@testing-library/react-native";
import { renderWithQueryClient } from "../render-with-query-client";

jest.mock("expo-router", () => ({
Expand Down Expand Up @@ -52,10 +52,10 @@ describe("PdfViewerScreen", () => {
mockOnError = null;
});

it("shows error view with Try Again button when PDF fails to load", () => {
it("shows error view with Try Again button when PDF fails to load", async () => {
renderWithProviders();

expect(screen.getByTestId("pdf-component")).toBeTruthy();
await waitFor(() => expect(screen.getByTestId("pdf-component")).toBeTruthy());
expect(screen.queryByText("Try Again")).toBeNull();

act(() => {
Expand All @@ -67,16 +67,40 @@ describe("PdfViewerScreen", () => {
expect(screen.queryByTestId("pdf-component")).toBeNull();
});

it("re-mounts PDF component when Try Again is pressed", () => {
it("re-mounts PDF component when Try Again is pressed", async () => {
renderWithProviders();

await waitFor(() => expect(screen.getByTestId("pdf-component")).toBeTruthy());

act(() => {
mockOnError!(new Error("ENOENT"));
});

fireEvent.press(screen.getByText("Try Again"));

expect(screen.getByTestId("pdf-component")).toBeTruthy();
await waitFor(() => expect(screen.getByTestId("pdf-component")).toBeTruthy());
expect(screen.queryByText("Try Again")).toBeNull();
});

it("shows loading spinner while downloading PDF", () => {
const { File } = require("expo-file-system");
File.downloadFileAsync.mockReturnValueOnce(new Promise(() => {}));

renderWithProviders();

expect(screen.queryByTestId("pdf-component")).toBeNull();
});
Comment thread
greptile-apps[bot] marked this conversation as resolved.

it("shows error view when PDF download fails", async () => {
const { File } = require("expo-file-system");
File.downloadFileAsync.mockRejectedValue(new Error("Network error"));

renderWithProviders();

await waitFor(() => expect(screen.getByText("Try Again")).toBeTruthy());
expect(screen.getByText(/Unable to load this PDF/)).toBeTruthy();
expect(screen.queryByTestId("pdf-component")).toBeNull();

File.downloadFileAsync.mockResolvedValue({ uri: "file:///cache/test.pdf" });
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Outdated
});
});
Loading