Open History to see the last commit
1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import { rangeRect, type CellRange, type GridMeta } from "@betteroffice/xlsx/headless";
3import { columnName } from "./sheet-cells";
4import type { SheetFrame, SheetFrameRequest } from "./sheet-protocol";
5
6/** Excel's light headers and green selection. The sheet keeps them on its white paper in every theme. */
7const colours = {
8 header: "#f5f5f5",
9 label: "#5c5c5c",
10 line: "#d4d4d4",
11 edge: "#bdbdbd",
12 corner: "#c8c8c8",
13 selectedHeader: "#d3ecdd",
14 selectedLabel: "#185c37",
15 accent: "#217346",
16 selection: "rgba(33, 115, 70, 0.12)",
17};
18
19const font = "11px ui-sans-serif, system-ui, sans-serif";
20
21/** The height of the column headers, in CSS pixels. */
22export const headerHeight = 20;
23
24/** The sizes of the header strips, in CSS pixels: the row headers' width and the column headers' height. */
25export type Headers = { readonly width: number; readonly height: number };
26
27/**
28 * The frozen panes' size in a frame: the offset of the first track past them. Without panes, the first track can start
29 * before the frame, part of it scrolled away.
30 */
31export function frozenSize(
32 grid: GridMeta | undefined,
33 frozen: { readonly rows: number; readonly cols: number },
34) {
35 if (!grid) return { width: 0, height: 0 };
36
37 const pane = (
38 offsets: readonly number[],
39 start: number,
40 indices: readonly number[] | undefined,
41 count: number,
42 ) => {
43 if (count === 0) return 0;
44
45 const first = offsets.findIndex(
46 (_, position) =>
47 position === offsets.length - 1 || trackIndex(start, indices, position) >= count,
48 );
49
50 return Math.max(0, offsets[first] ?? 0);
51 };
52
53 return {
54 width: pane(grid.colOffsets, grid.startCol, grid.colIndices, frozen.cols),
55 height: pane(grid.rowOffsets, grid.startRow, grid.rowIndices, frozen.rows),
56 };
57}
58
59/** A frame from the workbook worker and the request it answers, which says where its cells sit. */
60export type Painted = { readonly request: SheetFrameRequest; readonly frame: SheetFrame };
61
62/**
63 * Draws a frame's cells beside the headers at the current scroll position. A frame painted at another position, as one
64 * is while the next renders, moves with the scroll: the frozen panes stay put and the cells past them shift, leaving
65 * the paper where the frame has no cells yet.
66 */
67export function paintCells(
68 context: CanvasRenderingContext2D,
69 painted: Painted,
70 input: {
71 readonly ratio: number;
72 readonly headers: Headers;
73 readonly x: number;
74 readonly y: number;
75 readonly width: number;
76 readonly height: number;
77 },
78) {
79 const request = painted.request;
80 const bitmap = painted.frame.bitmap;
81 const panes = painted.frame.frozen;
82 const ratio = input.ratio;
83 const scale = ratio / request.ratio;
84 const origin = { x: input.headers.width * ratio, y: input.headers.height * ratio };
85
86 // Each side splits at the frozen panes: the panes stay put, the cells past them follow the scroll.
87 const columns = [
88 { start: 0, end: Math.min(panes.width, input.width), shift: 0 },
89 { start: panes.width, end: input.width, shift: painted.frame.viewport.x - input.x },
90 ];
91
92 const rows = [
93 { start: 0, end: Math.min(panes.height, input.height), shift: 0 },
94 { start: panes.height, end: input.height, shift: painted.frame.viewport.y - input.y },
95 ];
96
97 // The whole canvas clears, headers included: their edges cover part of a device pixel, which would darken with every
98 // paint drawn over the last.
99 context.save();
100 context.setTransform(1, 0, 0, 1, 0, 0);
101 context.clearRect(0, 0, context.canvas.width, context.canvas.height);
102
103 rows.forEach((row) =>
104 columns.forEach((column) => {
105 if (row.end <= row.start || column.end <= column.start) return;
106
107 const left = Math.round(origin.x + column.start * ratio);
108 const top = Math.round(origin.y + row.start * ratio);
109
110 context.save();
111 context.beginPath();
112 context.rect(
113 left,
114 top,
115 Math.round(origin.x + column.end * ratio) - left,
116 Math.round(origin.y + row.end * ratio) - top,
117 );
118 context.clip();
119 // Whole device pixels, so a frame at its own position lands exactly where the worker painted its cells.
120 context.drawImage(
121 bitmap,
122 Math.round(origin.x + column.shift * ratio - request.offset.x * scale),
123 Math.round(origin.y + row.shift * ratio - request.offset.y * scale),
124 bitmap.width * scale,
125 bitmap.height * scale,
126 );
127 context.restore();
128 }),
129 );
130
131 context.restore();
132}
133
134/**
135 * A frame's grid at another scroll position, moved as `paintCells` moves its cells: the tracks past the frozen panes
136 * shift by `shift`, and never under the panes, so headers, selection and hit tests follow the cells on screen.
137 */
138export function shiftGrid(
139 grid: GridMeta,
140 frozen: { readonly rows: number; readonly cols: number },
141 panes: { readonly width: number; readonly height: number },
142 shift: { readonly x: number; readonly y: number },
143): GridMeta {
144 if (shift.x === 0 && shift.y === 0) return grid;
145
146 const axis = (
147 offsets: readonly number[],
148 start: number,
149 indices: readonly number[] | undefined,
150 count: number,
151 edge: number,
152 by: number,
153 ) => {
154 // The offsets up to the panes' far edge belong to the panes; without panes, every track moves.
155 const fixed =
156 count === 0
157 ? -1
158 : offsets.findIndex((_, position) => trackIndex(start, indices, position) >= count);
159
160 return offsets.map((offset, position) => {
161 if (fixed === -1 && count > 0) return offset;
162
163 if (position <= fixed) return offset;
164
165 return count === 0 ? offset + by : Math.max(edge, offset + by);
166 });
167 };
168
169 return {
170 ...grid,
171 colOffsets: axis(
172 grid.colOffsets,
173 grid.startCol,
174 grid.colIndices,
175 frozen.cols,
176 panes.width,
177 shift.x,
178 ),
179 rowOffsets: axis(
180 grid.rowOffsets,
181 grid.startRow,
182 grid.rowIndices,
183 frozen.rows,
184 panes.height,
185 shift.y,
186 ),
187 };
188}
189
190/** The sheet row or column at a position in a frame's grid: its indices when tracks are skipped, else consecutive. */
191function trackIndex(start: number, indices: readonly number[] | undefined, position: number) {
192 return indices?.[position] ?? start + position;
193}
194
195/**
196 * Draws the column letters and row numbers of a frame's tracks, frozen panes first, along the top and left edges.
197 * Hidden tracks have no width in the grid, so they get no header.
198 */
199export function paintHeaders(
200 context: CanvasRenderingContext2D,
201 input: {
202 readonly grid: GridMeta;
203 readonly ratio: number;
204 readonly headers: Headers;
205 readonly width: number;
206 readonly height: number;
207 readonly selected: CellRange | undefined;
208 },
209) {
210 const grid = input.grid;
211 const headers = input.headers;
212 const selected = input.selected;
213
214 context.save();
215 context.setTransform(input.ratio, 0, 0, input.ratio, 0, 0);
216 context.fillStyle = colours.header;
217 context.fillRect(0, 0, input.width, headers.height);
218 context.fillRect(0, 0, headers.width, input.height);
219 context.font = font;
220 context.textAlign = "center";
221 context.textBaseline = "middle";
222
223 grid.colOffsets.slice(0, -1).forEach((offset, position) => {
224 const index = trackIndex(grid.startCol, grid.colIndices, position);
225
226 paintHeader(context, {
227 x: headers.width + offset,
228 y: 0,
229 width: grid.colOffsets[position + 1]! - offset,
230 height: headers.height,
231 label: columnName(index),
232 selected: !!selected && index >= selected.left && index <= selected.right,
233 clip: { x: headers.width, width: input.width - headers.width },
234 });
235 });
236 grid.rowOffsets.slice(0, -1).forEach((offset, position) => {
237 const index = trackIndex(grid.startRow, grid.rowIndices, position);
238
239 paintHeader(context, {
240 x: 0,
241 y: headers.height + offset,
242 width: headers.width,
243 height: grid.rowOffsets[position + 1]! - offset,
244 label: String(index + 1),
245 selected: !!selected && index >= selected.top && index <= selected.bottom,
246 clip: { y: headers.height, height: input.height - headers.height },
247 });
248 });
249
250 line(context, colours.edge, 0, headers.height, input.width, headers.height);
251 line(context, colours.edge, headers.width, 0, headers.width, input.height);
252 // Excel's select-all corner: a small triangle pointing at the cells.
253 context.fillStyle = colours.corner;
254 context.beginPath();
255 context.moveTo(headers.width - 4, headers.height - 12);
256 context.lineTo(headers.width - 4, headers.height - 4);
257 context.lineTo(headers.width - 12, headers.height - 4);
258 context.closePath();
259 context.fill();
260 context.restore();
261}
262
263/** Outlines the selected range and tints it, leaving its active cell clear, in the cells beside the headers. */
264export function paintSelection(
265 context: CanvasRenderingContext2D,
266 input: {
267 readonly grid: GridMeta;
268 readonly ratio: number;
269 readonly headers: Headers;
270 readonly width: number;
271 readonly height: number;
272 readonly range: CellRange;
273 readonly active: CellRange;
274 },
275) {
276 const range = rangeRect(input.grid, input.range);
277
278 if (!range) return;
279
280 const active = rangeRect(input.grid, input.active);
281
282 context.save();
283 context.setTransform(
284 input.ratio,
285 0,
286 0,
287 input.ratio,
288 input.headers.width * input.ratio,
289 input.headers.height * input.ratio,
290 );
291 context.beginPath();
292 context.rect(0, 0, input.width, input.height);
293 context.clip();
294
295 if (!sameRect(range, active)) {
296 context.beginPath();
297 context.rect(range.x, range.y, range.w, range.h);
298
299 if (active) context.rect(active.x, active.y, active.w, active.h);
300
301 context.fillStyle = colours.selection;
302 context.fill("evenodd");
303 }
304
305 context.strokeStyle = colours.accent;
306 context.lineWidth = 2;
307 context.strokeRect(range.x, range.y, range.w, range.h);
308 context.restore();
309}
310
311function paintHeader(
312 context: CanvasRenderingContext2D,
313 header: {
314 readonly x: number;
315 readonly y: number;
316 readonly width: number;
317 readonly height: number;
318 readonly label: string;
319 readonly selected: boolean;
320 readonly clip: {
321 readonly x?: number;
322 readonly y?: number;
323 readonly width?: number;
324 readonly height?: number;
325 };
326 },
327) {
328 if (header.width <= 0 || header.height <= 0) return;
329
330 const columns = header.y === 0;
331
332 context.save();
333 context.beginPath();
334 context.rect(
335 header.clip.x ?? header.x,
336 header.clip.y ?? header.y,
337 header.clip.width ?? header.width,
338 header.clip.height ?? header.height,
339 );
340 context.clip();
341
342 // A selected header is tinted, with a bar on the edge that meets the cells.
343 if (header.selected) {
344 context.fillStyle = colours.selectedHeader;
345 context.fillRect(header.x, header.y, header.width, header.height);
346 context.fillStyle = colours.accent;
347 context.fillRect(
348 columns ? header.x : header.x + header.width - 2,
349 columns ? header.y + header.height - 2 : header.y,
350 columns ? header.width : 2,
351 columns ? 2 : header.height,
352 );
353 }
354
355 // A track too small for its label shows none, rather than labels piled over each other.
356 if (columns ? context.measureText(header.label).width + 2 <= header.width : header.height >= 9) {
357 context.fillStyle = header.selected ? colours.selectedLabel : colours.label;
358 context.fillText(header.label, header.x + header.width / 2, header.y + header.height / 2 + 0.5);
359 }
360
361 context.restore();
362
363 // The line after the header, where the gridline between its cells and the next ones meets it.
364 const x = columns ? header.x + header.width : header.x;
365 const y = columns ? header.y : header.y + header.height;
366
367 line(
368 context,
369 colours.line,
370 x,
371 y,
372 columns ? x : x + header.width,
373 columns ? y + header.height : y,
374 );
375}
376
377/** A one-pixel line centred on its coordinates, as the display list draws gridlines, so the two meet. */
378function line(
379 context: CanvasRenderingContext2D,
380 colour: string,
381 x1: number,
382 y1: number,
383 x2: number,
384 y2: number,
385) {
386 context.strokeStyle = colour;
387 context.lineWidth = 1;
388 context.beginPath();
389 context.moveTo(x1, y1);
390 context.lineTo(x2, y2);
391 context.stroke();
392}
393
394function sameRect(a: { x: number; y: number; w: number; h: number }, b: typeof a | null) {
395 return !!b && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
396}