DocxView.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import {
  2. forwardRef,
  3. useEffect,
  4. useImperativeHandle,
  5. useLayoutEffect,
  6. useRef,
  7. useState,
  8. } from "react";
  9. import { renderAsync } from "docx-preview";
  10. import { parseLocator } from "#office/domain/anchor.ts";
  11. import { cut } from "#office/domain/text.ts";
  12. import {
  13. boxOf,
  14. findAllRanges,
  15. pointOn,
  16. findTextRange,
  17. installLinkGuard,
  18. paintRanges,
  19. scrollToElement,
  20. scrollToRange,
  21. selectionIn,
  22. trackTopmost,
  23. unionBox,
  24. } from "#ui/dom.ts";
  25. import { rasterize } from "#ui/raster.ts";
  26. import { alignBlocks } from "#ui/viewers/align.ts";
  27. import {
  28. nextZoom,
  29. type FitMode,
  30. type RevealedTarget,
  31. type ViewerHandle,
  32. type ViewerProps,
  33. } from "#ui/viewers/types.ts";
  34. const CLASS = "office-docx";
  35. /** Block element for a locator: `p:N` / `t:N` map to rendered elements, `t:N/rRcC` to a cell. */
  36. function elementsFor(root: HTMLElement, at: string): HTMLElement[] {
  37. const locator = parseLocator("docx", at);
  38. if (locator.kind !== "docx") return [];
  39. if (locator.type === "paragraph") {
  40. const out: HTMLElement[] = [];
  41. for (let n = locator.from; n <= locator.to; n++)
  42. out.push(...root.querySelectorAll<HTMLElement>(`[data-at="p:${n}"]`));
  43. return out;
  44. }
  45. const tables = [...root.querySelectorAll<HTMLElement>(`[data-at="t:${locator.table}"]`)];
  46. if (!locator.cell) return tables;
  47. for (const table of tables) {
  48. const cell = rowsOf(table)[locator.cell.row - 1]?.cells[locator.cell.col - 1];
  49. if (cell) return [cell as HTMLElement];
  50. }
  51. return tables;
  52. }
  53. /**
  54. * Word list bullets use private-use glyphs of the Symbol / Wingdings fonts, which the sandbox does
  55. * not have; map the common ones to Unicode bullets in docx-preview's generated numbering CSS.
  56. */
  57. const SYMBOL_BULLETS: Record<number, string> = {
  58. 0xf0b7: "\u2022",
  59. 0xf0a7: "\u25aa",
  60. 0xf06f: "\u25e6",
  61. 0xf0a8: "\u25cb",
  62. 0xf0d8: "\u27a2",
  63. 0xf0e0: "\u27a2",
  64. 0xf0fc: "\u2713",
  65. 0xf076: "\u2756",
  66. };
  67. function fixSymbolBullets(styles: HTMLElement) {
  68. for (const style of styles.querySelectorAll("style")) {
  69. const text = style.textContent ?? "";
  70. const next = text.replace(
  71. /[\uf020-\uf0ff]/g,
  72. (char) => SYMBOL_BULLETS[char.charCodeAt(0)] ?? "\u2022",
  73. );
  74. if (next !== text) style.textContent = next;
  75. }
  76. }
  77. function rowsOf(table: HTMLElement): HTMLTableRowElement[] {
  78. return [...(table as HTMLTableElement).rows].filter((row) => row.closest("table") === table);
  79. }
  80. /** Canvas padding (CSS keeps .docx-scroll in step). */
  81. const PADDING = 16;
  82. export const DocxView = forwardRef<ViewerHandle, ViewerProps>(function DocxView(props, ref) {
  83. const scrollRef = useRef<HTMLDivElement>(null);
  84. const bodyRef = useRef<HTMLDivElement>(null);
  85. const styleRef = useRef<HTMLDivElement>(null);
  86. const [zoom, setZoom] = useState<{ mode: FitMode | null; percent: number }>({
  87. mode: "width",
  88. percent: 100,
  89. });
  90. /** Natural (unzoomed) page size, measured once after rendering. */
  91. const [natural, setNatural] = useState<{ width: number; height: number } | null>(null);
  92. const [box, setBox] = useState({ width: 0, height: 0 });
  93. const callbacks = useRef(props);
  94. callbacks.current = props;
  95. const glance = Boolean(props.glance);
  96. const scale = (() => {
  97. if (!natural || !box.width) return 1;
  98. const fitWidth = Math.min(2, (box.width - PADDING * 2) / natural.width);
  99. if (zoom.mode === "width" || glance) return fitWidth;
  100. if (zoom.mode === "page")
  101. return Math.min(fitWidth, (box.height - PADDING * 2) / natural.height);
  102. if (zoom.mode === "actual") return 1;
  103. return zoom.percent / 100;
  104. })();
  105. const scaleRef = useRef(scale);
  106. scaleRef.current = scale;
  107. const previousScale = useRef(scale);
  108. /** The agent's marks: painted quote ranges, and per target what a click on it hits. */
  109. const reveal = useRef<{ ranges: Range[]; hits: (Range | HTMLElement[])[] }>({
  110. ranges: [],
  111. hits: [],
  112. });
  113. const find = useRef<{ ranges: Range[]; current: number } | null>(null);
  114. const sections = () => [
  115. ...(bodyRef.current?.querySelectorAll<HTMLElement>(`section.${CLASS}`) ?? []),
  116. ];
  117. useEffect(() => {
  118. let active = true;
  119. const body = bodyRef.current!;
  120. const styles = styleRef.current!;
  121. body.replaceChildren();
  122. styles.replaceChildren();
  123. renderAsync(props.bytes, body, styles, {
  124. className: CLASS,
  125. inWrapper: true,
  126. breakPages: true,
  127. ignoreLastRenderedPageBreak: true,
  128. experimental: true,
  129. renderHeaders: true,
  130. renderFooters: true,
  131. renderFootnotes: true,
  132. renderEndnotes: true,
  133. renderComments: false,
  134. renderChanges: false,
  135. renderAltChunks: false,
  136. useBase64URL: true,
  137. })
  138. .then(() => {
  139. if (!active) return;
  140. fixSymbolBullets(styles);
  141. annotate(body);
  142. const page = sections()[0];
  143. if (page) {
  144. const current = scaleRef.current || 1;
  145. const rect = page.getBoundingClientRect();
  146. setNatural({ width: rect.width / current, height: rect.height / current });
  147. }
  148. callbacks.current.onPage?.({ current: 1, count: Math.max(1, sections().length) });
  149. callbacks.current.onReady();
  150. })
  151. .catch((error) => active && callbacks.current.onError(error));
  152. return () => {
  153. active = false;
  154. };
  155. }, [props.bytes]);
  156. /** Tag rendered body elements with their locators (data-at). */
  157. function annotate(body: HTMLElement) {
  158. const elements: HTMLElement[] = [];
  159. for (const article of body.querySelectorAll<HTMLElement>(`section.${CLASS} > article`)) {
  160. const walk = (parent: Element) => {
  161. for (const child of parent.children) {
  162. const tag = child.tagName;
  163. if (tag === "P" || /^H[1-6]$/.test(tag)) elements.push(child as HTMLElement);
  164. else if (tag === "TABLE") elements.push(child as HTMLElement);
  165. else if (!["HEADER", "FOOTER", "OL", "UL"].includes(tag) || child.children.length)
  166. walk(child);
  167. }
  168. };
  169. walk(article);
  170. }
  171. const keys = alignBlocks(
  172. elements.map((element) => ({
  173. text: element.textContent ?? "",
  174. table: element.tagName === "TABLE",
  175. })),
  176. callbacks.current.blocks ?? [],
  177. );
  178. elements.forEach((element, i) => {
  179. if (keys[i]) element.dataset.at = keys[i]!;
  180. });
  181. }
  182. // Report zoom; keep the centre of the view in place when it changes.
  183. useLayoutEffect(() => {
  184. const scroll = scrollRef.current;
  185. const before = previousScale.current;
  186. previousScale.current = scale;
  187. if (natural) callbacks.current.onZoom?.({ mode: zoom.mode, percent: Math.round(scale * 100) });
  188. if (!scroll || !before || before === scale) return;
  189. const ratio = scale / before;
  190. const x = scroll.clientWidth / 2;
  191. const y = scroll.clientHeight / 2;
  192. scroll.scrollTo({
  193. left: Math.max(0, (scroll.scrollLeft + x - PADDING) * ratio + PADDING - x),
  194. top: Math.max(0, (scroll.scrollTop + y - PADDING) * ratio + PADDING - y),
  195. });
  196. }, [scale, natural, zoom.mode]);
  197. function paint() {
  198. paintRanges("office-reveal", reveal.current.ranges);
  199. const state = find.current;
  200. const current = state ? state.ranges[state.current] : undefined;
  201. paintRanges("office-find", state ? state.ranges.filter((range) => range !== current) : []);
  202. paintRanges("office-find-current", current ? [current] : []);
  203. }
  204. useEffect(() => {
  205. const scroll = scrollRef.current!;
  206. const resize = new ResizeObserver(() =>
  207. setBox((previous) =>
  208. Math.abs(previous.width - scroll.clientWidth) > 1 ||
  209. Math.abs(previous.height - scroll.clientHeight) > 1
  210. ? { width: scroll.clientWidth, height: scroll.clientHeight }
  211. : previous,
  212. ),
  213. );
  214. resize.observe(scroll);
  215. const unguard = installLinkGuard(
  216. bodyRef.current!,
  217. (url) => callbacks.current.onLink(url),
  218. (hash) => {
  219. const target = bodyRef.current!.querySelector(
  220. `[id="${CSS.escape(hash)}"], a[name="${CSS.escape(hash)}"]`,
  221. );
  222. if (target) scrollToElement(target, "start");
  223. return Boolean(target);
  224. },
  225. );
  226. const untrack = trackTopmost(
  227. scroll,
  228. () => scroll.querySelectorAll<HTMLElement>("[data-at]"),
  229. (element) => element.dataset.at ?? null,
  230. (at) => callbacks.current.onLocation(at),
  231. );
  232. const untrackPages = trackTopmost(
  233. scroll,
  234. sections,
  235. (element) => String(sections().indexOf(element) + 1),
  236. (page) =>
  237. callbacks.current.onPage?.({
  238. current: Number(page),
  239. count: Math.max(1, sections().length),
  240. }),
  241. 1 / 3,
  242. );
  243. const clearOutline = () =>
  244. scroll
  245. .querySelectorAll(".office-selected")
  246. .forEach((element) => element.classList.remove("office-selected"));
  247. const select = (event: Event) => {
  248. const selected = selectionIn(bodyRef.current!);
  249. if (selected) {
  250. const start =
  251. selected.range.startContainer.parentElement?.closest<HTMLElement>("[data-at]")?.dataset
  252. .at;
  253. const end =
  254. selected.range.endContainer.parentElement?.closest<HTMLElement>("[data-at]")?.dataset.at;
  255. if (!start) return;
  256. let at = start;
  257. const a = /^p:(\d+)$/.exec(start);
  258. const b = end && /^p:(\d+)$/.exec(end);
  259. if (a && b && Number(b[1]) > Number(a[1])) at = `p:${a[1]}-${b[1]}`;
  260. clearOutline();
  261. const range = selected.range.cloneRange();
  262. callbacks.current.onSelect(
  263. { at, text: selected.text },
  264. { text: true, locate: () => boxOf(range), user: true },
  265. );
  266. return;
  267. }
  268. if (event.type !== "click") return;
  269. // A click on one of the agent's marks brings its note back instead of selecting.
  270. const { clientX, clientY } = event as MouseEvent;
  271. const hit = reveal.current.hits.findIndex((mark) =>
  272. Array.isArray(mark)
  273. ? mark.some((element) => pointOn(element, clientX, clientY))
  274. : pointOn(mark, clientX, clientY),
  275. );
  276. if (hit >= 0 && callbacks.current.onRevealHit?.(hit)) {
  277. clearOutline();
  278. callbacks.current.onSelect(null);
  279. return;
  280. }
  281. const target = event.target as Element;
  282. if (target.closest("a[href]")) return;
  283. const cell = target.closest("td, th");
  284. const block = target.closest<HTMLElement>("[data-at]");
  285. clearOutline();
  286. if (!block?.dataset.at) {
  287. callbacks.current.onSelect(null);
  288. return;
  289. }
  290. let at = block.dataset.at;
  291. let text = block.textContent ?? "";
  292. if (cell && block.tagName === "TABLE") {
  293. const rows = rowsOf(block);
  294. const row = rows.findIndex((item) => item.contains(cell));
  295. const col = row >= 0 ? [...rows[row].cells].indexOf(cell as HTMLTableCellElement) : -1;
  296. if (row >= 0 && col >= 0) {
  297. at = `${block.dataset.at}/r${row + 1}c${col + 1}`;
  298. text = cell.textContent ?? "";
  299. }
  300. }
  301. const outlined = (cell && at.includes("/r") ? cell : block) as HTMLElement;
  302. outlined.classList.add("office-selected");
  303. callbacks.current.onSelect(
  304. { at, text: cut(text.replace(/\s+/g, " ").trim(), 0, 2000) },
  305. { text: false, locate: () => boxOf(outlined), user: true },
  306. );
  307. };
  308. const deferred = (event: Event) => setTimeout(() => select(event), 0);
  309. scroll.addEventListener("mouseup", deferred);
  310. scroll.addEventListener("click", select);
  311. return () => {
  312. resize.disconnect();
  313. unguard();
  314. untrack();
  315. untrackPages();
  316. scroll.removeEventListener("mouseup", deferred);
  317. scroll.removeEventListener("click", select);
  318. };
  319. }, []);
  320. useImperativeHandle(
  321. ref,
  322. (): ViewerHandle => ({
  323. async reveal(targets) {
  324. this.clearReveal();
  325. const body = bodyRef.current!;
  326. const results: RevealedTarget[] = [];
  327. for (const target of targets) {
  328. const elements = elementsFor(body, target.at);
  329. if (!elements.length) continue;
  330. let range: Range | null = null;
  331. if (target.quote)
  332. for (const element of elements) {
  333. range = findTextRange(element, target.quote);
  334. if (range) break;
  335. }
  336. if (range) reveal.current.ranges.push(range);
  337. else for (const element of elements) element.classList.add("office-revealed");
  338. reveal.current.hits.push(range ?? elements);
  339. const found = range;
  340. results.push({
  341. at: target.at,
  342. locate: () =>
  343. found ? boxOf(found) : unionBox(elements.map((element) => boxOf(element))),
  344. scrollTo: () =>
  345. found ? scrollToRange(found, "upper") : scrollToElement(elements[0], "upper"),
  346. });
  347. }
  348. paint();
  349. results[0]?.scrollTo();
  350. return results;
  351. },
  352. goTo(at) {
  353. const element = elementsFor(bodyRef.current!, at)[0];
  354. if (element) scrollToElement(element, "start");
  355. },
  356. clearReveal() {
  357. reveal.current = { ranges: [], hits: [] };
  358. bodyRef.current
  359. ?.querySelectorAll(".office-revealed")
  360. .forEach((element) => element.classList.remove("office-revealed"));
  361. paint();
  362. },
  363. async capture(at, maxWidth) {
  364. const body = bodyRef.current!;
  365. const scroll = scrollRef.current!;
  366. let anchor: HTMLElement | null = at ? (elementsFor(body, at)[0] ?? null) : null;
  367. if (at && !anchor) throw new Error(`Cannot find ${at} in the rendered document.`);
  368. let page: HTMLElement | null = anchor?.closest<HTMLElement>(`section.${CLASS}`) ?? null;
  369. if (!page) {
  370. const top = scroll.getBoundingClientRect().top;
  371. page =
  372. sections().find((section) => section.getBoundingClientRect().bottom > top + 8) ?? null;
  373. }
  374. if (!page) throw new Error("Nothing is rendered yet.");
  375. anchor ??= page.querySelector<HTMLElement>("[data-at]");
  376. const raster = await rasterize(page, { maxWidth, context: body, background: "#fff" });
  377. return { ...raster, at: anchor?.dataset.at ?? `page ${sections().indexOf(page) + 1}` };
  378. },
  379. zoom(direction) {
  380. setZoom({ mode: null, percent: nextZoom(Math.round(scaleRef.current * 100), direction) });
  381. },
  382. fit(mode) {
  383. setZoom({ mode, percent: 100 });
  384. },
  385. async find(query) {
  386. const ranges = query.trim() ? findAllRanges(bodyRef.current!, query) : [];
  387. find.current = ranges.length ? { ranges, current: -1 } : null;
  388. paint();
  389. return ranges.length;
  390. },
  391. findGo(index) {
  392. const state = find.current;
  393. if (!state?.ranges[index]) return;
  394. state.current = index;
  395. paint();
  396. scrollToRange(state.ranges[index], "center");
  397. },
  398. clearFind() {
  399. find.current = null;
  400. paint();
  401. },
  402. clearSelection() {
  403. scrollRef.current
  404. ?.querySelectorAll(".office-selected")
  405. .forEach((element) => element.classList.remove("office-selected"));
  406. if (bodyRef.current && selectionIn(bodyRef.current))
  407. document.getSelection()?.removeAllRanges();
  408. },
  409. goToPage(page) {
  410. const all = sections();
  411. const target = all[Math.min(Math.max(1, page), all.length) - 1];
  412. if (target) scrollToElement(target, "start");
  413. },
  414. }),
  415. [],
  416. );
  417. return (
  418. <div ref={scrollRef} className={`viewer-scroll docx-scroll${glance ? " glance" : ""}`}>
  419. <div ref={styleRef} />
  420. <div className="docx-zoom" style={{ zoom: scale }}>
  421. <div ref={bodyRef} />
  422. </div>
  423. </div>
  424. );
  425. });