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

sheet-frame.ts

319 lines11.3 KB

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 );
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 };
111​
112/** The engine's screen gridlines: one-pixel solid lines in its gridline grey, unlike any border it draws. */
113const gridline = (command: DisplayList["commands"][number]) =>
114 command.op === "line" && command.color === "#d4d4d4" && command.width === 1 && !command.style;
115​
116/** A frame without the gridlines the engine draws on every sheet, for a sheet whose view hides them. */
117export function withoutGridlines(frame: Frame): Frame {
118 return {
119 ...frame,
120 tiles: frame.tiles.map((tile) => ({
121 ...tile,
122 list: { ...tile.list, commands: tile.list.commands.filter((command) => !gridline(command)) },
123 })),
124 };
126​
127/**
128 * A frame whose chart text names real fonts. The engine leaves the theme's `+mj-lt` and `+mn-lt` in chart text and the
129 * painter sets chart families as CSS as they are, so an unresolved or missing family would keep the previous font.
130 */
131export function chartFonts(
132 frame: Frame,
133 theme: { readonly major: string; readonly minor: string },
134): Frame {
135 const family = (name: string) => {
136 const resolved = name.startsWith("+mj-")
137 ? theme.major
138 : name.startsWith("+mn-")
139 ? theme.minor
140 : name;
141 return `"${resolved.replaceAll('"', "")}", sans-serif`;
142 };
143​
144 return {
145 ...frame,
146 tiles: frame.tiles.map((tile) => ({
147 ...tile,
148 list: {
149 ...tile.list,
150 commands: tile.list.commands.map((command) =>
151 command.op === "text" && command.chart
152 ? { ...command, fontFamily: family(command.fontFamily ?? theme.minor) }
153 : command,
154 ),
155 },
156 })),
157 };
159​
160/**
161 * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a
162 * tile covers the panes it repeats. The cells past the frozen panes move back by `behind`; the panes stay put.
163 */
164export function paintFrame(
165 context: OffscreenCanvasRenderingContext2D,
166 frame: Frame,
167 input: { readonly ratio: number; readonly origin: { readonly x: number; readonly y: number } },
168) {
169 const ratio = input.ratio;
170 const origin = input.origin;
171 // SAFETY: the painter draws through the members a worker's 2D context shares with the window's. Only the window's
172 // context type is declared, and it has focus and attribute members the worker's lacks, hence the double cast.
173 const painter = context as unknown as CanvasRenderingContext2D;
174 const tiled = frame.tiles.length > 1;
175 const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined;
176 const textContext = text?.getContext("2d");
177 const columns = bands(frame.panes.width, frame.behind.x);
178 const rows = bands(frame.panes.height, frame.behind.y);
179 const parts = frame.tiles.flatMap((tile) =>
180 rows.flatMap((row) =>
181 columns.flatMap((column) => {
182 const left = Math.max(column.start, tile.clipX - column.shift);
183 const top = Math.max(row.start, tile.clipY - row.shift);
184​
185 if (left >= column.end || top >= row.end) return [];
186​
187 const clip = {
188 left: Math.round(origin.x + left * ratio),
189 top: Math.round(origin.y + top * ratio),
190 right: Math.round(origin.x + column.end * ratio),
191 bottom: Math.round(origin.y + row.end * ratio),
192 };
193​
194 return [
195 {
196 tile,
197 at: {
198 x: origin.x + (tile.x - column.shift) * ratio,
199 y: origin.y + (tile.y - row.shift) * ratio,
200 },
201 clip:
202 left === 0 && top === 0 && column.end === Infinity && row.end === Infinity
203 ? undefined
204 : clip,
205 },
206 ];
207 }),
208 ),
209 );
210 const clipped = (clip: (typeof parts)[number]["clip"], paint: () => void) => {
211 if (!clip) return paint();
212​
213 context.save();
214 context.setTransform(1, 0, 0, 1, 0, 0);
215 context.beginPath();
216 context.rect(
217 clip.left,
218 clip.top,
219 Math.min(clip.right, context.canvas.width) - clip.left,
220 Math.min(clip.bottom, context.canvas.height) - clip.top,
221 );
222 context.clip();
223 paint();
224 context.restore();
225 };
226​
227 parts.forEach(({ tile, at, clip }) => {
228 const list = tiled
229 ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") }
230 : tile.list;
231​
232 clipped(clip, () => paintDisplayList(painter, list, ratio, at));
233 });
234 // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds.
235 if (text && textContext)
236 parts.forEach(({ tile, at, clip }) => {
237 textContext.reset();
238 paintDisplayList(
239 textContext as unknown as CanvasRenderingContext2D,
240 {
241 ...tile.list,
242 width: frame.viewport.width + frame.behind.x - tile.x,
243 height: frame.viewport.height + frame.behind.y - tile.y,
244 commands: tile.list.commands.filter((command) => command.op === "text"),
245 },
246 ratio,
247 at,
248 );
249 clipped(clip, () => context.drawImage(text, 0, 0));
250 });
252​
253/** A side's frozen pane, drawn where it is, and the cells past it, drawn `behind` further on. */
254function bands(panes: number, behind: number) {
255 return panes > 0 && behind > 0
256 ? [
257 { start: 0, end: panes, shift: 0 },
258 { start: panes, end: Infinity, shift: behind },
259 ]
260 : [{ start: 0, end: Infinity, shift: behind }];
262​
263/**
264 * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for
265 * the frozen panes too, as every viewport has them, so the cells past them start just before its seam.
266 */
267function tiled(
268 workbook: WorkbookHandle,
269 viewport: SheetViewport,
270 panes: { readonly width: number; readonly height: number },
271 split: number,
272): Tile[] | undefined {
273 const columns = segments(viewport.width, panes.width, split);
274 const rows = segments(viewport.height, panes.height, split);
275 const tiles: Tile[] = [];
276​
277 const complete = rows.every((row) =>
278 columns.every((column) => {
279 const x = column.start === 0 ? 0 : column.start - seamOverlap - panes.width;
280 const y = row.start === 0 ? 0 : row.start - seamOverlap - panes.height;
281 // A tile but the last along an axis reaches past its end, which the next tile paints over.
282 const right = column.end === viewport.width ? column.end : column.end + seamOverlap;
283 const bottom = row.end === viewport.height ? row.end : row.end + seamOverlap;
284​
285 const list = untruncated(workbook, {
286 x: viewport.x + x,
287 y: viewport.y + y,
288 width: right - x,
289 height: bottom - y,
290 });
291​
292 if (list) tiles.push({ list, x, y, clipX: column.start, clipY: row.start });
293​
294 return !!list;
295 }),
296 );
297​
298 if (complete) return tiles;
299​
300 if (split >= maxSplit) return undefined;
301​
302 return tiled(workbook, viewport, panes, split + 1);
304​
305/** A viewport's display list, or undefined where the engine refuses it or cuts it short at its cell limit. */
306function untruncated(workbook: WorkbookHandle, viewport: SheetViewport) {
307 const list = attempt(() => workbook.displayList(viewport));
308​
309 return list?.truncated ? undefined : list;
311​
312/** Even spans of a side, the first holding the frozen panes whole; a seam inside them is dropped. */
313function segments(size: number, panes: number, split: number) {
314 const starts = Array.from({ length: split }, (_, part) =>
315 Math.round((part * size) / split),
316 ).filter((start, part) => part === 0 || (start >= panes + seamOverlap && start < size));
317​
318 return starts.map((start, part) => ({ start, end: starts[part + 1] ?? size }));