Open History to see the last commit
1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import { paintDisplayList, type DisplayList, type WorkbookHandle } from "@betteroffice/xlsx";
3import { attempt } from "./sheet-cells";
4import { frozenSize } from "./sheet-paint";
5import type { SheetViewport } from "./sheet-protocol";
6
7// The workbook worker's frames: the display lists of one viewport, split into tiles where the engine refuses it whole,
8// and their painting.
9
10/** The most tiles a side of a frame splits into before the frame gives up. */
11const maxSplit = 8;
12
13/**
14 * How far a tile reaches past each of its seams, in CSS pixels. The engine draws pane dividers and cut tracks at a
15 * frame's edges, which the next tile has to cover, and the seam falls inside a device pixel.
16 */
17const seamOverlap = 8;
18
19/**
20 * How far before a frame its cells are drawn from, in CSS pixels. The engine draws only the cells from a viewport's
21 * first track on, so the text of a cell before it, overflowing or merged into the frame, would vanish with that cell.
22 */
23const reach = { x: 1024, y: 512 };
24
25/** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */
26type Tile = {
27 readonly list: DisplayList;
28 readonly x: number;
29 readonly y: number;
30 readonly clipX: number;
31 readonly clipY: number;
32};
33
34/**
35 * A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the
36 * viewport it shows. The tiles' cells past the frozen panes start `behind` the viewport's.
37 */
38export type Frame = {
39 readonly list: DisplayList;
40 readonly tiles: readonly Tile[];
41 readonly viewport: SheetViewport;
42 readonly behind: { readonly x: number; readonly y: number };
43 readonly panes: { readonly width: number; readonly height: number };
44};
45
46/**
47 * The cells of one viewport, as the engine draws them; `undefined` when even its smallest tiles fail. A `wider`
48 * viewport around it is drawn instead when the engine takes it whole.
49 */
50export function drawFrame(
51 workbook: WorkbookHandle,
52 viewport: SheetViewport,
53 frozen: { readonly rows: number; readonly cols: number },
54 wider?: SheetViewport,
55): Frame | undefined {
56 return (
57 (wider && reaching(workbook, wider, frozen, false)) ||
58 reaching(workbook, viewport, frozen, true)
59 );
60}
61
62/** A frame of `viewport` drawn from up to `reach` before it, split into tiles when `split` and the engine needs it. */
63function reaching(
64 workbook: WorkbookHandle,
65 viewport: SheetViewport,
66 frozen: { readonly rows: number; readonly cols: number },
67 split: boolean,
68): Frame | undefined {
69 // One row and one column of the viewport give its tracks, and so where its frozen panes end.
70 const columns = untruncated(workbook, { ...viewport, height: 1 })?.grid;
71 const rows = untruncated(workbook, { ...viewport, width: 1 })?.grid;
72
73 if (!columns || !rows) return undefined;
74
75 const grid = {
76 startRow: rows.startRow,
77 ...(rows.rowIndices ? { rowIndices: rows.rowIndices } : {}),
78 rowOffsets: rows.rowOffsets,
79 startCol: columns.startCol,
80 ...(columns.colIndices ? { colIndices: columns.colIndices } : {}),
81 colOffsets: columns.colOffsets,
82 };
83 const panes = frozenSize(grid, frozen);
84 const behind = { x: Math.min(reach.x, viewport.x), y: Math.min(reach.y, viewport.y) };
85 const area = {
86 x: viewport.x - behind.x,
87 y: viewport.y - behind.y,
88 width: viewport.width + behind.x,
89 height: viewport.height + behind.y,
90 };
91 const whole = untruncated(workbook, area);
92 // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has.
93 const tiles = whole
94 ? [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }]
95 : split
96 ? tiled(workbook, area, panes, 2)
97 : undefined;
98
99 if (!tiles) return undefined;
100
101 const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []);
102
103 return {
104 list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks },
105 tiles,
106 viewport,
107 behind,
108 panes,
109 };
110}
111
112/**
113 * A frame whose chart text names real fonts. The engine leaves the theme's `+mj-lt` and `+mn-lt` in chart text and the
114 * painter sets chart families as CSS as they are, so an unresolved or missing family would keep the previous font.
115 */
116export function chartFonts(
117 frame: Frame,
118 theme: { readonly major: string; readonly minor: string },
119): Frame {
120 const family = (name: string) => {
121 const resolved = name.startsWith("+mj-")
122 ? theme.major
123 : name.startsWith("+mn-")
124 ? theme.minor
125 : name;
126 return `"${resolved.replaceAll('"', "")}", sans-serif`;
127 };
128
129 return {
130 ...frame,
131 tiles: frame.tiles.map((tile) => ({
132 ...tile,
133 list: {
134 ...tile.list,
135 commands: tile.list.commands.map((command) =>
136 command.op === "text" && command.chart
137 ? { ...command, fontFamily: family(command.fontFamily ?? theme.minor) }
138 : command,
139 ),
140 },
141 })),
142 };
143}
144
145/**
146 * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a
147 * tile covers the panes it repeats. The cells past the frozen panes move back by `behind`; the panes stay put.
148 */
149export function paintFrame(
150 context: OffscreenCanvasRenderingContext2D,
151 frame: Frame,
152 input: { readonly ratio: number; readonly origin: { readonly x: number; readonly y: number } },
153) {
154 const ratio = input.ratio;
155 const origin = input.origin;
156 // SAFETY: the painter draws through the members a worker's 2D context shares with the window's. Only the window's
157 // context type is declared, and it has focus and attribute members the worker's lacks, hence the double cast.
158 const painter = context as unknown as CanvasRenderingContext2D;
159 const tiled = frame.tiles.length > 1;
160 const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined;
161 const textContext = text?.getContext("2d");
162 const columns = bands(frame.panes.width, frame.behind.x);
163 const rows = bands(frame.panes.height, frame.behind.y);
164 const parts = frame.tiles.flatMap((tile) =>
165 rows.flatMap((row) =>
166 columns.flatMap((column) => {
167 const left = Math.max(column.start, tile.clipX - column.shift);
168 const top = Math.max(row.start, tile.clipY - row.shift);
169
170 if (left >= column.end || top >= row.end) return [];
171
172 const clip = {
173 left: Math.round(origin.x + left * ratio),
174 top: Math.round(origin.y + top * ratio),
175 right: Math.round(origin.x + column.end * ratio),
176 bottom: Math.round(origin.y + row.end * ratio),
177 };
178
179 return [
180 {
181 tile,
182 at: {
183 x: origin.x + (tile.x - column.shift) * ratio,
184 y: origin.y + (tile.y - row.shift) * ratio,
185 },
186 clip:
187 left === 0 && top === 0 && column.end === Infinity && row.end === Infinity
188 ? undefined
189 : clip,
190 },
191 ];
192 }),
193 ),
194 );
195 const clipped = (clip: (typeof parts)[number]["clip"], paint: () => void) => {
196 if (!clip) return paint();
197
198 context.save();
199 context.setTransform(1, 0, 0, 1, 0, 0);
200 context.beginPath();
201 context.rect(
202 clip.left,
203 clip.top,
204 Math.min(clip.right, context.canvas.width) - clip.left,
205 Math.min(clip.bottom, context.canvas.height) - clip.top,
206 );
207 context.clip();
208 paint();
209 context.restore();
210 };
211
212 parts.forEach(({ tile, at, clip }) => {
213 const list = tiled
214 ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") }
215 : tile.list;
216
217 clipped(clip, () => paintDisplayList(painter, list, ratio, at));
218 });
219 // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds.
220 if (text && textContext)
221 parts.forEach(({ tile, at, clip }) => {
222 textContext.reset();
223 paintDisplayList(
224 textContext as unknown as CanvasRenderingContext2D,
225 {
226 ...tile.list,
227 width: frame.viewport.width + frame.behind.x - tile.x,
228 height: frame.viewport.height + frame.behind.y - tile.y,
229 commands: tile.list.commands.filter((command) => command.op === "text"),
230 },
231 ratio,
232 at,
233 );
234 clipped(clip, () => context.drawImage(text, 0, 0));
235 });
236}
237
238/** A side's frozen pane, drawn where it is, and the cells past it, drawn `behind` further on. */
239function bands(panes: number, behind: number) {
240 return panes > 0 && behind > 0
241 ? [
242 { start: 0, end: panes, shift: 0 },
243 { start: panes, end: Infinity, shift: behind },
244 ]
245 : [{ start: 0, end: Infinity, shift: behind }];
246}
247
248/**
249 * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for
250 * the frozen panes too, as every viewport has them, so the cells past them start just before its seam.
251 */
252function tiled(
253 workbook: WorkbookHandle,
254 viewport: SheetViewport,
255 panes: { readonly width: number; readonly height: number },
256 split: number,
257): Tile[] | undefined {
258 const columns = segments(viewport.width, panes.width, split);
259 const rows = segments(viewport.height, panes.height, split);
260 const tiles: Tile[] = [];
261
262 const complete = rows.every((row) =>
263 columns.every((column) => {
264 const x = column.start === 0 ? 0 : column.start - seamOverlap - panes.width;
265 const y = row.start === 0 ? 0 : row.start - seamOverlap - panes.height;
266 // A tile but the last along an axis reaches past its end, which the next tile paints over.
267 const right = column.end === viewport.width ? column.end : column.end + seamOverlap;
268 const bottom = row.end === viewport.height ? row.end : row.end + seamOverlap;
269
270 const list = untruncated(workbook, {
271 x: viewport.x + x,
272 y: viewport.y + y,
273 width: right - x,
274 height: bottom - y,
275 });
276
277 if (list) tiles.push({ list, x, y, clipX: column.start, clipY: row.start });
278
279 return !!list;
280 }),
281 );
282
283 if (complete) return tiles;
284
285 if (split >= maxSplit) return undefined;
286
287 return tiled(workbook, viewport, panes, split + 1);
288}
289
290/** A viewport's display list, or undefined where the engine refuses it or cuts it short at its cell limit. */
291function untruncated(workbook: WorkbookHandle, viewport: SheetViewport) {
292 const list = attempt(() => workbook.displayList(viewport));
293
294 return list?.truncated ? undefined : list;
295}
296
297/** Even spans of a side, the first holding the frozen panes whole; a seam inside them is dropped. */
298function segments(size: number, panes: number, split: number) {
299 const starts = Array.from({ length: split }, (_, part) =>
300 Math.round((part * size) / split),
301 ).filter((start, part) => part === 0 || (start >= panes + seamOverlap && start < size));
302
303 return starts.map((start, part) => ({ start, end: starts[part + 1] ?? size }));
304}