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

sheet-cells.ts

261 lines8.3 KB

1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import type { XlsxAnchor } from "@betteroffice/xlsx";
3import {
4 selectionAt,
5 type CellAddr,
6 type CellRange,
7 type Selection,
8} from "@betteroffice/xlsx/headless";
9​
10/** The sheet's last cell, zero-based: row 1,048,576 in column XFD. */
11export const lastCell = { row: 1048575, col: 16383 };
12​
13/** A column's letters, such as "A", "Z" or "AA". */
14export function columnName(index: number): string {
15 return (
16 (index < 26 ? "" : columnName(Math.floor(index / 26) - 1)) +
17 String.fromCharCode(65 + (index % 26))
18 );
20​
21/** The cells an export anchor names: one range for a cell or range anchor, none for any other kind. */
22export function anchorRange(anchor: XlsxAnchor): CellRange[] {
23 if (anchor.kind !== "cell" && anchor.kind !== "range") return [];
24​
25 const range = parseRange(anchor.a1);
26​
27 return range ? [range] : [];
29​
30/** An A1 cell or range, such as "B2" or "A1:F20"; undefined for anything else. */
31export function parseRange(a1: string): CellRange | undefined {
32 // A lone cell is its own last corner; an empty one, as in "A1:", names no range.
33 const corners = a1.split(":");
34 const first = parseCell(corners[0] ?? "");
35 const last = corners.length === 1 ? first : parseCell(corners[1] ?? "");
36​
37 if (!first || !last) return undefined;
38​
39 return {
40 top: Math.min(first.row, last.row),
41 left: Math.min(first.col, last.col),
42 bottom: Math.max(first.row, last.row),
43 right: Math.max(first.col, last.col),
44 };
46​
47/** Grows a range until it covers every merged cell it touches, as Excel selects. */
48export function coverMerges(range: CellRange, merges: readonly CellRange[]): CellRange {
49 let grown = range;
50 for (let pass = 0; pass < 2; pass++) {
51 const next = merges.reduce(
52 (current, merge) =>
53 overlaps(current, merge)
54 ? {
55 top: Math.min(current.top, merge.top),
56 left: Math.min(current.left, merge.left),
57 bottom: Math.max(current.bottom, merge.bottom),
58 right: Math.max(current.right, merge.right),
59 }
60 : current,
61 grown,
62 );
63 if (same(next, grown)) return next;
64 grown = next;
65 }
66​
67 // Each overlap inequality becomes true only once as the selection grows. Sweep sorted
68 // edges so a chain of merges cannot force repeated full scans or recursive stack growth.
69 const sweeps = (
70 [
71 { mergeEdge: "top", rangeEdge: "bottom", direction: 1 },
72 { mergeEdge: "bottom", rangeEdge: "top", direction: -1 },
73 { mergeEdge: "left", rangeEdge: "right", direction: 1 },
74 { mergeEdge: "right", rangeEdge: "left", direction: -1 },
75 ] as const
76 ).map(({ mergeEdge, rangeEdge, direction }) => ({
77 rangeEdge,
78 direction,
79 position: 0,
80 edges: merges
81 .map((merge, index) => ({ index, value: direction * merge[mergeEdge] }))
82 .sort((a, b) => a.value - b.value),
83 }));
84 const crossed = new Uint8Array(merges.length);
85 let changed;
86 do {
87 changed = false;
88 for (const sweep of sweeps) {
89 let edge = sweep.edges[sweep.position];
90 while (edge && edge.value <= sweep.direction * grown[sweep.rangeEdge]) {
91 const index = edge.index;
92 crossed[index] = crossed[index]! + 1;
93 if (crossed[index] === 4) {
94 const merge = merges[index]!;
95 const next = {
96 top: Math.min(grown.top, merge.top),
97 left: Math.min(grown.left, merge.left),
98 bottom: Math.max(grown.bottom, merge.bottom),
99 right: Math.max(grown.right, merge.right),
100 };
101 changed ||= !same(grown, next);
102 grown = next;
103 }
104 edge = sweep.edges[++sweep.position];
105 }
106 }
107 } while (changed);
108​
109 return grown;
111​
112/**
113 * Moves a collapsed selection the way Excel moves its active cell around merged cells: landing in one selects its
114 * first cell, and a step that stays inside the merged cell it started from steps past it.
115 */
116export function settleMerges(
117 previous: Selection,
118 next: Selection,
119 merges: readonly CellRange[],
120): Selection {
121 if (!collapsed(next)) return next;
122​
123 const merge = merges.find((candidate) => contains(candidate, next.focus));
124​
125 if (!merge) return next;
126​
127 if (!collapsed(previous) || !contains(merge, previous.focus))
128 return selectionAt({ row: merge.top, col: merge.left });
129​
130 const cell = {
131 row: Math.min(
132 lastCell.row,
133 Math.max(0, past(previous.focus.row, next.focus.row, merge.top, merge.bottom)),
134 ),
135 col: Math.min(
136 lastCell.col,
137 Math.max(0, past(previous.focus.col, next.focus.col, merge.left, merge.right)),
138 ),
139 };
140​
141 const landed = merges.find((candidate) => contains(candidate, cell));
142​
143 return selectionAt(landed ? { row: landed.top, col: landed.left } : cell);
145​
146/** A run of hidden rows or columns, zero-based and inclusive. */
147export type Span = { readonly start: number; readonly end: number };
148​
149/** Hidden row spans such as "5:7", or column spans such as "C:D", as the export lists them. */
150export function parseSpans(spans: readonly string[], axis: "rows" | "columns"): Span[] {
151 return spans.flatMap((span) => {
152 const [first = "", last = first] = span.split(":");
153 const start = axis === "rows" ? Number(first) - 1 : columnIndex(first);
154 const end = axis === "rows" ? Number(last) - 1 : columnIndex(last);
155​
156 return Number.isInteger(start) && Number.isInteger(end) && start >= 0 && end >= start
157 ? [{ start, end }]
158 : [];
159 });
161​
162/**
163 * Moves a selection's focus off hidden rows and columns, on in the direction it moved, as Excel's arrow keys skip
164 * them. A move that would leave the sheet stays where it started.
165 */
166export function skipHidden(
167 from: CellAddr,
168 selection: Selection,
169 hidden: { readonly rows: readonly Span[]; readonly columns: readonly Span[] },
170): Selection {
171 const focus = {
172 row: clear(from.row, selection.focus.row, hidden.rows, lastCell.row),
173 col: clear(from.col, selection.focus.col, hidden.columns, lastCell.col),
174 };
175​
176 if (focus.row === selection.focus.row && focus.col === selection.focus.col) return selection;
177​
178 if (collapsed(selection)) return selectionAt(focus);
179​
180 return { anchor: selection.anchor, focus };
182​
183/** Runs an engine call that throws on input it cannot take, such as a viewport with too many cells to draw. */
184export function attempt<T>(run: () => T): T | undefined {
185 try {
186 return run();
187 } catch {
188 return undefined;
189 }
191​
192/** Whether a range holds a cell. */
193export function contains(range: CellRange, cell: CellAddr) {
194 return (
195 cell.row >= range.top &&
196 cell.row <= range.bottom &&
197 cell.col >= range.left &&
198 cell.col <= range.right
199 );
201​
202function parseCell(a1: string): CellAddr | undefined {
203 const match = /^\$?([A-Z]{1,3})\$?([1-9]\d*)$/i.exec(a1);
204​
205 if (!match) return undefined;
206​
207 const col = columnIndex(match[1]!);
208 const row = Number(match[2]) - 1;
209​
210 if (col > lastCell.col || row > lastCell.row) return undefined;
211​
212 return { row, col };
214​
215/** A column's zero-based index from its letters; NaN for anything but one to three letters. */
216function columnIndex(letters: string) {
217 if (!/^[A-Z]{1,3}$/i.test(letters)) return Number.NaN;
218​
219 return (
220 [...letters.toUpperCase()].reduce(
221 (total, letter) => total * 26 + letter.charCodeAt(0) - 64,
222 0,
223 ) - 1
224 );
226​
227/** Where a move along one axis lands once past any hidden span it ended in. */
228function clear(from: number, to: number, spans: readonly Span[], last: number): number {
229 const span = spans.find((candidate) => to >= candidate.start && to <= candidate.end);
230​
231 if (!span || to === from) return to;
232​
233 const next = to > from ? span.end + 1 : span.start - 1;
234​
235 if (next < 0 || next > last) return from;
236​
237 return clear(from, next, spans, last);
239​
240/** One step along an axis: past the merge's far edge in the direction of the move, or where it was. */
241function past(from: number, to: number, low: number, high: number) {
242 if (to > from) return high + 1;
243​
244 if (to < from) return low - 1;
245​
246 return from;
248​
249function collapsed(selection: Selection) {
250 return (
251 selection.anchor.row === selection.focus.row && selection.anchor.col === selection.focus.col
252 );
254​
255function overlaps(a: CellRange, b: CellRange) {
256 return a.left <= b.right && a.right >= b.left && a.top <= b.bottom && a.bottom >= b.top;
258​
259function same(a: CellRange, b: CellRange) {
260 return a.top === b.top && a.left === b.left && a.bottom === b.bottom && a.right === b.right;