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