Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import {
3 useEffect,
4 useEffectEvent,
5 useLayoutEffect,
6 useRef,
7 useState,
8 type CSSProperties,
9 type MouseEvent,
10 type ReactNode,
11} from "react";
12import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist";
13import { msg, useGT } from "gt-react";
14import { m } from "~/i18n/messages";
15import { ChevronDownIcon, ChevronUpIcon, MinusIcon, PlusIcon, ScanIcon } from "lucide-react";
16import { Input } from "~/components/ui/input";
17import { observeResize } from "~/lib/observeResize";
18import { FileSurfaceAction, FileSurfaceFailure, FileSurfaceLoading } from "./fileSurfaceChrome";
19import { readBoundedDocument } from "./readBoundedDocument";
20import { previewErrorText } from "./previewFailureMessages";
21import { openPdf } from "./pdfDocument";
22import {
23 currentPdfPage,
24 pdfFindIncludes,
25 pdfFindMatchRuns,
26 pdfPageOffsets,
27 pdfPageScrollTop,
28 pdfPageText,
29 pdfPageWidth,
30 pdfRestoredScrollTop,
31 PDF_MAX_ZOOM,
32 PDF_MIN_ZOOM,
33 stepPdfZoom,
34 visiblePdfPages,
35} from "./pdfLayout";
36import "./pdfViewer.css";
37
38const MAX_PAGES = 2000;
39const MAX_FIND_TEXT = 4 * 1024 * 1024;
40
41const MAX_POSITIONS = 50;
42type PdfPosition = PdfViewState & { width: number; ratios: readonly number[] };
43// Thread switches unmount the preview; retain only the most recent documents.
44const positions = new Map<string, PdfPosition>();
45
46type PdfLink = { box: readonly [number, number, number, number] } & (
47 | { url: string }
48 | { page: number }
49);
50
51// Resolves a link annotation's destination, named or explicit, to a page index.
52async function pdfLinkPage(pdf: PDFDocumentProxy, dest: unknown): Promise<number | null> {
53 const explicit: unknown = typeof dest === "string" ? await pdf.getDestination(dest) : dest;
54 if (!Array.isArray(explicit)) return null;
55 const [ref] = explicit as unknown[];
56 if (Number.isInteger(ref)) return ref as number;
57 if (typeof ref !== "object" || ref === null) return null;
58 return pdf.getPageIndex(ref as Parameters<PDFDocumentProxy["getPageIndex"]>[0]);
59}
60
61export type PdfViewState = {
62 page: number;
63 offset: number;
64 zoom: number | null;
65 left: number;
66};
67
68function PdfPage(props: {
69 document: PDFDocumentProxy;
70 index: number;
71 width: number;
72 query: string;
73 onSize: (index: number, ratio: number) => void;
74 onError: (error: string) => void;
75 onPageLink: (index: number) => void;
76 onOpenLink: ((url: string, event: MouseEvent) => void) | undefined;
77}) {
78 const gt = useGT();
79 const [links, setLinks] = useState<readonly PdfLink[]>([]);
80 const canvas = useRef<HTMLCanvasElement>(null);
81 const text = useRef<HTMLDivElement>(null);
82 const painted = useRef<PDFDocumentProxy>(null);
83 const { document: pdf, index, width, onSize, onError } = props;
84 // 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.
85 useEffect(() => {
86 let cancelled = false;
87 let paint: ReturnType<Awaited<ReturnType<PDFDocumentProxy["getPage"]>>["render"]> | undefined;
88 let layer: TextLayer | undefined;
89 let loadedPage: Awaited<ReturnType<PDFDocumentProxy["getPage"]>> | undefined;
90 let timer: ReturnType<typeof setTimeout> | undefined;
91 void (async () => {
92 // A drag changes the width every frame. CSS scales the painted page until the width settles.
93 if (painted.current === pdf)
94 await new Promise((resolve) => (timer = setTimeout(resolve, 150)));
95 const page = await pdf.getPage(index + 1);
96 loadedPage = page;
97 if (cancelled || !canvas.current || !text.current) {
98 page.cleanup();
99 return;
100 }
101 const natural = page.getViewport({ scale: 1 });
102 onSize(index, natural.height / natural.width);
103 const viewport = page.getViewport({ scale: width / natural.width });
104 const ratio = Math.min(
105 2,
106 window.devicePixelRatio || 1,
107 Math.sqrt((8 * 1024 * 1024) / (viewport.width * viewport.height)),
108 );
109 // Resizing a canvas blanks it, so the page paints off screen and replaces the old one whole.
110 const buffer = document.createElement("canvas");
111 buffer.width = Math.ceil(viewport.width * ratio);
112 buffer.height = Math.ceil(viewport.height * ratio);
113 paint = page.render({
114 canvas: buffer,
115 viewport,
116 transform: [ratio, 0, 0, ratio, 0, 0],
117 background: "white",
118 });
119 text.current.replaceChildren();
120 text.current.style.setProperty("--total-scale-factor", String(viewport.scale));
121 layer = new TextLayer({
122 container: text.current,
123 viewport,
124 textContentSource: page.streamTextContent(),
125 });
126 const shown = paint.promise.then(() => {
127 if (cancelled || !canvas.current) return;
128 canvas.current.width = buffer.width;
129 canvas.current.height = buffer.height;
130 canvas.current.getContext("2d", { alpha: false })?.drawImage(buffer, 0, 0);
131 buffer.width = 0;
132 painted.current = pdf;
133 });
134 const linked = page.getAnnotations({ intent: "display" }).then(async (annotations) => {
135 const found: PdfLink[] = [];
136 for (const annotation of annotations) {
137 if (annotation.subtype !== "Link") continue;
138 const [x1, y1] = viewport.convertToViewportPoint(annotation.rect[0], annotation.rect[1]);
139 const [x2, y2] = viewport.convertToViewportPoint(annotation.rect[2], annotation.rect[3]);
140 const box = [
141 Math.min(x1, x2) / viewport.width,
142 Math.min(y1, y2) / viewport.height,
143 Math.abs(x2 - x1) / viewport.width,
144 Math.abs(y2 - y1) / viewport.height,
145 ] as const;
146 if (typeof annotation.url === "string" && /^https?:\/\//i.test(annotation.url)) {
147 found.push({ box, url: annotation.url });
148 continue;
149 }
150 const target = await pdfLinkPage(pdf, annotation.dest).catch(() => null);
151 if (target !== null && target >= 0 && target < pdf.numPages)
152 found.push({ box, page: target });
153 }
154 if (!cancelled) setLinks(found);
155 });
156 // A page whose annotations cannot be read still renders, without links.
157 const linkedOrNone = linked.catch(() => undefined);
158 await Promise.all([shown, layer.render(), linkedOrNone]);
159 })().catch((cause: unknown) => {
160 if (!cancelled)
161 onError(thrownErrorMessage(cause, m) ?? m(msg("This PDF page could not render.")));
162 });
163 return () => {
164 cancelled = true;
165 clearTimeout(timer);
166 paint?.cancel();
167 layer?.cancel();
168 // Release operator lists when virtual pages leave the viewport.
169 void Promise.allSettled([paint?.promise]).then(() => loadedPage?.cleanup());
170 };
171 }, [pdf, index, width, onSize, onError]);
172 // 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.
173 useEffect(() => {
174 const node = text.current;
175 if (!node) return;
176 const mark = () => {
177 const elements = Array.from(node.querySelectorAll('span[role="presentation"], br'));
178 const hits = pdfFindMatchRuns(
179 elements.map((element) => (element.tagName === "BR" ? "\n" : (element.textContent ?? ""))),
180 props.query,
181 );
182 elements.forEach((element, index) => element.classList.toggle("pdf-find-match", hits[index]));
183 };
184 mark();
185 const observer = new MutationObserver(mark);
186 observer.observe(node, { childList: true, subtree: true });
187 return () => observer.disconnect();
188 }, [props.query]);
189 return (
190 <>
191 <canvas
192 ref={canvas}
193 aria-label={gt("Page {number}", { number: String(index + 1) })}
194 className="block h-full w-full"
195 />
196 <div ref={text} data-pdf-text-layer />
197 {links.length ? (
198 <div className="pointer-events-none absolute inset-0">
199 {links.map((link) => {
200 const [left, top, width, height] = link.box;
201 const key = `${link.box.join()}:${"url" in link ? link.url : link.page}`;
202 const style = {
203 left: `${left * 100}%`,
204 top: `${top * 100}%`,
205 width: `${width * 100}%`,
206 height: `${height * 100}%`,
207 };
208 return "url" in link ? (
209 <a
210 key={key}
211 href={link.url}
212 target="_blank"
213 rel="noopener noreferrer"
214 aria-label={link.url}
215 className="pointer-events-auto absolute"
216 style={style}
217 onClick={(event) => {
218 if (!props.onOpenLink) return;
219 event.preventDefault();
220 props.onOpenLink(link.url, event);
221 }}
222 />
223 ) : (
224 <a
225 key={key}
226 href={`#page=${link.page + 1}`}
227 aria-label={gt("Page {number}", { number: String(link.page + 1) })}
228 className="pointer-events-auto absolute"
229 style={style}
230 onClick={(event) => {
231 event.preventDefault();
232 props.onPageLink(link.page);
233 }}
234 />
235 );
236 })}
237 </div>
238 ) : null}
239 </>
240 );
241}
242
243export default function PdfViewer(props: {
244 src: string;
245 title: string;
246 positionKey?: string;
247 initialView?: PdfViewState;
248 onViewChange?: (view: PdfViewState) => void;
249 onOpenLink?: (url: string, event: MouseEvent) => void;
250 actions?: ReactNode;
251}) {
252 const gt = useGT();
253 const [savedPosition] = useState(() =>
254 props.positionKey === undefined ? undefined : positions.get(props.positionKey),
255 );
256 const [initialView] = useState<PdfViewState>(
257 () => savedPosition ?? props.initialView ?? { page: 0, offset: 0, zoom: null, left: 0 },
258 );
259 const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
260 const [error, setError] = useState<string | null>(null);
261 const [revision, setRevision] = useState(0);
262 const [ratios, setRatios] = useState<readonly number[]>([]);
263 const [zoom, setZoom] = useState(initialView.zoom);
264 const [pageWidth, setPageWidth] = useState(612);
265 const [viewport, setViewport] = useState({ width: 600, height: 800 });
266 const [scrollTop, setScrollTop] = useState(0);
267 const [query, setQuery] = useState("");
268 const [matches, setMatches] = useState<number[]>([]);
269 const [finding, setFinding] = useState(false);
270 const [findError, setFindError] = useState<string | null>(null);
271 const [match, setMatch] = useState(0);
272 const scroll = useRef<HTMLDivElement>(null);
273 const find = useRef<HTMLInputElement>(null);
274 const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);
275 const initialPage = initialView.page;
276 // 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.
277 useEffect(() => {
278 const controller = new AbortController();
279 let disposed = false;
280 let task: ReturnType<typeof openPdf> | undefined;
281 const timeout = setTimeout(() => {
282 setError(m(msg("This PDF took too long to load. Try again.")));
283 controller.abort();
284 void task?.destroy();
285 }, 30_000);
286 void readBoundedDocument(
287 props.src,
288 controller.signal,
289 50 * 1024 * 1024,
290 revision > 0 ? "reload" : "default",
291 )
292 .then(async (bytes) => {
293 controller.signal.throwIfAborted();
294 task = openPdf(bytes);
295 const document = await task.promise;
296 if (document.numPages > MAX_PAGES)
297 throw new Error(
298 m(msg("Preview limited to 2,000 pages. Save this PDF to read it in full.")),
299 );
300 const first = (await document.getPage(1)).getViewport({ scale: 1 });
301 const sizes = await Promise.all(
302 Array.from({ length: Math.min(initialPage + 1, document.numPages) }, async (_, index) => {
303 const size = (await document.getPage(index + 1)).getViewport({ scale: 1 });
304 return size.height / size.width;
305 }),
306 );
307 if (controller.signal.aborted) return;
308 setPageWidth(first.width);
309 setRatios(
310 savedPosition?.ratios.length === document.numPages
311 ? savedPosition.ratios
312 : Array.from(
313 { length: document.numPages },
314 (_, index) => sizes[index] ?? first.height / first.width,
315 ),
316 );
317 setPdf(document);
318 })
319 .catch((cause: unknown) => {
320 if (!disposed && !controller.signal.aborted)
321 setError(previewErrorText(cause, m(msg("Unable to open PDF."))));
322 })
323 .finally(() => clearTimeout(timeout));
324 return () => {
325 disposed = true;
326 controller.abort();
327 clearTimeout(timeout);
328 void task?.destroy();
329 };
330 }, [props.src, revision, initialPage, savedPosition]);
331 // 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.
332 useLayoutEffect(() => {
333 const node = scroll.current;
334 if (!node) return;
335 const update = () => setViewport({ width: node.clientWidth, height: node.clientHeight });
336 update();
337 return observeResize(node, update);
338 }, []);
339 const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom);
340 const offsets = pdfPageOffsets(ratios, width);
341 const current = currentPdfPage(offsets, ratios.length, scrollTop);
342 const visible = visiblePdfPages(ratios, offsets, scrollTop, viewport.height);
343 // Stable callbacks let page canvases survive scroll and find updates.
344 const [onSize] = useState(
345 () => (index: number, ratio: number) =>
346 setRatios((old) =>
347 old[index] === ratio ? old : old.map((value, i) => (i === index ? ratio : value)),
348 ),
349 );
350 const jumpToPage = useEffectEvent((index: number) => {
351 scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
352 });
353 const saveView = (node: HTMLDivElement, notify = true) => {
354 const page = currentPdfPage(offsets, ratios.length, node.scrollTop);
355 if (!pdf) return;
356 const view = {
357 page,
358 offset: Math.max(0, node.scrollTop - (offsets[page]! - 16)),
359 zoom,
360 left: node.scrollLeft,
361 };
362 if (notify) props.onViewChange?.(view);
363 if (props.positionKey !== undefined) {
364 positions.delete(props.positionKey);
365 positions.set(props.positionKey, { ...view, width, ratios });
366 const oldest = positions.keys().next();
367 if (positions.size > MAX_POSITIONS && !oldest.done) positions.delete(oldest.value);
368 }
369 };
370 const restoreView = useEffectEvent(() => {
371 const node = scroll.current;
372 if (!pdf || !node) return;
373 node.scrollTo({
374 top: pdfRestoredScrollTop(ratios, width, initialView, savedPosition?.width),
375 left: initialView.left,
376 });
377 setScrollTop(node.scrollTop);
378 saveView(node);
379 });
380 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the saved PDF scroll position after the loaded document's page layout commits.
381 useLayoutEffect(() => {
382 if (pdf) restoreView();
383 }, [pdf]);
384 const showPage = (index: number) => {
385 scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
386 };
387 const changeZoom = (value: number | null) => {
388 zoomAnchor.current = {
389 page: current,
390 offset: (scroll.current?.scrollTop ?? 0) - (offsets[current]! - 16),
391 width,
392 };
393 setZoom(value);
394 };
395 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the DOM scroll anchor after the new zoom width has committed to page layout.
396 useLayoutEffect(() => {
397 const anchor = zoomAnchor.current;
398 zoomAnchor.current = null;
399 const node = scroll.current;
400 if (!node || !pdf) return;
401 if (anchor && anchor.width !== width) {
402 node.scrollTo({
403 top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
404 });
405 }
406 saveView(node, anchor !== null);
407 });
408 const firstMatch = matches[0];
409 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll to the first asynchronous search result after its measured page offsets have committed.
410 useLayoutEffect(() => {
411 if (firstMatch !== undefined) jumpToPage(firstMatch);
412 }, [firstMatch]);
413 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.
414 useEffect(() => {
415 if (!pdf || !query.trim()) {
416 // oxlint-disable-next-line react/set-state-in-effect -- A blank query cancels the previous search.
417 setFinding(false);
418 return;
419 }
420 let cancelled = false;
421 const timer = setTimeout(() => {
422 setFinding(true);
423 setFindError(null);
424 setMatches([]);
425 setMatch(0);
426 void (async () => {
427 const found: number[] = [];
428 const sizes: number[] = [];
429 let size = 0;
430 for (let index = 0; index < pdf.numPages; index++) {
431 const page = await pdf.getPage(index + 1);
432 const pageSize = page.getViewport({ scale: 1 });
433 sizes.push(pageSize.height / pageSize.width);
434 const content = await page.getTextContent();
435 if (cancelled) return;
436 const text = pdfPageText(content.items);
437 size += text.length;
438 if (size > MAX_FIND_TEXT)
439 throw new Error(
440 m(msg("This PDF has too much text to search. Save it to search in another app.")),
441 );
442 if (!pdfFindIncludes(text, query)) continue;
443 found.push(index);
444 if (found.length > 1) continue;
445 // Pages up to the first hit are measured, so its jump lands before the scan finishes.
446 setRatios((old) => [...sizes, ...old.slice(sizes.length)]);
447 setMatches([index]);
448 }
449 if (cancelled) return;
450 setRatios(sizes);
451 setMatches(found);
452 })()
453 .catch((cause: unknown) => {
454 if (!cancelled)
455 setFindError(thrownErrorMessage(cause, m) ?? m(msg("Could not search this PDF.")));
456 })
457 .finally(() => {
458 if (!cancelled) setFinding(false);
459 });
460 }, 250);
461 return () => {
462 cancelled = true;
463 clearTimeout(timer);
464 };
465 }, [pdf, query]);
466 return (
467 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
468 <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">
469 <span className="mr-auto px-1 tabular-nums" aria-live="polite">
470 {pdf
471 ? gt(
472 "{count, plural, one {{current} / {count} page} other {{current} / {count} pages}}",
473 {
474 count: pdf.numPages,
475 current: String(current + 1),
476 },
477 )
478 : "PDF"}
479 </span>
480 <FileSurfaceAction
481 label={gt("Previous page")}
482 disabled={!pdf || current === 0}
483 onPress={() => showPage(current - 1)}
484 >
485 <ChevronUpIcon className="size-3.5" />
486 </FileSurfaceAction>
487 <FileSurfaceAction
488 label={gt("Next page")}
489 disabled={!pdf || current + 1 >= pdf.numPages}
490 onPress={() => showPage(current + 1)}
491 >
492 <ChevronDownIcon className="size-3.5" />
493 </FileSurfaceAction>
494 <FileSurfaceAction
495 label={gt("Zoom out")}
496 disabled={scale <= PDF_MIN_ZOOM}
497 onPress={() => changeZoom(stepPdfZoom(scale, -1))}
498 >
499 <MinusIcon className="size-3.5" />
500 </FileSurfaceAction>
501 <span className="min-w-14 text-center tabular-nums">
502 {zoom === null ? gt("Fit width") : `${Math.round(scale * 100)}%`}
503 </span>
504 <FileSurfaceAction
505 label={gt("Zoom in")}
506 disabled={scale >= PDF_MAX_ZOOM}
507 onPress={() => changeZoom(stepPdfZoom(scale, 1))}
508 >
509 <PlusIcon className="size-3.5" />
510 </FileSurfaceAction>
511 <FileSurfaceAction
512 label={gt("Fit width")}
513 onPress={() => {
514 changeZoom(null);
515 scroll.current?.scrollTo({ left: 0 });
516 }}
517 >
518 <ScanIcon className="size-3.5" />
519 </FileSurfaceAction>
520 <div className="w-28">
521 <Input
522 ref={find}
523 size="compact"
524 type="search"
525 aria-label={gt("Find in PDF")}
526 placeholder={gt("Find in PDF")}
527 value={query}
528 onChange={(event) => {
529 setQuery(event.target.value);
530 setMatches([]);
531 setFindError(null);
532 }}
533 />
534 </div>
535 {query ? (
536 <>
537 <span role="status">
538 {finding
539 ? gt("Searching…")
540 : (findError ?? `${matches.length ? match + 1 : 0}/${matches.length}`)}
541 </span>
542 <FileSurfaceAction
543 label={gt("Next matching page")}
544 disabled={!matches.length}
545 onPress={() => {
546 const next = (match + 1) % matches.length;
547 setMatch(next);
548 showPage(matches[next]!);
549 }}
550 >
551 <ChevronDownIcon className="size-3.5" />
552 </FileSurfaceAction>
553 </>
554 ) : null}
555 {props.actions}
556 </div>
557 <div
558 ref={scroll}
559 role="region"
560 aria-label={props.title}
561 tabIndex={0}
562 className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto scrollbar-gutter-stable bg-muted/40"
563 onScroll={(event) => {
564 const top = event.currentTarget.scrollTop;
565 setScrollTop(top);
566 saveView(event.currentTarget);
567 }}
568 onKeyDown={(event) => {
569 if ((event.ctrlKey || event.metaKey) && event.key === "f") {
570 event.preventDefault();
571 event.stopPropagation();
572 find.current?.focus();
573 }
574 }}
575 >
576 {error ? (
577 <FileSurfaceFailure
578 message={error}
579 onRetry={() => {
580 setError(null);
581 setPdf(null);
582 setRevision((value) => value + 1);
583 }}
584 />
585 ) : !pdf ? (
586 <FileSurfaceLoading />
587 ) : (
588 <div
589 className="relative"
590 style={{
591 height: `max(${offsets.at(-1) ?? 0}px, calc(100% + ${(offsets.at(-2) ?? 16) - 16}px))`,
592 minWidth: width + 32,
593 }}
594 >
595 {visible.map(({ index, ratio }) => (
596 <div
597 key={index}
598 className="absolute bg-white shadow-sm"
599 style={
600 {
601 top: offsets[index],
602 left: Math.max(16, (viewport.width - width) / 2),
603 width,
604 height: width * ratio,
605 "--total-scale-factor": 1,
606 } as CSSProperties
607 }
608 >
609 <PdfPage
610 document={pdf}
611 index={index}
612 width={width}
613 query={query}
614 onSize={onSize}
615 onError={setError}
616 onPageLink={showPage}
617 onOpenLink={props.onOpenLink}
618 />
619 </div>
620 ))}
621 </div>
622 )}
623 </div>
624 </div>
625 );
626}