import { useEffect, useState } from 'react'; import * as pdfjsLib from 'pdfjs-dist'; import { PageStack } from './PageStack'; pdfjsLib.GlobalWorkerOptions.workerSrc = new URL( 'pdfjs-dist/build/pdf.worker.mjs', import.meta.url, ).toString(); interface LoadedDocument { id: string; document: pdfjsLib.PDFDocumentProxy; } interface DocumentError { id: string; message: string; } export function PdfDocument({ documentId }: { documentId: string }) { const [loaded, setLoaded] = useState(null); const [error, setError] = useState(null); useEffect(() => { let active = true; const loadingTask = pdfjsLib.getDocument({ url: `/api/v1/documents/${documentId}/file` }); loadingTask.promise.then((document) => { if (active) setLoaded({ id: documentId, document }); }).catch((reason: unknown) => { if (active) { const message = reason instanceof Error ? reason.message : 'Unable to load this PDF.'; setError({ id: documentId, message }); } }); return () => { active = false; void loadingTask.destroy(); }; }, [documentId]); const currentError = error?.id === documentId ? error.message : null; const currentDocument = loaded?.id === documentId ? loaded.document : null; if (currentError) { return (
Error loading PDF: {currentError}
); } if (!currentDocument) { return (
Loading document…
); } return ; }