Open History to see the last commit
1import * as Schema from "effect/Schema";
2import { observeResize } from "~/lib/observeResize";
3import { useEffect, useRef, useState } from "react";
4import {
5 cellAtPoint,
6 normalizeRange,
7 selectionAt,
8 selectionKeyReducer,
9 extendTo,
10 hyperlinkAtCell,
11 safeExternalHyperlink,
12 parseHyperlinkLocation,
13 type Selection,
14 type CellAddr,
15} from "@betteroffice/xlsx/headless";
16import { FileSurfaceLoading, FileSurfaceNotice } from "../fileSurfaceChrome";
17import { createWorkerClient, SupersededError } from "./worker-rpc";
18import type { SheetLayout, SheetMethods, SheetFrameRequest, SheetTab } from "./sheet-protocol";
19import {
20 coverMerges,
21 contains,
22 lastCell,
23 settleMerges,
24 skipHidden,
25 columnName,
26} from "./sheet-cells";
27import {
28 paintCells,
29 paintHeaders,
30 paintSelection,
31 shiftGrid,
32 headerHeight,
33 type Painted,
34} from "./sheet-paint";
35import { externalUrl } from "./links";
36
37const isSupersededError = Schema.is(SupersededError);
38
39type Client = ReturnType<typeof createWorkerClient<SheetMethods>>;
40type Opened = {
41 engine: Client;
42 tabs: readonly SheetTab[];
43 layout: SheetLayout;
44 target?: CellAddr | undefined;
45};
46export default function Spreadsheet(props: {
47 bytes: ArrayBuffer;
48 onDetails: (text: string) => void;
49 onError: (cause: unknown) => void;
50}) {
51 const { onError, bytes: source, onDetails } = props;
52 const [opened, setOpened] = useState<Opened>();
53 const [error, setError] = useState("");
54 const picking = useRef<AbortController | null>(null);
55 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Open the workbook worker and cancel workbook and sheet requests when the source changes or unmounts.
56 useEffect(() => {
57 const controller = new AbortController();
58 const worker = new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), {
59 type: "module",
60 });
61 const engine = createWorkerClient<SheetMethods>(worker);
62 const fail = (cause: unknown) => {
63 if (!controller.signal.aborted) onError(cause);
64 };
65 worker.addEventListener("error", fail);
66 worker.addEventListener("messageerror", fail);
67 const bytes = source.slice(0);
68 void engine
69 .call("open", { bytes }, { transfer: [bytes], signal: controller.signal })
70 .then((value) => {
71 if (!value) throw new Error("This workbook has no visible sheets.");
72 setOpened({ ...value, engine });
73 onDetails(`${value.tabs.length} sheets`);
74 })
75 .catch(fail);
76 return () => {
77 controller.abort();
78 picking.current?.abort();
79 engine.close();
80 };
81 }, [source, onDetails, onError]);
82 const show = (sheet: number, target?: CellAddr) => {
83 if (!opened) return;
84 picking.current?.abort();
85 if (sheet === opened.layout.info.activeSheet) return;
86 const controller = new AbortController();
87 picking.current = controller;
88 void opened.engine
89 .call("show", { sheet }, { signal: controller.signal })
90 .then((layout) => {
91 setError("");
92 setOpened({ ...opened, layout, target });
93 })
94 .catch(() => {
95 if (!controller.signal.aborted) setError("This sheet could not be opened.");
96 });
97 };
98 if (!opened) return <FileSurfaceLoading />;
99 return (
100 <div className="flex min-h-0 flex-1 flex-col">
101 {error ? <FileSurfaceNotice>{error}</FileSurfaceNotice> : null}
102 <SpreadsheetGrid
103 key={opened.layout.info.activeSheet}
104 engine={opened.engine}
105 layout={opened.layout}
106 initialCell={opened.target}
107 onNavigate={(name, cell) => {
108 const tab = opened.tabs.find((tab) => tab.name.toLowerCase() === name.toLowerCase());
109 if (tab) show(tab.index, cell);
110 }}
111 />
112 <div
113 role="tablist"
114 aria-label="Sheets"
115 className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-t border-border px-2"
116 onKeyDown={(event) => {
117 const current = opened.tabs.findIndex(
118 (tab) => tab.index === opened.layout.info.activeSheet,
119 );
120 const next =
121 event.key === "ArrowRight"
122 ? (current + 1) % opened.tabs.length
123 : event.key === "ArrowLeft"
124 ? (current + opened.tabs.length - 1) % opened.tabs.length
125 : event.key === "Home"
126 ? 0
127 : event.key === "End"
128 ? opened.tabs.length - 1
129 : -1;
130 if (next < 0) return;
131 event.preventDefault();
132 const tab = opened.tabs[next];
133 if (tab) show(tab.index);
134 event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')[next]?.focus();
135 }}
136 >
137 {opened.tabs.map((tab) => (
138 <button
139 key={tab.index}
140 type="button"
141 role="tab"
142 aria-selected={tab.index === opened.layout.info.activeSheet}
143 tabIndex={tab.index === opened.layout.info.activeSheet ? 0 : -1}
144 onClick={() => show(tab.index)}
145 className="h-7 shrink-0 rounded-md px-2.5 text-xs text-muted-foreground hover:bg-accent aria-selected:bg-accent aria-selected:text-foreground"
146 >
147 {tab.name}
148 </button>
149 ))}
150 </div>
151 </div>
152 );
153}
154
155function SpreadsheetGrid(props: {
156 engine: Client;
157 layout: SheetLayout;
158 initialCell: CellAddr | undefined;
159 onNavigate: (sheet: string, cell: CellAddr) => void;
160}) {
161 const { onNavigate, layout, engine, initialCell } = props;
162 const scroller = useRef<HTMLDivElement>(null);
163 const canvas = useRef<HTMLCanvasElement>(null);
164 const spacer = useRef<HTMLDivElement>(null);
165 const [notice, setNotice] = useState("");
166 const [reader, setReader] = useState<{ row: number; col: number; text: string }[]>([]);
167 const [active, setActive] = useState({ row: 0, col: 0 });
168 const navigate = useRef(onNavigate);
169 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Keep the installed native pointer listener calling the latest navigation handler without restarting the canvas engine.
170 useEffect(() => {
171 navigate.current = onNavigate;
172 }, [onNavigate]);
173 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own canvas painting, worker requests, resize observation, and native scroll, keyboard, and pointer listeners for this sheet.
174 useEffect(() => {
175 const root = scroller.current;
176 const target = canvas.current;
177 const space = spacer.current;
178 if (!root || !target || !space) return;
179 const context = target.getContext("2d");
180 if (!context) return;
181 const controller = new AbortController();
182 const info = layout.info;
183 const sheet = info.activeSheet;
184 const frozen = { rows: info.frozenRows, cols: info.frozenCols };
185 const headers = { width: 44, height: headerHeight };
186 let selection: Selection = selectionAt(initialCell ?? { row: 0, col: 0 });
187 let painted: Painted | undefined;
188 let grid: ReturnType<typeof shiftGrid> | undefined;
189 let raf = 0;
190 let requested = "";
191 let sent = 0;
192 let received = 0;
193 let drag = false;
194 let header: "row" | "column" | "all" | undefined;
195 let pressed: { row: number; col: number } | undefined;
196 let end: { x: number; y: number } | undefined;
197 let left = info.initialScrollX;
198 let top = info.initialScrollY;
199 let reachX = 0;
200 let reachY = 0;
201 let readController: AbortController | undefined;
202 const range = () => coverMerges(normalizeRange(selection), layout.merges);
203 const at = (cell: { row: number; col: number }) => {
204 const merge = layout.merges.find((item) => contains(item, cell));
205 return selectionAt(merge ? { row: merge.top, col: merge.left } : cell);
206 };
207 const schedule = () => {
208 if (raf || controller.signal.aborted) return;
209 raf = requestAnimationFrame(() => {
210 raf = 0;
211 paint();
212 });
213 };
214 const resizeArea = () => {
215 const width = Math.min(
216 (end?.x ?? Infinity) + (painted?.frame.frozen.width ?? 0),
217 Math.max(info.contentWidth, layout.chartWidth, reachX, left + root.clientWidth) +
218 root.clientWidth,
219 );
220 const height = Math.min(
221 (end?.y ?? Infinity) + (painted?.frame.frozen.height ?? 0),
222 Math.max(info.contentHeight, layout.chartHeight, reachY, top + root.clientHeight) +
223 root.clientHeight,
224 );
225 space.style.width = `${headers.width + width}px`;
226 space.style.height = `${headers.height + height}px`;
227 };
228 const paint = () => {
229 const ratio = window.devicePixelRatio || 1;
230 const width = root.clientWidth;
231 const height = root.clientHeight;
232 const size = { width: width - headers.width, height: height - headers.height };
233 if (size.width <= 0 || size.height <= 0) return;
234 left = root.scrollLeft;
235 top = root.scrollTop;
236 resizeArea();
237 const input: SheetFrameRequest = {
238 sheet,
239 x: left,
240 y: top,
241 ...size,
242 ratio,
243 offset: { x: 0, y: 0 },
244 wider: undefined,
245 };
246 const key = JSON.stringify(input);
247 if (key !== requested) {
248 requested = key;
249 sent += 1;
250 const order = sent;
251 void engine
252 .call("frame", input, { key: "frame", signal: controller.signal })
253 .then((reply) => {
254 if (order < received || controller.signal.aborted) {
255 reply?.bitmap.close();
256 return;
257 }
258 received = order;
259 if (!reply) {
260 setNotice("These cells could not be drawn. Try scrolling to another area.");
261 return;
262 }
263 setNotice("");
264 painted?.frame.bitmap.close();
265 painted = { request: input, frame: reply };
266 end = reply.end;
267 schedule();
268 })
269 .catch((cause: unknown) => {
270 if (!isSupersededError(cause) && !controller.signal.aborted)
271 setNotice("These cells could not be drawn.");
272 });
273 }
274 if (
275 target.width !== Math.round(width * ratio) ||
276 target.height !== Math.round(height * ratio)
277 ) {
278 target.width = Math.round(width * ratio);
279 target.height = Math.round(height * ratio);
280 target.style.width = `${width}px`;
281 target.style.height = `${height}px`;
282 }
283 if (!painted) {
284 context.fillStyle = "#fff";
285 context.fillRect(0, 0, target.width, target.height);
286 return;
287 }
288 paintCells(context, painted, { ratio, headers, x: left, y: top, ...size });
289 grid =
290 painted.frame.grid &&
291 shiftGrid(painted.frame.grid, frozen, painted.frame.frozen, {
292 x: painted.frame.viewport.x - left,
293 y: painted.frame.viewport.y - top,
294 });
295 if (!grid) return;
296 const anchor = selection.anchor;
297 paintSelection(context, {
298 grid,
299 ratio,
300 headers,
301 ...size,
302 range: range(),
303 active: coverMerges(
304 { top: anchor.row, left: anchor.col, bottom: anchor.row, right: anchor.col },
305 layout.merges,
306 ),
307 });
308 paintHeaders(context, { grid, ratio, headers, width, height, selected: range() });
309 };
310 const read = () => {
311 const focus = selection.focus;
312 setActive(focus);
313 readController?.abort();
314 readController = new AbortController();
315 const top = Math.max(0, focus.row - 5);
316 const left = Math.max(0, focus.col - 3);
317 const range = {
318 top,
319 left,
320 bottom: Math.min(lastCell.row, top + 10),
321 right: Math.min(lastCell.col, left + 6),
322 };
323 void engine
324 .call("cells", { sheet, range }, { key: "reader", signal: readController.signal })
325 .then((rows) => {
326 if (!controller.signal.aborted)
327 setReader(
328 rows.flatMap((row, r) =>
329 row.map((text, c) => ({ row: top + r, col: left + c, text })),
330 ),
331 );
332 })
333 .catch(() => undefined);
334 };
335 const select = (next: Selection) => {
336 selection = next;
337 read();
338 schedule();
339 };
340 const reveal = () => {
341 const cell = selection.focus;
342 void engine
343 .call("position", { sheet, cell }, { key: "position", signal: controller.signal })
344 .then((position) => {
345 if (!position || controller.signal.aborted) return;
346 const panes = painted?.frame.frozen ?? { width: 0, height: 0 };
347 const place = (start: number, next: number, current: number, visible: number) =>
348 start < current ? start : next > current + visible ? next - visible : current;
349 const x =
350 cell.col < info.frozenCols
351 ? left
352 : place(
353 position.start.x,
354 position.next.x,
355 left,
356 root.clientWidth - headers.width - panes.width,
357 );
358 const y =
359 cell.row < info.frozenRows
360 ? top
361 : place(
362 position.start.y,
363 position.next.y,
364 top,
365 root.clientHeight - headers.height - panes.height,
366 );
367 reachX = Math.max(reachX, x + root.clientWidth);
368 reachY = Math.max(reachY, y + root.clientHeight);
369 resizeArea();
370 root.scrollTo({ left: Math.max(0, x), top: Math.max(0, y) });
371 schedule();
372 })
373 .catch(() => undefined);
374 };
375 const hit = (event: PointerEvent) => {
376 if (!grid) return;
377 const rect = target.getBoundingClientRect();
378 const x = event.clientX - rect.left - headers.width;
379 const y = event.clientY - rect.top - headers.height;
380 const frame = painted?.frame;
381 if (
382 frame &&
383 ((x >= frame.frozen.width && x < frame.frozen.width + frame.viewport.x - left) ||
384 (y >= frame.frozen.height && y < frame.frozen.height + frame.viewport.y - top))
385 )
386 return;
387 const cell = cellAtPoint(
388 grid,
389 Math.max(0, Math.min(x, root.clientWidth - headers.width - 1)),
390 Math.max(0, Math.min(y, root.clientHeight - headers.height - 1)),
391 );
392 return cell ? { cell, x, y } : undefined;
393 };
394 const pointerDown = (event: PointerEvent) => {
395 if (event.button !== 0) return;
396 const found = hit(event);
397 if (!found) return;
398 root.focus({ preventScroll: true });
399 root.setPointerCapture(event.pointerId);
400 drag = true;
401 header = found.x < 0 ? (found.y < 0 ? "all" : "row") : found.y < 0 ? "column" : undefined;
402 pressed = header ? undefined : found.cell;
403 if (found.x < 0 && found.y < 0)
404 select({ anchor: { row: lastCell.row, col: lastCell.col }, focus: { row: 0, col: 0 } });
405 else if (found.x < 0)
406 select({
407 anchor: { row: found.cell.row, col: lastCell.col },
408 focus: { row: found.cell.row, col: 0 },
409 });
410 else if (found.y < 0)
411 select({
412 anchor: { row: lastCell.row, col: found.cell.col },
413 focus: { row: 0, col: found.cell.col },
414 });
415 else select(event.shiftKey ? extendTo(selection, found.cell) : at(found.cell));
416 };
417 const pointerMove = (event: PointerEvent) => {
418 if (!drag) return;
419 const found = hit(event);
420 if (found && header !== "all")
421 select(
422 extendTo(selection, {
423 row: header === "column" ? 0 : found.cell.row,
424 col: header === "row" ? 0 : found.cell.col,
425 }),
426 );
427 };
428 const pointerUp = (event: PointerEvent) => {
429 drag = false;
430 const found = hit(event);
431 if (!found || !pressed || found.cell.row !== pressed.row || found.cell.col !== pressed.col)
432 return;
433 const cell = at(found.cell).anchor;
434 const list = painted?.frame;
435 if (!list) return;
436 const link = hyperlinkAtCell(
437 { width: 0, height: 0, commands: [], hyperlinks: [...list.hyperlinks] },
438 cell.row,
439 cell.col,
440 );
441 if (!link) return;
442 const url = safeExternalHyperlink(link);
443 const safe = url && externalUrl(url);
444 if (safe) {
445 window.open(safe, "_blank", "noopener,noreferrer");
446 return;
447 }
448 const internal =
449 link.location && parseHyperlinkLocation(link.location, info.sheetNames[sheet] ?? "");
450 if (!internal) return;
451 if (internal.sheetName.toLowerCase() !== (info.sheetNames[sheet] ?? "").toLowerCase())
452 navigate.current(internal.sheetName, { row: internal.row, col: internal.col });
453 else {
454 select(at({ row: internal.row, col: internal.col }));
455 reveal();
456 }
457 };
458 const copy = () => {
459 const used = layout.used;
460 const selected = range();
461 const clipped = {
462 ...selected,
463 bottom: Math.min(selected.bottom, Math.max(selected.top, used?.bottom ?? 0)),
464 right: Math.min(selected.right, Math.max(selected.left, used?.right ?? 0)),
465 };
466 if ((clipped.bottom - clipped.top + 1) * (clipped.right - clipped.left + 1) > 200_000) {
467 setNotice("Select fewer than 200,000 cells to copy.");
468 return;
469 }
470 void engine
471 .call("copy", { sheet, range: clipped }, { signal: controller.signal })
472 .then((text) => {
473 if (text === undefined) throw new Error("No cells");
474 return navigator.clipboard.writeText(text);
475 })
476 .catch(() => {
477 if (!controller.signal.aborted) setNotice("The selected cells could not be copied.");
478 });
479 };
480 const key = (event: KeyboardEvent) => {
481 const command = event.ctrlKey || event.metaKey;
482 if (command && event.key.toLowerCase() === "c") {
483 event.preventDefault();
484 copy();
485 return;
486 }
487 if (event.key === "Tab" || event.altKey || event.isComposing) return;
488 const action = selectionKeyReducer(selection, event, {
489 rows: Math.max((layout.used?.bottom ?? 0) + 1, selection.focus.row + 1),
490 cols: Math.max((layout.used?.right ?? 0) + 1, selection.focus.col + 1),
491 rowsPerPage: Math.max(1, Math.floor((root.clientHeight - headerHeight) / 20)),
492 });
493 if (action.type !== "move") return;
494 event.preventDefault();
495 select(
496 skipHidden(
497 selection.focus,
498 settleMerges(selection, action.selection, layout.merges),
499 layout.hidden,
500 ),
501 );
502 reveal();
503 };
504 const cancel = () => {
505 drag = false;
506 };
507 root.addEventListener("scroll", schedule);
508 root.addEventListener("keydown", key);
509 root.addEventListener("pointerdown", pointerDown);
510 root.addEventListener("pointermove", pointerMove);
511 root.addEventListener("pointerup", pointerUp);
512 root.addEventListener("pointercancel", cancel);
513 const unobserve = observeResize(root, schedule);
514 window.addEventListener("resize", schedule);
515 resizeArea();
516 root.scrollTo({ left, top });
517 if (initialCell) {
518 selection = at(initialCell);
519 reveal();
520 }
521 read();
522 schedule();
523 return () => {
524 controller.abort();
525 readController?.abort();
526 cancelAnimationFrame(raf);
527 unobserve();
528 window.removeEventListener("resize", schedule);
529 painted?.frame.bitmap.close();
530 root.removeEventListener("scroll", schedule);
531 root.removeEventListener("keydown", key);
532 root.removeEventListener("pointerdown", pointerDown);
533 root.removeEventListener("pointermove", pointerMove);
534 root.removeEventListener("pointerup", pointerUp);
535 root.removeEventListener("pointercancel", cancel);
536 };
537 }, [engine, layout, initialCell]);
538 return (
539 <div className="relative flex min-h-0 flex-1">
540 <div
541 ref={scroller}
542 dir="ltr"
543 tabIndex={0}
544 role="grid"
545 aria-label={layout.info.sheetNames[layout.info.activeSheet]}
546 aria-readonly="true"
547 aria-multiselectable="true"
548 aria-rowcount={lastCell.row + 1}
549 aria-colcount={lastCell.col + 1}
550 aria-activedescendant={`office-cell-${active.row}-${active.col}`}
551 className="relative min-h-0 min-w-0 flex-1 select-none overflow-auto bg-white outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
552 >
553 <div
554 ref={spacer}
555 aria-hidden="true"
556 className="pointer-events-none absolute left-0 top-0"
557 />
558 <div aria-hidden="true" className="sticky left-0 top-0 h-0 w-0">
559 <canvas ref={canvas} className="absolute left-0 top-0 block" />
560 </div>
561 <div className="sr-only">
562 {[...new Set(reader.map((cell) => cell.row))].map((row) => (
563 <div key={row} role="row" aria-rowindex={row + 1}>
564 {reader
565 .filter((cell) => cell.row === row)
566 .map((cell) => (
567 <span
568 key={cell.col}
569 role="gridcell"
570 id={`office-cell-${cell.row}-${cell.col}`}
571 aria-colindex={cell.col + 1}
572 aria-label={`${columnName(cell.col)}${cell.row + 1}`}
573 >
574 {cell.text}
575 </span>
576 ))}
577 </div>
578 ))}
579 </div>
580 </div>
581 {notice ? (
582 <div
583 role="status"
584 className="absolute inset-x-3 bottom-3 rounded-md bg-background p-2 text-xs text-foreground shadow-md"
585 >
586 {notice}
587 </div>
588 ) : null}
589 </div>
590 );
591}