Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PdfViewer.tsx

499 lines18.0 KB

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