PptxView.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
  2. import {
  3. RECOMMENDED_ZIP_LIMITS,
  4. buildPresentation,
  5. materializeSlideNodes,
  6. parseZipLazyMedia,
  7. renderSlide,
  8. type PresentationData,
  9. type SlideHandle,
  10. type SlideNode,
  11. } from "@aiden0z/pptx-renderer/browser";
  12. import { parseLocator } from "#office/domain/anchor.ts";
  13. import { cut } from "#office/domain/text.ts";
  14. import {
  15. boxOf,
  16. findAllRanges,
  17. pointOn,
  18. findTextRange,
  19. paintRanges,
  20. scrollToElement,
  21. scrollToRange,
  22. selectionIn,
  23. trackTopmost,
  24. } from "#ui/dom.ts";
  25. import { rasterize } from "#ui/raster.ts";
  26. import type { RevealedTarget, ViewerHandle, ViewerProps } from "#ui/viewers/types.ts";
  27. interface SlideSlot {
  28. frame: HTMLDivElement;
  29. host: HTMLDivElement;
  30. overlay: HTMLDivElement;
  31. handle?: SlideHandle;
  32. ready?: Promise<void>;
  33. }
  34. type TextBodyLike = { paragraphs?: { runs?: { text?: string }[] }[] };
  35. function bodyText(body: TextBodyLike | undefined): string {
  36. return (body?.paragraphs ?? [])
  37. .map((paragraph) => (paragraph.runs ?? []).map((run) => run.text ?? "").join(""))
  38. .join("\n")
  39. .trim();
  40. }
  41. function nodeText(node: SlideNode): string {
  42. const data = node as unknown as {
  43. textBody?: TextBodyLike;
  44. rows?: { cells: { textBody?: TextBodyLike }[] }[];
  45. };
  46. if (data.rows)
  47. return data.rows
  48. .map((row) => row.cells.map((cell) => bodyText(cell.textBody)).join(" | "))
  49. .join("\n");
  50. return bodyText(data.textBody);
  51. }
  52. const GAP = 16;
  53. export const PptxView = forwardRef<ViewerHandle, ViewerProps>(function PptxView(props, ref) {
  54. const scrollRef = useRef<HTMLDivElement>(null);
  55. const listRef = useRef<HTMLDivElement>(null);
  56. const presentation = useRef<PresentationData | null>(null);
  57. const slots = useRef<SlideSlot[]>([]);
  58. const mediaCache = useRef(new Map<string, string>());
  59. const [width, setWidth] = useState(0);
  60. // Bumped when a presentation finishes parsing; the ref alone would not re-render.
  61. const [loaded, setLoaded] = useState(0);
  62. const callbacks = useRef(props);
  63. callbacks.current = props;
  64. // Slides always fit the pane width; there is no zoom.
  65. const scale = loaded && presentation.current ? width / presentation.current.width : 0;
  66. const scaleRef = useRef(scale);
  67. scaleRef.current = scale;
  68. const thumbs = useRef(new Map<number, { element: HTMLElement; handle: SlideHandle }>());
  69. const reveal = useRef<Range[]>([]);
  70. /** Per agent target, what a click on it hits: its quote or its shape (not a whole slide). */
  71. const revealHits = useRef<(Range | Element | null)[]>([]);
  72. const find = useRef<{ ranges: Range[]; current: number } | null>(null);
  73. const glance = Boolean(props.glance);
  74. useEffect(() => {
  75. let cancelled = false;
  76. const list = listRef.current!;
  77. (async () => {
  78. const files = await parseZipLazyMedia(props.bytes, RECOMMENDED_ZIP_LIMITS);
  79. if (cancelled) return;
  80. const built = buildPresentation(files, { lazySlides: true });
  81. presentation.current = built;
  82. list.replaceChildren();
  83. slots.current = built.slides.map((_: unknown, i: number) => {
  84. const frame = document.createElement("div");
  85. frame.className = "slide-frame";
  86. frame.dataset.at = `slide:${i + 1}`;
  87. const host = document.createElement("div");
  88. host.className = "slide-host";
  89. host.style.width = `${built.width}px`;
  90. host.style.height = `${built.height}px`;
  91. const overlay = document.createElement("div");
  92. overlay.className = "slide-overlay";
  93. host.append(overlay);
  94. frame.append(host);
  95. list.append(frame);
  96. return { frame, host, overlay };
  97. });
  98. setWidth(Math.max(200, scrollRef.current!.clientWidth - GAP * 2));
  99. setLoaded((count) => count + 1);
  100. callbacks.current.onPage?.({ current: 1, count: built.slides.length });
  101. callbacks.current.onReady();
  102. })().catch((error) => !cancelled && callbacks.current.onError(error));
  103. return () => {
  104. cancelled = true;
  105. for (const slot of slots.current) slot.handle?.dispose();
  106. slots.current = [];
  107. for (const thumb of thumbs.current.values()) thumb.handle.dispose();
  108. thumbs.current.clear();
  109. for (const url of mediaCache.current.values()) URL.revokeObjectURL(url);
  110. mediaCache.current.clear();
  111. };
  112. }, [props.bytes]);
  113. useEffect(() => {
  114. const scroll = scrollRef.current!;
  115. const resize = new ResizeObserver(() => setWidth(Math.max(200, scroll.clientWidth - GAP * 2)));
  116. resize.observe(scroll);
  117. return () => resize.disconnect();
  118. }, []);
  119. // Apply scale and (re)observe for lazy rendering.
  120. useEffect(() => {
  121. const built = presentation.current;
  122. if (!built || !scale) return;
  123. for (const slot of slots.current) {
  124. slot.frame.style.width = `${built.width * scale}px`;
  125. slot.frame.style.height = `${built.height * scale}px`;
  126. slot.host.style.transform = `scale(${scale})`;
  127. slot.frame.style.setProperty("--slide-scale", String(scale));
  128. }
  129. const observer = new IntersectionObserver(
  130. (entries) => {
  131. for (const entry of entries) {
  132. if (!entry.isIntersecting) continue;
  133. const index = slots.current.findIndex((slot) => slot.frame === entry.target);
  134. if (index >= 0) void ensureRendered(index);
  135. }
  136. },
  137. { root: scrollRef.current, rootMargin: "800px 0px" },
  138. );
  139. for (const slot of slots.current) observer.observe(slot.frame);
  140. return () => observer.disconnect();
  141. }, [scale, loaded]);
  142. function ensureRendered(index: number): Promise<void> {
  143. const built = presentation.current;
  144. const slot = slots.current[index];
  145. if (!built || !slot) return Promise.resolve();
  146. if (slot.ready) return slot.ready;
  147. const slide = built.slides[index];
  148. materializeSlideNodes(built, slide);
  149. const handle = renderSlide(built, slide, {
  150. mediaUrlCache: mediaCache.current,
  151. pdfjs: false,
  152. onNavigate: (target: { slideIndex?: number; url?: string }) => {
  153. if (target.url) callbacks.current.onLink(target.url);
  154. else if (typeof target.slideIndex === "number") {
  155. const frame = slots.current[target.slideIndex]?.frame;
  156. if (frame) scrollToElement(frame, "start");
  157. }
  158. },
  159. });
  160. slot.handle = handle;
  161. slot.host.insertBefore(handle.element, slot.overlay);
  162. const ready = handle.ready.catch(() => undefined);
  163. slot.ready = ready;
  164. return ready;
  165. }
  166. /** Topmost node under a point in slide coordinates (later nodes paint on top). */
  167. function hitTest(index: number, x: number, y: number): SlideNode | null {
  168. const built = presentation.current;
  169. if (!built) return null;
  170. const slide = built.slides[index];
  171. materializeSlideNodes(built, slide);
  172. for (let i = slide.nodes.length - 1; i >= 0; i--) {
  173. const node = slide.nodes[i];
  174. const { x: left, y: top } = node.position;
  175. const { w, h } = node.size;
  176. if (w <= 0 && h <= 0) continue;
  177. const pad = Math.min(w, h) < 6 ? 4 : 0;
  178. if (x >= left - pad && x <= left + w + pad && y >= top - pad && y <= top + h + pad)
  179. return node;
  180. }
  181. return null;
  182. }
  183. function outline(slot: SlideSlot, node: SlideNode | null, kind: "selected" | "revealed") {
  184. slot.overlay.querySelectorAll(`.shape-${kind}`).forEach((element) => element.remove());
  185. if (!node) return;
  186. const box = document.createElement("div");
  187. box.className = `shape-${kind}`;
  188. box.style.left = `${node.position.x}px`;
  189. box.style.top = `${node.position.y}px`;
  190. box.style.width = `${node.size.w}px`;
  191. box.style.height = `${node.size.h}px`;
  192. slot.overlay.append(box);
  193. }
  194. useEffect(() => {
  195. const scroll = scrollRef.current!;
  196. const untrack = trackTopmost(
  197. scroll,
  198. () => slots.current.map((slot) => slot.frame),
  199. (element) => element.dataset.at ?? null,
  200. (at) => {
  201. callbacks.current.onLocation(at);
  202. callbacks.current.onPage?.({ current: Number(at.slice(6)), count: slots.current.length });
  203. },
  204. 1 / 3,
  205. );
  206. const pick = (event: MouseEvent) => {
  207. const frame = (event.target as Element).closest<HTMLElement>(".slide-frame");
  208. const index = slots.current.findIndex((slot) => slot.frame === frame);
  209. if (index < 0) {
  210. for (const other of slots.current) outline(other, null, "selected");
  211. callbacks.current.onSelect(null);
  212. return;
  213. }
  214. const slot = slots.current[index];
  215. const selected = selectionIn(slot.host);
  216. // A click on one of the agent's marks brings its note back instead of selecting.
  217. const hit = selected
  218. ? -1
  219. : revealHits.current.findIndex((mark) => pointOn(mark, event.clientX, event.clientY));
  220. if (hit >= 0 && callbacks.current.onRevealHit?.(hit)) {
  221. for (const other of slots.current) outline(other, null, "selected");
  222. callbacks.current.onSelect(null);
  223. return;
  224. }
  225. const rect = slot.host.getBoundingClientRect();
  226. const point = selected
  227. ? selected.range.getBoundingClientRect()
  228. : { left: event.clientX, top: event.clientY, width: 0, height: 0 };
  229. const x = (point.left + point.width / 2 - rect.left) / scaleRef.current;
  230. const y = (point.top + point.height / 2 - rect.top) / scaleRef.current;
  231. const node = hitTest(index, x, y);
  232. for (const other of slots.current) outline(other, null, "selected");
  233. outline(slot, node, "selected");
  234. const at = node ? `slide:${index + 1}/shape:${node.id}` : `slide:${index + 1}`;
  235. const text = selected?.text ?? (node ? nodeText(node) : "");
  236. const range = selected?.range.cloneRange();
  237. const box = slot.overlay.querySelector(".shape-selected");
  238. callbacks.current.onSelect(
  239. { at, text: cut(text, 0, 2000) },
  240. {
  241. text: Boolean(range),
  242. locate: () => (range ? boxOf(range) : (boxOf(box) ?? boxOf(slot.frame))),
  243. user: true,
  244. },
  245. );
  246. };
  247. const onUp = (event: MouseEvent) => setTimeout(() => pick(event), 0);
  248. scroll.addEventListener("mouseup", onUp);
  249. return () => {
  250. untrack();
  251. scroll.removeEventListener("mouseup", onUp);
  252. };
  253. }, []);
  254. function slotFor(at: string) {
  255. const locator = parseLocator("pptx", at);
  256. if (locator.kind !== "pptx") return null;
  257. return { locator, slot: slots.current[locator.from - 1] ?? null };
  258. }
  259. function paint() {
  260. paintRanges("office-reveal", reveal.current);
  261. const state = find.current;
  262. const current = state ? state.ranges[state.current] : undefined;
  263. paintRanges("office-find", state ? state.ranges.filter((range) => range !== current) : []);
  264. paintRanges("office-find-current", current ? [current] : []);
  265. }
  266. useImperativeHandle(
  267. ref,
  268. (): ViewerHandle => ({
  269. async reveal(targets) {
  270. this.clearReveal();
  271. const results: RevealedTarget[] = [];
  272. for (const target of targets) {
  273. const found = slotFor(target.at);
  274. if (!found?.slot) continue;
  275. const { locator, slot } = found;
  276. await ensureRendered(locator.from - 1);
  277. if (locator.shape) {
  278. const built = presentation.current!;
  279. const slide = built.slides[locator.from - 1];
  280. materializeSlideNodes(built, slide);
  281. outline(
  282. slot,
  283. slide.nodes.find((node: SlideNode) => node.id === locator.shape) ?? null,
  284. "revealed",
  285. );
  286. } else {
  287. for (let n = locator.from; n <= locator.to; n++)
  288. slots.current[n - 1]?.frame.classList.add("revealed");
  289. }
  290. const range = target.quote ? findTextRange(slot.host, target.quote) : null;
  291. if (range) reveal.current.push(range);
  292. const shape = locator.shape ? slot.overlay.querySelector(".shape-revealed") : null;
  293. revealHits.current.push(range ?? shape);
  294. results.push({
  295. at: target.at,
  296. locate: () => boxOf(range) ?? boxOf(shape) ?? boxOf(slot.frame),
  297. scrollTo: () =>
  298. range
  299. ? scrollToRange(range, "upper")
  300. : scrollToElement(shape ?? slot.frame, shape ? "upper" : "start"),
  301. });
  302. }
  303. paint();
  304. results[0]?.scrollTo();
  305. return results;
  306. },
  307. goTo(at) {
  308. const found = slotFor(at);
  309. if (found?.slot) scrollToElement(found.slot.frame, "start");
  310. },
  311. clearReveal() {
  312. reveal.current = [];
  313. revealHits.current = [];
  314. for (const slot of slots.current) {
  315. slot.frame.classList.remove("revealed");
  316. outline(slot, null, "revealed");
  317. }
  318. paint();
  319. },
  320. async capture(at, maxWidth) {
  321. const built = presentation.current;
  322. if (!built) throw new Error("The presentation is still loading.");
  323. let index: number;
  324. if (at) {
  325. const found = slotFor(at);
  326. if (!found?.slot)
  327. throw new Error(`${at} is not in this presentation (${built.slides.length} slides).`);
  328. index = found.locator.from - 1;
  329. } else {
  330. const top = scrollRef.current!.getBoundingClientRect().top;
  331. index = Math.max(
  332. 0,
  333. slots.current.findIndex((slot) => slot.frame.getBoundingClientRect().bottom > top + 8),
  334. );
  335. }
  336. await ensureRendered(index);
  337. const slot = slots.current[index];
  338. const raster = await rasterize(slot.handle!.element, {
  339. maxWidth,
  340. context: slot.host,
  341. background: "#fff",
  342. });
  343. return { ...raster, at: at ?? `slide:${index + 1}` };
  344. },
  345. zoom() {},
  346. fit() {},
  347. async find(query) {
  348. if (!query.trim()) {
  349. this.clearFind();
  350. return 0;
  351. }
  352. await Promise.all(slots.current.map((_, i) => ensureRendered(i)));
  353. const ranges = slots.current.flatMap((slot) => findAllRanges(slot.host, query));
  354. find.current = ranges.length ? { ranges, current: -1 } : null;
  355. paint();
  356. return ranges.length;
  357. },
  358. findGo(index) {
  359. const state = find.current;
  360. if (!state?.ranges[index]) return;
  361. state.current = index;
  362. paint();
  363. scrollToRange(state.ranges[index], "center");
  364. },
  365. clearFind() {
  366. find.current = null;
  367. paint();
  368. },
  369. clearSelection() {
  370. for (const slot of slots.current) outline(slot, null, "selected");
  371. if (scrollRef.current && selectionIn(scrollRef.current))
  372. document.getSelection()?.removeAllRanges();
  373. },
  374. goToPage(page) {
  375. const slot = slots.current[Math.min(Math.max(1, page), slots.current.length) - 1];
  376. if (slot) scrollToElement(slot.frame, "start");
  377. },
  378. async thumbnail(page, thumbWidth) {
  379. const built = presentation.current;
  380. if (!built) throw new Error("The presentation is still loading.");
  381. const cached = thumbs.current.get(page);
  382. if (cached) return cached.element;
  383. const slide = built.slides[page - 1];
  384. materializeSlideNodes(built, slide);
  385. const handle = renderSlide(built, slide, {
  386. mediaUrlCache: mediaCache.current,
  387. pdfjs: false,
  388. });
  389. const thumbScale = thumbWidth / built.width;
  390. const element = document.createElement("div");
  391. element.className = "slide-thumb";
  392. element.style.width = `${thumbWidth}px`;
  393. element.style.height = `${built.height * thumbScale}px`;
  394. const inner = document.createElement("div");
  395. inner.className = "slide-host";
  396. inner.style.width = `${built.width}px`;
  397. inner.style.height = `${built.height}px`;
  398. inner.style.transform = `scale(${thumbScale})`;
  399. inner.append(handle.element);
  400. element.append(inner);
  401. thumbs.current.set(page, { element, handle });
  402. await handle.ready.catch(() => undefined);
  403. return element;
  404. },
  405. }),
  406. [],
  407. );
  408. return (
  409. <div ref={scrollRef} className={`viewer-scroll pptx-scroll${glance ? " glance" : ""}`}>
  410. <div ref={listRef} className="slide-list" />
  411. </div>
  412. );
  413. });