diff --git a/docs/api.md b/docs/api.md index cc00368..70470d0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -157,6 +157,9 @@ open and the other pages keep working: `error.page !== undefined` tells them apart (it narrows the type to `PdfPageError`). iOS reports load failures only (PDFKit draws the pages). +Without `onError`, development builds warn about failures with +`console.warn`, once per source and code; release builds print nothing. + ### Method errors The ref's promise methods (`getOutline`, `getPageSizes`, `renderPage`, diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 408d59e..fb63255 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5,6 +5,7 @@ | The viewer does not appear in Expo Go | Use a development build (`npx expo run:ios` / `run:android`); Expo Go cannot load native modules. | | An error about `BetterPdfView` right after installing | Rebuild the native app: `pod install` and a new build on iOS, a new build on Android. | | Errors about the legacy architecture | Enable the New Architecture; Nitro Views need Fabric. | +| The viewer stays blank | The load failed, or is still running (there is no built-in spinner). Pass `onError` and read `error.code`; without it, a development build prints a warning such as `[react-native-better-pdf] file-not-found: …` in Metro. | | A password-protected document fails with `unsupported-pdf` on Android | The device is below Android 15 without SDK extension 13, where the platform renderer cannot open protected files. | | Search reports `isSupported: false`, long presses select nothing | Same devices as above; see the [capability matrix](../README.md#capability-matrix). | | On Android, `onError` arrives while the document is shown | It has `error.page`: one page could not be rendered after `onLoad` (`page-render-failed`, or `out-of-memory`), and the document stays open. Keep the viewer on screen; only `onError` without `page` ends the load. See [Errors](api.md#errors). | diff --git a/package/src/PdfView.test.tsx b/package/src/PdfView.test.tsx index 6be26f5..af41d60 100644 --- a/package/src/PdfView.test.tsx +++ b/package/src/PdfView.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, mock, test } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'; import { createRef, useEffect, type ReactNode } from 'react'; import { act, create, type ReactTestRenderer } from 'react-test-renderer'; @@ -1229,3 +1229,175 @@ describe('PdfView', () => { ).rejects.toMatchObject({ code: 'invalid-argument' }); }); }); + +describe('PdfView without onError', () => { + const globals = globalThis as { __DEV__?: boolean }; + const warn = console.warn; + let warnings: string[] = []; + + beforeEach(() => { + warnings = []; + console.warn = (...args: unknown[]) => warnings.push(args.join(' ')); + }); + + afterEach(() => { + console.warn = warn; + delete globals.__DEV__; + }); + + const emitError = (error: PdfError) => + (lastHost().onError as { f: (error: PdfError) => void }).f(error); + + test('warns in development about a load failure, once per source and code', () => { + globals.__DEV__ = true; + const renderer = render(); + const missing = { + code: 'file-not-found', + message: 'No file at /a.pdf', + } as const; + emitError({ ...missing, sourceIndex: 0 }); + emitError({ ...missing, sourceIndex: 0 }); + expect(warnings).toEqual([ + '[react-native-better-pdf] file-not-found: No file at /a.pdf. Pass onError to handle load failures.', + ]); + + emitError({ code: 'invalid-pdf', message: 'Not a PDF', sourceIndex: 0 }); + act(() => renderer.update()); + emitError({ ...missing, sourceIndex: 0 }); + expect(warnings).toHaveLength(2); + expect(warnings[1]).toContain('invalid-pdf: Not a PDF.'); + + act(() => renderer.update()); + emitError({ code: 'file-not-found', message: 'No file at /b.pdf' }); + expect(warnings).toHaveLength(3); + expect(warnings[2]).toContain('file-not-found: No file at /b.pdf.'); + }); + + test('warns in development about page failures once per document, not per page', () => { + globals.__DEV__ = true; + render(); + emitError({ + code: 'page-render-failed', + message: 'Rendering page 1 failed', + page: 1, + }); + emitError({ + code: 'page-render-failed', + message: 'Rendering page 4 failed', + page: 4, + }); + expect(warnings).toEqual([ + '[react-native-better-pdf] page-render-failed: Rendering page 1 failed. Pass onError to handle page failures.', + ]); + }); + + test('warns in development without the user info, query or fragment of URLs', () => { + globals.__DEV__ = true; + const errors: PdfError[] = []; + const renderer = render(); + emitError({ + code: 'http-error', + message: + 'Downloading https://cdn.x.test/a.pdf?X-Amz-Signature=secret&X-Amz-Expires=60 failed with HTTP 500', + httpStatus: 500, + }); + emitError({ + code: 'invalid-source', + message: + 'Unsupported PDF source: "ftp://user:p@ss@x.test/a@b.pdf?token=secret"', + }); + emitError({ + code: 'network-error', + message: 'Downloading https://x.test/a.pdf#token=secret failed', + }); + emitError({ + code: 'file-not-found', + message: 'Downloading https://user:secret@x.test/a.pdf failed', + }); + expect(warnings).toEqual([ + '[react-native-better-pdf] http-error: Downloading https://cdn.x.test/a.pdf?… failed with HTTP 500. Pass onError to handle load failures.', + '[react-native-better-pdf] invalid-source: Unsupported PDF source: "ftp://…@x.test/a@b.pdf?…". Pass onError to handle load failures.', + '[react-native-better-pdf] network-error: Downloading https://x.test/a.pdf#… failed. Pass onError to handle load failures.', + '[react-native-better-pdf] file-not-found: Downloading https://…@x.test/a.pdf failed. Pass onError to handle load failures.', + ]); + + // The app's handler gets the message as it is. + act(() => + renderer.update( + errors.push(error)} + />, + ), + ); + emitError({ + code: 'network-error', + message: 'Downloading https://x.test/a.pdf?token=secret failed', + }); + expect(errors.map((error) => error.message)).toEqual([ + 'Downloading https://x.test/a.pdf?token=secret failed', + ]); + }); + + test('warns in development about an invalid source once', () => { + globals.__DEV__ = true; + const renderer = render(); + act(() => renderer.update()); + expect(warnings).toEqual([ + '[react-native-better-pdf] invalid-source: source must be a require() result or an object with uri, filePath or base64; got {}. Pass onError to handle load failures.', + ]); + }); + + test('warns in development once the app removes its onError', () => { + globals.__DEV__ = true; + const errors: PdfError[] = []; + const renderer = render( + errors.push(error)} + />, + ); + const failure = { code: 'invalid-pdf', message: 'Not a PDF' } as const; + emitError(failure); + expect(errors).toEqual([failure]); + expect(warnings).toEqual([]); + + act(() => renderer.update()); + emitError(failure); + expect(errors).toHaveLength(1); + expect(warnings).toHaveLength(1); + }); + + test('does not warn when the app passes onError', () => { + globals.__DEV__ = true; + const errors: PdfError[] = []; + render( errors.push(e)} />); + render( + errors.push(e)} + />, + ); + emitError({ code: 'file-not-found', message: 'No file at /a.pdf' }); + expect(errors.map((error) => error.code)).toEqual([ + 'invalid-source', + 'file-not-found', + ]); + expect(warnings).toEqual([]); + }); + + test('release builds neither subscribe to onError nor warn', () => { + globals.__DEV__ = false; + render(); + expect(lastHost().onError).toBeUndefined(); + render(); + + // Subscribed for a handler the app then removed. + const renderer = render( + {}} />, + ); + act(() => renderer.update()); + emitError({ code: 'file-not-found', message: 'No file at /a.pdf' }); + expect(warnings).toEqual([]); + }); +}); diff --git a/package/src/PdfView.tsx b/package/src/PdfView.tsx index 87b0e2d..3fd58a9 100644 --- a/package/src/PdfView.tsx +++ b/package/src/PdfView.tsx @@ -49,6 +49,7 @@ import type { NativePdfSource } from './types/NativePdfSource'; import type { PdfColorScheme } from './types/PdfColorScheme'; import type { PdfContentInset } from './types/PdfContentInset'; import type { PdfError, PdfLoadError, PdfPageError } from './types/PdfError'; +import type { PdfErrorCode } from './types/PdfErrorCode'; import type { PdfExportOptions } from './types/PdfExportOptions'; import type { PdfExportResult } from './types/PdfExportResult'; import type { PdfFitPolicy } from './types/PdfFitPolicy'; @@ -83,6 +84,47 @@ const NativeBetterPdfView = getHostComponent( type NativeRef = HybridRef; +// React Native's global, missing elsewhere (tests); the library builds without +// React Native's global types. +declare const __DEV__: boolean | undefined; + +function isDevelopment(): boolean { + return typeof __DEV__ !== 'undefined' && __DEV__ === true; +} + +const warnedErrorCodes = new WeakMap>(); + +// Native messages name the source URL. Its user info can hold a password, and +// a signed URL's token is in its query. +const URL_PARTS = + /(\b[a-z][a-z\d+.-]*:\/\/)([^\s/?#"]*@)?([^\s?#"]*)([?#][^\s"]*)?/gi; + +function redactUrls(message: string): string { + return message.replace( + URL_PARTS, + (_url, scheme: string, userInfo?: string, path = '', tail?: string) => + `${scheme}${userInfo ? '…@' : ''}${path}${tail ? `${tail[0]}…` : ''}`, + ); +} + +/** + * In development, warns about an error the app has no `onError` for: once + * per `sources` and code when given. + */ +function warnUnhandledError(error: PdfError, sources?: object): void { + if (!isDevelopment()) return; + if (sources !== undefined) { + const codes = warnedErrorCodes.get(sources) ?? new Set(); + if (codes.has(error.code)) return; + warnedErrorCodes.set(sources, codes.add(error.code)); + } + const failures = error.page === undefined ? 'load' : 'page'; + const message = redactUrls(error.message); + console.warn( + `[react-native-better-pdf] ${error.code}: ${message}. Pass onError to handle ${failures} failures.`, + ); +} + /** `rgba(255, 214, 0, 0.4)` and `rgba(255, 140, 0, 0.6)` as ARGB. */ const DEFAULT_SEARCH_HIGHLIGHT_COLOR = 0x66ffd600; const DEFAULT_SEARCH_CURRENT_HIGHLIGHT_COLOR = 0x99ff8c00; @@ -429,6 +471,8 @@ export interface PdfViewProps extends ViewProps { * loaded again (e.g. a new `key`); each page is reported once. * `out-of-memory`: the viewer frees memory and tries the page again * later; reported once per document. + * + * Without it, development builds print a warning naming the code instead. */ onError?: (error: PdfLoadError | PdfPageError) => void; onPageChange?: (event: PdfPageChangeEvent) => void; @@ -653,9 +697,14 @@ export function PdfView({ handlers.current.onLoadProgress?.(event), ), // Native sets `page` only for page failures. - onError: callback((error: PdfError) => - handlers.current.onError?.(error as PdfLoadError | PdfPageError), - ), + onError: callback((error: PdfError) => { + const onError = handlers.current.onError; + if (onError === undefined) { + warnUnhandledError(error, latestSources.current); + } else { + onError(error as PdfLoadError | PdfPageError); + } + }), onPageChange: callback((event: PdfPageChangeEvent) => handlers.current.onPageChange?.(event), ), @@ -773,7 +822,10 @@ export function PdfView({ // entirely for the others. Once subscribed, an event stays subscribed (the // handler ref makes a removed handler a no-op): unsubscribing would send // `null`, which Nitro rejects. That takes reading the set during render. - const subscribed = useRef(new Set()); + // In development `onError` is always subscribed, to warn when it is missing. + const subscribed = useRef( + new Set(isDevelopment() ? ['onError'] : []), + ); const subscription = (name: K) => { if (renderedHandlers[name] !== undefined) subscribed.current.add(name); return subscribed.current.has(name) ? nativeCallbacks[name] : undefined; @@ -796,11 +848,17 @@ export function PdfView({ } if (reportedInvalidSource.current === invalidSourceKey) return; reportedInvalidSource.current = invalidSourceKey; - handlers.current.onError?.({ + const error: PdfLoadError = { code: 'invalid-source', message: invalidMessage!, sourceIndex: invalidSourceIndex, - }); + }; + const onError = handlers.current.onError; + if (onError === undefined) { + warnUnhandledError(error); + } else { + onError(error); + } }, [invalidMessage, invalidSourceIndex, invalidSourceKey]); useEffect(() => {