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

PdfViewer.tsx

697 lines26.2 KB

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