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