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

PdfViewer.tsx

499 lines17.9 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 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​
34const MAX_POSITIONS = 50;
35type PdfPosition = PdfViewState & { width: number; ratios: readonly number[] };
36// Thread switches unmount the preview; retain only the most recent documents.
37const positions = new Map<string, PdfPosition>();
38​
39export type PdfViewState = {
40 page: number;
41 offset: number;
42 zoom: number | null;
43 left: number;
44};
45​
46function PdfPage(props: {
47 document: PDFDocumentProxy;
48 index: number;
49 width: number;
50 query: string;
51 onSize: (index: number, ratio: number) => void;
52 onError: (error: string) => void;
53}) {
54 const canvas = useRef<HTMLCanvasElement>(null);
55 const text = useRef<HTMLDivElement>(null);
56 const { document: pdf, index, width, onSize, onError } = props;
57 // 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.
58 useEffect(() => {
59 let cancelled = false;
60 let paint: ReturnType<Awaited<ReturnType<PDFDocumentProxy["getPage"]>>["render"]> | undefined;
61 let layer: TextLayer | undefined;
62 let loadedPage: Awaited<ReturnType<PDFDocumentProxy["getPage"]>> | undefined;
63 void (async () => {
64 const page = await pdf.getPage(index + 1);
65 loadedPage = page;
66 if (cancelled || !canvas.current || !text.current) {
67 page.cleanup();
68 return;
69 }
70 const natural = page.getViewport({ scale: 1 });
71 onSize(index, natural.height / natural.width);
72 const viewport = page.getViewport({ scale: width / natural.width });
73 const ratio = Math.min(
74 2,
75 window.devicePixelRatio || 1,
76 Math.sqrt((8 * 1024 * 1024) / (viewport.width * viewport.height)),
77 );
78 canvas.current.width = Math.ceil(viewport.width * ratio);
79 canvas.current.height = Math.ceil(viewport.height * ratio);
80 paint = page.render({
81 canvas: canvas.current,
82 viewport,
83 transform: [ratio, 0, 0, ratio, 0, 0],
84 background: "white",
85 });
86 text.current.replaceChildren();
87 text.current.style.setProperty("--total-scale-factor", String(viewport.scale));
88 layer = new TextLayer({
89 container: text.current,
90 viewport,
91 textContentSource: page.streamTextContent(),
92 });
93 await Promise.all([paint.promise, layer.render()]);
94 })().catch((cause: unknown) => {
95 if (!cancelled)
96 onError(cause instanceof Error ? cause.message : "This PDF page could not render.");
97 });
98 return () => {
99 cancelled = true;
100 paint?.cancel();
101 layer?.cancel();
102 // Release operator lists when virtual pages leave the viewport.
103 void Promise.allSettled([paint?.promise]).then(() => loadedPage?.cleanup());
104 };
105 }, [pdf, index, width, onSize, onError]);
106 // 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.
107 useEffect(() => {
108 const node = text.current;
109 if (!node) return;
110 const mark = () => {
111 const elements = Array.from(node.querySelectorAll('span[role="presentation"], br'));
112 const hits = pdfFindMatchRuns(
113 elements.map((element) => (element.tagName === "BR" ? "\n" : (element.textContent ?? ""))),
114 props.query,
115 );
116 elements.forEach((element, index) => element.classList.toggle("pdf-find-match", hits[index]));
117 };
118 mark();
119 const observer = new MutationObserver(mark);
120 observer.observe(node, { childList: true, subtree: true });
121 return () => observer.disconnect();
122 }, [props.query]);
123 return (
124 <>
125 <canvas ref={canvas} aria-label={`Page ${index + 1}`} className="block h-full w-full" />
126 <div ref={text} data-pdf-text-layer />
127 </>
128 );
130​
131export default function PdfViewer(props: {
132 src: string;
133 title: string;
134 positionKey?: string;
135 initialView?: PdfViewState;
136 onViewChange?: (view: PdfViewState) => void;
137}) {
138 const [savedPosition] = useState(() =>
139 props.positionKey === undefined ? undefined : positions.get(props.positionKey),
140 );
141 const [initialView] = useState<PdfViewState>(
142 () => savedPosition ?? props.initialView ?? { page: 0, offset: 0, zoom: null, left: 0 },
143 );
144 const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
145 const [error, setError] = useState<string | null>(null);
146 const [revision, setRevision] = useState(0);
147 const [ratios, setRatios] = useState<readonly number[]>([]);
148 const [zoom, setZoom] = useState(initialView.zoom);
149 const [pageWidth, setPageWidth] = useState(612);
150 const [viewport, setViewport] = useState({ width: 600, height: 800 });
151 const [scrollTop, setScrollTop] = useState(0);
152 const [query, setQuery] = useState("");
153 const [matches, setMatches] = useState<number[]>([]);
154 const [finding, setFinding] = useState(false);
155 const [findError, setFindError] = useState<string | null>(null);
156 const [match, setMatch] = useState(0);
157 const scroll = useRef<HTMLDivElement>(null);
158 const find = useRef<HTMLInputElement>(null);
159 const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);
160 const initialPage = initialView.page;
161 // 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.
162 useEffect(() => {
163 const controller = new AbortController();
164 let disposed = false;
165 let task: ReturnType<typeof openPdf> | undefined;
166 const timeout = setTimeout(() => {
167 setError("This PDF took too long to load. Try again.");
168 controller.abort();
169 void task?.destroy();
170 }, 30_000);
171 void readBoundedDocument(
172 props.src,
173 controller.signal,
174 50 * 1024 * 1024,
175 revision > 0 ? "reload" : "default",
176 )
177 .then(async (bytes) => {
178 controller.signal.throwIfAborted();
179 task = openPdf(bytes);
180 const document = await task.promise;
181 if (document.numPages > MAX_PAGES)
182 throw new Error("Preview limited to 2,000 pages. Save this PDF to read it in full.");
183 const first = (await document.getPage(1)).getViewport({ scale: 1 });
184 const sizes = await Promise.all(
185 Array.from({ length: Math.min(initialPage + 1, document.numPages) }, async (_, index) => {
186 const size = (await document.getPage(index + 1)).getViewport({ scale: 1 });
187 return size.height / size.width;
188 }),
189 );
190 if (controller.signal.aborted) return;
191 setPageWidth(first.width);
192 setRatios(
193 savedPosition?.ratios.length === document.numPages
194 ? savedPosition.ratios
195 : Array.from(
196 { length: document.numPages },
197 (_, index) => sizes[index] ?? first.height / first.width,
198 ),
199 );
200 setPdf(document);
201 })
202 .catch((cause: unknown) => {
203 if (!disposed && !controller.signal.aborted)
204 setError(cause instanceof Error ? cause.message : "Unable to open PDF.");
205 })
206 .finally(() => clearTimeout(timeout));
207 return () => {
208 disposed = true;
209 controller.abort();
210 clearTimeout(timeout);
211 void task?.destroy();
212 };
213 }, [props.src, revision, initialPage, savedPosition]);
214 // 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.
215 useLayoutEffect(() => {
216 const node = scroll.current;
217 if (!node) return;
218 const update = () => setViewport({ width: node.clientWidth, height: node.clientHeight });
219 update();
220 return observeResize(node, update);
221 }, []);
222 const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom);
223 const offsets = pdfPageOffsets(ratios, width);
224 const current = currentPdfPage(offsets, ratios.length, scrollTop);
225 const visible = visiblePdfPages(ratios, offsets, scrollTop, viewport.height);
226 // Stable callbacks let page canvases survive scroll and find updates.
227 const [onSize] = useState(
228 () => (index: number, ratio: number) =>
229 setRatios((old) =>
230 old[index] === ratio ? old : old.map((value, i) => (i === index ? ratio : value)),
231 ),
232 );
233 const jumpToPage = useEffectEvent((index: number) => {
234 scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
235 });
236 const saveView = (node: HTMLDivElement, notify = true) => {
237 const page = currentPdfPage(offsets, ratios.length, node.scrollTop);
238 if (!pdf) return;
239 const view = {
240 page,
241 offset: Math.max(0, node.scrollTop - (offsets[page]! - 16)),
242 zoom,
243 left: node.scrollLeft,
244 };
245 if (notify) props.onViewChange?.(view);
246 if (props.positionKey !== undefined) {
247 positions.delete(props.positionKey);
248 positions.set(props.positionKey, { ...view, width, ratios });
249 const oldest = positions.keys().next();
250 if (positions.size > MAX_POSITIONS && !oldest.done) positions.delete(oldest.value);
251 }
252 };
253 const restoreView = useEffectEvent(() => {
254 const node = scroll.current;
255 if (!pdf || !node) return;
256 const page = Math.min(initialPage, pdf.numPages - 1);
257 node.scrollTo({
258 top:
259 offsets[page]! -
260 16 +
261 Math.min(
262 initialView.offset * (savedPosition ? width / savedPosition.width : 1),
263 Math.max(0, width * ratios[page]! - 1),
264 ),
265 left: initialView.left,
266 });
267 setScrollTop(node.scrollTop);
268 saveView(node);
269 });
270 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the saved PDF scroll position after the loaded document's page layout commits.
271 useLayoutEffect(() => {
272 if (pdf) restoreView();
273 }, [pdf]);
274 const showPage = (index: number) => {
275 scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
276 };
277 const changeZoom = (value: number | null) => {
278 zoomAnchor.current = {
279 page: current,
280 offset: (scroll.current?.scrollTop ?? 0) - (offsets[current]! - 16),
281 width,
282 };
283 setZoom(value);
284 };
285 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the DOM scroll anchor after the new zoom width has committed to page layout.
286 useLayoutEffect(() => {
287 const anchor = zoomAnchor.current;
288 zoomAnchor.current = null;
289 const node = scroll.current;
290 if (!node || !pdf) return;
291 if (anchor && anchor.width !== width) {
292 node.scrollTo({
293 top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
294 });
295 }
296 saveView(node, anchor !== null);
297 });
298 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll to the first asynchronous search result after its measured page offsets have committed.
299 useLayoutEffect(() => {
300 if (matches.length) jumpToPage(matches[0]!);
301 }, [matches]);
302 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.
303 useEffect(() => {
304 if (!pdf || !query.trim()) {
305 // oxlint-disable-next-line react/set-state-in-effect -- A blank query cancels the previous search.
306 setFinding(false);
307 return;
308 }
309 let cancelled = false;
310 const timer = setTimeout(() => {
311 setFinding(true);
312 setFindError(null);
313 setMatches([]);
314 setMatch(0);
315 void (async () => {
316 const found: number[] = [];
317 const sizes: number[] = [];
318 let size = 0;
319 for (let index = 0; index < pdf.numPages; index++) {
320 if (cancelled) return;
321 const page = await pdf.getPage(index + 1);
322 const pageSize = page.getViewport({ scale: 1 });
323 sizes.push(pageSize.height / pageSize.width);
324 const content = await page.getTextContent();
325 const text = pdfPageText(content.items);
326 size += text.length;
327 if (size > MAX_FIND_TEXT)
328 throw new Error(
329 "This PDF has too much text to search. Save it to search in another app.",
330 );
331 if (pdfFindIncludes(text, query)) found.push(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 );