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

PdfViewer.tsx

431 lines15.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 "./pdfViewer.css";
17​
18const MAX_PAGES = 2000;
19const MAX_FIND_TEXT = 4 * 1024 * 1024;
20​
21function PdfPage(props: {
22 document: PDFDocumentProxy;
23 index: number;
24 width: number;
25 query: string;
26 onSize: (index: number, ratio: number) => void;
27 onError: (error: string) => void;
28}) {
29 const canvas = useRef<HTMLCanvasElement>(null);
30 const text = useRef<HTMLDivElement>(null);
31 const { document: pdf, index, width, onSize, onError } = props;
32 // oxlint-disable-next-line t3code/react-effect-budget -- Render the PDF page canvas and text layer, cancelling tasks and releasing pdf.js page resources on cleanup.
33 useEffect(() => {
34 let cancelled = false;
35 let paint: ReturnType<Awaited<ReturnType<PDFDocumentProxy["getPage"]>>["render"]> | undefined;
36 let layer: TextLayer | undefined;
37 let loadedPage: Awaited<ReturnType<PDFDocumentProxy["getPage"]>> | undefined;
38 void (async () => {
39 const page = await pdf.getPage(index + 1);
40 loadedPage = page;
41 if (cancelled || !canvas.current || !text.current) {
42 page.cleanup();
43 return;
44 }
45 const natural = page.getViewport({ scale: 1 });
46 onSize(index, natural.height / natural.width);
47 const viewport = page.getViewport({ scale: width / natural.width });
48 const ratio = Math.min(
49 2,
50 window.devicePixelRatio || 1,
51 Math.sqrt((8 * 1024 * 1024) / (viewport.width * viewport.height)),
52 );
53 canvas.current.width = Math.ceil(viewport.width * ratio);
54 canvas.current.height = Math.ceil(viewport.height * ratio);
55 paint = page.render({
56 canvas: canvas.current,
57 viewport,
58 transform: [ratio, 0, 0, ratio, 0, 0],
59 background: "white",
60 });
61 text.current.replaceChildren();
62 text.current.style.setProperty("--total-scale-factor", String(viewport.scale));
63 layer = new TextLayer({
64 container: text.current,
65 viewport,
66 textContentSource: page.streamTextContent(),
67 });
68 await Promise.all([paint.promise, layer.render()]);
69 })().catch((cause: unknown) => {
70 if (!cancelled)
71 onError(cause instanceof Error ? cause.message : "This PDF page could not render.");
72 });
73 return () => {
74 cancelled = true;
75 paint?.cancel();
76 layer?.cancel();
77 // Release operator lists when virtual pages leave the viewport.
78 void Promise.allSettled([paint?.promise]).then(() => loadedPage?.cleanup());
79 };
80 }, [pdf, index, width, onSize, onError]);
81 // oxlint-disable-next-line t3code/react-effect-budget -- Highlight pdf.js-owned text nodes and observe asynchronous text layer mutations for the current search query.
82 useEffect(() => {
83 const node = text.current;
84 if (!node) return;
85 const mark = () => {
86 const runs = Array.from(node.querySelectorAll('span[role="presentation"], br')).map(
87 (element) => ({
88 element,
89 text: element.tagName === "BR" ? "\n" : (element.textContent ?? "").toLowerCase(),
90 }),
91 );
92 const text = runs.map((run) => run.text).join("");
93 const query = props.query.toLowerCase();
94 let match = query.trim() ? text.indexOf(query) : -1;
95 let offset = 0;
96 for (const run of runs) {
97 while (match !== -1 && match + query.length <= offset)
98 match = text.indexOf(query, match + query.length);
99 run.element.classList.toggle(
100 "pdf-find-match",
101 match !== -1 && match < offset + run.text.length,
102 );
103 offset += run.text.length;
104 }
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 );
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/react-effect-budget -- 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/react-effect-budget -- 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 fitWidth = Math.max(1, viewport.width - 32);
185 const scale = zoom ?? fitWidth / pageWidth;
186 const width = zoom === null ? fitWidth : pageWidth * zoom;
187 const offsets = (() => {
188 const result = [16];
189 for (const ratio of ratios) result.push(result[result.length - 1]! + width * ratio + 16);
190 return result;
191 })();
192 const current = Math.max(
193 0,
194 ratios.findIndex((_, index) => offsets[index + 1]! > scrollTop + 17),
195 );
196 const visible = ratios.flatMap((ratio, index) =>
197 offsets[index + 1]! >= scrollTop - viewport.height &&
198 offsets[index]! <= scrollTop + viewport.height * 2
199 ? [{ index, ratio }]
200 : [],
201 );
202 // Stable callbacks let page canvases survive scroll and find updates.
203 const [onSize] = useState(
204 () => (index: number, ratio: number) =>
205 setRatios((old) =>
206 old[index] === ratio ? old : old.map((value, i) => (i === index ? ratio : value)),
207 ),
208 );
209 const jumpToPage = useEffectEvent((index: number) => {
210 scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
211 });
212 const showPage = (index: number) => {
213 scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
214 };
215 const changeZoom = (value: number | null) => {
216 zoomAnchor.current = {
217 page: current,
218 offset: (scroll.current?.scrollTop ?? 0) - (offsets[current]! - 16),
219 width,
220 };
221 setZoom(value);
222 };
223 // oxlint-disable-next-line t3code/react-effect-budget -- Restore the DOM scroll anchor after the new zoom width has committed to page layout.
224 useLayoutEffect(() => {
225 const anchor = zoomAnchor.current;
226 zoomAnchor.current = null;
227 if (!anchor || anchor.width === width) return;
228 scroll.current?.scrollTo({
229 top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
230 });
231 });
232 // oxlint-disable-next-line t3code/react-effect-budget -- Scroll to the first asynchronous search result after its measured page offsets have committed.
233 useLayoutEffect(() => {
234 if (matches.length) jumpToPage(matches[0]!);
235 }, [matches]);
236 // oxlint-disable-next-line t3code/react-effect-budget -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.
237 useEffect(() => {
238 if (!pdf || !query.trim()) {
239 // oxlint-disable-next-line react/set-state-in-effect -- A blank query cancels the previous search.
240 setFinding(false);
241 return;
242 }
243 let cancelled = false;
244 const timer = setTimeout(() => {
245 setFinding(true);
246 setFindError(null);
247 setMatches([]);
248 setMatch(0);
249 void (async () => {
250 const found: number[] = [];
251 const sizes: number[] = [];
252 let size = 0;
253 for (let index = 0; index < pdf.numPages; index++) {
254 if (cancelled) return;
255 const page = await pdf.getPage(index + 1);
256 const pageSize = page.getViewport({ scale: 1 });
257 sizes.push(pageSize.height / pageSize.width);
258 const content = await page.getTextContent();
259 const text = content.items
260 .map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))
261 .join("");
262 size += text.length;
263 if (size > MAX_FIND_TEXT)
264 throw new Error(
265 "This PDF has too much text to search. Save it to search in another app.",
266 );
267 if (text.toLowerCase().includes(query.toLowerCase())) found.push(index);
268 }
269 if (cancelled) return;
270 setRatios(sizes);
271 setMatches(found);
272 })()
273 .catch((cause: unknown) => {
274 if (!cancelled)
275 setFindError(cause instanceof Error ? cause.message : "Could not search this PDF.");
276 })
277 .finally(() => {
278 if (!cancelled) setFinding(false);
279 });
280 }, 250);
281 return () => {
282 cancelled = true;
283 clearTimeout(timer);
284 };
285 }, [pdf, query]);
286 return (
287 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
288 <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">
289 <span className="mr-auto px-1 tabular-nums" aria-live="polite">
290 {pdf ? `${current + 1} / ${pdf.numPages} pages` : "PDF"}
291 </span>
292 <FileSurfaceAction
293 label="Previous page"
294 disabled={!pdf || current === 0}
295 onPress={() => showPage(current - 1)}
296 >
297 <ChevronUpIcon className="size-3.5" />
298 </FileSurfaceAction>
299 <FileSurfaceAction
300 label="Next page"
301 disabled={!pdf || current + 1 >= pdf.numPages}
302 onPress={() => showPage(current + 1)}
303 >
304 <ChevronDownIcon className="size-3.5" />
305 </FileSurfaceAction>
306 <FileSurfaceAction
307 label="Zoom out"
308 disabled={scale <= 0.25}
309 onPress={() => changeZoom(Math.max(0.25, scale - 0.25))}
310 >
311 <MinusIcon className="size-3.5" />
312 </FileSurfaceAction>
313 <span className="min-w-14 text-center tabular-nums">
314 {zoom === null ? "Fit width" : `${Math.round(scale * 100)}%`}
315 </span>
316 <FileSurfaceAction
317 label="Zoom in"
318 disabled={scale >= 3}
319 onPress={() => changeZoom(Math.min(3, scale + 0.25))}
320 >
321 <PlusIcon className="size-3.5" />
322 </FileSurfaceAction>
323 <FileSurfaceAction
324 label="Fit width"
325 onPress={() => {
326 changeZoom(null);
327 scroll.current?.scrollTo({ left: 0 });
328 }}
329 >
330 <ScanIcon className="size-3.5" />
331 </FileSurfaceAction>
332 <div className="w-28">
333 <Input
334 ref={find}
335 size="compact"
336 type="search"
337 aria-label="Find in PDF"
338 placeholder="Find in PDF"
339 value={query}
340 onChange={(event) => {
341 setQuery(event.target.value);
342 setMatches([]);
343 setFindError(null);
344 }}
345 />
346 </div>
347 {query ? (
348 <>
349 <span role="status">
350 {finding
351 ? "Searching…"
352 : (findError ?? `${matches.length ? match + 1 : 0}/${matches.length}`)}
353 </span>
354 <FileSurfaceAction
355 label="Next matching page"
356 disabled={!matches.length}
357 onPress={() => {
358 const next = (match + 1) % matches.length;
359 setMatch(next);
360 showPage(matches[next]!);
361 }}
362 >
363 <ChevronDownIcon className="size-3.5" />
364 </FileSurfaceAction>
365 </>
366 ) : null}
367 </div>
368 <div
369 ref={scroll}
370 role="region"
371 aria-label={props.title}
372 tabIndex={0}
373 className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto bg-muted/40"
374 onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
375 onKeyDown={(event) => {
376 if ((event.ctrlKey || event.metaKey) && event.key === "f") {
377 event.preventDefault();
378 event.stopPropagation();
379 find.current?.focus();
380 }
381 }}
382 >
383 {error ? (
384 <FileSurfaceFailure
385 message={error}
386 onRetry={() => {
387 setError(null);
388 setPdf(null);
389 setRevision((value) => value + 1);
390 }}
391 />
392 ) : !pdf ? (
393 <FileSurfaceLoading />
394 ) : (
395 <div
396 className="relative"
397 style={{
398 height: `max(${offsets.at(-1) ?? 0}px, calc(100% + ${(offsets.at(-2) ?? 16) - 16}px))`,
399 minWidth: width + 32,
400 }}
401 >
402 {visible.map(({ index, ratio }) => (
403 <div
404 key={index}
405 className="absolute bg-white shadow-sm"
406 style={
407 {
408 top: offsets[index],
409 left: Math.max(16, (viewport.width - width) / 2),
410 width,
411 height: width * ratio,
412 "--total-scale-factor": 1,
413 } as CSSProperties
414 }
415 >
416 <PdfPage
417 document={pdf}
418 index={index}
419 width={width}
420 query={query}
421 onSize={onSize}
422 onError={setError}
423 />
424 </div>
425 ))}
426 </div>
427 )}
428 </div>
429 </div>
430 );