@libregrid/formulas 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,661 @@
1
+ import { BeanStub, } from 'ag-grid-community';
2
+ import { FORMULA_FUNCTION_NAMES, FormulaError, columnPosition, convertFormula, evaluate, getFormulaFunction, parseCellFormula, parseExpression, referencedCells, shiftFormula, validateExpression, } from './expression';
3
+ /** Service column ids (`ag-Grid-*`) never participate in A1 column-letter mapping. */
4
+ function isServiceColumn(col) {
5
+ return col.getColId().startsWith('ag-Grid-');
6
+ }
7
+ const AST_CACHE_LIMIT = 2048;
8
+ /**
9
+ * The canonical `formula` bean — Community's formula seam, implementing both
10
+ * gap-plan A2 (calculated columns) and gap-plan A1 (per-cell formulas).
11
+ *
12
+ * `@libregrid/calculated-columns` and `@libregrid/formulas` both declare this
13
+ * class in their module `beans` arrays; the context collects module beans into
14
+ * a `Set`, so exactly one instance serves both features regardless of
15
+ * registration order.
16
+ *
17
+ * - **Calculated-column mode** (`colDef.calculatedExpression`): same-row
18
+ * `[colId]` expressions evaluated in `ValueService.getValueFromData`
19
+ * (Phase 18 behaviour, unchanged).
20
+ * - **Per-cell mode** (`colDef.allowFormula`): `=...` strings resolved from the
21
+ * row-data field or the external `formulaDataSource` (via the
22
+ * `formulaDataSvc` bean), A1-notation references, ranges, `$` anchors,
23
+ * `formulaFuncs` custom functions, and the fill-handle offset contract
24
+ * (`updateFormulaByOffset`).
25
+ *
26
+ * `active` mirrors the docs' compatibility table: per-cell formulas are a
27
+ * Client Row Model feature — tree data, pivot mode and active row grouping
28
+ * keep the flag off so Community's soft-filter stage path never engages.
29
+ *
30
+ * @feature Formulas
31
+ */
32
+ export class FormulaService extends BeanStub {
33
+ beanName = 'formula';
34
+ /** Per-cell formulas active (drives Community's soft-filter + error display paths). */
35
+ active = false;
36
+ /** Parsed-AST cache for calculated-column expressions, keyed by column instance. */
37
+ astCache = new Map();
38
+ /** Parsed-AST cache for per-cell formulas, keyed by the formula text itself. */
39
+ cellAstCache = new Map();
40
+ /**
41
+ * External formula text cache (`rowId:colId` → formula string | undefined).
42
+ * `getFormula` is lazy and cached per the docs; invalidated by edits, row
43
+ * refreshes, column changes and `api.refreshFormulas()`.
44
+ */
45
+ textCache = new Map();
46
+ /** Evaluation errors per cell, keyed `${rowId}:${colId}`. */
47
+ cellErrors = new Map();
48
+ /** Active calculated-column resolution chain (colIds) for `#CIRCREF!`. */
49
+ chain = [];
50
+ /** Active per-cell resolution chain (`rowId:colId` keys) for `#CIRCREF!`. */
51
+ cellChain = new Set();
52
+ /** Bumped whenever the column/row layout may have changed; keys the format map. */
53
+ formatGen = 0;
54
+ formatCache;
55
+ destroy() {
56
+ this.astCache.clear();
57
+ this.cellAstCache.clear();
58
+ this.textCache.clear();
59
+ this.cellErrors.clear();
60
+ this.cellChain.clear();
61
+ super.destroy();
62
+ }
63
+ // ------------------------------------------------------------------
64
+ // IFormulaService — value pipeline
65
+ // ------------------------------------------------------------------
66
+ resolveValue(column, row) {
67
+ const col = column;
68
+ if (col.calculatedExpression !== undefined) {
69
+ return this.resolveCalculated(col, row);
70
+ }
71
+ if (col.allowFormula) {
72
+ return this.resolveCellFormula(col, row);
73
+ }
74
+ return undefined;
75
+ }
76
+ /** Last evaluation error for the cell, evaluating on demand. */
77
+ getFormulaError(column, row) {
78
+ const col = column;
79
+ const key = this.key(row, col);
80
+ let error = this.cellErrors.get(key);
81
+ if (error === undefined) {
82
+ this.resolveValue(col, row);
83
+ error = this.cellErrors.get(key);
84
+ }
85
+ return error ?? null;
86
+ }
87
+ /** Parse-only check (dialog deferred mode + validation events). */
88
+ validateExpression(expression, options = {}) {
89
+ return validateExpression(expression, options);
90
+ }
91
+ // ------------------------------------------------------------------
92
+ // IFormulaService — invalidation
93
+ // ------------------------------------------------------------------
94
+ hasCachedRows() {
95
+ return this.textCache.size > 0 || this.cellErrors.size > 0;
96
+ }
97
+ isEvaluationActive() {
98
+ // Ranges resolve against the live displayed-row set, so the CSRM
99
+ // `formulaRowIndex` stamping pass is not needed.
100
+ return false;
101
+ }
102
+ refreshFormulas(refreshRows) {
103
+ this.textCache.clear();
104
+ this.cellErrors.clear();
105
+ this.formatGen++;
106
+ if (refreshRows) {
107
+ // The Community edit service relies on this hook to repaint rows after
108
+ // batch commits; external-store invalidation flows through the same path.
109
+ this.beans.gridApi?.refreshCells({ force: true });
110
+ }
111
+ }
112
+ refreshRow(row) {
113
+ const rowId = typeof row === 'string' ? row : row.id;
114
+ let removed = false;
115
+ const prefix = `${rowId}:`;
116
+ for (const map of [this.textCache, this.cellErrors]) {
117
+ for (const key of map.keys()) {
118
+ if (key.startsWith(prefix)) {
119
+ map.delete(key);
120
+ removed = true;
121
+ }
122
+ }
123
+ }
124
+ return removed;
125
+ }
126
+ onRowsChanged(_changedRowNodes, _newData) {
127
+ // Row set/order changed: drop the external-formula and error caches
128
+ // conservatively — the next render re-reads and repopulates. Parsed ASTs
129
+ // are keyed by text and stay valid.
130
+ this.textCache.clear();
131
+ this.cellErrors.clear();
132
+ this.formatGen++;
133
+ }
134
+ // ------------------------------------------------------------------
135
+ // IFormulaService — per-cell formula hooks
136
+ // ------------------------------------------------------------------
137
+ isFormula(value) {
138
+ return typeof value === 'string' && value.length > 1 && value.startsWith('=');
139
+ }
140
+ /**
141
+ * Column-model build hook: decides whether per-cell formulas are active and
142
+ * drops caches that depended on the previous column set.
143
+ */
144
+ setFormulasActive(colDefList) {
145
+ const anyAllowFormula = colDefList.some((colDef) => colDef?.allowFormula === true);
146
+ this.active = anyAllowFormula && this.eligible();
147
+ this.textCache.clear();
148
+ this.formatGen++;
149
+ }
150
+ /**
151
+ * Drop the cached external-store text for one cell. The data service calls
152
+ * this whenever a formula is written (or cleared) through
153
+ * `formulaDataSource`, so the next read — including Community's immediate
154
+ * re-evaluation inside the commit path — sees the new store entry.
155
+ */
156
+ invalidateCellFormula(row, column) {
157
+ this.textCache.delete(this.key(row, column));
158
+ }
159
+ getDataSourceFormula(row, column) {
160
+ const col = column;
161
+ if (!col.allowFormula)
162
+ return undefined;
163
+ const dataSvc = this.formulaDataSvc();
164
+ if (!dataSvc?.hasDataSource())
165
+ return undefined;
166
+ const key = this.key(row, col);
167
+ if (this.textCache.has(key))
168
+ return this.textCache.get(key);
169
+ const formula = dataSvc.getFormula({ column: col, rowNode: row });
170
+ this.textCache.set(key, formula);
171
+ return formula;
172
+ }
173
+ /**
174
+ * Convert between the long-hand storage form (col/row IDs) and the shorthand
175
+ * display form (A1). `shorthand: true` converts long-hand → shorthand (the
176
+ * display/export direction Community's `useRawFormula` path uses);
177
+ * `false` converts shorthand → long-hand. Non-formulas yield `null`.
178
+ */
179
+ normaliseFormula(value, shorthand) {
180
+ if (!this.isFormula(value))
181
+ return null;
182
+ const format = this.formatOrNull();
183
+ if (!format)
184
+ return null;
185
+ try {
186
+ return convertFormula(value, format, !shorthand);
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ /**
193
+ * The formula text an editor should display for this cell: the external
194
+ * store's entry when a `formulaDataSource` holds it (Community routes
195
+ * formula commits into the store even for field columns), else the raw
196
+ * cell value.
197
+ */
198
+ getEditableFormula(column, row) {
199
+ const raw = this.rawValue(column, row);
200
+ return raw == null ? undefined : String(raw);
201
+ }
202
+ getColByRef(ref) {
203
+ return this.columnModel().getNonPivotColById(ref) ?? null;
204
+ }
205
+ getColRef(col) {
206
+ return col.colId;
207
+ }
208
+ /** Fill-handle/bulk-edit hook: shift a formula's relative references. */
209
+ updateFormulaByOffset(params) {
210
+ try {
211
+ const format = this.formatOrNull();
212
+ if (!format)
213
+ return shiftFormula(params);
214
+ // Long-hand references are ID-pinned and `shiftFormula` deliberately
215
+ // leaves them in place — but a fill/offset must move the reference to
216
+ // the neighbouring row. Translate to display positions, shift, and
217
+ // convert back to the input's reference form (the external store holds
218
+ // long-hand; row-data formulas may be shorthand).
219
+ const display = convertFormula(params.value, format, false);
220
+ const shifted = shiftFormula({ ...params, value: display });
221
+ return this.hasLongHandRef(params.value)
222
+ ? convertFormula(shifted, format, true)
223
+ : shifted;
224
+ }
225
+ catch (e) {
226
+ if (e instanceof FormulaError && e.code === '#REF!')
227
+ return params.value;
228
+ throw e;
229
+ }
230
+ }
231
+ hasLongHandRef(formula) {
232
+ try {
233
+ return referencedCells(parseCellFormula(formula)).some((ref) => !ref.shorthand);
234
+ }
235
+ catch {
236
+ return false;
237
+ }
238
+ }
239
+ /**
240
+ * Grid positions of every reference in a formula, for editor range
241
+ * highlighting. Cells become 1×1 descriptors; ranges their normalised
242
+ * bounds. `[]` when the formula does not parse or the layout is unmappable.
243
+ */
244
+ formulaRangeDescriptors(formula) {
245
+ let ast;
246
+ try {
247
+ ast = parseCellFormula(formula);
248
+ }
249
+ catch {
250
+ return [];
251
+ }
252
+ const format = this.formatOrNull();
253
+ if (!format)
254
+ return [];
255
+ const descriptors = [];
256
+ const pushRef = (start, end) => {
257
+ try {
258
+ const colA = start.shorthand ? columnPosition(start.letters) : format.positionOf(start.colId);
259
+ const colB = end.shorthand ? columnPosition(end.letters) : format.positionOf(end.colId);
260
+ const rowA = start.shorthand ? start.row - 1 : format.indexOf(start.rowId);
261
+ const rowB = end.shorthand ? end.row - 1 : format.indexOf(end.rowId);
262
+ // Shorthand rows must still exist in the grid (throws #REF! otherwise).
263
+ format.rowIdAt(rowA);
264
+ format.rowIdAt(rowB);
265
+ descriptors.push({
266
+ rowStart: Math.min(rowA, rowB),
267
+ rowEnd: Math.max(rowA, rowB),
268
+ columnStart: format.colIdAt(Math.min(colA, colB)),
269
+ columnEnd: format.colIdAt(Math.max(colA, colB)),
270
+ });
271
+ }
272
+ catch {
273
+ // Unmappable reference (e.g. beyond the grid) — skip for highlighting.
274
+ }
275
+ };
276
+ const visit = (n) => {
277
+ switch (n.kind) {
278
+ case 'cell':
279
+ pushRef(n.ref, n.ref);
280
+ break;
281
+ case 'range':
282
+ pushRef(n.start, n.end);
283
+ break;
284
+ case 'binary':
285
+ visit(n.left);
286
+ visit(n.right);
287
+ break;
288
+ case 'unary':
289
+ case 'percent':
290
+ visit(n.operand);
291
+ break;
292
+ case 'call':
293
+ for (const a of n.args)
294
+ visit(a);
295
+ break;
296
+ default:
297
+ break;
298
+ }
299
+ };
300
+ visit(ast);
301
+ return descriptors;
302
+ }
303
+ getFunction(name) {
304
+ const custom = this.customFunction(name);
305
+ if (custom)
306
+ return custom;
307
+ const builtIn = this.builtInFunction(name);
308
+ if (!builtIn)
309
+ return undefined;
310
+ // Adapter: the engine's built-ins take scalar args with ranges flattened
311
+ // per argument; community-facing params arrive as FormulaParam objects.
312
+ return (params) => {
313
+ const args = [...params.args].map((p) => p.kind === 'value' ? p.value : 'values' in p ? p.values : [...p]);
314
+ return builtIn(args);
315
+ };
316
+ }
317
+ getFunctionNames() {
318
+ const names = new Set(FORMULA_FUNCTION_NAMES);
319
+ for (const name of Object.keys(this.gos.get('formulaFuncs') ?? {}))
320
+ names.add(name);
321
+ return [...names].sort();
322
+ }
323
+ // ------------------------------------------------------------------
324
+ // Calculated-column mode (Phase 18 behaviour)
325
+ // ------------------------------------------------------------------
326
+ resolveCalculated(column, row) {
327
+ const expression = column.calculatedExpression ?? null;
328
+ if (expression === null || expression === '') {
329
+ this.clearCellError(row, column);
330
+ return null; // empty expression → blank cells
331
+ }
332
+ const ast = this.getCalculatedAst(column, expression);
333
+ if (ast === null) {
334
+ const error = new FormulaError('#PARSE!', `cannot parse "${expression}"`);
335
+ this.storeCellError(row, column, error);
336
+ return error.code;
337
+ }
338
+ this.chain.push(column);
339
+ try {
340
+ const value = evaluate(ast, {
341
+ resolveColumn: (colId) => {
342
+ const ref = this.columnModel().getNonPivotColById(colId);
343
+ if (!ref)
344
+ throw new FormulaError('#REF!', `unknown column reference [${colId}]`);
345
+ return this.valueService()?.getValueFromData(ref, row) ?? null;
346
+ },
347
+ isResolving: (colId) => this.chain.some((c) => c.colId === colId),
348
+ });
349
+ this.clearCellError(row, column);
350
+ return value;
351
+ }
352
+ catch (e) {
353
+ return this.fail(row, column, e);
354
+ }
355
+ finally {
356
+ this.chain.pop();
357
+ }
358
+ }
359
+ /** Forget a column's AST when its expression is removed (column removed). */
360
+ forgetColumn(column) {
361
+ if (column)
362
+ this.astCache.delete(column);
363
+ }
364
+ getCalculatedAst(column, expression) {
365
+ const cached = this.astCache.get(column);
366
+ if (cached && cached.expression === expression)
367
+ return cached.ast;
368
+ let ast = null;
369
+ try {
370
+ ast = parseExpression(expression);
371
+ }
372
+ catch (e) {
373
+ if (!(e instanceof FormulaError) || e.code !== '#PARSE!') {
374
+ throw e;
375
+ }
376
+ }
377
+ this.astCache.set(column, { expression, ast });
378
+ if (this.astCache.size > AST_CACHE_LIMIT) {
379
+ const first = this.astCache.keys().next().value;
380
+ if (first !== undefined)
381
+ this.astCache.delete(first);
382
+ }
383
+ return ast;
384
+ }
385
+ // ------------------------------------------------------------------
386
+ // Per-cell mode
387
+ // ------------------------------------------------------------------
388
+ resolveCellFormula(column, row) {
389
+ if (row.group) {
390
+ // Grouping is not supported (docs compatibility table): group-row cells
391
+ // render blank rather than evaluating a row-positioned formula.
392
+ this.clearCellError(row, column);
393
+ return null;
394
+ }
395
+ const raw = this.rawValue(column, row);
396
+ if (!this.isFormula(raw)) {
397
+ this.clearCellError(row, column);
398
+ return raw ?? null;
399
+ }
400
+ if (!this.eligible()) {
401
+ // Unsupported runtime (grouping, tree data, pivot, non-CSR): formula
402
+ // strings render blank rather than evaluating row-positioned references.
403
+ this.clearCellError(row, column);
404
+ return null;
405
+ }
406
+ const ast = this.getCellAst(raw);
407
+ if (ast === null) {
408
+ return this.fail(row, column, new FormulaError('#PARSE!', `cannot parse "${raw}"`));
409
+ }
410
+ const key = this.key(row, column);
411
+ if (this.cellChain.has(key)) {
412
+ throw new FormulaError('#CIRCREF!', `circular reference through ${column.colId}`);
413
+ }
414
+ this.cellChain.add(key);
415
+ try {
416
+ const value = evaluate(ast, {
417
+ mode: 'cell',
418
+ resolveColumn: (colId) => {
419
+ const ref = this.columnModel().getNonPivotColById(colId);
420
+ if (!ref)
421
+ throw new FormulaError('#REF!', `unknown column reference [${colId}]`);
422
+ return this.valueService()?.getValueFromData(ref, row) ?? null;
423
+ },
424
+ isResolving: (colId) => this.chain.some((c) => c.colId === colId),
425
+ resolveCell: (ref) => this.resolveCellRef(ref),
426
+ resolveRange: (start, end) => this.resolveCellRange(start, end),
427
+ resolveCustomFunction: (name) => this.customFunction(name),
428
+ functionContext: { row, column },
429
+ });
430
+ this.clearCellError(row, column);
431
+ return value;
432
+ }
433
+ catch (e) {
434
+ return this.fail(row, column, e);
435
+ }
436
+ finally {
437
+ this.cellChain.delete(key);
438
+ }
439
+ }
440
+ /** The cell's raw (unresolved) value: pending edit, external store, or data field. */
441
+ rawValue(column, row) {
442
+ const dataSvc = this.formulaDataSvc();
443
+ if (dataSvc?.hasDataSource()) {
444
+ const stored = this.getDataSourceFormula(row, column);
445
+ if (stored !== undefined)
446
+ return stored;
447
+ }
448
+ return this.valueService()?.getValue(column, row, 'edit') ?? null;
449
+ }
450
+ getCellAst(expression) {
451
+ const cached = this.cellAstCache.get(expression);
452
+ if (cached !== undefined)
453
+ return cached;
454
+ let ast = null;
455
+ try {
456
+ ast = parseCellFormula(expression);
457
+ }
458
+ catch (e) {
459
+ if (!(e instanceof FormulaError) || e.code !== '#PARSE!') {
460
+ throw e;
461
+ }
462
+ }
463
+ this.cellAstCache.set(expression, ast);
464
+ if (this.cellAstCache.size > AST_CACHE_LIMIT) {
465
+ const first = this.cellAstCache.keys().next().value;
466
+ if (first !== undefined)
467
+ this.cellAstCache.delete(first);
468
+ }
469
+ return ast;
470
+ }
471
+ /** Resolve one cell reference to its evaluated value. */
472
+ resolveCellRef(ref) {
473
+ const format = this.format();
474
+ const colId = ref.shorthand ? format.colIdAt(columnPosition(ref.letters)) : ref.colId;
475
+ const rowIndex = ref.shorthand ? ref.row - 1 : format.indexOf(ref.rowId);
476
+ const rowNode = this.beans.gridApi?.getDisplayedRowAtIndex(rowIndex);
477
+ const refColumn = this.columnModel().getNonPivotColById(colId);
478
+ if (!rowNode || !refColumn) {
479
+ throw new FormulaError('#REF!', `unknown cell reference`);
480
+ }
481
+ return this.readCell(refColumn, rowNode);
482
+ }
483
+ /** Resolve a rectangular range to bounds + row-major values. */
484
+ resolveCellRange(start, end) {
485
+ const format = this.format();
486
+ const colA = start.shorthand ? columnPosition(start.letters) : format.positionOf(start.colId);
487
+ const colB = end.shorthand ? columnPosition(end.letters) : format.positionOf(end.colId);
488
+ const rowA = start.shorthand ? start.row - 1 : format.indexOf(start.rowId);
489
+ const rowB = end.shorthand ? end.row - 1 : format.indexOf(end.rowId);
490
+ const colStart = Math.min(colA, colB);
491
+ const colEnd = Math.max(colA, colB);
492
+ const rowStart = Math.min(rowA, rowB);
493
+ const rowEnd = Math.max(rowA, rowB);
494
+ const columns = [];
495
+ for (let p = colStart; p <= colEnd; p++) {
496
+ const col = this.columnModel().getNonPivotColById(format.colIdAt(p));
497
+ if (!col)
498
+ throw new FormulaError('#REF!', 'range references a missing column');
499
+ columns.push(col);
500
+ }
501
+ const values = [];
502
+ for (let r = rowStart; r <= rowEnd; r++) {
503
+ const rowNode = this.beans.gridApi?.getDisplayedRowAtIndex(r);
504
+ if (!rowNode)
505
+ throw new FormulaError('#REF!', 'range references a missing row');
506
+ for (const col of columns) {
507
+ values.push(this.readCell(col, rowNode));
508
+ }
509
+ }
510
+ return {
511
+ rowStart,
512
+ rowEnd,
513
+ colStart: columns[0],
514
+ colEnd: columns[columns.length - 1],
515
+ values,
516
+ };
517
+ }
518
+ /** Read one cell: referenced formula cells re-resolve; plain cells read committed data. */
519
+ readCell(refColumn, rowNode) {
520
+ if (refColumn.allowFormula || refColumn.calculatedExpression !== undefined) {
521
+ const key = `${rowNode.id}:${refColumn.colId}`;
522
+ if (this.cellChain.has(key)) {
523
+ throw new FormulaError('#CIRCREF!', `circular reference through ${refColumn.colId}`);
524
+ }
525
+ this.cellChain.add(key);
526
+ try {
527
+ return this.resolveValue(refColumn, rowNode);
528
+ }
529
+ finally {
530
+ this.cellChain.delete(key);
531
+ }
532
+ }
533
+ return this.valueService()?.getValueFromData(refColumn, rowNode) ?? null;
534
+ }
535
+ // ------------------------------------------------------------------
536
+ // Grid-layout format map (A1 ⇄ col/row IDs)
537
+ // ------------------------------------------------------------------
538
+ /**
539
+ * Column letters map over the displayed columns (left + centre + right,
540
+ * excluding `ag-Grid-*` service columns); row numbers map over the displayed
541
+ * rows. Rebuilt lazily whenever `formatGen` changes.
542
+ */
543
+ format() {
544
+ const cached = this.formatCache;
545
+ if (cached && cached.gen === this.formatGen) {
546
+ return this.formatFrom(cached.colIds, cached.rowIds);
547
+ }
548
+ const colIds = (this.beans.visibleCols?.allCols ?? [])
549
+ .filter((col) => !isServiceColumn(col))
550
+ .map((col) => col.getColId());
551
+ const rowIds = [];
552
+ const api = this.beans.gridApi;
553
+ if (api) {
554
+ const count = api.getDisplayedRowCount();
555
+ for (let i = 0; i < count; i++) {
556
+ const node = api.getDisplayedRowAtIndex(i);
557
+ rowIds.push(node?.id ?? '');
558
+ }
559
+ }
560
+ this.formatCache = { gen: this.formatGen, colIds, rowIds };
561
+ return this.formatFrom(colIds, rowIds);
562
+ }
563
+ formatFrom(colIds, rowIds) {
564
+ return {
565
+ colIdAt: (position) => {
566
+ const colId = colIds[position];
567
+ if (colId === undefined)
568
+ throw new FormulaError('#REF!', `column position ${position} is outside the grid`);
569
+ return colId;
570
+ },
571
+ positionOf: (colId) => {
572
+ const position = colIds.indexOf(colId);
573
+ if (position === -1)
574
+ throw new FormulaError('#REF!', `unknown column "${colId}"`);
575
+ return position;
576
+ },
577
+ rowIdAt: (index) => {
578
+ const rowId = rowIds[index];
579
+ if (rowId === undefined || rowId === '')
580
+ throw new FormulaError('#REF!', `row ${index} is outside the grid`);
581
+ return rowId;
582
+ },
583
+ indexOf: (rowId) => {
584
+ const index = rowIds.indexOf(rowId);
585
+ if (index === -1)
586
+ throw new FormulaError('#REF!', `unknown row "${rowId}"`);
587
+ return index;
588
+ },
589
+ };
590
+ }
591
+ formatOrNull() {
592
+ try {
593
+ return this.format();
594
+ }
595
+ catch {
596
+ return null;
597
+ }
598
+ }
599
+ // ------------------------------------------------------------------
600
+ // Functions
601
+ // ------------------------------------------------------------------
602
+ customFunction(name) {
603
+ const funcs = this.gos.get('formulaFuncs');
604
+ if (!funcs)
605
+ return undefined;
606
+ const entry = funcs[name] ?? funcs[name.toUpperCase()];
607
+ return entry?.func;
608
+ }
609
+ builtInFunction(name) {
610
+ return getFormulaFunction(name);
611
+ }
612
+ // ------------------------------------------------------------------
613
+ // Eligibility + helpers
614
+ // ------------------------------------------------------------------
615
+ /**
616
+ * Per-cell formulas are a CSR feature (docs compatibility table): server-side,
617
+ * infinite and viewport row models, tree data, pivot mode and active row
618
+ * grouping all keep `active` off.
619
+ */
620
+ eligible() {
621
+ if (this.gos.get('rowModelType') !== 'clientSide')
622
+ return false;
623
+ if (this.gos.get('treeData'))
624
+ return false;
625
+ if (this.columnModel().pivotMode)
626
+ return false;
627
+ const groupColumns = this.beans.rowGroupColsSvc?.columns;
628
+ if (groupColumns && groupColumns.length > 0)
629
+ return false;
630
+ return true;
631
+ }
632
+ fail(row, column, e) {
633
+ const error = e instanceof FormulaError ? e : new FormulaError('#ERROR!', e instanceof Error ? e.message : String(e));
634
+ this.storeCellError(row, column, error);
635
+ return error.code;
636
+ }
637
+ columnModel() {
638
+ const colModel = this.beans.colModel;
639
+ if (!colModel)
640
+ throw new Error('formulas: colModel bean missing');
641
+ return colModel;
642
+ }
643
+ valueService() {
644
+ return this.beans.valueSvc;
645
+ }
646
+ formulaDataSvc() {
647
+ return this.beans.formulaDataSvc;
648
+ }
649
+ key(row, column) {
650
+ return `${row.id}:${column.colId}`;
651
+ }
652
+ storeCellError(row, column, error) {
653
+ if (this.cellErrors.size > 20_000)
654
+ this.cellErrors.clear();
655
+ this.cellErrors.set(this.key(row, column), error);
656
+ }
657
+ clearCellError(row, column) {
658
+ this.cellErrors.delete(this.key(row, column));
659
+ }
660
+ }
661
+ //# sourceMappingURL=formulaService.js.map