Open History to see the last commit
1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import {
3 paintDisplayList,
4 type DisplayList,
5 type GridMeta,
6 type WorkbookHandle,
7} from "@betteroffice/xlsx";
8import { attempt } from "./sheet-cells";
9import { frozenSize } from "./sheet-paint";
10import type { SheetViewport } from "./sheet-protocol";
11
12// The workbook worker's frames: the display lists of one viewport, split into tiles where the engine refuses it whole,
13// and their painting.
14
15/** The most tiles a side of a frame splits into before the frame gives up. */
16const maxSplit = 8;
17
18/**
19 * How far a tile reaches past each of its seams, in CSS pixels. The engine draws pane dividers and cut tracks at a
20 * frame's edges, which the next tile has to cover, and the seam falls inside a device pixel.
21 */
22const seamOverlap = 8;
23
24/** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */
25type Tile = {
26 readonly list: DisplayList;
27 readonly x: number;
28 readonly y: number;
29 readonly clipX: number;
30 readonly clipY: number;
31};
32
33/**
34 * A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the
35 * viewport it shows.
36 */
37export type Frame = {
38 readonly list: DisplayList;
39 readonly tiles: readonly Tile[];
40 readonly viewport: SheetViewport;
41};
42
43/**
44 * The cells of one viewport, as the engine draws them; `undefined` when even its smallest tiles fail. A `wider`
45 * viewport around it is drawn instead when the engine takes it whole.
46 */
47export function drawFrame(
48 workbook: WorkbookHandle,
49 viewport: SheetViewport,
50 frozen: { readonly rows: number; readonly cols: number },
51 wider?: SheetViewport,
52): Frame | undefined {
53 const around = wider && attempt(() => workbook.displayList(wider));
54
55 if (wider && around)
56 return {
57 list: around,
58 tiles: [{ list: around, x: 0, y: 0, clipX: 0, clipY: 0 }],
59 viewport: wider,
60 };
61
62 const whole = attempt(() => workbook.displayList(viewport));
63
64 if (whole)
65 return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport };
66
67 // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of
68 // the frame give its tracks, and so where its frozen panes end.
69 const columns = attempt(() => workbook.displayList({ ...viewport, height: 1 }).grid);
70 const rows = attempt(() => workbook.displayList({ ...viewport, width: 1 }).grid);
71
72 if (!columns || !rows) return undefined;
73
74 const grid = {
75 startRow: rows.startRow,
76 ...(rows.rowIndices ? { rowIndices: rows.rowIndices } : {}),
77 rowOffsets: rows.rowOffsets,
78 startCol: columns.startCol,
79 ...(columns.colIndices ? { colIndices: columns.colIndices } : {}),
80 colOffsets: columns.colOffsets,
81 };
82
83 return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2);
84}
85
86/**
87 * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a
88 * tile covers the panes it repeats.
89 */
90export function paintFrame(
91 context: OffscreenCanvasRenderingContext2D,
92 frame: Frame,
93 input: { readonly ratio: number; readonly origin: { readonly x: number; readonly y: number } },
94) {
95 const ratio = input.ratio;
96 const origin = input.origin;
97 // SAFETY: the painter draws through the members a worker's 2D context shares with the window's. Only the window's
98 // context type is declared, and it has focus and attribute members the worker's lacks, hence the double cast.
99 const painter = context as unknown as CanvasRenderingContext2D;
100 const tiled = frame.tiles.length > 1;
101 const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined;
102 const textContext = text?.getContext("2d");
103
104 frame.tiles.forEach((tile) => {
105 const at = { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio };
106 const list = tiled
107 ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") }
108 : tile.list;
109
110 if (tile.clipX === 0 && tile.clipY === 0) return paintDisplayList(painter, list, ratio, at);
111
112 context.save();
113 context.setTransform(1, 0, 0, 1, 0, 0);
114 context.beginPath();
115 context.rect(
116 Math.round(origin.x + tile.clipX * ratio),
117 Math.round(origin.y + tile.clipY * ratio),
118 context.canvas.width,
119 context.canvas.height,
120 );
121 context.clip();
122 paintDisplayList(painter, list, ratio, at);
123 context.restore();
124 });
125 // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds.
126 if (text && textContext)
127 frame.tiles.forEach((tile) => {
128 textContext.reset();
129 paintDisplayList(
130 textContext as unknown as CanvasRenderingContext2D,
131 {
132 ...tile.list,
133 width: frame.viewport.width - tile.x,
134 height: frame.viewport.height - tile.y,
135 commands: tile.list.commands.filter((command) => command.op === "text"),
136 },
137 ratio,
138 { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio },
139 );
140 context.save();
141 context.setTransform(1, 0, 0, 1, 0, 0);
142 context.beginPath();
143 context.rect(
144 Math.round(origin.x + tile.clipX * ratio),
145 Math.round(origin.y + tile.clipY * ratio),
146 context.canvas.width,
147 context.canvas.height,
148 );
149 context.clip();
150 context.drawImage(text, 0, 0);
151 context.restore();
152 });
153}
154
155/**
156 * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for
157 * the frozen panes too, as every viewport has them, so the cells past them start just before its seam.
158 */
159function tiled(
160 workbook: WorkbookHandle,
161 viewport: SheetViewport,
162 panes: { readonly width: number; readonly height: number },
163 grid: GridMeta,
164 split: number,
165): Frame | undefined {
166 const columns = segments(viewport.width, panes.width, split);
167 const rows = segments(viewport.height, panes.height, split);
168 const tiles: Tile[] = [];
169
170 const complete = rows.every((row) =>
171 columns.every((column) => {
172 const x = column.start === 0 ? 0 : column.start - seamOverlap - panes.width;
173 const y = row.start === 0 ? 0 : row.start - seamOverlap - panes.height;
174 // A tile but the last along an axis reaches past its end, which the next tile paints over.
175 const right = column.end === viewport.width ? column.end : column.end + seamOverlap;
176 const bottom = row.end === viewport.height ? row.end : row.end + seamOverlap;
177
178 const list = attempt(() =>
179 workbook.displayList({
180 x: viewport.x + x,
181 y: viewport.y + y,
182 width: right - x,
183 height: bottom - y,
184 }),
185 );
186
187 if (list) tiles.push({ list, x, y, clipX: column.start, clipY: row.start });
188
189 return !!list;
190 }),
191 );
192
193 if (complete) {
194 const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []);
195
196 return {
197 list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks },
198 tiles,
199 viewport,
200 };
201 }
202
203 if (split >= maxSplit) return undefined;
204
205 return tiled(workbook, viewport, panes, grid, split + 1);
206}
207
208/** Even spans of a side, the first holding the frozen panes whole; a seam inside them is dropped. */
209function segments(size: number, panes: number, split: number) {
210 const starts = Array.from({ length: split }, (_, part) =>
211 Math.round((part * size) / split),
212 ).filter((start, part) => part === 0 || (start >= panes + seamOverlap && start < size));
213
214 return starts.map((start, part) => ({ start, end: starts[part + 1] ?? size }));
215}