Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Spreadsheet.tsx

588 lines21.0 KB

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