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

spreadsheet.worker.ts

309 lines10.1 KB

1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import {
3 initWasm,
4 openWorkbook,
5 toTsv,
6 type SheetInfo,
7 type WorkbookHandle,
8 type XlsxCellRead,
9 type XlsxRangeTarget,
10} from "@betteroffice/xlsx";
11import type { CellRange } from "@betteroffice/xlsx/headless";
12import { anchorRange, attempt, lastCell, parseRange, parseSpans } from "./sheet-cells";
13import { drawFrame, paintFrame } from "./sheet-frame";
14import { frozenSize } from "./sheet-paint";
15import type { SheetLayout, SheetMethods, SheetTab } from "./sheet-protocol";
16import { serveWorker, Transfer } from "./worker-rpc";
17​
18// One worker holds one open workbook: its engine, recalculation, display lists and the painting of its cells. The
19// window terminates the worker when the workbook closes, which is the only way the engine's memory is given back.
20​
21type Opened = {
22 readonly workbook: WorkbookHandle;
23 /** The active sheet's metadata; the engine draws only the active sheet. */
24 info: SheetInfo;
25 /** Where each sheet's last cell ends, by sheet and frozen panes' size; measured once, as it costs a frame. */
26 readonly ends: Map<string, { readonly x: number; readonly y: number } | undefined>;
27 /** The one canvas every frame paints on and hands over as a bitmap. */
28 readonly surface: OffscreenCanvas;
29};
30​
31/** The workbook this worker opened, once it has. */
32type State = { opened: Opened | undefined };
33​
34const state: State = { opened: undefined };
35​
36serveWorker<SheetMethods>({
37 open: async (input) => {
38 if (state.opened) throw new Error("The worker already holds a workbook");
39​
40 await initWasm();
41​
42 const workbook = openWorkbook(new Uint8Array(input.bytes));
43 const info = workbook.sheetInfo();
44​
45 state.opened = { workbook, info, ends: new Map(), surface: new OffscreenCanvas(1, 1) };
46​
47 const tabs = visibleTabs(workbook, info);
48 // A workbook saved on a hidden sheet opens on the first visible one, as Excel does.
49 const first = tabs.find((tab) => tab.index === info.activeSheet) ?? tabs[0];
50​
51 if (!first) return undefined;
52​
53 return { tabs, layout: show(state.opened, first.index) };
54 },
55 show: (input) => {
56 const opened = required();
57 const current = opened.info.activeSheet;
58 const layout = attempt(() => show(opened, input.sheet));
59​
60 if (layout) return layout;
61​
62 // One sheet that fails to open leaves the others readable: go back to the sheet on show.
63 attempt(() => show(opened, current));
64​
65 throw new Error(`Sheet ${input.sheet} could not open`);
66 },
67 frame: (input) => {
68 const opened = active(input.sheet);
69 const frozen = { rows: opened.info.frozenRows, cols: opened.info.frozenCols };
70 const viewport = { x: input.x, y: input.y, width: input.width, height: input.height };
71 const drawn = drawFrame(opened.workbook, viewport, frozen, input.wider);
72​
73 if (!drawn) return undefined;
74​
75 const surface = opened.surface;
76 const width = Math.ceil(input.offset.x + drawn.viewport.width * input.ratio);
77 const height = Math.ceil(input.offset.y + drawn.viewport.height * input.ratio);
78​
79 if (surface.width !== width) surface.width = width;
80​
81 if (surface.height !== height) surface.height = height;
82​
83 const context = surface.getContext("2d");
84​
85 if (!context) return undefined;
86​
87 paintFrame(context, drawn, { ratio: input.ratio, origin: input.offset });
88​
89 const bitmap = surface.transferToImageBitmap();
90 const grid = drawn.list.grid;
91 const panes = frozenSize(grid, frozen);
92​
93 return new Transfer(
94 {
95 bitmap,
96 viewport: drawn.viewport,
97 grid,
98 hyperlinks: drawn.list.hyperlinks ?? [],
99 frozen: panes,
100 end: end(opened, input.sheet, panes),
101 },
102 [bitmap],
103 );
104 },
105 position: (input) => {
106 const workbook = required().workbook;
107 const cell = input.cell;
108 const start = attempt(() => workbook.cellPosition(input.sheet, cell.row, cell.col));
109​
110 const next = attempt(() =>
111 workbook.cellPosition(
112 input.sheet,
113 Math.min(cell.row + 1, lastCell.row),
114 Math.min(cell.col + 1, lastCell.col),
115 ),
116 );
117​
118 return start && next ? { start, next } : undefined;
119 },
120 cells: (input) => {
121 const cells = read(required(), input.sheet, input.range);
122 const range = input.range;
123​
124 return Array.from({ length: range.bottom - range.top + 1 }, (_, row) =>
125 Array.from(
126 { length: range.right - range.left + 1 },
127 (_, col) => cells?.[row]?.[col]?.displayText ?? "",
128 ),
129 );
130 },
131 // Copies the cells as they show, which is what a reader expects to paste, not the formulas behind them.
132 copy: (input) => {
133 const cells = read(required(), input.sheet, input.range);
134​
135 if (!cells) return undefined;
136​
137 return toTsv(
138 cells.map((row) =>
139 row.map((cell) => ({ input: cell.displayText, isFormula: literal(cell) })),
140 ),
141 );
142 },
143});
144​
145function required() {
146 if (!state.opened) throw new Error("The worker holds no workbook");
147​
148 return state.opened;
150​
151/** The workbook with `sheet` active, as a frame from a grid that has since given way to another sheet may ask. */
152function active(sheet: number) {
153 const opened = required();
154​
155 if (opened.info.activeSheet !== sheet) show(opened, sheet);
156​
157 return opened;
159​
160/** Makes a sheet the active one and reads what its grid needs. */
161function show(opened: Opened, sheet: number): SheetLayout {
162 opened.workbook.setActiveSheet(sheet);
163 opened.info = opened.workbook.sheetInfo();
164​
165 return { info: opened.info, ...layout(opened.workbook, sheet) };
167​
168/**
169 * The used range, the merged cells, the hidden rows and columns, and how far the charts reach, from one export of the
170 * sheet's metadata. One cell is enough: the lists before the cells are complete however soon the export stops.
171 */
172function layout(workbook: WorkbookHandle, sheet: number) {
173 const result = attempt(() =>
174 workbook.exportStructured({
175 scope: [{ sheet, range: "A1:XFD1048576" }],
176 maxCells: 1,
177 includeDefinedNames: false,
178 }),
179 );
180​
181 const exported = result?.ok ? result.content.sheets[0] : undefined;
182​
183 const charts = (exported?.objects ?? [])
184 .filter((object) => object.kind === "chart" && !object.hidden)
185 .flatMap((object) => (object.anchor ? anchorRange(object.anchor) : []))
186 // The corner cell holds the chart's edge somewhere inside it, so the cell past it bounds the chart.
187 .flatMap((range) => {
188 const corner = attempt(() =>
189 workbook.cellPosition(
190 sheet,
191 Math.min(range.bottom + 1, lastCell.row),
192 Math.min(range.right + 1, lastCell.col),
193 ),
194 );
195​
196 return corner ? [corner] : [];
197 });
198​
199 return {
200 used: exported?.usedRange ? parseRange(exported.usedRange) : undefined,
201 merges: (exported?.merges ?? []).flatMap((merge) => anchorRange(merge.anchor)),
202 hidden: {
203 rows: parseSpans(exported?.hiddenRows ?? [], "rows"),
204 columns: parseSpans(exported?.hiddenColumns ?? [], "columns"),
205 },
206 chartWidth: Math.max(0, ...charts.map((corner) => corner.x)),
207 chartHeight: Math.max(0, ...charts.map((corner) => corner.y)),
208 };
210​
211/** Where the sheet's last cell ends, past the frozen panes. A viewport past it makes the engine throw. */
212function end(
213 opened: Opened,
214 sheet: number,
215 frozen: { readonly width: number; readonly height: number },
216) {
217 const key = `${sheet}:${frozen.width}:${frozen.height}`;
218​
219 if (opened.ends.has(key)) return opened.ends.get(key);
220​
221 const measured = measureEnd(opened.workbook, sheet, frozen);
222​
223 opened.ends.set(key, measured);
224​
225 return measured;
227​
228function measureEnd(
229 workbook: WorkbookHandle,
230 sheet: number,
231 frozen: { readonly width: number; readonly height: number },
232) {
233 const last = attempt(() => workbook.cellPosition(sheet, lastCell.row, lastCell.col));
234​
235 if (!last) return undefined;
236​
237 // A viewport one pixel past the frozen panes, on the last cell, reports where that cell ends.
238 const grid = attempt(
239 () =>
240 workbook.displayList({
241 x: last.x,
242 y: last.y,
243 width: frozen.width + 1,
244 height: frozen.height + 1,
245 }).grid,
246 );
247​
248 // The engine works in single precision there, so stay a little short of the edge.
249 const margin = 2;
250​
251 return {
252 x:
253 last.x +
254 Math.max(0, (grid ? (grid.colOffsets[grid.colOffsets.length - 1] ?? 0) : 0) - frozen.width) -
255 margin,
256 y:
257 last.y +
258 Math.max(0, (grid ? (grid.rowOffsets[grid.rowOffsets.length - 1] ?? 0) : 0) - frozen.height) -
259 margin,
260 };
262​
263/** The cells of a range on a sheet as the engine reads them, row by row; undefined when it cannot. */
264function read(opened: Opened, sheet: number, range: CellRange) {
265 if ((range.bottom - range.top + 1) * (range.right - range.left + 1) > 200_000) return undefined;
266 const target: XlsxRangeTarget = {
267 sheetId: opened.info.sheetIds[sheet]!,
268 range: {
269 kind: "rowCol",
270 start: { row: range.top, col: range.left },
271 end: { row: range.bottom, col: range.right },
272 },
273 };
274​
275 const result = attempt(() => opened.workbook.readCells({ ranges: [target] }));
276​
277 return result?.ok ? result.ranges[0]?.cells : undefined;
279​
280/** The workbook's sheets but its hidden and very hidden ones, which Excel lists only to unhide. */
281function visibleTabs(workbook: WorkbookHandle, info: SheetInfo): SheetTab[] {
282 const names = info.sheetNames;
283​
284 const result = attempt(() =>
285 workbook.exportStructured({
286 includeHiddenSheets: true,
287 includeDefinedNames: false,
288 scope: names.map((_, sheet) => ({ sheet, range: "A1" })),
289 }),
290 );
291​
292 const hidden = new Set(
293 (result?.ok ? result.content.sheets : [])
294 .filter((sheet) => sheet.visibility === "hidden" || sheet.visibility === "veryHidden")
295 .flatMap((sheet) => (sheet.anchor.kind === "sheet" ? [sheet.anchor.sheet.index] : [])),
296 );
297​
298 return names.flatMap((name, index) => (hidden.has(index) ? [] : [{ index, name }]));
300​
301/**
302 * Whether a cell's text pastes as it is. `toTsv` quotes text that a spreadsheet would read as a formula; a number shown
303 * with a sign, such as "-12.50", is safe, and quoting it would paste text instead of the number.
304 */
305function literal(cell: XlsxCellRead) {
306 return (
307 cell.value.kind === "number" && /^[-+][\d\s.,%\p{Sc}]+(?:e[-+]\d+)?$/iu.test(cell.displayText)
308 );