Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
69 changes: 60 additions & 9 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 @@ -31,6 +34,7 @@ export default function PdfViewerScreen() {
const { accessToken } = useAuth();
const queryClient = useQueryClient();
const pdfRef = useRef<PdfRef>(null);
const cancelDownloadRef = useRef<(() => void) | null>(null);
const [currentPage, setCurrentPage] = useState(initialPage ? Number(initialPage) : 1);
const currentPageRef = useRefToLatest(currentPage);
const [totalPages, setTotalPages] = useState(0);
Expand All @@ -42,6 +46,42 @@ 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) => {
if (!cancelled) {
console.error("Error downloading PDF", e);
setDownloadError(true);
}
})
.finally(() => {
if (!cancelled) setIsDownloading(false);
});

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

useEffect(() => {
cancelDownloadRef.current = downloadPdf();

return () => {
cancelDownloadRef.current?.();
cancelDownloadRef.current = null;
};
}, [downloadPdf]);

const switchViewMode = (mode: "single" | "continuous") => {
// Unmount the PDF component first to let the native rendering thread finish
Expand Down Expand Up @@ -95,16 +135,16 @@ export default function PdfViewerScreen() {
headerRight: () => (
<View className="flex-row items-center gap-1">
<TouchableOpacity
testID="share-pdf-button"
disabled={isSharing}
onPress={async () => {
setIsSharing(true);
try {
const isAvailable = await Sharing.isAvailableAsync();
if (!isAvailable) return;
const downloaded = await File.downloadFileAsync(uri, Paths.cache, {
idempotent: true,
});
await Sharing.shareAsync(downloaded.uri);
const sharedUri =
cachedUri ?? (await File.downloadFileAsync(uri, Paths.cache, { idempotent: true })).uri;
await Sharing.shareAsync(sharedUri);
} finally {
setIsSharing(false);
}
Expand All @@ -131,7 +171,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 +180,24 @@ export default function PdfViewerScreen() {
onPress={() => {
setPdfError(false);
setPdfKey((k) => k + 1);
if (downloadError) {
cancelDownloadRef.current?.();
cancelDownloadRef.current = downloadPdf();
}
}}
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 testID="loading-spinner" />
</View>
) : pdfMounted ? (
<Pdf
key={`${viewMode}-${pdfKey}`}
ref={pdfRef}
source={{ uri }}
source={{ uri: cachedUri }}
style={styles.pdf}
trustAllCerts={false}
fitPolicy={0}
Expand All @@ -164,7 +212,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 +225,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
17 changes: 14 additions & 3 deletions components/pdf-navigation-sheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export const PdfNavigationSheet = ({
const [failedPages, setFailedPages] = useState<Set<number>>(new Set());
const thumbnailWidth = (containerWidth - THUMBNAIL_GAP * (THUMBNAIL_COLUMNS + 1)) / THUMBNAIL_COLUMNS;
const thumbnailHeight = thumbnailWidth * 1.4;
const isLocalFile = uri.startsWith("file://");

useEffect(() => {
if (hasToc) setActiveTab("contents");
Expand All @@ -106,20 +107,30 @@ export const PdfNavigationSheet = ({
const downloadPdf = useCallback(() => {
let cancelled = false;
setDownloadError(false);

if (isLocalFile) {
setCachedUri(uri);
return () => {
cancelled = true;
};
}

setCachedUri(null);
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);
if (!cancelled) {
console.error("Error downloading PDF", e);
setDownloadError(true);
}
});

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

useEffect(downloadPdf, [downloadPdf]);

Expand Down
117 changes: 111 additions & 6 deletions tests/app/pdf-viewer.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
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", () => ({
useLocalSearchParams: () => ({ uri: "https://example.com/test.pdf", title: "Test PDF" }),
Stack: { Screen: () => null },
Stack: {
Screen: ({ options }: { options?: { headerRight?: () => React.ReactNode } }) => {
const React = require("react");
return React.createElement(React.Fragment, null, options?.headerRight?.());
},
},
}));

jest.mock("expo-sharing", () => ({
Expand All @@ -28,8 +33,29 @@ jest.mock("@/modules/pdf-thumbnail", () => ({
generateThumbnail: jest.fn().mockResolvedValue({ uri: "file:///thumb.jpg", width: 300, height: 420 }),
}));

jest.mock("@/components/pdf-navigation-sheet", () => ({
PdfNavigationSheet: () => null,
}));

let mockOnError: ((e: unknown) => void) | null = null;

type Deferred<T> = {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (error: Error) => void;
};

const deferred = <T,>(): Deferred<T> => {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((promiseResolve, promiseReject) => {
resolve = promiseResolve;
reject = promiseReject;
});

return { promise, resolve, reject };
};

jest.mock("react-native-pdf", () => {
const { forwardRef } = require("react");
const { View } = require("react-native");
Expand All @@ -49,13 +75,20 @@ const renderWithProviders = () => renderWithQueryClient(<PdfViewerScreen />);

describe("PdfViewerScreen", () => {
beforeEach(() => {
const { File } = require("expo-file-system");
const Sharing = require("expo-sharing");
mockOnError = null;
File.downloadFileAsync.mockReset();
File.downloadFileAsync.mockResolvedValue({ uri: "file:///cache/test.pdf" });
Sharing.isAvailableAsync.mockReset();
Sharing.shareAsync.mockReset();
Sharing.isAvailableAsync.mockResolvedValue(true);
});

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 +100,88 @@ 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.getByTestId("loading-spinner")).toBeTruthy();
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.mockRejectedValueOnce(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();
});

it("ignores stale retry failures after a newer retry succeeds", async () => {
const { File } = require("expo-file-system");
const slowFailure = deferred<{ uri: string }>();
const fastSuccess = deferred<{ uri: string }>();
File.downloadFileAsync
.mockRejectedValueOnce(new Error("Initial network error"))
.mockReturnValueOnce(slowFailure.promise)
.mockReturnValueOnce(fastSuccess.promise);

renderWithProviders();

await waitFor(() => expect(screen.getByText("Try Again")).toBeTruthy());
const retryButton = screen.getByText("Try Again");

act(() => {
fireEvent.press(retryButton);
fireEvent.press(retryButton);
});

expect(File.downloadFileAsync).toHaveBeenCalledTimes(3);

await act(async () => {
fastSuccess.resolve({ uri: "file:///cache/fast.pdf" });
});

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

await act(async () => {
slowFailure.reject(new Error("Stale retry failure"));
});

expect(screen.queryByText(/Unable to load this PDF/)).toBeNull();
expect(screen.getByTestId("pdf-component")).toBeTruthy();
});

it("shares the cached PDF file when available", async () => {
const { File } = require("expo-file-system");
const Sharing = require("expo-sharing");

renderWithProviders();

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

fireEvent.press(screen.getByTestId("share-pdf-button"));

await waitFor(() => expect(Sharing.shareAsync).toHaveBeenCalledWith("file:///cache/test.pdf"));
expect(File.downloadFileAsync).toHaveBeenCalledTimes(1);
});
});
Loading
Loading