XlsxView.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import {
  2. forwardRef,
  3. useCallback,
  4. useEffect,
  5. useImperativeHandle,
  6. useRef,
  7. useState,
  8. type CSSProperties,
  9. } from "react";
  10. import {
  11. XlsxViewer,
  12. setWasmSource,
  13. useXlsxViewerController,
  14. type XlsxCellRange,
  15. type XlsxCellStyleContext,
  16. type XlsxViewerController,
  17. } from "@extend-ai/react-xlsx";
  18. import { formatCell, formatLocator, parseLocator } from "#office/domain/anchor.ts";
  19. import { readBinary, readText } from "#ui/assets.ts";
  20. import { boxOf, installLinkGuard } from "#ui/dom.ts";
  21. import { rasterize } from "#ui/raster.ts";
  22. import type { RevealedTarget, ViewerHandle, ViewerProps } from "#ui/viewers/types.ts";
  23. let wasm: Promise<void> | undefined;
  24. /**
  25. * react-xlsx parses workbooks with wasm in a module worker. The sandbox cannot fetch, so hand it the
  26. * wasm bytes and a blob URL for the worker (the build points the library at `__officeXlsxWorkerUrl`).
  27. */
  28. export function loadXlsxWasm(): Promise<void> {
  29. return (wasm ??= Promise.all([readBinary("sheets.wasm"), readText("xlsx-worker.js")]).then(
  30. ([bytes, worker]) => {
  31. (globalThis as { __officeXlsxWorkerUrl?: string }).__officeXlsxWorkerUrl =
  32. URL.createObjectURL(new Blob([worker], { type: "text/javascript" }));
  33. setWasmSource(bytes);
  34. },
  35. ));
  36. }
  37. /** 0-based viewer range → 1-based anchor locator. */
  38. function anchorOf(sheet: string, range: XlsxCellRange): string {
  39. return formatLocator({
  40. kind: "xlsx",
  41. sheet,
  42. range: {
  43. start: {
  44. row: Math.min(range.start.row, range.end.row) + 1,
  45. col: Math.min(range.start.col, range.end.col) + 1,
  46. },
  47. end: {
  48. row: Math.max(range.start.row, range.end.row) + 1,
  49. col: Math.max(range.start.col, range.end.col) + 1,
  50. },
  51. },
  52. });
  53. }
  54. /** Display value and formula of a cell; worker-backed workbooks only answer asynchronously. */
  55. async function cellSnapshot(controller: XlsxViewerController, row: number, col: number) {
  56. const sheet = controller.activeSheet;
  57. if (controller.getCellSnapshotAsync && sheet && controller.isWorkerBacked)
  58. return controller
  59. .getCellSnapshotAsync(sheet.workbookSheetIndex, row, col)
  60. .catch(() => ({ displayValue: "", formula: "" }));
  61. return {
  62. displayValue: controller.getCellDisplayValue({ row, col }),
  63. formula: controller.getCellFormula({ row, col }),
  64. };
  65. }
  66. /** Values of a range as tab-separated text (capped at 50 rows × 20 columns). */
  67. async function rangeText(controller: XlsxViewerController, range: XlsxCellRange): Promise<string> {
  68. const top = Math.min(range.start.row, range.end.row);
  69. const bottom = Math.min(Math.max(range.start.row, range.end.row), top + 49);
  70. const left = Math.min(range.start.col, range.end.col);
  71. const right = Math.min(Math.max(range.start.col, range.end.col), left + 19);
  72. const single = top === bottom && left === right;
  73. const rows: Promise<string>[] = [];
  74. for (let row = top; row <= bottom; row++) {
  75. const cells: Promise<string>[] = [];
  76. for (let col = left; col <= right; col++)
  77. cells.push(
  78. cellSnapshot(controller, row, col).then(({ displayValue, formula }) =>
  79. formula && single ? `${displayValue} (=${formula.replace(/^=/, "")})` : displayValue,
  80. ),
  81. );
  82. rows.push(Promise.all(cells).then((values) => values.join("\t")));
  83. }
  84. return (await Promise.all(rows)).join("\n").trim();
  85. }
  86. interface Highlight {
  87. sheet: string;
  88. top: number;
  89. left: number;
  90. bottom: number;
  91. right: number;
  92. }
  93. const REVEAL_STYLE: CSSProperties = {
  94. backgroundColor: "rgba(255, 179, 0, 0.38)",
  95. boxShadow: "inset 0 -2px 0 #e59a00",
  96. };
  97. const FIND_STYLE: CSSProperties = { backgroundColor: "rgba(255, 213, 0, 0.45)" };
  98. const FIND_CURRENT_STYLE: CSSProperties = {
  99. backgroundColor: "rgba(255, 140, 0, 0.6)",
  100. boxShadow: "inset 0 0 0 1px #e07b00",
  101. };
  102. const inside = (item: Highlight, sheet: string, row: number, col: number) =>
  103. item.sheet === sheet &&
  104. row >= item.top &&
  105. row <= item.bottom &&
  106. col >= item.left &&
  107. col <= item.right;
  108. /** The grid's drawing surface (the largest canvas); it moves as the sheet scrolls. */
  109. function gridCanvas(root: HTMLElement | null): HTMLCanvasElement | null {
  110. let best: HTMLCanvasElement | null = null;
  111. let area = 0;
  112. for (const canvas of root?.querySelectorAll<HTMLCanvasElement>(".xlsx-grid canvas") ?? []) {
  113. const rect = canvas.getBoundingClientRect();
  114. if (rect.width * rect.height > area) {
  115. area = rect.width * rect.height;
  116. best = canvas;
  117. }
  118. }
  119. return best;
  120. }
  121. interface Press {
  122. start: { x: number; y: number };
  123. end: { x: number; y: number };
  124. /** Grid surface position when pressed, to follow later scrolling. */
  125. surface: DOMRect | null;
  126. }
  127. /**
  128. * The grid is drawn on canvas, so cells have no boxes; the selection bar anchors to where the
  129. * user pressed (or dragged), shifted by however far the sheet has scrolled since.
  130. */
  131. function pressBox(root: HTMLElement | null, press: Press): DOMRect | null {
  132. const now = boxOf(gridCanvas(root));
  133. const dx = press.surface && now ? now.left - press.surface.left : 0;
  134. const dy = press.surface && now ? now.top - press.surface.top : 0;
  135. const left = Math.min(press.start.x, press.end.x) + dx;
  136. const top = Math.min(press.start.y, press.end.y) + dy;
  137. return new DOMRect(
  138. left,
  139. top - 8,
  140. Math.max(2, Math.abs(press.end.x - press.start.x)),
  141. Math.max(16, Math.abs(press.end.y - press.start.y) + 16),
  142. );
  143. }
  144. function SheetTabs({ controller }: { controller: XlsxViewerController }) {
  145. if (controller.tabs.length <= 1) return null;
  146. return (
  147. <div className="sheet-tabs" role="tablist">
  148. {controller.tabs.map((tab, index) => (
  149. <button
  150. key={tab.id}
  151. type="button"
  152. role="tab"
  153. aria-selected={index === controller.activeTabIndex}
  154. className={index === controller.activeTabIndex ? "active" : ""}
  155. onClick={() => controller.setActiveTabIndex(index)}
  156. title={tab.name}
  157. >
  158. {tab.name}
  159. </button>
  160. ))}
  161. </div>
  162. );
  163. }
  164. export const XlsxView = forwardRef<ViewerHandle, ViewerProps>(function XlsxView(props, ref) {
  165. const rootRef = useRef<HTMLDivElement>(null);
  166. const callbacks = useRef(props);
  167. callbacks.current = props;
  168. const controller = useXlsxViewerController({
  169. file: props.bytes,
  170. fileName: props.info.path,
  171. readOnly: true,
  172. });
  173. const controllerRef = useRef(controller);
  174. controllerRef.current = controller;
  175. const [revealed, setRevealed] = useState<Highlight[]>([]);
  176. /** Agent targets with a cell range, by their position in the last reveal result. */
  177. const revealHits = useRef<{ item: Highlight; index: number }[]>([]);
  178. const [found, setFound] = useState<{ items: Highlight[]; current: number }>({
  179. items: [],
  180. current: -1,
  181. });
  182. const foundRef = useRef(found);
  183. foundRef.current = found;
  184. const readyRef = useRef(false);
  185. /** Set by a pointer or key action in the grid; selections without one open no selection bar. */
  186. /** Last pointer or key action in the grid; selections long after one open no selection bar. */
  187. const acted = useRef<{ time: number; press: Press | null }>({ time: 0, press: null });
  188. /** Bumped by every press in the grid so clicking the selected cell shows the bar again. */
  189. const [presses, setPresses] = useState(0);
  190. useEffect(() => {
  191. if (controller.error) callbacks.current.onError(controller.error);
  192. else if (!controller.isLoading && controller.sheets.length && !readyRef.current) {
  193. readyRef.current = true;
  194. callbacks.current.onReady();
  195. }
  196. }, [controller.error, controller.isLoading, controller.sheets.length]);
  197. const sheetName = controller.activeSheet?.name ?? controller.activeTab?.name ?? "";
  198. // Location: active sheet and cell.
  199. useEffect(() => {
  200. if (!sheetName) return;
  201. const cell = controller.activeCell;
  202. callbacks.current.onLocation(
  203. cell
  204. ? formatLocator({
  205. kind: "xlsx",
  206. sheet: sheetName,
  207. range: {
  208. start: { row: cell.row + 1, col: cell.col + 1 },
  209. end: { row: cell.row + 1, col: cell.col + 1 },
  210. },
  211. })
  212. : formatLocator({ kind: "xlsx", sheet: sheetName }),
  213. );
  214. }, [sheetName, controller.activeCell?.row, controller.activeCell?.col]);
  215. // Selection: report the selected range (or active cell) with its values.
  216. const selectionKey = controller.selection
  217. ? JSON.stringify(controller.selection)
  218. : controller.activeCellAddress;
  219. useEffect(() => {
  220. if (!sheetName || !readyRef.current) return;
  221. const range =
  222. controller.selection ??
  223. (controller.activeCell ? { start: controller.activeCell, end: controller.activeCell } : null);
  224. if (!range) return;
  225. let current = true;
  226. const at = anchorOf(sheetName, range);
  227. let user = performance.now() - acted.current.time < 1500;
  228. const pressed = user ? acted.current.press : null;
  229. // A click inside one of the agent's ranges brings its note back instead of the bar.
  230. if (pressed) {
  231. const row = Math.min(range.start.row, range.end.row);
  232. const col = Math.min(range.start.col, range.end.col);
  233. const hit = revealHits.current.find(({ item }) => inside(item, sheetName, row, col));
  234. if (hit && callbacks.current.onRevealHit?.(hit.index)) user = false;
  235. }
  236. const detail = {
  237. text: false,
  238. locate: () => (pressed ? pressBox(rootRef.current, pressed) : null),
  239. user,
  240. };
  241. void rangeText(controller, range).then(
  242. (text) => current && callbacks.current.onSelect({ at, text }, detail),
  243. () => current && callbacks.current.onSelect({ at, text: "" }, detail),
  244. );
  245. return () => {
  246. current = false;
  247. };
  248. }, [selectionKey, sheetName, presses]);
  249. useEffect(() => {
  250. const root = rootRef.current!;
  251. const unguard = installLinkGuard(root, (url) => callbacks.current.onLink(url));
  252. const inGrid = (event: Event) => Boolean((event.target as Element).closest?.(".xlsx-grid"));
  253. let pressing = false;
  254. const act = (event: PointerEvent) => {
  255. if (!inGrid(event)) return;
  256. pressing = true;
  257. const point = { x: event.clientX, y: event.clientY };
  258. acted.current = {
  259. time: performance.now(),
  260. press: { start: point, end: point, surface: boxOf(gridCanvas(root)) },
  261. };
  262. };
  263. const release = (event: PointerEvent) => {
  264. if (!pressing || !acted.current.press) return;
  265. pressing = false;
  266. acted.current = {
  267. time: performance.now(),
  268. press: { ...acted.current.press, end: { x: event.clientX, y: event.clientY } },
  269. };
  270. setPresses((count) => count + 1);
  271. };
  272. const key = (event: KeyboardEvent) => {
  273. if (inGrid(event)) acted.current = { time: performance.now(), press: null };
  274. };
  275. root.addEventListener("pointerdown", act, true);
  276. root.addEventListener("pointerup", release, true);
  277. root.addEventListener("keydown", key, true);
  278. return () => {
  279. unguard();
  280. root.removeEventListener("pointerdown", act, true);
  281. root.removeEventListener("pointerup", release, true);
  282. root.removeEventListener("keydown", key, true);
  283. };
  284. }, []);
  285. const getCellStyle = useCallback(
  286. (context: XlsxCellStyleContext): CSSProperties | undefined => {
  287. const { row, col } = context.cell;
  288. const current = found.items[found.current];
  289. if (current && inside(current, context.sheetName, row, col)) return FIND_CURRENT_STYLE;
  290. if (found.items.some((item) => inside(item, context.sheetName, row, col))) return FIND_STYLE;
  291. if (revealed.some((item) => inside(item, context.sheetName, row, col))) return REVEAL_STYLE;
  292. return undefined;
  293. },
  294. [revealed, found],
  295. );
  296. function tabIndexFor(name: string): number {
  297. const tabs = controllerRef.current.tabs;
  298. const exact = tabs.findIndex((tab) => tab.name === name);
  299. return exact >= 0
  300. ? exact
  301. : tabs.findIndex((tab) => tab.name.toLowerCase() === name.toLowerCase());
  302. }
  303. const waitFrame = () =>
  304. new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
  305. useImperativeHandle(
  306. ref,
  307. (): ViewerHandle => ({
  308. async reveal(targets) {
  309. const next: Highlight[] = [];
  310. const results: RevealedTarget[] = [];
  311. revealHits.current = [];
  312. for (const target of targets) {
  313. const locator = parseLocator("xlsx", target.at);
  314. if (locator.kind !== "xlsx") continue;
  315. const tab = tabIndexFor(locator.sheet);
  316. if (tab < 0) continue;
  317. const name = controllerRef.current.tabs[tab].name;
  318. const item: Highlight | null = locator.range
  319. ? {
  320. sheet: name,
  321. top: locator.range.start.row - 1,
  322. left: locator.range.start.col - 1,
  323. bottom: locator.range.end.row - 1,
  324. right: locator.range.end.col - 1,
  325. }
  326. : null;
  327. if (item) {
  328. next.push(item);
  329. revealHits.current.push({ item, index: results.length });
  330. }
  331. const show = async () => {
  332. if (tab !== controllerRef.current.activeTabIndex) {
  333. controllerRef.current.setActiveTabIndex(tab);
  334. await waitFrame();
  335. }
  336. if (item)
  337. controllerRef.current.selectRange({
  338. start: { row: item.top, col: item.left },
  339. end: { row: item.bottom, col: item.right },
  340. });
  341. };
  342. // Cells are drawn on canvas: the callout docks at the top of the sheet.
  343. results.push({ at: target.at, locate: () => null, scrollTo: () => void show() });
  344. }
  345. setRevealed(next);
  346. if (results[0]) {
  347. results[0].scrollTo();
  348. await waitFrame();
  349. }
  350. return results;
  351. },
  352. goTo(at) {
  353. const locator = parseLocator("xlsx", at);
  354. if (locator.kind !== "xlsx") return;
  355. const tab = tabIndexFor(locator.sheet);
  356. if (tab >= 0 && tab !== controllerRef.current.activeTabIndex)
  357. controllerRef.current.setActiveTabIndex(tab);
  358. },
  359. clearReveal() {
  360. revealHits.current = [];
  361. setRevealed([]);
  362. },
  363. async capture(at, maxWidth) {
  364. if (at) {
  365. await this.reveal([{ at }]);
  366. await waitFrame();
  367. await waitFrame();
  368. }
  369. const root = rootRef.current!;
  370. const raster = await rasterize(root, {
  371. maxWidth,
  372. background: props.dark ? "#1e1e1e" : "#fff",
  373. });
  374. const active = controllerRef.current;
  375. const name = active.activeSheet?.name ?? "";
  376. return {
  377. ...raster,
  378. at:
  379. at ??
  380. (active.activeCell
  381. ? `${formatLocator({ kind: "xlsx", sheet: name })}!${formatCell({ row: active.activeCell.row + 1, col: active.activeCell.col + 1 })}`
  382. : formatLocator({ kind: "xlsx", sheet: name })),
  383. };
  384. },
  385. zoom(direction) {
  386. if (direction > 0) controllerRef.current.zoomIn();
  387. else controllerRef.current.zoomOut();
  388. },
  389. fit() {
  390. controllerRef.current.resetZoom();
  391. },
  392. async find(query) {
  393. const needle = query.trim().toLowerCase();
  394. const active = controllerRef.current;
  395. const sheet = active.activeSheet;
  396. if (!needle || !sheet) {
  397. setFound({ items: [], current: -1 });
  398. return 0;
  399. }
  400. const items: Highlight[] = [];
  401. const lastRow = Math.min(sheet.maxUsedRow, sheet.minUsedRow + 2000);
  402. const lastCol = Math.min(sheet.maxUsedCol, sheet.minUsedCol + 100);
  403. for (let row = sheet.minUsedRow; row <= lastRow && items.length < 500; row++) {
  404. const values = await Promise.all(
  405. Array.from({ length: lastCol - sheet.minUsedCol + 1 }, (_, i) =>
  406. cellSnapshot(active, row, sheet.minUsedCol + i),
  407. ),
  408. );
  409. values.forEach(({ displayValue }, i) => {
  410. const col = sheet.minUsedCol + i;
  411. if (displayValue.toLowerCase().includes(needle))
  412. items.push({ sheet: sheet.name, top: row, left: col, bottom: row, right: col });
  413. });
  414. }
  415. setFound({ items, current: -1 });
  416. return items.length;
  417. },
  418. findGo(index) {
  419. const item = foundRef.current.items[index];
  420. if (!item) return;
  421. setFound((state) => ({ ...state, current: index }));
  422. controllerRef.current.selectCell({ row: item.top, col: item.left });
  423. },
  424. clearFind() {
  425. setFound({ items: [], current: -1 });
  426. },
  427. clearSelection() {},
  428. }),
  429. [props.dark],
  430. );
  431. return (
  432. <div ref={rootRef} className={`xlsx-root${props.glance ? " glance" : ""}`}>
  433. <div className="xlsx-grid">
  434. <XlsxViewer
  435. controller={controller}
  436. height="100%"
  437. isDark={props.dark}
  438. readOnly
  439. rounded={false}
  440. showDefaultToolbar={false}
  441. getCellStyle={getCellStyle}
  442. loadingState={<div className="viewer-pending" aria-busy="true" />}
  443. />
  444. </div>
  445. <SheetTabs controller={controller} />
  446. </div>
  447. );
  448. });