Open History to see the last commit
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 );
19}
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] : [];
28}
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 };
45}
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 const grown = merges.reduce(
50 (current, merge) =>
51 overlaps(current, merge)
52 ? {
53 top: Math.min(current.top, merge.top),
54 left: Math.min(current.left, merge.left),
55 bottom: Math.max(current.bottom, merge.bottom),
56 right: Math.max(current.right, merge.right),
57 }
58 : current,
59 range,
60 );
61
62 // A merge the range grew into can touch another one it did not reach before.
63 if (same(grown, range)) return grown;
64
65 return coverMerges(grown, merges);
66}
67
68/**
69 * Moves a collapsed selection the way Excel moves its active cell around merged cells: landing in one selects its
70 * first cell, and a step that stays inside the merged cell it started from steps past it.
71 */
72export function settleMerges(
73 previous: Selection,
74 next: Selection,
75 merges: readonly CellRange[],
76): Selection {
77 if (!collapsed(next)) return next;
78
79 const merge = merges.find((candidate) => contains(candidate, next.focus));
80
81 if (!merge) return next;
82
83 if (!collapsed(previous) || !contains(merge, previous.focus))
84 return selectionAt({ row: merge.top, col: merge.left });
85
86 const cell = {
87 row: Math.min(
88 lastCell.row,
89 Math.max(0, past(previous.focus.row, next.focus.row, merge.top, merge.bottom)),
90 ),
91 col: Math.min(
92 lastCell.col,
93 Math.max(0, past(previous.focus.col, next.focus.col, merge.left, merge.right)),
94 ),
95 };
96
97 const landed = merges.find((candidate) => contains(candidate, cell));
98
99 return selectionAt(landed ? { row: landed.top, col: landed.left } : cell);
100}
101
102/** A run of hidden rows or columns, zero-based and inclusive. */
103export type Span = { readonly start: number; readonly end: number };
104
105/** Hidden row spans such as "5:7", or column spans such as "C:D", as the export lists them. */
106export function parseSpans(spans: readonly string[], axis: "rows" | "columns"): Span[] {
107 return spans.flatMap((span) => {
108 const [first = "", last = first] = span.split(":");
109 const start = axis === "rows" ? Number(first) - 1 : columnIndex(first);
110 const end = axis === "rows" ? Number(last) - 1 : columnIndex(last);
111
112 return Number.isInteger(start) && Number.isInteger(end) && start >= 0 && end >= start
113 ? [{ start, end }]
114 : [];
115 });
116}
117
118/**
119 * Moves a selection's focus off hidden rows and columns, on in the direction it moved, as Excel's arrow keys skip
120 * them. A move that would leave the sheet stays where it started.
121 */
122export function skipHidden(
123 from: CellAddr,
124 selection: Selection,
125 hidden: { readonly rows: readonly Span[]; readonly columns: readonly Span[] },
126): Selection {
127 const focus = {
128 row: clear(from.row, selection.focus.row, hidden.rows, lastCell.row),
129 col: clear(from.col, selection.focus.col, hidden.columns, lastCell.col),
130 };
131
132 if (focus.row === selection.focus.row && focus.col === selection.focus.col) return selection;
133
134 if (collapsed(selection)) return selectionAt(focus);
135
136 return { anchor: selection.anchor, focus };
137}
138
139/** Runs an engine call that throws on input it cannot take, such as a viewport with too many cells to draw. */
140export function attempt<T>(run: () => T): T | undefined {
141 try {
142 return run();
143 } catch {
144 return undefined;
145 }
146}
147
148/** Whether a range holds a cell. */
149export function contains(range: CellRange, cell: CellAddr) {
150 return (
151 cell.row >= range.top &&
152 cell.row <= range.bottom &&
153 cell.col >= range.left &&
154 cell.col <= range.right
155 );
156}
157
158function parseCell(a1: string): CellAddr | undefined {
159 const match = /^\$?([A-Z]{1,3})\$?([1-9]\d*)$/i.exec(a1);
160
161 if (!match) return undefined;
162
163 const col = columnIndex(match[1]!);
164 const row = Number(match[2]) - 1;
165
166 if (col > lastCell.col || row > lastCell.row) return undefined;
167
168 return { row, col };
169}
170
171/** A column's zero-based index from its letters; NaN for anything but one to three letters. */
172function columnIndex(letters: string) {
173 if (!/^[A-Z]{1,3}$/i.test(letters)) return Number.NaN;
174
175 return (
176 [...letters.toUpperCase()].reduce(
177 (total, letter) => total * 26 + letter.charCodeAt(0) - 64,
178 0,
179 ) - 1
180 );
181}
182
183/** Where a move along one axis lands once past any hidden span it ended in. */
184function clear(from: number, to: number, spans: readonly Span[], last: number): number {
185 const span = spans.find((candidate) => to >= candidate.start && to <= candidate.end);
186
187 if (!span || to === from) return to;
188
189 const next = to > from ? span.end + 1 : span.start - 1;
190
191 if (next < 0 || next > last) return from;
192
193 return clear(from, next, spans, last);
194}
195
196/** One step along an axis: past the merge's far edge in the direction of the move, or where it was. */
197function past(from: number, to: number, low: number, high: number) {
198 if (to > from) return high + 1;
199
200 if (to < from) return low - 1;
201
202 return from;
203}
204
205function collapsed(selection: Selection) {
206 return (
207 selection.anchor.row === selection.focus.row && selection.anchor.col === selection.focus.col
208 );
209}
210
211function overlaps(a: CellRange, b: CellRange) {
212 return a.left <= b.right && a.right >= b.left && a.top <= b.bottom && a.bottom >= b.top;
213}
214
215function same(a: CellRange, b: CellRange) {
216 return a.top === b.top && a.left === b.left && a.bottom === b.bottom && a.right === b.right;
217}