@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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