@beyondwork/docx-react-component 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,822 @@
1
+ import { parseCellKey, type CellKey, type FormulaCell } from "../model/cell.ts";
2
+ import type { CanonicalSheet, MergeRange } from "../model/sheet.ts";
3
+ import type { CanonicalWorkbook, NamedItem } from "../model/workbook.ts";
4
+ import { getSheet, listSheets, workbookFromJson, workbookToJson } from "../model/workbook.ts";
5
+
6
+ export interface WorkbookCellRef {
7
+ row: number;
8
+ col: number;
9
+ }
10
+
11
+ export interface WorkbookRange {
12
+ startRow: number;
13
+ startCol: number;
14
+ endRow: number;
15
+ endCol: number;
16
+ }
17
+
18
+ export type WorkbookSelectionMode = "cell" | "row" | "column" | "sheet";
19
+
20
+ export interface WorkbookSelection {
21
+ mode: WorkbookSelectionMode;
22
+ sheetId?: string;
23
+ activeCell?: WorkbookCellRef;
24
+ range?: WorkbookRange;
25
+ }
26
+
27
+ export type WorkbookTransactionOperation =
28
+ | { type: "cell-set"; sheetId: string; row: number; col: number }
29
+ | { type: "row-insert"; sheetId: string; index: number; count: number }
30
+ | { type: "row-delete"; sheetId: string; index: number; count: number }
31
+ | { type: "column-insert"; sheetId: string; index: number; count: number }
32
+ | { type: "column-delete"; sheetId: string; index: number; count: number }
33
+ | { type: "merge-add"; sheetId: string; range: WorkbookRange }
34
+ | { type: "merge-remove"; sheetId: string; range: WorkbookRange }
35
+ | { type: "sheet-add"; sheetId: string; index: number; name: string }
36
+ | { type: "sheet-remove"; sheetId: string; index: number; name: string; fallbackSheetId?: string }
37
+ | { type: "sheet-rename"; sheetId: string; beforeName: string; afterName: string }
38
+ | { type: "sheet-reorder"; sheetId: string; fromIndex: number; toIndex: number }
39
+ | { type: "formula-remap"; ownerSheetId: string; row: number; col: number; before: string; after: string }
40
+ | { type: "named-item-remap"; name: string; before: string; after: string };
41
+
42
+ export interface WorkbookTransactionMapping {
43
+ operations: WorkbookTransactionOperation[];
44
+ }
45
+
46
+ export interface WorkbookTransaction {
47
+ nextWorkbook: CanonicalWorkbook;
48
+ nextSelection: WorkbookSelection;
49
+ mapping: WorkbookTransactionMapping;
50
+ inverseMapping: WorkbookTransactionMapping;
51
+ historyBoundary: "push" | "skip";
52
+ label: string;
53
+ }
54
+
55
+ interface ParsedA1CellRef {
56
+ col: number;
57
+ row: number;
58
+ colAbsolute: boolean;
59
+ rowAbsolute: boolean;
60
+ }
61
+
62
+ interface ParsedFormulaToken {
63
+ sheetName?: string;
64
+ sheetQuoted: boolean;
65
+ start: ParsedA1CellRef;
66
+ end?: ParsedA1CellRef;
67
+ }
68
+
69
+ interface InsertAxisMutation {
70
+ axis: "row" | "col";
71
+ kind: "insert";
72
+ index: number;
73
+ count: number;
74
+ }
75
+
76
+ interface DeleteAxisMutation {
77
+ axis: "row" | "col";
78
+ kind: "delete";
79
+ index: number;
80
+ count: number;
81
+ }
82
+
83
+ interface RenameSheetMutation {
84
+ kind: "rename-sheet";
85
+ beforeName: string;
86
+ afterName: string;
87
+ }
88
+
89
+ interface RemoveSheetMutation {
90
+ kind: "remove-sheet";
91
+ removedName: string;
92
+ }
93
+
94
+ type FormulaMutation =
95
+ | InsertAxisMutation
96
+ | DeleteAxisMutation
97
+ | RenameSheetMutation
98
+ | RemoveSheetMutation;
99
+
100
+ const SHEET_PREFIX_PATTERN =
101
+ "(?:'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!";
102
+ const CELL_REFERENCE_PATTERN = "\\$?[A-Z]{1,3}\\$?[1-9][0-9]*";
103
+ const RANGE_REFERENCE_PATTERN =
104
+ `${CELL_REFERENCE_PATTERN}(?::${CELL_REFERENCE_PATTERN})?`;
105
+ const FORMULA_REFERENCE_PATTERN = new RegExp(
106
+ String.raw`(?<![A-Za-z0-9_.$])(?:${SHEET_PREFIX_PATTERN})?${RANGE_REFERENCE_PATTERN}(?![A-Za-z0-9_])`,
107
+ "g",
108
+ );
109
+ const SIMPLE_SHEET_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.]*$/;
110
+
111
+ export function createEmptyWorkbookMapping(): WorkbookTransactionMapping {
112
+ return { operations: [] };
113
+ }
114
+
115
+ export function createWorkbookTransaction(
116
+ nextWorkbook: CanonicalWorkbook,
117
+ nextSelection: WorkbookSelection,
118
+ mapping: WorkbookTransactionMapping,
119
+ label: string,
120
+ ): WorkbookTransaction {
121
+ return {
122
+ nextWorkbook,
123
+ nextSelection,
124
+ mapping,
125
+ inverseMapping: {
126
+ operations: [...mapping.operations].reverse().map(invertOperation),
127
+ },
128
+ historyBoundary: "push",
129
+ label,
130
+ };
131
+ }
132
+
133
+ export function cloneWorkbook(workbook: CanonicalWorkbook): CanonicalWorkbook {
134
+ return workbookFromJson(workbookToJson(workbook));
135
+ }
136
+
137
+ export function createWorkbookSelection(
138
+ sheetId?: string,
139
+ row = 0,
140
+ col = 0,
141
+ mode: WorkbookSelectionMode = "cell",
142
+ ): WorkbookSelection {
143
+ if (!sheetId) {
144
+ return { mode: "sheet" };
145
+ }
146
+
147
+ const activeCell = { row: Math.max(0, row), col: Math.max(0, col) };
148
+ return {
149
+ mode,
150
+ sheetId,
151
+ activeCell,
152
+ range: {
153
+ startRow: activeCell.row,
154
+ startCol: activeCell.col,
155
+ endRow: activeCell.row,
156
+ endCol: activeCell.col,
157
+ },
158
+ };
159
+ }
160
+
161
+ export function getDefaultSelection(workbook: CanonicalWorkbook): WorkbookSelection {
162
+ const firstSheetId = workbook.sheetOrder[0];
163
+ return createWorkbookSelection(firstSheetId);
164
+ }
165
+
166
+ export function normalizeWorkbookSelection(
167
+ workbook: CanonicalWorkbook,
168
+ selection?: WorkbookSelection,
169
+ ): WorkbookSelection {
170
+ if (workbook.sheetOrder.length === 0) {
171
+ return { mode: "sheet" };
172
+ }
173
+
174
+ const sheetId = selection?.sheetId && workbook.sheets.has(selection.sheetId)
175
+ ? selection.sheetId
176
+ : workbook.sheetOrder[0];
177
+ const activeCell = selection?.activeCell ?? { row: 0, col: 0 };
178
+ const range = selection?.range
179
+ ? normalizeRange(selection.range)
180
+ : {
181
+ startRow: activeCell.row,
182
+ startCol: activeCell.col,
183
+ endRow: activeCell.row,
184
+ endCol: activeCell.col,
185
+ };
186
+
187
+ return {
188
+ mode: selection?.mode ?? "cell",
189
+ sheetId,
190
+ activeCell: {
191
+ row: Math.max(0, activeCell.row),
192
+ col: Math.max(0, activeCell.col),
193
+ },
194
+ range,
195
+ };
196
+ }
197
+
198
+ export function mapSelectionThroughMapping(
199
+ selection: WorkbookSelection,
200
+ mapping: WorkbookTransactionMapping,
201
+ ): WorkbookSelection {
202
+ let nextSelection: WorkbookSelection = cloneSelection(selection);
203
+
204
+ for (const operation of mapping.operations) {
205
+ nextSelection = mapSelectionThroughOperation(nextSelection, operation);
206
+ }
207
+
208
+ return nextSelection;
209
+ }
210
+
211
+ export function normalizeRange(range: WorkbookRange): WorkbookRange {
212
+ return {
213
+ startRow: Math.min(range.startRow, range.endRow),
214
+ startCol: Math.min(range.startCol, range.endCol),
215
+ endRow: Math.max(range.startRow, range.endRow),
216
+ endCol: Math.max(range.startCol, range.endCol),
217
+ };
218
+ }
219
+
220
+ export function rangesIntersect(left: WorkbookRange, right: WorkbookRange): boolean {
221
+ const a = normalizeRange(left);
222
+ const b = normalizeRange(right);
223
+ return !(
224
+ a.endRow < b.startRow ||
225
+ b.endRow < a.startRow ||
226
+ a.endCol < b.startCol ||
227
+ b.endCol < a.startCol
228
+ );
229
+ }
230
+
231
+ export function rangeContainsCell(range: WorkbookRange, cell: WorkbookCellRef): boolean {
232
+ const normalized = normalizeRange(range);
233
+ return (
234
+ cell.row >= normalized.startRow &&
235
+ cell.row <= normalized.endRow &&
236
+ cell.col >= normalized.startCol &&
237
+ cell.col <= normalized.endCol
238
+ );
239
+ }
240
+
241
+ export function remapFormulasForMutation(
242
+ workbook: CanonicalWorkbook,
243
+ targetSheetId: string,
244
+ mutation: FormulaMutation,
245
+ mapping: WorkbookTransactionMapping,
246
+ ): void {
247
+ const targetSheetName = getSheet(workbook, targetSheetId)?.name;
248
+ if (!targetSheetName) {
249
+ return;
250
+ }
251
+
252
+ for (const sheet of listSheets(workbook)) {
253
+ for (const [key, value] of sheet.cells) {
254
+ if (value.kind !== "formula") {
255
+ continue;
256
+ }
257
+
258
+ const rewritten = rewriteFormulaReferences(
259
+ value.formula,
260
+ sheet.name,
261
+ targetSheetName,
262
+ mutation,
263
+ );
264
+ if (!rewritten.changed) {
265
+ continue;
266
+ }
267
+
268
+ sheet.cells.set(key, {
269
+ ...value,
270
+ formula: rewritten.formula,
271
+ referenceTokens: extractFormulaReferenceTokens(rewritten.formula),
272
+ } satisfies FormulaCell);
273
+
274
+ const address = parseCellKey(key);
275
+ mapping.operations.push({
276
+ type: "formula-remap",
277
+ ownerSheetId: sheet.sheetId,
278
+ row: address.row,
279
+ col: address.col,
280
+ before: value.formula,
281
+ after: rewritten.formula,
282
+ });
283
+ }
284
+ }
285
+
286
+ workbook.namedItems = workbook.namedItems
287
+ .map((item) => remapNamedItemForMutation(item, workbook, targetSheetName, mutation, mapping))
288
+ .filter((item): item is NamedItem => item !== null);
289
+ }
290
+
291
+ export function getRequiredSheet(workbook: CanonicalWorkbook, sheetId: string): CanonicalSheet {
292
+ const sheet = workbook.sheets.get(sheetId);
293
+ if (!sheet) {
294
+ throw new Error(`Sheet not found: ${sheetId}`);
295
+ }
296
+ return sheet;
297
+ }
298
+
299
+ export function cloneSelection(selection: WorkbookSelection): WorkbookSelection {
300
+ return {
301
+ mode: selection.mode,
302
+ sheetId: selection.sheetId,
303
+ activeCell: selection.activeCell ? { ...selection.activeCell } : undefined,
304
+ range: selection.range ? { ...selection.range } : undefined,
305
+ };
306
+ }
307
+
308
+ export function mergeRangeToWorkbookRange(range: MergeRange): WorkbookRange {
309
+ return {
310
+ startRow: range.startRow,
311
+ startCol: range.startCol,
312
+ endRow: range.endRow,
313
+ endCol: range.endCol,
314
+ };
315
+ }
316
+
317
+ export function workbookRangeToMergeRange(range: WorkbookRange): MergeRange {
318
+ const normalized = normalizeRange(range);
319
+ return {
320
+ startRow: normalized.startRow,
321
+ startCol: normalized.startCol,
322
+ endRow: normalized.endRow,
323
+ endCol: normalized.endCol,
324
+ };
325
+ }
326
+
327
+ export function replaceSheetCells(
328
+ sheet: CanonicalSheet,
329
+ cells: Map<CellKey, CanonicalSheet["cells"] extends Map<CellKey, infer TValue> ? TValue : never>,
330
+ ): void {
331
+ sheet.cells = cells as CanonicalSheet["cells"];
332
+ }
333
+
334
+ export function replaceSheetRowProps(
335
+ sheet: CanonicalSheet,
336
+ rowProps: CanonicalSheet["rowProps"],
337
+ ): void {
338
+ sheet.rowProps = rowProps;
339
+ }
340
+
341
+ export function replaceSheetColProps(
342
+ sheet: CanonicalSheet,
343
+ colProps: CanonicalSheet["colProps"],
344
+ ): void {
345
+ sheet.colProps = colProps;
346
+ }
347
+
348
+ export function replaceSheetMerges(
349
+ sheet: CanonicalSheet,
350
+ merges: MergeRange[],
351
+ ): void {
352
+ sheet.merges = merges;
353
+ }
354
+
355
+ export function extractFormulaReferenceTokens(formula: string): string[] {
356
+ const maskedFormula = maskQuotedFormulaStrings(formula);
357
+ const tokens: string[] = [];
358
+ const seen = new Set<string>();
359
+
360
+ for (const match of maskedFormula.matchAll(FORMULA_REFERENCE_PATTERN)) {
361
+ const index = match.index ?? -1;
362
+ if (index < 0) {
363
+ continue;
364
+ }
365
+ const token = formula.slice(index, index + match[0].length);
366
+ if (seen.has(token)) {
367
+ continue;
368
+ }
369
+ seen.add(token);
370
+ tokens.push(token);
371
+ }
372
+
373
+ return tokens;
374
+ }
375
+
376
+ function invertOperation(operation: WorkbookTransactionOperation): WorkbookTransactionOperation {
377
+ switch (operation.type) {
378
+ case "cell-set":
379
+ return operation;
380
+ case "row-insert":
381
+ return { type: "row-delete", sheetId: operation.sheetId, index: operation.index, count: operation.count };
382
+ case "row-delete":
383
+ return { type: "row-insert", sheetId: operation.sheetId, index: operation.index, count: operation.count };
384
+ case "column-insert":
385
+ return { type: "column-delete", sheetId: operation.sheetId, index: operation.index, count: operation.count };
386
+ case "column-delete":
387
+ return { type: "column-insert", sheetId: operation.sheetId, index: operation.index, count: operation.count };
388
+ case "merge-add":
389
+ return { type: "merge-remove", sheetId: operation.sheetId, range: operation.range };
390
+ case "merge-remove":
391
+ return { type: "merge-add", sheetId: operation.sheetId, range: operation.range };
392
+ case "sheet-add":
393
+ return {
394
+ type: "sheet-remove",
395
+ sheetId: operation.sheetId,
396
+ index: operation.index,
397
+ name: operation.name,
398
+ };
399
+ case "sheet-remove":
400
+ return {
401
+ type: "sheet-add",
402
+ sheetId: operation.sheetId,
403
+ index: operation.index,
404
+ name: operation.name,
405
+ };
406
+ case "sheet-rename":
407
+ return {
408
+ type: "sheet-rename",
409
+ sheetId: operation.sheetId,
410
+ beforeName: operation.afterName,
411
+ afterName: operation.beforeName,
412
+ };
413
+ case "sheet-reorder":
414
+ return {
415
+ type: "sheet-reorder",
416
+ sheetId: operation.sheetId,
417
+ fromIndex: operation.toIndex,
418
+ toIndex: operation.fromIndex,
419
+ };
420
+ case "formula-remap":
421
+ return {
422
+ type: "formula-remap",
423
+ ownerSheetId: operation.ownerSheetId,
424
+ row: operation.row,
425
+ col: operation.col,
426
+ before: operation.after,
427
+ after: operation.before,
428
+ };
429
+ case "named-item-remap":
430
+ return {
431
+ type: "named-item-remap",
432
+ name: operation.name,
433
+ before: operation.after,
434
+ after: operation.before,
435
+ };
436
+ }
437
+ }
438
+
439
+ function mapSelectionThroughOperation(
440
+ selection: WorkbookSelection,
441
+ operation: WorkbookTransactionOperation,
442
+ ): WorkbookSelection {
443
+ const nextSelection = cloneSelection(selection);
444
+
445
+ switch (operation.type) {
446
+ case "sheet-remove":
447
+ if (nextSelection.sheetId === operation.sheetId) {
448
+ if (!operation.fallbackSheetId) {
449
+ return { mode: "sheet" };
450
+ }
451
+ nextSelection.sheetId = operation.fallbackSheetId;
452
+ }
453
+ return nextSelection;
454
+ case "row-insert":
455
+ case "row-delete":
456
+ if (nextSelection.sheetId !== operation.sheetId) {
457
+ return nextSelection;
458
+ }
459
+ if (nextSelection.activeCell) {
460
+ nextSelection.activeCell.row = mapIndexThroughOperation(nextSelection.activeCell.row, operation);
461
+ }
462
+ if (nextSelection.range) {
463
+ nextSelection.range.startRow = mapIndexThroughOperation(nextSelection.range.startRow, operation);
464
+ nextSelection.range.endRow = mapIndexThroughOperation(nextSelection.range.endRow, operation);
465
+ nextSelection.range = normalizeRange(nextSelection.range);
466
+ }
467
+ return nextSelection;
468
+ case "column-insert":
469
+ case "column-delete":
470
+ if (nextSelection.sheetId !== operation.sheetId) {
471
+ return nextSelection;
472
+ }
473
+ if (nextSelection.activeCell) {
474
+ nextSelection.activeCell.col = mapIndexThroughOperation(nextSelection.activeCell.col, operation);
475
+ }
476
+ if (nextSelection.range) {
477
+ nextSelection.range.startCol = mapIndexThroughOperation(nextSelection.range.startCol, operation);
478
+ nextSelection.range.endCol = mapIndexThroughOperation(nextSelection.range.endCol, operation);
479
+ nextSelection.range = normalizeRange(nextSelection.range);
480
+ }
481
+ return nextSelection;
482
+ default:
483
+ return nextSelection;
484
+ }
485
+ }
486
+
487
+ function mapIndexThroughOperation(
488
+ value: number,
489
+ operation:
490
+ | Extract<WorkbookTransactionOperation, { type: "row-insert" | "row-delete" }>
491
+ | Extract<WorkbookTransactionOperation, { type: "column-insert" | "column-delete" }>,
492
+ ): number {
493
+ if (operation.type === "row-insert" || operation.type === "column-insert") {
494
+ return value >= operation.index ? value + operation.count : value;
495
+ }
496
+
497
+ const deleteEnd = operation.index + operation.count - 1;
498
+ if (value < operation.index) {
499
+ return value;
500
+ }
501
+ if (value <= deleteEnd) {
502
+ return operation.index;
503
+ }
504
+ return value - operation.count;
505
+ }
506
+
507
+ function remapNamedItemForMutation(
508
+ item: NamedItem,
509
+ workbook: CanonicalWorkbook,
510
+ targetSheetName: string,
511
+ mutation: FormulaMutation,
512
+ mapping: WorkbookTransactionMapping,
513
+ ): NamedItem | null {
514
+ if (mutation.kind === "remove-sheet" && item.localSheetId === findSheetIdByName(workbook, mutation.removedName)) {
515
+ return null;
516
+ }
517
+
518
+ const ownerSheetName = item.localSheetId ? workbook.sheets.get(item.localSheetId)?.name : undefined;
519
+ const rewritten = rewriteFormulaReferences(
520
+ item.refersTo,
521
+ ownerSheetName,
522
+ targetSheetName,
523
+ mutation,
524
+ );
525
+ if (!rewritten.changed) {
526
+ return item;
527
+ }
528
+
529
+ mapping.operations.push({
530
+ type: "named-item-remap",
531
+ name: item.name,
532
+ before: item.refersTo,
533
+ after: rewritten.formula,
534
+ });
535
+
536
+ return {
537
+ ...item,
538
+ refersTo: rewritten.formula,
539
+ };
540
+ }
541
+
542
+ function findSheetIdByName(workbook: CanonicalWorkbook, name: string): string | undefined {
543
+ for (const sheet of workbook.sheets.values()) {
544
+ if (sheet.name === name) {
545
+ return sheet.sheetId;
546
+ }
547
+ }
548
+ return undefined;
549
+ }
550
+
551
+ function rewriteFormulaReferences(
552
+ formula: string,
553
+ ownerSheetName: string | undefined,
554
+ targetSheetName: string,
555
+ mutation: FormulaMutation,
556
+ ): { formula: string; changed: boolean } {
557
+ const maskedFormula = maskQuotedFormulaStrings(formula);
558
+ const matches = [...maskedFormula.matchAll(FORMULA_REFERENCE_PATTERN)];
559
+ if (matches.length === 0) {
560
+ return { formula, changed: false };
561
+ }
562
+
563
+ let changed = false;
564
+ let lastIndex = 0;
565
+ let output = "";
566
+
567
+ for (const match of matches) {
568
+ const index = match.index ?? -1;
569
+ if (index < 0) {
570
+ continue;
571
+ }
572
+
573
+ const originalToken = formula.slice(index, index + match[0].length);
574
+ const nextToken = rewriteFormulaToken(
575
+ originalToken,
576
+ ownerSheetName,
577
+ targetSheetName,
578
+ mutation,
579
+ );
580
+
581
+ output += formula.slice(lastIndex, index);
582
+ output += nextToken;
583
+ lastIndex = index + originalToken.length;
584
+ changed = changed || nextToken !== originalToken;
585
+ }
586
+
587
+ if (!changed) {
588
+ return { formula, changed: false };
589
+ }
590
+
591
+ output += formula.slice(lastIndex);
592
+ return { formula: output, changed: true };
593
+ }
594
+
595
+ function rewriteFormulaToken(
596
+ token: string,
597
+ ownerSheetName: string | undefined,
598
+ targetSheetName: string,
599
+ mutation: FormulaMutation,
600
+ ): string {
601
+ const parsed = parseFormulaToken(token);
602
+ if (!parsed) {
603
+ return token;
604
+ }
605
+
606
+ if (mutation.kind === "rename-sheet") {
607
+ if (parsed.sheetName !== mutation.beforeName) {
608
+ return token;
609
+ }
610
+
611
+ return formatFormulaToken({
612
+ ...parsed,
613
+ sheetName: mutation.afterName,
614
+ sheetQuoted: parsed.sheetQuoted || !SIMPLE_SHEET_NAME_PATTERN.test(mutation.afterName),
615
+ });
616
+ }
617
+
618
+ if (mutation.kind === "remove-sheet") {
619
+ return parsed.sheetName === mutation.removedName ? "#REF!" : token;
620
+ }
621
+
622
+ const tokenSheetName = parsed.sheetName ?? ownerSheetName;
623
+ if (tokenSheetName !== targetSheetName) {
624
+ return token;
625
+ }
626
+
627
+ const rowRange = mutation.axis === "row"
628
+ ? remapInterval(parsed.start.row, parsed.end?.row ?? parsed.start.row, mutation)
629
+ : { valid: true, start: parsed.start.row, end: parsed.end?.row ?? parsed.start.row };
630
+ const colRange = mutation.axis === "col"
631
+ ? remapInterval(parsed.start.col, parsed.end?.col ?? parsed.start.col, mutation)
632
+ : { valid: true, start: parsed.start.col, end: parsed.end?.col ?? parsed.start.col };
633
+
634
+ if (!rowRange.valid || !colRange.valid) {
635
+ return "#REF!";
636
+ }
637
+
638
+ const nextToken: ParsedFormulaToken = {
639
+ sheetName: parsed.sheetName,
640
+ sheetQuoted: parsed.sheetQuoted,
641
+ start: {
642
+ ...parsed.start,
643
+ row: rowRange.start,
644
+ col: colRange.start,
645
+ },
646
+ ...(parsed.end
647
+ ? {
648
+ end: {
649
+ ...parsed.end,
650
+ row: rowRange.end,
651
+ col: colRange.end,
652
+ },
653
+ }
654
+ : {}),
655
+ };
656
+
657
+ return formatFormulaToken(nextToken);
658
+ }
659
+
660
+ function remapInterval(
661
+ start: number,
662
+ end: number,
663
+ mutation: InsertAxisMutation | DeleteAxisMutation,
664
+ ): { valid: boolean; start: number; end: number } {
665
+ if (mutation.kind === "insert") {
666
+ if (mutation.index <= start) {
667
+ return {
668
+ valid: true,
669
+ start: start + mutation.count,
670
+ end: end + mutation.count,
671
+ };
672
+ }
673
+ if (mutation.index <= end) {
674
+ return {
675
+ valid: true,
676
+ start,
677
+ end: end + mutation.count,
678
+ };
679
+ }
680
+ return { valid: true, start, end };
681
+ }
682
+
683
+ const deleteStart = mutation.index;
684
+ const deleteEnd = mutation.index + mutation.count - 1;
685
+ const overlapStart = Math.max(start, deleteStart);
686
+ const overlapEnd = Math.min(end, deleteEnd);
687
+ if (overlapStart <= overlapEnd && overlapEnd - overlapStart + 1 >= end - start + 1) {
688
+ return { valid: false, start, end };
689
+ }
690
+
691
+ let nextStart = start;
692
+ let nextEnd = end;
693
+ if (start >= deleteStart && start <= deleteEnd) {
694
+ nextStart = deleteStart;
695
+ } else if (start > deleteEnd) {
696
+ nextStart = start - mutation.count;
697
+ }
698
+
699
+ if (end >= deleteStart && end <= deleteEnd) {
700
+ nextEnd = deleteStart - 1;
701
+ } else if (end > deleteEnd) {
702
+ nextEnd = end - mutation.count;
703
+ }
704
+
705
+ if (nextEnd < nextStart) {
706
+ nextEnd = nextStart;
707
+ }
708
+
709
+ return {
710
+ valid: true,
711
+ start: nextStart,
712
+ end: nextEnd,
713
+ };
714
+ }
715
+
716
+ function parseFormulaToken(token: string): ParsedFormulaToken | null {
717
+ const match = /^(?:(('(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!)?(\$?[A-Z]{1,3}\$?[1-9][0-9]*)(?::(\$?[A-Z]{1,3}\$?[1-9][0-9]*))?)$/.exec(token);
718
+ if (!match) {
719
+ return null;
720
+ }
721
+
722
+ const sheetRaw = match[2];
723
+ const sheetName = sheetRaw
724
+ ? sheetRaw.startsWith("'")
725
+ ? sheetRaw.slice(1, -1).replace(/''/g, "'")
726
+ : sheetRaw
727
+ : undefined;
728
+ const start = parseA1CellRef(match[3] ?? "");
729
+ const end = match[4] ? parseA1CellRef(match[4]) : undefined;
730
+ if (!start || (match[4] && !end)) {
731
+ return null;
732
+ }
733
+
734
+ return {
735
+ sheetName,
736
+ sheetQuoted: sheetRaw ? sheetRaw.startsWith("'") : false,
737
+ start,
738
+ ...(end ? { end } : {}),
739
+ };
740
+ }
741
+
742
+ function parseA1CellRef(ref: string): ParsedA1CellRef | null {
743
+ const match = /^(\$?)([A-Z]{1,3})(\$?)([1-9][0-9]*)$/.exec(ref);
744
+ if (!match) {
745
+ return null;
746
+ }
747
+
748
+ return {
749
+ colAbsolute: match[1] === "$",
750
+ col: parseColumnLetters(match[2]),
751
+ rowAbsolute: match[3] === "$",
752
+ row: Number.parseInt(match[4] ?? "1", 10) - 1,
753
+ };
754
+ }
755
+
756
+ function formatFormulaToken(token: ParsedFormulaToken): string {
757
+ const sheetPrefix = token.sheetName
758
+ ? `${formatSheetName(token.sheetName, token.sheetQuoted)}!`
759
+ : "";
760
+ const start = formatA1CellRef(token.start);
761
+ if (!token.end || (token.start.row === token.end.row && token.start.col === token.end.col)) {
762
+ return `${sheetPrefix}${start}`;
763
+ }
764
+ return `${sheetPrefix}${start}:${formatA1CellRef(token.end)}`;
765
+ }
766
+
767
+ function formatA1CellRef(ref: ParsedA1CellRef): string {
768
+ return `${ref.colAbsolute ? "$" : ""}${formatColumnLetters(ref.col)}${ref.rowAbsolute ? "$" : ""}${ref.row + 1}`;
769
+ }
770
+
771
+ function formatSheetName(name: string, forceQuote: boolean): string {
772
+ if (!forceQuote && SIMPLE_SHEET_NAME_PATTERN.test(name)) {
773
+ return name;
774
+ }
775
+ return `'${name.replace(/'/g, "''")}'`;
776
+ }
777
+
778
+ function parseColumnLetters(letters: string): number {
779
+ let value = 0;
780
+ for (const char of letters) {
781
+ value = value * 26 + (char.charCodeAt(0) - 64);
782
+ }
783
+ return value - 1;
784
+ }
785
+
786
+ function formatColumnLetters(value: number): string {
787
+ let next = value + 1;
788
+ let output = "";
789
+
790
+ while (next > 0) {
791
+ const remainder = (next - 1) % 26;
792
+ output = String.fromCharCode(65 + remainder) + output;
793
+ next = Math.floor((next - 1) / 26);
794
+ }
795
+
796
+ return output;
797
+ }
798
+
799
+ function maskQuotedFormulaStrings(formula: string): string {
800
+ let output = "";
801
+ let inString = false;
802
+
803
+ for (let index = 0; index < formula.length; index += 1) {
804
+ const char = formula[index];
805
+ const next = formula[index + 1];
806
+
807
+ if (char === "\"") {
808
+ output += char;
809
+ if (inString && next === "\"") {
810
+ output += " ";
811
+ index += 1;
812
+ continue;
813
+ }
814
+ inString = !inString;
815
+ continue;
816
+ }
817
+
818
+ output += inString ? " " : char;
819
+ }
820
+
821
+ return output;
822
+ }