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

PdfViewer.tsx

493 lines17.7 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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll to the first asynchronous search result after its measured page offsets have committed.
293 useLayoutEffect(() => {
294 if (matches.length) jumpToPage(matches[0]!);
295 }, [matches]);
296 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.
297 useEffect(() => {
298 if (!pdf || !query.trim()) {
299 // oxlint-disable-next-line react/set-state-in-effect -- A blank query cancels the previous search.
300 setFinding(false);
301 return;
302 }
303 let cancelled = false;
304 const timer = setTimeout(() => {
305 setFinding(true);
306 setFindError(null);
307 setMatches([]);
308 setMatch(0);
309 void (async () => {
310 const found: number[] = [];
311 const sizes: number[] = [];
312 let size = 0;
313 for (let index = 0; index < pdf.numPages; index++) {
314 if (cancelled) return;
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 const text = pdfPageText(content.items);
320 size += text.length;
321 if (size > MAX_FIND_TEXT)
322 throw new Error(
323 "This PDF has too much text to search. Save it to search in another app.",
324 );
325 if (pdfFindIncludes(text, query)) found.push(index);
326 }
327 if (cancelled) return;
328 setRatios(sizes);
329 setMatches(found);
330 })()
331 .catch((cause: unknown) => {
332 if (!cancelled)
333 setFindError(cause instanceof Error ? cause.message : "Could not search this PDF.");
334 })
335 .finally(() => {
336 if (!cancelled) setFinding(false);
337 });
338 }, 250);
339 return () => {
340 cancelled = true;
341 clearTimeout(timer);
342 };
343 }, [pdf, query]);
344 return (
345 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
346 <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">
347 <span className="mr-auto px-1 tabular-nums" aria-live="polite">
348 {pdf ? `${current + 1} / ${pdf.numPages} pages` : "PDF"}
349 </span>
350 <FileSurfaceAction
351 label="Previous page"
352 disabled={!pdf || current === 0}
353 onPress={() => showPage(current - 1)}
354 >
355 <ChevronUpIcon className="size-3.5" />
356 </FileSurfaceAction>
357 <FileSurfaceAction
358 label="Next page"
359 disabled={!pdf || current + 1 >= pdf.numPages}
360 onPress={() => showPage(current + 1)}
361 >
362 <ChevronDownIcon className="size-3.5" />
363 </FileSurfaceAction>
364 <FileSurfaceAction
365 label="Zoom out"
366 disabled={scale <= PDF_MIN_ZOOM}
367 onPress={() => changeZoom(stepPdfZoom(scale, -1))}
368 >
369 <MinusIcon className="size-3.5" />
370 </FileSurfaceAction>
371 <span className="min-w-14 text-center tabular-nums">
372 {zoom === null ? "Fit width" : `${Math.round(scale * 100)}%`}
373 </span>
374 <FileSurfaceAction
375 label="Zoom in"
376 disabled={scale >= PDF_MAX_ZOOM}
377 onPress={() => changeZoom(stepPdfZoom(scale, 1))}
378 >
379 <PlusIcon className="size-3.5" />
380 </FileSurfaceAction>
381 <FileSurfaceAction
382 label="Fit width"
383 onPress={() => {
384 changeZoom(null);
385 scroll.current?.scrollTo({ left: 0 });
386 }}
387 >
388 <ScanIcon className="size-3.5" />
389 </FileSurfaceAction>
390 <div className="w-28">
391 <Input
392 ref={find}
393 size="compact"
394 type="search"
395 aria-label="Find in PDF"
396 placeholder="Find in PDF"
397 value={query}
398 onChange={(event) => {
399 setQuery(event.target.value);
400 setMatches([]);
401 setFindError(null);
402 }}
403 />
404 </div>
405 {query ? (
406 <>
407 <span role="status">
408 {finding
409 ? "Searching…"
410 : (findError ?? `${matches.length ? match + 1 : 0}/${matches.length}`)}
411 </span>
412 <FileSurfaceAction
413 label="Next matching page"
414 disabled={!matches.length}
415 onPress={() => {
416 const next = (match + 1) % matches.length;
417 setMatch(next);
418 showPage(matches[next]!);
419 }}
420 >
421 <ChevronDownIcon className="size-3.5" />
422 </FileSurfaceAction>
423 </>
424 ) : null}
425 </div>
426 <div
427 ref={scroll}
428 role="region"
429 aria-label={props.title}
430 tabIndex={0}
431 className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto scrollbar-gutter-stable bg-muted/40"
432 onScroll={(event) => {
433 const top = event.currentTarget.scrollTop;
434 setScrollTop(top);
435 saveView(event.currentTarget);
436 }}
437 onKeyDown={(event) => {
438 if ((event.ctrlKey || event.metaKey) && event.key === "f") {
439 event.preventDefault();
440 event.stopPropagation();
441 find.current?.focus();
442 }
443 }}
444 >
445 {error ? (
446 <FileSurfaceFailure
447 message={error}
448 onRetry={() => {
449 setError(null);
450 setPdf(null);
451 setRevision((value) => value + 1);
452 }}
453 />
454 ) : !pdf ? (
455 <FileSurfaceLoading />
456 ) : (
457 <div
458 className="relative"
459 style={{
460 height: `max(${offsets.at(-1) ?? 0}px, calc(100% + ${(offsets.at(-2) ?? 16) - 16}px))`,
461 minWidth: width + 32,
462 }}
463 >
464 {visible.map(({ index, ratio }) => (
465 <div
466 key={index}
467 className="absolute bg-white shadow-sm"
468 style={
469 {
470 top: offsets[index],
471 left: Math.max(16, (viewport.width - width) / 2),
472 width,
473 height: width * ratio,
474 "--total-scale-factor": 1,
475 } as CSSProperties
476 }
477 >
478 <PdfPage
479 document={pdf}
480 index={index}
481 width={width}
482 query={query}
483 onSize={onSize}
484 onError={setError}
485 />
486 </div>
487 ))}
488 </div>
489 )}
490 </div>
491 </div>
492 );