@jsb188/mday 1.1.8 → 1.1.11
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.
- package/package.json +105 -35
- package/src/constants/agentDoc.ts +12 -0
- package/src/constants/agentMemory.ts +154 -0
- package/src/constants/aiChat.ts +5 -0
- package/src/constants/campaign.ts +127 -0
- package/src/constants/dataTable.ts +48 -0
- package/src/constants/dataTableFieldTypes.generated.ts +63 -0
- package/src/constants/docAccess.ts +32 -0
- package/src/constants/email.ts +44 -0
- package/src/constants/fieldDoc.ts +34 -0
- package/src/constants/graphqlReactivity.ts +113 -0
- package/src/constants/inboundContact.ts +8 -0
- package/src/constants/integration.ts +13 -0
- package/src/constants/log.ts +7 -366
- package/src/constants/logActivityGroupColors.generated.ts +19 -0
- package/src/constants/logTaxonomy.generated.ts +1103 -0
- package/src/constants/noteDoc.ts +77 -0
- package/src/constants/organization.ts +18 -11
- package/src/constants/pageRoute.ts +23 -0
- package/src/constants/schedule.ts +220 -0
- package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
- package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
- package/src/constants/sheet.ts +168 -0
- package/src/constants/sheetRegionSources.generated.ts +578 -0
- package/src/constants/square.ts +16 -0
- package/src/constants/storage.ts +61 -0
- package/src/constants/usage.ts +79 -0
- package/src/schemas/editLogEntry.ts +1017 -738
- package/src/schemas/fieldDocsQuery.ts +12 -0
- package/src/schemas/inboundContact.ts +77 -0
- package/src/schemas/logsQuery.ts +57 -316
- package/src/schemas/organization.ts +53 -213
- package/src/types/account.d.ts +81 -0
- package/src/types/agentDoc.d.ts +64 -0
- package/src/types/agentMemory.d.ts +74 -0
- package/src/types/campaign.d.ts +683 -0
- package/src/types/dataTable.d.ts +366 -0
- package/src/types/docAccess.d.ts +96 -0
- package/src/types/email.d.ts +142 -0
- package/src/types/fieldDoc.d.ts +273 -0
- package/src/types/inboundContact.d.ts +57 -0
- package/src/types/integration.d.ts +42 -0
- package/src/types/log.d.ts +169 -190
- package/src/types/noteDoc.d.ts +86 -0
- package/src/types/organization.d.ts +175 -76
- package/src/types/pageRoute.d.ts +48 -0
- package/src/types/schedule.d.ts +391 -0
- package/src/types/sheet.d.ts +1130 -0
- package/src/types/storage.d.ts +242 -0
- package/src/types/usage.d.ts +106 -0
- package/src/types/workflow.d.ts +305 -0
- package/src/utils/agentDoc.ts +109 -0
- package/src/utils/aiChat.ts +26 -0
- package/src/utils/campaign.ts +741 -0
- package/src/utils/campaignFormEditor.ts +871 -0
- package/src/utils/dataTable.ts +849 -0
- package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
- package/src/utils/dataTableRealtimeAuthority.ts +209 -0
- package/src/utils/dataTableRealtimeSelection.ts +134 -0
- package/src/utils/dataTableRowDocument.ts +508 -0
- package/src/utils/dataTableSource.ts +230 -0
- package/src/utils/docAccess.ts +383 -0
- package/src/utils/documentName.ts +53 -0
- package/src/utils/email.ts +172 -0
- package/src/utils/fieldDoc.ts +113 -0
- package/src/utils/log.ts +173 -778
- package/src/utils/logRegistryValue.ts +90 -0
- package/src/utils/logStoreRead.ts +266 -0
- package/src/utils/logTaxonomy.ts +76 -0
- package/src/utils/logTaxonomyDisplay.ts +439 -0
- package/src/utils/noteDoc.ts +827 -0
- package/src/utils/organization.ts +683 -81
- package/src/utils/pageRoute.ts +71 -0
- package/src/utils/schedule.ts +799 -0
- package/src/utils/scheduleEvaluation.ts +1994 -0
- package/src/utils/scheduleICS.ts +246 -0
- package/src/utils/scheduleRuleTemplates.ts +188 -0
- package/src/utils/sheet.ts +4973 -0
- package/src/utils/sheetAxisMove.ts +830 -0
- package/src/utils/sheetBootstrap.ts +1769 -0
- package/src/utils/sheetCommand.ts +423 -0
- package/src/utils/sheetExport.ts +238 -0
- package/src/utils/sheetFormulaEvaluation.ts +914 -0
- package/src/utils/sheetFormulaEvaluator.ts +852 -0
- package/src/utils/sheetJournal.ts +78 -0
- package/src/utils/sheetNumberFormat.ts +1211 -0
- package/src/utils/sheetRegion.ts +374 -0
- package/src/utils/sheetRegionFilter.ts +1259 -0
- package/src/utils/sheetRegionSourceRegistry.ts +594 -0
- package/src/utils/sheetSequence.ts +148 -0
- package/src/utils/sheetSnapshot.ts +992 -0
- package/src/utils/sheetStructureEdit.ts +1284 -0
- package/src/utils/square.ts +32 -0
- package/src/utils/storage.ts +152 -0
- package/src/utils/table-route.ts +262 -0
- package/src/utils/workflow.ts +380 -0
- package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
- package/tests/docAccess.test.ts +525 -0
- package/tests/editLogEntry.test.ts +112 -0
- package/tests/noteDoc.test.ts +669 -0
- package/tests/schedule.test.ts +693 -0
- package/tests/scheduleEvaluation.test.ts +1970 -0
- package/tests/scheduleICS.test.ts +208 -0
- package/tests/scheduleRuleTemplates.test.ts +176 -0
- package/tests/scheduleSweepInvariants.test.ts +428 -0
- package/tests/sheetAxisMove.test.ts +343 -0
- package/tests/sheetFormulaEvaluator.test.ts +575 -0
- package/tests/sheetRegionFilter.test.ts +1135 -0
- package/tests/sheetSequence.test.ts +41 -0
- package/tests/sheetStructureEdit.test.ts +82 -0
- package/tsconfig.json +12 -0
- package/vitest.config.ts +8 -0
- package/src/constants/log-activityTexts.ts +0 -209
- package/src/constants/product.ts +0 -66
- package/src/constants/report.ts +0 -25
- package/src/schemas/childOrganizationsQuery.ts +0 -44
- package/src/schemas/productsQuery.ts +0 -145
- package/src/schemas/reportsQuery.ts +0 -107
- package/src/types/action.d.ts +0 -42
- package/src/types/product.d.ts +0 -173
- package/src/types/report.d.ts +0 -203
- package/src/utils/product-calEvent.ts +0 -508
- package/src/utils/route-helpers.ts +0 -583
|
@@ -0,0 +1,4973 @@
|
|
|
1
|
+
import i18n from '@jsb188/app/i18n/index.ts';
|
|
2
|
+
import {
|
|
3
|
+
GRID_ITEM_LIST_LIMIT,
|
|
4
|
+
SHEET_CELL_SOURCE_TYPE_ENUMS,
|
|
5
|
+
SHEET_CELL_TEXT_ALIGN_ENUMS,
|
|
6
|
+
SHEET_CELL_TEXT_WRAP_ENUMS,
|
|
7
|
+
SHEET_CELL_VERTICAL_ALIGN_ENUMS,
|
|
8
|
+
SHEET_CUSTOM_REGION_SOURCE_CHILD_ORGANIZATIONS,
|
|
9
|
+
SHEET_CUSTOM_REGION_SOURCE_LOGS,
|
|
10
|
+
SHEET_DEFAULT_COLUMN_COUNT,
|
|
11
|
+
SHEET_DEFAULT_ROW_COUNT,
|
|
12
|
+
SHEET_MAX_COLUMN_COUNT,
|
|
13
|
+
SHEET_MAX_ROW_COUNT,
|
|
14
|
+
SHEET_REGION_CONFLICT_POLICY_ENUMS,
|
|
15
|
+
SHEET_REGION_SOURCE_DESCRIPTORS,
|
|
16
|
+
SHEET_REGION_SOURCE_TYPE_ENUMS,
|
|
17
|
+
SHEET_REGION_TYPE_ENUMS,
|
|
18
|
+
SHEET_STRUCTURE_OPERATION_ENUMS,
|
|
19
|
+
SHEET_VIEWPORT_MAX_COLUMNS,
|
|
20
|
+
SHEET_VIEWPORT_MAX_ROWS,
|
|
21
|
+
} from '../constants/sheet.ts';
|
|
22
|
+
import type {
|
|
23
|
+
DataTableDesignCellGQL,
|
|
24
|
+
DataTableFieldTypeGQL,
|
|
25
|
+
DataTableGQL,
|
|
26
|
+
} from '../types/dataTable.d.ts';
|
|
27
|
+
import type { OrganizationOperationEnum } from '../types/organization.d.ts';
|
|
28
|
+
import type {
|
|
29
|
+
SheetAxisDesignObj,
|
|
30
|
+
SheetCellBorderStyleValue,
|
|
31
|
+
SheetCellFormatObj,
|
|
32
|
+
SheetCellGQL,
|
|
33
|
+
SheetCellNumberFormatObj,
|
|
34
|
+
SheetCellSourceTypeEnum,
|
|
35
|
+
SheetCellStyleObj,
|
|
36
|
+
SheetCellTextAlignEnum,
|
|
37
|
+
SheetCellTextWrapEnum,
|
|
38
|
+
SheetCellValueTypeEnum,
|
|
39
|
+
SheetCellVerticalAlignEnum,
|
|
40
|
+
SheetCompiledFormulaObj,
|
|
41
|
+
SheetCustomRegionSourceColumnObj,
|
|
42
|
+
SheetDesignObj,
|
|
43
|
+
SheetGridViewportObj,
|
|
44
|
+
SheetMergedRangeObj,
|
|
45
|
+
SheetRangeData,
|
|
46
|
+
SheetRegionConflictPolicyEnum,
|
|
47
|
+
SheetRegionGQL,
|
|
48
|
+
SheetRegionSourceFilterGroupObj,
|
|
49
|
+
SheetRegionSourceObj,
|
|
50
|
+
SheetRegionSourceTypeEnum,
|
|
51
|
+
SheetRegionTypeEnum,
|
|
52
|
+
SheetStructureOperationEnum,
|
|
53
|
+
} from '../types/sheet.d.ts';
|
|
54
|
+
import { isOrganizationChildProfileLinkCellKey } from './organization.ts';
|
|
55
|
+
import { isSheetCellNumberFormatType } from './sheetNumberFormat.ts';
|
|
56
|
+
|
|
57
|
+
/*
|
|
58
|
+
* Return a normalized title value for cursor pagination across grid items.
|
|
59
|
+
*/
|
|
60
|
+
export function getGridItemTitleCursorValue(item: {
|
|
61
|
+
name?: string | null;
|
|
62
|
+
title?: string | null;
|
|
63
|
+
}) {
|
|
64
|
+
return String(item.title || item.name || '')
|
|
65
|
+
.trim()
|
|
66
|
+
.toLowerCase();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/*
|
|
70
|
+
* Encode a grid item title cursor value for GraphQL's colon-delimited Cursor scalar.
|
|
71
|
+
*/
|
|
72
|
+
export function encodeGridItemTitleCursorValue(
|
|
73
|
+
value: string | null | undefined,
|
|
74
|
+
) {
|
|
75
|
+
return encodeURIComponent(String(value || ''));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/*
|
|
79
|
+
* Decode a grid item title cursor value from GraphQL's colon-delimited Cursor scalar.
|
|
80
|
+
*/
|
|
81
|
+
export function decodeGridItemTitleCursorValue(
|
|
82
|
+
value: string | null | undefined,
|
|
83
|
+
) {
|
|
84
|
+
try {
|
|
85
|
+
return decodeURIComponent(String(value || ''));
|
|
86
|
+
} catch {
|
|
87
|
+
return String(value || '');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/*
|
|
92
|
+
* Return a safe page size for grid item list pagination.
|
|
93
|
+
*/
|
|
94
|
+
export function getGridItemListLimit(limit?: number | null) {
|
|
95
|
+
return Math.min(
|
|
96
|
+
GRID_ITEM_LIST_LIMIT,
|
|
97
|
+
Math.max(0, Math.floor(Number(limit) || GRID_ITEM_LIST_LIMIT)),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type SheetFormulaOperatorTerm<Operator extends string> = {
|
|
102
|
+
expression: string;
|
|
103
|
+
operator: Operator;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export type SheetFormulaCellReference = {
|
|
107
|
+
columnAbsolute?: boolean;
|
|
108
|
+
columnIndex: number;
|
|
109
|
+
columnLabel: string;
|
|
110
|
+
rowAbsolute?: boolean;
|
|
111
|
+
rowIndex: number;
|
|
112
|
+
sheetName?: string | null;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export type SheetProtectedAxisSpan = {
|
|
116
|
+
endIndex: number;
|
|
117
|
+
startIndex: number;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
export type SheetFormulaRangeReference = {
|
|
121
|
+
endColumnIndex: number;
|
|
122
|
+
endColumnLabel: string;
|
|
123
|
+
endRowIndex: number;
|
|
124
|
+
sheetName?: string | null;
|
|
125
|
+
startColumnIndex: number;
|
|
126
|
+
startColumnLabel: string;
|
|
127
|
+
startRowIndex: number;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
export type SheetFormulaCall = {
|
|
131
|
+
args: string[];
|
|
132
|
+
name: string;
|
|
133
|
+
text: string;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
export type SheetFormulaDataTableCall = {
|
|
137
|
+
cellKey: string;
|
|
138
|
+
dataTableName: string;
|
|
139
|
+
rowIdentifierExpression: string;
|
|
140
|
+
text: string;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
export type SheetFormulaDataTableQueryOperator =
|
|
144
|
+
| '!='
|
|
145
|
+
| '<'
|
|
146
|
+
| '<='
|
|
147
|
+
| '<>'
|
|
148
|
+
| '='
|
|
149
|
+
| '>'
|
|
150
|
+
| '>=';
|
|
151
|
+
|
|
152
|
+
export type SheetFormulaDateTimeShorthandName =
|
|
153
|
+
| 'CURRENT_DATE'
|
|
154
|
+
| 'CURRENT_DATETIME';
|
|
155
|
+
|
|
156
|
+
export type SheetFormulaDataTableQueryCondition = {
|
|
157
|
+
cellKey: string;
|
|
158
|
+
operator: SheetFormulaDataTableQueryOperator;
|
|
159
|
+
text: string;
|
|
160
|
+
valueExpression: string;
|
|
161
|
+
valueNode: SheetFormulaASTNode;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
export type SheetFormulaDataTableQueryCall = {
|
|
165
|
+
cellKey: string;
|
|
166
|
+
conditions: SheetFormulaDataTableQueryCondition[];
|
|
167
|
+
dataTableName: string;
|
|
168
|
+
text: string;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export type SheetFormulaSyntaxIssue = {
|
|
172
|
+
message: string;
|
|
173
|
+
text?: string | null;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
export type SheetFormulaASTNode =
|
|
177
|
+
| {
|
|
178
|
+
kind: 'BOOLEAN_LITERAL';
|
|
179
|
+
text: string;
|
|
180
|
+
value: boolean;
|
|
181
|
+
}
|
|
182
|
+
| {
|
|
183
|
+
kind: 'CELL_REFERENCE';
|
|
184
|
+
reference: SheetFormulaCellReference;
|
|
185
|
+
text: string;
|
|
186
|
+
}
|
|
187
|
+
| {
|
|
188
|
+
args: SheetFormulaASTNode[];
|
|
189
|
+
kind: 'FUNCTION_CALL';
|
|
190
|
+
name: string;
|
|
191
|
+
text: string;
|
|
192
|
+
}
|
|
193
|
+
| {
|
|
194
|
+
kind: 'DATA_TABLE_QUERY';
|
|
195
|
+
query: SheetFormulaDataTableQueryCall;
|
|
196
|
+
text: string;
|
|
197
|
+
}
|
|
198
|
+
| {
|
|
199
|
+
kind: 'DATE_TIME_SHORTHAND';
|
|
200
|
+
name: SheetFormulaDateTimeShorthandName;
|
|
201
|
+
text: string;
|
|
202
|
+
}
|
|
203
|
+
| {
|
|
204
|
+
kind: 'NUMBER_LITERAL';
|
|
205
|
+
text: string;
|
|
206
|
+
value: number;
|
|
207
|
+
}
|
|
208
|
+
| {
|
|
209
|
+
kind: 'RANGE_REFERENCE';
|
|
210
|
+
reference: SheetFormulaRangeReference;
|
|
211
|
+
text: string;
|
|
212
|
+
}
|
|
213
|
+
| {
|
|
214
|
+
kind: 'STRING_LITERAL';
|
|
215
|
+
text: string;
|
|
216
|
+
value: string;
|
|
217
|
+
}
|
|
218
|
+
| {
|
|
219
|
+
kind: 'BINARY_EXPRESSION';
|
|
220
|
+
left: SheetFormulaASTNode;
|
|
221
|
+
operator: SheetFormulaBinaryOperator;
|
|
222
|
+
right: SheetFormulaASTNode;
|
|
223
|
+
text: string;
|
|
224
|
+
}
|
|
225
|
+
| {
|
|
226
|
+
kind: 'UNARY_EXPRESSION';
|
|
227
|
+
operator: '+' | '-';
|
|
228
|
+
text: string;
|
|
229
|
+
value: SheetFormulaASTNode;
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
export type SheetFormulaBinaryOperator =
|
|
233
|
+
| '!='
|
|
234
|
+
| '*'
|
|
235
|
+
| '+'
|
|
236
|
+
| '-'
|
|
237
|
+
| '/'
|
|
238
|
+
| '<'
|
|
239
|
+
| '<='
|
|
240
|
+
| '<>'
|
|
241
|
+
| '='
|
|
242
|
+
| '>'
|
|
243
|
+
| '>=';
|
|
244
|
+
|
|
245
|
+
type SheetFormulaParserState = {
|
|
246
|
+
index: number;
|
|
247
|
+
value: string;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
type SheetRegionSourceLocator = {
|
|
251
|
+
dataTableId?: number | bigint | string | null;
|
|
252
|
+
sourceDataTableId?: number | bigint | string | null;
|
|
253
|
+
sourceId?: number | bigint | string | null;
|
|
254
|
+
sourceType?: SheetRegionSourceTypeEnum | string | null;
|
|
255
|
+
type?: SheetRegionSourceTypeEnum | string | null;
|
|
256
|
+
source?: Pick<SheetRegionSourceObj, 'dataTableId' | 'type'> | null;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
export type SheetFormulaReferenceToken =
|
|
260
|
+
| (SheetFormulaCellReference & {
|
|
261
|
+
coordinateEndIndex: number;
|
|
262
|
+
coordinateStartIndex: number;
|
|
263
|
+
endIndex: number;
|
|
264
|
+
kind: 'SHEET_CELL';
|
|
265
|
+
startIndex: number;
|
|
266
|
+
text: string;
|
|
267
|
+
})
|
|
268
|
+
| (SheetFormulaRangeReference & {
|
|
269
|
+
endReference: SheetFormulaCellReference;
|
|
270
|
+
endReferenceCoordinateEndIndex: number;
|
|
271
|
+
endReferenceCoordinateStartIndex: number;
|
|
272
|
+
endIndex: number;
|
|
273
|
+
kind: 'SHEET_RANGE';
|
|
274
|
+
startReference: SheetFormulaCellReference;
|
|
275
|
+
startReferenceCoordinateEndIndex: number;
|
|
276
|
+
startReferenceCoordinateStartIndex: number;
|
|
277
|
+
startIndex: number;
|
|
278
|
+
text: string;
|
|
279
|
+
})
|
|
280
|
+
| (SheetFormulaDataTableCall & {
|
|
281
|
+
endIndex: number;
|
|
282
|
+
kind: 'DATA_TABLE_CELL';
|
|
283
|
+
startIndex: number;
|
|
284
|
+
})
|
|
285
|
+
| (SheetFormulaDataTableQueryCall & {
|
|
286
|
+
endIndex: number;
|
|
287
|
+
kind: 'DATA_TABLE_QUERY_CELL';
|
|
288
|
+
startIndex: number;
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
export type SheetFormulaFunctionCallArgToken = {
|
|
292
|
+
argIndex: number;
|
|
293
|
+
endIndex: number;
|
|
294
|
+
startIndex: number;
|
|
295
|
+
text: string;
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
export type SheetFormulaFunctionCallToken = {
|
|
299
|
+
args: SheetFormulaFunctionCallArgToken[];
|
|
300
|
+
callEndIndex: number;
|
|
301
|
+
callStartIndex: number;
|
|
302
|
+
endIndex: number;
|
|
303
|
+
hasOpenParen: boolean;
|
|
304
|
+
isComplete: boolean;
|
|
305
|
+
name: string;
|
|
306
|
+
nameEndIndex: number;
|
|
307
|
+
nameStartIndex: number;
|
|
308
|
+
openParenIndex: number | null;
|
|
309
|
+
startIndex: number;
|
|
310
|
+
text: string;
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
type SheetFormulaSheetTabNamePrefixToken = {
|
|
314
|
+
endIndex: number;
|
|
315
|
+
sheetName: string;
|
|
316
|
+
startIndex: number;
|
|
317
|
+
text: string;
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
export type SheetFormulaSheetTabNameRewriteResult = {
|
|
321
|
+
changed: boolean;
|
|
322
|
+
text: string;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const SHEET_CELL_BORDER_SIDES = ['Top', 'Right', 'Bottom', 'Left'] as const;
|
|
326
|
+
const SHEET_CELL_BORDER_STYLE_VALUES = [
|
|
327
|
+
'solid',
|
|
328
|
+
'dashed',
|
|
329
|
+
'dotted',
|
|
330
|
+
'double',
|
|
331
|
+
] as const;
|
|
332
|
+
const SHEET_CELL_TEXT_STYLE_BOOLEAN_KEYS = [
|
|
333
|
+
'bold',
|
|
334
|
+
'italic',
|
|
335
|
+
'underline',
|
|
336
|
+
'strikethrough',
|
|
337
|
+
] as const;
|
|
338
|
+
const SHEET_FORMULA_STRING_QUOTE_CHARS = ['"', "'", '`'] as const;
|
|
339
|
+
const SHEET_FORMULA_BARE_DATA_TABLE_CELL_KEY_PATTERN =
|
|
340
|
+
/^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
341
|
+
const SHEET_FORMULA_BARE_STRING_VALUE_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
342
|
+
const SHEET_FORMULA_ISO_DATE_VALUE_PATTERN =
|
|
343
|
+
/^\d{4}-\d{2}-\d{2}(?:[T ][0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]+)?)?(?:Z|[+-][0-9]{2}:[0-9]{2})?)?$/;
|
|
344
|
+
export const SHEET_CELL_STYLE_MAX_FONT_SIZE = 48;
|
|
345
|
+
|
|
346
|
+
/*
|
|
347
|
+
* Return whether one character starts a supported formula string literal.
|
|
348
|
+
*/
|
|
349
|
+
function isSheetFormulaStringQuoteChar(
|
|
350
|
+
char?: string,
|
|
351
|
+
): char is (typeof SHEET_FORMULA_STRING_QUOTE_CHARS)[number] {
|
|
352
|
+
return SHEET_FORMULA_STRING_QUOTE_CHARS.includes(
|
|
353
|
+
char as (typeof SHEET_FORMULA_STRING_QUOTE_CHARS)[number],
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/*
|
|
358
|
+
* Return a plain object from flexible saved Sheet style input.
|
|
359
|
+
*/
|
|
360
|
+
function getSheetCellStyleObject(value?: unknown): Record<string, any> {
|
|
361
|
+
if (!value) {
|
|
362
|
+
return {};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (typeof value === 'object' && !Array.isArray(value)) {
|
|
366
|
+
return value as Record<string, any>;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (typeof value !== 'string') {
|
|
370
|
+
return {};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
try {
|
|
374
|
+
const parsed = JSON.parse(value);
|
|
375
|
+
|
|
376
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
377
|
+
? parsed
|
|
378
|
+
: {};
|
|
379
|
+
} catch {
|
|
380
|
+
return {};
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/*
|
|
385
|
+
* Return a positive rounded integer value when a style number is usable.
|
|
386
|
+
*/
|
|
387
|
+
function normalizeSheetCellStylePositiveInteger(value: unknown) {
|
|
388
|
+
const numberValue = Math.round(Number(value));
|
|
389
|
+
|
|
390
|
+
return Number.isFinite(numberValue) && numberValue > 0 ? numberValue : null;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/*
|
|
394
|
+
* Return a valid Sheet cell font size rounded to an integer and capped to the supported range.
|
|
395
|
+
*/
|
|
396
|
+
export function normalizeSheetCellFontSize(value: unknown) {
|
|
397
|
+
const fontSize = normalizeSheetCellStylePositiveInteger(value);
|
|
398
|
+
|
|
399
|
+
return fontSize ? Math.min(SHEET_CELL_STYLE_MAX_FONT_SIZE, fontSize) : null;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/*
|
|
403
|
+
* Return a supported cell border width or null when the side should be disabled.
|
|
404
|
+
*/
|
|
405
|
+
function normalizeSheetCellBorderWidth(value: unknown) {
|
|
406
|
+
const width = normalizeSheetCellStylePositiveInteger(value);
|
|
407
|
+
|
|
408
|
+
return width && width >= 1 && width <= 4 ? width : null;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/*
|
|
412
|
+
* Return a supported cell border style or null when the style should be dropped.
|
|
413
|
+
*/
|
|
414
|
+
function normalizeSheetCellBorderStyle(
|
|
415
|
+
value: unknown,
|
|
416
|
+
): SheetCellBorderStyleValue | null {
|
|
417
|
+
return SHEET_CELL_BORDER_STYLE_VALUES.includes(
|
|
418
|
+
value as SheetCellBorderStyleValue,
|
|
419
|
+
)
|
|
420
|
+
? (value as SheetCellBorderStyleValue)
|
|
421
|
+
: null;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/*
|
|
425
|
+
* Return a non-empty style color string or null when the color should be dropped.
|
|
426
|
+
*/
|
|
427
|
+
function normalizeSheetCellStyleColor(value: unknown) {
|
|
428
|
+
return typeof value === 'string' && value.trim() ? value : null;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/*
|
|
432
|
+
* Return a boolean cell style setting only when the value is explicitly boolean.
|
|
433
|
+
*/
|
|
434
|
+
function normalizeSheetCellStyleBoolean(value: unknown) {
|
|
435
|
+
return typeof value === 'boolean' ? value : null;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/*
|
|
439
|
+
* Return a supported text wrap style value or null when it should be dropped.
|
|
440
|
+
*/
|
|
441
|
+
export function normalizeSheetCellTextWrap(
|
|
442
|
+
value: unknown,
|
|
443
|
+
): SheetCellTextWrapEnum | null {
|
|
444
|
+
return SHEET_CELL_TEXT_WRAP_ENUMS.includes(value as SheetCellTextWrapEnum)
|
|
445
|
+
? (value as SheetCellTextWrapEnum)
|
|
446
|
+
: null;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/*
|
|
450
|
+
* Return a supported horizontal text alignment value or null when it should be dropped.
|
|
451
|
+
*/
|
|
452
|
+
export function normalizeSheetCellTextAlign(
|
|
453
|
+
value: unknown,
|
|
454
|
+
): SheetCellTextAlignEnum | null {
|
|
455
|
+
return SHEET_CELL_TEXT_ALIGN_ENUMS.includes(value as SheetCellTextAlignEnum)
|
|
456
|
+
? (value as SheetCellTextAlignEnum)
|
|
457
|
+
: null;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/*
|
|
461
|
+
* Return a supported vertical text alignment value or null when it should be dropped.
|
|
462
|
+
*/
|
|
463
|
+
export function normalizeSheetCellVerticalAlign(
|
|
464
|
+
value: unknown,
|
|
465
|
+
): SheetCellVerticalAlignEnum | null {
|
|
466
|
+
return SHEET_CELL_VERTICAL_ALIGN_ENUMS.includes(
|
|
467
|
+
value as SheetCellVerticalAlignEnum,
|
|
468
|
+
)
|
|
469
|
+
? (value as SheetCellVerticalAlignEnum)
|
|
470
|
+
: null;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/*
|
|
474
|
+
* Add normalized border fields for one side into a Sheet style result object.
|
|
475
|
+
*/
|
|
476
|
+
function addNormalizedSheetCellBorderSideStyle(
|
|
477
|
+
result: SheetCellStyleObj,
|
|
478
|
+
source: Record<string, any>,
|
|
479
|
+
side: (typeof SHEET_CELL_BORDER_SIDES)[number],
|
|
480
|
+
) {
|
|
481
|
+
const widthKey = `border${side}Width` as keyof SheetCellStyleObj;
|
|
482
|
+
const colorKey = `border${side}Color` as keyof SheetCellStyleObj;
|
|
483
|
+
const styleKey = `border${side}Style` as keyof SheetCellStyleObj;
|
|
484
|
+
const width = normalizeSheetCellBorderWidth(source[widthKey]);
|
|
485
|
+
|
|
486
|
+
if (!width) {
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const color = normalizeSheetCellStyleColor(source[colorKey]);
|
|
491
|
+
const style = normalizeSheetCellBorderStyle(source[styleKey]);
|
|
492
|
+
const mutableResult = result as Record<string, any>;
|
|
493
|
+
|
|
494
|
+
mutableResult[widthKey] = width;
|
|
495
|
+
|
|
496
|
+
if (color) {
|
|
497
|
+
mutableResult[colorKey] = color;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
if (style) {
|
|
501
|
+
mutableResult[styleKey] = style;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/*
|
|
506
|
+
* Add normalized full-cell text style booleans into one Sheet style result object.
|
|
507
|
+
*/
|
|
508
|
+
function addNormalizedSheetCellTextStyleBooleans(
|
|
509
|
+
result: SheetCellStyleObj,
|
|
510
|
+
source: Record<string, any>,
|
|
511
|
+
) {
|
|
512
|
+
SHEET_CELL_TEXT_STYLE_BOOLEAN_KEYS.forEach((key) => {
|
|
513
|
+
const value = normalizeSheetCellStyleBoolean(source[key]);
|
|
514
|
+
|
|
515
|
+
if (value !== null) {
|
|
516
|
+
result[key] = value;
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/*
|
|
522
|
+
* Return the only style fields Sheets currently supports for cells and ranges.
|
|
523
|
+
*/
|
|
524
|
+
export function normalizeSheetCellStyle(
|
|
525
|
+
style?: Partial<SheetCellStyleObj> | Record<string, any> | string | null,
|
|
526
|
+
): SheetCellStyleObj {
|
|
527
|
+
const source = getSheetCellStyleObject(style);
|
|
528
|
+
const fontSize = normalizeSheetCellFontSize(source.fontSize);
|
|
529
|
+
const normalized: SheetCellStyleObj = {};
|
|
530
|
+
|
|
531
|
+
if (fontSize) {
|
|
532
|
+
normalized.fontSize = fontSize;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const textColor = normalizeSheetCellStyleColor(source.textColor);
|
|
536
|
+
if (textColor) {
|
|
537
|
+
normalized.textColor = textColor;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
const fillColor = normalizeSheetCellStyleColor(source.fillColor);
|
|
541
|
+
if (fillColor) {
|
|
542
|
+
normalized.fillColor = fillColor;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const textWrap = normalizeSheetCellTextWrap(source.textWrap);
|
|
546
|
+
if (textWrap) {
|
|
547
|
+
normalized.textWrap = textWrap;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const textAlign = normalizeSheetCellTextAlign(source.textAlign);
|
|
551
|
+
if (textAlign) {
|
|
552
|
+
normalized.textAlign = textAlign;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const verticalAlign = normalizeSheetCellVerticalAlign(source.verticalAlign);
|
|
556
|
+
if (verticalAlign) {
|
|
557
|
+
normalized.verticalAlign = verticalAlign;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const disableMarkdown = normalizeSheetCellStyleBoolean(
|
|
561
|
+
source.disableMarkdown,
|
|
562
|
+
);
|
|
563
|
+
if (disableMarkdown !== null) {
|
|
564
|
+
normalized.disableMarkdown = disableMarkdown;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
addNormalizedSheetCellTextStyleBooleans(normalized, source);
|
|
568
|
+
SHEET_CELL_BORDER_SIDES.forEach((side) => {
|
|
569
|
+
addNormalizedSheetCellBorderSideStyle(normalized, source, side);
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
return normalized;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/*
|
|
576
|
+
* Return axis design values with supported cell style and format fields
|
|
577
|
+
* normalized.
|
|
578
|
+
*/
|
|
579
|
+
function normalizeSheetAxisDesignMap(
|
|
580
|
+
map?: Record<string, SheetAxisDesignObj> | null,
|
|
581
|
+
) {
|
|
582
|
+
return Object.fromEntries(
|
|
583
|
+
Object.entries(map || {}).map(([key, value]) => {
|
|
584
|
+
const { format: _format, style: _style, ...axisDesign } = value || {};
|
|
585
|
+
const style = normalizeSheetCellStyle(_style);
|
|
586
|
+
const format = normalizeSheetCellFormat(_format);
|
|
587
|
+
const next: SheetAxisDesignObj = { ...axisDesign };
|
|
588
|
+
|
|
589
|
+
if (Object.keys(style).length) {
|
|
590
|
+
next.style = style;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (Object.keys(format).length) {
|
|
594
|
+
next.format = format;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
return [key, next];
|
|
598
|
+
}),
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/*
|
|
603
|
+
* Return whether one text input should be treated as a sheet formula.
|
|
604
|
+
*/
|
|
605
|
+
export function isSheetFormulaText(value: unknown): value is string {
|
|
606
|
+
return typeof value === 'string' && value.trim().startsWith('=');
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/*
|
|
610
|
+
* Return whether one text input is an ISO-like datetime without an explicit
|
|
611
|
+
* UTC offset. Naive wall-clock times like these are anchored in the
|
|
612
|
+
* organization's timezone at save time, never in the server timezone.
|
|
613
|
+
*/
|
|
614
|
+
export function isNaiveSheetDateTimeText(value: unknown): value is string {
|
|
615
|
+
if (typeof value !== 'string') {
|
|
616
|
+
return false;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const trimmed = value.trim();
|
|
620
|
+
return (
|
|
621
|
+
/^\d{4}-\d{2}-\d{2}T/.test(trimmed) &&
|
|
622
|
+
!/(Z|[+-]\d{2}:?\d{2})$/i.test(trimmed)
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/*
|
|
627
|
+
* Return the expression portion of a formula without the leading equals sign.
|
|
628
|
+
*/
|
|
629
|
+
export function getSheetFormulaExpression(text: string) {
|
|
630
|
+
return text.trim().replace(/^=/, '').trim();
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/*
|
|
634
|
+
* Return a normalized data table function identifier.
|
|
635
|
+
*/
|
|
636
|
+
export function normalizeSheetFormulaDataTableName(value: string) {
|
|
637
|
+
const name = String(value || '')
|
|
638
|
+
.trim()
|
|
639
|
+
.toLowerCase();
|
|
640
|
+
return /^[a-z0-9]+(?:_[a-z0-9]+)*$/.test(name) ? name : '';
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/*
|
|
644
|
+
* Return whether one character is an identifier character in formula text.
|
|
645
|
+
*/
|
|
646
|
+
function isSheetFormulaIdentifierChar(char?: string) {
|
|
647
|
+
return Boolean(char && /[A-Za-z0-9_@]/.test(char));
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/*
|
|
651
|
+
* Return the index after a quoted string literal in formula text.
|
|
652
|
+
*/
|
|
653
|
+
function getSheetFormulaStringEndIndex(value: string, startIndex: number) {
|
|
654
|
+
const quoteChar = value[startIndex];
|
|
655
|
+
if (!isSheetFormulaStringQuoteChar(quoteChar)) {
|
|
656
|
+
return startIndex;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
let escaped = false;
|
|
660
|
+
|
|
661
|
+
for (let index = startIndex + 1; index < value.length; index += 1) {
|
|
662
|
+
const char = value[index];
|
|
663
|
+
|
|
664
|
+
if (escaped) {
|
|
665
|
+
escaped = false;
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
if (char === '\\') {
|
|
670
|
+
escaped = true;
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
if (char === quoteChar) {
|
|
675
|
+
return index + 1;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
return value.length;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/*
|
|
683
|
+
* Return the index after a function call in formula text, respecting nested calls and strings.
|
|
684
|
+
*/
|
|
685
|
+
function getSheetFormulaCallEndIndex(value: string, openParenIndex: number) {
|
|
686
|
+
let depth = 0;
|
|
687
|
+
let index = openParenIndex;
|
|
688
|
+
|
|
689
|
+
while (index < value.length) {
|
|
690
|
+
const char = value[index];
|
|
691
|
+
|
|
692
|
+
if (isSheetFormulaStringQuoteChar(char)) {
|
|
693
|
+
index = getSheetFormulaStringEndIndex(value, index);
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
if (char === '(') {
|
|
698
|
+
depth += 1;
|
|
699
|
+
} else if (char === ')') {
|
|
700
|
+
depth -= 1;
|
|
701
|
+
|
|
702
|
+
if (depth === 0) {
|
|
703
|
+
return index + 1;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
if (depth < 0) {
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
index += 1;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/*
|
|
718
|
+
* Split a formula string on one top-level separator while respecting strings and calls.
|
|
719
|
+
*/
|
|
720
|
+
export function splitSheetFormulaTopLevel(value: string, separator: string) {
|
|
721
|
+
return splitSheetFormulaTopLevelSpans(value, separator).map((part) =>
|
|
722
|
+
part.text.trim(),
|
|
723
|
+
);
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/*
|
|
727
|
+
* Split a formula string into top-level spans while preserving local indexes
|
|
728
|
+
* and whitespace.
|
|
729
|
+
*/
|
|
730
|
+
export function splitSheetFormulaTopLevelSpans(
|
|
731
|
+
value: string,
|
|
732
|
+
separator: string,
|
|
733
|
+
) {
|
|
734
|
+
const parts: Array<{ endIndex: number; startIndex: number; text: string }> =
|
|
735
|
+
[];
|
|
736
|
+
let depth = 0;
|
|
737
|
+
let escaped = false;
|
|
738
|
+
let partStartIndex = 0;
|
|
739
|
+
let quoteChar: string | null = null;
|
|
740
|
+
|
|
741
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
742
|
+
const char = value[index];
|
|
743
|
+
|
|
744
|
+
if (escaped) {
|
|
745
|
+
escaped = false;
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
if (char === '\\' && quoteChar) {
|
|
750
|
+
escaped = true;
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (quoteChar ? char === quoteChar : isSheetFormulaStringQuoteChar(char)) {
|
|
755
|
+
quoteChar = quoteChar ? null : char;
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
if (!quoteChar && char === '(') {
|
|
760
|
+
depth += 1;
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
if (!quoteChar && char === ')') {
|
|
765
|
+
depth = Math.max(0, depth - 1);
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
if (!quoteChar && depth === 0 && value.startsWith(separator, index)) {
|
|
770
|
+
parts.push({
|
|
771
|
+
endIndex: index,
|
|
772
|
+
startIndex: partStartIndex,
|
|
773
|
+
text: value.slice(partStartIndex, index),
|
|
774
|
+
});
|
|
775
|
+
index += separator.length - 1;
|
|
776
|
+
partStartIndex = index + 1;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
parts.push({
|
|
781
|
+
endIndex: value.length,
|
|
782
|
+
startIndex: partStartIndex,
|
|
783
|
+
text: value.slice(partStartIndex),
|
|
784
|
+
});
|
|
785
|
+
return parts;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/*
|
|
789
|
+
* Return a function-like identifier token that starts at one formula index.
|
|
790
|
+
*/
|
|
791
|
+
function getSheetFormulaFunctionNameTokenAtIndex(value: string, index: number) {
|
|
792
|
+
if (isSheetFormulaIdentifierChar(value[index - 1])) {
|
|
793
|
+
return null;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const match = value.slice(index).match(/^@?[A-Za-z_][A-Za-z0-9_]*/);
|
|
797
|
+
if (!match) {
|
|
798
|
+
return null;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
return {
|
|
802
|
+
endIndex: index + match[0].length,
|
|
803
|
+
name: match[0],
|
|
804
|
+
startIndex: index,
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/*
|
|
809
|
+
* Return the next non-whitespace index at or after the provided formula index.
|
|
810
|
+
*/
|
|
811
|
+
function getSheetFormulaNextNonWhitespaceIndex(value: string, index: number) {
|
|
812
|
+
let nextIndex = index;
|
|
813
|
+
|
|
814
|
+
while (nextIndex < value.length && /\s/.test(value[nextIndex])) {
|
|
815
|
+
nextIndex += 1;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
return nextIndex;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/*
|
|
822
|
+
* Return argument tokens for one function call argument span.
|
|
823
|
+
*/
|
|
824
|
+
function getSheetFormulaFunctionCallArgTokens(
|
|
825
|
+
value: string,
|
|
826
|
+
startIndex: number,
|
|
827
|
+
endIndex: number,
|
|
828
|
+
) {
|
|
829
|
+
const argsText = value.slice(startIndex, endIndex);
|
|
830
|
+
|
|
831
|
+
return splitSheetFormulaTopLevelSpans(argsText, ',').map(
|
|
832
|
+
(part, argIndex) => ({
|
|
833
|
+
argIndex,
|
|
834
|
+
endIndex: startIndex + part.endIndex,
|
|
835
|
+
startIndex: startIndex + part.startIndex,
|
|
836
|
+
text: part.text,
|
|
837
|
+
}),
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/*
|
|
842
|
+
* Return one function call token at the provided formula index.
|
|
843
|
+
*/
|
|
844
|
+
function getSheetFormulaFunctionCallTokenAtIndex(
|
|
845
|
+
value: string,
|
|
846
|
+
index: number,
|
|
847
|
+
): SheetFormulaFunctionCallToken | null {
|
|
848
|
+
const nameToken = getSheetFormulaFunctionNameTokenAtIndex(value, index);
|
|
849
|
+
if (!nameToken) {
|
|
850
|
+
return null;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
const openParenIndex = getSheetFormulaNextNonWhitespaceIndex(
|
|
854
|
+
value,
|
|
855
|
+
nameToken.endIndex,
|
|
856
|
+
);
|
|
857
|
+
if (value[openParenIndex] !== '(') {
|
|
858
|
+
return {
|
|
859
|
+
args: [],
|
|
860
|
+
callEndIndex: nameToken.endIndex,
|
|
861
|
+
callStartIndex: nameToken.startIndex,
|
|
862
|
+
endIndex: nameToken.endIndex,
|
|
863
|
+
hasOpenParen: false,
|
|
864
|
+
isComplete: false,
|
|
865
|
+
name: nameToken.name,
|
|
866
|
+
nameEndIndex: nameToken.endIndex,
|
|
867
|
+
nameStartIndex: nameToken.startIndex,
|
|
868
|
+
openParenIndex: null,
|
|
869
|
+
startIndex: nameToken.startIndex,
|
|
870
|
+
text: value.slice(nameToken.startIndex, nameToken.endIndex),
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
const completeEndIndex = getSheetFormulaCallEndIndex(value, openParenIndex);
|
|
875
|
+
const callEndIndex = completeEndIndex || value.length;
|
|
876
|
+
const argsEndIndex = completeEndIndex ? completeEndIndex - 1 : callEndIndex;
|
|
877
|
+
|
|
878
|
+
return {
|
|
879
|
+
args: getSheetFormulaFunctionCallArgTokens(
|
|
880
|
+
value,
|
|
881
|
+
openParenIndex + 1,
|
|
882
|
+
argsEndIndex,
|
|
883
|
+
),
|
|
884
|
+
callEndIndex,
|
|
885
|
+
callStartIndex: nameToken.startIndex,
|
|
886
|
+
endIndex: nameToken.endIndex,
|
|
887
|
+
hasOpenParen: true,
|
|
888
|
+
isComplete: Boolean(completeEndIndex),
|
|
889
|
+
name: nameToken.name,
|
|
890
|
+
nameEndIndex: nameToken.endIndex,
|
|
891
|
+
nameStartIndex: nameToken.startIndex,
|
|
892
|
+
openParenIndex,
|
|
893
|
+
startIndex: nameToken.startIndex,
|
|
894
|
+
text: value.slice(nameToken.startIndex, callEndIndex),
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/*
|
|
899
|
+
* Return function-call-like tokens from formula text for live client helpers.
|
|
900
|
+
*/
|
|
901
|
+
export function tokenizeSheetFormulaFunctionCalls(
|
|
902
|
+
value: string,
|
|
903
|
+
): SheetFormulaFunctionCallToken[] {
|
|
904
|
+
if (!isSheetFormulaText(value)) {
|
|
905
|
+
return [];
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const tokens: SheetFormulaFunctionCallToken[] = [];
|
|
909
|
+
let index = 0;
|
|
910
|
+
|
|
911
|
+
while (index < value.length) {
|
|
912
|
+
const char = value[index];
|
|
913
|
+
|
|
914
|
+
if (isSheetFormulaStringQuoteChar(char)) {
|
|
915
|
+
index = getSheetFormulaStringEndIndex(value, index);
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
const token = getSheetFormulaFunctionCallTokenAtIndex(value, index);
|
|
920
|
+
if (token) {
|
|
921
|
+
tokens.push(token);
|
|
922
|
+
index = token.nameEndIndex;
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
index += 1;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
return tokens;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/*
|
|
933
|
+
* Return whether a keyword starts at one index with non-identifier boundaries.
|
|
934
|
+
*/
|
|
935
|
+
function isSheetFormulaTopLevelKeywordAtIndex(
|
|
936
|
+
value: string,
|
|
937
|
+
index: number,
|
|
938
|
+
keyword: string,
|
|
939
|
+
) {
|
|
940
|
+
const previousChar = value[index - 1];
|
|
941
|
+
const nextChar = value[index + keyword.length];
|
|
942
|
+
|
|
943
|
+
return (
|
|
944
|
+
value.slice(index, index + keyword.length).toLowerCase() ===
|
|
945
|
+
keyword.toLowerCase() &&
|
|
946
|
+
!isSheetFormulaIdentifierChar(previousChar) &&
|
|
947
|
+
!isSheetFormulaIdentifierChar(nextChar)
|
|
948
|
+
);
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/*
|
|
952
|
+
* Split a formula string on one top-level keyword while respecting strings and calls.
|
|
953
|
+
*/
|
|
954
|
+
function splitSheetFormulaTopLevelKeyword(value: string, keyword: string) {
|
|
955
|
+
const parts: string[] = [];
|
|
956
|
+
let current = '';
|
|
957
|
+
let depth = 0;
|
|
958
|
+
let quoteChar: string | null = null;
|
|
959
|
+
let escaped = false;
|
|
960
|
+
|
|
961
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
962
|
+
const char = value[index];
|
|
963
|
+
|
|
964
|
+
if (escaped) {
|
|
965
|
+
current += char;
|
|
966
|
+
escaped = false;
|
|
967
|
+
continue;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
if (char === '\\' && quoteChar) {
|
|
971
|
+
current += char;
|
|
972
|
+
escaped = true;
|
|
973
|
+
continue;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
if (quoteChar ? char === quoteChar : isSheetFormulaStringQuoteChar(char)) {
|
|
977
|
+
quoteChar = quoteChar ? null : char;
|
|
978
|
+
current += char;
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
if (!quoteChar && char === '(') {
|
|
983
|
+
depth += 1;
|
|
984
|
+
current += char;
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
if (!quoteChar && char === ')') {
|
|
989
|
+
depth = Math.max(0, depth - 1);
|
|
990
|
+
current += char;
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
if (
|
|
995
|
+
!quoteChar &&
|
|
996
|
+
depth === 0 &&
|
|
997
|
+
isSheetFormulaTopLevelKeywordAtIndex(value, index, keyword)
|
|
998
|
+
) {
|
|
999
|
+
parts.push(current.trim());
|
|
1000
|
+
current = '';
|
|
1001
|
+
index += keyword.length - 1;
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
current += char;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
parts.push(current.trim());
|
|
1009
|
+
return parts;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/*
|
|
1013
|
+
* Parse top-level operator terms while respecting strings, calls, and unary signs.
|
|
1014
|
+
*/
|
|
1015
|
+
function parseSheetFormulaOperatorTerms<Operator extends string>(params: {
|
|
1016
|
+
defaultOperator: Operator;
|
|
1017
|
+
operators: readonly Operator[];
|
|
1018
|
+
value: string;
|
|
1019
|
+
}) {
|
|
1020
|
+
const terms: Array<SheetFormulaOperatorTerm<Operator>> = [];
|
|
1021
|
+
const operatorSet = new Set<string>(params.operators);
|
|
1022
|
+
let current = '';
|
|
1023
|
+
let depth = 0;
|
|
1024
|
+
let quoteChar: string | null = null;
|
|
1025
|
+
let escaped = false;
|
|
1026
|
+
let operator = params.defaultOperator;
|
|
1027
|
+
|
|
1028
|
+
for (let index = 0; index < params.value.length; index += 1) {
|
|
1029
|
+
const char = params.value[index];
|
|
1030
|
+
|
|
1031
|
+
if (escaped) {
|
|
1032
|
+
current += char;
|
|
1033
|
+
escaped = false;
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
if (char === '\\' && quoteChar) {
|
|
1038
|
+
current += char;
|
|
1039
|
+
escaped = true;
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
if (quoteChar ? char === quoteChar : isSheetFormulaStringQuoteChar(char)) {
|
|
1044
|
+
quoteChar = quoteChar ? null : char;
|
|
1045
|
+
current += char;
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
if (!quoteChar && char === '(') {
|
|
1050
|
+
depth += 1;
|
|
1051
|
+
current += char;
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
if (!quoteChar && char === ')') {
|
|
1056
|
+
if (depth <= 0) {
|
|
1057
|
+
return null;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
depth -= 1;
|
|
1061
|
+
current += char;
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
if (!quoteChar && depth === 0 && operatorSet.has(char)) {
|
|
1066
|
+
const expression = current.trim();
|
|
1067
|
+
const previousChar = current.trimEnd().slice(-1);
|
|
1068
|
+
|
|
1069
|
+
if (
|
|
1070
|
+
(char === '+' || char === '-') &&
|
|
1071
|
+
(!expression ||
|
|
1072
|
+
previousChar === '*' ||
|
|
1073
|
+
previousChar === '/' ||
|
|
1074
|
+
previousChar === '(')
|
|
1075
|
+
) {
|
|
1076
|
+
current += char;
|
|
1077
|
+
continue;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
if (!expression) {
|
|
1081
|
+
return null;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
terms.push({
|
|
1085
|
+
operator,
|
|
1086
|
+
expression,
|
|
1087
|
+
});
|
|
1088
|
+
current = '';
|
|
1089
|
+
operator = char as Operator;
|
|
1090
|
+
continue;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
current += char;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
if (quoteChar || depth !== 0) {
|
|
1097
|
+
return null;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
const expression = current.trim();
|
|
1101
|
+
if (!expression) {
|
|
1102
|
+
return null;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
terms.push({
|
|
1106
|
+
operator,
|
|
1107
|
+
expression,
|
|
1108
|
+
});
|
|
1109
|
+
|
|
1110
|
+
return terms;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/*
|
|
1114
|
+
* Parse top-level additive operators while preserving signs on numeric literals.
|
|
1115
|
+
*/
|
|
1116
|
+
export function parseSheetFormulaAdditiveTerms(value: string) {
|
|
1117
|
+
return parseSheetFormulaOperatorTerms({
|
|
1118
|
+
defaultOperator: '+' as const,
|
|
1119
|
+
operators: ['+', '-'] as const,
|
|
1120
|
+
value,
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/*
|
|
1125
|
+
* Parse top-level multiplicative operators while preserving signed right-hand literals.
|
|
1126
|
+
*/
|
|
1127
|
+
export function parseSheetFormulaMultiplicativeTerms(value: string) {
|
|
1128
|
+
return parseSheetFormulaOperatorTerms({
|
|
1129
|
+
defaultOperator: '*' as const,
|
|
1130
|
+
operators: ['*', '/'] as const,
|
|
1131
|
+
value,
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/*
|
|
1136
|
+
* Return a decoded escape sequence for a flexible formula string literal.
|
|
1137
|
+
*/
|
|
1138
|
+
function getSheetFormulaStringEscapeValue(char: string) {
|
|
1139
|
+
switch (char) {
|
|
1140
|
+
case 'n':
|
|
1141
|
+
return '\n';
|
|
1142
|
+
case 'r':
|
|
1143
|
+
return '\r';
|
|
1144
|
+
case 't':
|
|
1145
|
+
return '\t';
|
|
1146
|
+
default:
|
|
1147
|
+
return char;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/*
|
|
1152
|
+
* Parse a formula string literal quoted with double quotes, single quotes, or backticks.
|
|
1153
|
+
*/
|
|
1154
|
+
export function parseSheetFormulaStringLiteral(value: string) {
|
|
1155
|
+
const trimmed = value.trim();
|
|
1156
|
+
const quoteChar = trimmed[0];
|
|
1157
|
+
if (
|
|
1158
|
+
!isSheetFormulaStringQuoteChar(quoteChar) ||
|
|
1159
|
+
trimmed[trimmed.length - 1] !== quoteChar
|
|
1160
|
+
) {
|
|
1161
|
+
return null;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
if (quoteChar === '"') {
|
|
1165
|
+
try {
|
|
1166
|
+
const parsed = JSON.parse(trimmed);
|
|
1167
|
+
return typeof parsed === 'string' ? parsed : null;
|
|
1168
|
+
} catch {
|
|
1169
|
+
return null;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
let escaped = false;
|
|
1174
|
+
let result = '';
|
|
1175
|
+
|
|
1176
|
+
for (let index = 1; index < trimmed.length - 1; index += 1) {
|
|
1177
|
+
const char = trimmed[index];
|
|
1178
|
+
|
|
1179
|
+
if (escaped) {
|
|
1180
|
+
result += getSheetFormulaStringEscapeValue(char);
|
|
1181
|
+
escaped = false;
|
|
1182
|
+
continue;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
if (char === '\\') {
|
|
1186
|
+
escaped = true;
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
if (char === quoteChar) {
|
|
1191
|
+
return null;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
result += char;
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
return escaped ? null : result;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
/*
|
|
1201
|
+
* Parse a formula number literal.
|
|
1202
|
+
*/
|
|
1203
|
+
export function parseSheetFormulaNumberLiteral(value: string) {
|
|
1204
|
+
const trimmed = value.trim();
|
|
1205
|
+
return /^[-+]?\d+(?:\.\d+)?$/.test(trimmed) ? Number(trimmed) : null;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
/*
|
|
1209
|
+
* Return the current parser offset after any whitespace.
|
|
1210
|
+
*/
|
|
1211
|
+
function skipSheetFormulaParserWhitespace(state: SheetFormulaParserState) {
|
|
1212
|
+
while (/\s/.test(state.value[state.index] || '')) {
|
|
1213
|
+
state.index += 1;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/*
|
|
1218
|
+
* Return source text covered by one parser span.
|
|
1219
|
+
*/
|
|
1220
|
+
function getSheetFormulaParserSpanText(
|
|
1221
|
+
state: SheetFormulaParserState,
|
|
1222
|
+
startIndex: number,
|
|
1223
|
+
) {
|
|
1224
|
+
return state.value.slice(startIndex, state.index).trim();
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/*
|
|
1228
|
+
* Return whether the parser has consumed the full formula expression.
|
|
1229
|
+
*/
|
|
1230
|
+
function isSheetFormulaParserAtEnd(state: SheetFormulaParserState) {
|
|
1231
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1232
|
+
return state.index >= state.value.length;
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/*
|
|
1236
|
+
* Return a parsed function or identifier name at the current parser position.
|
|
1237
|
+
*/
|
|
1238
|
+
function parseSheetFormulaIdentifierName(state: SheetFormulaParserState) {
|
|
1239
|
+
const match = state.value
|
|
1240
|
+
.slice(state.index)
|
|
1241
|
+
.match(/^@?[A-Za-z_][A-Za-z0-9_]*/);
|
|
1242
|
+
if (!match) {
|
|
1243
|
+
return null;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
state.index += match[0].length;
|
|
1247
|
+
return match[0];
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/*
|
|
1251
|
+
* Return a normalized sheet-tab name parsed from a formula prefix.
|
|
1252
|
+
*/
|
|
1253
|
+
function normalizeSheetFormulaReferenceSheetName(value: string) {
|
|
1254
|
+
const sheetName = value.trim();
|
|
1255
|
+
|
|
1256
|
+
return sheetName ? sheetName : null;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/*
|
|
1260
|
+
* Return the case-insensitive lookup key for a formula sheet-tab name.
|
|
1261
|
+
*/
|
|
1262
|
+
export function getSheetFormulaSheetTabNameLookupKey(value?: string | null) {
|
|
1263
|
+
return String(value || '')
|
|
1264
|
+
.trim()
|
|
1265
|
+
.toLowerCase();
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/*
|
|
1269
|
+
* Return a quoted sheet-tab prefix at the current parser position.
|
|
1270
|
+
*/
|
|
1271
|
+
function parseSheetFormulaQuotedSheetNamePrefix(
|
|
1272
|
+
state: SheetFormulaParserState,
|
|
1273
|
+
) {
|
|
1274
|
+
if (state.value[state.index] !== "'") {
|
|
1275
|
+
return null;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
let sheetName = '';
|
|
1279
|
+
let index = state.index + 1;
|
|
1280
|
+
while (index < state.value.length) {
|
|
1281
|
+
const char = state.value[index];
|
|
1282
|
+
|
|
1283
|
+
if (char === "'" && state.value[index + 1] === "'") {
|
|
1284
|
+
sheetName += "'";
|
|
1285
|
+
index += 2;
|
|
1286
|
+
continue;
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
if (char === "'") {
|
|
1290
|
+
const normalizedName = normalizeSheetFormulaReferenceSheetName(sheetName);
|
|
1291
|
+
if (!normalizedName || state.value[index + 1] !== '!') {
|
|
1292
|
+
return null;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
state.index = index + 2;
|
|
1296
|
+
return normalizedName;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
sheetName += char;
|
|
1300
|
+
index += 1;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
return null;
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
/*
|
|
1307
|
+
* Return an unquoted sheet-tab prefix at the current parser position.
|
|
1308
|
+
*/
|
|
1309
|
+
function parseSheetFormulaUnquotedSheetNamePrefix(
|
|
1310
|
+
state: SheetFormulaParserState,
|
|
1311
|
+
) {
|
|
1312
|
+
const remaining = state.value.slice(state.index);
|
|
1313
|
+
const match = remaining.match(/^([A-Za-z_][A-Za-z0-9_ .-]*)!/);
|
|
1314
|
+
if (!match) {
|
|
1315
|
+
return null;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
const sheetName = normalizeSheetFormulaReferenceSheetName(match[1]);
|
|
1319
|
+
if (!sheetName) {
|
|
1320
|
+
return null;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
state.index += match[0].length;
|
|
1324
|
+
return sheetName;
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/*
|
|
1328
|
+
* Return an optional sheet-tab prefix before a cell or range reference.
|
|
1329
|
+
*/
|
|
1330
|
+
function parseSheetFormulaSheetNamePrefix(state: SheetFormulaParserState) {
|
|
1331
|
+
const startIndex = state.index;
|
|
1332
|
+
const sheetName =
|
|
1333
|
+
parseSheetFormulaQuotedSheetNamePrefix(state) ||
|
|
1334
|
+
parseSheetFormulaUnquotedSheetNamePrefix(state);
|
|
1335
|
+
if (
|
|
1336
|
+
!sheetName ||
|
|
1337
|
+
getSheetFormulaCellReferenceEndIndex(state.value, state.index) === null
|
|
1338
|
+
) {
|
|
1339
|
+
state.index = startIndex;
|
|
1340
|
+
return null;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
return sheetName;
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
/*
|
|
1347
|
+
* Return the end index of a cell reference that starts immediately after a
|
|
1348
|
+
* sheet-tab prefix, or null when the prefix is not followed by a cell ref.
|
|
1349
|
+
*/
|
|
1350
|
+
function getSheetFormulaCellReferenceEndIndex(
|
|
1351
|
+
value: string,
|
|
1352
|
+
startIndex: number,
|
|
1353
|
+
) {
|
|
1354
|
+
const match = value.slice(startIndex).match(/^(\$?[A-Za-z]+\$?[1-9]\d*)/);
|
|
1355
|
+
if (!match) {
|
|
1356
|
+
return null;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
const endIndex = startIndex + match[1].length;
|
|
1360
|
+
return isSheetFormulaIdentifierChar(value[endIndex]) ? null : endIndex;
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
/*
|
|
1364
|
+
* Return a quoted sheet-tab prefix token at one formula text index when that
|
|
1365
|
+
* prefix is followed by a valid cell reference.
|
|
1366
|
+
*/
|
|
1367
|
+
function getQuotedSheetFormulaSheetTabNamePrefixTokenAtIndex(
|
|
1368
|
+
value: string,
|
|
1369
|
+
startIndex: number,
|
|
1370
|
+
): SheetFormulaSheetTabNamePrefixToken | null {
|
|
1371
|
+
if (value[startIndex] !== "'") {
|
|
1372
|
+
return null;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
let sheetName = '';
|
|
1376
|
+
for (let index = startIndex + 1; index < value.length; index += 1) {
|
|
1377
|
+
const char = value[index];
|
|
1378
|
+
|
|
1379
|
+
if (char === "'" && value[index + 1] === "'") {
|
|
1380
|
+
sheetName += "'";
|
|
1381
|
+
index += 1;
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
if (char === "'") {
|
|
1386
|
+
const endIndex = index + 2;
|
|
1387
|
+
const normalizedName = normalizeSheetFormulaReferenceSheetName(sheetName);
|
|
1388
|
+
if (
|
|
1389
|
+
!normalizedName ||
|
|
1390
|
+
value[index + 1] !== '!' ||
|
|
1391
|
+
!getSheetFormulaCellReferenceEndIndex(value, endIndex)
|
|
1392
|
+
) {
|
|
1393
|
+
return null;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
return {
|
|
1397
|
+
endIndex,
|
|
1398
|
+
sheetName: normalizedName,
|
|
1399
|
+
startIndex,
|
|
1400
|
+
text: value.slice(startIndex, endIndex),
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
sheetName += char;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
return null;
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
/*
|
|
1411
|
+
* Return an unquoted sheet-tab prefix token at one formula text index when
|
|
1412
|
+
* that prefix is followed by a valid cell reference.
|
|
1413
|
+
*/
|
|
1414
|
+
function getUnquotedSheetFormulaSheetTabNamePrefixTokenAtIndex(
|
|
1415
|
+
value: string,
|
|
1416
|
+
startIndex: number,
|
|
1417
|
+
): SheetFormulaSheetTabNamePrefixToken | null {
|
|
1418
|
+
const match = value.slice(startIndex).match(/^([A-Za-z_][A-Za-z0-9_ .-]*)!/);
|
|
1419
|
+
if (!match) {
|
|
1420
|
+
return null;
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
const endIndex = startIndex + match[0].length;
|
|
1424
|
+
const sheetName = normalizeSheetFormulaReferenceSheetName(match[1]);
|
|
1425
|
+
if (!sheetName || !getSheetFormulaCellReferenceEndIndex(value, endIndex)) {
|
|
1426
|
+
return null;
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
return {
|
|
1430
|
+
endIndex,
|
|
1431
|
+
sheetName,
|
|
1432
|
+
startIndex,
|
|
1433
|
+
text: match[0],
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
/*
|
|
1438
|
+
* Return a sheet-tab prefix token at one formula text index, if the text
|
|
1439
|
+
* starts a cross-tab cell or range reference.
|
|
1440
|
+
*/
|
|
1441
|
+
function getSheetFormulaSheetTabNamePrefixTokenAtIndex(
|
|
1442
|
+
value: string,
|
|
1443
|
+
startIndex: number,
|
|
1444
|
+
): SheetFormulaSheetTabNamePrefixToken | null {
|
|
1445
|
+
return (
|
|
1446
|
+
getQuotedSheetFormulaSheetTabNamePrefixTokenAtIndex(value, startIndex) ||
|
|
1447
|
+
getUnquotedSheetFormulaSheetTabNamePrefixTokenAtIndex(value, startIndex)
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
/*
|
|
1452
|
+
* Rewrite cross-tab formula prefixes that reference one stored sheet-tab name.
|
|
1453
|
+
* Title-like references are not normalized into names; they only change when
|
|
1454
|
+
* their parsed sheet name already matches fromSheetTabName.
|
|
1455
|
+
*/
|
|
1456
|
+
export function rewriteSheetFormulaSheetTabNameReferences(
|
|
1457
|
+
value: string,
|
|
1458
|
+
fromSheetTabName?: string | null,
|
|
1459
|
+
toSheetTabName?: string | null,
|
|
1460
|
+
): SheetFormulaSheetTabNameRewriteResult {
|
|
1461
|
+
const fromKey = getSheetFormulaSheetTabNameLookupKey(fromSheetTabName);
|
|
1462
|
+
const toName = normalizeSheetFormulaDataTableName(toSheetTabName || '');
|
|
1463
|
+
if (
|
|
1464
|
+
!isSheetFormulaText(value) ||
|
|
1465
|
+
!fromKey ||
|
|
1466
|
+
!toName ||
|
|
1467
|
+
fromKey === getSheetFormulaSheetTabNameLookupKey(toName)
|
|
1468
|
+
) {
|
|
1469
|
+
return {
|
|
1470
|
+
changed: false,
|
|
1471
|
+
text: value,
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
let changed = false;
|
|
1476
|
+
let cursor = 0;
|
|
1477
|
+
let index = 0;
|
|
1478
|
+
let text = '';
|
|
1479
|
+
|
|
1480
|
+
while (index < value.length) {
|
|
1481
|
+
const token = getSheetFormulaSheetTabNamePrefixTokenAtIndex(value, index);
|
|
1482
|
+
if (token) {
|
|
1483
|
+
if (getSheetFormulaSheetTabNameLookupKey(token.sheetName) === fromKey) {
|
|
1484
|
+
text += value.slice(cursor, token.startIndex);
|
|
1485
|
+
text += `${toName}!`;
|
|
1486
|
+
cursor = token.endIndex;
|
|
1487
|
+
changed = true;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
index = token.endIndex;
|
|
1491
|
+
continue;
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
if (isSheetFormulaStringQuoteChar(value[index])) {
|
|
1495
|
+
index = getSheetFormulaStringEndIndex(value, index);
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
index += 1;
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
if (!changed) {
|
|
1503
|
+
return {
|
|
1504
|
+
changed: false,
|
|
1505
|
+
text: value,
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
return {
|
|
1510
|
+
changed,
|
|
1511
|
+
text: text + value.slice(cursor),
|
|
1512
|
+
};
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
/*
|
|
1516
|
+
* Return a parsed cell reference at the current parser position.
|
|
1517
|
+
*/
|
|
1518
|
+
function parseSheetFormulaCellReferenceAtState(state: SheetFormulaParserState) {
|
|
1519
|
+
const startIndex = state.index;
|
|
1520
|
+
const sheetName = parseSheetFormulaSheetNamePrefix(state);
|
|
1521
|
+
const coordinateStartIndex = state.index;
|
|
1522
|
+
const match = state.value
|
|
1523
|
+
.slice(state.index)
|
|
1524
|
+
.match(/^(\$?[A-Za-z]+\$?[1-9]\d*)/);
|
|
1525
|
+
if (!match) {
|
|
1526
|
+
state.index = startIndex;
|
|
1527
|
+
return null;
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
const nextChar = state.value[state.index + match[1].length];
|
|
1531
|
+
if (isSheetFormulaIdentifierChar(nextChar)) {
|
|
1532
|
+
state.index = startIndex;
|
|
1533
|
+
return null;
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
const reference = parseSheetFormulaCellReference(match[1]);
|
|
1537
|
+
if (!reference) {
|
|
1538
|
+
state.index = startIndex;
|
|
1539
|
+
return null;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
state.index += match[1].length;
|
|
1543
|
+
return {
|
|
1544
|
+
coordinateEndIndex: state.index,
|
|
1545
|
+
coordinateStartIndex,
|
|
1546
|
+
reference: {
|
|
1547
|
+
...reference,
|
|
1548
|
+
sheetName,
|
|
1549
|
+
},
|
|
1550
|
+
text: state.value.slice(startIndex, state.index),
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/*
|
|
1555
|
+
* Return a range reference with ordered corners.
|
|
1556
|
+
*/
|
|
1557
|
+
function buildSheetFormulaRangeReference(
|
|
1558
|
+
start: SheetFormulaCellReference,
|
|
1559
|
+
end: SheetFormulaCellReference,
|
|
1560
|
+
): SheetFormulaRangeReference | null {
|
|
1561
|
+
if (
|
|
1562
|
+
start.sheetName &&
|
|
1563
|
+
end.sheetName &&
|
|
1564
|
+
start.sheetName.toLowerCase() !== end.sheetName.toLowerCase()
|
|
1565
|
+
) {
|
|
1566
|
+
return null;
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
const startColumnIndex = Math.min(start.columnIndex, end.columnIndex);
|
|
1570
|
+
const endColumnIndex = Math.max(start.columnIndex, end.columnIndex);
|
|
1571
|
+
const startRowIndex = Math.min(start.rowIndex, end.rowIndex);
|
|
1572
|
+
const endRowIndex = Math.max(start.rowIndex, end.rowIndex);
|
|
1573
|
+
|
|
1574
|
+
return {
|
|
1575
|
+
endColumnIndex,
|
|
1576
|
+
endColumnLabel:
|
|
1577
|
+
start.columnIndex <= end.columnIndex
|
|
1578
|
+
? end.columnLabel
|
|
1579
|
+
: start.columnLabel,
|
|
1580
|
+
endRowIndex,
|
|
1581
|
+
sheetName: start.sheetName || end.sheetName || null,
|
|
1582
|
+
startColumnIndex,
|
|
1583
|
+
startColumnLabel:
|
|
1584
|
+
start.columnIndex <= end.columnIndex
|
|
1585
|
+
? start.columnLabel
|
|
1586
|
+
: end.columnLabel,
|
|
1587
|
+
startRowIndex,
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
/*
|
|
1592
|
+
* Return a parsed range reference from a complete formula expression.
|
|
1593
|
+
*/
|
|
1594
|
+
export function parseSheetFormulaRangeReference(
|
|
1595
|
+
value: string,
|
|
1596
|
+
): SheetFormulaRangeReference | null {
|
|
1597
|
+
const state = {
|
|
1598
|
+
index: 0,
|
|
1599
|
+
value: value.trim(),
|
|
1600
|
+
};
|
|
1601
|
+
const start = parseSheetFormulaCellReferenceAtState(state);
|
|
1602
|
+
if (!start) {
|
|
1603
|
+
return null;
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1607
|
+
if (state.value[state.index] !== ':') {
|
|
1608
|
+
return null;
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
state.index += 1;
|
|
1612
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1613
|
+
const end = parseSheetFormulaCellReferenceAtState(state);
|
|
1614
|
+
if (!end || !isSheetFormulaParserAtEnd(state)) {
|
|
1615
|
+
return null;
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
return buildSheetFormulaRangeReference(start.reference, end.reference);
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/*
|
|
1622
|
+
* Return a parsed string literal node at the current parser position.
|
|
1623
|
+
*/
|
|
1624
|
+
function parseSheetFormulaStringNode(
|
|
1625
|
+
state: SheetFormulaParserState,
|
|
1626
|
+
): SheetFormulaASTNode | null {
|
|
1627
|
+
if (!isSheetFormulaStringQuoteChar(state.value[state.index])) {
|
|
1628
|
+
return null;
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
const startIndex = state.index;
|
|
1632
|
+
const endIndex = getSheetFormulaStringEndIndex(state.value, state.index);
|
|
1633
|
+
const text = state.value.slice(startIndex, endIndex);
|
|
1634
|
+
const value = parseSheetFormulaStringLiteral(text);
|
|
1635
|
+
if (value === null) {
|
|
1636
|
+
return null;
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
state.index = endIndex;
|
|
1640
|
+
return {
|
|
1641
|
+
kind: 'STRING_LITERAL',
|
|
1642
|
+
text,
|
|
1643
|
+
value,
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
/*
|
|
1648
|
+
* Return a parsed number literal node at the current parser position.
|
|
1649
|
+
*/
|
|
1650
|
+
function parseSheetFormulaNumberNode(
|
|
1651
|
+
state: SheetFormulaParserState,
|
|
1652
|
+
): SheetFormulaASTNode | null {
|
|
1653
|
+
const match = state.value
|
|
1654
|
+
.slice(state.index)
|
|
1655
|
+
.match(/^(?:\d+(?:\.\d+)?|\.\d+)/);
|
|
1656
|
+
if (!match) {
|
|
1657
|
+
return null;
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
const nextChar = state.value[state.index + match[0].length];
|
|
1661
|
+
if (isSheetFormulaIdentifierChar(nextChar)) {
|
|
1662
|
+
return null;
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
state.index += match[0].length;
|
|
1666
|
+
return {
|
|
1667
|
+
kind: 'NUMBER_LITERAL',
|
|
1668
|
+
text: match[0],
|
|
1669
|
+
value: Number(match[0]),
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
/*
|
|
1674
|
+
* Return a parsed comma-separated function argument list.
|
|
1675
|
+
*/
|
|
1676
|
+
function parseSheetFormulaFunctionArguments(state: SheetFormulaParserState) {
|
|
1677
|
+
const args: SheetFormulaASTNode[] = [];
|
|
1678
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1679
|
+
if (state.value[state.index] === ')') {
|
|
1680
|
+
state.index += 1;
|
|
1681
|
+
return args;
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
while (state.index < state.value.length) {
|
|
1685
|
+
const arg = parseSheetFormulaComparisonExpression(state);
|
|
1686
|
+
if (!arg) {
|
|
1687
|
+
return null;
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
args.push(arg);
|
|
1691
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1692
|
+
const char = state.value[state.index];
|
|
1693
|
+
|
|
1694
|
+
if (char === ')') {
|
|
1695
|
+
state.index += 1;
|
|
1696
|
+
return args;
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
if (char !== ',') {
|
|
1700
|
+
return null;
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
state.index += 1;
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
return null;
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/*
|
|
1710
|
+
* Return a parsed data table lookup function node with a normalized field-key argument.
|
|
1711
|
+
*/
|
|
1712
|
+
function parseSheetFormulaDataTableFunctionCallNode(
|
|
1713
|
+
state: SheetFormulaParserState,
|
|
1714
|
+
name: string,
|
|
1715
|
+
startIndex: number,
|
|
1716
|
+
): Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }> | null {
|
|
1717
|
+
if (!name.startsWith('@')) {
|
|
1718
|
+
return null;
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
const endIndex = getSheetFormulaCallEndIndex(state.value, state.index);
|
|
1722
|
+
if (!endIndex) {
|
|
1723
|
+
return null;
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
const text = state.value.slice(startIndex, endIndex).trim();
|
|
1727
|
+
const dataTableCall = parseSheetFormulaDataTableCall(text);
|
|
1728
|
+
const call = dataTableCall ? parseSheetFormulaCall(text) : null;
|
|
1729
|
+
const rowIdentifierNode = dataTableCall
|
|
1730
|
+
? parseSheetFormulaExpression(dataTableCall.rowIdentifierExpression)
|
|
1731
|
+
: null;
|
|
1732
|
+
if (!dataTableCall || !call || !rowIdentifierNode) {
|
|
1733
|
+
return null;
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
state.index = endIndex;
|
|
1737
|
+
return {
|
|
1738
|
+
args: [
|
|
1739
|
+
rowIdentifierNode,
|
|
1740
|
+
{
|
|
1741
|
+
kind: 'STRING_LITERAL',
|
|
1742
|
+
text: call.args[1].trim(),
|
|
1743
|
+
value: dataTableCall.cellKey,
|
|
1744
|
+
},
|
|
1745
|
+
],
|
|
1746
|
+
kind: 'FUNCTION_CALL',
|
|
1747
|
+
name,
|
|
1748
|
+
text,
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
/*
|
|
1753
|
+
* Return a parsed function call node for one already-read function name.
|
|
1754
|
+
*/
|
|
1755
|
+
function parseSheetFormulaFunctionCallNode(
|
|
1756
|
+
state: SheetFormulaParserState,
|
|
1757
|
+
name: string,
|
|
1758
|
+
startIndex: number,
|
|
1759
|
+
): SheetFormulaASTNode | null {
|
|
1760
|
+
state.index += 1;
|
|
1761
|
+
const args = parseSheetFormulaFunctionArguments(state);
|
|
1762
|
+
if (!args) {
|
|
1763
|
+
return null;
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
return {
|
|
1767
|
+
args,
|
|
1768
|
+
kind: 'FUNCTION_CALL',
|
|
1769
|
+
name,
|
|
1770
|
+
text: state.value.slice(startIndex, state.index).trim(),
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/*
|
|
1775
|
+
* Return a parsed cell or range reference node at the current parser position.
|
|
1776
|
+
*/
|
|
1777
|
+
function parseSheetFormulaReferenceNode(
|
|
1778
|
+
state: SheetFormulaParserState,
|
|
1779
|
+
): SheetFormulaASTNode | null {
|
|
1780
|
+
const startIndex = state.index;
|
|
1781
|
+
const start = parseSheetFormulaCellReferenceAtState(state);
|
|
1782
|
+
if (!start) {
|
|
1783
|
+
return null;
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1786
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1787
|
+
if (state.value[state.index] !== ':') {
|
|
1788
|
+
return {
|
|
1789
|
+
kind: 'CELL_REFERENCE',
|
|
1790
|
+
reference: start.reference,
|
|
1791
|
+
text: start.text,
|
|
1792
|
+
};
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
state.index += 1;
|
|
1796
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1797
|
+
const end = parseSheetFormulaCellReferenceAtState(state);
|
|
1798
|
+
if (!end) {
|
|
1799
|
+
state.index = startIndex;
|
|
1800
|
+
return null;
|
|
1801
|
+
}
|
|
1802
|
+
const reference = buildSheetFormulaRangeReference(
|
|
1803
|
+
start.reference,
|
|
1804
|
+
end.reference,
|
|
1805
|
+
);
|
|
1806
|
+
if (!reference) {
|
|
1807
|
+
state.index = startIndex;
|
|
1808
|
+
return null;
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
return {
|
|
1812
|
+
kind: 'RANGE_REFERENCE',
|
|
1813
|
+
reference,
|
|
1814
|
+
text: state.value.slice(startIndex, state.index).trim(),
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
/*
|
|
1819
|
+
* Return a parsed identifier-backed node such as a boolean, function call, or reference.
|
|
1820
|
+
*/
|
|
1821
|
+
function parseSheetFormulaIdentifierNode(
|
|
1822
|
+
state: SheetFormulaParserState,
|
|
1823
|
+
): SheetFormulaASTNode | null {
|
|
1824
|
+
const startIndex = state.index;
|
|
1825
|
+
const name = parseSheetFormulaIdentifierName(state);
|
|
1826
|
+
if (!name) {
|
|
1827
|
+
return null;
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1831
|
+
if (state.value[state.index] === '(') {
|
|
1832
|
+
return (
|
|
1833
|
+
parseSheetFormulaDataTableFunctionCallNode(state, name, startIndex) ||
|
|
1834
|
+
parseSheetFormulaFunctionCallNode(state, name, startIndex)
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
if (/^(?:true|false)$/i.test(name)) {
|
|
1839
|
+
return {
|
|
1840
|
+
kind: 'BOOLEAN_LITERAL',
|
|
1841
|
+
text: name,
|
|
1842
|
+
value: /^true$/i.test(name),
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
return null;
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1849
|
+
/*
|
|
1850
|
+
* Return a parsed grouped or atomic formula expression.
|
|
1851
|
+
*/
|
|
1852
|
+
function parseSheetFormulaPrimaryExpression(
|
|
1853
|
+
state: SheetFormulaParserState,
|
|
1854
|
+
): SheetFormulaASTNode | null {
|
|
1855
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1856
|
+
const startIndex = state.index;
|
|
1857
|
+
|
|
1858
|
+
if (state.value[state.index] === '(') {
|
|
1859
|
+
state.index += 1;
|
|
1860
|
+
const node = parseSheetFormulaComparisonExpression(state);
|
|
1861
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1862
|
+
if (!node || state.value[state.index] !== ')') {
|
|
1863
|
+
return null;
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
state.index += 1;
|
|
1867
|
+
return {
|
|
1868
|
+
...node,
|
|
1869
|
+
text: state.value.slice(startIndex, state.index).trim(),
|
|
1870
|
+
};
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
return (
|
|
1874
|
+
parseSheetFormulaDataTableQueryNode(state) ||
|
|
1875
|
+
parseSheetFormulaReferenceNode(state) ||
|
|
1876
|
+
parseSheetFormulaStringNode(state) ||
|
|
1877
|
+
parseSheetFormulaNumberNode(state) ||
|
|
1878
|
+
parseSheetFormulaIdentifierNode(state)
|
|
1879
|
+
);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
/*
|
|
1883
|
+
* Return a parsed unary formula expression.
|
|
1884
|
+
*/
|
|
1885
|
+
function parseSheetFormulaUnaryExpression(
|
|
1886
|
+
state: SheetFormulaParserState,
|
|
1887
|
+
): SheetFormulaASTNode | null {
|
|
1888
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1889
|
+
const startIndex = state.index;
|
|
1890
|
+
const operator = state.value[state.index];
|
|
1891
|
+
if (operator === '+' || operator === '-') {
|
|
1892
|
+
state.index += 1;
|
|
1893
|
+
const value = parseSheetFormulaUnaryExpression(state);
|
|
1894
|
+
if (!value) {
|
|
1895
|
+
return null;
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
return {
|
|
1899
|
+
kind: 'UNARY_EXPRESSION',
|
|
1900
|
+
operator,
|
|
1901
|
+
text: state.value.slice(startIndex, state.index).trim(),
|
|
1902
|
+
value,
|
|
1903
|
+
};
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
return parseSheetFormulaPrimaryExpression(state);
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/*
|
|
1910
|
+
* Return a parsed left-associative binary expression for the provided operators.
|
|
1911
|
+
*/
|
|
1912
|
+
function parseSheetFormulaBinaryExpression(
|
|
1913
|
+
state: SheetFormulaParserState,
|
|
1914
|
+
parseOperand: (state: SheetFormulaParserState) => SheetFormulaASTNode | null,
|
|
1915
|
+
operators: readonly SheetFormulaBinaryOperator[],
|
|
1916
|
+
) {
|
|
1917
|
+
let left = parseOperand(state);
|
|
1918
|
+
if (!left) {
|
|
1919
|
+
return null;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
while (state.index < state.value.length) {
|
|
1923
|
+
skipSheetFormulaParserWhitespace(state);
|
|
1924
|
+
const operator = operators.find((candidate) =>
|
|
1925
|
+
state.value.slice(state.index).startsWith(candidate),
|
|
1926
|
+
);
|
|
1927
|
+
if (!operator) {
|
|
1928
|
+
break;
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
const startIndex = state.index;
|
|
1932
|
+
state.index += operator.length;
|
|
1933
|
+
const right = parseOperand(state);
|
|
1934
|
+
if (!right) {
|
|
1935
|
+
state.index = startIndex;
|
|
1936
|
+
return null;
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
left = {
|
|
1940
|
+
kind: 'BINARY_EXPRESSION',
|
|
1941
|
+
left,
|
|
1942
|
+
operator,
|
|
1943
|
+
right,
|
|
1944
|
+
text: `${left.text}${operator}${right.text}`,
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
return left;
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
/*
|
|
1952
|
+
* Return a parsed multiplicative formula expression.
|
|
1953
|
+
*/
|
|
1954
|
+
function parseSheetFormulaMultiplicativeExpressionNode(
|
|
1955
|
+
state: SheetFormulaParserState,
|
|
1956
|
+
) {
|
|
1957
|
+
return parseSheetFormulaBinaryExpression(
|
|
1958
|
+
state,
|
|
1959
|
+
parseSheetFormulaUnaryExpression,
|
|
1960
|
+
['*', '/'] as const,
|
|
1961
|
+
);
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
/*
|
|
1965
|
+
* Return a parsed additive formula expression.
|
|
1966
|
+
*/
|
|
1967
|
+
function parseSheetFormulaAdditiveExpressionNode(
|
|
1968
|
+
state: SheetFormulaParserState,
|
|
1969
|
+
) {
|
|
1970
|
+
return parseSheetFormulaBinaryExpression(
|
|
1971
|
+
state,
|
|
1972
|
+
parseSheetFormulaMultiplicativeExpressionNode,
|
|
1973
|
+
['+', '-'] as const,
|
|
1974
|
+
);
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
/*
|
|
1978
|
+
* Return a parsed comparison formula expression.
|
|
1979
|
+
*/
|
|
1980
|
+
function parseSheetFormulaComparisonExpression(
|
|
1981
|
+
state: SheetFormulaParserState,
|
|
1982
|
+
): SheetFormulaASTNode | null {
|
|
1983
|
+
return parseSheetFormulaBinaryExpression(
|
|
1984
|
+
state,
|
|
1985
|
+
parseSheetFormulaAdditiveExpressionNode,
|
|
1986
|
+
['<=', '>=', '<>', '!=', '=', '<', '>'] as const,
|
|
1987
|
+
);
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
/*
|
|
1991
|
+
* Parse one full formula expression into an AST node.
|
|
1992
|
+
*/
|
|
1993
|
+
export function parseSheetFormulaExpression(
|
|
1994
|
+
value: string,
|
|
1995
|
+
): SheetFormulaASTNode | null {
|
|
1996
|
+
const state = {
|
|
1997
|
+
index: 0,
|
|
1998
|
+
value: value.trim(),
|
|
1999
|
+
};
|
|
2000
|
+
const node = parseSheetFormulaComparisonExpression(state);
|
|
2001
|
+
|
|
2002
|
+
return node && isSheetFormulaParserAtEnd(state)
|
|
2003
|
+
? {
|
|
2004
|
+
...node,
|
|
2005
|
+
text: getSheetFormulaParserSpanText(state, 0),
|
|
2006
|
+
}
|
|
2007
|
+
: null;
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
export interface SheetFormulaStaticCellReference {
|
|
2011
|
+
rowIndex: number;
|
|
2012
|
+
columnIndex: number;
|
|
2013
|
+
sheetName?: string | null;
|
|
2014
|
+
sheetTabId?: number | bigint | string | null;
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
export interface SheetFormulaStaticRangeReference {
|
|
2018
|
+
startRowIndex: number;
|
|
2019
|
+
startColumnIndex: number;
|
|
2020
|
+
endRowIndex: number;
|
|
2021
|
+
endColumnIndex: number;
|
|
2022
|
+
sheetName?: string | null;
|
|
2023
|
+
sheetTabId?: number | bigint | string | null;
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
export interface SheetFormulaStaticDataTableCellReference {
|
|
2027
|
+
dataTableName: string;
|
|
2028
|
+
cellKey: string;
|
|
2029
|
+
rowIdentifier: string | null;
|
|
2030
|
+
text: string;
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
export interface SheetFormulaStaticDataTableQueryCondition {
|
|
2034
|
+
cellKey: string;
|
|
2035
|
+
operator: SheetFormulaDataTableQueryOperator;
|
|
2036
|
+
isStatic: boolean;
|
|
2037
|
+
staticValue: string | number | boolean | null;
|
|
2038
|
+
text: string;
|
|
2039
|
+
}
|
|
2040
|
+
|
|
2041
|
+
export interface SheetFormulaStaticDataTableQueryReference {
|
|
2042
|
+
dataTableName: string;
|
|
2043
|
+
cellKey: string;
|
|
2044
|
+
conditions: SheetFormulaStaticDataTableQueryCondition[];
|
|
2045
|
+
text: string;
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
export interface SheetFormulaStaticReferences {
|
|
2049
|
+
cells: SheetFormulaStaticCellReference[];
|
|
2050
|
+
ranges: SheetFormulaStaticRangeReference[];
|
|
2051
|
+
dataTableCells: SheetFormulaStaticDataTableCellReference[];
|
|
2052
|
+
dataTableQueries: SheetFormulaStaticDataTableQueryReference[];
|
|
2053
|
+
volatile: boolean;
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
/*
|
|
2057
|
+
* Return whether a formula function name refers to a time-dependent builtin.
|
|
2058
|
+
*/
|
|
2059
|
+
function isSheetFormulaVolatileFunctionName(name: string) {
|
|
2060
|
+
const normalizedName = name.replace(/^@/, '').toUpperCase();
|
|
2061
|
+
return normalizedName === 'TODAY' || normalizedName === 'NOW';
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
/*
|
|
2065
|
+
* Return the literal scalar value of an AST node, or null when the value can
|
|
2066
|
+
* only be known at evaluation time (cell references, expressions, shorthands).
|
|
2067
|
+
*/
|
|
2068
|
+
function getSheetFormulaStaticNodeValue(
|
|
2069
|
+
node: SheetFormulaASTNode,
|
|
2070
|
+
): string | number | boolean | null {
|
|
2071
|
+
if (
|
|
2072
|
+
node.kind === 'STRING_LITERAL' ||
|
|
2073
|
+
node.kind === 'NUMBER_LITERAL' ||
|
|
2074
|
+
node.kind === 'BOOLEAN_LITERAL'
|
|
2075
|
+
) {
|
|
2076
|
+
return node.value;
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
return null;
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
/*
|
|
2083
|
+
* Return the data-table lookup call metadata for a function-call AST node, or
|
|
2084
|
+
* null when the node is not an @table(rowIdentifier, "cellKey") lookup.
|
|
2085
|
+
*/
|
|
2086
|
+
export function parseSheetFormulaDataTableCellCallNode(
|
|
2087
|
+
node: Extract<SheetFormulaASTNode, { kind: 'FUNCTION_CALL' }>,
|
|
2088
|
+
) {
|
|
2089
|
+
if (!node.name.startsWith('@')) {
|
|
2090
|
+
return null;
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
const dataTableName = normalizeSheetFormulaDataTableName(node.name.slice(1));
|
|
2094
|
+
const cellKeyNode = node.args[1];
|
|
2095
|
+
if (
|
|
2096
|
+
!dataTableName ||
|
|
2097
|
+
node.args.length !== 2 ||
|
|
2098
|
+
cellKeyNode?.kind !== 'STRING_LITERAL'
|
|
2099
|
+
) {
|
|
2100
|
+
return null;
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
return {
|
|
2104
|
+
cellKey: cellKeyNode.value,
|
|
2105
|
+
dataTableName,
|
|
2106
|
+
rowIdentifierNode: node.args[0],
|
|
2107
|
+
text: node.text,
|
|
2108
|
+
};
|
|
2109
|
+
}
|
|
2110
|
+
|
|
2111
|
+
/*
|
|
2112
|
+
* Walk one formula AST node and accumulate its static references. Used by
|
|
2113
|
+
* collectSheetFormulaStaticReferences below; does no I/O and no evaluation.
|
|
2114
|
+
*/
|
|
2115
|
+
function walkSheetFormulaStaticReferences(
|
|
2116
|
+
node: SheetFormulaASTNode,
|
|
2117
|
+
result: SheetFormulaStaticReferences,
|
|
2118
|
+
) {
|
|
2119
|
+
if (node.kind === 'CELL_REFERENCE') {
|
|
2120
|
+
result.cells.push({
|
|
2121
|
+
rowIndex: node.reference.rowIndex,
|
|
2122
|
+
columnIndex: node.reference.columnIndex,
|
|
2123
|
+
sheetName: node.reference.sheetName || null,
|
|
2124
|
+
});
|
|
2125
|
+
return;
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
if (node.kind === 'RANGE_REFERENCE') {
|
|
2129
|
+
result.ranges.push({
|
|
2130
|
+
startRowIndex: node.reference.startRowIndex,
|
|
2131
|
+
startColumnIndex: node.reference.startColumnIndex,
|
|
2132
|
+
endRowIndex: node.reference.endRowIndex,
|
|
2133
|
+
endColumnIndex: node.reference.endColumnIndex,
|
|
2134
|
+
sheetName: node.reference.sheetName || null,
|
|
2135
|
+
});
|
|
2136
|
+
return;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
if (node.kind === 'DATE_TIME_SHORTHAND') {
|
|
2140
|
+
result.volatile = true;
|
|
2141
|
+
return;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
if (node.kind === 'DATA_TABLE_QUERY') {
|
|
2145
|
+
result.dataTableQueries.push({
|
|
2146
|
+
dataTableName: normalizeSheetFormulaDataTableName(
|
|
2147
|
+
node.query.dataTableName,
|
|
2148
|
+
),
|
|
2149
|
+
cellKey: node.query.cellKey,
|
|
2150
|
+
conditions: node.query.conditions.map((condition) => {
|
|
2151
|
+
const staticValue = getSheetFormulaStaticNodeValue(condition.valueNode);
|
|
2152
|
+
|
|
2153
|
+
return {
|
|
2154
|
+
cellKey: condition.cellKey,
|
|
2155
|
+
operator: condition.operator,
|
|
2156
|
+
isStatic: staticValue !== null,
|
|
2157
|
+
staticValue,
|
|
2158
|
+
text: condition.text,
|
|
2159
|
+
};
|
|
2160
|
+
}),
|
|
2161
|
+
text: node.query.text,
|
|
2162
|
+
});
|
|
2163
|
+
|
|
2164
|
+
// Condition values may reference sheet cells or volatile shorthands
|
|
2165
|
+
node.query.conditions.forEach((condition) => {
|
|
2166
|
+
walkSheetFormulaStaticReferences(condition.valueNode, result);
|
|
2167
|
+
});
|
|
2168
|
+
return;
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
if (node.kind === 'FUNCTION_CALL') {
|
|
2172
|
+
const dataTableCall = parseSheetFormulaDataTableCellCallNode(node);
|
|
2173
|
+
if (dataTableCall) {
|
|
2174
|
+
const staticIdentifier = getSheetFormulaStaticNodeValue(
|
|
2175
|
+
dataTableCall.rowIdentifierNode,
|
|
2176
|
+
);
|
|
2177
|
+
|
|
2178
|
+
result.dataTableCells.push({
|
|
2179
|
+
dataTableName: dataTableCall.dataTableName,
|
|
2180
|
+
cellKey: dataTableCall.cellKey,
|
|
2181
|
+
rowIdentifier:
|
|
2182
|
+
staticIdentifier === null ? null : String(staticIdentifier),
|
|
2183
|
+
text: dataTableCall.text,
|
|
2184
|
+
});
|
|
2185
|
+
|
|
2186
|
+
// The row identifier may itself reference sheet cells
|
|
2187
|
+
walkSheetFormulaStaticReferences(dataTableCall.rowIdentifierNode, result);
|
|
2188
|
+
return;
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
if (isSheetFormulaVolatileFunctionName(node.name)) {
|
|
2192
|
+
result.volatile = true;
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
node.args.forEach((arg) => {
|
|
2196
|
+
walkSheetFormulaStaticReferences(arg, result);
|
|
2197
|
+
});
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
if (node.kind === 'BINARY_EXPRESSION') {
|
|
2202
|
+
walkSheetFormulaStaticReferences(node.left, result);
|
|
2203
|
+
walkSheetFormulaStaticReferences(node.right, result);
|
|
2204
|
+
return;
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
if (node.kind === 'UNARY_EXPRESSION') {
|
|
2208
|
+
walkSheetFormulaStaticReferences(node.value, result);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
/*
|
|
2213
|
+
* Collect every reference a formula AST depends on, without evaluating it:
|
|
2214
|
+
* sheet cells/ranges, data table cell lookups, data table query lookups, and
|
|
2215
|
+
* whether the formula is volatile (time-dependent). Cell and range references
|
|
2216
|
+
* are de-duplicated. Pure function shared by the server dependency graph and
|
|
2217
|
+
* client dependency highlighting.
|
|
2218
|
+
*/
|
|
2219
|
+
export function collectSheetFormulaStaticReferences(
|
|
2220
|
+
node: SheetFormulaASTNode,
|
|
2221
|
+
): SheetFormulaStaticReferences {
|
|
2222
|
+
const result: SheetFormulaStaticReferences = {
|
|
2223
|
+
cells: [],
|
|
2224
|
+
ranges: [],
|
|
2225
|
+
dataTableCells: [],
|
|
2226
|
+
dataTableQueries: [],
|
|
2227
|
+
volatile: false,
|
|
2228
|
+
};
|
|
2229
|
+
|
|
2230
|
+
walkSheetFormulaStaticReferences(node, result);
|
|
2231
|
+
|
|
2232
|
+
const cellKeys = new Set<string>();
|
|
2233
|
+
result.cells = result.cells.filter((cell) => {
|
|
2234
|
+
const key = `${getSheetFormulaSheetTabNameLookupKey(cell.sheetName)}:${cell.rowIndex}:${cell.columnIndex}`;
|
|
2235
|
+
if (cellKeys.has(key)) {
|
|
2236
|
+
return false;
|
|
2237
|
+
}
|
|
2238
|
+
cellKeys.add(key);
|
|
2239
|
+
return true;
|
|
2240
|
+
});
|
|
2241
|
+
|
|
2242
|
+
const rangeKeys = new Set<string>();
|
|
2243
|
+
result.ranges = result.ranges.filter((range) => {
|
|
2244
|
+
const key = `${getSheetFormulaSheetTabNameLookupKey(range.sheetName)}:${range.startRowIndex}:${range.startColumnIndex}:${range.endRowIndex}:${range.endColumnIndex}`;
|
|
2245
|
+
if (rangeKeys.has(key)) {
|
|
2246
|
+
return false;
|
|
2247
|
+
}
|
|
2248
|
+
rangeKeys.add(key);
|
|
2249
|
+
return true;
|
|
2250
|
+
});
|
|
2251
|
+
|
|
2252
|
+
return result;
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
export type SheetFormulaCompileSheetTabLookup = Map<
|
|
2256
|
+
string,
|
|
2257
|
+
{
|
|
2258
|
+
id?: number | bigint | string | null;
|
|
2259
|
+
name?: string | null;
|
|
2260
|
+
}
|
|
2261
|
+
>;
|
|
2262
|
+
|
|
2263
|
+
/*
|
|
2264
|
+
* Return the resolved tab id for one parsed formula sheet-tab name.
|
|
2265
|
+
*/
|
|
2266
|
+
function resolveCompiledSheetFormulaSheetTabId(params: {
|
|
2267
|
+
currentSheetTabId?: number | bigint | string | null;
|
|
2268
|
+
sheetName?: string | null;
|
|
2269
|
+
sheetTabByName?: SheetFormulaCompileSheetTabLookup | null;
|
|
2270
|
+
}) {
|
|
2271
|
+
if (!params.sheetName) {
|
|
2272
|
+
return params.currentSheetTabId || null;
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
return (
|
|
2276
|
+
params.sheetTabByName?.get(
|
|
2277
|
+
getSheetFormulaSheetTabNameLookupKey(params.sheetName),
|
|
2278
|
+
)?.id || null
|
|
2279
|
+
);
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
/*
|
|
2283
|
+
* Return one missing-tab diagnostic for a compiled formula reference.
|
|
2284
|
+
*/
|
|
2285
|
+
function getSheetCompiledFormulaMissingTabDiagnostic(
|
|
2286
|
+
sheetName?: string | null,
|
|
2287
|
+
) {
|
|
2288
|
+
return {
|
|
2289
|
+
code: 'NOT_FOUND',
|
|
2290
|
+
message: 'Formula sheet tab reference could not be found.',
|
|
2291
|
+
sheetName: sheetName || null,
|
|
2292
|
+
};
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
/*
|
|
2296
|
+
* Add one diagnostic when it has not already been recorded.
|
|
2297
|
+
*/
|
|
2298
|
+
function addUniqueSheetCompiledFormulaDiagnostic(
|
|
2299
|
+
diagnostics: SheetCompiledFormulaObj['diagnostics'],
|
|
2300
|
+
diagnostic: SheetCompiledFormulaObj['diagnostics'][number],
|
|
2301
|
+
) {
|
|
2302
|
+
const key = `${diagnostic.code}:${diagnostic.sheetName || ''}:${diagnostic.message}`;
|
|
2303
|
+
if (
|
|
2304
|
+
!diagnostics.some(
|
|
2305
|
+
(item) => `${item.code}:${item.sheetName || ''}:${item.message}` === key,
|
|
2306
|
+
)
|
|
2307
|
+
) {
|
|
2308
|
+
diagnostics.push(diagnostic);
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
/*
|
|
2313
|
+
* Compile formula references into canonical sheet-tab ids and diagnostics.
|
|
2314
|
+
*/
|
|
2315
|
+
export function compileSheetFormulaReferences(params: {
|
|
2316
|
+
currentSheetTabId?: number | bigint | string | null;
|
|
2317
|
+
sheetTabByName?: SheetFormulaCompileSheetTabLookup | null;
|
|
2318
|
+
text: string;
|
|
2319
|
+
version?: number | null;
|
|
2320
|
+
}): SheetCompiledFormulaObj {
|
|
2321
|
+
const expression = getSheetFormulaExpression(params.text);
|
|
2322
|
+
const node = parseSheetFormulaExpression(expression);
|
|
2323
|
+
const diagnostics: SheetCompiledFormulaObj['diagnostics'] = [];
|
|
2324
|
+
|
|
2325
|
+
if (!node) {
|
|
2326
|
+
diagnostics.push({
|
|
2327
|
+
code: 'INVALID_FORMULA',
|
|
2328
|
+
message: getSheetFormulaSyntaxErrorMessage(expression),
|
|
2329
|
+
sheetName: null,
|
|
2330
|
+
});
|
|
2331
|
+
|
|
2332
|
+
return {
|
|
2333
|
+
version: params.version || 1,
|
|
2334
|
+
text: params.text,
|
|
2335
|
+
volatile: false,
|
|
2336
|
+
cells: [],
|
|
2337
|
+
ranges: [],
|
|
2338
|
+
dataTableCells: [],
|
|
2339
|
+
dataTableQueries: [],
|
|
2340
|
+
diagnostics,
|
|
2341
|
+
// Parse failure: no tree to store; evaluation re-parses and
|
|
2342
|
+
// re-reports the syntax error
|
|
2343
|
+
ast: null,
|
|
2344
|
+
};
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
const references = collectSheetFormulaStaticReferences(node);
|
|
2348
|
+
const cells = references.cells.map((reference) => {
|
|
2349
|
+
const sheetTabId = resolveCompiledSheetFormulaSheetTabId({
|
|
2350
|
+
currentSheetTabId: params.currentSheetTabId,
|
|
2351
|
+
sheetName: reference.sheetName,
|
|
2352
|
+
sheetTabByName: params.sheetTabByName,
|
|
2353
|
+
});
|
|
2354
|
+
if (!sheetTabId) {
|
|
2355
|
+
addUniqueSheetCompiledFormulaDiagnostic(
|
|
2356
|
+
diagnostics,
|
|
2357
|
+
getSheetCompiledFormulaMissingTabDiagnostic(reference.sheetName),
|
|
2358
|
+
);
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
return {
|
|
2362
|
+
...reference,
|
|
2363
|
+
sheetTabId,
|
|
2364
|
+
status: sheetTabId ? ('READY' as const) : ('NOT_FOUND' as const),
|
|
2365
|
+
};
|
|
2366
|
+
});
|
|
2367
|
+
const ranges = references.ranges.map((reference) => {
|
|
2368
|
+
const sheetTabId = resolveCompiledSheetFormulaSheetTabId({
|
|
2369
|
+
currentSheetTabId: params.currentSheetTabId,
|
|
2370
|
+
sheetName: reference.sheetName,
|
|
2371
|
+
sheetTabByName: params.sheetTabByName,
|
|
2372
|
+
});
|
|
2373
|
+
if (!sheetTabId) {
|
|
2374
|
+
addUniqueSheetCompiledFormulaDiagnostic(
|
|
2375
|
+
diagnostics,
|
|
2376
|
+
getSheetCompiledFormulaMissingTabDiagnostic(reference.sheetName),
|
|
2377
|
+
);
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
return {
|
|
2381
|
+
...reference,
|
|
2382
|
+
sheetTabId,
|
|
2383
|
+
status: sheetTabId ? ('READY' as const) : ('NOT_FOUND' as const),
|
|
2384
|
+
};
|
|
2385
|
+
});
|
|
2386
|
+
|
|
2387
|
+
return {
|
|
2388
|
+
version: params.version || 1,
|
|
2389
|
+
text: params.text,
|
|
2390
|
+
volatile: references.volatile,
|
|
2391
|
+
cells,
|
|
2392
|
+
ranges,
|
|
2393
|
+
dataTableCells: references.dataTableCells,
|
|
2394
|
+
dataTableQueries: references.dataTableQueries,
|
|
2395
|
+
diagnostics,
|
|
2396
|
+
// Stored parse tree: plain-JSON node values only, so the jsonb
|
|
2397
|
+
// round-trip is lossless and evaluation can skip re-parsing
|
|
2398
|
+
ast: node,
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
/*
|
|
2403
|
+
* Return the stored AST of a compiled formula when it is trustworthy for
|
|
2404
|
+
* evaluation: version >= 3, ast present, and text identical to the text
|
|
2405
|
+
* being evaluated. Missing or stale compile caches return null so the caller
|
|
2406
|
+
* reparses the canonical formula text.
|
|
2407
|
+
*/
|
|
2408
|
+
export function getSheetCompiledFormulaASTNode(
|
|
2409
|
+
compiledFormula: SheetCompiledFormulaObj | null | undefined,
|
|
2410
|
+
formulaText: string,
|
|
2411
|
+
): SheetFormulaASTNode | null {
|
|
2412
|
+
if (!compiledFormula?.ast || (compiledFormula.version || 0) < 3) {
|
|
2413
|
+
return null;
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
return compiledFormula.text === formulaText ? compiledFormula.ast : null;
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
/*
|
|
2420
|
+
* Return static dependency references from one compiled formula payload.
|
|
2421
|
+
*/
|
|
2422
|
+
export function getSheetCompiledFormulaStaticReferences(
|
|
2423
|
+
compiledFormula?: SheetCompiledFormulaObj | null,
|
|
2424
|
+
): SheetFormulaStaticReferences | null {
|
|
2425
|
+
if (!compiledFormula?.ast || (compiledFormula.version || 0) < 3) {
|
|
2426
|
+
return null;
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
return {
|
|
2430
|
+
cells: (compiledFormula.cells || []).map((reference) => ({
|
|
2431
|
+
rowIndex: reference.rowIndex,
|
|
2432
|
+
columnIndex: reference.columnIndex,
|
|
2433
|
+
sheetName: reference.sheetName || null,
|
|
2434
|
+
sheetTabId: reference.sheetTabId || null,
|
|
2435
|
+
})),
|
|
2436
|
+
ranges: (compiledFormula.ranges || []).map((reference) => ({
|
|
2437
|
+
startRowIndex: reference.startRowIndex,
|
|
2438
|
+
startColumnIndex: reference.startColumnIndex,
|
|
2439
|
+
endRowIndex: reference.endRowIndex,
|
|
2440
|
+
endColumnIndex: reference.endColumnIndex,
|
|
2441
|
+
sheetName: reference.sheetName || null,
|
|
2442
|
+
sheetTabId: reference.sheetTabId || null,
|
|
2443
|
+
})),
|
|
2444
|
+
dataTableCells: compiledFormula.dataTableCells || [],
|
|
2445
|
+
dataTableQueries: (compiledFormula.dataTableQueries ||
|
|
2446
|
+
[]) as SheetFormulaStaticDataTableQueryReference[],
|
|
2447
|
+
volatile: compiledFormula.volatile === true,
|
|
2448
|
+
};
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
/*
|
|
2452
|
+
* Return a one-based column index from a spreadsheet-style column label.
|
|
2453
|
+
*/
|
|
2454
|
+
export function getSheetFormulaColumnIndex(columnLabel: string) {
|
|
2455
|
+
return columnLabel
|
|
2456
|
+
.toUpperCase()
|
|
2457
|
+
.split('')
|
|
2458
|
+
.reduce((index, char) => {
|
|
2459
|
+
return index * 26 + char.charCodeAt(0) - 64;
|
|
2460
|
+
}, 0);
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
/*
|
|
2464
|
+
* Return a spreadsheet-style column label from a one-based column index.
|
|
2465
|
+
*/
|
|
2466
|
+
export function getSheetFormulaColumnLabel(columnIndex: number) {
|
|
2467
|
+
let label = '';
|
|
2468
|
+
let remaining = Math.floor(columnIndex);
|
|
2469
|
+
|
|
2470
|
+
while (remaining > 0) {
|
|
2471
|
+
const remainder = (remaining - 1) % 26;
|
|
2472
|
+
label = String.fromCharCode(65 + remainder) + label;
|
|
2473
|
+
remaining = Math.floor((remaining - 1) / 26);
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
return label;
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
/*
|
|
2480
|
+
* Render a parsed spreadsheet cell reference while preserving its absolute
|
|
2481
|
+
* row and column markers.
|
|
2482
|
+
*/
|
|
2483
|
+
export function getSheetFormulaCellReferenceText(
|
|
2484
|
+
reference: SheetFormulaCellReference,
|
|
2485
|
+
) {
|
|
2486
|
+
return `${reference.columnAbsolute ? '$' : ''}${getSheetFormulaColumnLabel(reference.columnIndex)}${reference.rowAbsolute ? '$' : ''}${reference.rowIndex}`;
|
|
2487
|
+
}
|
|
2488
|
+
|
|
2489
|
+
/*
|
|
2490
|
+
* Parse a spreadsheet-style cell reference like C12 or $C$12.
|
|
2491
|
+
*/
|
|
2492
|
+
export function parseSheetFormulaCellReference(
|
|
2493
|
+
value: string,
|
|
2494
|
+
): SheetFormulaCellReference | null {
|
|
2495
|
+
const trimmed = value.trim();
|
|
2496
|
+
const bangIndex = trimmed.lastIndexOf('!');
|
|
2497
|
+
if (bangIndex > 0) {
|
|
2498
|
+
const sheetNameText = trimmed.slice(0, bangIndex);
|
|
2499
|
+
const cellText = trimmed.slice(bangIndex + 1);
|
|
2500
|
+
const sheetName =
|
|
2501
|
+
sheetNameText.startsWith("'") && sheetNameText.endsWith("'")
|
|
2502
|
+
? normalizeSheetFormulaReferenceSheetName(
|
|
2503
|
+
sheetNameText.slice(1, -1).replaceAll("''", "'"),
|
|
2504
|
+
)
|
|
2505
|
+
: normalizeSheetFormulaReferenceSheetName(sheetNameText);
|
|
2506
|
+
const reference = parseSheetFormulaCellReference(cellText);
|
|
2507
|
+
|
|
2508
|
+
return reference && sheetName
|
|
2509
|
+
? {
|
|
2510
|
+
...reference,
|
|
2511
|
+
sheetName,
|
|
2512
|
+
}
|
|
2513
|
+
: null;
|
|
2514
|
+
}
|
|
2515
|
+
|
|
2516
|
+
const match = trimmed.match(/^(\$?)([A-Za-z]+)(\$?)([1-9]\d*)$/);
|
|
2517
|
+
if (!match) {
|
|
2518
|
+
return null;
|
|
2519
|
+
}
|
|
2520
|
+
|
|
2521
|
+
const columnLabel = match[2].toUpperCase();
|
|
2522
|
+
const columnIndex = getSheetFormulaColumnIndex(columnLabel);
|
|
2523
|
+
const rowIndex = Number(match[4]);
|
|
2524
|
+
|
|
2525
|
+
return {
|
|
2526
|
+
...(match[1] ? { columnAbsolute: true } : {}),
|
|
2527
|
+
columnIndex,
|
|
2528
|
+
columnLabel,
|
|
2529
|
+
...(match[3] ? { rowAbsolute: true } : {}),
|
|
2530
|
+
rowIndex,
|
|
2531
|
+
};
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
/*
|
|
2535
|
+
* Parse a formula function call by name.
|
|
2536
|
+
*/
|
|
2537
|
+
export function parseSheetFormulaCall(
|
|
2538
|
+
value: string,
|
|
2539
|
+
functionName?: string | null,
|
|
2540
|
+
): SheetFormulaCall | null {
|
|
2541
|
+
const trimmed = value.trim();
|
|
2542
|
+
const match = trimmed.match(/^(@?[A-Za-z_][A-Za-z0-9_]*)\s*\(/);
|
|
2543
|
+
if (!match || !trimmed.endsWith(')')) {
|
|
2544
|
+
return null;
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
const name = match[1];
|
|
2548
|
+
if (functionName && name.toLowerCase() !== functionName.toLowerCase()) {
|
|
2549
|
+
return null;
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
const argsText = trimmed.slice(match[0].length, -1);
|
|
2553
|
+
return {
|
|
2554
|
+
args: splitSheetFormulaTopLevel(argsText, ','),
|
|
2555
|
+
name,
|
|
2556
|
+
text: trimmed,
|
|
2557
|
+
};
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
/*
|
|
2561
|
+
* Parse a data table field key expression, keeping cell-like values as cell references.
|
|
2562
|
+
*/
|
|
2563
|
+
function parseSheetFormulaDataTableCellKeyExpression(value: string) {
|
|
2564
|
+
const trimmed = value.trim();
|
|
2565
|
+
const stringLiteral = parseSheetFormulaStringLiteral(trimmed);
|
|
2566
|
+
if (stringLiteral !== null) {
|
|
2567
|
+
return stringLiteral;
|
|
2568
|
+
}
|
|
2569
|
+
|
|
2570
|
+
if (
|
|
2571
|
+
!SHEET_FORMULA_BARE_DATA_TABLE_CELL_KEY_PATTERN.test(trimmed) ||
|
|
2572
|
+
parseSheetFormulaCellReference(trimmed)
|
|
2573
|
+
) {
|
|
2574
|
+
return null;
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
return trimmed;
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
/*
|
|
2581
|
+
* Return the formula text that references one data table field key, written as a
|
|
2582
|
+
* bare identifier when it is a safe key and a quoted string literal otherwise.
|
|
2583
|
+
* This is the inverse of parseSheetFormulaDataTableCellKeyExpression and is used
|
|
2584
|
+
* when inserting a chosen field key back into a formula.
|
|
2585
|
+
*/
|
|
2586
|
+
export function getSheetFormulaDataTableCellKeyText(key: string) {
|
|
2587
|
+
const trimmed = String(key || '').trim();
|
|
2588
|
+
|
|
2589
|
+
if (
|
|
2590
|
+
trimmed &&
|
|
2591
|
+
SHEET_FORMULA_BARE_DATA_TABLE_CELL_KEY_PATTERN.test(trimmed) &&
|
|
2592
|
+
!parseSheetFormulaCellReference(trimmed)
|
|
2593
|
+
) {
|
|
2594
|
+
return trimmed;
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
return JSON.stringify(trimmed);
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
/*
|
|
2601
|
+
* Parse a data table formula call such as @organizations("row", "category") or organizations("row", "category").
|
|
2602
|
+
*/
|
|
2603
|
+
export function parseSheetFormulaDataTableCall(
|
|
2604
|
+
value: string,
|
|
2605
|
+
): SheetFormulaDataTableCall | null {
|
|
2606
|
+
const call = parseSheetFormulaCall(value);
|
|
2607
|
+
if (!call) {
|
|
2608
|
+
return null;
|
|
2609
|
+
}
|
|
2610
|
+
|
|
2611
|
+
const dataTableName = normalizeSheetFormulaDataTableName(
|
|
2612
|
+
call.name.startsWith('@') ? call.name.slice(1) : call.name,
|
|
2613
|
+
);
|
|
2614
|
+
if (!dataTableName || call.args.length !== 2) {
|
|
2615
|
+
return null;
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2618
|
+
const cellKey = parseSheetFormulaDataTableCellKeyExpression(call.args[1]);
|
|
2619
|
+
if (!cellKey) {
|
|
2620
|
+
return null;
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
return {
|
|
2624
|
+
cellKey,
|
|
2625
|
+
dataTableName,
|
|
2626
|
+
rowIdentifierExpression: call.args[0],
|
|
2627
|
+
text: call.text,
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
|
|
2631
|
+
/*
|
|
2632
|
+
* Return the canonical formula date/time shorthand name for a bare or called identifier.
|
|
2633
|
+
*/
|
|
2634
|
+
function normalizeSheetFormulaDateTimeShorthandName(
|
|
2635
|
+
value: string,
|
|
2636
|
+
): SheetFormulaDateTimeShorthandName | null {
|
|
2637
|
+
const normalized = value.trim().toUpperCase();
|
|
2638
|
+
|
|
2639
|
+
if (normalized === 'TODAY' || normalized === 'CURRENT_DATE') {
|
|
2640
|
+
return 'CURRENT_DATE';
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
if (normalized === 'NOW' || normalized === 'CURRENT_DATETIME') {
|
|
2644
|
+
return 'CURRENT_DATETIME';
|
|
2645
|
+
}
|
|
2646
|
+
|
|
2647
|
+
return null;
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2650
|
+
/*
|
|
2651
|
+
* Parse a supported query date/time shorthand such as TODAY or NOW().
|
|
2652
|
+
*/
|
|
2653
|
+
export function parseSheetFormulaDateTimeShorthand(
|
|
2654
|
+
value: string,
|
|
2655
|
+
): Extract<SheetFormulaASTNode, { kind: 'DATE_TIME_SHORTHAND' }> | null {
|
|
2656
|
+
const trimmed = value.trim();
|
|
2657
|
+
const call = parseSheetFormulaCall(trimmed);
|
|
2658
|
+
const isEmptyCall = call
|
|
2659
|
+
? call.args.length === 0 ||
|
|
2660
|
+
(call.args.length === 1 && call.args[0].trim() === '')
|
|
2661
|
+
: false;
|
|
2662
|
+
const shorthandName = call
|
|
2663
|
+
? isEmptyCall
|
|
2664
|
+
? normalizeSheetFormulaDateTimeShorthandName(call.name)
|
|
2665
|
+
: null
|
|
2666
|
+
: normalizeSheetFormulaDateTimeShorthandName(trimmed);
|
|
2667
|
+
|
|
2668
|
+
return shorthandName
|
|
2669
|
+
? {
|
|
2670
|
+
kind: 'DATE_TIME_SHORTHAND',
|
|
2671
|
+
name: shorthandName,
|
|
2672
|
+
text: trimmed,
|
|
2673
|
+
}
|
|
2674
|
+
: null;
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
/*
|
|
2678
|
+
* Parse a query condition's left-side dataTable cell key.
|
|
2679
|
+
*/
|
|
2680
|
+
function parseSheetFormulaDataTableQueryConditionCellKey(value: string) {
|
|
2681
|
+
const trimmed = value.trimStart();
|
|
2682
|
+
const offset = value.length - trimmed.length;
|
|
2683
|
+
|
|
2684
|
+
if (isSheetFormulaStringQuoteChar(trimmed[0])) {
|
|
2685
|
+
const endIndex = getSheetFormulaStringEndIndex(trimmed, 0);
|
|
2686
|
+
const text = trimmed.slice(0, endIndex);
|
|
2687
|
+
const cellKey = parseSheetFormulaStringLiteral(text);
|
|
2688
|
+
return cellKey
|
|
2689
|
+
? {
|
|
2690
|
+
cellKey,
|
|
2691
|
+
endIndex: offset + endIndex,
|
|
2692
|
+
}
|
|
2693
|
+
: null;
|
|
2694
|
+
}
|
|
2695
|
+
|
|
2696
|
+
const match = trimmed.match(/^[A-Za-z_][A-Za-z0-9_]*/);
|
|
2697
|
+
return match
|
|
2698
|
+
? {
|
|
2699
|
+
cellKey: match[0],
|
|
2700
|
+
endIndex: offset + match[0].length,
|
|
2701
|
+
}
|
|
2702
|
+
: null;
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
/*
|
|
2706
|
+
* Parse a query condition value using the flexible data-table query grammar.
|
|
2707
|
+
*/
|
|
2708
|
+
function parseSheetFormulaDataTableQueryValueExpression(
|
|
2709
|
+
value: string,
|
|
2710
|
+
): SheetFormulaASTNode | null {
|
|
2711
|
+
const trimmed = value.trim();
|
|
2712
|
+
if (!trimmed) {
|
|
2713
|
+
return null;
|
|
2714
|
+
}
|
|
2715
|
+
|
|
2716
|
+
const shorthandNode = parseSheetFormulaDateTimeShorthand(trimmed);
|
|
2717
|
+
if (shorthandNode) {
|
|
2718
|
+
return shorthandNode;
|
|
2719
|
+
}
|
|
2720
|
+
|
|
2721
|
+
if (SHEET_FORMULA_ISO_DATE_VALUE_PATTERN.test(trimmed)) {
|
|
2722
|
+
return {
|
|
2723
|
+
kind: 'STRING_LITERAL',
|
|
2724
|
+
text: trimmed,
|
|
2725
|
+
value: trimmed,
|
|
2726
|
+
};
|
|
2727
|
+
}
|
|
2728
|
+
|
|
2729
|
+
const expressionNode = parseSheetFormulaExpression(trimmed);
|
|
2730
|
+
if (expressionNode) {
|
|
2731
|
+
return expressionNode;
|
|
2732
|
+
}
|
|
2733
|
+
|
|
2734
|
+
if (
|
|
2735
|
+
SHEET_FORMULA_BARE_STRING_VALUE_PATTERN.test(trimmed) &&
|
|
2736
|
+
!parseSheetFormulaCellReference(trimmed)
|
|
2737
|
+
) {
|
|
2738
|
+
return {
|
|
2739
|
+
kind: 'STRING_LITERAL',
|
|
2740
|
+
text: trimmed,
|
|
2741
|
+
value: trimmed,
|
|
2742
|
+
};
|
|
2743
|
+
}
|
|
2744
|
+
|
|
2745
|
+
return null;
|
|
2746
|
+
}
|
|
2747
|
+
|
|
2748
|
+
/*
|
|
2749
|
+
* Parse one dataTable query WHERE condition.
|
|
2750
|
+
*/
|
|
2751
|
+
function parseSheetFormulaDataTableQueryCondition(
|
|
2752
|
+
value: string,
|
|
2753
|
+
): SheetFormulaDataTableQueryCondition | null {
|
|
2754
|
+
const cellKey = parseSheetFormulaDataTableQueryConditionCellKey(value);
|
|
2755
|
+
if (!cellKey) {
|
|
2756
|
+
return null;
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
const rest = value.slice(cellKey.endIndex).trimStart();
|
|
2760
|
+
const operatorMatch = rest.match(/^(<=|>=|<>|!=|=|<|>)/);
|
|
2761
|
+
if (!operatorMatch) {
|
|
2762
|
+
return null;
|
|
2763
|
+
}
|
|
2764
|
+
|
|
2765
|
+
const operator = operatorMatch[1] as SheetFormulaDataTableQueryOperator;
|
|
2766
|
+
const valueExpression = rest.slice(operator.length).trim();
|
|
2767
|
+
const valueNode = valueExpression
|
|
2768
|
+
? parseSheetFormulaDataTableQueryValueExpression(valueExpression)
|
|
2769
|
+
: null;
|
|
2770
|
+
if (
|
|
2771
|
+
!valueNode ||
|
|
2772
|
+
(valueNode.kind !== 'STRING_LITERAL' &&
|
|
2773
|
+
valueNode.kind !== 'NUMBER_LITERAL' &&
|
|
2774
|
+
valueNode.kind !== 'BOOLEAN_LITERAL' &&
|
|
2775
|
+
valueNode.kind !== 'CELL_REFERENCE' &&
|
|
2776
|
+
valueNode.kind !== 'DATE_TIME_SHORTHAND')
|
|
2777
|
+
) {
|
|
2778
|
+
return null;
|
|
2779
|
+
}
|
|
2780
|
+
|
|
2781
|
+
return {
|
|
2782
|
+
cellKey: cellKey.cellKey,
|
|
2783
|
+
operator,
|
|
2784
|
+
text: value.trim(),
|
|
2785
|
+
valueExpression,
|
|
2786
|
+
valueNode,
|
|
2787
|
+
};
|
|
2788
|
+
}
|
|
2789
|
+
|
|
2790
|
+
/*
|
|
2791
|
+
* Return a readable formula syntax issue for one invalid query condition.
|
|
2792
|
+
*/
|
|
2793
|
+
function getSheetFormulaDataTableQueryConditionSyntaxIssue(
|
|
2794
|
+
value: string,
|
|
2795
|
+
): SheetFormulaSyntaxIssue | null {
|
|
2796
|
+
const trimmed = value.trim();
|
|
2797
|
+
if (!trimmed) {
|
|
2798
|
+
return null;
|
|
2799
|
+
}
|
|
2800
|
+
|
|
2801
|
+
const cellKey = parseSheetFormulaDataTableQueryConditionCellKey(value);
|
|
2802
|
+
if (!cellKey) {
|
|
2803
|
+
return {
|
|
2804
|
+
message: 'Query conditions must start with a field key.',
|
|
2805
|
+
text: trimmed,
|
|
2806
|
+
};
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
const rest = value.slice(cellKey.endIndex).trimStart();
|
|
2810
|
+
const operatorMatch = rest.match(/^(<=|>=|<>|!=|=|<|>)/);
|
|
2811
|
+
if (!operatorMatch) {
|
|
2812
|
+
return {
|
|
2813
|
+
message:
|
|
2814
|
+
'Query condition is missing a comparison operator such as =, !=, <, or >.',
|
|
2815
|
+
text: trimmed,
|
|
2816
|
+
};
|
|
2817
|
+
}
|
|
2818
|
+
|
|
2819
|
+
const valueExpression = rest.slice(operatorMatch[1].length).trim();
|
|
2820
|
+
if (!valueExpression) {
|
|
2821
|
+
return {
|
|
2822
|
+
message: 'Query condition is missing a value after the operator.',
|
|
2823
|
+
text: trimmed,
|
|
2824
|
+
};
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
const valueNode =
|
|
2828
|
+
parseSheetFormulaDataTableQueryValueExpression(valueExpression);
|
|
2829
|
+
if (!valueNode) {
|
|
2830
|
+
return {
|
|
2831
|
+
message: 'Query condition value could not be parsed.',
|
|
2832
|
+
text: valueExpression,
|
|
2833
|
+
};
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
if (
|
|
2837
|
+
valueNode.kind !== 'STRING_LITERAL' &&
|
|
2838
|
+
valueNode.kind !== 'NUMBER_LITERAL' &&
|
|
2839
|
+
valueNode.kind !== 'BOOLEAN_LITERAL' &&
|
|
2840
|
+
valueNode.kind !== 'CELL_REFERENCE' &&
|
|
2841
|
+
valueNode.kind !== 'DATE_TIME_SHORTHAND'
|
|
2842
|
+
) {
|
|
2843
|
+
return {
|
|
2844
|
+
message:
|
|
2845
|
+
'Query condition value must be a string, number, boolean, cell reference, TODAY, or NOW().',
|
|
2846
|
+
text: valueExpression,
|
|
2847
|
+
};
|
|
2848
|
+
}
|
|
2849
|
+
|
|
2850
|
+
return null;
|
|
2851
|
+
}
|
|
2852
|
+
|
|
2853
|
+
/*
|
|
2854
|
+
* Parse AND-joined dataTable query WHERE conditions.
|
|
2855
|
+
*/
|
|
2856
|
+
function parseSheetFormulaDataTableQueryConditions(value: string) {
|
|
2857
|
+
const conditionTexts = splitSheetFormulaTopLevelKeyword(value, 'AND').filter(
|
|
2858
|
+
Boolean,
|
|
2859
|
+
);
|
|
2860
|
+
if (!conditionTexts.length) {
|
|
2861
|
+
return null;
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
const conditions = conditionTexts.map(
|
|
2865
|
+
parseSheetFormulaDataTableQueryCondition,
|
|
2866
|
+
);
|
|
2867
|
+
return conditions.every(
|
|
2868
|
+
(condition): condition is SheetFormulaDataTableQueryCondition =>
|
|
2869
|
+
Boolean(condition),
|
|
2870
|
+
)
|
|
2871
|
+
? conditions
|
|
2872
|
+
: null;
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
/*
|
|
2876
|
+
* Return possible end indexes for a data-table query expression that starts at
|
|
2877
|
+
* one index inside a larger formula expression.
|
|
2878
|
+
*/
|
|
2879
|
+
function getSheetFormulaDataTableQueryCandidateEndIndexes(
|
|
2880
|
+
value: string,
|
|
2881
|
+
startIndex: number,
|
|
2882
|
+
) {
|
|
2883
|
+
const candidateEndIndexes: number[] = [];
|
|
2884
|
+
let depth = 0;
|
|
2885
|
+
let quoteChar: string | null = null;
|
|
2886
|
+
let escaped = false;
|
|
2887
|
+
|
|
2888
|
+
for (let index = startIndex; index < value.length; index += 1) {
|
|
2889
|
+
const char = value[index];
|
|
2890
|
+
|
|
2891
|
+
if (escaped) {
|
|
2892
|
+
escaped = false;
|
|
2893
|
+
continue;
|
|
2894
|
+
}
|
|
2895
|
+
|
|
2896
|
+
if (char === '\\' && quoteChar) {
|
|
2897
|
+
escaped = true;
|
|
2898
|
+
continue;
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
if (quoteChar ? char === quoteChar : isSheetFormulaStringQuoteChar(char)) {
|
|
2902
|
+
quoteChar = quoteChar ? null : char;
|
|
2903
|
+
continue;
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
if (quoteChar) {
|
|
2907
|
+
continue;
|
|
2908
|
+
}
|
|
2909
|
+
|
|
2910
|
+
if (char === '(') {
|
|
2911
|
+
depth += 1;
|
|
2912
|
+
continue;
|
|
2913
|
+
}
|
|
2914
|
+
|
|
2915
|
+
if (char === ')') {
|
|
2916
|
+
if (depth === 0) {
|
|
2917
|
+
candidateEndIndexes.push(index);
|
|
2918
|
+
break;
|
|
2919
|
+
}
|
|
2920
|
+
|
|
2921
|
+
depth -= 1;
|
|
2922
|
+
continue;
|
|
2923
|
+
}
|
|
2924
|
+
|
|
2925
|
+
if (depth === 0 && char === ',') {
|
|
2926
|
+
candidateEndIndexes.push(index);
|
|
2927
|
+
break;
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
if (!candidateEndIndexes.includes(value.length)) {
|
|
2932
|
+
candidateEndIndexes.push(value.length);
|
|
2933
|
+
}
|
|
2934
|
+
|
|
2935
|
+
return candidateEndIndexes;
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
/*
|
|
2939
|
+
* Parse a data table query formula such as @orders("total") WHERE id = A1.
|
|
2940
|
+
*/
|
|
2941
|
+
export function parseSheetFormulaDataTableQueryCall(
|
|
2942
|
+
value: string,
|
|
2943
|
+
): SheetFormulaDataTableQueryCall | null {
|
|
2944
|
+
const trimmed = value.trim();
|
|
2945
|
+
const match = trimmed.match(/^(@?[A-Za-z_][A-Za-z0-9_]*)\s*\(/);
|
|
2946
|
+
if (!match) {
|
|
2947
|
+
return null;
|
|
2948
|
+
}
|
|
2949
|
+
|
|
2950
|
+
const openParenIndex = match[0].lastIndexOf('(');
|
|
2951
|
+
const callEndIndex = getSheetFormulaCallEndIndex(trimmed, openParenIndex);
|
|
2952
|
+
if (!callEndIndex) {
|
|
2953
|
+
return null;
|
|
2954
|
+
}
|
|
2955
|
+
|
|
2956
|
+
const call = parseSheetFormulaCall(trimmed.slice(0, callEndIndex));
|
|
2957
|
+
const whereText = trimmed.slice(callEndIndex).trim();
|
|
2958
|
+
if (!call || !/^WHERE\b/i.test(whereText)) {
|
|
2959
|
+
return null;
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2962
|
+
const dataTableName = normalizeSheetFormulaDataTableName(
|
|
2963
|
+
call.name.startsWith('@') ? call.name.slice(1) : call.name,
|
|
2964
|
+
);
|
|
2965
|
+
const cellKey =
|
|
2966
|
+
call.args.length === 1
|
|
2967
|
+
? parseSheetFormulaDataTableCellKeyExpression(call.args[0])
|
|
2968
|
+
: null;
|
|
2969
|
+
const conditions = parseSheetFormulaDataTableQueryConditions(
|
|
2970
|
+
whereText.replace(/^WHERE\b/i, '').trim(),
|
|
2971
|
+
);
|
|
2972
|
+
if (!dataTableName || !cellKey || !conditions) {
|
|
2973
|
+
return null;
|
|
2974
|
+
}
|
|
2975
|
+
|
|
2976
|
+
return {
|
|
2977
|
+
cellKey,
|
|
2978
|
+
conditions,
|
|
2979
|
+
dataTableName,
|
|
2980
|
+
text: trimmed,
|
|
2981
|
+
};
|
|
2982
|
+
}
|
|
2983
|
+
|
|
2984
|
+
/*
|
|
2985
|
+
* Return one parsed data-table query expression that starts at a formula index.
|
|
2986
|
+
*/
|
|
2987
|
+
function parseSheetFormulaDataTableQueryCallAtIndex(
|
|
2988
|
+
value: string,
|
|
2989
|
+
startIndex: number,
|
|
2990
|
+
) {
|
|
2991
|
+
if (/\s/.test(value[startIndex] || '')) {
|
|
2992
|
+
return null;
|
|
2993
|
+
}
|
|
2994
|
+
|
|
2995
|
+
const candidateEndIndexes = getSheetFormulaDataTableQueryCandidateEndIndexes(
|
|
2996
|
+
value,
|
|
2997
|
+
startIndex,
|
|
2998
|
+
);
|
|
2999
|
+
for (const endIndex of candidateEndIndexes) {
|
|
3000
|
+
const query = parseSheetFormulaDataTableQueryCall(
|
|
3001
|
+
value.slice(startIndex, endIndex),
|
|
3002
|
+
);
|
|
3003
|
+
if (query) {
|
|
3004
|
+
return {
|
|
3005
|
+
endIndex,
|
|
3006
|
+
query,
|
|
3007
|
+
};
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
|
|
3011
|
+
return null;
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
/*
|
|
3015
|
+
* Return a data-table query AST node at the current parser position.
|
|
3016
|
+
*/
|
|
3017
|
+
function parseSheetFormulaDataTableQueryNode(
|
|
3018
|
+
state: SheetFormulaParserState,
|
|
3019
|
+
): SheetFormulaASTNode | null {
|
|
3020
|
+
const result = parseSheetFormulaDataTableQueryCallAtIndex(
|
|
3021
|
+
state.value,
|
|
3022
|
+
state.index,
|
|
3023
|
+
);
|
|
3024
|
+
if (!result) {
|
|
3025
|
+
return null;
|
|
3026
|
+
}
|
|
3027
|
+
|
|
3028
|
+
state.index = result.endIndex;
|
|
3029
|
+
return {
|
|
3030
|
+
kind: 'DATA_TABLE_QUERY',
|
|
3031
|
+
query: result.query,
|
|
3032
|
+
text: result.query.text,
|
|
3033
|
+
};
|
|
3034
|
+
}
|
|
3035
|
+
|
|
3036
|
+
/*
|
|
3037
|
+
* Return syntax issues for a data table query formula that could not be parsed.
|
|
3038
|
+
*/
|
|
3039
|
+
function getSheetFormulaDataTableQuerySyntaxIssues(
|
|
3040
|
+
value: string,
|
|
3041
|
+
): SheetFormulaSyntaxIssue[] {
|
|
3042
|
+
const trimmed = value.trim();
|
|
3043
|
+
const match = trimmed.match(/^(@?[A-Za-z_][A-Za-z0-9_]*)\s*\(/);
|
|
3044
|
+
if (!match) {
|
|
3045
|
+
return [];
|
|
3046
|
+
}
|
|
3047
|
+
|
|
3048
|
+
const openParenIndex = match[0].lastIndexOf('(');
|
|
3049
|
+
const callEndIndex = getSheetFormulaCallEndIndex(trimmed, openParenIndex);
|
|
3050
|
+
if (!callEndIndex) {
|
|
3051
|
+
return [
|
|
3052
|
+
{
|
|
3053
|
+
message: 'Data table query call is missing a closing parenthesis.',
|
|
3054
|
+
text: trimmed,
|
|
3055
|
+
},
|
|
3056
|
+
];
|
|
3057
|
+
}
|
|
3058
|
+
|
|
3059
|
+
const callText = trimmed.slice(0, callEndIndex);
|
|
3060
|
+
const call = parseSheetFormulaCall(callText);
|
|
3061
|
+
const whereText = trimmed.slice(callEndIndex).trim();
|
|
3062
|
+
const issues: SheetFormulaSyntaxIssue[] = [];
|
|
3063
|
+
if (!call) {
|
|
3064
|
+
issues.push({
|
|
3065
|
+
message: 'Data table query call could not be parsed.',
|
|
3066
|
+
text: callText,
|
|
3067
|
+
});
|
|
3068
|
+
}
|
|
3069
|
+
|
|
3070
|
+
const resultKeyText = call?.args.length === 1 ? call.args[0].trim() : '';
|
|
3071
|
+
if (
|
|
3072
|
+
!call ||
|
|
3073
|
+
call.args.length !== 1 ||
|
|
3074
|
+
parseSheetFormulaDataTableCellKeyExpression(resultKeyText) === null
|
|
3075
|
+
) {
|
|
3076
|
+
issues.push({
|
|
3077
|
+
message:
|
|
3078
|
+
'Data table query result field must be a quoted or bare field key, for example @attendance(attended). Quote field keys that look like cell references.',
|
|
3079
|
+
text: resultKeyText || callText,
|
|
3080
|
+
});
|
|
3081
|
+
}
|
|
3082
|
+
|
|
3083
|
+
if (!/^WHERE\b/i.test(whereText)) {
|
|
3084
|
+
issues.push({
|
|
3085
|
+
message: 'Data table query must include a WHERE clause after the call.',
|
|
3086
|
+
text: whereText || trimmed,
|
|
3087
|
+
});
|
|
3088
|
+
return issues;
|
|
3089
|
+
}
|
|
3090
|
+
|
|
3091
|
+
const conditionText = whereText.replace(/^WHERE\b/i, '').trim();
|
|
3092
|
+
const conditionParts = splitSheetFormulaTopLevelKeyword(
|
|
3093
|
+
conditionText,
|
|
3094
|
+
'AND',
|
|
3095
|
+
).filter(Boolean);
|
|
3096
|
+
if (!conditionParts.length) {
|
|
3097
|
+
issues.push({
|
|
3098
|
+
message: 'WHERE clause must include at least one condition.',
|
|
3099
|
+
text: whereText,
|
|
3100
|
+
});
|
|
3101
|
+
return issues;
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
for (const conditionPart of conditionParts) {
|
|
3105
|
+
const issue =
|
|
3106
|
+
getSheetFormulaDataTableQueryConditionSyntaxIssue(conditionPart);
|
|
3107
|
+
if (issue) {
|
|
3108
|
+
issues.push(issue);
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
|
|
3112
|
+
return issues;
|
|
3113
|
+
}
|
|
3114
|
+
|
|
3115
|
+
/*
|
|
3116
|
+
* Return a concise syntax error message that points at the unsupported formula parts.
|
|
3117
|
+
*/
|
|
3118
|
+
export function getSheetFormulaSyntaxErrorMessage(value: string) {
|
|
3119
|
+
const trimmed = value.trim();
|
|
3120
|
+
const queryIssues = getSheetFormulaDataTableQuerySyntaxIssues(trimmed);
|
|
3121
|
+
if (queryIssues.length) {
|
|
3122
|
+
const issueText = queryIssues
|
|
3123
|
+
.map((issue) =>
|
|
3124
|
+
issue.text ? `${issue.text}: ${issue.message}` : issue.message,
|
|
3125
|
+
)
|
|
3126
|
+
.join(' ');
|
|
3127
|
+
|
|
3128
|
+
return `Formula syntax is not supported. ${issueText}`;
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
const state = {
|
|
3132
|
+
index: 0,
|
|
3133
|
+
value: trimmed,
|
|
3134
|
+
};
|
|
3135
|
+
const node = parseSheetFormulaComparisonExpression(state);
|
|
3136
|
+
if (node) {
|
|
3137
|
+
skipSheetFormulaParserWhitespace(state);
|
|
3138
|
+
const unsupportedText = trimmed.slice(state.index).trim();
|
|
3139
|
+
if (unsupportedText) {
|
|
3140
|
+
return `Formula syntax is not supported. Unsupported part: ${unsupportedText}`;
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
return 'Formula syntax is not supported.';
|
|
3145
|
+
}
|
|
3146
|
+
|
|
3147
|
+
/*
|
|
3148
|
+
* Return a stable key for resolved dataTable query condition values.
|
|
3149
|
+
*/
|
|
3150
|
+
export function getSheetFormulaDataTableQueryConditionKey(
|
|
3151
|
+
conditions: Array<{
|
|
3152
|
+
cellKey: string;
|
|
3153
|
+
keyValue?: unknown;
|
|
3154
|
+
operator: SheetFormulaDataTableQueryOperator;
|
|
3155
|
+
value: unknown;
|
|
3156
|
+
}>,
|
|
3157
|
+
) {
|
|
3158
|
+
return JSON.stringify(
|
|
3159
|
+
conditions.map((condition) => ({
|
|
3160
|
+
cellKey: condition.cellKey,
|
|
3161
|
+
operator: condition.operator,
|
|
3162
|
+
value:
|
|
3163
|
+
condition.keyValue === null || condition.keyValue === undefined
|
|
3164
|
+
? condition.value === null || condition.value === undefined
|
|
3165
|
+
? null
|
|
3166
|
+
: String(condition.value)
|
|
3167
|
+
: String(condition.keyValue),
|
|
3168
|
+
})),
|
|
3169
|
+
);
|
|
3170
|
+
}
|
|
3171
|
+
|
|
3172
|
+
/*
|
|
3173
|
+
* Return a data table query reference token at one formula text index, when one starts there.
|
|
3174
|
+
*/
|
|
3175
|
+
function getSheetFormulaDataTableQueryReferenceTokenAtIndex(
|
|
3176
|
+
value: string,
|
|
3177
|
+
startIndex: number,
|
|
3178
|
+
): SheetFormulaReferenceToken | null {
|
|
3179
|
+
const result = parseSheetFormulaDataTableQueryCallAtIndex(value, startIndex);
|
|
3180
|
+
if (!result) {
|
|
3181
|
+
return null;
|
|
3182
|
+
}
|
|
3183
|
+
|
|
3184
|
+
return {
|
|
3185
|
+
...result.query,
|
|
3186
|
+
endIndex: result.endIndex,
|
|
3187
|
+
kind: 'DATA_TABLE_QUERY_CELL',
|
|
3188
|
+
startIndex,
|
|
3189
|
+
text: result.query.text,
|
|
3190
|
+
};
|
|
3191
|
+
}
|
|
3192
|
+
|
|
3193
|
+
/*
|
|
3194
|
+
* Return a data table reference token at one formula text index, when one starts there.
|
|
3195
|
+
*/
|
|
3196
|
+
function getSheetFormulaDataTableReferenceTokenAtIndex(
|
|
3197
|
+
value: string,
|
|
3198
|
+
startIndex: number,
|
|
3199
|
+
): SheetFormulaReferenceToken | null {
|
|
3200
|
+
const slice = value.slice(startIndex);
|
|
3201
|
+
const match = slice.match(/^@?[A-Za-z_][A-Za-z0-9_]*\s*\(/);
|
|
3202
|
+
if (!match) {
|
|
3203
|
+
return null;
|
|
3204
|
+
}
|
|
3205
|
+
|
|
3206
|
+
const openParenIndex = startIndex + match[0].lastIndexOf('(');
|
|
3207
|
+
const endIndex = getSheetFormulaCallEndIndex(value, openParenIndex);
|
|
3208
|
+
if (!endIndex) {
|
|
3209
|
+
return null;
|
|
3210
|
+
}
|
|
3211
|
+
|
|
3212
|
+
const text = value.slice(startIndex, endIndex);
|
|
3213
|
+
const dataTableCall = parseSheetFormulaDataTableCall(text);
|
|
3214
|
+
if (!dataTableCall) {
|
|
3215
|
+
return null;
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
return {
|
|
3219
|
+
...dataTableCall,
|
|
3220
|
+
endIndex,
|
|
3221
|
+
kind: 'DATA_TABLE_CELL',
|
|
3222
|
+
startIndex,
|
|
3223
|
+
text,
|
|
3224
|
+
};
|
|
3225
|
+
}
|
|
3226
|
+
|
|
3227
|
+
/*
|
|
3228
|
+
* Return one complete qualified or unqualified cell/range token at a formula
|
|
3229
|
+
* text index. Coordinate spans are retained separately so rewriters can keep
|
|
3230
|
+
* the user's exact sheet-name quoting and whitespace.
|
|
3231
|
+
*/
|
|
3232
|
+
function getSheetFormulaDirectReferenceTokenAtIndex(
|
|
3233
|
+
value: string,
|
|
3234
|
+
startIndex: number,
|
|
3235
|
+
): SheetFormulaReferenceToken | null {
|
|
3236
|
+
const state = { index: startIndex, value };
|
|
3237
|
+
const start = parseSheetFormulaCellReferenceAtState(state);
|
|
3238
|
+
if (!start) {
|
|
3239
|
+
return null;
|
|
3240
|
+
}
|
|
3241
|
+
|
|
3242
|
+
const afterStartIndex = state.index;
|
|
3243
|
+
skipSheetFormulaParserWhitespace(state);
|
|
3244
|
+
if (value[state.index] !== ':') {
|
|
3245
|
+
return {
|
|
3246
|
+
...start.reference,
|
|
3247
|
+
coordinateEndIndex: start.coordinateEndIndex,
|
|
3248
|
+
coordinateStartIndex: start.coordinateStartIndex,
|
|
3249
|
+
endIndex: afterStartIndex,
|
|
3250
|
+
kind: 'SHEET_CELL',
|
|
3251
|
+
startIndex,
|
|
3252
|
+
text: value.slice(startIndex, afterStartIndex),
|
|
3253
|
+
};
|
|
3254
|
+
}
|
|
3255
|
+
|
|
3256
|
+
state.index += 1;
|
|
3257
|
+
skipSheetFormulaParserWhitespace(state);
|
|
3258
|
+
const end = parseSheetFormulaCellReferenceAtState(state);
|
|
3259
|
+
if (!end) {
|
|
3260
|
+
return null;
|
|
3261
|
+
}
|
|
3262
|
+
const rangeReference = buildSheetFormulaRangeReference(
|
|
3263
|
+
start.reference,
|
|
3264
|
+
end.reference,
|
|
3265
|
+
);
|
|
3266
|
+
if (!rangeReference) {
|
|
3267
|
+
return null;
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
return {
|
|
3271
|
+
...rangeReference,
|
|
3272
|
+
endReference: end.reference,
|
|
3273
|
+
endReferenceCoordinateEndIndex: end.coordinateEndIndex,
|
|
3274
|
+
endReferenceCoordinateStartIndex: end.coordinateStartIndex,
|
|
3275
|
+
endIndex: state.index,
|
|
3276
|
+
kind: 'SHEET_RANGE',
|
|
3277
|
+
startReference: start.reference,
|
|
3278
|
+
startReferenceCoordinateEndIndex: start.coordinateEndIndex,
|
|
3279
|
+
startReferenceCoordinateStartIndex: start.coordinateStartIndex,
|
|
3280
|
+
startIndex,
|
|
3281
|
+
text: value.slice(startIndex, state.index),
|
|
3282
|
+
};
|
|
3283
|
+
}
|
|
3284
|
+
|
|
3285
|
+
/*
|
|
3286
|
+
* Return reference tokens from formula text for live client highlighting.
|
|
3287
|
+
*/
|
|
3288
|
+
export function tokenizeSheetFormulaReferences(
|
|
3289
|
+
value: string,
|
|
3290
|
+
): SheetFormulaReferenceToken[] {
|
|
3291
|
+
const tokens: SheetFormulaReferenceToken[] = [];
|
|
3292
|
+
let index = 0;
|
|
3293
|
+
|
|
3294
|
+
while (index < value.length) {
|
|
3295
|
+
const char = value[index];
|
|
3296
|
+
const quotedReferenceToken =
|
|
3297
|
+
char === "'"
|
|
3298
|
+
? getSheetFormulaDirectReferenceTokenAtIndex(value, index)
|
|
3299
|
+
: null;
|
|
3300
|
+
|
|
3301
|
+
if (isSheetFormulaStringQuoteChar(char) && !quotedReferenceToken) {
|
|
3302
|
+
index = getSheetFormulaStringEndIndex(value, index);
|
|
3303
|
+
continue;
|
|
3304
|
+
}
|
|
3305
|
+
|
|
3306
|
+
if (isSheetFormulaIdentifierChar(value[index - 1])) {
|
|
3307
|
+
index += 1;
|
|
3308
|
+
continue;
|
|
3309
|
+
}
|
|
3310
|
+
|
|
3311
|
+
const dataTableQueryToken =
|
|
3312
|
+
getSheetFormulaDataTableQueryReferenceTokenAtIndex(value, index);
|
|
3313
|
+
if (dataTableQueryToken) {
|
|
3314
|
+
tokens.push(dataTableQueryToken);
|
|
3315
|
+
index = dataTableQueryToken.endIndex;
|
|
3316
|
+
continue;
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
const dataTableToken = getSheetFormulaDataTableReferenceTokenAtIndex(
|
|
3320
|
+
value,
|
|
3321
|
+
index,
|
|
3322
|
+
);
|
|
3323
|
+
if (dataTableToken) {
|
|
3324
|
+
tokens.push(dataTableToken);
|
|
3325
|
+
index = dataTableToken.endIndex;
|
|
3326
|
+
continue;
|
|
3327
|
+
}
|
|
3328
|
+
|
|
3329
|
+
const directToken =
|
|
3330
|
+
quotedReferenceToken ||
|
|
3331
|
+
getSheetFormulaDirectReferenceTokenAtIndex(value, index);
|
|
3332
|
+
if (directToken) {
|
|
3333
|
+
tokens.push(directToken);
|
|
3334
|
+
index = directToken.endIndex;
|
|
3335
|
+
continue;
|
|
3336
|
+
}
|
|
3337
|
+
|
|
3338
|
+
index += 1;
|
|
3339
|
+
}
|
|
3340
|
+
|
|
3341
|
+
return tokens;
|
|
3342
|
+
}
|
|
3343
|
+
|
|
3344
|
+
export const SHEET_FORMULA_REF_ERROR = '#REF!';
|
|
3345
|
+
|
|
3346
|
+
/* Display token for cells whose referenced log/entity no longer exists */
|
|
3347
|
+
export const SHEET_DELETED_REFERENCE_ERROR = '#DELETED!';
|
|
3348
|
+
|
|
3349
|
+
export type SheetFormulaShiftResult = {
|
|
3350
|
+
hasRefError: boolean;
|
|
3351
|
+
text: string;
|
|
3352
|
+
};
|
|
3353
|
+
|
|
3354
|
+
export type SheetFormulaAutofillContext = {
|
|
3355
|
+
sourceColumnIndex: number;
|
|
3356
|
+
sourceRowIndex: number;
|
|
3357
|
+
targetColumnIndex: number;
|
|
3358
|
+
targetRowIndex: number;
|
|
3359
|
+
};
|
|
3360
|
+
|
|
3361
|
+
export type SheetFormulaShiftOptions = {
|
|
3362
|
+
autofillContext?: SheetFormulaAutofillContext | null;
|
|
3363
|
+
};
|
|
3364
|
+
|
|
3365
|
+
/*
|
|
3366
|
+
* Return one cell reference rendered after a row/column shift. Column and row
|
|
3367
|
+
* dollar markers lock only their respective axes. Return null when the shift
|
|
3368
|
+
* moves an unlocked axis out of the sheet bounds.
|
|
3369
|
+
*/
|
|
3370
|
+
function getShiftedSheetFormulaCellReferenceText(
|
|
3371
|
+
reference: SheetFormulaCellReference,
|
|
3372
|
+
rowDelta: number,
|
|
3373
|
+
columnDelta: number,
|
|
3374
|
+
) {
|
|
3375
|
+
const rowIndex = reference.rowIndex + (reference.rowAbsolute ? 0 : rowDelta);
|
|
3376
|
+
const columnIndex =
|
|
3377
|
+
reference.columnIndex + (reference.columnAbsolute ? 0 : columnDelta);
|
|
3378
|
+
|
|
3379
|
+
if (rowIndex < 1 || columnIndex < 1) {
|
|
3380
|
+
return null;
|
|
3381
|
+
}
|
|
3382
|
+
|
|
3383
|
+
return getSheetFormulaCellReferenceText({
|
|
3384
|
+
...reference,
|
|
3385
|
+
columnIndex,
|
|
3386
|
+
rowIndex,
|
|
3387
|
+
});
|
|
3388
|
+
}
|
|
3389
|
+
|
|
3390
|
+
/*
|
|
3391
|
+
* Return autofill-aware shift deltas for a data-table query condition ref.
|
|
3392
|
+
* Header-style refs in the source column stay fixed during vertical fills,
|
|
3393
|
+
* and row-label refs in the source row stay fixed during horizontal fills.
|
|
3394
|
+
*/
|
|
3395
|
+
function getSheetFormulaDataTableQueryConditionShiftDeltas(
|
|
3396
|
+
reference: { columnIndex: number; rowIndex: number },
|
|
3397
|
+
rowDelta: number,
|
|
3398
|
+
columnDelta: number,
|
|
3399
|
+
options?: SheetFormulaShiftOptions,
|
|
3400
|
+
) {
|
|
3401
|
+
const context = options?.autofillContext;
|
|
3402
|
+
if (!context) {
|
|
3403
|
+
return { columnDelta, rowDelta };
|
|
3404
|
+
}
|
|
3405
|
+
|
|
3406
|
+
const verticalAutofill =
|
|
3407
|
+
context.sourceColumnIndex === context.targetColumnIndex &&
|
|
3408
|
+
context.sourceRowIndex !== context.targetRowIndex;
|
|
3409
|
+
const horizontalAutofill =
|
|
3410
|
+
context.sourceRowIndex === context.targetRowIndex &&
|
|
3411
|
+
context.sourceColumnIndex !== context.targetColumnIndex;
|
|
3412
|
+
|
|
3413
|
+
if (verticalAutofill && reference.columnIndex === context.sourceColumnIndex) {
|
|
3414
|
+
return { columnDelta, rowDelta: 0 };
|
|
3415
|
+
}
|
|
3416
|
+
|
|
3417
|
+
if (horizontalAutofill && reference.rowIndex === context.sourceRowIndex) {
|
|
3418
|
+
return { columnDelta: 0, rowDelta };
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3421
|
+
return { columnDelta, rowDelta };
|
|
3422
|
+
}
|
|
3423
|
+
|
|
3424
|
+
/*
|
|
3425
|
+
* Return the rewritten text for one reference token after a row/column shift,
|
|
3426
|
+
* or null when the token needs no rewrite. Data table tokens only rewrite the
|
|
3427
|
+
* sheet cell references nested inside them; field keys and table names are
|
|
3428
|
+
* never shifted.
|
|
3429
|
+
*/
|
|
3430
|
+
function getShiftedSheetFormulaReferenceTokenText(
|
|
3431
|
+
token: SheetFormulaReferenceToken,
|
|
3432
|
+
rowDelta: number,
|
|
3433
|
+
columnDelta: number,
|
|
3434
|
+
options?: SheetFormulaShiftOptions,
|
|
3435
|
+
): SheetFormulaShiftResult | null {
|
|
3436
|
+
if (token.kind === 'SHEET_CELL') {
|
|
3437
|
+
const shifted = getShiftedSheetFormulaCellReferenceText(
|
|
3438
|
+
token,
|
|
3439
|
+
rowDelta,
|
|
3440
|
+
columnDelta,
|
|
3441
|
+
);
|
|
3442
|
+
return shifted
|
|
3443
|
+
? {
|
|
3444
|
+
hasRefError: false,
|
|
3445
|
+
text:
|
|
3446
|
+
token.text.slice(0, token.coordinateStartIndex - token.startIndex) +
|
|
3447
|
+
shifted +
|
|
3448
|
+
token.text.slice(token.coordinateEndIndex - token.startIndex),
|
|
3449
|
+
}
|
|
3450
|
+
: { hasRefError: true, text: SHEET_FORMULA_REF_ERROR };
|
|
3451
|
+
}
|
|
3452
|
+
|
|
3453
|
+
if (token.kind === 'SHEET_RANGE') {
|
|
3454
|
+
const start = getShiftedSheetFormulaCellReferenceText(
|
|
3455
|
+
token.startReference,
|
|
3456
|
+
rowDelta,
|
|
3457
|
+
columnDelta,
|
|
3458
|
+
);
|
|
3459
|
+
const end = getShiftedSheetFormulaCellReferenceText(
|
|
3460
|
+
token.endReference,
|
|
3461
|
+
rowDelta,
|
|
3462
|
+
columnDelta,
|
|
3463
|
+
);
|
|
3464
|
+
|
|
3465
|
+
// A range with either corner out of bounds collapses to one #REF! error
|
|
3466
|
+
return start && end
|
|
3467
|
+
? {
|
|
3468
|
+
hasRefError: false,
|
|
3469
|
+
text:
|
|
3470
|
+
token.text.slice(
|
|
3471
|
+
0,
|
|
3472
|
+
token.startReferenceCoordinateStartIndex - token.startIndex,
|
|
3473
|
+
) +
|
|
3474
|
+
start +
|
|
3475
|
+
token.text.slice(
|
|
3476
|
+
token.startReferenceCoordinateEndIndex - token.startIndex,
|
|
3477
|
+
token.endReferenceCoordinateStartIndex - token.startIndex,
|
|
3478
|
+
) +
|
|
3479
|
+
end +
|
|
3480
|
+
token.text.slice(
|
|
3481
|
+
token.endReferenceCoordinateEndIndex - token.startIndex,
|
|
3482
|
+
),
|
|
3483
|
+
}
|
|
3484
|
+
: { hasRefError: true, text: SHEET_FORMULA_REF_ERROR };
|
|
3485
|
+
}
|
|
3486
|
+
|
|
3487
|
+
if (token.kind === 'DATA_TABLE_CELL') {
|
|
3488
|
+
// Only the row identifier argument is an expression that can hold refs
|
|
3489
|
+
const inner = shiftSheetFormulaReferencesInText(
|
|
3490
|
+
token.rowIdentifierExpression.trim(),
|
|
3491
|
+
rowDelta,
|
|
3492
|
+
columnDelta,
|
|
3493
|
+
);
|
|
3494
|
+
if (
|
|
3495
|
+
inner.text === token.rowIdentifierExpression.trim() &&
|
|
3496
|
+
!inner.hasRefError
|
|
3497
|
+
) {
|
|
3498
|
+
return null;
|
|
3499
|
+
}
|
|
3500
|
+
|
|
3501
|
+
const call = parseSheetFormulaCall(token.text);
|
|
3502
|
+
if (!call || call.args.length !== 2) {
|
|
3503
|
+
return null;
|
|
3504
|
+
}
|
|
3505
|
+
|
|
3506
|
+
return {
|
|
3507
|
+
hasRefError: inner.hasRefError,
|
|
3508
|
+
text: `${call.name}(${inner.text}, ${call.args[1].trim()})`,
|
|
3509
|
+
};
|
|
3510
|
+
}
|
|
3511
|
+
|
|
3512
|
+
if (token.kind === 'DATA_TABLE_QUERY_CELL') {
|
|
3513
|
+
// Rewrite only WHERE condition values the parser classified as cell references
|
|
3514
|
+
let hasRefError = false;
|
|
3515
|
+
let changed = false;
|
|
3516
|
+
const conditionTexts = token.conditions.map((condition) => {
|
|
3517
|
+
if (condition.valueNode.kind !== 'CELL_REFERENCE') {
|
|
3518
|
+
return condition.text;
|
|
3519
|
+
}
|
|
3520
|
+
|
|
3521
|
+
const conditionDeltas = getSheetFormulaDataTableQueryConditionShiftDeltas(
|
|
3522
|
+
condition.valueNode.reference,
|
|
3523
|
+
rowDelta,
|
|
3524
|
+
columnDelta,
|
|
3525
|
+
options,
|
|
3526
|
+
);
|
|
3527
|
+
const shifted = shiftSheetFormulaReferencesInText(
|
|
3528
|
+
condition.valueExpression,
|
|
3529
|
+
conditionDeltas.rowDelta,
|
|
3530
|
+
conditionDeltas.columnDelta,
|
|
3531
|
+
);
|
|
3532
|
+
const prefix = condition.text.slice(
|
|
3533
|
+
0,
|
|
3534
|
+
condition.text.length - condition.valueExpression.length,
|
|
3535
|
+
);
|
|
3536
|
+
changed = changed || shifted.text !== condition.valueExpression;
|
|
3537
|
+
hasRefError = hasRefError || shifted.hasRefError;
|
|
3538
|
+
|
|
3539
|
+
return `${prefix}${shifted.text}`;
|
|
3540
|
+
});
|
|
3541
|
+
|
|
3542
|
+
if (!changed) {
|
|
3543
|
+
return null;
|
|
3544
|
+
}
|
|
3545
|
+
|
|
3546
|
+
const headMatch = token.text.match(/^@?[A-Za-z_][A-Za-z0-9_]*\s*\(/);
|
|
3547
|
+
const callEndIndex = headMatch
|
|
3548
|
+
? getSheetFormulaCallEndIndex(token.text, headMatch[0].lastIndexOf('('))
|
|
3549
|
+
: null;
|
|
3550
|
+
if (!callEndIndex) {
|
|
3551
|
+
return null;
|
|
3552
|
+
}
|
|
3553
|
+
|
|
3554
|
+
return {
|
|
3555
|
+
hasRefError,
|
|
3556
|
+
text: `${token.text.slice(0, callEndIndex)} WHERE ${conditionTexts.join(' AND ')}`,
|
|
3557
|
+
};
|
|
3558
|
+
}
|
|
3559
|
+
|
|
3560
|
+
return null;
|
|
3561
|
+
}
|
|
3562
|
+
|
|
3563
|
+
/*
|
|
3564
|
+
* Shift sheet references inside one formula expression text by splicing each
|
|
3565
|
+
* rewritten token over its original span, preserving all other characters.
|
|
3566
|
+
*/
|
|
3567
|
+
function shiftSheetFormulaReferencesInText(
|
|
3568
|
+
text: string,
|
|
3569
|
+
rowDelta: number,
|
|
3570
|
+
columnDelta: number,
|
|
3571
|
+
options?: SheetFormulaShiftOptions,
|
|
3572
|
+
): SheetFormulaShiftResult {
|
|
3573
|
+
const tokens = tokenizeSheetFormulaReferences(text);
|
|
3574
|
+
if (!tokens.length) {
|
|
3575
|
+
return { hasRefError: false, text };
|
|
3576
|
+
}
|
|
3577
|
+
|
|
3578
|
+
let hasRefError = false;
|
|
3579
|
+
let result = '';
|
|
3580
|
+
let cursor = 0;
|
|
3581
|
+
|
|
3582
|
+
tokens.forEach((token) => {
|
|
3583
|
+
const rewrite = getShiftedSheetFormulaReferenceTokenText(
|
|
3584
|
+
token,
|
|
3585
|
+
rowDelta,
|
|
3586
|
+
columnDelta,
|
|
3587
|
+
options,
|
|
3588
|
+
);
|
|
3589
|
+
result += text.slice(cursor, token.startIndex);
|
|
3590
|
+
result += rewrite
|
|
3591
|
+
? rewrite.text
|
|
3592
|
+
: text.slice(token.startIndex, token.endIndex);
|
|
3593
|
+
hasRefError = hasRefError || Boolean(rewrite?.hasRefError);
|
|
3594
|
+
cursor = token.endIndex;
|
|
3595
|
+
});
|
|
3596
|
+
|
|
3597
|
+
result += text.slice(cursor);
|
|
3598
|
+
return { hasRefError, text: result };
|
|
3599
|
+
}
|
|
3600
|
+
|
|
3601
|
+
/*
|
|
3602
|
+
* Shift every sheet cell/range reference in one formula input by a row and
|
|
3603
|
+
* column delta — the relative-addressing rewrite applied when a formula is
|
|
3604
|
+
* pasted or autofilled into a different cell (=A3 copied one row down
|
|
3605
|
+
* becomes =A4). References shifted out of bounds become #REF! and flag
|
|
3606
|
+
* hasRefError. Non-formula inputs are returned unchanged.
|
|
3607
|
+
*/
|
|
3608
|
+
export function shiftSheetFormulaReferences(
|
|
3609
|
+
value: string,
|
|
3610
|
+
rowDelta: number,
|
|
3611
|
+
columnDelta: number,
|
|
3612
|
+
options?: SheetFormulaShiftOptions,
|
|
3613
|
+
): SheetFormulaShiftResult {
|
|
3614
|
+
if (!isSheetFormulaText(value) || (!rowDelta && !columnDelta)) {
|
|
3615
|
+
return { hasRefError: false, text: value };
|
|
3616
|
+
}
|
|
3617
|
+
|
|
3618
|
+
return shiftSheetFormulaReferencesInText(
|
|
3619
|
+
value,
|
|
3620
|
+
rowDelta,
|
|
3621
|
+
columnDelta,
|
|
3622
|
+
options,
|
|
3623
|
+
);
|
|
3624
|
+
}
|
|
3625
|
+
|
|
3626
|
+
export type SheetAutofillCell = {
|
|
3627
|
+
columnIndex: number;
|
|
3628
|
+
rowIndex: number;
|
|
3629
|
+
value: string;
|
|
3630
|
+
};
|
|
3631
|
+
|
|
3632
|
+
/*
|
|
3633
|
+
* Return one autofill source value parsed as a plain numeric literal, or null
|
|
3634
|
+
* when it is not a number.
|
|
3635
|
+
*/
|
|
3636
|
+
function getSheetAutofillNumericValue(value: string) {
|
|
3637
|
+
const trimmed = value.trim();
|
|
3638
|
+
if (!trimmed || !/^[+-]?(\d+\.?\d*|\.\d+)$/.test(trimmed)) {
|
|
3639
|
+
return null;
|
|
3640
|
+
}
|
|
3641
|
+
|
|
3642
|
+
const parsed = Number(trimmed);
|
|
3643
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
3644
|
+
}
|
|
3645
|
+
|
|
3646
|
+
/*
|
|
3647
|
+
* Return the constant step of one all-numeric source run, or null when the
|
|
3648
|
+
* values do not form an arithmetic series.
|
|
3649
|
+
*/
|
|
3650
|
+
function getSheetAutofillArithmeticStep(values: number[]) {
|
|
3651
|
+
if (values.length < 2) {
|
|
3652
|
+
return null;
|
|
3653
|
+
}
|
|
3654
|
+
|
|
3655
|
+
const step = values[1] - values[0];
|
|
3656
|
+
|
|
3657
|
+
for (let index = 2; index < values.length; index += 1) {
|
|
3658
|
+
if (Math.abs(values[index] - values[index - 1] - step) > 1e-9) {
|
|
3659
|
+
return null;
|
|
3660
|
+
}
|
|
3661
|
+
}
|
|
3662
|
+
|
|
3663
|
+
return step;
|
|
3664
|
+
}
|
|
3665
|
+
|
|
3666
|
+
/*
|
|
3667
|
+
* Format one extrapolated numeric autofill value without float drift.
|
|
3668
|
+
*/
|
|
3669
|
+
function formatSheetAutofillNumber(value: number) {
|
|
3670
|
+
return String(parseFloat(value.toPrecision(12)));
|
|
3671
|
+
}
|
|
3672
|
+
|
|
3673
|
+
/*
|
|
3674
|
+
* Return the source-run index one autofill target cell repeats — the cyclic
|
|
3675
|
+
* tiling used by getSheetAutofillValues. Formatting copies must follow the
|
|
3676
|
+
* same mapping so pattern fills carry each source cell's presentation.
|
|
3677
|
+
*/
|
|
3678
|
+
export function getSheetAutofillSourceIndex(params: {
|
|
3679
|
+
backward?: boolean;
|
|
3680
|
+
count: number;
|
|
3681
|
+
index: number;
|
|
3682
|
+
}): number {
|
|
3683
|
+
// Signed position of the target relative to the source block start;
|
|
3684
|
+
// negative offsets wrap to tile the pattern backwards
|
|
3685
|
+
const offset = params.backward
|
|
3686
|
+
? -(params.index + 1)
|
|
3687
|
+
: params.count + params.index;
|
|
3688
|
+
|
|
3689
|
+
return ((offset % params.count) + params.count) % params.count;
|
|
3690
|
+
}
|
|
3691
|
+
|
|
3692
|
+
/*
|
|
3693
|
+
* Return the autofill values for one run of target cells extending one
|
|
3694
|
+
* ordered run of source cells — one column of a vertical fill or one row of
|
|
3695
|
+
* a horizontal fill. Source cells are ordered along the fill axis
|
|
3696
|
+
* (top-to-bottom / left-to-right) and target cells from nearest-to-block
|
|
3697
|
+
* outward; backward marks fills that extend up or left.
|
|
3698
|
+
* - All-numeric source runs with a constant step extend the arithmetic
|
|
3699
|
+
* series (1, 2, 3 fills 4, 5, 6).
|
|
3700
|
+
* - Every other run repeats the source block cyclically, with formula values
|
|
3701
|
+
* shifting their cell references by the distance from their source cell.
|
|
3702
|
+
*/
|
|
3703
|
+
export function getSheetAutofillValues(params: {
|
|
3704
|
+
backward?: boolean;
|
|
3705
|
+
sourceCells: SheetAutofillCell[];
|
|
3706
|
+
targetCells: Array<{ columnIndex: number; rowIndex: number }>;
|
|
3707
|
+
}): string[] {
|
|
3708
|
+
const { backward, sourceCells, targetCells } = params;
|
|
3709
|
+
const count = sourceCells.length;
|
|
3710
|
+
|
|
3711
|
+
if (!count) {
|
|
3712
|
+
return targetCells.map(() => '');
|
|
3713
|
+
}
|
|
3714
|
+
|
|
3715
|
+
const numericValues = sourceCells.map((cell) => {
|
|
3716
|
+
return isSheetFormulaText(cell.value)
|
|
3717
|
+
? null
|
|
3718
|
+
: getSheetAutofillNumericValue(cell.value);
|
|
3719
|
+
});
|
|
3720
|
+
const step = numericValues.every((value) => value !== null)
|
|
3721
|
+
? getSheetAutofillArithmeticStep(numericValues as number[])
|
|
3722
|
+
: null;
|
|
3723
|
+
|
|
3724
|
+
return targetCells.map((target, index) => {
|
|
3725
|
+
if (step !== null) {
|
|
3726
|
+
// Signed position of the target relative to the source block start
|
|
3727
|
+
const offset = backward ? -(index + 1) : count + index;
|
|
3728
|
+
|
|
3729
|
+
return formatSheetAutofillNumber(
|
|
3730
|
+
(numericValues[0] as number) + offset * step,
|
|
3731
|
+
);
|
|
3732
|
+
}
|
|
3733
|
+
|
|
3734
|
+
const source =
|
|
3735
|
+
sourceCells[getSheetAutofillSourceIndex({ backward, count, index })];
|
|
3736
|
+
|
|
3737
|
+
return shiftSheetFormulaReferences(
|
|
3738
|
+
source.value,
|
|
3739
|
+
target.rowIndex - source.rowIndex,
|
|
3740
|
+
target.columnIndex - source.columnIndex,
|
|
3741
|
+
{
|
|
3742
|
+
autofillContext: {
|
|
3743
|
+
sourceColumnIndex: source.columnIndex,
|
|
3744
|
+
sourceRowIndex: source.rowIndex,
|
|
3745
|
+
targetColumnIndex: target.columnIndex,
|
|
3746
|
+
targetRowIndex: target.rowIndex,
|
|
3747
|
+
},
|
|
3748
|
+
},
|
|
3749
|
+
).text;
|
|
3750
|
+
});
|
|
3751
|
+
}
|
|
3752
|
+
|
|
3753
|
+
/*
|
|
3754
|
+
* Return a fresh default sheet design object.
|
|
3755
|
+
*/
|
|
3756
|
+
|
|
3757
|
+
export function getDefaultSheetDesign(): SheetDesignObj {
|
|
3758
|
+
return {
|
|
3759
|
+
version: 1,
|
|
3760
|
+
grid: {
|
|
3761
|
+
rowCount: SHEET_DEFAULT_ROW_COUNT,
|
|
3762
|
+
columnCount: SHEET_DEFAULT_COLUMN_COUNT,
|
|
3763
|
+
frozenRows: 0,
|
|
3764
|
+
frozenColumns: 0,
|
|
3765
|
+
},
|
|
3766
|
+
columns: {},
|
|
3767
|
+
rows: {},
|
|
3768
|
+
defaultCellStyle: {},
|
|
3769
|
+
defaultCellFormat: {},
|
|
3770
|
+
namedRanges: [],
|
|
3771
|
+
metadata: {},
|
|
3772
|
+
};
|
|
3773
|
+
}
|
|
3774
|
+
|
|
3775
|
+
/*
|
|
3776
|
+
* Return the validated merged-cell ranges stored in one sheet design's
|
|
3777
|
+
* metadata. Invalid or single-cell entries are dropped.
|
|
3778
|
+
*/
|
|
3779
|
+
export function getSheetMergedRanges(
|
|
3780
|
+
metadata?: Record<string, any> | null,
|
|
3781
|
+
): SheetMergedRangeObj[] {
|
|
3782
|
+
const merges = Array.isArray(metadata?.merges) ? metadata.merges : [];
|
|
3783
|
+
|
|
3784
|
+
return merges.flatMap((merge: Partial<SheetMergedRangeObj>) => {
|
|
3785
|
+
const startRowIndex = Math.floor(Number(merge?.startRowIndex || 0));
|
|
3786
|
+
const startColumnIndex = Math.floor(Number(merge?.startColumnIndex || 0));
|
|
3787
|
+
const endRowIndex = Math.floor(Number(merge?.endRowIndex || 0));
|
|
3788
|
+
const endColumnIndex = Math.floor(Number(merge?.endColumnIndex || 0));
|
|
3789
|
+
|
|
3790
|
+
if (
|
|
3791
|
+
startRowIndex < 1 ||
|
|
3792
|
+
startColumnIndex < 1 ||
|
|
3793
|
+
endRowIndex < startRowIndex ||
|
|
3794
|
+
endColumnIndex < startColumnIndex ||
|
|
3795
|
+
(endRowIndex === startRowIndex && endColumnIndex === startColumnIndex)
|
|
3796
|
+
) {
|
|
3797
|
+
return [];
|
|
3798
|
+
}
|
|
3799
|
+
|
|
3800
|
+
return [{ startRowIndex, startColumnIndex, endRowIndex, endColumnIndex }];
|
|
3801
|
+
});
|
|
3802
|
+
}
|
|
3803
|
+
|
|
3804
|
+
/*
|
|
3805
|
+
* Return whether one cell coordinate falls inside one merged range.
|
|
3806
|
+
*/
|
|
3807
|
+
export function isSheetCellInMergedRange(
|
|
3808
|
+
merge: SheetMergedRangeObj,
|
|
3809
|
+
rowIndex: number,
|
|
3810
|
+
columnIndex: number,
|
|
3811
|
+
) {
|
|
3812
|
+
return (
|
|
3813
|
+
rowIndex >= merge.startRowIndex &&
|
|
3814
|
+
rowIndex <= merge.endRowIndex &&
|
|
3815
|
+
columnIndex >= merge.startColumnIndex &&
|
|
3816
|
+
columnIndex <= merge.endColumnIndex
|
|
3817
|
+
);
|
|
3818
|
+
}
|
|
3819
|
+
|
|
3820
|
+
/*
|
|
3821
|
+
* Return the merged range containing one cell coordinate, or null.
|
|
3822
|
+
*/
|
|
3823
|
+
export function getSheetMergedRangeAtCell(
|
|
3824
|
+
merges: SheetMergedRangeObj[],
|
|
3825
|
+
rowIndex: number,
|
|
3826
|
+
columnIndex: number,
|
|
3827
|
+
) {
|
|
3828
|
+
return (
|
|
3829
|
+
merges.find((merge) =>
|
|
3830
|
+
isSheetCellInMergedRange(merge, rowIndex, columnIndex),
|
|
3831
|
+
) || null
|
|
3832
|
+
);
|
|
3833
|
+
}
|
|
3834
|
+
|
|
3835
|
+
/*
|
|
3836
|
+
* Return whether one cell is the anchor (top-left) of one merged range.
|
|
3837
|
+
*/
|
|
3838
|
+
export function isSheetMergedRangeAnchor(
|
|
3839
|
+
merge: SheetMergedRangeObj,
|
|
3840
|
+
rowIndex: number,
|
|
3841
|
+
columnIndex: number,
|
|
3842
|
+
) {
|
|
3843
|
+
return (
|
|
3844
|
+
merge.startRowIndex === rowIndex && merge.startColumnIndex === columnIndex
|
|
3845
|
+
);
|
|
3846
|
+
}
|
|
3847
|
+
|
|
3848
|
+
/*
|
|
3849
|
+
* Return whether two merged ranges intersect.
|
|
3850
|
+
*/
|
|
3851
|
+
export function sheetMergedRangesIntersect(
|
|
3852
|
+
a: SheetMergedRangeObj,
|
|
3853
|
+
b: SheetMergedRangeObj,
|
|
3854
|
+
) {
|
|
3855
|
+
return (
|
|
3856
|
+
a.startRowIndex <= b.endRowIndex &&
|
|
3857
|
+
a.endRowIndex >= b.startRowIndex &&
|
|
3858
|
+
a.startColumnIndex <= b.endColumnIndex &&
|
|
3859
|
+
a.endColumnIndex >= b.startColumnIndex
|
|
3860
|
+
);
|
|
3861
|
+
}
|
|
3862
|
+
|
|
3863
|
+
/*
|
|
3864
|
+
* Return merged ranges with one new range added; existing ranges it overlaps
|
|
3865
|
+
* are absorbed (removed), matching the merge-over behavior of spreadsheets.
|
|
3866
|
+
*/
|
|
3867
|
+
export function addSheetMergedRange(
|
|
3868
|
+
merges: SheetMergedRangeObj[],
|
|
3869
|
+
range: SheetMergedRangeObj,
|
|
3870
|
+
) {
|
|
3871
|
+
return [
|
|
3872
|
+
...merges.filter((merge) => !sheetMergedRangesIntersect(merge, range)),
|
|
3873
|
+
range,
|
|
3874
|
+
];
|
|
3875
|
+
}
|
|
3876
|
+
|
|
3877
|
+
/*
|
|
3878
|
+
* Return merged ranges without any range intersecting the given bounds.
|
|
3879
|
+
*/
|
|
3880
|
+
export function removeSheetMergedRangesIntersecting(
|
|
3881
|
+
merges: SheetMergedRangeObj[],
|
|
3882
|
+
bounds: SheetMergedRangeObj,
|
|
3883
|
+
) {
|
|
3884
|
+
return merges.filter((merge) => !sheetMergedRangesIntersect(merge, bounds));
|
|
3885
|
+
}
|
|
3886
|
+
|
|
3887
|
+
/*
|
|
3888
|
+
* Return one axis span shifted by a row/column insert or delete at the target
|
|
3889
|
+
* index, or null when the span collapses entirely.
|
|
3890
|
+
*/
|
|
3891
|
+
function shiftSheetMergedRangeAxis(
|
|
3892
|
+
start: number,
|
|
3893
|
+
end: number,
|
|
3894
|
+
targetIndex: number,
|
|
3895
|
+
delta: 1 | -1,
|
|
3896
|
+
): [number, number] | null {
|
|
3897
|
+
if (delta === 1) {
|
|
3898
|
+
// Insert before targetIndex: spans at/after shift; spans containing the
|
|
3899
|
+
// index grow
|
|
3900
|
+
if (targetIndex <= start) {
|
|
3901
|
+
return [start + 1, end + 1];
|
|
3902
|
+
}
|
|
3903
|
+
if (targetIndex <= end) {
|
|
3904
|
+
return [start, end + 1];
|
|
3905
|
+
}
|
|
3906
|
+
return [start, end];
|
|
3907
|
+
}
|
|
3908
|
+
|
|
3909
|
+
// Delete targetIndex: spans after shift back; spans containing it shrink
|
|
3910
|
+
if (targetIndex < start) {
|
|
3911
|
+
return [start - 1, end - 1];
|
|
3912
|
+
}
|
|
3913
|
+
if (targetIndex <= end) {
|
|
3914
|
+
return start === end ? null : [start, end - 1];
|
|
3915
|
+
}
|
|
3916
|
+
return [start, end];
|
|
3917
|
+
}
|
|
3918
|
+
|
|
3919
|
+
/*
|
|
3920
|
+
* Return merged ranges shifted by one row/column structure edit. Ranges that
|
|
3921
|
+
* collapse to a single cell or lose their span entirely are dropped.
|
|
3922
|
+
*/
|
|
3923
|
+
export function shiftSheetMergedRangesForStructureEdit(
|
|
3924
|
+
merges: SheetMergedRangeObj[],
|
|
3925
|
+
operation: SheetStructureOperationEnum,
|
|
3926
|
+
targetIndex: number,
|
|
3927
|
+
): SheetMergedRangeObj[] {
|
|
3928
|
+
const rowDelta =
|
|
3929
|
+
operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0;
|
|
3930
|
+
const columnDelta =
|
|
3931
|
+
operation === 'INSERT_COLUMN_LEFT'
|
|
3932
|
+
? 1
|
|
3933
|
+
: operation === 'DELETE_COLUMN'
|
|
3934
|
+
? -1
|
|
3935
|
+
: 0;
|
|
3936
|
+
|
|
3937
|
+
if (!rowDelta && !columnDelta) {
|
|
3938
|
+
return merges;
|
|
3939
|
+
}
|
|
3940
|
+
|
|
3941
|
+
return merges.flatMap((merge) => {
|
|
3942
|
+
const rowSpan = rowDelta
|
|
3943
|
+
? shiftSheetMergedRangeAxis(
|
|
3944
|
+
merge.startRowIndex,
|
|
3945
|
+
merge.endRowIndex,
|
|
3946
|
+
targetIndex,
|
|
3947
|
+
rowDelta as 1 | -1,
|
|
3948
|
+
)
|
|
3949
|
+
: ([merge.startRowIndex, merge.endRowIndex] as [number, number]);
|
|
3950
|
+
const columnSpan = columnDelta
|
|
3951
|
+
? shiftSheetMergedRangeAxis(
|
|
3952
|
+
merge.startColumnIndex,
|
|
3953
|
+
merge.endColumnIndex,
|
|
3954
|
+
targetIndex,
|
|
3955
|
+
columnDelta as 1 | -1,
|
|
3956
|
+
)
|
|
3957
|
+
: ([merge.startColumnIndex, merge.endColumnIndex] as [number, number]);
|
|
3958
|
+
|
|
3959
|
+
if (!rowSpan || !columnSpan) {
|
|
3960
|
+
return [];
|
|
3961
|
+
}
|
|
3962
|
+
|
|
3963
|
+
const next = {
|
|
3964
|
+
startRowIndex: rowSpan[0],
|
|
3965
|
+
endRowIndex: rowSpan[1],
|
|
3966
|
+
startColumnIndex: columnSpan[0],
|
|
3967
|
+
endColumnIndex: columnSpan[1],
|
|
3968
|
+
};
|
|
3969
|
+
|
|
3970
|
+
// A merge reduced to one cell is no longer a merge
|
|
3971
|
+
if (
|
|
3972
|
+
next.startRowIndex === next.endRowIndex &&
|
|
3973
|
+
next.startColumnIndex === next.endColumnIndex
|
|
3974
|
+
) {
|
|
3975
|
+
return [];
|
|
3976
|
+
}
|
|
3977
|
+
|
|
3978
|
+
return [next];
|
|
3979
|
+
});
|
|
3980
|
+
}
|
|
3981
|
+
|
|
3982
|
+
/*
|
|
3983
|
+
* Return a sheet design object with all top-level defaults filled in.
|
|
3984
|
+
*/
|
|
3985
|
+
|
|
3986
|
+
export function normalizeSheetDesign(
|
|
3987
|
+
design?: Partial<SheetDesignObj> | null,
|
|
3988
|
+
): SheetDesignObj {
|
|
3989
|
+
const baseDesign = getDefaultSheetDesign();
|
|
3990
|
+
const grid: Partial<SheetDesignObj['grid']> = design?.grid || {};
|
|
3991
|
+
|
|
3992
|
+
return {
|
|
3993
|
+
...baseDesign,
|
|
3994
|
+
...(design || {}),
|
|
3995
|
+
version: Number(design?.version || baseDesign.version),
|
|
3996
|
+
grid: {
|
|
3997
|
+
rowCount: Math.min(
|
|
3998
|
+
SHEET_MAX_ROW_COUNT,
|
|
3999
|
+
Math.max(
|
|
4000
|
+
1,
|
|
4001
|
+
Math.floor(Number(grid.rowCount || baseDesign.grid.rowCount)),
|
|
4002
|
+
),
|
|
4003
|
+
),
|
|
4004
|
+
columnCount: Math.min(
|
|
4005
|
+
SHEET_MAX_COLUMN_COUNT,
|
|
4006
|
+
Math.max(
|
|
4007
|
+
1,
|
|
4008
|
+
Math.floor(Number(grid.columnCount || baseDesign.grid.columnCount)),
|
|
4009
|
+
),
|
|
4010
|
+
),
|
|
4011
|
+
frozenRows: Math.max(0, Math.floor(Number(grid.frozenRows || 0))),
|
|
4012
|
+
frozenColumns: Math.max(0, Math.floor(Number(grid.frozenColumns || 0))),
|
|
4013
|
+
},
|
|
4014
|
+
columns: normalizeSheetAxisDesignMap(design?.columns),
|
|
4015
|
+
rows: normalizeSheetAxisDesignMap(design?.rows),
|
|
4016
|
+
defaultCellStyle: normalizeSheetCellStyle(design?.defaultCellStyle),
|
|
4017
|
+
defaultCellFormat: normalizeSheetCellFormat(design?.defaultCellFormat),
|
|
4018
|
+
namedRanges: Array.isArray(design?.namedRanges) ? design.namedRanges : [],
|
|
4019
|
+
metadata: design?.metadata || {},
|
|
4020
|
+
};
|
|
4021
|
+
}
|
|
4022
|
+
|
|
4023
|
+
/*
|
|
4024
|
+
* Return a viewport bounded to positive indexes and backend query limits.
|
|
4025
|
+
*/
|
|
4026
|
+
|
|
4027
|
+
export function normalizeSheetViewport(
|
|
4028
|
+
viewport: Partial<SheetGridViewportObj>,
|
|
4029
|
+
): SheetGridViewportObj {
|
|
4030
|
+
return {
|
|
4031
|
+
startRowIndex: Math.max(1, Math.floor(Number(viewport.startRowIndex || 1))),
|
|
4032
|
+
startColumnIndex: Math.max(
|
|
4033
|
+
1,
|
|
4034
|
+
Math.floor(Number(viewport.startColumnIndex || 1)),
|
|
4035
|
+
),
|
|
4036
|
+
rowCount: Math.min(
|
|
4037
|
+
SHEET_VIEWPORT_MAX_ROWS,
|
|
4038
|
+
Math.max(1, Math.floor(Number(viewport.rowCount || 1))),
|
|
4039
|
+
),
|
|
4040
|
+
columnCount: Math.min(
|
|
4041
|
+
SHEET_VIEWPORT_MAX_COLUMNS,
|
|
4042
|
+
Math.max(1, Math.floor(Number(viewport.columnCount || 1))),
|
|
4043
|
+
),
|
|
4044
|
+
};
|
|
4045
|
+
}
|
|
4046
|
+
|
|
4047
|
+
/*
|
|
4048
|
+
* Return the whole-grid sheetView viewport for one normalized sheet design.
|
|
4049
|
+
* Every caller must build sheetView query variables through this function so
|
|
4050
|
+
* the query cache key stays identical between mounted hooks and prefetches.
|
|
4051
|
+
*/
|
|
4052
|
+
|
|
4053
|
+
export function getSheetViewFullViewport(
|
|
4054
|
+
design: SheetDesignObj,
|
|
4055
|
+
): SheetGridViewportObj {
|
|
4056
|
+
return {
|
|
4057
|
+
startRowIndex: 1,
|
|
4058
|
+
startColumnIndex: 1,
|
|
4059
|
+
rowCount: Math.min(
|
|
4060
|
+
SHEET_MAX_ROW_COUNT,
|
|
4061
|
+
Math.max(1, design.grid.rowCount || 1),
|
|
4062
|
+
),
|
|
4063
|
+
columnCount: Math.min(
|
|
4064
|
+
SHEET_MAX_COLUMN_COUNT,
|
|
4065
|
+
Math.max(1, design.grid.columnCount || 1),
|
|
4066
|
+
),
|
|
4067
|
+
};
|
|
4068
|
+
}
|
|
4069
|
+
|
|
4070
|
+
/*
|
|
4071
|
+
* Return whether one value is a known stored sheet cell source type.
|
|
4072
|
+
*/
|
|
4073
|
+
|
|
4074
|
+
export function isSheetCellSourceType(
|
|
4075
|
+
value: unknown,
|
|
4076
|
+
): value is SheetCellSourceTypeEnum {
|
|
4077
|
+
return SHEET_CELL_SOURCE_TYPE_ENUMS.includes(
|
|
4078
|
+
value as SheetCellSourceTypeEnum,
|
|
4079
|
+
);
|
|
4080
|
+
}
|
|
4081
|
+
|
|
4082
|
+
/*
|
|
4083
|
+
* Return whether one value is a known sheet region type.
|
|
4084
|
+
*/
|
|
4085
|
+
|
|
4086
|
+
export function isSheetRegionType(
|
|
4087
|
+
value: unknown,
|
|
4088
|
+
): value is SheetRegionTypeEnum {
|
|
4089
|
+
return SHEET_REGION_TYPE_ENUMS.includes(value as SheetRegionTypeEnum);
|
|
4090
|
+
}
|
|
4091
|
+
|
|
4092
|
+
/*
|
|
4093
|
+
* Return whether one value is a known sheet region source type.
|
|
4094
|
+
*/
|
|
4095
|
+
|
|
4096
|
+
export function isSheetRegionSourceType(
|
|
4097
|
+
value: unknown,
|
|
4098
|
+
): value is SheetRegionSourceTypeEnum {
|
|
4099
|
+
return SHEET_REGION_SOURCE_TYPE_ENUMS.includes(
|
|
4100
|
+
value as SheetRegionSourceTypeEnum,
|
|
4101
|
+
);
|
|
4102
|
+
}
|
|
4103
|
+
|
|
4104
|
+
/*
|
|
4105
|
+
* Return whether one value is a known sheet region conflict policy.
|
|
4106
|
+
*/
|
|
4107
|
+
|
|
4108
|
+
export function isSheetRegionConflictPolicy(
|
|
4109
|
+
value: unknown,
|
|
4110
|
+
): value is SheetRegionConflictPolicyEnum {
|
|
4111
|
+
return SHEET_REGION_CONFLICT_POLICY_ENUMS.includes(
|
|
4112
|
+
value as SheetRegionConflictPolicyEnum,
|
|
4113
|
+
);
|
|
4114
|
+
}
|
|
4115
|
+
|
|
4116
|
+
/*
|
|
4117
|
+
* Return the current organization's label for the Child Organizations Sheet source.
|
|
4118
|
+
* INTENTIONALLY code-side and operation-parameterized: the region source
|
|
4119
|
+
* registry's titleKey only covers the default table title; this per-operation
|
|
4120
|
+
* label resolution must NOT move into registry rows (locked decision — no
|
|
4121
|
+
* visible label changes).
|
|
4122
|
+
*/
|
|
4123
|
+
export function getSheetChildOrganizationsRegionSourceLabel(
|
|
4124
|
+
operation?: OrganizationOperationEnum | string | null,
|
|
4125
|
+
) {
|
|
4126
|
+
return operation && i18n.has(`org.children.${operation}`)
|
|
4127
|
+
? i18n.t(`org.children.${operation}`)
|
|
4128
|
+
: i18n.t('org.children.default');
|
|
4129
|
+
}
|
|
4130
|
+
|
|
4131
|
+
/*
|
|
4132
|
+
* Return the current organization's table title for the Child Organizations Sheet source.
|
|
4133
|
+
*/
|
|
4134
|
+
export function getSheetChildOrganizationsRegionSourceListLabel(
|
|
4135
|
+
operation?: OrganizationOperationEnum | string | null,
|
|
4136
|
+
) {
|
|
4137
|
+
return operation && i18n.has(`org.children_list.${operation}`)
|
|
4138
|
+
? i18n.t(`org.children_list.${operation}`)
|
|
4139
|
+
: i18n.t('org.children_list.default');
|
|
4140
|
+
}
|
|
4141
|
+
|
|
4142
|
+
/*
|
|
4143
|
+
* Return the label used for the Logs Sheet source.
|
|
4144
|
+
* INTENTIONALLY kind-specific: a LOGS-only client behavior that new registry
|
|
4145
|
+
* kinds do not inherit (they fall back to their registry titleKey).
|
|
4146
|
+
*/
|
|
4147
|
+
export function getSheetLogsRegionSourceLabel() {
|
|
4148
|
+
return i18n.t('log.logs');
|
|
4149
|
+
}
|
|
4150
|
+
|
|
4151
|
+
/*
|
|
4152
|
+
* Return a DataTable design cell for one custom region source column.
|
|
4153
|
+
*/
|
|
4154
|
+
function buildSheetCustomRegionSourceDesignCell(
|
|
4155
|
+
column: SheetCustomRegionSourceColumnObj,
|
|
4156
|
+
sourceType: SheetRegionSourceTypeEnum | string | null | undefined,
|
|
4157
|
+
): DataTableDesignCellGQL {
|
|
4158
|
+
const sourceColumn = column as SheetCustomRegionSourceColumnObj & {
|
|
4159
|
+
fieldType?: DataTableFieldTypeGQL | null;
|
|
4160
|
+
relatedTable?: string | null;
|
|
4161
|
+
};
|
|
4162
|
+
const linksToOrganizationProfile =
|
|
4163
|
+
sourceType === SHEET_CUSTOM_REGION_SOURCE_CHILD_ORGANIZATIONS &&
|
|
4164
|
+
!sourceColumn.fieldType &&
|
|
4165
|
+
isOrganizationChildProfileLinkCellKey(column.key);
|
|
4166
|
+
const fieldType: DataTableFieldTypeGQL =
|
|
4167
|
+
sourceColumn.fieldType ||
|
|
4168
|
+
(column.key === 'organizationId'
|
|
4169
|
+
? 'ID'
|
|
4170
|
+
: linksToOrganizationProfile
|
|
4171
|
+
? 'ID_OR_TEXT'
|
|
4172
|
+
: 'TEXT');
|
|
4173
|
+
return {
|
|
4174
|
+
key: column.key,
|
|
4175
|
+
label: i18n.t(column.labelKey),
|
|
4176
|
+
humanLabel: i18n.t(column.labelKey),
|
|
4177
|
+
iconName: null,
|
|
4178
|
+
fieldType,
|
|
4179
|
+
format: null,
|
|
4180
|
+
instructions: null,
|
|
4181
|
+
source: sourceColumn.relatedTable
|
|
4182
|
+
? {
|
|
4183
|
+
path: 'id',
|
|
4184
|
+
table: sourceColumn.relatedTable,
|
|
4185
|
+
}
|
|
4186
|
+
: null,
|
|
4187
|
+
options: [],
|
|
4188
|
+
openLink: !!sourceColumn.relatedTable || linksToOrganizationProfile,
|
|
4189
|
+
humansOnly: false,
|
|
4190
|
+
humansCannotEdit: true,
|
|
4191
|
+
hidden: false,
|
|
4192
|
+
indexed: false,
|
|
4193
|
+
width: column.width,
|
|
4194
|
+
};
|
|
4195
|
+
}
|
|
4196
|
+
|
|
4197
|
+
/*
|
|
4198
|
+
* Return DataTable-shaped design cells for one custom Sheet region source.
|
|
4199
|
+
*/
|
|
4200
|
+
export function getSheetCustomRegionSourceDesignCells(
|
|
4201
|
+
sourceType: SheetRegionSourceTypeEnum | string | null | undefined,
|
|
4202
|
+
) {
|
|
4203
|
+
return getSheetCustomRegionSourceColumns(sourceType).map((column) =>
|
|
4204
|
+
buildSheetCustomRegionSourceDesignCell(column, sourceType),
|
|
4205
|
+
);
|
|
4206
|
+
}
|
|
4207
|
+
|
|
4208
|
+
/*
|
|
4209
|
+
* Return the default DataTable title for one custom Sheet region source.
|
|
4210
|
+
*/
|
|
4211
|
+
function getSheetCustomRegionSourceDataTableTitle(
|
|
4212
|
+
sourceType: SheetRegionSourceTypeEnum | string | null | undefined,
|
|
4213
|
+
) {
|
|
4214
|
+
// Registry titleKey is the kind's default title ('form.vendors',
|
|
4215
|
+
// 'log.logs', ...); operation-dependent label RESOLUTION stays code-side
|
|
4216
|
+
// (getSheetChildOrganizationsRegionSourceLabel) by design
|
|
4217
|
+
const kind = SHEET_REGION_SOURCE_DESCRIPTORS[String(sourceType || '')];
|
|
4218
|
+
|
|
4219
|
+
return kind ? i18n.t(kind.titleKey) : '';
|
|
4220
|
+
}
|
|
4221
|
+
|
|
4222
|
+
/*
|
|
4223
|
+
* Return a DataTable-shaped object for one built-in custom Sheet region source.
|
|
4224
|
+
*/
|
|
4225
|
+
export function getSheetCustomRegionSourceDataTable(params: {
|
|
4226
|
+
organizationId: string;
|
|
4227
|
+
sourceType: SheetRegionSourceTypeEnum | string | null | undefined;
|
|
4228
|
+
title?: string | null;
|
|
4229
|
+
}): DataTableGQL | null {
|
|
4230
|
+
if (!isSheetCustomRegionSourceType(params.sourceType)) {
|
|
4231
|
+
return null;
|
|
4232
|
+
}
|
|
4233
|
+
|
|
4234
|
+
const sourceType = String(params.sourceType);
|
|
4235
|
+
const columns = getSheetCustomRegionSourceDesignCells(sourceType);
|
|
4236
|
+
|
|
4237
|
+
return {
|
|
4238
|
+
id: sourceType,
|
|
4239
|
+
organizationId: params.organizationId,
|
|
4240
|
+
name: sourceType,
|
|
4241
|
+
title: params.title || getSheetCustomRegionSourceDataTableTitle(sourceType),
|
|
4242
|
+
description: null,
|
|
4243
|
+
design: {
|
|
4244
|
+
id: sourceType,
|
|
4245
|
+
cells: columns,
|
|
4246
|
+
cellsOrder: columns.map((column) => column.key),
|
|
4247
|
+
humansCannotEdit: true,
|
|
4248
|
+
instructions: null,
|
|
4249
|
+
stickyLeft: 0,
|
|
4250
|
+
stickyTop: 0,
|
|
4251
|
+
},
|
|
4252
|
+
active: true,
|
|
4253
|
+
deletedAt: null,
|
|
4254
|
+
createdAt: '',
|
|
4255
|
+
updatedAt: '',
|
|
4256
|
+
};
|
|
4257
|
+
}
|
|
4258
|
+
|
|
4259
|
+
/*
|
|
4260
|
+
* Return reusable column definitions for a custom Sheet region source.
|
|
4261
|
+
*/
|
|
4262
|
+
|
|
4263
|
+
export function getSheetCustomRegionSourceColumns(
|
|
4264
|
+
sourceType: SheetRegionSourceTypeEnum | string | null | undefined,
|
|
4265
|
+
): SheetCustomRegionSourceColumnObj[] {
|
|
4266
|
+
// Registry-iterated: any kind's fields map onto the legacy column shape
|
|
4267
|
+
// (optional keys emitted only when set, matching the historical literals)
|
|
4268
|
+
const kind = SHEET_REGION_SOURCE_DESCRIPTORS[String(sourceType || '')];
|
|
4269
|
+
|
|
4270
|
+
return (kind?.fields || []).map((field) => ({
|
|
4271
|
+
key: field.key,
|
|
4272
|
+
labelKey: field.labelKey,
|
|
4273
|
+
...(field.fieldType ? { fieldType: field.fieldType } : {}),
|
|
4274
|
+
...(field.formulaValueSource
|
|
4275
|
+
? {
|
|
4276
|
+
formulaValueSource:
|
|
4277
|
+
field.formulaValueSource as SheetCustomRegionSourceColumnObj['formulaValueSource'],
|
|
4278
|
+
}
|
|
4279
|
+
: {}),
|
|
4280
|
+
...(field.relatedTable ? { relatedTable: field.relatedTable } : {}),
|
|
4281
|
+
width: field.width,
|
|
4282
|
+
}));
|
|
4283
|
+
}
|
|
4284
|
+
|
|
4285
|
+
/*
|
|
4286
|
+
* Return whether one Sheet region source type is backed by custom app data.
|
|
4287
|
+
*/
|
|
4288
|
+
|
|
4289
|
+
export function isSheetCustomRegionSourceType(sourceType: unknown) {
|
|
4290
|
+
// Registry membership (including disabled kinds: regions that already
|
|
4291
|
+
// exist must keep rendering regardless of the staged-launch flag)
|
|
4292
|
+
return (
|
|
4293
|
+
typeof sourceType === 'string' &&
|
|
4294
|
+
Boolean(SHEET_REGION_SOURCE_DESCRIPTORS[sourceType])
|
|
4295
|
+
);
|
|
4296
|
+
}
|
|
4297
|
+
|
|
4298
|
+
/*
|
|
4299
|
+
* Return whether one Sheet region row is backed by the LOGS custom source.
|
|
4300
|
+
* INTENTIONALLY kind-specific (not registry-iterated): callers gate LOGS-only
|
|
4301
|
+
* client behaviors that other registry kinds must not silently inherit.
|
|
4302
|
+
*/
|
|
4303
|
+
|
|
4304
|
+
export function isLogsSourceSheetRegion(
|
|
4305
|
+
region: { source?: { type?: string | null } | null } | null | undefined,
|
|
4306
|
+
) {
|
|
4307
|
+
return region?.source?.type === SHEET_CUSTOM_REGION_SOURCE_LOGS;
|
|
4308
|
+
}
|
|
4309
|
+
|
|
4310
|
+
/*
|
|
4311
|
+
* Return the serialized child organization id carried by one custom Child
|
|
4312
|
+
* Organizations source cell, or null for cells from other sources. Custom
|
|
4313
|
+
* Child Organizations source rows are keyed by the child organization id.
|
|
4314
|
+
*/
|
|
4315
|
+
|
|
4316
|
+
export function getSheetChildOrganizationSourceOrgId(
|
|
4317
|
+
cell?: { dataTableId?: string | null; dataTableRowId?: string | null } | null,
|
|
4318
|
+
) {
|
|
4319
|
+
if (
|
|
4320
|
+
!cell ||
|
|
4321
|
+
String(cell.dataTableId || '') !==
|
|
4322
|
+
SHEET_CUSTOM_REGION_SOURCE_CHILD_ORGANIZATIONS
|
|
4323
|
+
) {
|
|
4324
|
+
return null;
|
|
4325
|
+
}
|
|
4326
|
+
|
|
4327
|
+
return String(cell.dataTableRowId || '') || null;
|
|
4328
|
+
}
|
|
4329
|
+
|
|
4330
|
+
/*
|
|
4331
|
+
* Return the concrete source type for a generated Sheet region or rendered region result.
|
|
4332
|
+
*/
|
|
4333
|
+
export function getSheetRegionSourceType(
|
|
4334
|
+
sourceLocator?: SheetRegionSourceLocator | null,
|
|
4335
|
+
): SheetRegionSourceTypeEnum {
|
|
4336
|
+
const sourceType =
|
|
4337
|
+
sourceLocator?.source?.type ||
|
|
4338
|
+
sourceLocator?.sourceType ||
|
|
4339
|
+
sourceLocator?.type ||
|
|
4340
|
+
(sourceLocator?.sourceDataTableId ||
|
|
4341
|
+
sourceLocator?.dataTableId ||
|
|
4342
|
+
sourceLocator?.source?.dataTableId
|
|
4343
|
+
? 'DATA_TABLE'
|
|
4344
|
+
: null);
|
|
4345
|
+
|
|
4346
|
+
return isSheetRegionSourceType(sourceType) ? sourceType : 'DATA_TABLE';
|
|
4347
|
+
}
|
|
4348
|
+
|
|
4349
|
+
/*
|
|
4350
|
+
* Return the stable source id used to key source cells for a generated Sheet region.
|
|
4351
|
+
*/
|
|
4352
|
+
export function getSheetRegionSourceId(
|
|
4353
|
+
sourceLocator?: SheetRegionSourceLocator | null,
|
|
4354
|
+
): string {
|
|
4355
|
+
return String(
|
|
4356
|
+
sourceLocator?.sourceDataTableId ||
|
|
4357
|
+
sourceLocator?.dataTableId ||
|
|
4358
|
+
sourceLocator?.source?.dataTableId ||
|
|
4359
|
+
sourceLocator?.sourceId ||
|
|
4360
|
+
sourceLocator?.source?.type ||
|
|
4361
|
+
sourceLocator?.sourceType ||
|
|
4362
|
+
sourceLocator?.type ||
|
|
4363
|
+
'',
|
|
4364
|
+
);
|
|
4365
|
+
}
|
|
4366
|
+
|
|
4367
|
+
/*
|
|
4368
|
+
* Return the app route where one Sheet generated-region source can be opened.
|
|
4369
|
+
*/
|
|
4370
|
+
export function getSheetRegionSourceDataTableRoute(
|
|
4371
|
+
sourceLocator?: SheetRegionSourceLocator | null,
|
|
4372
|
+
): string | null {
|
|
4373
|
+
const sourceType = getSheetRegionSourceType(sourceLocator);
|
|
4374
|
+
|
|
4375
|
+
// Registry appRoute ('/app/vendors', '/app/logs', ...) — null when a kind
|
|
4376
|
+
// has no dedicated app surface
|
|
4377
|
+
const kind = SHEET_REGION_SOURCE_DESCRIPTORS[sourceType];
|
|
4378
|
+
if (kind) {
|
|
4379
|
+
return kind.appRoute;
|
|
4380
|
+
}
|
|
4381
|
+
|
|
4382
|
+
const dataTableId = String(
|
|
4383
|
+
sourceLocator?.sourceDataTableId ||
|
|
4384
|
+
sourceLocator?.dataTableId ||
|
|
4385
|
+
sourceLocator?.source?.dataTableId ||
|
|
4386
|
+
'',
|
|
4387
|
+
);
|
|
4388
|
+
|
|
4389
|
+
return dataTableId ? `/app/d/${dataTableId}` : null;
|
|
4390
|
+
}
|
|
4391
|
+
|
|
4392
|
+
/*
|
|
4393
|
+
* Return whether a Sheet region source can generate rows into the grid.
|
|
4394
|
+
*/
|
|
4395
|
+
export function isSheetGeneratedRegionSource(
|
|
4396
|
+
sourceLocator?: SheetRegionSourceLocator | null,
|
|
4397
|
+
) {
|
|
4398
|
+
return Boolean(
|
|
4399
|
+
sourceLocator?.sourceDataTableId ||
|
|
4400
|
+
sourceLocator?.dataTableId ||
|
|
4401
|
+
sourceLocator?.source?.dataTableId ||
|
|
4402
|
+
isSheetCustomRegionSourceType(getSheetRegionSourceType(sourceLocator)),
|
|
4403
|
+
);
|
|
4404
|
+
}
|
|
4405
|
+
|
|
4406
|
+
/*
|
|
4407
|
+
* Return whether one value is a known sheet structure edit operation.
|
|
4408
|
+
*/
|
|
4409
|
+
|
|
4410
|
+
export function isSheetStructureOperation(
|
|
4411
|
+
value: unknown,
|
|
4412
|
+
): value is SheetStructureOperationEnum {
|
|
4413
|
+
return SHEET_STRUCTURE_OPERATION_ENUMS.includes(
|
|
4414
|
+
value as SheetStructureOperationEnum,
|
|
4415
|
+
);
|
|
4416
|
+
}
|
|
4417
|
+
|
|
4418
|
+
/*
|
|
4419
|
+
* Return a shallow merged JSON object, ignoring non-object values.
|
|
4420
|
+
*/
|
|
4421
|
+
|
|
4422
|
+
export function mergeSheetJSONObjects(
|
|
4423
|
+
...values: Array<Record<string, any> | null | undefined>
|
|
4424
|
+
) {
|
|
4425
|
+
return values.reduce<Record<string, any>>((merged, value) => {
|
|
4426
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
4427
|
+
return merged;
|
|
4428
|
+
}
|
|
4429
|
+
|
|
4430
|
+
return {
|
|
4431
|
+
...merged,
|
|
4432
|
+
...value,
|
|
4433
|
+
};
|
|
4434
|
+
}, {});
|
|
4435
|
+
}
|
|
4436
|
+
|
|
4437
|
+
/*
|
|
4438
|
+
* Return the string key used by sheet design JSON for one column index.
|
|
4439
|
+
*/
|
|
4440
|
+
|
|
4441
|
+
export function getSheetColumnDesignKey(columnIndex: number) {
|
|
4442
|
+
return String(Math.max(1, Math.floor(Number(columnIndex) || 1)));
|
|
4443
|
+
}
|
|
4444
|
+
|
|
4445
|
+
/*
|
|
4446
|
+
* Return the string key used by sheet design JSON for one row index.
|
|
4447
|
+
*/
|
|
4448
|
+
|
|
4449
|
+
export function getSheetRowDesignKey(rowIndex: number) {
|
|
4450
|
+
return String(Math.max(1, Math.floor(Number(rowIndex) || 1)));
|
|
4451
|
+
}
|
|
4452
|
+
|
|
4453
|
+
/*
|
|
4454
|
+
* Return whether one axis index falls inside a protected region span.
|
|
4455
|
+
*/
|
|
4456
|
+
|
|
4457
|
+
function isSheetAxisIndexInProtectedSpan(
|
|
4458
|
+
index: number,
|
|
4459
|
+
spans: SheetProtectedAxisSpan[],
|
|
4460
|
+
) {
|
|
4461
|
+
return spans.some(
|
|
4462
|
+
(span) => index >= span.startIndex && index <= span.endIndex,
|
|
4463
|
+
);
|
|
4464
|
+
}
|
|
4465
|
+
|
|
4466
|
+
/*
|
|
4467
|
+
* Return whether a protected region span blocks shifting an axis index backward.
|
|
4468
|
+
*/
|
|
4469
|
+
|
|
4470
|
+
function doesSheetProtectedSpanBlockBackwardShift(
|
|
4471
|
+
targetIndex: number,
|
|
4472
|
+
sourceIndex: number,
|
|
4473
|
+
spans: SheetProtectedAxisSpan[],
|
|
4474
|
+
) {
|
|
4475
|
+
return spans.some(
|
|
4476
|
+
(span) =>
|
|
4477
|
+
span.endIndex >= targetIndex && span.startIndex <= sourceIndex - 1,
|
|
4478
|
+
);
|
|
4479
|
+
}
|
|
4480
|
+
|
|
4481
|
+
/*
|
|
4482
|
+
* Return the new axis design index for one structure edit.
|
|
4483
|
+
*/
|
|
4484
|
+
|
|
4485
|
+
function getSheetShiftedAxisDesignIndex(
|
|
4486
|
+
index: number,
|
|
4487
|
+
operation: SheetStructureOperationEnum,
|
|
4488
|
+
targetIndex: number,
|
|
4489
|
+
protectedSpans: SheetProtectedAxisSpan[],
|
|
4490
|
+
) {
|
|
4491
|
+
if (isSheetAxisIndexInProtectedSpan(index, protectedSpans)) {
|
|
4492
|
+
return index;
|
|
4493
|
+
}
|
|
4494
|
+
|
|
4495
|
+
if (operation === 'INSERT_ROW_ABOVE' || operation === 'INSERT_COLUMN_LEFT') {
|
|
4496
|
+
const nextIndex = index >= targetIndex ? index + 1 : index;
|
|
4497
|
+
return isSheetAxisIndexInProtectedSpan(nextIndex, protectedSpans)
|
|
4498
|
+
? index
|
|
4499
|
+
: nextIndex;
|
|
4500
|
+
}
|
|
4501
|
+
|
|
4502
|
+
if (index === targetIndex) {
|
|
4503
|
+
return null;
|
|
4504
|
+
}
|
|
4505
|
+
|
|
4506
|
+
if (index > targetIndex) {
|
|
4507
|
+
const nextIndex = index - 1;
|
|
4508
|
+
return isSheetAxisIndexInProtectedSpan(nextIndex, protectedSpans) ||
|
|
4509
|
+
doesSheetProtectedSpanBlockBackwardShift(
|
|
4510
|
+
targetIndex,
|
|
4511
|
+
index,
|
|
4512
|
+
protectedSpans,
|
|
4513
|
+
)
|
|
4514
|
+
? index
|
|
4515
|
+
: nextIndex;
|
|
4516
|
+
}
|
|
4517
|
+
|
|
4518
|
+
return index;
|
|
4519
|
+
}
|
|
4520
|
+
|
|
4521
|
+
/*
|
|
4522
|
+
* Shift saved row or column design entries for one sheet structure edit.
|
|
4523
|
+
*/
|
|
4524
|
+
|
|
4525
|
+
export function shiftSheetAxisDesignForStructureEdit(
|
|
4526
|
+
axisDesign: Record<string, SheetAxisDesignObj> | null | undefined,
|
|
4527
|
+
operation: SheetStructureOperationEnum,
|
|
4528
|
+
targetIndex: number,
|
|
4529
|
+
protectedSpans: SheetProtectedAxisSpan[] = [],
|
|
4530
|
+
) {
|
|
4531
|
+
const nextDesign: Record<string, SheetAxisDesignObj> = {};
|
|
4532
|
+
const normalizedTargetIndex = Math.max(
|
|
4533
|
+
1,
|
|
4534
|
+
Math.floor(Number(targetIndex) || 1),
|
|
4535
|
+
);
|
|
4536
|
+
|
|
4537
|
+
Object.entries(axisDesign || {}).forEach(([key, design]) => {
|
|
4538
|
+
const index = Math.floor(Number(key || 0));
|
|
4539
|
+
if (!Number.isFinite(index) || index < 1) {
|
|
4540
|
+
nextDesign[key] = design;
|
|
4541
|
+
return;
|
|
4542
|
+
}
|
|
4543
|
+
|
|
4544
|
+
const nextIndex = getSheetShiftedAxisDesignIndex(
|
|
4545
|
+
index,
|
|
4546
|
+
operation,
|
|
4547
|
+
normalizedTargetIndex,
|
|
4548
|
+
protectedSpans,
|
|
4549
|
+
);
|
|
4550
|
+
if (!nextIndex) {
|
|
4551
|
+
return;
|
|
4552
|
+
}
|
|
4553
|
+
|
|
4554
|
+
nextDesign[String(nextIndex)] = design;
|
|
4555
|
+
});
|
|
4556
|
+
|
|
4557
|
+
return nextDesign;
|
|
4558
|
+
}
|
|
4559
|
+
|
|
4560
|
+
/*
|
|
4561
|
+
* Return whether one row design object represents meaningful row-level content.
|
|
4562
|
+
*/
|
|
4563
|
+
|
|
4564
|
+
export function sheetAxisDesignHasContent(design?: SheetAxisDesignObj | null) {
|
|
4565
|
+
if (!design) {
|
|
4566
|
+
return false;
|
|
4567
|
+
}
|
|
4568
|
+
|
|
4569
|
+
return Object.values(design).some((value) => {
|
|
4570
|
+
if (value === null || value === undefined || value === false) {
|
|
4571
|
+
return false;
|
|
4572
|
+
}
|
|
4573
|
+
|
|
4574
|
+
if (typeof value === 'object') {
|
|
4575
|
+
return Object.keys(value).length > 0;
|
|
4576
|
+
}
|
|
4577
|
+
|
|
4578
|
+
return true;
|
|
4579
|
+
});
|
|
4580
|
+
}
|
|
4581
|
+
|
|
4582
|
+
/*
|
|
4583
|
+
* Return the detected value type of one raw cell text: whole numbers are
|
|
4584
|
+
* CELL_INT, decimal numbers CELL_FLOAT, ISO calendar dates CELL_DATE, and
|
|
4585
|
+
* everything else CELL_TEXT.
|
|
4586
|
+
*/
|
|
4587
|
+
export function getSheetTextValueType(
|
|
4588
|
+
value?: string | null,
|
|
4589
|
+
): SheetCellValueTypeEnum {
|
|
4590
|
+
const trimmedValue = String(value ?? '').trim();
|
|
4591
|
+
|
|
4592
|
+
if (!trimmedValue) {
|
|
4593
|
+
return 'CELL_TEXT';
|
|
4594
|
+
}
|
|
4595
|
+
|
|
4596
|
+
if (/^-?\d+$/.test(trimmedValue)) {
|
|
4597
|
+
return 'CELL_INT';
|
|
4598
|
+
}
|
|
4599
|
+
|
|
4600
|
+
if (/^-?(\d+\.\d+|\.\d+|\d+\.)$/.test(trimmedValue)) {
|
|
4601
|
+
return 'CELL_FLOAT';
|
|
4602
|
+
}
|
|
4603
|
+
|
|
4604
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmedValue)) {
|
|
4605
|
+
// A date-shaped string still has to be a real calendar date
|
|
4606
|
+
const [year, month, day] = trimmedValue.split('-').map(Number);
|
|
4607
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
4608
|
+
|
|
4609
|
+
if (
|
|
4610
|
+
date.getUTCFullYear() === year &&
|
|
4611
|
+
date.getUTCMonth() === month - 1 &&
|
|
4612
|
+
date.getUTCDate() === day
|
|
4613
|
+
) {
|
|
4614
|
+
return 'CELL_DATE';
|
|
4615
|
+
}
|
|
4616
|
+
}
|
|
4617
|
+
|
|
4618
|
+
const upperValue = trimmedValue.toUpperCase();
|
|
4619
|
+
|
|
4620
|
+
if (upperValue === 'TRUE' || upperValue === 'FALSE') {
|
|
4621
|
+
return 'CELL_BOOLEAN';
|
|
4622
|
+
}
|
|
4623
|
+
|
|
4624
|
+
return 'CELL_TEXT';
|
|
4625
|
+
}
|
|
4626
|
+
|
|
4627
|
+
/*
|
|
4628
|
+
* Return the cell value type one DataTable column field type projects into a
|
|
4629
|
+
* Sheet region cell, or null when the field type is unknown. Numeric columns
|
|
4630
|
+
* report CELL_FLOAT; callers can refine to CELL_INT from the stored value.
|
|
4631
|
+
*/
|
|
4632
|
+
export function getSheetCellValueTypeForDataTableFieldType(
|
|
4633
|
+
fieldType?: string | null,
|
|
4634
|
+
): SheetCellValueTypeEnum | null {
|
|
4635
|
+
switch (fieldType) {
|
|
4636
|
+
case 'NUMBER':
|
|
4637
|
+
case 'PRICE':
|
|
4638
|
+
return 'CELL_FLOAT';
|
|
4639
|
+
case 'BOOLEAN':
|
|
4640
|
+
return 'CELL_BOOLEAN';
|
|
4641
|
+
case 'DATE':
|
|
4642
|
+
case 'DATETIME':
|
|
4643
|
+
case 'WEEK_OF_MON':
|
|
4644
|
+
case 'WEEK_OF_SUN':
|
|
4645
|
+
return 'CELL_DATE';
|
|
4646
|
+
case undefined:
|
|
4647
|
+
case null:
|
|
4648
|
+
return null;
|
|
4649
|
+
default:
|
|
4650
|
+
return 'CELL_TEXT';
|
|
4651
|
+
}
|
|
4652
|
+
}
|
|
4653
|
+
|
|
4654
|
+
/*
|
|
4655
|
+
* Return the detected value type of one Sheet cell. The server's stored typed
|
|
4656
|
+
* columns win when present; pending or optimistic cells (no typed columns yet)
|
|
4657
|
+
* fall back to classifying the display text client-side.
|
|
4658
|
+
*/
|
|
4659
|
+
export function getSheetCellValueType(
|
|
4660
|
+
cell?: Pick<
|
|
4661
|
+
SheetCellGQL,
|
|
4662
|
+
'booleanValue' | 'dateValue' | 'datetimeValue' | 'numberValue'
|
|
4663
|
+
> | null,
|
|
4664
|
+
displayValue?: string | null,
|
|
4665
|
+
): SheetCellValueTypeEnum {
|
|
4666
|
+
if (cell) {
|
|
4667
|
+
if (cell.numberValue !== null && cell.numberValue !== undefined) {
|
|
4668
|
+
return Number.isInteger(Number(cell.numberValue))
|
|
4669
|
+
? 'CELL_INT'
|
|
4670
|
+
: 'CELL_FLOAT';
|
|
4671
|
+
}
|
|
4672
|
+
|
|
4673
|
+
if (cell.dateValue || cell.datetimeValue) {
|
|
4674
|
+
return 'CELL_DATE';
|
|
4675
|
+
}
|
|
4676
|
+
|
|
4677
|
+
if (cell.booleanValue !== null && cell.booleanValue !== undefined) {
|
|
4678
|
+
return 'CELL_BOOLEAN';
|
|
4679
|
+
}
|
|
4680
|
+
}
|
|
4681
|
+
|
|
4682
|
+
return getSheetTextValueType(displayValue);
|
|
4683
|
+
}
|
|
4684
|
+
|
|
4685
|
+
/*
|
|
4686
|
+
* Return one axis design map (columns or rows) with style deltas merged into a
|
|
4687
|
+
* set of lines. Null delta values remove the key from the saved line style;
|
|
4688
|
+
* lines whose merged style (and design) end up empty drop out of the map.
|
|
4689
|
+
* Whole-column/row formatting persists through these line styles as a single
|
|
4690
|
+
* design patch instead of one cell write per covered coordinate.
|
|
4691
|
+
*/
|
|
4692
|
+
export function mergeSheetAxisDesignLineStyles(
|
|
4693
|
+
axisDesign: Record<string, SheetAxisDesignObj> | null | undefined,
|
|
4694
|
+
lineDeltas: Array<{ delta: Record<string, unknown>; key: string }>,
|
|
4695
|
+
): Record<string, SheetAxisDesignObj> {
|
|
4696
|
+
const next: Record<string, SheetAxisDesignObj> = { ...(axisDesign || {}) };
|
|
4697
|
+
|
|
4698
|
+
lineDeltas.forEach(({ delta, key }) => {
|
|
4699
|
+
const lineDesign = next[key] || {};
|
|
4700
|
+
const mergedStyle: Record<string, unknown> = {
|
|
4701
|
+
...normalizeSheetCellStyle(lineDesign.style),
|
|
4702
|
+
};
|
|
4703
|
+
|
|
4704
|
+
Object.entries(delta).forEach(([prop, value]) => {
|
|
4705
|
+
if (value === null || value === undefined) {
|
|
4706
|
+
delete mergedStyle[prop];
|
|
4707
|
+
} else {
|
|
4708
|
+
mergedStyle[prop] = value;
|
|
4709
|
+
}
|
|
4710
|
+
});
|
|
4711
|
+
|
|
4712
|
+
const normalizedStyle = normalizeSheetCellStyle(mergedStyle);
|
|
4713
|
+
|
|
4714
|
+
if (Object.keys(normalizedStyle).length) {
|
|
4715
|
+
next[key] = {
|
|
4716
|
+
...lineDesign,
|
|
4717
|
+
style: normalizedStyle,
|
|
4718
|
+
};
|
|
4719
|
+
return;
|
|
4720
|
+
}
|
|
4721
|
+
|
|
4722
|
+
// An emptied style drops from the line design; an emptied line drops
|
|
4723
|
+
// from the axis map so the saved design stays sparse
|
|
4724
|
+
const { style: _droppedStyle, ...lineDesignWithoutStyle } = lineDesign;
|
|
4725
|
+
|
|
4726
|
+
if (Object.keys(lineDesignWithoutStyle).length) {
|
|
4727
|
+
next[key] = lineDesignWithoutStyle;
|
|
4728
|
+
} else {
|
|
4729
|
+
delete next[key];
|
|
4730
|
+
}
|
|
4731
|
+
});
|
|
4732
|
+
|
|
4733
|
+
return next;
|
|
4734
|
+
}
|
|
4735
|
+
|
|
4736
|
+
/*
|
|
4737
|
+
* Return one canonical hard-NEW cell format from flexible saved input. Only a
|
|
4738
|
+
* validated numberFormat survives; null, malformed, and retired keys normalize
|
|
4739
|
+
* to key-absent so an empty cascade layer cannot shadow lower layers.
|
|
4740
|
+
*/
|
|
4741
|
+
export function normalizeSheetCellFormat(
|
|
4742
|
+
format?: Partial<SheetCellFormatObj> | Record<string, any> | string | null,
|
|
4743
|
+
): SheetCellFormatObj {
|
|
4744
|
+
const { numberFormat: rawNumberFormat } = getSheetCellStyleObject(format);
|
|
4745
|
+
const normalized: SheetCellFormatObj = {};
|
|
4746
|
+
|
|
4747
|
+
if (
|
|
4748
|
+
rawNumberFormat &&
|
|
4749
|
+
typeof rawNumberFormat === 'object' &&
|
|
4750
|
+
!Array.isArray(rawNumberFormat) &&
|
|
4751
|
+
isSheetCellNumberFormatType(rawNumberFormat.type)
|
|
4752
|
+
) {
|
|
4753
|
+
const numberFormat: SheetCellNumberFormatObj = {
|
|
4754
|
+
type: rawNumberFormat.type,
|
|
4755
|
+
};
|
|
4756
|
+
|
|
4757
|
+
if (
|
|
4758
|
+
typeof rawNumberFormat.pattern === 'string' &&
|
|
4759
|
+
rawNumberFormat.pattern &&
|
|
4760
|
+
rawNumberFormat.pattern.length <= 500
|
|
4761
|
+
) {
|
|
4762
|
+
numberFormat.pattern = rawNumberFormat.pattern;
|
|
4763
|
+
}
|
|
4764
|
+
|
|
4765
|
+
if (
|
|
4766
|
+
typeof rawNumberFormat.currency === 'string' &&
|
|
4767
|
+
/^[A-Z]{3,8}$/.test(rawNumberFormat.currency)
|
|
4768
|
+
) {
|
|
4769
|
+
numberFormat.currency = rawNumberFormat.currency;
|
|
4770
|
+
}
|
|
4771
|
+
|
|
4772
|
+
normalized.numberFormat = numberFormat;
|
|
4773
|
+
}
|
|
4774
|
+
|
|
4775
|
+
return normalized;
|
|
4776
|
+
}
|
|
4777
|
+
|
|
4778
|
+
/*
|
|
4779
|
+
* Return one axis design map (columns or rows) with number-format layers
|
|
4780
|
+
* replaced whole per line. A null/empty format deletes the line format, and
|
|
4781
|
+
* lines whose design ends up empty drop out so the saved map stays sparse.
|
|
4782
|
+
*/
|
|
4783
|
+
export function mergeSheetAxisDesignLineFormats(
|
|
4784
|
+
axisDesign: Record<string, SheetAxisDesignObj> | null | undefined,
|
|
4785
|
+
lineFormats: Array<{ format: SheetCellFormatObj | null; key: string }>,
|
|
4786
|
+
): Record<string, SheetAxisDesignObj> {
|
|
4787
|
+
const next: Record<string, SheetAxisDesignObj> = { ...(axisDesign || {}) };
|
|
4788
|
+
|
|
4789
|
+
lineFormats.forEach(({ format, key }) => {
|
|
4790
|
+
const lineDesign = next[key] || {};
|
|
4791
|
+
const normalizedFormat = format ? normalizeSheetCellFormat(format) : {};
|
|
4792
|
+
|
|
4793
|
+
if (Object.keys(normalizedFormat).length) {
|
|
4794
|
+
next[key] = {
|
|
4795
|
+
...lineDesign,
|
|
4796
|
+
format: normalizedFormat,
|
|
4797
|
+
};
|
|
4798
|
+
return;
|
|
4799
|
+
}
|
|
4800
|
+
|
|
4801
|
+
// An emptied format drops from the line design; an emptied line drops
|
|
4802
|
+
// from the axis map so the saved design stays sparse
|
|
4803
|
+
const { format: _droppedFormat, ...lineDesignWithoutFormat } = lineDesign;
|
|
4804
|
+
|
|
4805
|
+
if (Object.keys(lineDesignWithoutFormat).length) {
|
|
4806
|
+
next[key] = lineDesignWithoutFormat;
|
|
4807
|
+
} else {
|
|
4808
|
+
delete next[key];
|
|
4809
|
+
}
|
|
4810
|
+
});
|
|
4811
|
+
|
|
4812
|
+
return next;
|
|
4813
|
+
}
|
|
4814
|
+
|
|
4815
|
+
/* Return a shallow merged canonical cell format using the format cascade. */
|
|
4816
|
+
export function mergeSheetCellFormats(
|
|
4817
|
+
...values: Array<
|
|
4818
|
+
| Partial<SheetCellFormatObj>
|
|
4819
|
+
| Record<string, any>
|
|
4820
|
+
| string
|
|
4821
|
+
| null
|
|
4822
|
+
| undefined
|
|
4823
|
+
>
|
|
4824
|
+
): SheetCellFormatObj {
|
|
4825
|
+
return values.reduce<SheetCellFormatObj>((merged, value) => {
|
|
4826
|
+
const format = normalizeSheetCellFormat(value);
|
|
4827
|
+
|
|
4828
|
+
if (!Object.keys(format).length) {
|
|
4829
|
+
return merged;
|
|
4830
|
+
}
|
|
4831
|
+
|
|
4832
|
+
return Object.assign(merged, format);
|
|
4833
|
+
}, {});
|
|
4834
|
+
}
|
|
4835
|
+
|
|
4836
|
+
/*
|
|
4837
|
+
* Return whether one grid coordinate is inside a saved sheet range.
|
|
4838
|
+
*/
|
|
4839
|
+
|
|
4840
|
+
export function isSheetCellInRange(
|
|
4841
|
+
rowIndex: number,
|
|
4842
|
+
columnIndex: number,
|
|
4843
|
+
range: Pick<
|
|
4844
|
+
SheetRangeData,
|
|
4845
|
+
'startRowIndex' | 'startColumnIndex' | 'endRowIndex' | 'endColumnIndex'
|
|
4846
|
+
>,
|
|
4847
|
+
) {
|
|
4848
|
+
return (
|
|
4849
|
+
rowIndex >= range.startRowIndex &&
|
|
4850
|
+
rowIndex <= range.endRowIndex &&
|
|
4851
|
+
columnIndex >= range.startColumnIndex &&
|
|
4852
|
+
columnIndex <= range.endColumnIndex
|
|
4853
|
+
);
|
|
4854
|
+
}
|
|
4855
|
+
|
|
4856
|
+
/*
|
|
4857
|
+
* Return one region source filter group picked down to mutation input fields,
|
|
4858
|
+
* dropping GQL-only metadata so the payload round-trips through SheetRegionInput.
|
|
4859
|
+
*/
|
|
4860
|
+
function getSheetRegionSourceFilterInput(
|
|
4861
|
+
filter: SheetRegionSourceFilterGroupObj,
|
|
4862
|
+
): Record<string, any> {
|
|
4863
|
+
return {
|
|
4864
|
+
combinator: filter.combinator,
|
|
4865
|
+
...(filter.conditions?.length
|
|
4866
|
+
? {
|
|
4867
|
+
conditions: filter.conditions.map((condition) => ({
|
|
4868
|
+
cellKey: condition.cellKey,
|
|
4869
|
+
operator: condition.operator,
|
|
4870
|
+
...(condition.textValue === null ||
|
|
4871
|
+
condition.textValue === undefined
|
|
4872
|
+
? {}
|
|
4873
|
+
: { textValue: condition.textValue }),
|
|
4874
|
+
...(condition.textValues?.length
|
|
4875
|
+
? { textValues: condition.textValues }
|
|
4876
|
+
: {}),
|
|
4877
|
+
...(condition.numberValue === null ||
|
|
4878
|
+
condition.numberValue === undefined
|
|
4879
|
+
? {}
|
|
4880
|
+
: { numberValue: condition.numberValue }),
|
|
4881
|
+
...(condition.booleanValue === null ||
|
|
4882
|
+
condition.booleanValue === undefined
|
|
4883
|
+
? {}
|
|
4884
|
+
: { booleanValue: condition.booleanValue }),
|
|
4885
|
+
...(condition.dateValue === null ||
|
|
4886
|
+
condition.dateValue === undefined
|
|
4887
|
+
? {}
|
|
4888
|
+
: { dateValue: condition.dateValue }),
|
|
4889
|
+
...(condition.datetimeValue === null ||
|
|
4890
|
+
condition.datetimeValue === undefined
|
|
4891
|
+
? {}
|
|
4892
|
+
: { datetimeValue: condition.datetimeValue }),
|
|
4893
|
+
})),
|
|
4894
|
+
}
|
|
4895
|
+
: {}),
|
|
4896
|
+
...(filter.groups?.length
|
|
4897
|
+
? { groups: filter.groups.map(getSheetRegionSourceFilterInput) }
|
|
4898
|
+
: {}),
|
|
4899
|
+
};
|
|
4900
|
+
}
|
|
4901
|
+
|
|
4902
|
+
/*
|
|
4903
|
+
* Return the upsert mutation input that recreates one saved Sheet region.
|
|
4904
|
+
* Used to undo a region delete locally today, and shaped to stay serializable
|
|
4905
|
+
* for future server-persisted undo records.
|
|
4906
|
+
*/
|
|
4907
|
+
export function getSheetRegionInputFromRegion(
|
|
4908
|
+
region: SheetRegionGQL,
|
|
4909
|
+
): Record<string, any> | null {
|
|
4910
|
+
const source = region.source;
|
|
4911
|
+
|
|
4912
|
+
if (
|
|
4913
|
+
!source?.type ||
|
|
4914
|
+
!region.type ||
|
|
4915
|
+
!region.startRowIndex ||
|
|
4916
|
+
!region.startColumnIndex
|
|
4917
|
+
) {
|
|
4918
|
+
return null;
|
|
4919
|
+
}
|
|
4920
|
+
|
|
4921
|
+
return {
|
|
4922
|
+
// Preserving active keeps an inactive region from silently reactivating
|
|
4923
|
+
// when history recreates it from these variables
|
|
4924
|
+
...(region.active === null || region.active === undefined
|
|
4925
|
+
? {}
|
|
4926
|
+
: { active: region.active }),
|
|
4927
|
+
columns: (region.columns || []).map((column) => ({
|
|
4928
|
+
...(column.kind ? { kind: column.kind } : {}),
|
|
4929
|
+
...(column.sourceCellKey ? { sourceCellKey: column.sourceCellKey } : {}),
|
|
4930
|
+
...(column.formulaText ? { formulaText: column.formulaText } : {}),
|
|
4931
|
+
})),
|
|
4932
|
+
source: {
|
|
4933
|
+
type: source.type,
|
|
4934
|
+
...(source.dataTableId === null || source.dataTableId === undefined
|
|
4935
|
+
? {}
|
|
4936
|
+
: { dataTableId: String(source.dataTableId) }),
|
|
4937
|
+
...(source.filter
|
|
4938
|
+
? { filter: getSheetRegionSourceFilterInput(source.filter) }
|
|
4939
|
+
: {}),
|
|
4940
|
+
...(source.sort?.length
|
|
4941
|
+
? {
|
|
4942
|
+
sort: source.sort.map((sort) => ({
|
|
4943
|
+
cellKey: sort.cellKey,
|
|
4944
|
+
direction: sort.direction,
|
|
4945
|
+
})),
|
|
4946
|
+
}
|
|
4947
|
+
: {}),
|
|
4948
|
+
...(source.includeRowIds?.length
|
|
4949
|
+
? { includeRowIds: source.includeRowIds.map(String) }
|
|
4950
|
+
: {}),
|
|
4951
|
+
},
|
|
4952
|
+
startColumnIndex: region.startColumnIndex,
|
|
4953
|
+
startRowIndex: region.startRowIndex,
|
|
4954
|
+
type: region.type,
|
|
4955
|
+
...(region.options
|
|
4956
|
+
? {
|
|
4957
|
+
options: {
|
|
4958
|
+
...(region.options.conflictPolicy
|
|
4959
|
+
? { conflictPolicy: region.options.conflictPolicy }
|
|
4960
|
+
: {}),
|
|
4961
|
+
...(region.options.endRowIndex === null ||
|
|
4962
|
+
region.options.endRowIndex === undefined
|
|
4963
|
+
? {}
|
|
4964
|
+
: { endRowIndex: region.options.endRowIndex }),
|
|
4965
|
+
...(region.options.includeHeaderRow === null ||
|
|
4966
|
+
region.options.includeHeaderRow === undefined
|
|
4967
|
+
? {}
|
|
4968
|
+
: { includeHeaderRow: region.options.includeHeaderRow }),
|
|
4969
|
+
},
|
|
4970
|
+
}
|
|
4971
|
+
: {}),
|
|
4972
|
+
};
|
|
4973
|
+
}
|