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