Open History to see the last commit
1import {
2 useEffect,
3 useEffectEvent,
4 useLayoutEffect,
5 useRef,
6 useState,
7 type CSSProperties,
8} from "react";
9import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist";
10import { ChevronDownIcon, ChevronUpIcon, MinusIcon, PlusIcon, ScanIcon } from "lucide-react";
11import { Input } from "~/components/ui/input";
12import { observeResize } from "~/lib/observeResize";
13import { FileSurfaceAction, FileSurfaceFailure, FileSurfaceLoading } from "./fileSurfaceChrome";
14import { readBoundedDocument } from "./readBoundedDocument";
15import { openPdf } from "./pdfDocument";
16import {
17 currentPdfPage,
18 pdfFindIncludes,
19 pdfFindMatchRuns,
20 pdfPageOffsets,
21 pdfPageScrollTop,
22 pdfPageText,
23 pdfPageWidth,
24 PDF_MAX_ZOOM,
25 PDF_MIN_ZOOM,
26 stepPdfZoom,
27 visiblePdfPages,
28} from "./pdfLayout";
29import "./pdfViewer.css";
30
31const MAX_PAGES = 2000;
32const MAX_FIND_TEXT = 4 * 1024 * 1024;
33
34function PdfPage(props: {
35 document: PDFDocumentProxy;
36 index: number;
37 width: number;
38 query: string;
39 onSize: (index: number, ratio: number) => void;
40 onError: (error: string) => void;
41}) {
42 const canvas = useRef<HTMLCanvasElement>(null);
43 const text = useRef<HTMLDivElement>(null);
44 const { document: pdf, index, width, onSize, onError } = props;
45 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Render the PDF page canvas and text layer, cancelling tasks and releasing pdf.js page resources on cleanup.
46 useEffect(() => {
47 let cancelled = false;
48 let paint: ReturnType<Awaited<ReturnType<PDFDocumentProxy["getPage"]>>["render"]> | undefined;
49 let layer: TextLayer | undefined;
50 let loadedPage: Awaited<ReturnType<PDFDocumentProxy["getPage"]>> | undefined;
51 void (async () => {
52 const page = await pdf.getPage(index + 1);
53 loadedPage = page;
54 if (cancelled || !canvas.current || !text.current) {
55 page.cleanup();
56 return;
57 }
58 const natural = page.getViewport({ scale: 1 });
59 onSize(index, natural.height / natural.width);
60 const viewport = page.getViewport({ scale: width / natural.width });
61 const ratio = Math.min(
62 2,
63 window.devicePixelRatio || 1,
64 Math.sqrt((8 * 1024 * 1024) / (viewport.width * viewport.height)),
65 );
66 canvas.current.width = Math.ceil(viewport.width * ratio);
67 canvas.current.height = Math.ceil(viewport.height * ratio);
68 paint = page.render({
69 canvas: canvas.current,
70 viewport,
71 transform: [ratio, 0, 0, ratio, 0, 0],
72 background: "white",
73 });
74 text.current.replaceChildren();
75 text.current.style.setProperty("--total-scale-factor", String(viewport.scale));
76 layer = new TextLayer({
77 container: text.current,
78 viewport,
79 textContentSource: page.streamTextContent(),
80 });
81 await Promise.all([paint.promise, layer.render()]);
82 })().catch((cause: unknown) => {
83 if (!cancelled)
84 onError(cause instanceof Error ? cause.message : "This PDF page could not render.");
85 });
86 return () => {
87 cancelled = true;
88 paint?.cancel();
89 layer?.cancel();
90 // Release operator lists when virtual pages leave the viewport.
91 void Promise.allSettled([paint?.promise]).then(() => loadedPage?.cleanup());
92 };
93 }, [pdf, index, width, onSize, onError]);
94 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Highlight pdf.js-owned text nodes and observe asynchronous text layer mutations for the current search query.
95 useEffect(() => {
96 const node = text.current;
97 if (!node) return;
98 const mark = () => {
99 const elements = Array.from(node.querySelectorAll('span[role="presentation"], br'));
100 const hits = pdfFindMatchRuns(
101 elements.map((element) => (element.tagName === "BR" ? "\n" : (element.textContent ?? ""))),
102 props.query,
103 );
104 elements.forEach((element, index) => element.classList.toggle("pdf-find-match", hits[index]));
105 };
106 mark();
107 const observer = new MutationObserver(mark);
108 observer.observe(node, { childList: true, subtree: true });
109 return () => observer.disconnect();
110 }, [props.query]);
111 return (
112 <>
113 <canvas ref={canvas} aria-label={`Page ${index + 1}`} className="block h-full w-full" />
114 <div ref={text} data-pdf-text-layer />
115 </>
116 );
117}
118
119export default function PdfViewer(props: { src: string; title: string }) {
120 const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
121 const [error, setError] = useState<string | null>(null);
122 const [revision, setRevision] = useState(0);
123 const [ratios, setRatios] = useState<number[]>([]);
124 const [zoom, setZoom] = useState<number | null>(null);
125 const [pageWidth, setPageWidth] = useState(612);
126 const [viewport, setViewport] = useState({ width: 600, height: 800 });
127 const [scrollTop, setScrollTop] = useState(0);
128 const [query, setQuery] = useState("");
129 const [matches, setMatches] = useState<number[]>([]);
130 const [finding, setFinding] = useState(false);
131 const [findError, setFindError] = useState<string | null>(null);
132 const [match, setMatch] = useState(0);
133 const scroll = useRef<HTMLDivElement>(null);
134 const find = useRef<HTMLInputElement>(null);
135 const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);
136 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the PDF fetch, load timeout, and pdf.js document task across source changes, retries, and unmounts.
137 useEffect(() => {
138 const controller = new AbortController();
139 let disposed = false;
140 let task: ReturnType<typeof openPdf> | undefined;
141 const timeout = setTimeout(() => {
142 setError("This PDF took too long to load. Try again.");
143 controller.abort();
144 void task?.destroy();
145 }, 30_000);
146 void readBoundedDocument(
147 props.src,
148 controller.signal,
149 50 * 1024 * 1024,
150 revision > 0 ? "reload" : "default",
151 )
152 .then(async (bytes) => {
153 controller.signal.throwIfAborted();
154 task = openPdf(bytes);
155 const document = await task.promise;
156 if (document.numPages > MAX_PAGES)
157 throw new Error("Preview limited to 2,000 pages. Save this PDF to read it in full.");
158 const first = (await document.getPage(1)).getViewport({ scale: 1 });
159 if (controller.signal.aborted) return;
160 setPageWidth(first.width);
161 setRatios(Array.from({ length: document.numPages }, () => first.height / first.width));
162 setPdf(document);
163 })
164 .catch((cause: unknown) => {
165 if (!disposed && !controller.signal.aborted)
166 setError(cause instanceof Error ? cause.message : "Unable to open PDF.");
167 })
168 .finally(() => clearTimeout(timeout));
169 return () => {
170 disposed = true;
171 controller.abort();
172 clearTimeout(timeout);
173 void task?.destroy();
174 };
175 }, [props.src, revision]);
176 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure the PDF viewport before paint and observe resizes for fit-width sizing and visible-page selection.
177 useLayoutEffect(() => {
178 const node = scroll.current;
179 if (!node) return;
180 const update = () => setViewport({ width: node.clientWidth, height: node.clientHeight });
181 update();
182 return observeResize(node, update);
183 }, []);
184 const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom);
185 const offsets = pdfPageOffsets(ratios, width);
186 const current = currentPdfPage(offsets, ratios.length, scrollTop);
187 const visible = visiblePdfPages(ratios, offsets, scrollTop, viewport.height);
188 // Stable callbacks let page canvases survive scroll and find updates.
189 const [onSize] = useState(
190 () => (index: number, ratio: number) =>
191 setRatios((old) =>
192 old[index] === ratio ? old : old.map((value, i) => (i === index ? ratio : value)),
193 ),
194 );
195 const jumpToPage = useEffectEvent((index: number) => {
196 scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
197 });
198 const showPage = (index: number) => {
199 scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
200 };
201 const changeZoom = (value: number | null) => {
202 zoomAnchor.current = {
203 page: current,
204 offset: (scroll.current?.scrollTop ?? 0) - (offsets[current]! - 16),
205 width,
206 };
207 setZoom(value);
208 };
209 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the DOM scroll anchor after the new zoom width has committed to page layout.
210 useLayoutEffect(() => {
211 const anchor = zoomAnchor.current;
212 zoomAnchor.current = null;
213 if (!anchor || anchor.width === width) return;
214 scroll.current?.scrollTo({
215 top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
216 });
217 });
218 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll to the first asynchronous search result after its measured page offsets have committed.
219 useLayoutEffect(() => {
220 if (matches.length) jumpToPage(matches[0]!);
221 }, [matches]);
222 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.
223 useEffect(() => {
224 if (!pdf || !query.trim()) {
225 // oxlint-disable-next-line react/set-state-in-effect -- A blank query cancels the previous search.
226 setFinding(false);
227 return;
228 }
229 let cancelled = false;
230 const timer = setTimeout(() => {
231 setFinding(true);
232 setFindError(null);
233 setMatches([]);
234 setMatch(0);
235 void (async () => {
236 const found: number[] = [];
237 const sizes: number[] = [];
238 let size = 0;
239 for (let index = 0; index < pdf.numPages; index++) {
240 if (cancelled) return;
241 const page = await pdf.getPage(index + 1);
242 const pageSize = page.getViewport({ scale: 1 });
243 sizes.push(pageSize.height / pageSize.width);
244 const content = await page.getTextContent();
245 const text = pdfPageText(content.items);
246 size += text.length;
247 if (size > MAX_FIND_TEXT)
248 throw new Error(
249 "This PDF has too much text to search. Save it to search in another app.",
250 );
251 if (pdfFindIncludes(text, query)) found.push(index);
252 }
253 if (cancelled) return;
254 setRatios(sizes);
255 setMatches(found);
256 })()
257 .catch((cause: unknown) => {
258 if (!cancelled)
259 setFindError(cause instanceof Error ? cause.message : "Could not search this PDF.");
260 })
261 .finally(() => {
262 if (!cancelled) setFinding(false);
263 });
264 }, 250);
265 return () => {
266 cancelled = true;
267 clearTimeout(timer);
268 };
269 }, [pdf, query]);
270 return (
271 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
272 <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-2 py-1 text-xs">
273 <span className="mr-auto px-1 tabular-nums" aria-live="polite">
274 {pdf ? `${current + 1} / ${pdf.numPages} pages` : "PDF"}
275 </span>
276 <FileSurfaceAction
277 label="Previous page"
278 disabled={!pdf || current === 0}
279 onPress={() => showPage(current - 1)}
280 >
281 <ChevronUpIcon className="size-3.5" />
282 </FileSurfaceAction>
283 <FileSurfaceAction
284 label="Next page"
285 disabled={!pdf || current + 1 >= pdf.numPages}
286 onPress={() => showPage(current + 1)}
287 >
288 <ChevronDownIcon className="size-3.5" />
289 </FileSurfaceAction>
290 <FileSurfaceAction
291 label="Zoom out"
292 disabled={scale <= PDF_MIN_ZOOM}
293 onPress={() => changeZoom(stepPdfZoom(scale, -1))}
294 >
295 <MinusIcon className="size-3.5" />
296 </FileSurfaceAction>
297 <span className="min-w-14 text-center tabular-nums">
298 {zoom === null ? "Fit width" : `${Math.round(scale * 100)}%`}
299 </span>
300 <FileSurfaceAction
301 label="Zoom in"
302 disabled={scale >= PDF_MAX_ZOOM}
303 onPress={() => changeZoom(stepPdfZoom(scale, 1))}
304 >
305 <PlusIcon className="size-3.5" />
306 </FileSurfaceAction>
307 <FileSurfaceAction
308 label="Fit width"
309 onPress={() => {
310 changeZoom(null);
311 scroll.current?.scrollTo({ left: 0 });
312 }}
313 >
314 <ScanIcon className="size-3.5" />
315 </FileSurfaceAction>
316 <div className="w-28">
317 <Input
318 ref={find}
319 size="compact"
320 type="search"
321 aria-label="Find in PDF"
322 placeholder="Find in PDF"
323 value={query}
324 onChange={(event) => {
325 setQuery(event.target.value);
326 setMatches([]);
327 setFindError(null);
328 }}
329 />
330 </div>
331 {query ? (
332 <>
333 <span role="status">
334 {finding
335 ? "Searching…"
336 : (findError ?? `${matches.length ? match + 1 : 0}/${matches.length}`)}
337 </span>
338 <FileSurfaceAction
339 label="Next matching page"
340 disabled={!matches.length}
341 onPress={() => {
342 const next = (match + 1) % matches.length;
343 setMatch(next);
344 showPage(matches[next]!);
345 }}
346 >
347 <ChevronDownIcon className="size-3.5" />
348 </FileSurfaceAction>
349 </>
350 ) : null}
351 </div>
352 <div
353 ref={scroll}
354 role="region"
355 aria-label={props.title}
356 tabIndex={0}
357 className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto bg-muted/40"
358 onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
359 onKeyDown={(event) => {
360 if ((event.ctrlKey || event.metaKey) && event.key === "f") {
361 event.preventDefault();
362 event.stopPropagation();
363 find.current?.focus();
364 }
365 }}
366 >
367 {error ? (
368 <FileSurfaceFailure
369 message={error}
370 onRetry={() => {
371 setError(null);
372 setPdf(null);
373 setRevision((value) => value + 1);
374 }}
375 />
376 ) : !pdf ? (
377 <FileSurfaceLoading />
378 ) : (
379 <div
380 className="relative"
381 style={{
382 height: `max(${offsets.at(-1) ?? 0}px, calc(100% + ${(offsets.at(-2) ?? 16) - 16}px))`,
383 minWidth: width + 32,
384 }}
385 >
386 {visible.map(({ index, ratio }) => (
387 <div
388 key={index}
389 className="absolute bg-white shadow-sm"
390 style={
391 {
392 top: offsets[index],
393 left: Math.max(16, (viewport.width - width) / 2),
394 width,
395 height: width * ratio,
396 "--total-scale-factor": 1,
397 } as CSSProperties
398 }
399 >
400 <PdfPage
401 document={pdf}
402 index={index}
403 width={width}
404 query={query}
405 onSize={onSize}
406 onError={setError}
407 />
408 </div>
409 ))}
410 </div>
411 )}
412 </div>
413 </div>
414 );
415}