PdfView.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. import {
  2. forwardRef,
  3. useEffect,
  4. useImperativeHandle,
  5. useLayoutEffect,
  6. useRef,
  7. useState,
  8. } from "react";
  9. import * as pdfjs from "pdfjs-dist";
  10. import type { PDFDocumentProxy, PDFPageProxy } from "pdfjs-dist";
  11. import { parseLocator } from "#office/domain/anchor.ts";
  12. import { normalizeCjkCompat } from "#office/domain/cjk.ts";
  13. import { readBinary, readText } from "#ui/assets.ts";
  14. import {
  15. boxOf,
  16. countMatches,
  17. pointOn,
  18. findAllRanges,
  19. findTextRange,
  20. paintRanges,
  21. safeExternalUrl,
  22. scrollToElement,
  23. scrollToRange,
  24. selectionIn,
  25. trackTopmost,
  26. } from "#ui/dom.ts";
  27. import { canvasToPng } from "#ui/raster.ts";
  28. import {
  29. nextZoom,
  30. type FitMode,
  31. type RevealedTarget,
  32. type ViewerHandle,
  33. type ViewerProps,
  34. } from "#ui/viewers/types.ts";
  35. // pdf.js would fetch cMaps, fonts and wasm over the network; the sandbox has none, so read them
  36. // through the plugin's MCP resources instead.
  37. class AssetCMapFactory {
  38. constructor(private readonly options: { baseUrl: string | null; isCompressed: boolean }) {}
  39. async fetch({ name }: { name: string }) {
  40. return {
  41. cMapData: await readBinary(`${this.options.baseUrl}${name}.bcmap`),
  42. isCompressed: true,
  43. };
  44. }
  45. }
  46. class AssetBinaryFactory {
  47. constructor(private readonly options: { baseUrl: string | null }) {}
  48. async fetch({ filename }: { filename: string }) {
  49. return readBinary(`${this.options.baseUrl}${filename}`);
  50. }
  51. }
  52. let sharedWorker: Promise<pdfjs.PDFWorker> | undefined;
  53. /**
  54. * One pdf.js worker for the page's lifetime. Passed explicitly, so destroying a document (reload,
  55. * switching files) never tears down the worker the next document is about to use.
  56. */
  57. function worker(): Promise<pdfjs.PDFWorker> {
  58. return (sharedWorker ??= readText("pdf-worker.js").then((source) => {
  59. const url = URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
  60. return pdfjs.PDFWorker.create({ port: new Worker(url, { type: "module" }) });
  61. }));
  62. }
  63. type TextContent = Awaited<ReturnType<PDFPageProxy["getTextContent"]>>;
  64. /** Page text with CJK radicals mapped back to ideographs (see src/domain/cjk.ts). */
  65. async function pageTextContent(page: PDFPageProxy): Promise<TextContent> {
  66. const content = await page.getTextContent();
  67. return {
  68. ...content,
  69. items: content.items.map((item) =>
  70. "str" in item ? { ...item, str: normalizeCjkCompat(item.str) } : item,
  71. ),
  72. };
  73. }
  74. interface PageSlot {
  75. element: HTMLDivElement;
  76. /** Resolves when the canvas and text layer of the current scale are in place. */
  77. done?: Promise<void>;
  78. task?: { cancel(): void };
  79. textLayer?: HTMLDivElement;
  80. }
  81. /** Canvas padding and the gap between pages (CSS keeps these in step). */
  82. const PADDING = 16;
  83. /** pdf.js scale 1 is 72 dpi; "100%" means actual size at 96 CSS px per inch. */
  84. const CSS_UNITS = 96 / 72;
  85. interface Zoom {
  86. mode: FitMode | null;
  87. /** Percent of actual size when mode is null. */
  88. percent: number;
  89. }
  90. interface RevealItem {
  91. page: number;
  92. to: number;
  93. quote?: string;
  94. }
  95. export const PdfView = forwardRef<ViewerHandle, ViewerProps>(function PdfView(props, ref) {
  96. const scrollRef = useRef<HTMLDivElement>(null);
  97. const docRef = useRef<PDFDocumentProxy | null>(null);
  98. const slots = useRef<PageSlot[]>([]);
  99. const sizes = useRef<{ width: number; height: number }[]>([]);
  100. const [zoom, setZoom] = useState<Zoom>({ mode: "width", percent: 100 });
  101. const [box, setBox] = useState({ width: 0, height: 0 });
  102. const [loaded, setLoaded] = useState(0);
  103. const callbacks = useRef(props);
  104. callbacks.current = props;
  105. const glance = Boolean(props.glance);
  106. const scale = (() => {
  107. if (!loaded || !box.width || !sizes.current.length) return 0;
  108. const maxWidth = Math.max(...sizes.current.map((size) => size.width));
  109. const maxHeight = Math.max(...sizes.current.map((size) => size.height));
  110. const columns = glance && box.width >= 520 ? 2 : 1;
  111. const fitWidth = Math.min(4, (box.width - PADDING * (columns + 1)) / columns / maxWidth);
  112. if (zoom.mode === "width" || glance) return fitWidth;
  113. if (zoom.mode === "page") return Math.min(fitWidth, (box.height - PADDING * 2) / maxHeight);
  114. if (zoom.mode === "actual") return CSS_UNITS;
  115. return (zoom.percent / 100) * CSS_UNITS;
  116. })();
  117. const scaleRef = useRef(scale);
  118. const previousScale = useRef(0);
  119. scaleRef.current = scale;
  120. /** Point (in container coordinates) that should stay put across the next zoom change. */
  121. const zoomAnchor = useRef<{ x: number; y: number } | null>(null);
  122. const observer = useRef<IntersectionObserver | null>(null);
  123. /** Bumped whenever pages are resized; a render from an older generation must not land. */
  124. const generation = useRef(0);
  125. // Decorations that must survive re-rendering a page (zoom replaces the text layers).
  126. const revealItems = useRef<RevealItem[]>([]);
  127. const revealRanges = useRef(new Map<number, Range>());
  128. const find = useRef<{
  129. query: string;
  130. matches: { page: number; k: number }[];
  131. current: number;
  132. ranges: Map<number, Range[]>;
  133. } | null>(null);
  134. const pageTexts = useRef<Promise<string>[]>([]);
  135. // Load the document.
  136. useEffect(() => {
  137. let cancelled = false;
  138. let loadedDoc: PDFDocumentProxy | null = null;
  139. (async () => {
  140. const task = pdfjs.getDocument({
  141. worker: await worker(),
  142. data: new Uint8Array(props.bytes.slice(0)),
  143. cMapUrl: "pdfjs/cmaps/",
  144. cMapPacked: true,
  145. standardFontDataUrl: "pdfjs/standard_fonts/",
  146. wasmUrl: "pdfjs/wasm/",
  147. CMapReaderFactory: AssetCMapFactory,
  148. StandardFontDataFactory: AssetBinaryFactory,
  149. WasmFactory: AssetBinaryFactory,
  150. useWorkerFetch: false,
  151. isEvalSupported: false,
  152. enableXfa: false,
  153. });
  154. loadedDoc = await task.promise;
  155. if (cancelled) return void loadedDoc.destroy();
  156. docRef.current = loadedDoc;
  157. const pageSizes: { width: number; height: number }[] = [];
  158. const count = glance ? Math.min(4, loadedDoc.numPages) : loadedDoc.numPages;
  159. for (let n = 1; n <= count; n++) {
  160. const page = await loadedDoc.getPage(n);
  161. const viewport = page.getViewport({ scale: 1 });
  162. pageSizes.push({ width: viewport.width, height: viewport.height });
  163. }
  164. if (cancelled) return;
  165. sizes.current = pageSizes;
  166. const container = scrollRef.current!;
  167. container.replaceChildren();
  168. slots.current = pageSizes.map((_, i) => {
  169. const element = document.createElement("div");
  170. element.className = "pdf-page";
  171. element.dataset.at = `page:${i + 1}`;
  172. container.append(element);
  173. return { element };
  174. });
  175. setBox({ width: container.clientWidth, height: container.clientHeight });
  176. setLoaded((value) => value + 1);
  177. callbacks.current.onPage?.({ current: 1, count: loadedDoc.numPages });
  178. callbacks.current.onReady();
  179. })().catch((error) => !cancelled && callbacks.current.onError(error));
  180. return () => {
  181. cancelled = true;
  182. observer.current?.disconnect();
  183. void loadedDoc?.destroy();
  184. docRef.current = null;
  185. pageTexts.current = [];
  186. };
  187. }, [props.bytes, glance]);
  188. // Follow the pane size.
  189. useEffect(() => {
  190. const container = scrollRef.current!;
  191. const resize = new ResizeObserver(() =>
  192. setBox((previous) =>
  193. Math.abs(previous.width - container.clientWidth) > 1 ||
  194. Math.abs(previous.height - container.clientHeight) > 1
  195. ? { width: container.clientWidth, height: container.clientHeight }
  196. : previous,
  197. ),
  198. );
  199. resize.observe(container);
  200. return () => resize.disconnect();
  201. }, []);
  202. // Report the zoom the control shows.
  203. useEffect(() => {
  204. if (!scale) return;
  205. callbacks.current.onZoom?.({
  206. mode: zoom.mode,
  207. percent: Math.round((scale / CSS_UNITS) * 100),
  208. });
  209. }, [scale, zoom.mode]);
  210. // Size page placeholders, keep the anchor point in place, render what is visible.
  211. useLayoutEffect(() => {
  212. const doc = docRef.current;
  213. const container = scrollRef.current;
  214. if (!doc || !scale || !container) return;
  215. const before = previousScale.current;
  216. previousScale.current = scale;
  217. const anchor = zoomAnchor.current ?? {
  218. x: container.clientWidth / 2,
  219. y: container.clientHeight / 2,
  220. };
  221. zoomAnchor.current = null;
  222. const fraction = {
  223. x: container.scrollLeft + anchor.x,
  224. y: container.scrollTop + anchor.y,
  225. };
  226. observer.current?.disconnect();
  227. generation.current++;
  228. for (const [i, slot] of slots.current.entries()) {
  229. slot.task?.cancel();
  230. slot.done = undefined;
  231. slot.textLayer = undefined;
  232. slot.element.replaceChildren();
  233. slot.element.style.width = `${sizes.current[i].width * scale}px`;
  234. slot.element.style.height = `${sizes.current[i].height * scale}px`;
  235. }
  236. revealRanges.current.clear();
  237. find.current?.ranges.clear();
  238. paint();
  239. if (before && before !== scale) {
  240. const ratio = scale / before;
  241. container.scrollTo({
  242. left: Math.max(0, (fraction.x - PADDING) * ratio + PADDING - anchor.x),
  243. top: Math.max(0, (fraction.y - PADDING) * ratio + PADDING - anchor.y),
  244. });
  245. }
  246. observer.current = new IntersectionObserver(
  247. (entries) => {
  248. for (const entry of entries) {
  249. if (!entry.isIntersecting) continue;
  250. const index = slots.current.findIndex((slot) => slot.element === entry.target);
  251. if (index >= 0) void renderPage(index);
  252. }
  253. },
  254. { root: container, rootMargin: "600px 0px" },
  255. );
  256. for (const slot of slots.current) observer.current.observe(slot.element);
  257. }, [scale]);
  258. function renderPage(index: number): Promise<void> {
  259. const slot = slots.current[index];
  260. if (!slot) return Promise.resolve();
  261. return (slot.done ??= draw(index, slot));
  262. }
  263. async function draw(index: number, slot: PageSlot) {
  264. const doc = docRef.current;
  265. if (!doc) return;
  266. const currentScale = scaleRef.current;
  267. const mine = generation.current;
  268. const page = await doc.getPage(index + 1);
  269. // The pane was resized while the page loaded: a newer render owns this slot now.
  270. if (generation.current !== mine) return;
  271. const viewport = page.getViewport({ scale: currentScale });
  272. const ratio = window.devicePixelRatio || 1;
  273. const canvas = document.createElement("canvas");
  274. canvas.width = Math.floor(viewport.width * ratio);
  275. canvas.height = Math.floor(viewport.height * ratio);
  276. canvas.style.width = `${viewport.width}px`;
  277. canvas.style.height = `${viewport.height}px`;
  278. const textLayer = document.createElement("div");
  279. textLayer.className = "textLayer";
  280. const links = document.createElement("div");
  281. links.className = "pdf-links";
  282. slot.element.style.setProperty("--scale-factor", String(currentScale));
  283. slot.element.style.setProperty("--user-unit", "1");
  284. slot.element.style.setProperty("--total-scale-factor", String(currentScale));
  285. slot.element.replaceChildren(canvas, textLayer, links);
  286. const task = page.render({
  287. canvas,
  288. canvasContext: canvas.getContext("2d")!,
  289. viewport,
  290. transform: ratio !== 1 ? [ratio, 0, 0, ratio, 0, 0] : undefined,
  291. });
  292. slot.task = task;
  293. try {
  294. await task.promise;
  295. if (generation.current !== mine) return;
  296. // 文字层用归一后的文字:复制、选区引用、查找与 Agent 引文定位都要看到“文”而不是“⽂”。
  297. const content = await pageTextContent(page);
  298. if (generation.current !== mine) return;
  299. const text = new pdfjs.TextLayer({
  300. textContentSource: content,
  301. container: textLayer,
  302. viewport,
  303. });
  304. await text.render();
  305. if (generation.current !== mine || !textLayer.isConnected) return;
  306. slot.textLayer = textLayer;
  307. await addLinks(page, viewport, links);
  308. decorate(index + 1);
  309. } catch (error) {
  310. if ((error as Error)?.name !== "RenderingCancelledException")
  311. console.warn("pdf render", error);
  312. }
  313. }
  314. async function addLinks(
  315. page: PDFPageProxy,
  316. viewport: ReturnType<PDFPageProxy["getViewport"]>,
  317. layer: HTMLDivElement,
  318. ) {
  319. const annotations = await page.getAnnotations({ intent: "display" });
  320. for (const annotation of annotations) {
  321. if (annotation.subtype !== "Link") continue;
  322. const [x1, y1, x2, y2] = viewport.convertToViewportRectangle(annotation.rect);
  323. const link = document.createElement("a");
  324. link.className = "pdf-link";
  325. link.style.left = `${Math.min(x1, x2)}px`;
  326. link.style.top = `${Math.min(y1, y2)}px`;
  327. link.style.width = `${Math.abs(x2 - x1)}px`;
  328. link.style.height = `${Math.abs(y2 - y1)}px`;
  329. const url = safeExternalUrl(annotation.url ?? annotation.unsafeUrl);
  330. if (url) {
  331. link.title = url;
  332. link.addEventListener("click", (event) => {
  333. event.preventDefault();
  334. event.stopPropagation();
  335. callbacks.current.onLink(url);
  336. });
  337. } else if (annotation.dest) {
  338. link.addEventListener("click", async (event) => {
  339. event.preventDefault();
  340. event.stopPropagation();
  341. const target = await resolveDest(annotation.dest);
  342. if (target) scrollToPage(target);
  343. });
  344. } else continue;
  345. layer.append(link);
  346. }
  347. }
  348. async function resolveDest(dest: unknown): Promise<number | null> {
  349. const doc = docRef.current;
  350. if (!doc) return null;
  351. const explicit = typeof dest === "string" ? await doc.getDestination(dest) : dest;
  352. const target = Array.isArray(explicit) ? explicit[0] : null;
  353. if (target && typeof target === "object") return (await doc.getPageIndex(target)) + 1;
  354. return typeof target === "number" ? target + 1 : null;
  355. }
  356. function scrollToPage(page: number) {
  357. const slot = slots.current[page - 1];
  358. if (slot) scrollToElement(slot.element, "start");
  359. }
  360. /** Page `n` with its text layer for the current scale (null if it does not exist). */
  361. async function rendered(n: number): Promise<PageSlot | null> {
  362. const slot = slots.current[n - 1];
  363. if (!slot) return null;
  364. // A resize while waiting starts a fresh render; wait for that one too.
  365. for (let attempt = 0; attempt < 5; attempt++) {
  366. await renderPage(n - 1);
  367. if (slot.textLayer?.isConnected) return slot;
  368. }
  369. return null;
  370. }
  371. /** Re-attach reveal and find highlights to a freshly rendered page. */
  372. function decorate(page: number) {
  373. const slot = slots.current[page - 1];
  374. if (!slot?.textLayer) return;
  375. revealItems.current.forEach((item, i) => {
  376. if (!item.quote || item.page !== page) return;
  377. // Always re-find on the live layer: a range on a replaced layer would paint nothing.
  378. const current = revealRanges.current.get(i);
  379. if (current && slot.textLayer!.contains(current.startContainer)) return;
  380. const range = findTextRange(slot.textLayer!, item.quote);
  381. if (range) revealRanges.current.set(i, range);
  382. else revealRanges.current.delete(i);
  383. });
  384. if (find.current?.query)
  385. find.current.ranges.set(page, findAllRanges(slot.textLayer, find.current.query));
  386. paint();
  387. }
  388. function currentFindRange(): Range | null {
  389. const state = find.current;
  390. const match = state?.matches[state.current];
  391. if (!state || !match) return null;
  392. const ranges = state.ranges.get(match.page) ?? [];
  393. return ranges[Math.min(match.k, ranges.length - 1)] ?? null;
  394. }
  395. function paint() {
  396. paintRanges("office-reveal", [...revealRanges.current.values()]);
  397. const current = currentFindRange();
  398. paintRanges(
  399. "office-find",
  400. [...(find.current?.ranges.values() ?? [])].flat().filter((range) => range !== current),
  401. );
  402. paintRanges("office-find-current", current ? [current] : []);
  403. }
  404. function pageText(n: number): Promise<string> {
  405. const doc = docRef.current;
  406. if (!doc) return Promise.resolve("");
  407. return (pageTexts.current[n - 1] ??= doc
  408. .getPage(n)
  409. .then(pageTextContent)
  410. .then((content) => content.items.map((item) => ("str" in item ? item.str : "")).join(" "))
  411. .catch(() => ""));
  412. }
  413. // Visible page tracking.
  414. useEffect(() => {
  415. const container = scrollRef.current!;
  416. return trackTopmost(
  417. container,
  418. () => slots.current.map((slot) => slot.element),
  419. (element) => element.dataset.at ?? null,
  420. (at) => {
  421. callbacks.current.onLocation(at);
  422. callbacks.current.onPage?.({
  423. current: Number(at.slice(5)),
  424. count: docRef.current?.numPages ?? slots.current.length,
  425. });
  426. },
  427. 1 / 3,
  428. );
  429. }, []);
  430. // ⌘/Ctrl + wheel zooms around the pointer, like ZCode's PDF preview.
  431. useEffect(() => {
  432. const container = scrollRef.current!;
  433. let accumulated = 0;
  434. const onWheel = (event: WheelEvent) => {
  435. if (!event.ctrlKey && !event.metaKey) return;
  436. event.preventDefault();
  437. accumulated += event.deltaY;
  438. if (Math.abs(accumulated) < 40) return;
  439. const direction = accumulated < 0 ? 1 : -1;
  440. accumulated = 0;
  441. const rect = container.getBoundingClientRect();
  442. zoomAnchor.current = { x: event.clientX - rect.left, y: event.clientY - rect.top };
  443. stepZoom(direction);
  444. };
  445. container.addEventListener("wheel", onWheel, { passive: false });
  446. return () => container.removeEventListener("wheel", onWheel);
  447. }, []);
  448. function stepZoom(direction: 1 | -1) {
  449. const percent = Math.round((scaleRef.current / CSS_UNITS) * 100);
  450. setZoom({ mode: null, percent: nextZoom(percent, direction) });
  451. }
  452. // Selection: text selection inside pages, or a click on a page outside its text.
  453. useEffect(() => {
  454. const container = scrollRef.current!;
  455. const pageOf = (node: Node | null) =>
  456. (node instanceof Element ? node : node?.parentElement)?.closest<HTMLElement>(".pdf-page")
  457. ?.dataset.at;
  458. const clearPage = () =>
  459. container
  460. .querySelectorAll(".pdf-page.selected")
  461. .forEach((element) => element.classList.remove("selected"));
  462. const report = (event: Event) => {
  463. const selected = selectionIn(container);
  464. if (selected) {
  465. const start = pageOf(selected.range.startContainer);
  466. const end = pageOf(selected.range.endContainer);
  467. if (!start) return;
  468. clearPage();
  469. const a = Number(start.slice(5));
  470. const b = end ? Number(end.slice(5)) : a;
  471. const range = selected.range.cloneRange();
  472. callbacks.current.onSelect(
  473. { at: b > a ? `page:${a}-${b}` : start, text: selected.text },
  474. { text: true, locate: () => boxOf(range), user: true },
  475. );
  476. return;
  477. }
  478. if (event.type !== "mouseup") return;
  479. // A click on one of the agent's marks brings its note back instead of selecting.
  480. const { clientX, clientY } = event as MouseEvent;
  481. for (const [i, range] of revealRanges.current)
  482. if (pointOn(range, clientX, clientY) && callbacks.current.onRevealHit?.(i)) {
  483. clearPage();
  484. callbacks.current.onSelect(null);
  485. return;
  486. }
  487. const target = event.target as Element;
  488. if (target.closest(".pdf-link")) return;
  489. const page = target.closest<HTMLElement>(".pdf-page");
  490. clearPage();
  491. // A click on text (no drag) or outside the pages clears the selection.
  492. if (!page?.dataset.at || target.closest(".textLayer span")) {
  493. callbacks.current.onSelect(null);
  494. return;
  495. }
  496. page.classList.add("selected");
  497. callbacks.current.onSelect(
  498. { at: page.dataset.at, text: "" },
  499. { text: false, locate: () => boxOf(page), user: true },
  500. );
  501. };
  502. const onUp = (event: Event) => setTimeout(() => report(event), 0);
  503. container.addEventListener("mouseup", onUp);
  504. container.addEventListener("keyup", onUp);
  505. return () => {
  506. container.removeEventListener("mouseup", onUp);
  507. container.removeEventListener("keyup", onUp);
  508. };
  509. }, []);
  510. useImperativeHandle(
  511. ref,
  512. (): ViewerHandle => ({
  513. async reveal(targets) {
  514. this.clearReveal();
  515. const items: RevealItem[] = [];
  516. for (const target of targets) {
  517. const locator = parseLocator("pdf", target.at);
  518. if (locator.kind !== "pdf" || !slots.current[locator.from - 1]) continue;
  519. items.push({
  520. page: locator.from,
  521. to: locator.to,
  522. ...(target.quote ? { quote: target.quote } : {}),
  523. });
  524. }
  525. revealItems.current = items;
  526. // Quotes may sit on any page of a range: find the page that has it.
  527. for (const [i, item] of items.entries()) {
  528. if (!item.quote) {
  529. for (let n = item.page; n <= item.to; n++)
  530. slots.current[n - 1]?.element.classList.add("revealed");
  531. continue;
  532. }
  533. for (let n = item.page; n <= item.to; n++) {
  534. const slot = await rendered(n);
  535. const range = slot?.textLayer && findTextRange(slot.textLayer, item.quote);
  536. if (range) {
  537. item.page = n;
  538. revealRanges.current.set(i, range);
  539. break;
  540. }
  541. }
  542. }
  543. paint();
  544. const results: RevealedTarget[] = items.map((item, i) => ({
  545. at:
  546. item.to > item.page && !item.quote
  547. ? `page:${item.page}-${item.to}`
  548. : `page:${item.page}`,
  549. locate: () =>
  550. boxOf(revealRanges.current.get(i)) ?? boxOf(slots.current[item.page - 1]?.element),
  551. scrollTo: () => {
  552. const range = revealRanges.current.get(i);
  553. if (range?.startContainer.isConnected) scrollToRange(range, "upper");
  554. else if (item.quote)
  555. void rendered(item.page).then(() => {
  556. decorate(item.page);
  557. const again = revealRanges.current.get(i);
  558. if (again) scrollToRange(again, "upper");
  559. else scrollToPage(item.page);
  560. });
  561. else scrollToPage(item.page);
  562. },
  563. }));
  564. results[0]?.scrollTo();
  565. return results;
  566. },
  567. goTo(at) {
  568. const locator = parseLocator("pdf", at);
  569. if (locator.kind === "pdf") scrollToPage(locator.from);
  570. },
  571. clearReveal() {
  572. revealItems.current = [];
  573. revealRanges.current.clear();
  574. scrollRef.current
  575. ?.querySelectorAll(".pdf-page.revealed")
  576. .forEach((element) => element.classList.remove("revealed"));
  577. paint();
  578. },
  579. async capture(at, maxWidth) {
  580. const doc = docRef.current;
  581. if (!doc) throw new Error("The PDF is still loading.");
  582. const page = at ? parseLocator("pdf", at) : null;
  583. const number =
  584. page?.kind === "pdf"
  585. ? page.from
  586. : Number(
  587. (
  588. slots.current.find(
  589. (slot) =>
  590. slot.element.getBoundingClientRect().bottom >
  591. scrollRef.current!.getBoundingClientRect().top + 8,
  592. )?.element.dataset.at ?? "page:1"
  593. ).slice(5),
  594. );
  595. if (number < 1 || number > doc.numPages)
  596. throw new Error(`Page ${number} does not exist; the PDF has ${doc.numPages} pages.`);
  597. const pdfPage = await doc.getPage(number);
  598. const base = pdfPage.getViewport({ scale: 1 });
  599. const viewport = pdfPage.getViewport({ scale: Math.min(3, maxWidth / base.width) });
  600. const canvas = document.createElement("canvas");
  601. canvas.width = Math.floor(viewport.width);
  602. canvas.height = Math.floor(viewport.height);
  603. const context = canvas.getContext("2d")!;
  604. context.fillStyle = "#fff";
  605. context.fillRect(0, 0, canvas.width, canvas.height);
  606. await pdfPage.render({ canvas, canvasContext: context, viewport }).promise;
  607. return { ...canvasToPng(canvas, maxWidth), at: `page:${number}` };
  608. },
  609. zoom(direction) {
  610. stepZoom(direction);
  611. },
  612. fit(mode) {
  613. setZoom({ mode, percent: 100 });
  614. },
  615. async find(query) {
  616. const doc = docRef.current;
  617. if (!doc || !query.trim()) {
  618. this.clearFind();
  619. return 0;
  620. }
  621. const state = {
  622. query,
  623. matches: [] as { page: number; k: number }[],
  624. current: -1,
  625. ranges: new Map<number, Range[]>(),
  626. };
  627. find.current = state;
  628. const counts = await Promise.all(
  629. Array.from({ length: doc.numPages }, (_, i) =>
  630. pageText(i + 1).then((text) => countMatches(text, query)),
  631. ),
  632. );
  633. if (find.current !== state) return 0;
  634. counts.forEach((count, i) => {
  635. for (let k = 0; k < count; k++) state.matches.push({ page: i + 1, k });
  636. });
  637. for (const [i, slot] of slots.current.entries())
  638. if (slot.textLayer) state.ranges.set(i + 1, findAllRanges(slot.textLayer, query));
  639. paint();
  640. return state.matches.length;
  641. },
  642. findGo(index) {
  643. const state = find.current;
  644. const match = state?.matches[index];
  645. if (!state || !match) return;
  646. state.current = index;
  647. void rendered(match.page).then(() => {
  648. if (find.current !== state || state.current !== index) return;
  649. if (!state.ranges.has(match.page)) decorate(match.page);
  650. paint();
  651. const range = currentFindRange();
  652. if (range) scrollToRange(range, "center");
  653. else scrollToPage(match.page);
  654. });
  655. paint();
  656. },
  657. clearFind() {
  658. find.current = null;
  659. paint();
  660. },
  661. clearSelection() {
  662. scrollRef.current
  663. ?.querySelectorAll(".pdf-page.selected")
  664. .forEach((element) => element.classList.remove("selected"));
  665. const selection = document.getSelection();
  666. if (selection && scrollRef.current && selectionIn(scrollRef.current))
  667. selection.removeAllRanges();
  668. },
  669. goToPage(page) {
  670. scrollToPage(Math.min(Math.max(1, page), slots.current.length));
  671. },
  672. async thumbnail(page, width) {
  673. const doc = docRef.current;
  674. if (!doc) throw new Error("The PDF is still loading.");
  675. const pdfPage = await doc.getPage(page);
  676. const base = pdfPage.getViewport({ scale: 1 });
  677. const ratio = window.devicePixelRatio || 1;
  678. const viewport = pdfPage.getViewport({ scale: (width / base.width) * ratio });
  679. const canvas = document.createElement("canvas");
  680. canvas.width = Math.floor(viewport.width);
  681. canvas.height = Math.floor(viewport.height);
  682. canvas.style.width = `${width}px`;
  683. canvas.style.height = `${(viewport.height / viewport.width) * width}px`;
  684. const context = canvas.getContext("2d")!;
  685. context.fillStyle = "#fff";
  686. context.fillRect(0, 0, canvas.width, canvas.height);
  687. await pdfPage.render({ canvas, canvasContext: context, viewport }).promise;
  688. return canvas;
  689. },
  690. }),
  691. [],
  692. );
  693. return <div ref={scrollRef} className={`viewer-scroll pdf-scroll${glance ? " glance" : ""}`} />;
  694. });