Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

perf(formula): dependency optimization (#3969)

Univer196d0d8e9b27
diff --git a/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts b/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts
index d33363c489..b2d377dcdc 100644
--- a/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts
+++ b/packages-experimental/uni-formula-ui/src/services/uni-formula.service.ts
@@ -235,7 +235,7 @@ export class UniFormulaService extends DumbUniFormulaService implements IUniForm
const pseudoId = getPseudoUnitKey(unitId);
this._checkSyncingUnit(pseudoId);
- const id = this._registerOtherFormulaSrv.registerFormula(pseudoId, PSEUDO_SUBUNIT, f);
+ const id = this._registerOtherFormulaSrv.registerFormulaWithRange(pseudoId, PSEUDO_SUBUNIT, f);
this._docFormulas.set(key, { unitId, rangeId, f, formulaId: id, v, t });
this._formulaIdToKey.set(id, key);
@@ -265,7 +265,7 @@ export class UniFormulaService extends DumbUniFormulaService implements IUniForm
const pseudoId = getPseudoUnitKey(unitId);
this._checkSyncingUnit(pseudoId);
- const id = this._registerOtherFormulaSrv.registerFormula(pseudoId, PSEUDO_SUBUNIT, f);
+ const id = this._registerOtherFormulaSrv.registerFormulaWithRange(pseudoId, PSEUDO_SUBUNIT, f);
this._slideFormulas.set(key, { unitId, pageId, elementId, rangeId, f, formulaId: id, v, t });
this._formulaIdToKey.set(id, key);
@@ -320,7 +320,7 @@ export class UniFormulaService extends DumbUniFormulaService implements IUniForm
const pseudoId = getPseudoUnitKey(unitId);
this._checkSyncingUnit(pseudoId);
- const id = this._registerOtherFormulaSrv.registerFormula(pseudoId, PSEUDO_SUBUNIT, f);
+ const id = this._registerOtherFormulaSrv.registerFormulaWithRange(pseudoId, PSEUDO_SUBUNIT, f);
value.formulaId = id;
this._formulaIdToKey.set(id, key);
}
@@ -354,7 +354,7 @@ export class UniFormulaService extends DumbUniFormulaService implements IUniForm
const docItem = this._docFormulas.get(key);
if (docItem) {
- const r = result.result?.[0][0];
+ const r = result.result?.[0][0][0][0]; // Ranges defaults to one row and one column
if (docItem.v === r?.v && docItem.t === r?.t) return null;
return { position: { rangeId: docItem.rangeId }, unitId: docItem.unitId, cache: r };
@@ -362,7 +362,7 @@ export class UniFormulaService extends DumbUniFormulaService implements IUniForm
const slideItem = this._slideFormulas.get(key);
if (slideItem) {
- const r = result.result?.[0][0];
+ const r = result.result?.[0][0][0][0]; // Ranges defaults to one row and one column
if (slideItem.v === r?.v && slideItem.t === r?.t) return null;
return {
diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.ts
index 16c0c5b161..9c3e9fac87 100644
--- a/packages/core/src/shared/object-matrix.ts
+++ b/packages/core/src/shared/object-matrix.ts
@@ -274,18 +274,16 @@ export class ObjectMatrix<T> {
*/
forValue(callback: (row: number, col: number, value: T) => Nullable<boolean>): ObjectMatrix<T> {
const matrix = this._matrix;
- const matrixRow = Object.keys(matrix);
- for (const row of matrixRow) {
+ for (const row in matrix) {
const rowNumber = Number(row);
const columns = matrix[rowNumber];
if (!columns) continue;
- const columnKeys = Object.keys(columns);
- for (const column of columnKeys) {
+ for (const column in columns) {
const colNumber = Number(column);
- const value = columns[Number(column)];
+ const value = columns[colNumber];
const result = callback(rowNumber, colNumber, value);
if (result === false) {
diff --git a/packages/core/src/shared/r-tree.ts b/packages/core/src/shared/r-tree.ts
index 357d1dbe65..d936c72c26 100644
--- a/packages/core/src/shared/r-tree.ts
+++ b/packages/core/src/shared/r-tree.ts
@@ -49,8 +49,6 @@ export class RTree {
private _kdTree: Map<string, Map<string, { tree: KDBush; items: IRdTreeItem[] } | undefined>> = new Map();
- private _kdTreeSearchState = false;
-
constructor(private _enableOneCellCache = false) {
}
@@ -103,6 +101,30 @@ export class RTree {
cellCache.delete(id);
}
+ private _removeCellCacheByRange(search: IRTreeItem) {
+ const { unitId, sheetId: subUnitId, range, id } = search;
+
+ const unitCache = this._oneCellCache.get(unitId);
+ if (!unitCache) return;
+
+ const subUnitCache = unitCache.get(subUnitId);
+ if (!subUnitCache) return;
+
+ const { startRow, startColumn, endRow, endColumn } = range;
+
+ for (let row = startRow; row <= endRow; row++) {
+ const rowCache = subUnitCache.get(row);
+ if (!rowCache) continue;
+
+ for (let column = startColumn; column <= endColumn; column++) {
+ const cellCache = rowCache.get(column);
+ if (!cellCache) continue;
+
+ cellCache.delete(id);
+ }
+ }
+ }
+
private _insertOneCellCache(unitId: string, subUnitId: string, row: number, column: number, id: StringOrNumber) {
this._getOneCellCache(unitId, subUnitId, row, column).add(id);
}
@@ -150,7 +172,6 @@ export class RTree {
* The kd-tree is used to search for data in a single cell.
*/
openKdTree() {
- this._kdTreeSearchState = true;
for (const [unitId, map1] of this._oneCellCache) {
if (!this._kdTree.has(unitId)) {
this._kdTree.set(unitId, new Map());
@@ -171,7 +192,6 @@ export class RTree {
}
closeKdTree() {
- this._kdTreeSearchState = false;
for (const [unitId, map1] of this._oneCellCache) {
for (const [subUnitId, map2] of map1) {
this._kdTree.get(unitId)?.set(subUnitId, undefined);
@@ -223,21 +243,19 @@ export class RTree {
}
}
- search(search: IUnitRange): StringOrNumber[] {
+ *searchGenerator(search: IUnitRange): IterableIterator<StringOrNumber> {
const { unitId, sheetId: subUnitId, range } = search;
- const results: StringOrNumber[] = [];
-
- if (this._enableOneCellCache && this._enableOneCellCache) {
+ if (this._enableOneCellCache) {
const oneCellResults = this._searchByOneCellCache(search);
for (const result of oneCellResults) {
- results.push(result);
+ yield result;
}
}
const tree = this._tree.get(unitId)?.get(subUnitId);
if (!tree) {
- return results;
+ return;
}
const searchData = tree.search({
@@ -248,17 +266,17 @@ export class RTree {
}) as unknown as IRTreeItem[];
for (const item of searchData) {
- results.push(item.id);
+ yield item.id;
}
-
- return results;
}
- bulkSearch(searchList: IUnitRange[]): Set<StringOrNumber> {
+ bulkSearch(searchList: IUnitRange[], exceptTreeIds?: Set<number>): Set<StringOrNumber> {
const result = new Set<StringOrNumber>();
for (const search of searchList) {
- const items = this.search(search);
- for (const item of items) {
+ for (const item of this.searchGenerator(search)) {
+ if (exceptTreeIds?.has(item as number) === true) {
+ continue;
+ }
result.add(item);
}
}
@@ -275,17 +293,37 @@ export class RTree {
}
}
- remove(search: IRTreeItem) {
+ private _removeRTreeItem(search: IRTreeItem) {
const { unitId, sheetId: subUnitId, range, id } = search;
const tree = this.getTree(unitId, subUnitId);
- this._removeOneCellCache(unitId, subUnitId, range.startRow, range.startColumn, id);
- tree.remove({
+
+ const items = tree.search({
minX: range.startColumn,
minY: range.startRow,
maxX: range.endColumn,
maxY: range.endRow,
- id,
});
+
+ for (let i = 0; i < items.length; i++) {
+ if (items[i].id === id) {
+ tree.remove(items[i]);
+ }
+ }
+ }
+
+ remove(search: IRTreeItem) {
+ const { unitId, sheetId: subUnitId, range, id } = search;
+ const { startRow, startColumn, endRow, endColumn } = range;
+ if (this._enableOneCellCache) {
+ if (startRow === endRow && startColumn === endColumn) {
+ this._removeOneCellCache(unitId, subUnitId, range.startRow, range.startColumn, id);
+ } else {
+ this._removeCellCacheByRange(search);
+ this._removeRTreeItem(search);
+ }
+ } else {
+ this._removeRTreeItem(search);
+ }
}
bulkRemove(searchList: IRTreeItem[]) {
diff --git a/packages/core/src/shared/ref-alias.ts b/packages/core/src/shared/ref-alias.ts
index 673a803082..d76ed34fb1 100644
--- a/packages/core/src/shared/ref-alias.ts
+++ b/packages/core/src/shared/ref-alias.ts
@@ -78,8 +78,8 @@ export class RefAlias<T extends Record<string, unknown>, K extends keyof T = key
}
}
- deleteValue(key: string) {
- const value = this.getValue(key);
+ deleteValue(key: string, keyGroup?: K[]) {
+ const value = this.getValue(key, keyGroup);
if (value) {
this._keys.forEach((keyItem) => {
const keyMap = this._keyMaps.get(keyItem);
diff --git a/packages/data-validation/src/validators/base-data-validator.ts b/packages/data-validation/src/validators/base-data-validator.ts
index 196496eefc..61e5ad885b 100644
--- a/packages/data-validation/src/validators/base-data-validator.ts
+++ b/packages/data-validation/src/validators/base-data-validator.ts
@@ -108,7 +108,7 @@ export abstract class BaseDataValidator<DataType = CellValue> {
return `${errorMsg}`;
}
- getExtraStyle(rule: IDataValidationRuleBase, value: Nullable<CellValue>, ctx: { style: IStyleData }): Nullable<IStyleData> {}
+ getExtraStyle(rule: IDataValidationRuleBase, value: Nullable<CellValue>, ctx: { style: IStyleData }, row: number, column: number): Nullable<IStyleData> {}
getRuleFinalError(rule: IDataValidationRule) {
if (rule.showErrorMessage && rule.error) {
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index 82fc38f1b3..7b5578aa65 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -84,7 +84,7 @@ export interface IRuntimeUnitDataPrimitiveType {
}
export interface IRuntimeOtherUnitDataType {
- [unitId: string]: Nullable<{ [sheetId: string]: Nullable<{ [formulaId: string]: Nullable<ICellData>[][] }> }>;
+ [unitId: string]: Nullable<{ [sheetId: string]: Nullable<{ [formulaId: string]: IObjectMatrixPrimitiveType<Nullable<ICellData>[][]> }> }>;
}
export interface IUnitSheetNameMap {
@@ -126,7 +126,7 @@ export interface IFormulaData {
}
export interface IOtherFormulaData {
- [unitId: string]: Nullable<{ [subUnitId: string]: Nullable<{ [formulaId: string]: IFormulaDataItem }> }>;
+ [unitId: string]: Nullable<{ [subUnitId: string]: Nullable<{ [formulaId: string]: IOtherFormulaDataItem }> }>;
}
/**
* @f formulaString, the text string of the formula.
@@ -142,6 +142,11 @@ export interface IFormulaDataItem {
// sheetId: string;
}
+export interface IOtherFormulaDataItem {
+ f: string; // formulaString
+ ranges: IRange[];
+}
+
export interface ISuperTable {
sheetId: string;
hasCustomTitle: BooleanNumber;
diff --git a/packages/engine-formula/src/basics/runtime.ts b/packages/engine-formula/src/basics/runtime.ts
index 210d46acce..3ae081bc24 100644
--- a/packages/engine-formula/src/basics/runtime.ts
+++ b/packages/engine-formula/src/basics/runtime.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import { ObjectMatrix } from '@univerjs/core';
-
+import type { ICellData, IObjectMatrixPrimitiveType, Nullable } from '@univerjs/core';
import type { IArrayFormulaUnitCellType, IRuntimeUnitDataPrimitiveType, IRuntimeUnitDataType } from './common';
+import { ObjectMatrix } from '@univerjs/core';
+
export function convertUnitDataToRuntime(unitData: IArrayFormulaUnitCellType) {
const arrayFormulaCellData: IRuntimeUnitDataType = {};
Object.keys(unitData).forEach((unitId) => {
@@ -43,23 +44,32 @@ export function convertUnitDataToRuntime(unitData: IArrayFormulaUnitCellType) {
export function convertRuntimeToUnitData(unitData: IRuntimeUnitDataType) {
const unitPrimitiveData: IRuntimeUnitDataPrimitiveType = {};
- Object.keys(unitData).forEach((unitId) => {
- const sheetData = unitData[unitId];
+ for (const unitId in unitData) {
+ const sheetData = unitData[unitId];
if (sheetData == null) {
- return true;
+ continue;
}
if (unitPrimitiveData[unitId] == null) {
unitPrimitiveData[unitId] = {};
}
- Object.keys(sheetData).forEach((sheetId) => {
+ for (const sheetId in sheetData) {
const cellData = sheetData[sheetId];
+ const primitiveData: IObjectMatrixPrimitiveType<Nullable<ICellData>> = {};
- unitPrimitiveData[unitId]![sheetId] = cellData.getData();
- });
- });
+ cellData.forValue((row, column, value) => {
+ if (primitiveData[row] === undefined) {
+ primitiveData[row] = {};
+ }
+
+ primitiveData[row][column] = value;
+ });
+
+ unitPrimitiveData[unitId][sheetId] = primitiveData;
+ }
+ }
return unitPrimitiveData;
}
diff --git a/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts b/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts
index 4f97ef3d11..d0bfe94adc 100644
--- a/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts
@@ -15,14 +15,14 @@
*/
import type { IMutation } from '@univerjs/core';
-import { CommandType } from '@univerjs/core';
+import type { IOtherFormulaDataItem } from '../../basics/common';
-import type { IFormulaDataItem } from '../../basics/common';
+import { CommandType } from '@univerjs/core';
export interface ISetOtherFormulaMutationParams {
unitId: string;
subUnitId: string;
- formulaMap: Record<string, IFormulaDataItem>;
+ formulaMap: Record<string, IOtherFormulaDataItem>;
};
export interface IRemoveOtherFormulaMutationParams {
unitId: string;
diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.ts
index d84a892b2a..4a4efd4334 100644
--- a/packages/engine-formula/src/controller/calculate.controller.ts
+++ b/packages/engine-formula/src/controller/calculate.controller.ts
@@ -85,16 +85,6 @@ export class CalculateController extends Disposable {
formulaDirtyData: Partial<IFormulaDirtyData>
) {
const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {} } = formulaDirtyData;
- if (
- dirtyRanges.length === 0 &&
- Object.keys(dirtyNameMap).length === 0 &&
- Object.keys(dirtyDefinedNameMap).length === 0 &&
- Object.keys(dirtyUnitFeatureMap).length === 0 &&
- Object.keys(dirtyUnitOtherFormulaMap).length === 0 &&
- forceCalculate === false
- ) {
- return;
- }
const formulaData = this._formulaDataModel.getFormulaData();
diff --git a/packages/engine-formula/src/controller/set-other-formula.controller.ts b/packages/engine-formula/src/controller/set-other-formula.controller.ts
index 9f1bf54c20..99598ca71d 100644
--- a/packages/engine-formula/src/controller/set-other-formula.controller.ts
+++ b/packages/engine-formula/src/controller/set-other-formula.controller.ts
@@ -15,8 +15,9 @@
*/
import type { ICommandInfo } from '@univerjs/core';
-import type { IRemoveOtherFormulaMutationParams, ISetOtherFormulaMutationParams } from '../commands/mutations/set-other-formula.mutation';
+import type { IOtherFormulaData } from '../basics/common';
+import type { IRemoveOtherFormulaMutationParams, ISetOtherFormulaMutationParams } from '../commands/mutations/set-other-formula.mutation';
import { Disposable, ICommandService } from '@univerjs/core';
import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';
import { IDependencyManagerService } from '../services/dependency-manager.service';
@@ -47,7 +48,7 @@ export class SetOtherFormulaController extends Disposable {
if (params == null) {
return;
}
- const config = { [params.unitId]: { [params.subUnitId]: params.formulaMap } };
+ const config: IOtherFormulaData = { [params.unitId]: { [params.subUnitId]: params.formulaMap } };
this._otherFormulaManagerService.batchRegister(config);
} else if (command.id === RemoveOtherFormulaMutation.id) {
const params = command.params as IRemoveOtherFormulaMutationParams;
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
index 64b4d1dd7f..89a876e8de 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts
@@ -16,16 +16,20 @@
import type { Injector } from '@univerjs/core';
+import type { FormulaDependencyTreeVirtual } from '../../dependency/dependency-tree';
import { beforeEach, describe, expect, it } from 'vitest';
import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
+import { IOtherFormulaManagerService } from '../../../services/other-formula-manager.service';
import { IFormulaRuntimeService } from '../../../services/runtime.service';
+import { FormulaDependencyTree } from '../../dependency/dependency-tree';
import { FormulaDependencyGenerator } from '../../dependency/formula-dependency';
import { createCommandTestBed } from './create-command-test-bed';
-describe('Test indirect', () => {
+describe('Test dependency', () => {
let get: Injector['get'];
let formulaDependencyGenerator: FormulaDependencyGenerator;
let formulaCurrentConfigService: IFormulaCurrentConfigService;
+ let otherFormulaManagerService: IOtherFormulaManagerService;
let testUnitId = 'test';
let testSheetId = 'sheet1';
let testSheetData = {};
@@ -38,6 +42,8 @@ describe('Test indirect', () => {
formulaCurrentConfigService = get(IFormulaCurrentConfigService);
+ otherFormulaManagerService = get(IOtherFormulaManagerService);
+
const formulaRuntimeService = get(IFormulaRuntimeService);
const sheetItem = testBed.sheetData[testBed.sheetId];
@@ -58,6 +64,8 @@ describe('Test indirect', () => {
describe('dependency normal', () => {
it('test formula dependency simple ref', async () => {
+ const testOtherFormulaId = 'sheet.cf_workbook-01_Q2oij1uNg7HLUT7aT2ikk_yhq9VWH_';
+ const testOtherFormulaId2 = 'sheet.cf_workbook-01_Q2oij1uNg7HLUT7aT2ikk_idjs46G_';
formulaCurrentConfigService.load({
formulaData: {
[testUnitId]: {
@@ -108,15 +116,55 @@ describe('Test indirect', () => {
dirtyNameMap: {},
dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
- dirtyUnitOtherFormulaMap: {},
+ dirtyUnitOtherFormulaMap: {
+ [testUnitId]: {
+ [testSheetId]: {
+ [testOtherFormulaId]: true,
+ [testOtherFormulaId2]: true,
+ },
+ },
+ },
excludedCell: {},
allUnitData: {
[testUnitId]: testSheetData,
},
});
+ otherFormulaManagerService.batchRegister({
+ [testUnitId]: {
+ [testSheetId]: {
+ [testOtherFormulaId]: {
+ f: '=A1>1',
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 2,
+ endColumn: 0,
+ startAbsoluteRefType: 0,
+ endAbsoluteRefType: 0,
+ rangeType: 0,
+ },
+ ],
+ },
+ [testOtherFormulaId2]: {
+ f: '=A1>1',
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ },
+ ],
+ },
+ },
+ },
+ });
+
const treeList = await formulaDependencyGenerator.generate();
- const treeJson = treeList.map((tree) => tree.toJson().formula);
+ const treeJson = treeList.map((tree) => tree instanceof FormulaDependencyTree ? tree.formula : tree.refTree?.formula).reverse();
+
expect(treeJson).toEqual(
[
'=A1:C4',
@@ -124,8 +172,22 @@ describe('Test indirect', () => {
'=SUM(E10:I17)',
'=E10:I23',
'=SUM(F27:J34)',
+ '=A1>1',
+ '=A1>1',
+ '=A1>1',
+ '=A1>1',
]
);
+
+ // Check the offset position of other formula
+ // Note that the order is reversed
+ const tree = treeList[2] as FormulaDependencyTreeVirtual;
+ expect(tree.refOffsetX).toEqual(0);
+ expect(tree.refOffsetY).toEqual(1);
+
+ const tree2 = treeList[1] as FormulaDependencyTreeVirtual;
+ expect(tree2.refOffsetX).toEqual(0);
+ expect(tree2.refOffsetY).toEqual(2);
});
});
});
diff --git a/packages/engine-formula/src/engine/analysis/lexer-node.ts b/packages/engine-formula/src/engine/analysis/lexer-node.ts
index 994f2b6a78..5cac05cb2c 100644
--- a/packages/engine-formula/src/engine/analysis/lexer-node.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer-node.ts
@@ -16,8 +16,8 @@
import type { Nullable } from '@univerjs/core';
-import { DEFAULT_TOKEN_TYPE_ROOT } from '../../basics/token-type';
import type { LambdaPrivacyVarType } from '../ast-node/base-ast-node';
+import { DEFAULT_TOKEN_TYPE_ROOT } from '../../basics/token-type';
interface LexerNodeJson {
token: string;
@@ -51,7 +51,13 @@ export class LexerNode {
});
this._functionDefinitionPrivacyVar?.clear();
+ this._functionDefinitionPrivacyVar = null;
+
+ this._children = [];
+
this._parent = null;
+
+ this._definedNames = [];
}
getDefinedNames() {
diff --git a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
index 15a02a3fee..51c2fd043a 100644
--- a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
@@ -50,7 +50,7 @@ enum bracketType {
LAMBDA,
}
-const FORMULA_CACHE_LRU_COUNT = 100000;
+const FORMULA_CACHE_LRU_COUNT = 2000;
export const FormulaLexerNodeCache = new FormulaAstLRU<LexerNode>(FORMULA_CACHE_LRU_COUNT);
diff --git a/packages/engine-formula/src/engine/analysis/parser.ts b/packages/engine-formula/src/engine/analysis/parser.ts
index ce8bf40e0e..f412c518f5 100644
--- a/packages/engine-formula/src/engine/analysis/parser.ts
+++ b/packages/engine-formula/src/engine/analysis/parser.ts
@@ -50,10 +50,6 @@ import { LexerNode } from './lexer-node';
export class AstTreeBuilder extends Disposable {
private _astNodeFactoryList: AstRootNodeFactory[] = [];
- private _refOffsetX = 0;
-
- private _refOffsetY = 0;
-
constructor(
@IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,
@Inject(AstRootNodeFactory) private readonly _astRootNodeFactory: AstRootNodeFactory,
diff --git a/packages/engine-formula/src/engine/ast-node/ast-root-node.ts b/packages/engine-formula/src/engine/ast-node/ast-root-node.ts
index 05010c4faa..322fc18178 100644
--- a/packages/engine-formula/src/engine/ast-node/ast-root-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/ast-root-node.ts
@@ -32,6 +32,7 @@ export class AstRootNode extends BaseAstNode {
if (children.length > 1) {
this.setValue(ErrorValueObject.create(ErrorType.VALUE));
+
return;
}
diff --git a/packages/engine-formula/src/engine/ast-node/base-ast-node.ts b/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
index acf0d33089..a7d458510c 100644
--- a/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
@@ -34,7 +34,7 @@ export type LambdaPrivacyVarType = Map<string, Nullable<BaseAstNode>>;
export class BaseAstNode {
private _children: BaseAstNode[] = [];
- private _definedNames: Array<string> = [];
+ private _definedNames: Nullable<Array<string>>;
private _parent: Nullable<BaseAstNode>;
@@ -58,6 +58,12 @@ export class BaseAstNode {
});
this._valueObject?.dispose();
+ this._valueObject = null;
+
+ this._children = [];
+
+ this._definedNames = null;
+
this._parent = null;
}
@@ -164,12 +170,16 @@ export class BaseAstNode {
}
hasDefinedName(definedName: string) {
- return this._definedNames.includes(definedName);
+ return this._definedNames?.includes(definedName) || false;
}
setDefinedNames(definedNames: Array<string>) {
this._definedNames = definedNames;
}
+
+ getDefinedNames() {
+ return this._definedNames;
+ }
}
export class ErrorNode extends BaseAstNode {
diff --git a/packages/engine-formula/src/engine/ast-node/function-node.ts b/packages/engine-formula/src/engine/ast-node/function-node.ts
index b5cd2445e8..6075c451b0 100644
--- a/packages/engine-formula/src/engine/ast-node/function-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/function-node.ts
@@ -49,7 +49,7 @@ export class FunctionNode extends BaseAstNode {
private _definedNamesService: IDefinedNamesService,
private _formulaDataModel: FormulaDataModel
) {
- super(token);
+ super('');
if (this._functionExecutor.isAsync()) {
this.setAsync();
@@ -84,7 +84,8 @@ export class FunctionNode extends BaseAstNode {
this._compatibility();
for (let i = 0; i < childrenCount; i++) {
- const object = children[i].getValue();
+ const child = children[i];
+ const object = child.getValue();
if (object == null) {
continue;
}
@@ -106,6 +107,7 @@ export class FunctionNode extends BaseAstNode {
this._setRefData(result);
this.setValue(result);
+
return Promise.resolve(AstNodePromiseType.SUCCESS);
}
@@ -117,7 +119,8 @@ export class FunctionNode extends BaseAstNode {
this._compatibility();
for (let i = 0; i < childrenCount; i++) {
- const object = children[i].getValue();
+ const child = children[i];
+ const object = child.getValue();
if (object == null) {
continue;
@@ -311,6 +314,7 @@ export class ErrorFunctionNode extends BaseAstNode {
override async executeAsync() {
this.setValue(ErrorValueObject.create(ErrorType.NAME) as FunctionVariantType);
+
return Promise.resolve(AstNodePromiseType.SUCCESS);
}
@@ -358,7 +362,7 @@ export class FunctionNodeFactory extends BaseAstNodeFactory {
}
const token = param.getToken();
- const { tokenTrim, minusPrefixNode, atPrefixNode } = prefixHandler(token.trim(), this._functionService, this._injector);
+ const { tokenTrim, minusPrefixNode, atPrefixNode } = prefixHandler(token.trim(), this._functionService, this._runtimeService);
if (!Number.isNaN(Number(tokenTrim)) && !this._isParentUnionNode(param)) {
return ErrorNode.create(ErrorType.VALUE);
diff --git a/packages/engine-formula/src/engine/ast-node/operator-node.ts b/packages/engine-formula/src/engine/ast-node/operator-node.ts
index 2f5a9807cd..633b7aa810 100644
--- a/packages/engine-formula/src/engine/ast-node/operator-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/operator-node.ts
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-import { ErrorType } from '../../basics/error-type';
import type { compareToken } from '../../basics/token';
-import { OPERATOR_TOKEN_COMPARE_SET, OPERATOR_TOKEN_SET, operatorToken } from '../../basics/token';
import type { BaseFunction } from '../../functions/base-function';
-import { FUNCTION_NAMES_MATH } from '../../functions/math/function-names';
import type { Compare } from '../../functions/meta/compare';
+import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
+import { ErrorType } from '../../basics/error-type';
+import { OPERATOR_TOKEN_COMPARE_SET, OPERATOR_TOKEN_SET, operatorToken } from '../../basics/token';
+import { FUNCTION_NAMES_MATH } from '../../functions/math/function-names';
import { FUNCTION_NAMES_META } from '../../functions/meta/function-names';
import { FUNCTION_NAMES_TEXT } from '../../functions/text/function-names';
import { IFunctionService } from '../../services/function.service';
import { LexerNode } from '../analysis/lexer-node';
-import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
import { type BaseValueObject, ErrorValueObject } from '../value-object/base-value-object';
import { NullValueObject } from '../value-object/primitive-object';
import { BaseAstNode, ErrorNode } from './base-ast-node';
@@ -33,10 +33,10 @@ import { NODE_ORDER_MAP, NodeType } from './node-type';
export class OperatorNode extends BaseAstNode {
constructor(
- private _operatorString: string,
+ operatorString: string,
private _functionExecutor: BaseFunction
) {
- super(_operatorString);
+ super(operatorString);
}
override get nodeType() {
@@ -48,8 +48,12 @@ export class OperatorNode extends BaseAstNode {
if (this._functionExecutor.name === FUNCTION_NAMES_META.COMPARE) {
(this._functionExecutor as Compare).setCompareType(this.getToken() as compareToken);
}
- let object1 = children[0]?.getValue();
- let object2 = children[1]?.getValue();
+
+ const child1 = children[0];
+ const child2 = children[1];
+
+ let object1 = child1?.getValue();
+ let object2 = child2?.getValue();
const token = this.getToken();
diff --git a/packages/engine-formula/src/engine/ast-node/prefix-node.ts b/packages/engine-formula/src/engine/ast-node/prefix-node.ts
index e99c53279b..b09377a470 100644
--- a/packages/engine-formula/src/engine/ast-node/prefix-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/prefix-node.ts
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-import type { IAccessor, Nullable } from '@univerjs/core';
+import type { Nullable } from '@univerjs/core';
import type { BaseFunction } from '../../functions/base-function';
import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
import type { BaseValueObject } from '../value-object/base-value-object';
-import { Inject, Injector } from '@univerjs/core';
import { ErrorType } from '../../basics/error-type';
import { prefixToken } from '../../basics/token';
import { FUNCTION_NAMES_META } from '../../functions/meta/function-names';
@@ -34,7 +33,7 @@ import { NODE_ORDER_MAP, NodeType } from './node-type';
export class PrefixNode extends BaseAstNode {
constructor(
- private _accessor: IAccessor,
+ private _runtimeService: IFormulaRuntimeService,
private _operatorString: string,
private _functionExecutor?: Nullable<BaseFunction>
) {
@@ -80,7 +79,7 @@ export class PrefixNode extends BaseAstNode {
return ErrorValueObject.create(ErrorType.VALUE);
}
- const runtimeService = this._accessor.get(IFormulaRuntimeService);
+ const runtimeService = this._runtimeService;
const currentRow = runtimeService.currentRow || 0;
const currentColumn = runtimeService.currentColumn || 0;
@@ -115,7 +114,7 @@ export class PrefixNode extends BaseAstNode {
export class PrefixNodeFactory extends BaseAstNodeFactory {
constructor(
@IFunctionService private readonly _functionService: IFunctionService,
- @Inject(Injector) private readonly _injector: Injector
+ @IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService
) {
super();
}
@@ -140,7 +139,7 @@ export class PrefixNodeFactory extends BaseAstNodeFactory {
if (tokenTrim === prefixToken.MINUS) {
functionName = FUNCTION_NAMES_META.MINUS;
} else if (tokenTrim === prefixToken.AT) {
- return new PrefixNode(this._injector, tokenTrim);
+ return new PrefixNode(this._runtimeService, tokenTrim);
} else {
return;
}
@@ -150,6 +149,6 @@ export class PrefixNodeFactory extends BaseAstNodeFactory {
console.error(`No function ${token}`);
return ErrorNode.create(ErrorType.NAME);
}
- return new PrefixNode(this._injector, tokenTrim, functionExecutor);
+ return new PrefixNode(this._runtimeService, tokenTrim, functionExecutor);
}
}
diff --git a/packages/engine-formula/src/engine/ast-node/reference-node.ts b/packages/engine-formula/src/engine/ast-node/reference-node.ts
index f03637a9bb..7a96908a32 100644
--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts
@@ -14,10 +14,8 @@
* limitations under the License.
*/
-import type { IAccessor, Nullable } from '@univerjs/core';
-import type { BaseReferenceObject } from '../reference-object/base-reference-object';
+import type { Nullable } from '@univerjs/core';
-import { Inject, Injector } from '@univerjs/core';
import { ErrorType } from '../../basics/error-type';
import {
regexTestSingeRange,
@@ -28,12 +26,9 @@ import { matchToken } from '../../basics/token';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
import { IFunctionService } from '../../services/function.service';
import { IFormulaRuntimeService } from '../../services/runtime.service';
-import { ISuperTableService } from '../../services/super-table.service';
import { LexerNode } from '../analysis/lexer-node';
-import { CellReferenceObject } from '../reference-object/cell-reference-object';
-import { ColumnReferenceObject } from '../reference-object/column-reference-object';
-import { RowReferenceObject } from '../reference-object/row-reference-object';
import { prefixHandler } from '../utils/prefixHandler';
+import { getReferenceObjectFromCache, ReferenceObjectType } from '../utils/value-object';
import { ErrorValueObject } from '../value-object/base-value-object';
import { BaseAstNode } from './base-ast-node';
import { BaseAstNodeFactory, DEFAULT_AST_NODE_FACTORY_Z_INDEX } from './base-ast-node-factory';
@@ -44,12 +39,13 @@ export class ReferenceNode extends BaseAstNode {
private _refOffsetY = 0;
constructor(
- private _accessor: IAccessor,
- private _operatorString: string,
- private _referenceObject: BaseReferenceObject,
+ private _currentConfigService: IFormulaCurrentConfigService,
+ private _runtimeService: IFormulaRuntimeService,
+ operatorString: string,
+ private _referenceObjectType: ReferenceObjectType,
private _isPrepareMerge: boolean = false
) {
- super(_operatorString);
+ super(operatorString);
}
override get nodeType() {
@@ -57,35 +53,37 @@ export class ReferenceNode extends BaseAstNode {
}
override execute() {
- const currentConfigService = this._accessor.get(IFormulaCurrentConfigService);
- const runtimeService = this._accessor.get(IFormulaRuntimeService);
+ const currentConfigService = this._currentConfigService;
+ const runtimeService = this._runtimeService;
- this._referenceObject.setDefaultUnitId(runtimeService.currentUnitId);
+ const referenceObject = getReferenceObjectFromCache(this.getToken(), this._referenceObjectType);
- this._referenceObject.setDefaultSheetId(runtimeService.currentSubUnitId);
+ referenceObject.setDefaultUnitId(runtimeService.currentUnitId);
- this._referenceObject.setForcedSheetId(currentConfigService.getSheetNameMap());
+ referenceObject.setDefaultSheetId(runtimeService.currentSubUnitId);
- this._referenceObject.setUnitData(currentConfigService.getUnitData());
+ referenceObject.setForcedSheetId(currentConfigService.getSheetNameMap());
- this._referenceObject.setArrayFormulaCellData(currentConfigService.getArrayFormulaCellData());
+ referenceObject.setUnitData(currentConfigService.getUnitData());
- this._referenceObject.setRuntimeData(runtimeService.getUnitData());
+ referenceObject.setArrayFormulaCellData(currentConfigService.getArrayFormulaCellData());
- this._referenceObject.setUnitStylesData(currentConfigService.getUnitStylesData());
+ referenceObject.setRuntimeData(runtimeService.getUnitData());
- this._referenceObject.setRuntimeArrayFormulaCellData(runtimeService.getRuntimeArrayFormulaCellData());
+ referenceObject.setUnitStylesData(currentConfigService.getUnitStylesData());
- this._referenceObject.setRuntimeFeatureCellData(runtimeService.getRuntimeFeatureCellData());
+ referenceObject.setRuntimeArrayFormulaCellData(runtimeService.getRuntimeArrayFormulaCellData());
+
+ referenceObject.setRuntimeFeatureCellData(runtimeService.getRuntimeFeatureCellData());
const { x, y } = this.getRefOffset();
- this._referenceObject.setRefOffset(x, y);
+ referenceObject.setRefOffset(x, y);
- if (!this._isPrepareMerge && this._referenceObject.isExceedRange()) {
+ if (!this._isPrepareMerge && referenceObject.isExceedRange()) {
this.setValue(ErrorValueObject.create(ErrorType.NAME));
} else {
- this.setValue(this._referenceObject);
+ this.setValue(referenceObject);
}
}
@@ -104,10 +102,9 @@ export class ReferenceNode extends BaseAstNode {
export class ReferenceNodeFactory extends BaseAstNodeFactory {
constructor(
- @ISuperTableService private readonly _superTableService: ISuperTableService,
+ @IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,
@IFormulaRuntimeService private readonly _formulaRuntimeService: IFormulaRuntimeService,
- @IFunctionService private readonly _functionService: IFunctionService,
- @Inject(Injector) private readonly _injector: Injector
+ @IFunctionService private readonly _functionService: IFunctionService
) {
super();
}
@@ -140,7 +137,10 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {
// return true;
// }
- const { tokenTrim, minusPrefixNode, atPrefixNode } = prefixHandler(tokenTrimPre, this._functionService, this._injector);
+ const currentConfigService = this._currentConfigService;
+ const runtimeService = this._formulaRuntimeService;
+
+ const { tokenTrim, minusPrefixNode, atPrefixNode } = prefixHandler(tokenTrimPre, this._functionService, runtimeService);
if (!isLexerNode && tokenTrim.charAt(0) === '"' && tokenTrim.charAt(tokenTrim.length - 1) === '"') {
return;
@@ -148,12 +148,12 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {
let node: Nullable<ReferenceNode>;
if (regexTestSingeRange(tokenTrim)) {
- node = new ReferenceNode(this._injector, tokenTrim, new CellReferenceObject(tokenTrim), isPrepareMerge);
+ node = new ReferenceNode(currentConfigService, runtimeService, tokenTrim, ReferenceObjectType.CELL, isPrepareMerge);
} else if (isLexerNode && this._checkParentIsUnionOperator(param as LexerNode)) {
if (regexTestSingleRow(tokenTrim)) {
- node = new ReferenceNode(this._injector, tokenTrim, new RowReferenceObject(tokenTrim), isPrepareMerge);
+ node = new ReferenceNode(currentConfigService, runtimeService, tokenTrim, ReferenceObjectType.ROW, isPrepareMerge);
} else if (regexTestSingleColumn(tokenTrim)) {
- node = new ReferenceNode(this._injector, tokenTrim, new ColumnReferenceObject(tokenTrim), isPrepareMerge);
+ node = new ReferenceNode(currentConfigService, runtimeService, tokenTrim, ReferenceObjectType.COLUMN, isPrepareMerge);
}
}
// else {
@@ -193,3 +193,4 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {
return param.getParent()?.getParent()?.getToken().trim() === matchToken.COLON;
}
}
+
diff --git a/packages/engine-formula/src/engine/ast-node/suffix-node.ts b/packages/engine-formula/src/engine/ast-node/suffix-node.ts
index 14b3c58873..e4b3037cf8 100644
--- a/packages/engine-formula/src/engine/ast-node/suffix-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/suffix-node.ts
@@ -14,20 +14,19 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
-import { Inject, Injector } from '@univerjs/core';
+import type { BaseFunction } from '../../functions/base-function';
+import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
+import type { CellReferenceObject } from '../reference-object/cell-reference-object';
+import type { BaseValueObject } from '../value-object/base-value-object';
+import { Inject } from '@univerjs/core';
import { ErrorType } from '../../basics/error-type';
import { suffixToken } from '../../basics/token';
-import type { BaseFunction } from '../../functions/base-function';
import { FUNCTION_NAMES_META } from '../../functions/meta/function-names';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
import { IFunctionService } from '../../services/function.service';
import { Lexer } from '../analysis/lexer';
import { LexerNode } from '../analysis/lexer-node';
-import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
-import type { CellReferenceObject } from '../reference-object/cell-reference-object';
-import type { BaseValueObject } from '../value-object/base-value-object';
import { ErrorValueObject } from '../value-object/base-value-object';
import { NumberValueObject } from '../value-object/primitive-object';
import { BaseAstNode, ErrorNode } from './base-ast-node';
@@ -36,7 +35,8 @@ import { NODE_ORDER_MAP, NodeType } from './node-type';
export class SuffixNode extends BaseAstNode {
constructor(
- private _accessor: IAccessor,
+ private _currentConfigService: IFormulaCurrentConfigService,
+ private _lexer: Lexer,
private _operatorString: string,
private _functionExecutor?: BaseFunction
) {
@@ -91,15 +91,15 @@ export class SuffixNode extends BaseAstNode {
return ErrorValueObject.create(ErrorType.VALUE);
}
- const currentConfigService = this._accessor.get(IFormulaCurrentConfigService);
+ // const currentConfigService = this._accessor.get(IFormulaCurrentConfigService);
- const lexer = this._accessor.get(Lexer);
+ // const lexer = this._accessor.get(Lexer);
const cellValue = value as CellReferenceObject;
const range = cellValue.getRangePosition();
const unitId = cellValue.getUnitId();
const sheetId = cellValue.getSheetId();
- const formulaData = currentConfigService.getFormulaData();
+ const formulaData = this._currentConfigService.getFormulaData();
const formulaString = formulaData?.[unitId]?.[sheetId]?.[range.startRow]?.[range.startColumn]?.f;
@@ -107,7 +107,7 @@ export class SuffixNode extends BaseAstNode {
return ErrorValueObject.create(ErrorType.VALUE);
}
- const lexerNode = lexer.treeBuilder(formulaString);
+ const lexerNode = this._lexer.treeBuilder(formulaString);
return ErrorValueObject.create(ErrorType.VALUE);
/** todo */
@@ -117,7 +117,8 @@ export class SuffixNode extends BaseAstNode {
export class SuffixNodeFactory extends BaseAstNodeFactory {
constructor(
@IFunctionService private readonly _functionService: IFunctionService,
- @Inject(Injector) private readonly _injector: Injector
+ @Inject(Lexer) private readonly _lexer: Lexer,
+ @IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService
) {
super();
}
@@ -141,7 +142,7 @@ export class SuffixNodeFactory extends BaseAstNodeFactory {
if (tokenTrim === suffixToken.PERCENTAGE) {
functionName = FUNCTION_NAMES_META.DIVIDED;
} else if (tokenTrim === suffixToken.POUND) {
- return new SuffixNode(this._injector, tokenTrim);
+ return new SuffixNode(this._currentConfigService, this._lexer, tokenTrim);
} else {
return;
}
@@ -151,6 +152,6 @@ export class SuffixNodeFactory extends BaseAstNodeFactory {
console.error(`No function ${param}`);
return ErrorNode.create(ErrorType.NAME);
}
- return new SuffixNode(this._injector, tokenTrim, functionExecutor);
+ return new SuffixNode(this._currentConfigService, this._lexer, tokenTrim, functionExecutor);
}
}
diff --git a/packages/engine-formula/src/engine/ast-node/union-node.ts b/packages/engine-formula/src/engine/ast-node/union-node.ts
index a44885903e..3fe245239f 100644
--- a/packages/engine-formula/src/engine/ast-node/union-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/union-node.ts
@@ -14,11 +14,12 @@
* limitations under the License.
*/
+import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
import { ErrorType } from '../../basics/error-type';
import { matchToken } from '../../basics/token';
import { IFunctionService } from '../../services/function.service';
import { LexerNode } from '../analysis/lexer-node';
-import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
+import { getRangeReferenceObjectFromCache } from '../utils/value-object';
import { ErrorValueObject } from '../value-object/base-value-object';
import { BaseAstNode } from './base-ast-node';
import { BaseAstNodeFactory, DEFAULT_AST_NODE_FACTORY_Z_INDEX } from './base-ast-node-factory';
@@ -27,8 +28,8 @@ import { NODE_ORDER_MAP, NodeType } from './node-type';
// const UNION_EXECUTOR_NAME = 'UNION';
export class UnionNode extends BaseAstNode {
- constructor(private _operatorString: string) {
- super(_operatorString);
+ constructor(operatorString: string) {
+ super(operatorString);
}
override get nodeType() {
@@ -37,15 +38,17 @@ export class UnionNode extends BaseAstNode {
override execute() {
const children = this.getChildren();
- const leftNode = children[0].getValue();
- const rightNode = children[1].getValue();
+ const leftChild = children[0];
+ const rightChild = children[1];
+ const leftNode = leftChild.getValue();
+ const rightNode = rightChild.getValue();
if (leftNode == null || rightNode == null) {
throw new Error('leftNode and rightNode');
}
let result: FunctionVariantType;
- if (this._operatorString === matchToken.COLON) {
+ if (this.getToken() === matchToken.COLON) {
result = this._unionFunction(leftNode, rightNode) as FunctionVariantType;
} else {
result = ErrorValueObject.create(ErrorType.NAME);
@@ -66,18 +69,21 @@ export class UnionNode extends BaseAstNode {
variant2 = variant2 as BaseReferenceObject;
- if (variant1.isCell() && variant2.isCell()) {
- return variant1.unionBy(variant2);
- }
- if (variant1.isRow() && variant2.isRow()) {
- return variant1.unionBy(variant2);
- }
- if (variant1.isColumn() && variant2.isColumn()) {
- return variant1.unionBy(variant2);
- }
+ return getRangeReferenceObjectFromCache(variant1, variant2);
+
+ // if (variant1.isCell() && variant2.isCell()) {
+
+ // return variant1.unionBy(variant2);
+ // }
+ // if (variant1.isRow() && variant2.isRow()) {
+ // return variant1.unionBy(variant2);
+ // }
+ // if (variant1.isColumn() && variant2.isColumn()) {
+ // return variant1.unionBy(variant2);
+ // }
- // =A1:A gets #NAME?
- return ErrorValueObject.create(ErrorType.NAME);
+ // // =A1:A gets #NAME?
+ // return ErrorValueObject.create(ErrorType.NAME);
}
}
diff --git a/packages/engine-formula/src/engine/ast-node/value-node.ts b/packages/engine-formula/src/engine/ast-node/value-node.ts
index a6f8b75bf9..c71589c71f 100644
--- a/packages/engine-formula/src/engine/ast-node/value-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/value-node.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { BooleanValue } from '../../basics/common';
import type { ErrorType } from '../../basics/error-type';
+import { BooleanValue } from '../../basics/common';
import { ERROR_TYPE_SET } from '../../basics/error-type';
import { LexerNode } from '../analysis/lexer-node';
import { ValueObjectFactory } from '../value-object/array-value-object';
@@ -24,8 +24,8 @@ import { BaseAstNodeFactory, DEFAULT_AST_NODE_FACTORY_Z_INDEX } from './base-ast
import { NODE_ORDER_MAP, NodeType } from './node-type';
export class ValueNode extends BaseAstNode {
- constructor(private _operatorString: string) {
- super(_operatorString);
+ constructor(operatorString: string) {
+ super(operatorString);
}
override get nodeType(): NodeType {
@@ -33,7 +33,7 @@ export class ValueNode extends BaseAstNode {
}
override execute(): void {
- this.setValue(ValueObjectFactory.create(this._operatorString));
+ this.setValue(ValueObjectFactory.create(this.getToken()));
}
}
diff --git a/packages/engine-formula/src/engine/dependency/dependency-tree.ts b/packages/engine-formula/src/engine/dependency/dependency-tree.ts
index 1428b387d7..25bebf6f4b 100644
--- a/packages/engine-formula/src/engine/dependency/dependency-tree.ts
+++ b/packages/engine-formula/src/engine/dependency/dependency-tree.ts
@@ -14,18 +14,17 @@
* limitations under the License.
*/
-import type { IRange, IRTreeItem, IUnitRange, Nullable } from '@univerjs/core';
import type {
IDirtyUnitSheetNameMap,
IFeatureDirtyRangeType,
IRuntimeUnitDataType,
IUnitExcludedCell,
} from '../../basics/common';
-
import type { IFormulaDirtyData } from '../../services/current-data.service';
import type { IAllRuntimeData } from '../../services/runtime.service';
-import type { IExecuteAstNodeData } from '../utils/ast-node-tool';
+import type { AstRootNode } from '../ast-node';
+import { type IRange, type IUnitRange, moveRangeByOffset, type Nullable } from '@univerjs/core';
export enum FDtreeStateType {
DEFAULT,
@@ -33,105 +32,322 @@ export enum FDtreeStateType {
SKIP,
}
+export enum FormulaDependencyTreeType {
+ NORMAL_FORMULA,
+ OTHER_FORMULA,
+ FEATURE_FORMULA,
+}
+
// export interface IUnitRangeWithToken {
// gridRange: IUnitRange;
// token: string;
// }
-/**
- * A dependency tree, capable of calculating mutual dependencies,
- * is used to determine the order of formula calculations.
- */
-export class FormulaDependencyTree {
- treeId: number = -1;
+class FormulaDependencyTreeCalculator {
+ private _state = FDtreeStateType.DEFAULT;
+
+ resetState() {
+ this._state = FDtreeStateType.DEFAULT;
+ }
+
+ setAdded() {
+ this._state = FDtreeStateType.ADDED;
+ }
+
+ isAdded() {
+ return this._state === FDtreeStateType.ADDED;
+ }
+
+ setSkip() {
+ this._state = FDtreeStateType.SKIP;
+ }
+
+ isSkip() {
+ return this._state === FDtreeStateType.SKIP;
+ }
- nodeData: Nullable<IExecuteAstNodeData>;
+ treeId: number;
children: Set<number> = new Set();
parents: Set<number> = new Set();
- formula: string = '';
+ pushChildren(tree: FormulaDependencyTreeCalculator) {
+ this.children.add(tree.treeId);
+ tree._pushParent(this);
+ }
- row: number = -1;
+ hasChildren(treeId: number) {
+ return this.children.has(treeId);
+ }
- column: number = -1;
+ private _pushParent(tree: FormulaDependencyTreeCalculator) {
+ this.parents.add(tree.treeId);
+ }
+}
- rowCount: number = Number.NEGATIVE_INFINITY;
+type GetDirtyDataType = Nullable<
+ (dirtyData: IFormulaDirtyData, runtimeData: IAllRuntimeData) => {
+ runtimeCellData: IRuntimeUnitDataType;
+ dirtyRanges: IFeatureDirtyRangeType;
+ }
+>;
+export type IFormulaDependencyTree = FormulaDependencyTree | FormulaDependencyTreeVirtual;
- columnCount: number = Number.NEGATIVE_INFINITY;
+export class FormulaDependencyTreeVirtual extends FormulaDependencyTreeCalculator {
+ refTree: Nullable<FormulaDependencyTree>;
+ refOffsetX: number = -1;
+ refOffsetY: number = -1;
+ isCache: boolean = false;
+ isDirty: boolean = false;
- subUnitId: string = '';
+ get isVirtual() {
+ return true;
+ }
- unitId: string = '';
+ get row() {
+ if (this.refTree == null) {
+ return -1;
+ }
+ return this.refTree.row + this.refOffsetY;
+ }
- rangeList: IUnitRange[] = [];
+ get column() {
+ if (this.refTree == null) {
+ return -1;
+ }
+ return this.refTree.column + this.refOffsetX;
+ }
- formulaId: Nullable<string>;
+ get rowCount() {
+ if (this.refTree == null) {
+ return 0;
+ }
+ return this.refTree.rowCount;
+ }
- featureId: Nullable<string>;
+ get columnCount() {
+ if (this.refTree == null) {
+ return 0;
+ }
+ return this.refTree.columnCount;
+ }
- isCache: boolean = false;
+ get unitId() {
+ if (this.refTree == null) {
+ return '';
+ }
+ return this.refTree.unitId;
+ }
- constructor(treeId: number) {
- this.treeId = treeId;
+ get subUnitId() {
+ if (this.refTree == null) {
+ return '';
+ }
+ return this.refTree.subUnitId;
}
- toJson() {
+ get formula() {
+ return this.refTree?.formula ?? '';
+ }
+
+ get nodeData() {
return {
- formula: this.formula,
- row: this.row,
- column: this.column,
- subUnitId: this.subUnitId,
- unitId: this.unitId,
- formulaId: this.formulaId,
- featureId: this.featureId,
+ node: this.node,
+ refOffsetX: this.refOffsetX,
+ refOffsetY: this.refOffsetY,
};
}
- getDirtyData: Nullable<
- (dirtyData: IFormulaDirtyData, runtimeData: IAllRuntimeData) => {
- runtimeCellData: IRuntimeUnitDataType;
- dirtyRanges: IFeatureDirtyRangeType;
+ get node() {
+ return this.refTree?.node;
+ }
+
+ dispose() {
+ this.refTree = null;
+ }
+
+ get rangeList() {
+ const unitRangeList = [];
+ if (this.refTree == null) {
+ return [];
}
- >;
+ for (let i = 0; i < this.refTree.rangeList.length; i++) {
+ const range = this.refTree.rangeList[i];
+ unitRangeList.push({
+ unitId: range.unitId,
+ sheetId: range.sheetId,
+ range: moveRangeByOffset(range.range, this.refOffsetX, this.refOffsetY),
+ });
+ }
+ return unitRangeList;
+ }
- private _state = FDtreeStateType.DEFAULT;
+ toRTreeItem(): IUnitRange[] {
+ const currentRow = this.row;
+ const currentColumn = this.column;
- dispose(): void {
- // this.children.forEach((tree) => {
- // tree.dispose();
- // });
+ return [{
+ unitId: this.unitId,
+ sheetId: this.subUnitId,
+ range: {
+ startRow: currentRow,
+ startColumn: currentColumn,
+ endRow: currentRow,
+ endColumn: currentColumn,
+ },
+ }];
+ }
- this.children.clear();
+ inRangeData(range: IRange) {
+ const startRow = range.startRow;
+ const startColumn = range.startColumn;
+ const endRow = range.endRow;
+ const endColumn = range.endColumn;
- this.rangeList = [];
+ const currentRow = this.row;
+ const currentColumn = this.column;
- this.parents.clear();
+ if (currentRow < startRow || currentRow > endRow || currentColumn < startColumn || currentColumn > endColumn) {
+ return false;
+ }
- this.nodeData?.node.dispose();
+ return true;
+ }
- this.nodeData = null;
+ dependencySheetName(dirtyUnitSheetNameMap?: IDirtyUnitSheetNameMap) {
+ if (this.refTree == null) {
+ return false;
+ }
+ return this.refTree.dependencySheetName(dirtyUnitSheetNameMap);
}
- resetState() {
- this._state = FDtreeStateType.DEFAULT;
+ isExcludeRange(unitExcludedCell: Nullable<IUnitExcludedCell>) {
+ const rangeList = this.rangeList;
+
+ if (rangeList.length === 0) {
+ return false;
+ }
+
+ for (let r = 0, len = rangeList.length; r < len; r++) {
+ const unitRange = rangeList[r];
+ const { unitId, sheetId, range } = unitRange;
+
+ const excludedCell = unitExcludedCell?.[unitId]?.[sheetId];
+ let { startRow: rangeStartRow, endRow: rangeEndRow, startColumn: rangeStartColumn, endColumn: rangeEndColumn } = range;
+
+ if (Number.isNaN(rangeStartRow)) {
+ rangeStartRow = 0;
+ }
+ if (Number.isNaN(rangeStartColumn)) {
+ rangeStartColumn = 0;
+ }
+ if (Number.isNaN(rangeEndRow)) {
+ rangeEndRow = Number.POSITIVE_INFINITY;
+ }
+ if (Number.isNaN(rangeEndColumn)) {
+ rangeEndColumn = Number.POSITIVE_INFINITY;
+ }
+
+ let isInclude = false;
+
+ excludedCell?.forValue((row, column) => {
+ if (row >= rangeStartRow && row <= rangeEndRow && column >= rangeStartColumn && column <= rangeEndColumn) {
+ isInclude = true;
+ return false;
+ }
+ });
+
+ if (isInclude) {
+ return true;
+ }
+ }
+ return false;
}
- setAdded() {
- this._state = FDtreeStateType.ADDED;
+ getDirtyData: GetDirtyDataType;
+
+ featureId: Nullable<string>;
+ get formulaId() {
+ if (this.refTree == null) {
+ return '';
+ }
+ return this.refTree.formulaId;
}
+}
- isAdded() {
- return this._state === FDtreeStateType.ADDED;
+/**
+ * A dependency tree, capable of calculating mutual dependencies,
+ * is used to determine the order of formula calculations.
+ */
+export class FormulaDependencyTree extends FormulaDependencyTreeCalculator {
+ isCache: boolean = false;
+
+ featureId: Nullable<string>;
+ featureDirtyRanges: IUnitRange[] = [];
+
+ refOffsetX: number = 0;
+ refOffsetY: number = 0;
+
+ type: FormulaDependencyTreeType = FormulaDependencyTreeType.NORMAL_FORMULA;
+
+ formulaId: Nullable<string>;
+
+ subUnitId: string = '';
+
+ unitId: string = '';
+
+ rangeList: IUnitRange[] = [];
+
+ formula: string = '';
+
+ row: number = -1;
+
+ column: number = -1;
+
+ rowCount: number = Number.NEGATIVE_INFINITY;
+
+ columnCount: number = Number.NEGATIVE_INFINITY;
+
+ isDirty: boolean = false;
+
+ node: Nullable<AstRootNode>;
+
+ constructor(treeId: number) {
+ super();
+ this.treeId = treeId;
}
- setSkip() {
- this._state = FDtreeStateType.SKIP;
+ get isVirtual() {
+ return false;
}
- isSkip() {
- return this._state === FDtreeStateType.SKIP;
+ get nodeData() {
+ return {
+ node: this.node,
+ refOffsetX: 0,
+ refOffsetY: 0,
+ };
+ }
+
+ toJson() {
+ return {
+ formula: this.formula,
+ refOffsetX: this.refOffsetX,
+ refOffsetY: this.refOffsetY,
+ };
+ }
+
+ getDirtyData: GetDirtyDataType;
+
+ dispose(): void {
+ this.featureDirtyRanges = [];
+
+ this.rangeList = [];
+
+ // this.nodeData?.node.dispose();
+
+ this.getDirtyData = null;
}
inRangeData(range: IRange) {
@@ -140,7 +356,10 @@ export class FormulaDependencyTree {
const endRow = range.endRow;
const endColumn = range.endColumn;
- if (this.row < startRow || this.row > endRow || this.column < startColumn || this.column > endColumn) {
+ const currentRow = this.row;
+ const currentColumn = this.column;
+
+ if (currentRow < startRow || currentRow > endRow || currentColumn < startColumn || currentColumn > endColumn) {
return false;
}
@@ -148,12 +367,14 @@ export class FormulaDependencyTree {
}
dependencySheetName(dirtyUnitSheetNameMap?: IDirtyUnitSheetNameMap) {
- if (this.rangeList.length === 0 || dirtyUnitSheetNameMap == null) {
+ const rangeList = this.rangeList;
+
+ if (rangeList.length === 0 || dirtyUnitSheetNameMap == null) {
return false;
}
- for (let r = 0, len = this.rangeList.length; r < len; r++) {
- const unitRange = this.rangeList[r];
+ for (let r = 0, len = rangeList.length; r < len; r++) {
+ const unitRange = rangeList[r];
const { unitId, sheetId } = unitRange;
/**
@@ -169,12 +390,14 @@ export class FormulaDependencyTree {
}
isExcludeRange(unitExcludedCell: Nullable<IUnitExcludedCell>) {
- if (this.rangeList.length === 0) {
+ const rangeList = this.rangeList;
+
+ if (rangeList.length === 0) {
return false;
}
- for (let r = 0, len = this.rangeList.length; r < len; r++) {
- const unitRange = this.rangeList[r];
+ for (let r = 0, len = rangeList.length; r < len; r++) {
+ const unitRange = rangeList[r];
const { unitId, sheetId, range } = unitRange;
const excludedCell = unitExcludedCell?.[unitId]?.[sheetId];
@@ -209,10 +432,10 @@ export class FormulaDependencyTree {
return false;
}
- pushChildren(tree: FormulaDependencyTree) {
- this.children.add(tree.treeId);
- tree._pushParent(this);
- }
+ // pushChildren(tree: FormulaDependencyTree) {
+ // this.children.add(tree.treeId);
+ // tree._pushParent(this);
+ // }
/**
* Add the range corresponding to the current ast node.
@@ -222,52 +445,62 @@ export class FormulaDependencyTree {
this.rangeList.push(...ranges);
}
- hasChildren(treeId: number) {
- return this.children.has(treeId);
+ shouldBePushRangeList() {
+ return this.rangeList.length === 0 && this.type !== FormulaDependencyTreeType.FEATURE_FORMULA;
}
- toRTreeItem(): IRTreeItem {
- return {
+ // hasChildren(treeId: number) {
+ // return this.children.has(treeId);
+ // }
+
+ toRTreeItem(): IUnitRange[] {
+ if (this.featureId != null) {
+ return this.featureDirtyRanges;
+ }
+
+ const currentRow = this.row;
+ const currentColumn = this.column;
+
+ return [{
unitId: this.unitId,
sheetId: this.subUnitId,
range: {
- startRow: this.row,
- startColumn: this.column,
- endRow: this.row,
- endColumn: this.column,
+ startRow: currentRow,
+ startColumn: currentColumn,
+ endRow: currentRow,
+ endColumn: currentColumn,
},
- id: this.treeId,
- };
+ }];
}
/**
* Determine whether it is dependent on other trees.
* @param dependenceTree
*/
- dependency(dependenceTree: FormulaDependencyTree) {
- if (this.rangeList.length === 0) {
- return false;
- }
-
- for (let r = 0, len = this.rangeList.length; r < len; r++) {
- const unitRange = this.rangeList[r];
- const unitId = unitRange.unitId;
- const sheetId = unitRange.sheetId;
- const range = unitRange.range;
-
- if (
- dependenceTree.unitId === unitId &&
- dependenceTree.subUnitId === sheetId &&
- dependenceTree.inRangeData(range)
- ) {
- return true;
- }
- }
-
- return false;
- }
-
- private _pushParent(tree: FormulaDependencyTree) {
- this.parents.add(tree.treeId);
- }
+ // dependency(dependenceTree: FormulaDependencyTree) {
+ // if (this.rangeList.length === 0) {
+ // return false;
+ // }
+
+ // for (let r = 0, len = this.rangeList.length; r < len; r++) {
+ // const unitRange = this.rangeList[r];
+ // const unitId = unitRange.unitId;
+ // const sheetId = unitRange.sheetId;
+ // const range = unitRange.range;
+
+ // if (
+ // dependenceTree.unitId === unitId &&
+ // dependenceTree.subUnitId === sheetId &&
+ // dependenceTree.inRangeData(range)
+ // ) {
+ // return true;
+ // }
+ // }
+
+ // return false;
+ // }
+
+ // private _pushParent(tree: FormulaDependencyTree) {
+ // this.parents.add(tree.treeId);
+ // }
}
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 459580838b..b596e487d1 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -15,20 +15,18 @@
*/
import type { IRange, IUnitRange, Nullable } from '@univerjs/core';
-import type { IFeatureDirtyRangeType, IFormulaData, IOtherFormulaData, IUnitData } from '../../basics/common';
+import type { IFeatureDirtyRangeType, IFormulaData, IFormulaDataItem, IOtherFormulaData, IUnitData } from '../../basics/common';
-import type { ErrorType } from '../../basics/error-type';
import type { IFormulaDirtyData } from '../../services/current-data.service';
import type { IFeatureCalculationManagerParam } from '../../services/feature-calculation-manager.service';
import type { IAllRuntimeData } from '../../services/runtime.service';
-import type { LexerNode } from '../analysis/lexer-node';
-import type { AstRootNode, FunctionNode, PrefixNode, SuffixNode } from '../ast-node';
+import type { FunctionNode, PrefixNode, SuffixNode } from '../ast-node';
import type { BaseAstNode } from '../ast-node/base-ast-node';
import type { BaseReferenceObject } from '../reference-object/base-reference-object';
+import type { IExecuteAstNodeData } from '../utils/ast-node-tool';
import type { PreCalculateNodeType } from '../utils/node-type';
-import { Disposable, Inject, moveRangeByOffset, ObjectMatrix } from '@univerjs/core';
-import { FormulaAstLRU } from '../../basics/cache-lru';
-import { ERROR_TYPE_SET } from '../../basics/error-type';
+import type { IFormulaDependencyTree } from './dependency-tree';
+import { Disposable, Inject, ObjectMatrix } from '@univerjs/core';
import { prefixToken, suffixToken } from '../../basics/token';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
import { IDependencyManagerService } from '../../services/dependency-manager.service';
@@ -37,13 +35,12 @@ import { IOtherFormulaManagerService } from '../../services/other-formula-manage
import { IFormulaRuntimeService } from '../../services/runtime.service';
import { Lexer } from '../analysis/lexer';
import { AstTreeBuilder } from '../analysis/parser';
-import { ErrorNode } from '../ast-node/base-ast-node';
import { NodeType } from '../ast-node/node-type';
import { Interpreter } from '../interpreter/interpreter';
-import { generateExecuteAstNodeData, type IExecuteAstNodeData } from '../utils/ast-node-tool';
-import { FormulaDependencyTree } from './dependency-tree';
+import { generateAstNode, includeDefinedName } from '../utils/generate-ast-node';
+import { FormulaDependencyTree, FormulaDependencyTreeType, FormulaDependencyTreeVirtual } from './dependency-tree';
-const FORMULA_CACHE_LRU_COUNT = 100000;
+const FORMULA_CACHE_LRU_COUNT = 5000;
interface IFeatureFormulaParam {
unitId: string;
@@ -57,7 +54,6 @@ function generateRandomDependencyTreeId(dependencyManagerService: IDependencyMan
}
export class FormulaDependencyGenerator extends Disposable {
- private _formulaASTCache = new FormulaAstLRU<AstRootNode>(FORMULA_CACHE_LRU_COUNT);
private _updateRangeFlattenCache = new Map<string, Map<string, IRange[]>>();
constructor(
@@ -75,7 +71,7 @@ export class FormulaDependencyGenerator extends Disposable {
}
override dispose(): void {
- this._formulaASTCache.clear();
+ this._updateRangeFlattenCache.clear();
}
async generate() {
@@ -131,6 +127,136 @@ export class FormulaDependencyGenerator extends Disposable {
return Promise.resolve(finalTreeList);
}
+ private _dependencyFeatureCalculation(newTreeList: IFormulaDependencyTree[]) {
+ const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();
+
+ if (featureMap.size === 0) {
+ return;
+ }
+
+ /**
+ * Clear the dependency relationships of all featureCalculation nodes in the tree.
+ * Because each execution requires rebuilding the reverse dependencies,
+ * the previous dependencies may become outdated due to data changes in applications such as pivot tables,
+ * which can result in an outdated dirty mark range.
+ */
+ this._clearFeatureCalculationNode(newTreeList);
+
+ let hasFeatureCalculation = false;
+
+ featureMap.forEach((subUnitMap, _) => {
+ subUnitMap.forEach((featureMap, _) => {
+ featureMap.forEach((params, featureId) => {
+ const { unitId, subUnitId, getDirtyData } = params;
+ const allDependency = getDirtyData(this._currentConfigService.getDirtyData() as IFormulaDirtyData, this._runtimeService.getAllRuntimeData() as IAllRuntimeData);
+ const dirtyRanges = this._convertDirtyRangesToUnitRange(allDependency.dirtyRanges);
+ const intersectTrees = this._intersectFeatureCalculation(dirtyRanges, newTreeList, { unitId, subUnitId, featureId });
+ if (intersectTrees.length > 0) {
+ let featureTree = this._getExistTreeList({ unitId, subUnitId, featureId }, newTreeList);
+ if (featureTree == null) {
+ featureTree = this._getFeatureFormulaTree(featureId, generateRandomDependencyTreeId(this._dependencyManagerService), params);
+ newTreeList.push(featureTree);
+ }
+ featureTree.parents = new Set<number>();
+ intersectTrees.forEach((tree) => {
+ if (tree.hasChildren(featureTree!.treeId)) {
+ return;
+ }
+ tree.pushChildren(featureTree!);
+ });
+
+ hasFeatureCalculation = true;
+ }
+ });
+ });
+ });
+
+ return hasFeatureCalculation;
+ }
+
+ private _clearFeatureCalculationNode(newTreeList: IFormulaDependencyTree[]) {
+ const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();
+
+ newTreeList.forEach((tree) => {
+ const newChildren = new Set<number>();
+ for (const childTreeId of tree.children) {
+ const child = this._dependencyManagerService.getTreeById(childTreeId);
+ if (!child) {
+ continue;
+ }
+ if (!child.featureId) {
+ newChildren.add(childTreeId);
+ } else if (!featureMap.get(tree.unitId)?.get(tree.subUnitId)?.has(child.featureId)) {
+ newChildren.add(childTreeId);
+ }
+ }
+ tree.children = newChildren;
+
+ const newParents = new Set<number>();
+ for (const parentTreeId of tree.parents) {
+ const parent = this._dependencyManagerService.getTreeById(parentTreeId);
+ if (!parent) {
+ continue;
+ }
+ if (!parent.featureId) {
+ newParents.add(parentTreeId);
+ } else if (!featureMap.get(tree.unitId)?.get(tree.subUnitId)?.has(parent.featureId)) {
+ newParents.add(parentTreeId);
+ }
+ }
+ tree.parents = newParents;
+ });
+ }
+
+ /**
+ * TODO @DR-Univer: The next step will be to try changing the incoming dirtyRanges to an array, thus avoiding conversion.
+ * @param dirtyRanges
+ * @returns
+ */
+ private _convertDirtyRangesToUnitRange(dirtyRanges: IFeatureDirtyRangeType) {
+ const unitRange: IUnitRange[] = [];
+ for (const unitId in dirtyRanges) {
+ const unitMap = dirtyRanges[unitId];
+ for (const subUnitId in unitMap) {
+ const ranges = unitMap[subUnitId];
+ for (const range of ranges) {
+ unitRange.push({
+ unitId,
+ sheetId: subUnitId,
+ range,
+ });
+ }
+ }
+ }
+ return unitRange;
+ }
+
+ private _intersectFeatureCalculation(dirtyRanges: IUnitRange[], newTreeList: IFormulaDependencyTree[], param: IFeatureFormulaParam) {
+ const dependencyTree = [];
+ const treeIds = this._dependencyManagerService.searchDependency(dirtyRanges);
+ for (let i = 0, len = newTreeList.length; i < len; i++) {
+ const tree = newTreeList[i];
+ if (tree.unitId === param.unitId && tree.subUnitId === param.subUnitId && tree.featureId === param.featureId) {
+ continue;
+ }
+ const isAdded = treeIds.has(tree.treeId);
+ if (isAdded) {
+ dependencyTree.push(tree);
+ }
+ }
+ return dependencyTree;
+ }
+
+ private _getExistTreeList(param: IFeatureFormulaParam, treeList: IFormulaDependencyTree[]) {
+ const { unitId, subUnitId, featureId } = param;
+ for (let i = 0, len = treeList.length; i < len; i++) {
+ const tree = treeList[i];
+ if (tree.unitId === unitId && tree.subUnitId === subUnitId && tree.featureId === featureId) {
+ return tree;
+ }
+ }
+ }
+
private _isCyclicUtil(
treeId: number,
visited: Set<number>,
@@ -159,7 +285,7 @@ export class FormulaDependencyGenerator extends Disposable {
return false;
}
- private _checkIsCycleDependency(treeList: FormulaDependencyTree[]) {
+ private _checkIsCycleDependency(treeList: IFormulaDependencyTree[]) {
const visited = new Set<number>();
const recursionStack = new Set<number>();
@@ -189,26 +315,35 @@ export class FormulaDependencyGenerator extends Disposable {
const otherFormulaDataKeys = Object.keys(otherFormulaData);
- const treeList: FormulaDependencyTree[] = [];
-
- const formulaRefCache = new Map<string, FormulaDependencyTree>();
+ const treeList: IFormulaDependencyTree[] = [];
// Recalculation can only be triggered after clearing the cache. For example, if a calculation error is reported for a non-existent formula and a custom formula is registered later, all formulas need to be calculated forcibly.
const forceCalculate = this._currentConfigService.isForceCalculate();
if (forceCalculate) {
this._dependencyManagerService.reset();
- this._formulaASTCache.clear();
}
- this._registerFormulas(formulaDataKeys, formulaData, unitData, treeList, formulaRefCache);
+ this._registerFormulas(formulaDataKeys, formulaData, unitData, treeList);
- this._registerOtherFormulas(otherFormulaData, otherFormulaDataKeys, treeList, formulaRefCache);
+ this._registerOtherFormulas(otherFormulaData, otherFormulaDataKeys, treeList as FormulaDependencyTree[]);
- this._registerFeatureFormulas(treeList);
+ this._registerFeatureFormulas(treeList as FormulaDependencyTree[]);
for (let i = 0, len = treeList.length; i < len; i++) {
const tree = treeList[i];
+ const node = tree.node;
+
+ if (node == null) {
+ continue;
+ }
+
+ tree.isDirty = this._includeTree(tree, node);
+
+ if (tree.isVirtual) {
+ continue;
+ }
+
this._runtimeService.setCurrent(
tree.row,
tree.column,
@@ -218,52 +353,39 @@ export class FormulaDependencyGenerator extends Disposable {
tree.unitId
);
- const { unitId, formula, nodeData } = tree;
+ const rangeList = await this._getRangeListByNode({
+ node,
+ refOffsetX: tree.refOffsetX,
+ refOffsetY: tree.refOffsetY,
+ });
+ (tree as FormulaDependencyTree).pushRangeList(rangeList);
+ }
- if (nodeData == null) {
+ for (let i = 0, len = treeList.length; i < len; i++) {
+ const tree = treeList[i];
+ if (tree.isCache) {
continue;
}
-
- const { refOffsetX, refOffsetY } = nodeData;
-
- let applyCacheRange = false;
- if (refOffsetX !== 0 || refOffsetY !== 0) {
- const refTreeNode = formulaRefCache.get(`${unitId}${formula}`);
- if (refTreeNode && refTreeNode.rangeList.length > 0) {
- tree.pushRangeList(this._moveRangeList(refTreeNode, refOffsetX, refOffsetY));
- applyCacheRange = true;
- }
- }
-
- if (!applyCacheRange) {
- const rangeList = await this._getRangeListByNode(nodeData);
- tree.pushRangeList(rangeList);
- }
-
- if (!tree.isCache) {
- this._dependencyManagerService.addDependencyRTreeCache(tree);
- }
+ this._dependencyManagerService.addDependencyRTreeCache(tree);
}
- formulaRefCache.clear();
-
return treeList;
}
- private _moveRangeList(tree: FormulaDependencyTree, refOffsetX: number, refOffsetY: number) {
- const rangeList = tree.rangeList;
- const newRangeList = [];
- for (let i = 0, len = rangeList.length; i < len; i++) {
- const unitRange = rangeList[i];
- const newRange = {
- unitId: tree.unitId,
- sheetId: tree.subUnitId,
- range: moveRangeByOffset(unitRange.range, refOffsetX, refOffsetY),
- };
- newRangeList.push(newRange);
- }
- return newRangeList;
- }
+ // private _moveRangeList(tree: FormulaDependencyTree, refOffsetX: number, refOffsetY: number) {
+ // const rangeList = tree.rangeList;
+ // const newRangeList = [];
+ // for (let i = 0, len = rangeList.length; i < len; i++) {
+ // const unitRange = rangeList[i];
+ // const newRange = {
+ // unitId: tree.unitId,
+ // sheetId: tree.subUnitId,
+ // range: moveRangeByOffset(unitRange.range, refOffsetX, refOffsetY),
+ // };
+ // newRangeList.push(newRange);
+ // }
+ // return newRangeList;
+ // }
private _registerFeatureFormulas(treeList: FormulaDependencyTree[]) {
/**
@@ -275,109 +397,140 @@ export class FormulaDependencyGenerator extends Disposable {
featureMap.forEach((subUnitMap, _) => {
subUnitMap.forEach((featureMap, _) => {
featureMap.forEach((params, featureId) => {
- const treeCache = this._dependencyManagerService.getFeatureFormulaDependency(params.unitId, params.subUnitId, featureId);
- if (treeCache) {
- treeCache.isCache = true;
- return;
- }
- treeList.push(this._getFeatureFormulaTree(featureId, params));
+ const treeId = this._dependencyManagerService.getFeatureFormulaDependency(params.unitId, params.subUnitId, featureId);
+ treeList.push(this._getFeatureFormulaTree(featureId, treeId, params));
});
});
});
}
- private _getFeatureFormulaTree(featureId: string, params: IFeatureCalculationManagerParam) {
+ private _getFeatureFormulaTree(featureId: string, treeId: Nullable<number>, params: IFeatureCalculationManagerParam) {
const { unitId, subUnitId, dependencyRanges, getDirtyData } = params;
+ const treeIdNum = treeId || generateRandomDependencyTreeId(this._dependencyManagerService);
+ const FDtree = new FormulaDependencyTree(treeIdNum);
- const FDtree = new FormulaDependencyTree(generateRandomDependencyTreeId(this._dependencyManagerService));
+ // FDtree.unitId = unitId;
+ // FDtree.subUnitId = subUnitId;
FDtree.unitId = unitId;
FDtree.subUnitId = subUnitId;
-
+ FDtree.rangeList = dependencyRanges;
FDtree.getDirtyData = getDirtyData;
+ const allDependency = getDirtyData(this._currentConfigService.getDirtyData() as IFormulaDirtyData, this._runtimeService.getAllRuntimeData() as IAllRuntimeData);
+ const dirtyRanges = this._convertDirtyRangesToUnitRange(allDependency.dirtyRanges);
+
+ FDtree.featureDirtyRanges = dirtyRanges;
+
FDtree.featureId = featureId;
- FDtree.rangeList = dependencyRanges;
+ FDtree.type = FormulaDependencyTreeType.FEATURE_FORMULA;
+
+ // FDtree.rangeList = dependencyRanges;
this._dependencyManagerService.addFeatureFormulaDependency(unitId, subUnitId, featureId, FDtree);
+ const treeCache = this._dependencyManagerService.getFeatureFormulaDependency(params.unitId, params.subUnitId, featureId);
+ if (treeCache) {
+ FDtree.isCache = true;
+ }
+
return FDtree;
}
- private _registerOtherFormulas(otherFormulaData: IOtherFormulaData, otherFormulaDataKeys: string[], treeList: FormulaDependencyTree[], formulaRefCache: Map<string, FormulaDependencyTree>) {
+ private _registerOtherFormulas(otherFormulaData: IOtherFormulaData, otherFormulaDataKeys: string[], treeList: IFormulaDependencyTree[]) {
/**
* Register formulas in doc, slide, and other types of applications.
*/
for (const unitId of otherFormulaDataKeys) {
const subComponentData = otherFormulaData[unitId];
-
if (subComponentData == null) {
continue;
}
-
const subComponentKeys = Object.keys(subComponentData);
-
for (const subUnitId of subComponentKeys) {
const subFormulaData = subComponentData[subUnitId];
-
if (subFormulaData == null) {
continue;
}
-
const subFormulaDataKeys = Object.keys(subFormulaData);
-
for (const subFormulaDataId of subFormulaDataKeys) {
- const treeCache = this._dependencyManagerService.getOtherFormulaDependency(unitId, subUnitId, subFormulaDataId);
+ const hasOtherFormula = this._dependencyManagerService.hasOtherFormulaDataMainData(subFormulaDataId);
const formulaDataItem = subFormulaData[subFormulaDataId];
- const { f: formulaString, x = 0, y = 0 } = formulaDataItem;
-
- if (treeCache) {
- treeCache.isCache = true;
- if (x === 0 && y === 0) {
- formulaRefCache.set(`${unitId}${formulaString}`, treeCache);
- }
- continue;
+ const { f: formulaString, ranges } = formulaDataItem;
+ let isCache = false;
+ if (hasOtherFormula) {
+ isCache = true;
}
-
- const nodeData = this._generateAstNode(unitId, formulaString, x, y);
-
- const FDtree = new FormulaDependencyTree(generateRandomDependencyTreeId(this._dependencyManagerService));
-
- FDtree.nodeData = nodeData;
- FDtree.formula = formulaString;
- FDtree.unitId = unitId;
- FDtree.subUnitId = subUnitId;
-
- FDtree.formulaId = subFormulaDataId;
-
- if (x === 0 && y === 0) {
- formulaRefCache.set(`${unitId}${formulaString}`, FDtree);
+ const node = generateAstNode(unitId, formulaString, this._lexer, this._astTreeBuilder, this._currentConfigService);
+ const { firstRow, firstColumn } = this._getFirstCellOfRange(ranges);
+
+ const treeMatrix = this._dependencyManagerService.getOtherFormulaDependency(unitId, subUnitId, subFormulaDataId);
+ const firstTreeId = treeMatrix?.getValue(0, 0) || generateRandomDependencyTreeId(this._dependencyManagerService);
+ const firstFDtree = new FormulaDependencyTree(firstTreeId);
+
+ for (let i = 0; i < ranges.length; i++) {
+ const range = ranges[i];
+ const { startRow, startColumn, endRow, endColumn } = range;
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ const x = c - firstColumn;
+ const y = r - firstRow;
+ if (x === 0 && y === 0) {
+ firstFDtree.node = node;
+ firstFDtree.formula = formulaString;
+ firstFDtree.unitId = unitId;
+ firstFDtree.subUnitId = subUnitId;
+ firstFDtree.formulaId = subFormulaDataId;
+ firstFDtree.type = FormulaDependencyTreeType.OTHER_FORMULA;
+ firstFDtree.isCache = isCache;
+ treeList.push(firstFDtree);
+ this._dependencyManagerService.addOtherFormulaDependency(unitId, subUnitId, subFormulaDataId, firstFDtree);
+ this._dependencyManagerService.addFormulaDependencyByDefinedName(firstFDtree);
+ continue;
+ }
+
+ const virtual = new FormulaDependencyTreeVirtual();
+ virtual.treeId = treeMatrix?.getValue(x, y) || generateRandomDependencyTreeId(this._dependencyManagerService);
+
+ virtual.refTree = firstFDtree;
+ virtual.refOffsetX = x;
+ virtual.refOffsetY = y;
+ virtual.isCache = isCache;
+ this._dependencyManagerService.addOtherFormulaDependency(unitId, subUnitId, subFormulaDataId, virtual);
+ this._dependencyManagerService.addFormulaDependencyByDefinedName(virtual);
+ treeList.push(virtual);
+ }
+ }
}
-
- this._dependencyManagerService.addOtherFormulaDependency(unitId, subUnitId, subFormulaDataId, FDtree);
-
- treeList.push(FDtree);
+ this._dependencyManagerService.addOtherFormulaDependencyMainData(subFormulaDataId);
}
}
}
}
- private _registerFormulas(formulaDataKeys: string[], formulaData: IFormulaData, unitData: IUnitData, treeList: FormulaDependencyTree[], formulaRefCache: Map<string, FormulaDependencyTree>) {
+ private _getFirstCellOfRange(ranges: IRange[]) {
+ const range = ranges[0];
+ return {
+ firstRow: range.startRow,
+ firstColumn: range.startColumn,
+ };
+ }
+
+ private _registerFormulas(formulaDataKeys: string[], formulaData: IFormulaData, unitData: IUnitData, treeList: IFormulaDependencyTree[]) {
/**
* Register formulas in the sheet.
*/
for (const unitId of formulaDataKeys) {
const sheetData = formulaData[unitId];
-
if (sheetData == null) {
continue;
}
-
const sheetDataKeys = Object.keys(sheetData);
-
for (const sheetId of sheetDataKeys) {
const matrixData = new ObjectMatrix(sheetData[sheetId] || {});
+ const sIdCache = new Map<string, FormulaDependencyTree>();
matrixData.forValue((row, column, formulaDataItem) => {
// const formulaString = formulaDataItem.f;
@@ -385,45 +538,100 @@ export class FormulaDependencyGenerator extends Disposable {
return true;
}
- const { f: formulaString, x = 0, y = 0 } = formulaDataItem;
+ const { x = 0, y = 0, si } = formulaDataItem;
- const treeCache = this._dependencyManagerService.getFormulaDependency(unitId, sheetId, row, column);
- if (treeCache) {
- treeCache.isCache = true;
- if (x === 0 && y === 0) {
- formulaRefCache.set(`${unitId}${formulaString}`, treeCache);
- }
+ if (!(x === 0 && y === 0 && si != null)) {
return true;
}
- const nodeData = this._generateAstNode(unitId, formulaString, x, y);
+ const FDtree = this._createFDtree(unitId, sheetId, row, column, unitData, formulaDataItem);
+
+ const treeId = this._dependencyManagerService.getFormulaDependency(unitId, sheetId, row, column);
+ if (treeId != null) {
+ FDtree.treeId = treeId;
+ } else {
+ this._dependencyManagerService.addFormulaDependency(unitId, sheetId, row, column, FDtree);
+ this._dependencyManagerService.addFormulaDependencyByDefinedName(FDtree);
+ }
+
+ sIdCache.set(si, FDtree);
+ treeList.push(FDtree);
+ });
- const FDtree = new FormulaDependencyTree(generateRandomDependencyTreeId(this._dependencyManagerService));
+ matrixData.forValue((row, column, formulaDataItem) => {
+ // const formulaString = formulaDataItem.f;
+ if (formulaDataItem == null) {
+ return true;
+ }
- const sheetItem = unitData[unitId][sheetId];
+ const { x = 0, y = 0, si } = formulaDataItem;
- FDtree.nodeData = nodeData;
- FDtree.formula = formulaString;
- FDtree.unitId = unitId;
- FDtree.subUnitId = sheetId;
- FDtree.row = row;
- FDtree.column = column;
+ if (x === 0 && y === 0 && si != null) {
+ return true;
+ }
- FDtree.rowCount = sheetItem.rowCount;
- FDtree.columnCount = sheetItem.columnCount;
+ let FDtree: IFormulaDependencyTree;
- if (x === 0 && y === 0) {
- formulaRefCache.set(`${unitId}${formulaString}`, FDtree);
+ if (si && sIdCache.has(si)) {
+ const cache = sIdCache.get(si)!;
+ FDtree = this._createVirtualFDtree(cache as FormulaDependencyTree, formulaDataItem);
+ // FDtree.rangeList = this._moveRangeList(cache, x, y);
+ } else {
+ FDtree = this._createFDtree(unitId, sheetId, row, column, unitData, formulaDataItem);
}
- this._dependencyManagerService.addFormulaDependency(unitId, sheetId, row, column, FDtree);
+ const treeId = this._dependencyManagerService.getFormulaDependency(unitId, sheetId, row, column);
+ if (treeId != null) {
+ FDtree.treeId = treeId;
+ } else {
+ this._dependencyManagerService.addFormulaDependency(unitId, sheetId, row, column, FDtree);
+ this._dependencyManagerService.addFormulaDependencyByDefinedName(FDtree);
+ }
treeList.push(FDtree);
});
+
+ sIdCache.clear();
}
}
}
+ private _createFDtree(unitId: string, sheetId: string, row: number, column: number, unitData: IUnitData, formulaDataItem: IFormulaDataItem) {
+ const { f: formulaString, x = 0, y = 0 } = formulaDataItem;
+
+ const FDtree = new FormulaDependencyTree(generateRandomDependencyTreeId(this._dependencyManagerService));
+
+ const sheetItem = unitData[unitId][sheetId];
+
+ const node = generateAstNode(unitId, formulaString, this._lexer, this._astTreeBuilder, this._currentConfigService);
+
+ FDtree.node = node;
+ FDtree.formula = formulaString;
+ FDtree.unitId = unitId;
+ FDtree.subUnitId = sheetId;
+ FDtree.row = row;
+ FDtree.column = column;
+
+ // FDtree.refOffsetX = x;
+ // FDtree.refOffsetY = y;
+
+ FDtree.rowCount = sheetItem.rowCount;
+ FDtree.columnCount = sheetItem.columnCount;
+
+ return FDtree;
+ }
+
+ private _createVirtualFDtree(tree: FormulaDependencyTree, formulaDataItem: IFormulaDataItem) {
+ const { x = 0, y = 0 } = formulaDataItem;
+ const virtual = new FormulaDependencyTreeVirtual();
+ virtual.treeId = generateRandomDependencyTreeId(this._dependencyManagerService);
+ virtual.refTree = tree;
+ virtual.refOffsetX = x;
+ virtual.refOffsetY = y;
+
+ return virtual;
+ }
+
/**
* Break down the dirty areas into ranges for subsequent matching.
*/
@@ -444,40 +652,6 @@ export class FormulaDependencyGenerator extends Disposable {
}
}
- private _generateAstNode(unitId: string, formulaString: string, refOffsetX: number = 0, refOffsetY: number = 0): IExecuteAstNodeData {
- // refOffsetX and refOffsetY are separated by -, otherwise x:1 y:10 will be repeated with x:11 y:0
- let astNode: Nullable<AstRootNode> = this._formulaASTCache.get(`${unitId}${formulaString}`);
-
- if (astNode && !this._isDirtyDefinedForNode(astNode)) {
- // astNode.setRefOffset(refOffsetX, refOffsetY);
- return generateExecuteAstNodeData(astNode, refOffsetX, refOffsetY);
- }
-
- const lexerNode = this._lexer.treeBuilder(formulaString);
-
- if (ERROR_TYPE_SET.has(lexerNode as ErrorType)) {
- return {
- node: ErrorNode.create(lexerNode as ErrorType),
- refOffsetX,
- refOffsetY,
- };
- }
-
- // suffix Express, 1+(3*4=4)*5+1 convert to 134*4=5*1++
-
- astNode = this._astTreeBuilder.parse(lexerNode as LexerNode);
-
- if (astNode == null) {
- throw new Error('astNode is null');
- }
-
- // astNode.setRefOffset(refOffsetX, refOffsetY);
-
- this._formulaASTCache.set(`${unitId}${formulaString}`, astNode);
-
- return generateExecuteAstNodeData(astNode, refOffsetX, refOffsetY);
- }
-
private _addFlattenCache(unitId: string, sheetId: string, range: IRange) {
let unitMatrix = this._updateRangeFlattenCache.get(unitId);
if (unitMatrix == null) {
@@ -588,10 +762,15 @@ export class FormulaDependencyGenerator extends Disposable {
const refOffsetX = nodeData.refOffsetX;
const refOffsetY = nodeData.refOffsetY;
+ const node = nodeData.node;
+
+ if (node == null) {
+ return [];
+ }
- this._nodeTraversalRef(nodeData.node, preCalculateNodeList);
+ this._nodeTraversalRef(node, preCalculateNodeList);
- this._nodeTraversalReferenceFunction(nodeData.node, referenceFunctionList);
+ this._nodeTraversalReferenceFunction(node, referenceFunctionList);
const rangeList: IUnitRange[] = [];
@@ -605,6 +784,8 @@ export class FormulaDependencyGenerator extends Disposable {
// const token = serializeRangeToRefString({ ...gridRange, sheetName: this._currentConfigService.getSheetName(gridRange.unitId, gridRange.sheetId) });
rangeList.push(gridRange);
+
+ node.setValue(null);
}
for (let i = 0, len = referenceFunctionList.length; i < len; i++) {
@@ -616,60 +797,32 @@ export class FormulaDependencyGenerator extends Disposable {
// const token = serializeRangeToRefString({ ...gridRange, sheetName: this._currentConfigService.getSheetName(gridRange.unitId, gridRange.sheetId) });
rangeList.push(gridRange);
- }
-
- return rangeList;
- }
- private _isDirtyDefinedForNode(node: BaseAstNode) {
- const definedNameMap = this._currentConfigService.getDirtyDefinedNameMap();
- const executeUnitId = this._currentConfigService.getExecuteUnitId();
- if (executeUnitId != null && definedNameMap[executeUnitId] != null) {
- const names = Object.keys(definedNameMap[executeUnitId]!);
- for (let i = 0, len = names.length; i < len; i++) {
- const name = names[i];
- if (node.hasDefinedName(name)) {
- return true;
- }
- }
+ node.setValue(null);
}
- return false;
+ return rangeList;
}
/**
* Build a formula dependency tree based on the dependency relationships.
* @param treeList
*/
- private _getUpdateTreeListAndMakeDependency(treeList: FormulaDependencyTree[]) {
- const newTreeList: FormulaDependencyTree[] = [];
- const existTree = new Set<FormulaDependencyTree>();
+ private _getUpdateTreeListAndMakeDependency(treeList: IFormulaDependencyTree[]) {
+ const newTreeList: IFormulaDependencyTree[] = [];
+ const existTree = new Set<number>();
const forceCalculate = this._currentConfigService.isForceCalculate();
- this._dependencyManagerService.openKdTree();
-
- const allTree: FormulaDependencyTree[] = this._dependencyManagerService.buildDependencyTree(treeList);
+ // const allTree: IFormulaDependencyTree[] = Array.from(this._dependencyTreeCache.values());
const dirtyRanges = this._currentConfigService.getDirtyRanges();
const treeIds = this._dependencyManagerService.searchDependency(dirtyRanges); // RTree Average case is O(logN + k)
- for (let i = 0, len = allTree.length; i < len; i++) {
- const tree = allTree[i];
-
- // if (dependencyAlgorithm) {
- // dependencyTreeCache.dependency(tree);
- // } else {
- // for (let m = 0, mLen = treeList.length; m < mLen; m++) {
- // const treeMatch = treeList[m];
- // if (tree === treeMatch) {
- // continue;
- // }
+ const allTree: IFormulaDependencyTree[] = this._dependencyManagerService.buildDependencyTree(treeList);
- // if (tree.dependency(treeMatch)) {
- // tree.pushChildren(treeMatch);
- // }
- // }
- // }
+ for (const tree of allTree) {
+ // const tree = allTree[i];
+ const treeId = tree.treeId;
/**
* forceCalculate: Mandatory calculation, adding all formulas to dependencies
@@ -679,154 +832,21 @@ export class FormulaDependencyGenerator extends Disposable {
if (
(
forceCalculate ||
+ tree.isDirty ||
tree.dependencySheetName(this._currentConfigService.getDirtyNameMap()) || //O(n) n=tree.rangeList.length
(
- treeIds.has(tree.treeId)// O(1)
+ treeIds.has(treeId)// O(1)
&& !tree.isExcludeRange(this._currentConfigService.getExcludedRange()) //worst O(n^2), best O(n) n^2=tree.rangeList.length*excludedRange.length, excludedRange.length is usually small
- ) ||
- this._includeTree(tree) //O(n) n=tree.rangeList.length
- ) && !existTree.has(tree) //O(1)
+ )
+ ) && !existTree.has(treeId) //O(1)
) {
newTreeList.push(tree);
- existTree.add(tree);
+ existTree.add(treeId);
}
}
-
- this._dependencyManagerService.closeKdTree();
-
return newTreeList;
}
- private _dependencyFeatureCalculation(newTreeList: FormulaDependencyTree[]) {
- const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();
-
- if (featureMap.size === 0) {
- return;
- }
-
- /**
- * Clear the dependency relationships of all featureCalculation nodes in the tree.
- * Because each execution requires rebuilding the reverse dependencies,
- * the previous dependencies may become outdated due to data changes in applications such as pivot tables,
- * which can result in an outdated dirty mark range.
- */
- this._clearFeatureCalculationNode(newTreeList);
-
- let hasFeatureCalculation = false;
-
- featureMap.forEach((subUnitMap, _) => {
- subUnitMap.forEach((featureMap, _) => {
- featureMap.forEach((params, featureId) => {
- const { unitId, subUnitId, getDirtyData } = params;
- const allDependency = getDirtyData(this._currentConfigService.getDirtyData() as IFormulaDirtyData, this._runtimeService.getAllRuntimeData() as IAllRuntimeData);
- const dirtyRanges = this._convertDirtyRangesToUnitRange(allDependency.dirtyRanges);
- const intersectTrees = this._intersectFeatureCalculation(dirtyRanges, newTreeList, { unitId, subUnitId, featureId });
- if (intersectTrees.length > 0) {
- let featureTree = this._getExistTreeList({ unitId, subUnitId, featureId }, newTreeList);
- if (featureTree == null) {
- featureTree = this._getFeatureFormulaTree(featureId, params);
- newTreeList.push(featureTree);
- }
- featureTree.parents = new Set<number>();
- intersectTrees.forEach((tree) => {
- if (tree.hasChildren(featureTree!.treeId)) {
- return;
- }
- tree.pushChildren(featureTree!);
- });
-
- hasFeatureCalculation = true;
- }
- });
- });
- });
-
- return hasFeatureCalculation;
- }
-
- private _clearFeatureCalculationNode(newTreeList: FormulaDependencyTree[]) {
- const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();
-
- newTreeList.forEach((tree) => {
- const newChildren = new Set<number>();
- for (const childTreeId of tree.children) {
- const child = this._dependencyManagerService.getTreeById(childTreeId);
- if (!child) {
- continue;
- }
- if (!child.featureId) {
- newChildren.add(childTreeId);
- } else if (!featureMap.get(tree.unitId)?.get(tree.subUnitId)?.has(child.featureId)) {
- newChildren.add(childTreeId);
- }
- }
- tree.children = newChildren;
-
- const newParents = new Set<number>();
- for (const parentTreeId of tree.parents) {
- const parent = this._dependencyManagerService.getTreeById(parentTreeId);
- if (!parent) {
- continue;
- }
- if (!parent.featureId) {
- newParents.add(parentTreeId);
- } else if (!featureMap.get(tree.unitId)?.get(tree.subUnitId)?.has(parent.featureId)) {
- newParents.add(parentTreeId);
- }
- }
- tree.parents = newParents;
- });
- }
-
- private _getExistTreeList(param: IFeatureFormulaParam, treeList: FormulaDependencyTree[]) {
- const { unitId, subUnitId, featureId } = param;
- for (let i = 0, len = treeList.length; i < len; i++) {
- const tree = treeList[i];
- if (tree.unitId === unitId && tree.subUnitId === subUnitId && tree.featureId === featureId) {
- return tree;
- }
- }
- }
-
- /**
- * TODO @DR-Univer: The next step will be to try changing the incoming dirtyRanges to an array, thus avoiding conversion.
- * @param dirtyRanges
- * @returns
- */
- private _convertDirtyRangesToUnitRange(dirtyRanges: IFeatureDirtyRangeType) {
- const unitRange: IUnitRange[] = [];
- for (const unitId in dirtyRanges) {
- const unitMap = dirtyRanges[unitId];
- for (const subUnitId in unitMap) {
- const ranges = unitMap[subUnitId];
- for (const range of ranges) {
- unitRange.push({
- unitId,
- sheetId: subUnitId,
- range,
- });
- }
- }
- }
- return unitRange;
- }
-
- private _intersectFeatureCalculation(dirtyRanges: IUnitRange[], newTreeList: FormulaDependencyTree[], param: IFeatureFormulaParam) {
- const dependencyTree = [];
- const treeIds = this._dependencyManagerService.searchDependency(dirtyRanges);
- for (let i = 0, len = newTreeList.length; i < len; i++) {
- const tree = newTreeList[i];
- if (tree.unitId === param.unitId && tree.subUnitId === param.subUnitId && tree.featureId === param.featureId) {
- continue;
- }
- const isAdded = treeIds.has(tree.treeId);
- if (isAdded) {
- dependencyTree.push(tree);
- }
- }
- return dependencyTree;
- }
-
private _includeTreeFeature(tree: FormulaDependencyTree) {
const unitId = tree.unitId;
const subUnitId = tree.subUnitId;
@@ -863,23 +883,7 @@ export class FormulaDependencyGenerator extends Disposable {
return false;
}
- private _includeDefinedName(tree: FormulaDependencyTree) {
- /**
- * Detect whether the dirty map contains a defined name.
- */
- const node = tree.nodeData?.node;
- if (node != null) {
- const dirtyDefinedName = this._isDirtyDefinedForNode(node);
- if (dirtyDefinedName) {
- return true;
- }
- }
- return false;
- }
-
- private _detectForcedRecalculationNode(tree: FormulaDependencyTree) {
- const node = tree.nodeData?.node;
-
+ private _detectForcedRecalculationNode(tree: IFormulaDependencyTree, node: Nullable<BaseAstNode>) {
if (node == null) {
return false;
}
@@ -908,26 +912,26 @@ export class FormulaDependencyGenerator extends Disposable {
* If they are within the dirty area, return true, indicating that this node needs to be calculated.
* @param tree
*/
- private _includeTree(tree: FormulaDependencyTree) {
+ private _includeTree(tree: IFormulaDependencyTree, node: BaseAstNode) {
const unitId = tree.unitId;
const subUnitId = tree.subUnitId;
/**
* RAND, RANDBETWEEN, NOW, TODAY are volatile functions that are marked dirty and recalculated every time a calculation occurs.
*/
- if (this._detectForcedRecalculationNode(tree) === true) {
+ if (this._detectForcedRecalculationNode(tree, node) === true) {
return true;
}
- if (this._includeTreeFeature(tree) === true) {
+ if (this._includeTreeFeature(tree as FormulaDependencyTree) === true) {
return true;
}
- if (this._includeOtherFormula(tree) === true) {
+ if (this._includeOtherFormula(tree as FormulaDependencyTree) === true) {
return true;
}
- if (this._includeDefinedName(tree) === true) {
+ if (includeDefinedName(tree, node, this._currentConfigService) === true) {
return true;
}
@@ -937,13 +941,7 @@ export class FormulaDependencyGenerator extends Disposable {
* The position of the primary cell in the array formula needs to be excluded when calculating the impact of the array formula on dependencies.
* This is because its impact was already considered during the first calculation.
*/
- let isExclude = false;
- excludedCell?.forValue((row, column) => {
- if (tree.row === row && tree.column === column) {
- isExclude = true;
- return false;
- }
- });
+ const isExclude = excludedCell?.getValue(tree.row, tree.column) != null;
if (isExclude) {
return false;
@@ -982,10 +980,10 @@ export class FormulaDependencyGenerator extends Disposable {
* Generate the final formula calculation order array by traversing the dependency tree established via depth-first search.
* @param treeList
*/
- private _calculateRunList(treeList: FormulaDependencyTree[]) {
+ private _calculateRunList(treeList: IFormulaDependencyTree[]) {
const stack = treeList;
const formulaRunList = [];
- const cacheStack: FormulaDependencyTree[] = [];
+ const cacheStack: IFormulaDependencyTree[] = [];
while (stack.length > 0) {
const tree = stack.pop();
@@ -1024,6 +1022,6 @@ export class FormulaDependencyGenerator extends Disposable {
}
}
- return formulaRunList.reverse();
+ return formulaRunList;
}
}
diff --git a/packages/engine-formula/src/engine/interpreter/interpreter.ts b/packages/engine-formula/src/engine/interpreter/interpreter.ts
index 8497524d28..5b387af929 100644
--- a/packages/engine-formula/src/engine/interpreter/interpreter.ts
+++ b/packages/engine-formula/src/engine/interpreter/interpreter.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { Nullable } from '@univerjs/core';
import type { BaseAstNode } from '../ast-node/base-ast-node';
import type { FunctionNode } from '../ast-node/function-node';
import type { LambdaNode } from '../ast-node/lambda-node';
@@ -39,7 +40,7 @@ export class Interpreter extends Disposable {
// return ErrorValueObject.create(ErrorType.ERROR);
// }
- if (!nodeData) {
+ if (!nodeData || !nodeData.node) {
return Promise.resolve(ErrorValueObject.create(ErrorType.VALUE));
}
@@ -63,7 +64,7 @@ export class Interpreter extends Disposable {
// return ErrorValueObject.create(ErrorType.ERROR);
// }
- if (!nodeData) {
+ if (!nodeData || !nodeData.node) {
return ErrorValueObject.create(ErrorType.VALUE);
}
@@ -87,7 +88,10 @@ export class Interpreter extends Disposable {
return node.getValue();
}
- checkAsyncNode(node: BaseAstNode) {
+ checkAsyncNode(node: Nullable<BaseAstNode>) {
+ if (node == null) {
+ return false;
+ }
const result: boolean[] = [];
this._checkAsyncNode(node, result);
diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
index 66491dd2e4..bc0ff7b63e 100644
--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
@@ -37,7 +37,7 @@ export type NodeValueType = BaseValueObject | BaseReferenceObject | AsyncObject
export type FunctionVariantType = BaseValueObject | BaseReferenceObject;
-const FORMULA_CACHE_LRU_COUNT = 100000;
+const FORMULA_CACHE_LRU_COUNT = 10000;
export const FORMULA_REF_TO_ARRAY_CACHE = new FormulaAstLRU<ArrayValueObject>(FORMULA_CACHE_LRU_COUNT);
export class BaseReferenceObject extends ObjectClassType {
diff --git a/packages/engine-formula/src/engine/utils/ast-node-tool.ts b/packages/engine-formula/src/engine/utils/ast-node-tool.ts
index 130efc7310..8b04b64f21 100644
--- a/packages/engine-formula/src/engine/utils/ast-node-tool.ts
+++ b/packages/engine-formula/src/engine/utils/ast-node-tool.ts
@@ -18,7 +18,7 @@ import type { Nullable } from '@univerjs/core';
import type { BaseAstNode } from '../ast-node/base-ast-node';
export interface IExecuteAstNodeData {
- node: BaseAstNode;
+ node: Nullable<BaseAstNode>;
refOffsetX: number;
refOffsetY: number;
}
diff --git a/packages/engine-formula/src/engine/utils/generate-ast-node.ts b/packages/engine-formula/src/engine/utils/generate-ast-node.ts
new file mode 100644
index 0000000000..32d83117e0
--- /dev/null
+++ b/packages/engine-formula/src/engine/utils/generate-ast-node.ts
@@ -0,0 +1,91 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable } from '@univerjs/core';
+import type { ErrorType } from '../../basics/error-type';
+import type { IFormulaCurrentConfigService } from '../../services/current-data.service';
+import type { Lexer } from '../analysis/lexer';
+import type { LexerNode } from '../analysis/lexer-node';
+import type { AstTreeBuilder } from '../analysis/parser';
+import type { AstRootNode } from '../ast-node/ast-root-node';
+import type { IFormulaDependencyTree } from '../dependency/dependency-tree';
+import { FormulaAstLRU } from '../../basics/cache-lru';
+import { ERROR_TYPE_SET } from '../../basics/error-type';
+import { type BaseAstNode, ErrorNode } from '../ast-node/base-ast-node';
+
+const FORMULA_CACHE_LRU_COUNT = 5000;
+
+const FORMULA_AST_CACHE = new FormulaAstLRU<AstRootNode>(FORMULA_CACHE_LRU_COUNT);
+
+export function generateAstNode(unitId: string, formulaString: string, lexer: Lexer, astTreeBuilder: AstTreeBuilder, currentConfigService: IFormulaCurrentConfigService): AstRootNode {
+ // refOffsetX and refOffsetY are separated by -, otherwise x:1 y:10 will be repeated with x:11 y:0
+ let astNode: Nullable<AstRootNode> = FORMULA_AST_CACHE.get(`${unitId}${formulaString}`);
+
+ if (astNode && !isDirtyDefinedForNode(astNode, currentConfigService)) {
+ // astNode.setRefOffset(refOffsetX, refOffsetY);
+ return astNode;
+ }
+
+ const lexerNode = lexer.treeBuilder(formulaString);
+
+ if (ERROR_TYPE_SET.has(lexerNode as ErrorType)) {
+ return ErrorNode.create(lexerNode as ErrorType);
+ }
+
+ // suffix Express, 1+(3*4=4)*5+1 convert to 134*4=5*1++
+
+ astNode = astTreeBuilder.parse(lexerNode as LexerNode);
+
+ if (astNode == null) {
+ throw new Error('astNode is null');
+ }
+
+ // astNode.setRefOffset(refOffsetX, refOffsetY);
+
+ FORMULA_AST_CACHE.set(`${unitId}${formulaString}`, astNode);
+
+ return astNode;
+}
+
+function isDirtyDefinedForNode(node: BaseAstNode, currentConfigService: IFormulaCurrentConfigService) {
+ const definedNameMap = currentConfigService.getDirtyDefinedNameMap();
+ const executeUnitId = currentConfigService.getExecuteUnitId();
+ if (executeUnitId != null && definedNameMap[executeUnitId] != null) {
+ const names = Object.keys(definedNameMap[executeUnitId]!);
+ for (let i = 0, len = names.length; i < len; i++) {
+ const name = names[i];
+ if (node.hasDefinedName(name)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+export function includeDefinedName(tree: IFormulaDependencyTree, node: Nullable<AstRootNode>, currentConfigService: IFormulaCurrentConfigService) {
+ /**
+ * Detect whether the dirty map contains a defined name.
+ */
+ // const node = tree.nodeData?.node;
+ if (node != null) {
+ const dirtyDefinedName = isDirtyDefinedForNode(node, currentConfigService);
+ if (dirtyDefinedName) {
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/packages/engine-formula/src/engine/utils/prefixHandler.ts b/packages/engine-formula/src/engine/utils/prefixHandler.ts
index 6857ebd68f..51966047b3 100644
--- a/packages/engine-formula/src/engine/utils/prefixHandler.ts
+++ b/packages/engine-formula/src/engine/utils/prefixHandler.ts
@@ -14,8 +14,9 @@
* limitations under the License.
*/
-import type { Injector, Nullable } from '@univerjs/core';
+import type { Nullable } from '@univerjs/core';
import type { IFunctionService } from '../../services/function.service';
+import type { IFormulaRuntimeService } from '../../services/runtime.service';
import { prefixToken } from '../../basics/token';
import { FUNCTION_NAMES_META } from '../../functions/meta/function-names';
import { PrefixNode } from '../ast-node/prefix-node';
@@ -23,7 +24,7 @@ import { PrefixNode } from '../ast-node/prefix-node';
const minusRegExp = new RegExp(prefixToken.MINUS, 'g');
const atRegExp = new RegExp(prefixToken.AT, 'g');
-export function prefixHandler(tokenTrimParam: string, functionService: IFunctionService, injector: Injector) {
+export function prefixHandler(tokenTrimParam: string, functionService: IFunctionService, runtimeService: IFormulaRuntimeService) {
let minusPrefixNode: Nullable<PrefixNode>;
let atPrefixNode: Nullable<PrefixNode>;
let tokenTrim = tokenTrimParam;
@@ -31,12 +32,12 @@ export function prefixHandler(tokenTrimParam: string, functionService: IFunction
let sliceLength = 0;
if (prefix[0] === prefixToken.MINUS) {
const functionExecutor = functionService.getExecutor(FUNCTION_NAMES_META.MINUS);
- minusPrefixNode = new PrefixNode(injector, prefixToken.MINUS, functionExecutor);
+ minusPrefixNode = new PrefixNode(runtimeService, prefixToken.MINUS, functionExecutor);
sliceLength++;
}
if (prefix[0] === prefixToken.AT) {
- atPrefixNode = new PrefixNode(injector, prefixToken.AT);
+ atPrefixNode = new PrefixNode(runtimeService, prefixToken.AT);
if (minusPrefixNode) {
// minusPrefixNode.addChildren(atPrefixNode);
atPrefixNode.setParent(minusPrefixNode);
diff --git a/packages/engine-formula/src/engine/utils/value-object.ts b/packages/engine-formula/src/engine/utils/value-object.ts
index 230c181251..348bfe9417 100644
--- a/packages/engine-formula/src/engine/utils/value-object.ts
+++ b/packages/engine-formula/src/engine/utils/value-object.ts
@@ -15,13 +15,16 @@
*/
import type { ICellData, Nullable } from '@univerjs/core';
-import { CellValueType } from '@univerjs/core';
import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
import type { ArrayValueObject } from '../value-object/array-value-object';
import type { BaseValueObject } from '../value-object/base-value-object';
+import { CellValueType } from '@univerjs/core';
+import { ErrorType } from '../../basics/error-type';
+import { CellReferenceObject } from '../reference-object/cell-reference-object';
+import { ColumnReferenceObject } from '../reference-object/column-reference-object';
+import { RowReferenceObject } from '../reference-object/row-reference-object';
import { ErrorValueObject } from '../value-object/base-value-object';
import { BooleanValueObject, NumberValueObject } from '../value-object/primitive-object';
-import { ErrorType } from '../../basics/error-type';
import { expandArrayValueObject } from './array-object';
import { booleanObjectIntersection, findCompareToken, valueObjectCompare } from './object-compare';
@@ -268,3 +271,64 @@ export function isSameValueObjectType(left: BaseValueObject, right: BaseValueObj
return false;
}
+
+export enum ReferenceObjectType {
+ CELL,
+ COLUMN,
+ ROW,
+}
+
+const referenceObjectFromCache: Map<string, BaseReferenceObject> = new Map();
+
+export function getReferenceObjectFromCache(trimToken: string, type: ReferenceObjectType) {
+ const o = referenceObjectFromCache.get(trimToken);
+ if (o) {
+ return o;
+ }
+
+ let referenceObject: BaseReferenceObject;
+ switch (type) {
+ case ReferenceObjectType.CELL:
+ referenceObject = new CellReferenceObject(trimToken);
+ break;
+ case ReferenceObjectType.COLUMN:
+ referenceObject = new ColumnReferenceObject(trimToken);
+ break;
+ case ReferenceObjectType.ROW:
+ referenceObject = new RowReferenceObject(trimToken);
+ break;
+ default:
+ throw new Error('Unknown reference object type');
+ }
+
+ referenceObjectFromCache.set(trimToken, referenceObject);
+
+ return referenceObject;
+}
+
+export function getRangeReferenceObjectFromCache(variant1: BaseReferenceObject, variant2: BaseReferenceObject) {
+ const key = `${variant1.getToken()}:${variant2.getToken()}`;
+ const o = referenceObjectFromCache.get(key);
+ if (o) {
+ const { x, y } = variant1.getRefOffset();
+ o.setRefOffset(x, y);
+ return o;
+ }
+ let referenceObject: FunctionVariantType = ErrorValueObject.create(ErrorType.NAME);
+ if (variant1.isCell() && variant2.isCell()) {
+ referenceObject = variant1.unionBy(variant2) as BaseReferenceObject;
+ referenceObjectFromCache.set(key, referenceObject as BaseReferenceObject);
+ } else if (variant1.isRow() && variant2.isRow()) {
+ referenceObject = variant1.unionBy(variant2) as BaseReferenceObject;
+ referenceObjectFromCache.set(key, referenceObject as BaseReferenceObject);
+ } else if (variant1.isColumn() && variant2.isColumn()) {
+ referenceObject = variant1.unionBy(variant2) as BaseReferenceObject;
+ referenceObjectFromCache.set(key, referenceObject as BaseReferenceObject);
+ }
+
+ return referenceObject;
+}
+
+export function clearReferenceObjectCache() {
+ referenceObjectFromCache.clear();
+}
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts
index 290ec3b3b0..fe9ee5fb3a 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-ceil.spec.ts
@@ -16,9 +16,9 @@
import { describe, expect, it } from 'vitest';
+import { stripArrayValue } from '../../../functions/__tests__/create-function-test-bed';
import { ArrayValueObject, transformToValueObject } from '../array-value-object';
import { NumberValueObject } from '../primitive-object';
-import { stripArrayValue } from '../../../functions/__tests__/create-function-test-bed';
describe('arrayValueObject ceil method test', () => {
const originArrayValueObject = ArrayValueObject.create({
@@ -172,8 +172,8 @@ describe('arrayValueObject ceil method test', () => {
const ceilValueObject = NumberValueObject.create(1);
expect((originArrayValueObject.ceil(ceilValueObject) as ArrayValueObject).toValue()).toStrictEqual([
- [1, '#VALUE!', 1.3, 1, 0],
- [0, 100, 2.4, '#VALUE!', -3],
+ [1, '#VALUE!', 1.3, 1, -0],
+ [-0, 100, 2.4, '#VALUE!', -3],
]);
});
diff --git a/packages/engine-formula/src/engine/value-object/array-value-object.ts b/packages/engine-formula/src/engine/value-object/array-value-object.ts
index d6933d256d..c29fb0c295 100644
--- a/packages/engine-formula/src/engine/value-object/array-value-object.ts
+++ b/packages/engine-formula/src/engine/value-object/array-value-object.ts
@@ -168,14 +168,18 @@ export class ArrayValueObject extends BaseValueObject {
}
override dispose(): void {
- this._values.forEach((cells) => {
- cells.forEach((cell) => {
- cell?.dispose();
- });
- });
+ // this._values.forEach((cells) => {
+ // cells.forEach((cell) => {
+ // cell?.dispose();
+ // });
+ // });
this._values = [];
+ this._defaultValue = null;
+
+ this._flattenPosition = null;
+
this._clearCache();
}
diff --git a/packages/engine-formula/src/engine/value-object/cube-value-object.ts b/packages/engine-formula/src/engine/value-object/cube-value-object.ts
index 29897a5535..2dbdc345e8 100644
--- a/packages/engine-formula/src/engine/value-object/cube-value-object.ts
+++ b/packages/engine-formula/src/engine/value-object/cube-value-object.ts
@@ -34,6 +34,13 @@ export class CubeValueObject extends BaseValueObject {
this._values = values;
}
+ override dispose(): void {
+ this._values.forEach((value) => {
+ value.dispose();
+ });
+ this._values = [];
+ }
+
override sum() {
const result = NumberValueObject.create(0);
this._values.forEach((arr) => {
diff --git a/packages/engine-formula/src/engine/value-object/lambda-value-object.ts b/packages/engine-formula/src/engine/value-object/lambda-value-object.ts
index ec834d078f..86bd578eef 100644
--- a/packages/engine-formula/src/engine/value-object/lambda-value-object.ts
+++ b/packages/engine-formula/src/engine/value-object/lambda-value-object.ts
@@ -59,9 +59,9 @@ export class LambdaValueObjectObject extends BaseValueObject {
private _lambdaPrivacyValueMap = new Map<string, FunctionVariantType>();
constructor(
- private _lambdaNode: BaseAstNode,
+ private _lambdaNode: Nullable<BaseAstNode>,
- private _interpreter: Interpreter,
+ private _interpreter: Nullable<Interpreter>,
private _lambdaPrivacyVarKeys: string[]
) {
@@ -69,13 +69,21 @@ export class LambdaValueObjectObject extends BaseValueObject {
this._lambdaPrivacyValueMap.clear();
}
+ override dispose(): void {
+ this._lambdaPrivacyValueMap.clear();
+ this._lambdaPrivacyValueMap = new Map();
+ this._lambdaNode = null;
+ this._interpreter = null;
+ this._lambdaPrivacyVarKeys = [];
+ }
+
override isLambda() {
return true;
}
execute(...variants: FunctionVariantType[]) {
const paramCount = this._lambdaPrivacyVarKeys.length;
- if (variants.length !== paramCount) {
+ if (variants.length !== paramCount || !this._interpreter || !this._lambdaNode) {
return ErrorValueObject.create(ErrorType.VALUE);
}
@@ -102,7 +110,10 @@ export class LambdaValueObjectObject extends BaseValueObject {
return value;
}
- private _setLambdaNodeValue(node: BaseAstNode) {
+ private _setLambdaNodeValue(node: Nullable<BaseAstNode>) {
+ if (!node) {
+ return;
+ }
const children = node.getChildren();
const childrenCount = children.length;
for (let i = 0; i < childrenCount; i++) {
diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.ts
index 968f0901cf..0bdb62f04a 100644
--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts
+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts
@@ -432,27 +432,15 @@ export class BooleanValueObject extends BaseValueObject {
}
}
-const NUMBER_CACHE_LRU_COUNT = 200000;
-
-export const NumberValueObjectCache = new FormulaAstLRU<NumberValueObject>(NUMBER_CACHE_LRU_COUNT);
-
export class NumberValueObject extends BaseValueObject {
private _value: number = 0;
static create(value: number, pattern: string = '') {
- // The same number may have different number formats
- const key = `${value}-${pattern}`;
- const cached = NumberValueObjectCache.get(key);
- if (cached) {
- return cached;
- }
-
const instance = new NumberValueObject(value);
if (pattern) {
instance.setPattern(pattern);
}
- NumberValueObjectCache.set(key, instance);
return instance;
}
@@ -1307,7 +1295,7 @@ export class NumberValueObject extends BaseValueObject {
}
}
-const STRING_CACHE_LRU_COUNT = 200000;
+const STRING_CACHE_LRU_COUNT = 100000;
export const StringValueObjectCache = new FormulaAstLRU<StringValueObject>(STRING_CACHE_LRU_COUNT);
export class StringValueObject extends BaseValueObject {
diff --git a/packages/engine-formula/src/facade/f-formula.ts b/packages/engine-formula/src/facade/f-formula.ts
index fefbca91c6..36d8d711db 100644
--- a/packages/engine-formula/src/facade/f-formula.ts
+++ b/packages/engine-formula/src/facade/f-formula.ts
@@ -17,17 +17,18 @@
import type { ICommandInfo, IDisposable } from '@univerjs/core';
import type { ISetFormulaCalculationNotificationMutation, ISetFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';
import type { FormulaExecutedStateType, IExecutionInProgressParams } from '../services/runtime.service';
-import { ICommandService } from '@univerjs/core';
+import { FBase, ICommandService, Inject, Injector } from '@univerjs/core';
import { SetFormulaCalculationNotificationMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '../commands/mutations/set-formula-calculation.mutation';
/**
* This interface class provides methods to modify the behavior of the operation formula.
*/
-export class FFormula {
+export class FFormula extends FBase {
constructor(
- @ICommandService private readonly _commandService: ICommandService
+ @Inject(ICommandService) private readonly _commandService: ICommandService,
+ @Inject(Injector) protected readonly _injector: Injector
) {
- // empty
+ super();
}
/**
diff --git a/packages/engine-formula/src/functions/financial/ipmt/__tests__/index.spec.ts b/packages/engine-formula/src/functions/financial/ipmt/__tests__/index.spec.ts
index 4ac619eb97..ca7a18f716 100644
--- a/packages/engine-formula/src/functions/financial/ipmt/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/financial/ipmt/__tests__/index.spec.ts
@@ -72,7 +72,7 @@ describe('Test ipmt function', () => {
const fv = NumberValueObject.create(0);
const type = NumberValueObject.create(0);
const result = testFunction.calculate(rate, per, nper, pv, fv, type);
- expect(result.getValue()).toStrictEqual(-0 | 0);
+ expect(result.getValue()).toStrictEqual(-0);
});
it('Value is normal string', () => {
@@ -131,7 +131,7 @@ describe('Test ipmt function', () => {
const result = testFunction.calculate(rate, per, nper, pv, fv, type);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
[ErrorType.VALUE, ErrorType.NUM, ErrorType.NUM, ErrorType.NA],
- [-80000, 0, ErrorType.NAME, ErrorType.NA],
+ [-80000, -0, ErrorType.NAME, ErrorType.NA],
[ErrorType.NUM, ErrorType.NUM, ErrorType.NUM, ErrorType.NA],
[ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
diff --git a/packages/engine-formula/src/functions/financial/ispmt/__tests__/index.spec.ts b/packages/engine-formula/src/functions/financial/ispmt/__tests__/index.spec.ts
index 1f438a4d04..1d46c2bb9e 100644
--- a/packages/engine-formula/src/functions/financial/ispmt/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/financial/ispmt/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_FINANCIAL } from '../../function-names';
-import { Ispmt } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { ErrorType } from '../../../../basics/error-type';
import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
-import { ErrorType } from '../../../../basics/error-type';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_FINANCIAL } from '../../function-names';
+import { Ispmt } from '../index';
describe('Test ispmt function', () => {
const testFunction = new Ispmt(FUNCTION_NAMES_FINANCIAL.ISPMT);
@@ -69,7 +69,7 @@ describe('Test ispmt function', () => {
const nper = NumberValueObject.create(3 * 12);
const pv = NumberValueObject.create(80000);
const result = testFunction.calculate(rate, per, nper, pv);
- expect(result.getValue()).toBe(0 | -0);
+ expect(result.getValue()).toBe(-0);
});
it('Value is normal string', () => {
@@ -123,8 +123,8 @@ describe('Test ispmt function', () => {
const pv = NumberValueObject.create(80000);
const result = testFunction.calculate(rate, per, nper, pv);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [ErrorType.VALUE, 4800, 0 | -0, ErrorType.NA],
- [-72000, 0 | -0, ErrorType.NAME, ErrorType.NA],
+ [ErrorType.VALUE, 4800, -0, ErrorType.NA],
+ [-72000, -0, ErrorType.NAME, ErrorType.NA],
[ErrorType.DIV_BY_ZERO, ErrorType.DIV_BY_ZERO, ErrorType.DIV_BY_ZERO, ErrorType.NA],
[ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA],
]);
diff --git a/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.ts b/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.ts
index 33f210d0c3..46d3f56b6e 100644
--- a/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.ts
@@ -124,7 +124,7 @@ describe('Test pv function', () => {
const type = NumberValueObject.create(0);
const result = testFunction.calculate(rate, nper, pmt, fv, type);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [ErrorType.VALUE, 1918748.3979545343, 0, ErrorType.NA],
+ [ErrorType.VALUE, 1918748.3979545343, -0, ErrorType.NA],
[-5, 2000, ErrorType.NAME, ErrorType.NA],
[0, 0, 0, ErrorType.NA],
[ErrorType.NA, ErrorType.NA, ErrorType.NA, ErrorType.NA],
diff --git a/packages/engine-formula/src/functions/math/ceiling-math/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/ceiling-math/__tests__/index.spec.ts
index affdff9ea6..f052170139 100644
--- a/packages/engine-formula/src/functions/math/ceiling-math/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/ceiling-math/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_MATH } from '../../function-names';
-import { CeilingMath } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
-import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_MATH } from '../../function-names';
+import { CeilingMath } from '../index';
describe('Test ceiling.math function', () => {
const testFunction = new CeilingMath(FUNCTION_NAMES_MATH.CEILING_MATH);
@@ -102,7 +102,7 @@ describe('Test ceiling.math function', () => {
});
const result = testFunction.calculate(number, significance);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [3, 0, 0, 0, ErrorType.VALUE, 2.5, -48, 6, ErrorType.NA],
+ [3, 0, -0, 0, ErrorType.VALUE, 2.5, -48, 6, ErrorType.NA],
]);
});
diff --git a/packages/engine-formula/src/functions/math/ceiling-precise/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/ceiling-precise/__tests__/index.spec.ts
index 233044af7e..9a1f1c8e1c 100644
--- a/packages/engine-formula/src/functions/math/ceiling-precise/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/ceiling-precise/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_MATH } from '../../function-names';
-import { CeilingPrecise } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
-import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_MATH } from '../../function-names';
+import { CeilingPrecise } from '../index';
describe('Test ceiling.precise function', () => {
const testFunction = new CeilingPrecise(FUNCTION_NAMES_MATH.CEILING_PRECISE);
@@ -101,7 +101,7 @@ describe('Test ceiling.precise function', () => {
});
const result = testFunction.calculate(number, significance);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [3, 0, 0, 0, ErrorType.VALUE, 2.5, -48, 6, ErrorType.NA],
+ [3, 0, -0, 0, ErrorType.VALUE, 2.5, -48, 6, ErrorType.NA],
]);
});
});
diff --git a/packages/engine-formula/src/functions/math/ceiling/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/ceiling/__tests__/index.spec.ts
index 4dbfef18ac..01f335e1bb 100644
--- a/packages/engine-formula/src/functions/math/ceiling/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/ceiling/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_MATH } from '../../function-names';
-import { Ceiling } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
-import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_MATH } from '../../function-names';
+import { Ceiling } from '../index';
describe('Test ceiling function', () => {
const testFunction = new Ceiling(FUNCTION_NAMES_MATH.CEILING);
@@ -101,7 +101,7 @@ describe('Test ceiling function', () => {
});
const result = testFunction.calculate(number, significance);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [3, 0, 0, 0, ErrorType.VALUE, 2.5, -51, ErrorType.NUM, ErrorType.NA],
+ [3, 0, -0, 0, ErrorType.VALUE, 2.5, -51, ErrorType.NUM, ErrorType.NA],
]);
});
});
diff --git a/packages/engine-formula/src/functions/math/floor-math/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/floor-math/__tests__/index.spec.ts
index 33be3ce102..8610566638 100644
--- a/packages/engine-formula/src/functions/math/floor-math/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/floor-math/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_MATH } from '../../function-names';
-import { FloorMath } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
-import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_MATH } from '../../function-names';
+import { FloorMath } from '../index';
describe('Test floor.math function', () => {
const testFunction = new FloorMath(FUNCTION_NAMES_MATH.FLOOR_MATH);
@@ -132,7 +132,7 @@ describe('Test floor.math function', () => {
const mode = NumberValueObject.create(-23);
const result = testFunction.calculate(number, significance, mode);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [2, 0, 0, 0, ErrorType.VALUE, 0, -48, 4, ErrorType.NA],
+ [2, 0, -0, 0, ErrorType.VALUE, 0, -48, 4, ErrorType.NA],
]);
});
});
diff --git a/packages/engine-formula/src/functions/math/round/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/round/__tests__/index.spec.ts
index fac9af83ab..dd7d29fd87 100644
--- a/packages/engine-formula/src/functions/math/round/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/round/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_MATH } from '../../function-names';
-import { Round } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
-import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_MATH } from '../../function-names';
+import { Round } from '../index';
describe('Test round function', () => {
const testFunction = new Round(FUNCTION_NAMES_MATH.ROUND);
@@ -108,7 +108,7 @@ describe('Test round function', () => {
});
const result = testFunction.calculate(number, numDigits);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [2.2, 2.1, -1.58, 22, 630, 0, 0, ErrorType.NA, ErrorType.NA],
+ [2.2, 2.1, -1.58, 22, 630, 0, -0, ErrorType.NA, ErrorType.NA],
]);
});
});
diff --git a/packages/engine-formula/src/functions/math/rounddown/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/rounddown/__tests__/index.spec.ts
index 12cd96c865..efda42e72a 100644
--- a/packages/engine-formula/src/functions/math/rounddown/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/rounddown/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_MATH } from '../../function-names';
-import { Rounddown } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
-import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_MATH } from '../../function-names';
+import { Rounddown } from '../index';
describe('Test rounddown function', () => {
const testFunction = new Rounddown(FUNCTION_NAMES_MATH.ROUNDDOWN);
@@ -108,7 +108,7 @@ describe('Test rounddown function', () => {
});
const result = testFunction.calculate(number, numDigits);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [2.1, 2.1, -1.57, 21, 620, 0, 0, ErrorType.NA, ErrorType.NA],
+ [2.1, 2.1, -1.57, 21, 620, 0, -0, ErrorType.NA, ErrorType.NA],
]);
});
});
diff --git a/packages/engine-formula/src/functions/math/trunc/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/trunc/__tests__/index.spec.ts
index b35ee9deb6..6861a54f4b 100644
--- a/packages/engine-formula/src/functions/math/trunc/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/trunc/__tests__/index.spec.ts
@@ -16,12 +16,12 @@
import { describe, expect, it } from 'vitest';
-import { FUNCTION_NAMES_MATH } from '../../function-names';
-import { Trunc } from '../index';
-import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
-import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
+import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_MATH } from '../../function-names';
+import { Trunc } from '../index';
describe('Test trunc function', () => {
const testFunction = new Trunc(FUNCTION_NAMES_MATH.TRUNC);
@@ -107,7 +107,7 @@ describe('Test trunc function', () => {
});
const result = testFunction.calculate(number, numDigits);
expect(transformToValue(result.getArrayValue())).toStrictEqual([
- [2.1, 2.1, -1.57, 21, 620, 0, 0, ErrorType.NA, ErrorType.NA],
+ [2.1, 2.1, -1.57, 21, 620, 0, -0, ErrorType.NA, ErrorType.NA],
]);
});
});
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index d503e9be8d..36f2fa5a0f 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -156,3 +156,4 @@ export { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeServic
export { ISuperTableService } from './services/super-table.service';
export { SuperTableService } from './services/super-table.service';
export { deserializeRangeWithSheetWithCache } from './engine/utils/reference-cache';
+export { FFormula } from './facade/f-formula';
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 9f0ca74f9a..17b8b97850 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable, Workbook } from '@univerjs/core';
+import type { ICellData, IObjectMatrixPrimitiveType, IRange, IUnitRange, Nullable, Workbook } from '@univerjs/core';
import type {
IArrayFormulaRangeType,
IArrayFormulaUnitCellType,
@@ -28,7 +28,7 @@ import type {
import type { IFormulaIdMap } from './utils/formula-data-util';
-import { Disposable, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
+import { Disposable, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';
import { clearArrayFormulaCellDataByCell, updateFormulaDataByCellValue } from './utils/formula-data-util';
@@ -237,8 +237,12 @@ export class FormulaDataModel extends Disposable {
return;
}
+ if (!this._formulaData[unitId]?.[sheetId]) {
+ this._formulaData[unitId]![sheetId] = {};
+ }
+
const sheetFormula = new ObjectMatrix(currentSheetData);
- const formulaMatrix = new ObjectMatrix(this._formulaData[unitId]?.[sheetId] || {});
+ const formulaMatrix = new ObjectMatrix(this._formulaData[unitId]![sheetId]);
sheetFormula.forValue((r, c, v) => {
if (v == null) {
@@ -247,8 +251,6 @@ export class FormulaDataModel extends Disposable {
formulaMatrix.setValue(r, c, v);
}
});
-
- this._formulaData[unitId]![sheetId] = formulaMatrix.clone();
});
});
}
@@ -409,7 +411,7 @@ export class FormulaDataModel extends Disposable {
}
});
- return newSheetFormulaDataMatrix.clone();
+ return newSheetFormulaDataMatrix.getMatrix();
}
updateArrayFormulaRange(
@@ -563,6 +565,88 @@ export class FormulaDataModel extends Disposable {
return null;
}
+
+ /**
+ * Function to get all formula ranges
+ * @returns
+ */
+ getFormulaDirtyRanges(): IUnitRange[] {
+ const formulaData = this._formulaData;
+
+ const dirtyRanges: IUnitRange[] = [];
+
+ for (const unitId in formulaData) {
+ const workbook = formulaData[unitId];
+
+ if (!workbook) continue;
+
+ const workbookInstance = this._univerInstanceService.getUnit<Workbook>(unitId);
+
+ if (!workbookInstance) continue;
+
+ for (const sheetId in workbook) {
+ const sheet = workbook[sheetId];
+
+ if (!sheet) continue;
+
+ const sheetInstance = workbookInstance.getSheetBySheetId(sheetId);
+
+ if (!sheetInstance) continue;
+
+ // Object to store continuous cell ranges by column
+ const columnRanges: { [column: number]: { startRow: number; endRow: number }[] } = {};
+
+ for (const rowStr of Object.keys(sheet)) {
+ const row = Number(rowStr);
+
+ for (const columnStr in sheet[row]) {
+ const column = Number(columnStr);
+
+ const currentCell = sheetInstance.getCellRaw(row, column);
+
+ // Calculation is only required when there is only a formula and no value
+ const isFormula = isFormulaString(currentCell?.f) || isFormulaId(currentCell?.si);
+ const noValue = currentCell?.v === undefined;
+
+ if (!(isFormula && noValue)) continue;
+
+ if (!columnRanges[column]) columnRanges[column] = [];
+
+ const lastRange = columnRanges[column].slice(-1)[0];
+
+ // If the current row is continuous with the last range, extend endRow
+ if (lastRange && lastRange.endRow === row - 1) {
+ lastRange.endRow = row;
+ } else {
+ // Otherwise, start a new range
+ columnRanges[column].push({ startRow: row, endRow: row });
+ }
+ }
+ }
+
+ // Convert collected column ranges to IUnitRange format
+ for (const column in columnRanges) {
+ const currentColumnRanges = columnRanges[column];
+ for (let i = 0; i < currentColumnRanges.length; i++) {
+ const range = currentColumnRanges[i];
+ dirtyRanges.push({
+ unitId,
+ sheetId,
+ range: {
+ rangeType: RANGE_TYPE.NORMAL,
+ startRow: range.startRow,
+ endRow: range.endRow, // Use endRow as the inclusive end row
+ startColumn: Number(column),
+ endColumn: Number(column),
+ },
+ });
+ }
+ }
+ }
+ }
+
+ return dirtyRanges;
+ }
}
export function initSheetFormulaData(
@@ -571,8 +655,17 @@ export function initSheetFormulaData(
sheetId: string,
cellMatrix: ObjectMatrix<Nullable<ICellData>>
): IFormulaData {
+ if (!formulaData[unitId]) {
+ formulaData[unitId] = {};
+ }
+
+ if (!formulaData[unitId][sheetId]) {
+ formulaData[unitId][sheetId] = {};
+ }
+
const formulaIdMap = new Map<string, { f: string; r: number; c: number }>(); // Connect the formula and ID
- const sheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem>();
+ const sheetFormulaDataMatrix = new ObjectMatrix<Nullable<IFormulaDataItem>>(formulaData[unitId][sheetId]);
+
cellMatrix.forValue((r, c, cell) => {
const formulaString = cell?.f || '';
const formulaId = cell?.si || '';
@@ -618,13 +711,7 @@ export function initSheetFormulaData(
}
});
- if (!formulaData[unitId]) {
- formulaData[unitId] = {};
- }
-
- const newSheetFormulaData = sheetFormulaDataMatrix.clone();
-
- formulaData[unitId]![sheetId] = newSheetFormulaData;
+ const newSheetFormulaData = sheetFormulaDataMatrix.getMatrix(); // Don't use clone, otherwise it will cause performance problems
return {
[unitId]: {
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index e860f19a03..2dd60adbb9 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -127,6 +127,8 @@ export class CalculateFormulaService extends Disposable {
this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());
CELL_INVERTED_INDEX_CACHE.clear();
+
+ this._runtimeService.reset();
}
private async _execute() {
@@ -226,7 +228,7 @@ export class CalculateFormulaService extends Disposable {
this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
- const treeList = await this._formulaDependencyGenerator.generate();
+ const treeList = (await this._formulaDependencyGenerator.generate()).reverse();
const interpreter = this._interpreter;
@@ -247,7 +249,8 @@ export class CalculateFormulaService extends Disposable {
const config = this._configService.getConfig(PLUGIN_CONFIG_KEY) as IUniverEngineFormulaConfig;
const intervalCount = config?.intervalCount || DEFAULT_INTERVAL_COUNT;
- for (let i = 0, len = treeList.length; i < len; i++) {
+ const treeCount = treeList.length;
+ for (let i = 0; i < treeCount; i++) {
const tree = treeList[i];
const nodeData = tree.nodeData;
const getDirtyData = tree.getDirtyData;
@@ -314,7 +317,7 @@ export class CalculateFormulaService extends Disposable {
}
if (tree.formulaId != null) {
- this._runtimeService.setRuntimeOtherData(tree.formulaId, value);
+ this._runtimeService.setRuntimeOtherData(tree.formulaId, tree.refOffsetX, tree.refOffsetY, value);
} else {
this._runtimeService.setRuntimeData(value);
}
@@ -325,13 +328,13 @@ export class CalculateFormulaService extends Disposable {
pendingTasks.forEach((cancel) => cancel());
pendingTasks = [];
- if (treeList.length > 0) {
+ if (treeCount > 0) {
this._runtimeService.markedAsSuccessfullyExecuted();
} else if (!isArrayFormulaState) {
this._runtimeService.markedAsNoFunctionsExecuted();
}
- this._runtimeService.clearReferenceAndNumberformatCache();
+ // treeList.length = 0;
return this._runtimeService.getAllRuntimeData();
}
diff --git a/packages/engine-formula/src/services/dependency-manager.service.ts b/packages/engine-formula/src/services/dependency-manager.service.ts
index 036edea9b2..6e85843632 100644
--- a/packages/engine-formula/src/services/dependency-manager.service.ts
+++ b/packages/engine-formula/src/services/dependency-manager.service.ts
@@ -15,69 +15,46 @@
*/
import type { IRTreeItem, IUnitRange, Nullable } from '@univerjs/core';
-import type { FormulaDependencyTree } from '../engine/dependency/dependency-tree';
+import type { AstRootNode } from '../engine/ast-node';
+import type { FormulaDependencyTree, IFormulaDependencyTree } from '../engine/dependency/dependency-tree';
import { createIdentifier, Disposable, ObjectMatrix, RTree } from '@univerjs/core';
-export interface IOtherFormulaDependencyParam {
- [unitId: string]: Nullable<{ [sheetId: string]: { [formulaId: string]: Nullable<number> } }>;
-}
-
-export interface IFeatureFormulaDependencyParam {
- [unitId: string]: Nullable<{ [sheetId: string]: { [featureId: string]: Nullable<number> } }>;
-}
-
-export interface IFormulaDependencyParam {
- [unitId: string]: Nullable<{ [sheetId: string]: ObjectMatrix< number> }>;
-}
-
export interface IDependencyManagerService {
dispose(): void;
- getAllTree(): FormulaDependencyTree[];
-
- buildDependencyTree(shouldBeBuildTrees: FormulaDependencyTree[], dependencyTrees?: FormulaDependencyTree[]): FormulaDependencyTree[];
-
- clearDependencyForTree(shouldBeClearTree: Nullable<FormulaDependencyTree>): void;
-
reset(): void;
- addOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string, dependencyTree: FormulaDependencyTree): void;
-
+ addOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string, dependencyTree: IFormulaDependencyTree): void;
+ addOtherFormulaDependencyMainData(formulaId: string): void;
removeOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string[]): void;
-
- getOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string): Nullable<FormulaDependencyTree>;
+ hasOtherFormulaDataMainData(formulaId: string): boolean;
+ clearOtherFormulaDependency(unitId: string, sheetId?: string): void;
+ getOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string): Nullable<ObjectMatrix<number>>;
addFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string, dependencyTree: FormulaDependencyTree): void;
-
removeFeatureFormulaDependency(unitId: string, sheetId: string, featureIds: string[]): void;
+ getFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string): Nullable<number>;
+ clearFeatureFormulaDependency(unitId: string, sheetId?: string): void;
- getFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string): Nullable<FormulaDependencyTree>;
-
- addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: FormulaDependencyTree): void;
-
+ addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: IFormulaDependencyTree): void;
removeFormulaDependency(unitId: string, sheetId: string, row: number, column: number): void;
-
- getFormulaDependency(unitId: string, sheetId: string, row: number, column: number): Nullable<FormulaDependencyTree>;
-
- removeFormulaDependencyByDefinedName(unitId: string, definedName: string): void;
-
+ getFormulaDependency(unitId: string, sheetId: string, row: number, column: number): Nullable<number>;
clearFormulaDependency(unitId: string, sheetId?: string): void;
- addDependencyRTreeCache(tree: FormulaDependencyTree): void;
+ removeFormulaDependencyByDefinedName(unitId: string, definedName: string): void;
+ addFormulaDependencyByDefinedName(tree: IFormulaDependencyTree, node: Nullable<AstRootNode>): void;
- searchDependency(search: IUnitRange[]): Set<number>;
+ addDependencyRTreeCache(tree: IFormulaDependencyTree): void;
+ searchDependency(search: IUnitRange[], exceptTreeIds?: Set<number>): Set<number>;
getLastTreeId(): number;
- clearDependencyAll(): void;
+ getTreeById(treeId: number): Nullable<IFormulaDependencyTree>;
- clearOtherFormulaDependency(unitId: string, sheetId?: string): void;
- clearFeatureFormulaDependency(unitId: string, sheetId?: string): void;
+ getAllTree(): IFormulaDependencyTree[];
- openKdTree(): void;
- closeKdTree(): void;
+ buildDependencyTree(shouldBeBuildTrees: IFormulaDependencyTree[], dependencyTrees?: IFormulaDependencyTree[]): IFormulaDependencyTree[];
- getTreeById(treeId: number): Nullable<FormulaDependencyTree>;
}
/**
@@ -87,103 +64,27 @@ export interface IDependencyManagerService {
* thereby completing the calculation of the entire dependency tree.
*/
export class DependencyManagerService extends Disposable implements IDependencyManagerService {
- private _otherFormulaData: IOtherFormulaDependencyParam = {};
+ private _otherFormulaData: Map<string, Map<string, Map<string, ObjectMatrix<number>>>> = new Map(); // [unitId: string]: Nullable<{ [sheetId: string]: { [formulaId: string]: Set<number> } }>;
- private _featureFormulaData: IFeatureFormulaDependencyParam = {};
+ private _featureFormulaData: Map<string, Map<string, Map<string, Nullable<number>>>> = new Map(); // [unitId: string]: Nullable<{ [sheetId: string]: { [featureId: string]: Nullable<number> } }>;
- private _formulaData: IFormulaDependencyParam = {};
+ private _formulaData: Map<string, Map<string, ObjectMatrix<number>>> = new Map(); // [unitId: string]: Nullable<{ [sheetId: string]: ObjectMatrix<number> }>;
- private _allTreeMap: Map<number, FormulaDependencyTree> = new Map();
+ private _definedNameMap: Map<string, Map<string, Set<number>>> = new Map(); // unitId -> definedName -> treeId
- private _dependencyRTreeCache: RTree = new RTree(true); // true: open kd-tree search state
+ private _allTreeMap: Map<number, IFormulaDependencyTree> = new Map();
- private _dependencyTreeIdLast: number = 0;
+ private _otherFormulaDataMainData: Set<string> = new Set();
- override dispose(): void {
- this._otherFormulaData = {};
- this._featureFormulaData = {};
- this._formulaData = {};
- this._dependencyRTreeCache.dispose();
- this._restDependencyTreeId();
- this._allTreeMap.clear();
- }
+ private _dependencyRTreeCache: RTree = new RTree();
- /**
- * Get all FormulaDependencyTree from _otherFormulaData, _featureFormulaData, _formulaData
- * return FormulaDependencyTree[]
- */
- getAllTree() {
- // const trees: FormulaDependencyTree[] = [];
-
- // const resetAndPush = (item: FormulaDependencyTree) => {
- // if (item) {
- // item.resetState();
- // trees.push(item);
- // }
- // };
-
- // // _otherFormulaData
- // for (const unitKey in this._otherFormulaData) {
- // const unit = this._otherFormulaData[unitKey];
- // if (!unit) continue;
-
- // for (const sheetKey in unit) {
- // const sheet = unit[sheetKey];
- // for (const formulaKey in sheet) {
- // if (sheet[formulaKey] == null) {
- // continue;
- // }
- // resetAndPush(sheet[formulaKey]);
- // }
- // }
- // }
-
- // // _featureFormulaData
- // for (const unitKey in this._featureFormulaData) {
- // const unit = this._featureFormulaData[unitKey];
- // if (!unit) continue;
-
- // for (const sheetKey in unit) {
- // const sheet = unit[sheetKey];
- // for (const featureKey in sheet) {
- // if (sheet[featureKey] == null) {
- // continue;
- // }
- // resetAndPush(sheet[featureKey]);
- // }
- // }
- // }
-
- // // _formulaData
- // for (const unitKey in this._formulaData) {
- // const unit = this._formulaData[unitKey];
- // if (!unit) continue;
-
- // for (const sheetKey in unit) {
- // const sheet = unit[sheetKey];
- // sheet.forValue((row, col, item) => {
- // if (item == null) {
- // return true;
- // }
- // resetAndPush(item);
- // });
- // }
- // }
-
- const trees: FormulaDependencyTree[] = [];
- this._allTreeMap.forEach((tree) => {
- tree.resetState();
- trees.push(tree);
- });
-
- return trees;
- }
+ private _dependencyTreeIdLast: number = 0;
- getTreeById(treeId: number) {
- return this._allTreeMap.get(treeId);
+ override dispose(): void {
+ this.reset();
}
- buildDependencyTree(shouldBeBuildTrees: FormulaDependencyTree[], dependencyTrees: FormulaDependencyTree[] = []): FormulaDependencyTree[] {
+ buildDependencyTree(shouldBeBuildTrees: IFormulaDependencyTree[], dependencyTrees: IFormulaDependencyTree[] = []): IFormulaDependencyTree[] {
const allTrees = this.getAllTree();
if (shouldBeBuildTrees.length === 0) {
this._buildReverseDependency(allTrees, dependencyTrees);
@@ -195,17 +96,13 @@ export class DependencyManagerService extends Disposable implements IDependencyM
return allTrees;
}
- searchDependency(search: IUnitRange[]): Set<number> {
- return this._dependencyRTreeCache.bulkSearch(search) as Set<number>;
- }
-
/**
* Build the dependency relationship between the trees.
* @param allTrees all FormulaDependencyTree
* @param shouldBeBuildTrees FormulaDependencyTree[] | FormulaDependencyTreeCache
*/
- private _buildDependencyTree(allTrees: FormulaDependencyTree[], shouldBeBuildTrees: FormulaDependencyTree[]) {
- const shouldBeBuildTreeMap = new Map<number, FormulaDependencyTree>();
+ private _buildDependencyTree(allTrees: IFormulaDependencyTree[], shouldBeBuildTrees: IFormulaDependencyTree[]) {
+ const shouldBeBuildTreeMap = new Map<number, IFormulaDependencyTree>();
for (let i = 0; i < shouldBeBuildTrees.length; i++) {
const tree = shouldBeBuildTrees[i];
shouldBeBuildTreeMap.set(tree.treeId, tree);
@@ -215,11 +112,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
const tree = allTrees[i];
const RTreeItem = tree.toRTreeItem();
- const searchResults = this._dependencyRTreeCache.search(RTreeItem);
+ const searchResults = this._dependencyRTreeCache.bulkSearch(RTreeItem);
- for (let j = 0; j < searchResults.length; j++) {
- const id = searchResults[j] as number;
- const shouldBeBuildTree = shouldBeBuildTreeMap.get(id);
+ for (const id of searchResults) {
+ const shouldBeBuildTree = shouldBeBuildTreeMap.get(id as number);
if (shouldBeBuildTree && tree !== shouldBeBuildTree && !shouldBeBuildTree.hasChildren(tree.treeId)) {
shouldBeBuildTree.pushChildren(tree);
@@ -237,8 +133,8 @@ export class DependencyManagerService extends Disposable implements IDependencyM
* @param allTrees
* @param dependencyTrees
*/
- private _buildReverseDependency(allTrees: FormulaDependencyTree[], dependencyTrees: FormulaDependencyTree[]) {
- const allTreeMap = new Map<number, FormulaDependencyTree>();
+ private _buildReverseDependency(allTrees: IFormulaDependencyTree[], dependencyTrees: IFormulaDependencyTree[]) {
+ const allTreeMap = new Map<number, IFormulaDependencyTree>();
for (let i = 0; i < allTrees.length; i++) {
const tree = allTrees[i];
@@ -249,11 +145,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
const tree = dependencyTrees[i];
const RTreeItem = tree.toRTreeItem();
- const searchResults = this._dependencyRTreeCache.search(RTreeItem);
+ const searchResults = this._dependencyRTreeCache.bulkSearch(RTreeItem);
- for (let j = 0; j < searchResults.length; j++) {
- const id = searchResults[j] as number;
- const allTree = allTreeMap.get(id);
+ for (const id of searchResults) {
+ const allTree = allTreeMap.get(id as number);
if (allTree && tree !== allTree && !allTree.hasChildren(tree.treeId)) {
allTree.pushChildren(tree);
@@ -264,265 +159,299 @@ export class DependencyManagerService extends Disposable implements IDependencyM
allTreeMap.clear();
}
- /**
- * Clear the dependency relationship of the tree.
- * establish the relationship between the parent and the child.
- * @param shouldBeClearTree
- */
- clearDependencyForTree(shouldBeClearTree: Nullable<FormulaDependencyTree>) {
- if (shouldBeClearTree == null) {
- return;
- }
-
- const parents = shouldBeClearTree.parents;
-
- const children = shouldBeClearTree.children;
-
- const allTreeMap = this._allTreeMap;
+ /**
+ * Get all FormulaDependencyTree from _otherFormulaData, _featureFormulaData, _formulaData
+ * return FormulaDependencyTree[]
+ */
+ getAllTree() {
+ const trees: IFormulaDependencyTree[] = [];
+ this._allTreeMap.forEach((tree) => {
+ tree.resetState();
+ trees.push(tree);
+ });
- for (const parentTreeId of parents) {
- const parent = allTreeMap.get(parentTreeId);
- parent?.children.delete(shouldBeClearTree.treeId);
- }
+ return trees;
+ }
- for (const childTreeId of children) {
- const child = allTreeMap.get(childTreeId);
- child?.parents.delete(shouldBeClearTree.treeId);
- }
+ getTreeById(treeId: number) {
+ return this._allTreeMap.get(treeId);
+ }
- shouldBeClearTree.dispose();
+ searchDependency(search: IUnitRange[], exceptTreeIds?: Set<number>): Set<number> {
+ return this._dependencyRTreeCache.bulkSearch(search, exceptTreeIds) as Set<number>;
}
reset() {
- this._otherFormulaData = {};
- this._featureFormulaData = {};
- this._formulaData = {};
+ this._otherFormulaData.clear();
+ this._featureFormulaData.clear();
+ this._formulaData.clear();
this._dependencyRTreeCache.clear();
this._allTreeMap.clear();
this._restDependencyTreeId();
+
+ this._otherFormulaDataMainData.clear();
}
- addOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string, dependencyTree: FormulaDependencyTree) {
- if (!this._otherFormulaData[unitId]) {
- this._otherFormulaData[unitId] = {};
+ addOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string, dependencyTree: IFormulaDependencyTree) {
+ if (!this._otherFormulaData.has(unitId)) {
+ this._otherFormulaData.set(unitId, new Map<string, Map<string, ObjectMatrix<number>>>());
}
- if (!this._otherFormulaData[unitId]![sheetId]) {
- this._otherFormulaData[unitId]![sheetId] = {};
+
+ const unitMap = this._otherFormulaData.get(unitId)!;
+
+ if (!unitMap.has(sheetId)) {
+ unitMap.set(sheetId, new Map<string, ObjectMatrix<number>>());
}
- this._otherFormulaData[unitId]![sheetId][formulaId] = dependencyTree.treeId;
- this._allTreeMap.set(dependencyTree.treeId, dependencyTree);
+ const sheetMap = unitMap.get(sheetId)!;
+
+ if (!sheetMap.has(formulaId)) {
+ sheetMap.set(formulaId, new ObjectMatrix<number>());
+ }
+
+ const formulaMatrix = sheetMap.get(formulaId)!;
+
+ formulaMatrix.setValue(dependencyTree.refOffsetX, dependencyTree.refOffsetY, dependencyTree.treeId);
+
+ this._addAllTreeMap(dependencyTree);
}
removeOtherFormulaDependency(unitId: string, sheetId: string, formulaIds: string[]) {
- if (this._otherFormulaData[unitId] && this._otherFormulaData[unitId]![sheetId]) {
+ const unitMap = this._otherFormulaData.get(unitId);
+ if (unitMap && unitMap.has(sheetId)) {
+ const sheetMap = unitMap.get(sheetId)!;
+
formulaIds.forEach((formulaId) => {
- const deleteTreeId = this._otherFormulaData[unitId]![sheetId][formulaId];
- if (deleteTreeId == null) {
+ const treeSet = sheetMap.get(formulaId);
+ if (treeSet == null) {
return;
}
- const deleteTree = this._allTreeMap.get(deleteTreeId);
- this._removeDependencyRTreeCache(deleteTree);
- this.clearDependencyForTree(deleteTree);
- delete this._otherFormulaData[unitId]![sheetId][formulaId];
- this._removeAllTreeMap(deleteTreeId);
+
+ treeSet.forValue((row, column, treeId) => {
+ this._removeDependencyRTreeCache(treeId);
+ this.clearDependencyForTree(this._allTreeMap.get(treeId));
+ this._removeAllTreeMap(treeId);
+ });
+
+ sheetMap.delete(formulaId);
+ this._otherFormulaDataMainData.delete(formulaId);
});
+
+ if (sheetMap.size === 0) {
+ unitMap.delete(sheetId);
+ }
+
+ if (unitMap.size === 0) {
+ this._otherFormulaData.delete(unitId);
+ }
}
}
getOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string) {
- let treeId = this._otherFormulaData[unitId]?.[sheetId]?.[formulaId];
- if (treeId == null) {
- treeId = -1;
- }
- return this._allTreeMap.get(treeId);
+ return this._otherFormulaData.get(unitId)?.get(sheetId)?.get(formulaId);
}
- hasOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string) {
- return this.getOtherFormulaDependency(unitId, sheetId, formulaId) != null;
+ addOtherFormulaDependencyMainData(formulaId: string) {
+ this._otherFormulaDataMainData.add(formulaId);
+ }
+
+ hasOtherFormulaDataMainData(formulaId: string) {
+ return this._otherFormulaDataMainData.has(formulaId);
}
clearOtherFormulaDependency(unitId: string, sheetId?: string) {
- if (sheetId && this._otherFormulaData[unitId] && this._otherFormulaData[unitId]![sheetId]) {
+ const unitMap = this._otherFormulaData.get(unitId);
+
+ if (sheetId && unitMap && unitMap.has(sheetId)) {
+ const sheetMap = unitMap.get(sheetId)!;
+
this._removeDependencyRTreeCacheById(unitId, sheetId);
- Object.values(this._otherFormulaData[unitId]![sheetId]).forEach((formulaTreeId) => {
- if (formulaTreeId == null) {
- return;
+ for (const formulaId of sheetMap.keys()) {
+ const formulaTreeSet = sheetMap.get(formulaId);
+ if (formulaTreeSet == null) {
+ continue;
}
- const formula = this._allTreeMap.get(formulaTreeId);
- this.clearDependencyForTree(formula);
- this._removeAllTreeMap(formulaTreeId);
- });
- this._otherFormulaData[unitId]![sheetId] = {};
- } else if (this._otherFormulaData[unitId]) {
- const unitOtherData = this._otherFormulaData[unitId]!;
- Object.keys(unitOtherData).forEach((sheetId) => {
- if (sheetId == null) {
- return;
- }
- this._removeDependencyRTreeCacheById(unitId, sheetId);
- Object.values(unitOtherData[sheetId]!).forEach((formulaTreeId) => {
- if (formulaTreeId == null) {
- return;
+ formulaTreeSet.forValue((row, column, treeId) => {
+ const tree = this._allTreeMap.get(treeId);
+ if (tree) {
+ this.clearDependencyForTree(tree);
+ this._removeAllTreeMap(treeId);
}
- const formula = this._allTreeMap.get(formulaTreeId);
- this.clearDependencyForTree(formula);
- this._removeAllTreeMap(formulaTreeId);
});
- });
- this._otherFormulaData[unitId] = null;
+ this._otherFormulaDataMainData.delete(formulaId);
+ }
+
+ sheetMap.clear(); // 清空该 sheetId 对应的公式依赖数据
+ } else if (unitMap) {
+ for (const sheetId of unitMap.keys()) {
+ const sheetMap = unitMap.get(sheetId)!;
+ this._removeDependencyRTreeCacheById(unitId, sheetId);
+ for (const formulaId of sheetMap.keys()) {
+ const formulaTreeSet = sheetMap.get(formulaId);
+ if (formulaTreeSet == null) {
+ continue;
+ }
+
+ formulaTreeSet.forValue((row, column, treeId) => {
+ const tree = this._allTreeMap.get(treeId);
+ if (tree) {
+ this.clearDependencyForTree(tree);
+ this._removeAllTreeMap(treeId);
+ }
+ });
+
+ this._otherFormulaDataMainData.delete(formulaId);
+ }
+ }
+
+ this._otherFormulaData.delete(unitId); // 删除整个 unitId 对应的数据
}
}
addFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string, dependencyTree: FormulaDependencyTree) {
- if (!this._featureFormulaData[unitId]) {
- this._featureFormulaData[unitId] = {};
+ if (!this._featureFormulaData.has(unitId)) {
+ this._featureFormulaData.set(unitId, new Map<string, Map<string, number>>());
}
- if (!this._featureFormulaData[unitId]![sheetId]) {
- this._featureFormulaData[unitId]![sheetId] = {};
+
+ const unitMap = this._featureFormulaData.get(unitId)!;
+
+ if (!unitMap.has(sheetId)) {
+ unitMap.set(sheetId, new Map<string, number>());
}
- this._featureFormulaData[unitId]![sheetId][featureId] = dependencyTree.treeId;
- this._allTreeMap.set(dependencyTree.treeId, dependencyTree);
+ const sheetMap = unitMap.get(sheetId)!;
+ sheetMap.set(featureId, dependencyTree.treeId);
+ // this._allTreeMap.set(dependencyTree.treeId, dependencyTree);
+ this._addAllTreeMap(dependencyTree);
}
removeFeatureFormulaDependency(unitId: string, sheetId: string, featureIds: string[]) {
- if (this._featureFormulaData[unitId] && this._featureFormulaData[unitId]![sheetId]) {
+ const unitMap = this._featureFormulaData.get(unitId);
+ if (unitMap && unitMap.has(sheetId)) {
+ const sheetMap = unitMap.get(sheetId)!;
featureIds.forEach((featureId) => {
- const deleteTreeId = this._featureFormulaData[unitId]![sheetId][featureId];
+ const deleteTreeId = sheetMap.get(featureId);
if (deleteTreeId == null) {
return;
}
- const deleteTree = this._allTreeMap.get(deleteTreeId);
- this._removeDependencyRTreeCache(deleteTree);
- this.clearDependencyForTree(deleteTree);
- delete this._featureFormulaData[unitId]![sheetId][featureId];
+
+ this._removeDependencyRTreeCache(deleteTreeId);
+
+ sheetMap.delete(featureId);
+ this.clearDependencyForTree(this._allTreeMap.get(deleteTreeId));
this._removeAllTreeMap(deleteTreeId);
});
}
}
clearFeatureFormulaDependency(unitId: string, sheetId?: string) {
- if (sheetId && this._featureFormulaData[unitId] && this._featureFormulaData[unitId]![sheetId]) {
+ const unitMap = this._featureFormulaData.get(unitId);
+
+ if (sheetId && unitMap && unitMap.has(sheetId)) {
+ const sheetMap = unitMap.get(sheetId)!;
this._removeDependencyRTreeCacheById(unitId, sheetId);
- Object.values(this._featureFormulaData[unitId]![sheetId]).forEach((featureTreeId) => {
+ sheetMap.forEach((featureTreeId) => {
if (featureTreeId == null) {
return;
}
- const feature = this._allTreeMap.get(featureTreeId);
- this._removeDependencyRTreeCache(feature);
- this.clearDependencyForTree(feature);
+ this.clearDependencyForTree(this._allTreeMap.get(featureTreeId));
this._removeAllTreeMap(featureTreeId);
});
- this._featureFormulaData[unitId]![sheetId] = {};
- } else if (this._featureFormulaData[unitId]) {
- const unitFeatureData = this._featureFormulaData[unitId]!;
- Object.keys(unitFeatureData).forEach((sheetId) => {
- if (sheetId == null) {
- return;
- }
+ sheetMap.clear(); // 清空该 sheetId 对应的公式依赖数据
+ } else if (unitMap) {
+ unitMap.forEach((sheetMap, sheetId) => {
this._removeDependencyRTreeCacheById(unitId, sheetId);
- Object.values(unitFeatureData[sheetId]!).forEach((featureTreeId) => {
+ sheetMap.forEach((featureTreeId) => {
if (featureTreeId == null) {
return;
}
- const feature = this._allTreeMap.get(featureTreeId);
- this.clearDependencyForTree(feature);
+ this.clearDependencyForTree(this._allTreeMap.get(featureTreeId));
this._removeAllTreeMap(featureTreeId);
});
});
- this._featureFormulaData[unitId] = null;
+ this._featureFormulaData.delete(unitId); // 删除整个 unitId 对应的数据
}
}
getFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string) {
- const treeId = this._featureFormulaData[unitId]?.[sheetId]?.[featureId];
- if (treeId == null) {
- return null;
- }
- return this._allTreeMap.get(treeId);
+ return this._featureFormulaData.get(unitId)?.get(sheetId)?.get(featureId);
}
- addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: FormulaDependencyTree) {
- if (!this._formulaData[unitId]) {
- this._formulaData[unitId] = {};
+ addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: IFormulaDependencyTree) {
+ if (!this._formulaData.has(unitId)) {
+ this._formulaData.set(unitId, new Map<string, ObjectMatrix<number>>());
}
- if (!this._formulaData[unitId]![sheetId]) {
- this._formulaData[unitId]![sheetId] = new ObjectMatrix<number>();
+ const unitMap = this._formulaData.get(unitId)!;
+
+ if (!unitMap.has(sheetId)) {
+ unitMap.set(sheetId, new ObjectMatrix<number>());
}
- this._formulaData[unitId]![sheetId].setValue(row, column, dependencyTree.treeId);
- this._allTreeMap.set(dependencyTree.treeId, dependencyTree);
+ const sheetMatrix = unitMap.get(sheetId)!;
+
+ sheetMatrix.setValue(row, column, dependencyTree.treeId);
+ // this._allTreeMap.set(dependencyTree.treeId, dependencyTree);
+ this._addAllTreeMap(dependencyTree);
}
removeFormulaDependency(unitId: string, sheetId: string, row: number, column: number) {
- if (this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {
- const deleteTreeId = this._formulaData[unitId]![sheetId].getValue(row, column);
+ const unitMap = this._formulaData.get(unitId);
+ if (unitMap && unitMap.has(sheetId)) {
+ const sheetMatrix = unitMap.get(sheetId)!;
+ const deleteTreeId = sheetMatrix.getValue(row, column);
if (deleteTreeId == null) {
return;
}
- const deleteTree = this._allTreeMap.get(deleteTreeId);
- this._removeDependencyRTreeCache(deleteTree);
- this.clearDependencyForTree(deleteTree);
- this._formulaData[unitId]![sheetId].realDeleteValue(row, column);
+
+ this._removeDependencyRTreeCache(deleteTreeId);
+
+ sheetMatrix.realDeleteValue(row, column);
+ this.clearDependencyForTree(this._allTreeMap.get(deleteTreeId));
this._removeAllTreeMap(deleteTreeId);
}
}
clearFormulaDependency(unitId: string, sheetId?: string) {
- if (sheetId && this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {
+ const unitMap = this._formulaData.get(unitId);
+
+ if (sheetId && unitMap && unitMap.has(sheetId)) {
+ const sheetMatrix = unitMap.get(sheetId)!;
this._removeDependencyRTreeCacheById(unitId, sheetId);
- this._formulaData[unitId]![sheetId].forValue((row, column, treeId) => {
+
+ sheetMatrix.forValue((row, column, treeId) => {
if (treeId == null) {
return true;
}
- const tree = this._allTreeMap.get(treeId);
- this.clearDependencyForTree(tree);
+ this.clearDependencyForTree(this._allTreeMap.get(treeId));
this._removeAllTreeMap(treeId);
});
- this._formulaData[unitId]![sheetId].reset();
- } else if (this._formulaData[unitId]) {
- const unitFormulaData = this._formulaData[unitId]!;
- Object.keys(unitFormulaData).forEach((sheetId) => {
- if (sheetId == null) {
- return;
- }
+ sheetMatrix.reset();
+ } else if (unitMap) {
+ unitMap.forEach((sheetMatrix, sheetId) => {
this._removeDependencyRTreeCacheById(unitId, sheetId);
- unitFormulaData[sheetId].forValue((row, column, treeId) => {
+
+ sheetMatrix.forValue((row, column, treeId) => {
if (treeId == null) {
return true;
}
- const tree = this._allTreeMap.get(treeId);
- this.clearDependencyForTree(tree);
+ this.clearDependencyForTree(this._allTreeMap.get(treeId));
this._removeAllTreeMap(treeId);
});
});
- this._formulaData[unitId] = null;
+ this._formulaData.delete(unitId); // 删除整个 unitId 的数据
}
}
- clearDependencyAll() {
- this._otherFormulaData = {};
- this._featureFormulaData = {};
- this._formulaData = {};
- this._dependencyRTreeCache.clear();
- this._restDependencyTreeId();
- }
-
getFormulaDependency(unitId: string, sheetId: string, row: number, column: number) {
- const treeId = this._formulaData[unitId]?.[sheetId]?.getValue(row, column);
- if (treeId == null) {
- return null;
- }
- return this._allTreeMap.get(treeId);
+ return this._formulaData.get(unitId)?.get(sheetId)?.getValue(row, column);
}
- addDependencyRTreeCache(tree: FormulaDependencyTree) {
+ addDependencyRTreeCache(tree: IFormulaDependencyTree) {
const searchRanges: IRTreeItem[] = [];
for (let i = 0; i < tree.rangeList.length; i++) {
const unitRangeWithNum = tree.rangeList[i];
@@ -537,6 +466,37 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
this._dependencyRTreeCache.bulkInsert(searchRanges);
+
+ this._addAllTreeMap(tree);
+ }
+
+ /**
+ * Clear the dependency relationship of the tree.
+ * establish the relationship between the parent and the child.
+ * @param shouldBeClearTree
+ */
+ clearDependencyForTree(shouldBeClearTree: Nullable<IFormulaDependencyTree>) {
+ if (shouldBeClearTree == null) {
+ return;
+ }
+
+ const parents = shouldBeClearTree.parents;
+
+ const children = shouldBeClearTree.children;
+
+ const allTreeMap = this._allTreeMap;
+
+ for (const parentTreeId of parents) {
+ const parent = allTreeMap.get(parentTreeId);
+ parent?.children.delete(shouldBeClearTree.treeId);
+ }
+
+ for (const childTreeId of children) {
+ const child = allTreeMap.get(childTreeId);
+ child?.parents.delete(shouldBeClearTree.treeId);
+ }
+
+ shouldBeClearTree.dispose();
}
private _restDependencyTreeId() {
@@ -553,48 +513,70 @@ export class DependencyManagerService extends Disposable implements IDependencyM
this._dependencyRTreeCache.removeById(unitId, sheetId);
}
- private _removeDependencyRTreeCache(tree: Nullable<FormulaDependencyTree>) {
- if (tree == null) {
+ private _removeDependencyRTreeCache(treeId: Nullable<number>) {
+ if (treeId == null) {
return;
}
- const searchRanges: IRTreeItem[] = [];
- for (let i = 0; i < tree.rangeList.length; i++) {
- const unitRangeWithNum = tree.rangeList[i];
- const { unitId, sheetId, range } = unitRangeWithNum;
+ const treeRangeMap = this._allTreeMap.get(treeId);
- searchRanges.push({
- unitId,
- sheetId,
- range,
- id: tree.treeId,
- });
- }
+ if (treeRangeMap) {
+ const searchRanges: IRTreeItem[] = [];
+ for (let i = 0; i < treeRangeMap.rangeList.length; i++) {
+ const unitRangeWithNum = treeRangeMap.rangeList[i];
+ const { unitId, sheetId, range } = unitRangeWithNum;
- this._dependencyRTreeCache.bulkRemove(searchRanges);
+ searchRanges.push({
+ unitId,
+ sheetId,
+ range,
+ id: treeId,
+ });
+ }
+ this._dependencyRTreeCache.bulkRemove(searchRanges);
+ }
}
- removeFormulaDependencyByDefinedName(unitId: string, definedName: string) {
- if (this._formulaData[unitId]) {
- Object.values(this._formulaData[unitId]).forEach((sheet) => {
- sheet.forValue((row, column, treeId) => {
- const tree = this._allTreeMap.get(treeId);
- if (tree?.nodeData?.node.hasDefinedName(definedName)) {
- this._removeDependencyRTreeCache(tree);
- this.clearDependencyForTree(tree);
- sheet.realDeleteValue(row, column);
- }
- });
- });
+ private _addDefinedName(unitId: string, definedName: string, treeId: number) {
+ if (!this._definedNameMap.has(unitId)) {
+ this._definedNameMap.set(unitId, new Map<string, Set<number>>());
+ }
+
+ const unitMap = this._definedNameMap.get(unitId)!;
+
+ if (!unitMap.has(definedName)) {
+ unitMap.set(definedName, new Set<number>());
}
+
+ const treeSet = unitMap.get(definedName)!;
+ treeSet.add(treeId);
}
- openKdTree() {
- this._dependencyRTreeCache.openKdTree();
+ addFormulaDependencyByDefinedName(tree: IFormulaDependencyTree, node: Nullable<AstRootNode>) {
+ const treeId = tree.treeId;
+ // const node = tree.node;
+
+ const definedNames = node?.getDefinedNames() || [];
+
+ for (const definedName of definedNames) {
+ this._addDefinedName(tree.unitId, definedName, treeId);
+ }
}
- closeKdTree() {
- this._dependencyRTreeCache.closeKdTree();
+ removeFormulaDependencyByDefinedName(unitId: string, definedName: string) {
+ const unitMap = this._definedNameMap.get(unitId);
+
+ if (unitMap) {
+ const treeSet = unitMap.get(definedName);
+ if (treeSet) {
+ for (const treeId of treeSet) {
+ this._removeDependencyRTreeCache(treeId);
+ this.clearDependencyForTree(this._allTreeMap.get(treeId));
+ this._removeAllTreeMap(treeId);
+ }
+ treeSet.clear();
+ }
+ }
}
private _removeAllTreeMap(treeId: Nullable<number>) {
@@ -603,6 +585,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
this._allTreeMap.delete(treeId);
}
+
+ private _addAllTreeMap(tree: IFormulaDependencyTree) {
+ this._allTreeMap.set(tree.treeId, tree);
+ }
}
export const IDependencyManagerService = createIdentifier<DependencyManagerService>(
diff --git a/packages/engine-formula/src/services/other-formula-manager.service.ts b/packages/engine-formula/src/services/other-formula-manager.service.ts
index 5e78dd2b72..b094639664 100644
--- a/packages/engine-formula/src/services/other-formula-manager.service.ts
+++ b/packages/engine-formula/src/services/other-formula-manager.service.ts
@@ -15,9 +15,9 @@
*/
import type { Nullable } from '@univerjs/core';
-import { createIdentifier, Disposable } from '@univerjs/core';
+import type { IDirtyUnitOtherFormulaMap, IOtherFormulaData, IOtherFormulaDataItem } from '../basics/common';
-import type { IDirtyUnitOtherFormulaMap, IFormulaDataItem, IOtherFormulaData } from '../basics/common';
+import { createIdentifier, Disposable } from '@univerjs/core';
export interface IOtherFormulaManagerSearchParam {
unitId: string;
@@ -26,7 +26,7 @@ export interface IOtherFormulaManagerSearchParam {
}
export interface IOtherFormulaManagerInsertParam extends IOtherFormulaManagerSearchParam {
- item: IFormulaDataItem;
+ item: IOtherFormulaDataItem;
}
export interface IOtherFormulaManagerService {
@@ -34,7 +34,7 @@ export interface IOtherFormulaManagerService {
remove(searchParam: IOtherFormulaManagerSearchParam): void;
- get(searchParam: IOtherFormulaManagerSearchParam): Nullable<IFormulaDataItem>;
+ get(searchParam: IOtherFormulaManagerSearchParam): Nullable<IOtherFormulaDataItem>;
has(searchParam: IOtherFormulaManagerSearchParam): boolean;
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index 7523de25dd..291b604eb9 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -28,11 +28,12 @@ import type { ArrayValueObject } from '../engine/value-object/array-value-object
import { createIdentifier, Disposable, isNullCell, ObjectMatrix } from '@univerjs/core';
import { isInDirtyRange } from '../basics/dirty';
import { ErrorType } from '../basics/error-type';
+
import { getRuntimeFeatureCell } from '../engine/utils/get-runtime-feature-cell';
-import { clearNumberFormatTypeCache, clearStringToNumberPatternCache } from '../engine/utils/numfmt-kit';
+import { clearNumberFormatTypeCache, clearStringToNumberPatternCache } from '../engine/utils/numfmt-kit';
import { clearReferenceToRangeCache } from '../engine/utils/reference-cache';
-import { objectValueToCellValue } from '../engine/utils/value-object';
+import { clearReferenceObjectCache, objectValueToCellValue } from '../engine/utils/value-object';
import { type BaseValueObject, ErrorValueObject } from '../engine/value-object/base-value-object';
import { IFormulaCurrentConfigService } from './current-data.service';
@@ -130,7 +131,7 @@ export interface IFormulaRuntimeService {
getFormulaExecuteStage(): FormulaExecuteStageType;
- setRuntimeOtherData(formulaId: string, functionVariant: FunctionVariantType): void;
+ setRuntimeOtherData(formulaId: string, x: number, y: number, functionVariant: FunctionVariantType): void;
getRuntimeOtherData(): IRuntimeOtherUnitDataType;
@@ -365,12 +366,15 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
this._isCycleDependency = false;
this._totalFormulasToCalculate = 0;
this._completedFormulasCount = 0;
+
+ this.clearReferenceAndNumberformatCache();
}
clearReferenceAndNumberformatCache() {
clearNumberFormatTypeCache();
clearStringToNumberPatternCache();
clearReferenceToRangeCache();
+ clearReferenceObjectCache();
}
setCurrent(row: number, column: number, rowCount: number, columnCount: number, sheetId: string, unitId: string) {
@@ -394,7 +398,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
return this._functionDefinitionPrivacyVar.get(lambdaId);
}
- setRuntimeOtherData(formulaId: string, functionVariant: FunctionVariantType) {
+ setRuntimeOtherData(formulaId: string, x: number, y: number, functionVariant: FunctionVariantType) {
const subUnitId = this._currentSubUnitId;
const unitId = this._currentUnitId;
@@ -404,7 +408,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
const unitData = this._runtimeOtherData[unitId]!;
- if (unitData[subUnitId] === undefined) {
+ if (unitData[subUnitId] === undefined || unitData[subUnitId] === null) {
unitData[subUnitId] = {};
}
@@ -433,7 +437,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
cellDatas = [[objectValueToCellValue(functionVariant as BaseValueObject)!]];
}
- subComponentData![formulaId] = cellDatas;
+ if (subComponentData[formulaId] === undefined || subComponentData[formulaId] === null) {
+ subComponentData[formulaId] = {};
+ }
+
+ if (subComponentData[formulaId][y] === undefined || subComponentData[formulaId][y] === null) {
+ subComponentData[formulaId][y] = {};
+ }
+
+ // x represents the column offset, y represents the row offset
+ subComponentData[formulaId][y][x] = cellDatas;
}
// eslint-disable-next-line max-lines-per-function
diff --git a/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
index 12dafd06e6..27b25fb01b 100644
--- a/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
+++ b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
@@ -15,13 +15,15 @@
*/
import type { FUniver, ICellData, Injector, IStyleData, Nullable } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService } from '@univerjs/core';
-import { SetArrayFormulaDataMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
+import type { IUniverSheetsFormulaBaseConfig } from '@univerjs/sheets-formula';
+import { ICommandService, IConfigService, IUniverInstanceService } from '@univerjs/core';
+import { SetArrayFormulaDataMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';
+import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '@univerjs/sheets-formula';
import { beforeEach, describe, expect, it } from 'vitest';
-import { createFormulaTestBed } from './create-formula-test-bed';
+import { createFormulaTestBed } from './create-formula-test-bed';
import '../../everything';
describe('Test FFormula', () => {
@@ -103,4 +105,20 @@ describe('Test FFormula', () => {
formula.executeCalculation();
formula.stopCalculation();
});
+
+ it('FFormula setInitialFormulaComputing', () => {
+ const formula = univerAPI.getFormula();
+
+ const configService = get(IConfigService);
+
+ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, {});
+
+ const config = configService.getConfig<Partial<IUniverSheetsFormulaBaseConfig>>(PLUGIN_CONFIG_KEY_BASE);
+
+ expect(config?.initialFormulaComputing).toBeUndefined();
+
+ formula.setInitialFormulaComputing(CalculationMode.FORCED);
+
+ expect(config?.initialFormulaComputing).toBe(CalculationMode.FORCED);
+ });
});
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/color-scale.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/color-scale.ts
index bca38e1143..e559717ced 100644
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/color-scale.ts
+++ b/packages/sheets-conditional-formatting/src/services/calculate-unit/color-scale.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
+import type { IColorScale, IConditionFormattingRule } from '../../models/type';
+import type { ICalculateUnit } from './type';
import { CellValueType, ColorKit, ObjectMatrix, Range } from '@univerjs/core';
import { isObject } from '@univerjs/engine-render';
import { CFRuleType } from '../../base/const';
-import type { IColorScale, IConditionFormattingRule } from '../../models/type';
import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
import { filterRange, getColorScaleFromValue, getValueByType, isNullable } from './utils';
-import type { ICalculateUnit } from './type';
const emptyStyle = '';
export const colorScaleCellCalculateUnit: ICalculateUnit = {
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts
index fd9d13f49a..5a925db026 100644
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts
+++ b/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts
@@ -62,7 +62,7 @@ export const dataBarCellCalculateUnit: ICalculateUnit = {
if (_min.status === FormulaResultStatus.WAIT) {
return conditionalFormattingFormulaService.getCache(context.unitId, context.subUnitId, rule.cfId) || computeResult;
} else if (_min.status === FormulaResultStatus.SUCCESS) {
- const v = Number(_min.result);
+ const v = Number(_min.result); // Get the minimum value
min = Number.isNaN(v) ? 0 : v;
} else {
return computeResult;
@@ -70,7 +70,8 @@ export const dataBarCellCalculateUnit: ICalculateUnit = {
if (_max.status === FormulaResultStatus.WAIT) {
return conditionalFormattingFormulaService.getCache(context.unitId, context.subUnitId, rule.cfId) || computeResult;
} else if (_max.status === FormulaResultStatus.SUCCESS) {
- const v = Number.isNaN(Number(_max.result)) ? 0 : Number(_max.result);
+ const maxResult = Number(_max.result); // Get the maximum value
+ const v = Number.isNaN(maxResult) ? 0 : maxResult;
max = Math.max(v, min);
min = Math.min(v, min);
} else {
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/highlight-cell.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/highlight-cell.ts
index 8cfdd16958..1dd1fc8d87 100644
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/highlight-cell.ts
+++ b/packages/sheets-conditional-formatting/src/services/calculate-unit/highlight-cell.ts
@@ -19,8 +19,8 @@
import type { IStyleBase } from '@univerjs/core';
import type { IAverageHighlightCell, IConditionFormattingRule, IFormulaHighlightCell, IHighlightCell, INumberHighlightCell, IRankHighlightCell, ITextHighlightCell, ITimePeriodHighlightCell } from '../../models/type';
import type { ICalculateUnit } from './type';
-import { CellValueType, ObjectMatrix, Range, Rectangle, Tools } from '@univerjs/core';
-import { deserializeRangeWithSheet, ERROR_TYPE_SET, generateStringWithSequence, LexerTreeBuilder, sequenceNodeType, serializeRange } from '@univerjs/engine-formula';
+import { CellValueType, ObjectMatrix, Range } from '@univerjs/core';
+import { ERROR_TYPE_SET } from '@univerjs/engine-formula';
import dayjs from 'dayjs';
import { CFNumberOperator, CFRuleType, CFSubRuleType, CFTextOperator, CFTimePeriodOperator } from '../../base/const';
import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
@@ -31,10 +31,10 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
type: CFRuleType.highlightCell,
handle: async (rule: IConditionFormattingRule, context) => {
const ruleConfig = rule.rule as IHighlightCell;
- const { worksheet } = context;
+
+ const { worksheet, unitId, subUnitId } = context;
const ranges = filterRange(rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
- // eslint-disable-next-line complexity
const getCache = () => {
switch (ruleConfig.subType) {
case CFSubRuleType.average: {
@@ -94,17 +94,10 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
}
}
case CFSubRuleType.formula: {
- const subRuleConfig = ruleConfig as IFormulaHighlightCell;
- const lexerTreeBuilder = context.accessor.get(LexerTreeBuilder);
- const formulaString = subRuleConfig.value;
- const sequenceNodes = lexerTreeBuilder.sequenceNodesBuilder(formulaString);
- if (!sequenceNodes) {
- return {
- sequenceNodes: null,
- };
- } else {
- return { sequenceNodes };
- }
+ const _ruleConfig = ruleConfig as IFormulaHighlightCell;
+ const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
+ conditionalFormattingFormulaService.registerFormulaWithRange(context.unitId, context.subUnitId, rule.cfId, _ruleConfig.value, rule.ranges);
+ break;
}
case CFSubRuleType.timePeriod: {
const subRuleConfig = ruleConfig as ITimePeriodHighlightCell;
@@ -326,49 +319,26 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
return uniqueCache.get(value) !== 1;
}
case CFSubRuleType.formula: {
- if (!cache?.sequenceNodes) {
- return false;
- }
- const { unitId, subUnitId } = context;
+ const _ruleConfig = ruleConfig as IFormulaHighlightCell;
const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
-
- const getRangeFromCell = (row: number, col: number) => ({ startRow: row, endRow: row, startColumn: col, endColumn: col });
- const originRange = getRangeFromCell(rule.ranges[0].startRow, rule.ranges[0].startColumn);
- const sequenceNodes = Tools.deepClone(cache.sequenceNodes);
- const transformSequenceNodes = Array.isArray(sequenceNodes)
- ? sequenceNodes.map((node) => {
- if (typeof node === 'object' && node.nodeType === sequenceNodeType.REFERENCE) {
- const gridRangeName = deserializeRangeWithSheet(node.token);
- const relativeRange = Rectangle.getRelativeRange(gridRangeName.range, originRange);
- const newRange = Rectangle.getPositionRange(relativeRange, getRangeFromCell(row, col), gridRangeName.range);
- const newToken = serializeRange(newRange);
- return {
- ...node, token: newToken,
- };
- }
- return node;
- })
- : sequenceNodes;
- let formulaString = transformSequenceNodes && generateStringWithSequence(transformSequenceNodes);
- if (formulaString) {
- formulaString = `=${formulaString}`;
- conditionalFormattingFormulaService.registerFormula(unitId, subUnitId, rule.cfId, formulaString);
- const formulaItem = conditionalFormattingFormulaService.getFormulaResult(unitId, subUnitId, formulaString);
- if (formulaItem && formulaItem.status === FormulaResultStatus.SUCCESS) {
- return formulaItem.result === true;
- } else {
- // If the formula triggers the calculation, wait for the result,
- // and use the previous style cache until the result comes out
- const cache = conditionalFormattingFormulaService.getCache(unitId, subUnitId, rule.cfId);
- const style = cache?.getValue(row, col);
- return style && style !== EMPTY_STYLE;
- }
+ const result = conditionalFormattingFormulaService.getFormulaResult(unitId, subUnitId, rule.cfId, _ruleConfig.value, row, col);
+ if (result && result.status === FormulaResultStatus.SUCCESS) {
+ return result.result === true;
}
return false;
}
}
};
const computeResult = new ObjectMatrix<IStyleBase>();
+ if (ruleConfig.subType === CFSubRuleType.formula) {
+ const _ruleConfig = ruleConfig as IFormulaHighlightCell;
+ const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
+ const aliasItemMap = conditionalFormattingFormulaService.getSubUnitFormulaMap(unitId, subUnitId);
+ const item = aliasItemMap?.getValue(conditionalFormattingFormulaService.createCFormulaId(rule.cfId, _ruleConfig.value), ['id']);
+ if (!item || (item.status !== FormulaResultStatus.SUCCESS)) {
+ return conditionalFormattingFormulaService.getCache(unitId, subUnitId, rule.cfId) || computeResult;
+ }
+ }
ranges.forEach((range) => {
Range.foreach(range, (row, col) => {
if (check(row, col)) {
@@ -382,3 +352,4 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
return computeResult;
},
};
+
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts
index 7d4ec2f363..ced9d49176 100644
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts
+++ b/packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts
@@ -14,16 +14,16 @@
* limitations under the License.
*/
-import { CellValueType, ObjectMatrix, Range } from '@univerjs/core';
import type { CFNumberOperator } from '../../base/const';
-import { CFRuleType } from '../../base/const';
-
-import type { IIconSetRenderParams } from '../../render/type';
import type { IConditionFormattingRule, IIconSet } from '../../models/type';
-import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
-import { compareWithNumber, filterRange, getOppositeOperator, getValueByType, isNullable } from './utils';
+import type { IIconSetRenderParams } from '../../render/type';
+
import type { ICalculateUnit } from './type';
+import { CellValueType, ObjectMatrix, Range } from '@univerjs/core';
+import { CFRuleType } from '../../base/const';
+import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
import { EMPTY_STYLE } from './type';
+import { compareWithNumber, filterRange, getOppositeOperator, getValueByType, isNullable } from './utils';
export const iconSetCalculateUnit: ICalculateUnit = {
type: CFRuleType.iconSet,
@@ -46,7 +46,7 @@ export const iconSetCalculateUnit: ICalculateUnit = {
});
});
- const computeResult = new ObjectMatrix<IIconSetRenderParams >();
+ const computeResult = new ObjectMatrix<IIconSetRenderParams>();
ranges.forEach((range) => {
Range.foreach(range, (row, col) => {
computeResult.setValue(row, col, EMPTY_STYLE as IIconSetRenderParams);
@@ -74,7 +74,7 @@ export const iconSetCalculateUnit: ICalculateUnit = {
}
}
return result;
- }, [] as { operator: CFNumberOperator;value: number;iconType: string;iconId: string }[]);
+ }, [] as { operator: CFNumberOperator; value: number; iconType: string; iconId: string }[]);
const isShowValue = ruleConfig.isShowValue === undefined ? true : !!ruleConfig.isShowValue;
matrix.forValue((row, col, value) => {
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/utils.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/utils.ts
index 43dbfbc960..972e5ef3a1 100644
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/utils.ts
+++ b/packages/sheets-conditional-formatting/src/services/calculate-unit/utils.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, IRange } from '@univerjs/core';
+import type { CellValue, ICellData, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
import type { IConditionFormattingRule, IValueConfig } from '../../models/type';
import type { IContext } from './type';
import { BooleanNumber, CellValueType, ColorKit, ObjectMatrix, Range } from '@univerjs/core';
@@ -158,8 +158,8 @@ export const getValueByType = (value: IValueConfig, matrix: ObjectMatrix<number>
const { accessor, unitId, subUnitId, cfId } = context;
const formulaText = String(value.value);
const conditionalFormattingFormulaService = accessor.get(ConditionalFormattingFormulaService);
- conditionalFormattingFormulaService.registerFormula(unitId, subUnitId, cfId, formulaText);
- const result = conditionalFormattingFormulaService.getFormulaResult(unitId, subUnitId, formulaText);
+ conditionalFormattingFormulaService.registerFormulaWithRange(unitId, subUnitId, cfId, formulaText);
+ const result = conditionalFormattingFormulaService.getFormulaResult(unitId, subUnitId, cfId, formulaText);
return result;
}
case CFValueType.num: {
@@ -301,3 +301,11 @@ export const filterRange = (ranges: IRange[], maxRow: number, maxCol: number): I
return _range;
}).filter((range) => !!range);
};
+
+export function getMaxInFormulaResult(result: IObjectMatrixPrimitiveType<Nullable<CellValue>>) {
+ let max = 0;
+ new ObjectMatrix(result).forValue((row, col, value) => {
+ max = Math.max(Number.isNaN(max) ? 0 : max, Number(value));
+ });
+ return max;
+}
diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.ts
index 3800b39482..add712f7b6 100644
--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.ts
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.ts
@@ -14,19 +14,19 @@
* limitations under the License.
*/
-import type { ICellData, Nullable, ObjectMatrix } from '@univerjs/core';
+import type { ICellData, IRange, Nullable } from '@univerjs/core';
import type { IRemoveOtherFormulaMutationParams, ISetFormulaCalculationResultMutation, ISetOtherFormulaMutationParams } from '@univerjs/engine-formula';
import type { IConditionalFormattingFormulaMarkDirtyParams } from '../commands/mutations/formula-mark-dirty.mutation';
-import { BooleanNumber, CellValueType, Disposable, ICommandService, Inject, Injector, RefAlias, toDisposable, Tools } from '@univerjs/core';
+import type { IConditionalFormattingRuleConfig } from '../models/type';
+import { BooleanNumber, CellValueType, Disposable, ICommandService, Inject, Injector, ObjectMatrix, RefAlias, toDisposable, Tools } from '@univerjs/core';
import {
IActiveDirtyManagerService,
RemoveOtherFormulaMutation,
SetFormulaCalculationResultMutation,
SetOtherFormulaMutation,
} from '@univerjs/engine-formula';
-import { Subject } from 'rxjs';
-import { bufferTime, filter, map } from 'rxjs/operators';
+import { CFRuleType, CFSubRuleType, CFValueType } from '../base/const';
import { ConditionalFormattingFormulaMarkDirty } from '../commands/mutations/formula-mark-dirty.mutation';
import { ConditionalFormattingRuleModel } from '../models/conditional-formatting-rule-model';
import { ConditionalFormattingViewModel } from '../models/conditional-formatting-view-model';
@@ -34,7 +34,13 @@ import { ConditionalFormattingService } from './conditional-formatting.service';
// eslint-disable-next-line ts/consistent-type-definitions
type IFormulaItem = {
- formulaText: string;cfId: string;result?: boolean | number | string;status: FormulaResultStatus;count: number;formulaId: string;
+ formulaText: string;
+ cfId: string;
+ id: string;
+ ranges: IRange[];
+ status: FormulaResultStatus;
+ formulaId: string;
+ result: ObjectMatrix<string | number | boolean | undefined | null | void>;
};
export enum FormulaResultStatus {
NOT_REGISTER = 1,
@@ -53,16 +59,12 @@ const getResultFromFormula = (formulaResult: Nullable<ICellData>[][]) => {
// TODO: @Gggpound
// It may be possible later to abstract a service that manages the results of an asynchronous calculation to handle the use of the last calculation before waiting for the result to return.
export class ConditionalFormattingFormulaService extends Disposable {
- private _formulaMap: Map<string, Map<string, RefAlias<IFormulaItem, 'formulaId' | 'formulaText'>>> = new Map();
+ // Cache Formula ID and formula mapping.
+ private _formulaMap: Map<string, Map<string, RefAlias<IFormulaItem, 'id' | 'formulaId'>>> = new Map();
+ // Cache style results, style replacement needs to wait until the formula has been calculated, then replace.
private _cache: Map<string, Map<string, Map<string, ObjectMatrix<unknown>>>> = new Map();
- private _formulaChange$ = new Subject<{
- unitId: string; subUnitId: string; cfId: string; formulaText: string;formulaId: string;
- }>();
-
- public formulaChange$ = this._formulaChange$.asObservable();
-
constructor(
@Inject(ICommandService) private _commandService: ICommandService,
@Inject(Injector) private _injector: Injector,
@@ -81,10 +83,6 @@ export class ConditionalFormattingFormulaService extends Disposable {
}));
}
- override dispose(): void {
- this._formulaChange$.complete();
- }
-
private _initCache() {
const _conditionalFormattingService = this._injector.get(ConditionalFormattingService);
this.disposeWithMe(_conditionalFormattingService.ruleComputeStatus$.subscribe((option) => {
@@ -103,12 +101,33 @@ export class ConditionalFormattingFormulaService extends Disposable {
}
private _initRuleChange() {
+ const isNeedMarkFormulaDirty = (rule: IConditionalFormattingRuleConfig) => {
+ switch (rule.type) {
+ case CFRuleType.colorScale: {
+ return rule.config.some((item) => item.value.type === CFValueType.formula);
+ }
+ case CFRuleType.highlightCell: {
+ return rule.subType === CFSubRuleType.formula;
+ }
+ case CFRuleType.dataBar: {
+ return [rule.config.max, rule.config.min].some((item) => item.type === CFValueType.formula);
+ }
+
+ case CFRuleType.iconSet: {
+ return rule.config.some((item) => item.value.type === CFValueType.formula);
+ }
+ }
+ };
this.disposeWithMe(this._conditionalFormattingRuleModel.$ruleChange.subscribe((option) => {
- const { unitId, subUnitId, rule } = option;
+ const { unitId, subUnitId, rule, oldRule } = option;
if (option.type === 'delete') {
this._removeFormulaByCfId(unitId, subUnitId, rule.cfId);
}
- // @gggpound: todo clear cache when set rule
+ if (option.type === 'set') {
+ if (isNeedMarkFormulaDirty(rule.rule) || (oldRule && isNeedMarkFormulaDirty(oldRule.rule))) {
+ this._removeFormulaByCfId(unitId, subUnitId, rule.cfId);
+ }
+ }
}));
}
@@ -119,21 +138,32 @@ export class ConditionalFormattingFormulaService extends Disposable {
const params = commandInfo.params as ISetFormulaCalculationResultMutation;
for (const unitId in params.unitOtherData) {
for (const subUnitId in params.unitOtherData[unitId]) {
- const map = this.getSubUnitFormulaMap(unitId, subUnitId);
- if (!map) {
- continue;
- }
- const cfIdSet = new Set<string>();
+ const cfIdsSet = new Set<string>();
for (const formulaId in params.unitOtherData[unitId]![subUnitId]) {
- const item = map.getValue(formulaId, ['formulaId']);
- if (item) {
- const value = getResultFromFormula(params.unitOtherData[unitId]![subUnitId]![formulaId]);
- item.result = value!;
- item.status = FormulaResultStatus.SUCCESS;
- cfIdSet.add(item.cfId);
+ const resultMatrix = new ObjectMatrix(params.unitOtherData[unitId][subUnitId][formulaId]);
+ const formulaMapAlias = this._ensureSubunitFormulaMap(unitId, subUnitId).getValue(formulaId, ['formulaId']);
+ if (!formulaMapAlias) {
+ continue;
}
+ const ranges = formulaMapAlias.ranges;
+
+ if (!ranges) {
+ continue;
+ }
+ const resultObject = formulaMapAlias.result;
+
+ // The engine's calculation result only has the offset, and the actual position needs to be calculated from the upper left corner.
+ const startRow = ranges[0].startRow;
+ const startCol = ranges[0].startColumn;
+
+ resultMatrix.forValue((row, col, value) => {
+ resultObject.setValue(startRow + row, startCol + col, getResultFromFormula(value));
+ });
+
+ formulaMapAlias.status = FormulaResultStatus.SUCCESS;
+ cfIdsSet.add(formulaMapAlias.cfId);
}
- for (const cfId of cfIdSet) {
+ for (const cfId of cfIdsSet) {
const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId);
rule && this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
}
@@ -144,50 +174,26 @@ export class ConditionalFormattingFormulaService extends Disposable {
// Register formula with Dirty Logic
this._activeDirtyManagerService.register(ConditionalFormattingFormulaMarkDirty.id,
- { commandId: ConditionalFormattingFormulaMarkDirty.id,
- getDirtyData(commandInfo) {
- const params = commandInfo.params as IConditionalFormattingFormulaMarkDirtyParams;
- return {
- dirtyUnitOtherFormulaMap: params,
- };
- } });
-
- // Sum up formulas that need to be marked dirty
- this.formulaChange$.pipe(bufferTime(16), filter((list) => !!list.length), map((list) => {
- return list.reduce((result, cur) => {
- const { unitId, subUnitId, formulaId, formulaText } = cur;
- if (!result[unitId]) {
- result[unitId] = {};
- }
- if (!result[unitId][subUnitId]) {
- result[unitId][subUnitId] = {};
- }
- result[unitId][subUnitId][formulaId] = { f: formulaText };
- return result;
- }, {} as { [unitId: string]: { [sunUnitId: string]: { [formulaId: string]: { f: string } } } });
- })).subscribe((result) => {
- for (const unitId in result) {
- for (const subUnitId in result[unitId]) {
- const value = result[unitId][subUnitId];
- const config: ISetOtherFormulaMutationParams = { unitId, subUnitId, formulaMap: value };
- this._commandService.executeCommand(SetOtherFormulaMutation.id, config).then(() => {
- this._commandService.executeCommand(ConditionalFormattingFormulaMarkDirty.id,
- { [unitId]: { [subUnitId]: value } } as unknown as IConditionalFormattingFormulaMarkDirtyParams);
- });
- }
- }
- });
+ {
+ commandId: ConditionalFormattingFormulaMarkDirty.id,
+ getDirtyData(commandInfo) {
+ const params = commandInfo.params as IConditionalFormattingFormulaMarkDirtyParams;
+ return {
+ dirtyUnitOtherFormulaMap: params,
+ };
+ },
+ });
}
private _ensureSubunitFormulaMap(unitId: string, subUnitId: string) {
let unitMap = this._formulaMap.get(unitId);
if (!unitMap) {
- unitMap = new Map<string, RefAlias<IFormulaItem, 'formulaId' | 'formulaText'>>();
+ unitMap = new Map<string, RefAlias<IFormulaItem, 'formulaId' | 'id'>>();
this._formulaMap.set(unitId, unitMap);
}
let subUnitMap = unitMap.get(subUnitId);
if (!subUnitMap) {
- subUnitMap = new RefAlias<IFormulaItem, 'formulaId' | 'formulaText'>([], ['formulaId', 'formulaText']);
+ subUnitMap = new RefAlias<IFormulaItem, 'formulaId' | 'id'>([], ['formulaId', 'id']);
unitMap.set(subUnitId, subUnitMap);
}
return subUnitMap;
@@ -230,50 +236,61 @@ export class ConditionalFormattingFormulaService extends Disposable {
return this._formulaMap.get(unitId)?.get(subUnitId);
}
- public registerFormula(unitId: string, subUnitId: string, cfId: string, formulaText: string) {
- const subUnitFormulaMap = this._ensureSubunitFormulaMap(unitId, subUnitId);
- const formulaItem = subUnitFormulaMap.getValue(formulaText, ['formulaText']);
- if (formulaItem) {
- if (!subUnitFormulaMap.getValues().some((item) => item.cfId === cfId)) {
- formulaItem.count++;
- }
+ public registerFormulaWithRange(unitId: string, subUnitId: string, cfId: string, formulaText: string, ranges: IRange[] = [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]) {
+ const formulaMap = this._ensureSubunitFormulaMap(unitId, subUnitId);
+ if (formulaMap.getValue(this.createCFormulaId(cfId, formulaText), ['id'])) {
return;
}
const formulaId = this._createFormulaId(unitId, subUnitId);
- subUnitFormulaMap.addValue({ formulaId, formulaText, cfId, status: FormulaResultStatus.WAIT, count: 1 });
- this._formulaChange$.next({ unitId, cfId, subUnitId, formulaText, formulaId });
+ formulaMap.addValue({
+ formulaText,
+ cfId,
+ id: this.createCFormulaId(cfId, formulaText),
+ ranges,
+ formulaId,
+ status: FormulaResultStatus.WAIT,
+ result: new ObjectMatrix(),
+ });
+ const params: ISetOtherFormulaMutationParams = {
+ unitId,
+ subUnitId,
+ formulaMap: {
+ [formulaId]: {
+ f: formulaText,
+ ranges,
+ },
+ },
+ };
+
+ this._commandService.executeCommand(SetOtherFormulaMutation.id, params).then(() => {
+ this._commandService.executeCommand(ConditionalFormattingFormulaMarkDirty.id,
+ { [unitId]: { [subUnitId]: { [formulaId]: true } } });
+ });
}
private _removeFormulaByCfId(unitId: string, subUnitId: string, cfId: string) {
const subUnitFormulaMap = this._ensureSubunitFormulaMap(unitId, subUnitId);
- const reduceCount = (formulaText: string) => {
- const formulaItem = subUnitFormulaMap.getValue(formulaText, ['formulaText']);
- if (formulaItem) {
- formulaItem.count--;
- if (formulaItem.count <= 0) {
- subUnitFormulaMap.deleteValue(formulaText);
- }
- }
- };
+ subUnitFormulaMap.deleteValue(cfId);
const values = subUnitFormulaMap.getValues().filter((item) => item.cfId === cfId);
- values.forEach((item) => {
- reduceCount(item.formulaText);
+ values.forEach((v) => {
+ subUnitFormulaMap.deleteValue(v.id, ['id']);
});
const formulaIdList = values.map((item) => item.formulaId);
this._commandService.executeCommand(RemoveOtherFormulaMutation.id, { unitId, subUnitId, formulaIdList } as IRemoveOtherFormulaMutationParams);
}
- public getFormulaResult(unitId: string, subUnitId: string, formulaText: string) {
+ public getFormulaResult(unitId: string, subUnitId: string, cfId: string, formulaText: string, row: number = 0, col: number = 0) {
const map = this.getSubUnitFormulaMap(unitId, subUnitId);
if (!map) {
return { status: FormulaResultStatus.NOT_REGISTER };
}
- const item = map.getValue(formulaText, ['formulaText']);
+ const item = map.getValue(this.createCFormulaId(cfId, formulaText), ['id']);
if (!item) {
return { status: FormulaResultStatus.NOT_REGISTER };
}
- if (FormulaResultStatus.SUCCESS === item.status) {
- return { result: item.result, status: FormulaResultStatus.SUCCESS };
+ if (FormulaResultStatus.SUCCESS === item.status && item.result) {
+ const result = item.result.getValue(row, col);
+ return { result, status: FormulaResultStatus.SUCCESS };
}
if (item.status === FormulaResultStatus.WAIT) {
@@ -283,7 +300,11 @@ export class ConditionalFormattingFormulaService extends Disposable {
return { status: FormulaResultStatus.ERROR };
}
- _createFormulaId(unitId: string, subUnitId: string) {
+ private _createFormulaId(unitId: string, subUnitId: string) {
return `sheet.cf_${unitId}_${subUnitId}_${Tools.generateRandomId(8)}`;
}
+
+ public createCFormulaId(cfId: string, formulaText: string) {
+ return `${cfId}_${formulaText}`;
+ }
}
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
index 0f8a7d2aa0..00daf6e082 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
@@ -192,7 +192,7 @@ export class SheetsDataValidationRenderController extends RxDisposable {
const styleMap = workbook.getStyles();
return (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};
},
- }),
+ }, row, col),
},
interceptorAutoHeight: () => {
const skeleton = this._renderManagerService.getRenderById(unitId)
@@ -359,7 +359,7 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {
const styleMap = workbook.getStyles();
return (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};
},
- }),
+ }, row, col),
},
interceptorAutoHeight: () => {
const skeleton = this._renderManagerService.getRenderById(unitId)
diff --git a/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx b/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx
index 04c64ba209..c250bceac4 100644
--- a/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx
@@ -35,11 +35,15 @@ export function CustomFormulaInput(props: IFormulaInputProps) {
unitId={unitId}
subUnitId={subUnitId}
isFocus={isFocusFormulaEditor}
- onChange={(v = '') => {
- const formula = v || '';
+ onChange={(newValue) => {
+ const newFormula = (newValue ?? '').trim();
+ if (newFormula === value?.formula1) {
+ return;
+ }
+
onChange?.({
...value,
- formula1: (formula).trim(),
+ formula1: newFormula,
});
}}
errorText={formula1Res}
diff --git a/packages/sheets-data-validation-ui/src/views/widgets/checkbox-widget.ts b/packages/sheets-data-validation-ui/src/views/widgets/checkbox-widget.ts
index bd12d85c6b..adf177406a 100644
--- a/packages/sheets-data-validation-ui/src/views/widgets/checkbox-widget.ts
+++ b/packages/sheets-data-validation-ui/src/views/widgets/checkbox-widget.ts
@@ -88,12 +88,12 @@ export class CheckboxRender implements IBaseDataValidationWidget {
private async _parseFormula(rule: IDataValidationRule, unitId: string, subUnitId: string): Promise<IFormulaResult> {
const { formula1 = CHECKBOX_FORMULA_1, formula2 = CHECKBOX_FORMULA_2 } = rule;
const results = await this._formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
- const formulaResult1 = getFormulaResult(results?.[0]?.result);
- const formulaResult2 = getFormulaResult(results?.[1]?.result);
+ const formulaResult1 = getFormulaResult(results?.[0]?.result?.[0]?.[0]);
+ const formulaResult2 = getFormulaResult(results?.[1]?.result?.[0]?.[0]);
const isFormulaValid = isLegalFormulaResult(String(formulaResult1)) && isLegalFormulaResult(String(formulaResult2));
return {
- formula1: isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result) : formula1,
+ formula1: isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result?.[0]?.[0]) : formula1,
formula2: isFormulaString(formula2) ? formulaResult2 : formula2,
isFormulaValid,
};
@@ -110,7 +110,7 @@ export class CheckboxRender implements IBaseDataValidationWidget {
}
const colors = this._themeService.getCurrentTheme();
- if (!validator.skipDefaultFontRender?.(rule, value, { unitId: unitId!, subUnitId })) {
+ if (!validator.skipDefaultFontRender?.(rule, value, { unitId: unitId!, subUnitId, row, column: col })) {
return;
}
@@ -185,7 +185,7 @@ export class CheckboxRender implements IBaseDataValidationWidget {
return;
}
- if (!validator.skipDefaultFontRender?.(rule, value, { unitId, subUnitId })) {
+ if (!validator.skipDefaultFontRender?.(rule, value, { unitId, subUnitId, row, column: col })) {
return;
}
diff --git a/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts b/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
index 5e2fbb7410..ac444726fd 100644
--- a/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
+++ b/packages/sheets-data-validation/src/models/sheet-data-validation-model.ts
@@ -142,7 +142,7 @@ export class SheetDataValidationModel extends Disposable {
const ruleMatrix = this._ensureRuleMatrix(unitId, subUnitId);
ruleMatrix.addRule(rule);
this._dataValidationCacheService.addRule(unitId, subUnitId, rule);
- this._dataValidationFormulaService.addRule(unitId, subUnitId, rule.uid, rule.formula1, rule.formula2);
+ this._dataValidationFormulaService.addRule(unitId, subUnitId, rule.uid, rule.formula1, rule.formula2, rule.ranges);
if (rule.type === DataValidationType.CUSTOM) {
this._dataValidationCustomFormulaService.addRule(unitId, subUnitId, rule);
}
@@ -162,13 +162,21 @@ export class SheetDataValidationModel extends Disposable {
ruleMatrix.updateRange(ruleId, payload.payload);
this._dataValidationCacheService.updateRuleRanges(unitId, subUnitId, ruleId, payload.payload, oldRule.ranges);
if (oldRule.type === DataValidationType.CUSTOM) {
- this._dataValidationCustomFormulaService.updateRuleRanges(unitId, subUnitId, ruleId, oldRule.ranges, payload.payload);
+ this._dataValidationCustomFormulaService.deleteByRuleId(unitId, subUnitId, ruleId);
+ this._dataValidationCustomFormulaService.addRule(unitId, subUnitId, {
+ ...oldRule,
+ ranges: payload.payload,
+ });
}
} else if (payload.type === UpdateRuleType.SETTING) {
this._dataValidationCacheService.markRangeDirty(unitId, subUnitId, oldRule.ranges);
- this._dataValidationFormulaService.updateRuleFormulaText(unitId, subUnitId, ruleId, payload.payload.formula1, payload.payload.formula2);
+ this._dataValidationFormulaService.updateRuleFormulaText(unitId, subUnitId, ruleId, payload.payload.formula1, payload.payload.formula2, oldRule.ranges);
if (oldRule.type === DataValidationType.CUSTOM) {
- this._dataValidationCustomFormulaService.updateRuleFormula(unitId, subUnitId, ruleId, oldRule.ranges, payload.payload.formula1!);
+ this._dataValidationCustomFormulaService.deleteByRuleId(unitId, subUnitId, ruleId);
+ this._dataValidationCustomFormulaService.addRule(unitId, subUnitId, {
+ ...oldRule,
+ ...payload.payload,
+ });
} else if (payload.payload.type === DataValidationType.CUSTOM) {
this._dataValidationCustomFormulaService.addRule(unitId, subUnitId, {
...oldRule,
diff --git a/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts b/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts
index c2e755b2ea..6a79223311 100644
--- a/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts
+++ b/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts
@@ -15,60 +15,35 @@
*/
import type { IRange, ISheetDataValidationRule } from '@univerjs/core';
-import { DataValidationType, Disposable, Inject, Injector, isFormulaString, IUniverInstanceService, ObjectMatrix, Range, UniverInstanceType } from '@univerjs/core';
+import { DataValidationType, Disposable, Inject, isFormulaString, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DataValidationModel } from '@univerjs/data-validation';
-import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { RegisterOtherFormulaService } from '@univerjs/sheets-formula';
+import { getFormulaCellData } from '../utils/formula';
import { DataValidationCacheService } from './dv-cache.service';
-interface IDataValidationFormula {
- ruleId: string;
- // formulaText: string;
- formulaId: string;
- temp?: boolean;
-}
-
interface IFormulaData {
formula: string;
originRow: number;
originCol: number;
isTransformable: boolean;
- formulaId?: string;
-}
-
-interface ICellData {
- row: number;
- column: number;
+ formulaId: string;
}
type RuleId = string;
type UnitId = string;
type SubUnitId = string;
-type FormulaId = string;
-
-function transformFormula(lexerTreeBuilder: LexerTreeBuilder, formula: string, originRow: number, originCol: number, targetRow: number, targetCol: number) {
- return lexerTreeBuilder.moveFormulaRefOffset(formula, targetCol - originCol, targetRow - originRow);
-}
export class DataValidationCustomFormulaService extends Disposable {
- private _formulaMap: Map<UnitId, Map<SubUnitId, ObjectMatrix<IDataValidationFormula>>> = new Map();
/**
* Map of origin formula of rule
*/
private _ruleFormulaMap: Map<UnitId, Map<SubUnitId, Map<RuleId, IFormulaData>>> = new Map();
- /**
- * reflect of formulaId to cell, only store transformable formula
- */
- private _formulaCellMap: Map<UnitId, Map<SubUnitId, Map<FormulaId, ICellData>>> = new Map();
-
constructor(
@IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,
@Inject(RegisterOtherFormulaService) private _registerOtherFormulaService: RegisterOtherFormulaService,
- @Inject(LexerTreeBuilder) private _lexerTreeBuilder: LexerTreeBuilder,
@Inject(DataValidationModel) private readonly _dataValidationModel: DataValidationModel,
- @Inject(DataValidationCacheService) private readonly _dataValidationCacheService: DataValidationCacheService,
- @Inject(Injector) private readonly _injector: Injector
+ @Inject(DataValidationCacheService) private readonly _dataValidationCacheService: DataValidationCacheService
) {
super();
@@ -85,19 +60,14 @@ export class DataValidationCustomFormulaService extends Disposable {
for (const subUnitId in unitMap) {
const results = unitMap[subUnitId];
- const { formulaCellMap, ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
+ const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
results.forEach((result) => {
const ruleInfo = ruleFormulaMap.get(result.extra?.ruleId);
- const cellInfo = formulaCellMap.get(result.formulaId);
const rule = this._dataValidationModel.getRuleById(unitId, subUnitId, result.extra?.ruleId);
if (rule && ruleInfo && !ruleInfo.isTransformable) {
this._dataValidationCacheService.markRangeDirty(unitId, subUnitId, rule.ranges);
}
-
- if (cellInfo) {
- this._dataValidationCacheService.markCellDirty(unitId, subUnitId, cellInfo.row, cellInfo.column);
- }
});
}
}
@@ -105,74 +75,44 @@ export class DataValidationCustomFormulaService extends Disposable {
}
private _ensureMaps(unitId: string, subUnitId: string) {
- let formulaUnitMap = this._formulaMap.get(unitId);
let ruleFormulaUnitMap = this._ruleFormulaMap.get(unitId);
- let formulaCellUnitMap = this._formulaCellMap.get(unitId);
- if (!formulaUnitMap || !ruleFormulaUnitMap || !formulaCellUnitMap) {
- formulaUnitMap = new Map<string, ObjectMatrix<IDataValidationFormula>>();
+ if (!ruleFormulaUnitMap) {
ruleFormulaUnitMap = new Map();
- formulaCellUnitMap = new Map();
- this._formulaMap.set(unitId, formulaUnitMap);
this._ruleFormulaMap.set(unitId, ruleFormulaUnitMap);
- this._formulaCellMap.set(unitId, formulaCellUnitMap);
}
- let formulaMap = formulaUnitMap.get(subUnitId);
let ruleFormulaMap = ruleFormulaUnitMap.get(subUnitId);
- let formulaCellMap = formulaCellUnitMap.get(subUnitId);
-
- if (!formulaMap || !ruleFormulaMap || !formulaCellMap) {
- formulaMap = new ObjectMatrix<IDataValidationFormula>();
- formulaUnitMap.set(subUnitId, formulaMap);
+ if (!ruleFormulaMap) {
ruleFormulaMap = new Map();
ruleFormulaUnitMap.set(subUnitId, ruleFormulaMap);
-
- formulaCellMap = new Map();
- formulaCellUnitMap.set(subUnitId, formulaCellMap);
}
- return {
- formulaMap,
- ruleFormulaMap,
- formulaCellMap,
- };
+ return { ruleFormulaMap };
};
- private _registerFormula(unitId: string, subUnitId: string, ruleId: string, formulaString: string) {
- return this._registerOtherFormulaService.registerFormula(unitId, subUnitId, formulaString, { ruleId });
+ private _registerFormula(unitId: string, subUnitId: string, ruleId: string, formulaString: string, ranges: IRange[]) {
+ return this._registerOtherFormulaService.registerFormulaWithRange(unitId, subUnitId, formulaString, ranges, { ruleId });
};
deleteByRuleId(unitId: string, subUnitId: string, ruleId: string) {
- const { formulaMap, formulaCellMap, ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
+ const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
const rule = this._dataValidationModel.getRuleById(unitId, subUnitId, ruleId) as ISheetDataValidationRule;
- const formulaIdList = new Set<string>();
const formulaInfo = ruleFormulaMap.get(ruleId);
if (!rule || !formulaInfo) {
return;
}
- // formulaIdList.add(formulaInfo.formulaId);
- ruleFormulaMap.delete(ruleId);
-
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const value = formulaMap.getValue(row, col);
- if (value && value.ruleId === ruleId) {
- const { formulaId } = value;
- formulaMap.realDeleteValue(row, col);
- formulaIdList.add(formulaId);
- formulaCellMap.delete(formulaId);
- }
- });
- });
-
- this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, Array.from(formulaIdList.values()));
+ const current = ruleFormulaMap.get(ruleId);
+ if (current) {
+ ruleFormulaMap.delete(ruleId);
+ this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, [current.formulaId]);
+ }
}
private _addFormulaByRange(unitId: string, subUnitId: string, ruleId: string, formula: string, ranges: IRange[]) {
- const { formulaMap, ruleFormulaMap, formulaCellMap } = this._ensureMaps(unitId, subUnitId);
+ const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
if (!formula) {
return;
@@ -181,32 +121,13 @@ export class DataValidationCustomFormulaService extends Disposable {
const originRow = ranges[0].startRow;
const originCol = ranges[0].startColumn;
- let originFormulaId: string | undefined;
- ranges.forEach((range) => {
- Range.foreach(range, (row, column) => {
- const relativeFormula = transformFormula(
- this._lexerTreeBuilder,
- formula,
- originRow,
- originCol,
- row,
- column
- );
- const formulaId = this._registerFormula(unitId, subUnitId, ruleId, relativeFormula);
- formulaMap.setValue(row, column, {
- formulaId,
- // formulaText: relativeFormula,
- ruleId,
- });
- formulaCellMap.set(formulaId, { row, column });
- });
- });
+ const formulaId = this._registerFormula(unitId, subUnitId, ruleId, formula, ranges);
ruleFormulaMap.set(ruleId, {
formula,
originCol,
originRow,
- formulaId: originFormulaId,
+ formulaId,
isTransformable: true,
});
}
@@ -219,89 +140,18 @@ export class DataValidationCustomFormulaService extends Disposable {
this._addFormulaByRange(unitId, subUnitId, ruleId, formula1, ranges);
}
- updateRuleRanges(unitId: string, subUnitId: string, ruleId: string, oldRanges: IRange[], newRanges: IRange[]) {
- const { formulaMap, ruleFormulaMap, formulaCellMap } = this._ensureMaps(unitId, subUnitId);
- const info = ruleFormulaMap.get(ruleId);
- // isn't custom formula type
- if (!info) {
- return;
- }
- const { formula, originCol, originRow, isTransformable, formulaId } = info;
- const deleteFormulaIdList = new Set<string>();
-
- oldRanges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const value = formulaMap.getValue(row, col);
- if (value && value.ruleId === ruleId) {
- value.temp = true;
- }
- });
- });
-
- newRanges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const oldValue = formulaMap.getValue(row, col) ?? {} as IDataValidationFormula;
- if ((oldValue.ruleId !== ruleId)) {
- const oldRuleFormula = ruleFormulaMap.get(oldValue.ruleId);
- if (oldRuleFormula?.isTransformable) {
- deleteFormulaIdList.add(oldValue.formulaId);
- }
-
- if (isTransformable) {
- const relativeText = transformFormula(this._lexerTreeBuilder, formula, originRow, originCol, row, col);
- const formulaId = this._registerFormula(unitId, subUnitId, ruleId, relativeText);
- formulaMap.setValue(row, col, {
- ruleId,
- formulaId,
- });
- formulaCellMap.set(formulaId, { row, column: col });
- } else {
- formulaMap.setValue(row, col, {
- // formulaText: formula,
- ruleId,
- formulaId: formulaId!,
- });
- }
- } else {
- oldValue.temp = false;
- }
- });
- });
-
- oldRanges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const value = formulaMap.getValue(row, col);
- if (value && value.ruleId === ruleId && value.temp === true) {
- formulaMap.realDeleteValue(row, col);
- if (isTransformable) {
- deleteFormulaIdList.add(value.formulaId);
- }
- }
- });
- });
-
- deleteFormulaIdList.forEach((formulaId) => {
- formulaCellMap.delete(formulaId);
- });
- this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, Array.from(deleteFormulaIdList.values()));
- }
-
- updateRuleFormula(unitId: string, subUnitId: string, ruleId: string, ranges: IRange[], formula: string) {
+ async getCellFormulaValue(unitId: string, subUnitId: string, ruleId: string, row: number, column: number) {
const { ruleFormulaMap } = this._ensureMaps(unitId, subUnitId);
const current = ruleFormulaMap.get(ruleId);
- if (!current || current.formula !== formula) {
- this._addFormulaByRange(unitId, subUnitId, ruleId, formula, ranges);
- }
- }
-
- getCellFormulaValue(unitId: string, subUnitId: string, row: number, col: number) {
- const { formulaMap } = this._ensureMaps(unitId, subUnitId);
- const current = formulaMap.getValue(row, col);
if (!current) {
return Promise.resolve(undefined);
}
- return this._registerOtherFormulaService.getFormulaValue(unitId, subUnitId, current.formulaId);
+ const result = await this._registerOtherFormulaService.getFormulaValue(unitId, subUnitId, current.formulaId);
+ const { originRow, originCol } = current;
+ const offsetRow = row - originRow;
+ const offsetCol = column - originCol;
+ return getFormulaCellData(result?.result?.[offsetRow]?.[offsetCol]);
}
getRuleFormulaInfo(unitId: string, subUnitId: string, ruleId: string) {
diff --git a/packages/sheets-data-validation/src/services/dv-formula.service.ts b/packages/sheets-data-validation/src/services/dv-formula.service.ts
index 978feb9f9f..f874cf0657 100644
--- a/packages/sheets-data-validation/src/services/dv-formula.service.ts
+++ b/packages/sheets-data-validation/src/services/dv-formula.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
+import type { IRange, Nullable } from '@univerjs/core';
import type { IFormulaInfo, IOtherFormulaResult } from '@univerjs/sheets-formula';
import { Disposable, Inject, isFormulaString, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DataValidationModel } from '@univerjs/data-validation';
@@ -80,7 +80,12 @@ export class DataValidationFormulaService extends Disposable {
return subUnitMap;
}
- addRule(unitId: string, subUnitId: string, ruleId: string, formula1: string | undefined, formula2: string | undefined) {
+ private _registerSingleFormula(unitId: string, subUnitId: string, formula: string, ruleId: string) {
+ const ranges = [{ startColumn: 0, endColumn: 0, startRow: 0, endRow: 0 }];
+ return this._registerOtherFormulaService.registerFormulaWithRange(unitId, subUnitId, formula, ranges, { ruleId });
+ }
+
+ addRule(unitId: string, subUnitId: string, ruleId: string, formula1: string | undefined, formula2: string | undefined, ranges: IRange[]) {
const isFormula1Legal = isFormulaString(formula1);
const isFormula2Legal = isFormulaString(formula2);
if (!isFormula1Legal && !isFormula2Legal) {
@@ -89,12 +94,11 @@ export class DataValidationFormulaService extends Disposable {
const formulaRuleMap = this._ensureRuleFormulaMap(unitId, subUnitId);
const item: [IFormulaInfo | undefined, IFormulaInfo | undefined] = [undefined, undefined];
if (isFormula1Legal) {
- const id = this._registerOtherFormulaService.registerFormula(unitId, subUnitId, formula1!, { ruleId });
-
+ const id = this._registerSingleFormula(unitId, subUnitId, formula1!, ruleId);
item[0] = { id, text: formula1! };
}
if (isFormula2Legal) {
- const id = this._registerOtherFormulaService.registerFormula(unitId, subUnitId, formula2!, { ruleId });
+ const id = this._registerSingleFormula(unitId, subUnitId, formula2!, ruleId);
item[1] = { id, text: formula2! };
}
formulaRuleMap.set(ruleId, item);
@@ -111,11 +115,11 @@ export class DataValidationFormulaService extends Disposable {
idList.length && this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, idList);
}
- updateRuleFormulaText(unitId: string, subUnitId: string, ruleId: string, formula1: string | undefined, formula2: string | undefined) {
+ updateRuleFormulaText(unitId: string, subUnitId: string, ruleId: string, formula1: string | undefined, formula2: string | undefined, ranges: IRange[]) {
const formulaRuleMap = this._ensureRuleFormulaMap(unitId, subUnitId);
const item = formulaRuleMap.get(ruleId);
if (!item) {
- this.addRule(unitId, subUnitId, ruleId, formula1, formula2);
+ this.addRule(unitId, subUnitId, ruleId, formula1, formula2, ranges);
return;
}
@@ -123,7 +127,7 @@ export class DataValidationFormulaService extends Disposable {
if (oldFormula1?.text !== formula1) {
oldFormula1 && this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, [oldFormula1.id]);
if (isFormulaString(formula1)) {
- const formulaId = this._registerOtherFormulaService.registerFormula(unitId, subUnitId, formula1!, { ruleId });
+ const formulaId = this._registerSingleFormula(unitId, subUnitId, formula1!, ruleId);
item[0] = {
text: formula1!,
id: formulaId,
@@ -136,7 +140,7 @@ export class DataValidationFormulaService extends Disposable {
if (oldFormula2?.text !== formula2) {
oldFormula2 && this._registerOtherFormulaService.deleteFormula(unitId, subUnitId, [oldFormula2.id]);
if (isFormulaString(formula2)) {
- const formulaId = this._registerOtherFormulaService.registerFormula(unitId, subUnitId, formula2!, { ruleId });
+ const formulaId = this._registerSingleFormula(unitId, subUnitId, formula2!, ruleId);
item[1] = {
text: formula2!,
id: formulaId,
diff --git a/packages/sheets-data-validation/src/validators/checkbox-validator.ts b/packages/sheets-data-validation/src/validators/checkbox-validator.ts
index ae2e4ea4fc..6360609c48 100644
--- a/packages/sheets-data-validation/src/validators/checkbox-validator.ts
+++ b/packages/sheets-data-validation/src/validators/checkbox-validator.ts
@@ -56,8 +56,9 @@ export class CheckboxValidator extends BaseDataValidator {
private _formulaService = this.injector.get(DataValidationFormulaService);
- override skipDefaultFontRender = (rule: ISheetDataValidationRule, cellValue: Nullable<CellValue>, pos: { unitId: string; subUnitId: string }) => {
- const { formula1, formula2 } = this.parseFormulaSync(rule, pos.unitId, pos.subUnitId);
+ override skipDefaultFontRender = (rule: ISheetDataValidationRule, cellValue: Nullable<CellValue>, pos: { unitId: string; subUnitId: string; row: number; column: number }) => {
+ const { unitId, subUnitId } = pos;
+ const { formula1, formula2 } = this.parseFormulaSync(rule, unitId, subUnitId);
const valueStr = `${cellValue ?? ''}`;
@@ -97,8 +98,8 @@ export class CheckboxValidator extends BaseDataValidator {
const { formula1 = CHECKBOX_FORMULA_1, formula2 = CHECKBOX_FORMULA_2 } = rule;
const results = await this._formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
- const originFormula1 = isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result) : formula1;
- const originFormula2 = isFormulaString(formula2) ? getFormulaResult(results?.[1]?.result) : formula2;
+ const originFormula1 = isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result?.[0][0]) : formula1;
+ const originFormula2 = isFormulaString(formula2) ? getFormulaResult(results?.[1]?.result?.[0][0]) : formula2;
const isFormulaValid = isLegalFormulaResult(String(originFormula1)) && isLegalFormulaResult(String(originFormula2));
return {
@@ -116,17 +117,19 @@ export class CheckboxValidator extends BaseDataValidator {
};
}
- parseFormulaSync(rule: IDataValidationRule, unitId: string, subUnitId: string) {
+ parseFormulaSync(rule: IDataValidationRule, unitId: string, subUnitId: string): ICheckboxFormulaResult {
const { formula1 = CHECKBOX_FORMULA_1, formula2 = CHECKBOX_FORMULA_2 } = rule;
const results = this._formulaService.getRuleFormulaResultSync(unitId, subUnitId, rule.uid);
- const originFormula1 = isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result) : formula1;
- const originFormula2 = isFormulaString(formula2) ? getFormulaResult(results?.[1]?.result) : formula2;
+ const originFormula1 = isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result?.[0][0]) : formula1;
+ const originFormula2 = isFormulaString(formula2) ? getFormulaResult(results?.[1]?.result?.[0][0]) : formula2;
+ const isFormulaValid = isLegalFormulaResult(String(originFormula1)) && isLegalFormulaResult(String(originFormula2)); // TODO@Dushusir Handling return type errors, not sure if this is correct
return {
formula1: transformCheckboxValue(originFormula1),
formula2: transformCheckboxValue(originFormula2),
originFormula1,
originFormula2,
+ isFormulaValid,
};
}
diff --git a/packages/sheets-data-validation/src/validators/custom-validator.ts b/packages/sheets-data-validation/src/validators/custom-validator.ts
index 4d14eb767b..6e671cd278 100644
--- a/packages/sheets-data-validation/src/validators/custom-validator.ts
+++ b/packages/sheets-data-validation/src/validators/custom-validator.ts
@@ -19,7 +19,7 @@ import type { IFormulaResult, IFormulaValidResult, IValidatorCellInfo } from '@u
import { CellValueType, DataValidationType, isFormulaString, Tools } from '@univerjs/core';
import { BaseDataValidator } from '@univerjs/data-validation';
import { DataValidationCustomFormulaService } from '../services/dv-custom-formula.service';
-import { getFormulaCellData, isLegalFormulaResult } from '../utils/formula';
+import { isLegalFormulaResult } from '../utils/formula';
export class CustomFormulaValidator extends BaseDataValidator {
override id: string = DataValidationType.CUSTOM;
@@ -41,14 +41,13 @@ export class CustomFormulaValidator extends BaseDataValidator {
return {
formula1: undefined,
formula2: undefined,
- isFormulaValid: false,
+ isFormulaValid: true,
};
}
override async isValidType(cellInfo: IValidatorCellInfo<CellValue>, _formula: IFormulaResult, _rule: IDataValidationRule): Promise<boolean> {
const { column, row, unitId, subUnitId } = cellInfo;
- const result = await this._customFormulaService.getCellFormulaValue(unitId, subUnitId, row, column);
- const cellData = getFormulaCellData(result?.result);
+ const cellData = await this._customFormulaService.getCellFormulaValue(unitId, subUnitId, _rule.uid, row, column);
const formulaResult = cellData?.v;
if (!isLegalFormulaResult(String(formulaResult))) {
diff --git a/packages/sheets-data-validation/src/validators/date-validator.ts b/packages/sheets-data-validation/src/validators/date-validator.ts
index de5a120329..33061afb10 100644
--- a/packages/sheets-data-validation/src/validators/date-validator.ts
+++ b/packages/sheets-data-validation/src/validators/date-validator.ts
@@ -66,8 +66,8 @@ export class DateValidator extends BaseDataValidator<number> {
override async parseFormula(rule: IDataValidationRule, unitId: string, subUnitId: string): Promise<IFormulaResult<number | undefined>> {
const results = await this._formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
const { formula1, formula2 } = rule;
- const formulaResult1 = getFormulaResult(results?.[0]?.result);
- const formulaResult2 = getFormulaResult(results?.[1]?.result);
+ const formulaResult1 = getFormulaResult(results?.[0]?.result?.[0][0]);
+ const formulaResult2 = getFormulaResult(results?.[1]?.result?.[0][0]);
const isFormulaValid = isLegalFormulaResult(String(formulaResult1)) && isLegalFormulaResult(String(formulaResult2));
return {
@@ -82,8 +82,8 @@ export class DateValidator extends BaseDataValidator<number> {
const { formula1, formula2 } = rule;
return {
- formula1: transformDate2SerialNumber(isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result) : formula1),
- formula2: transformDate2SerialNumber(isFormulaString(formula2) ? getFormulaResult(results?.[1]?.result) : formula2),
+ formula1: transformDate2SerialNumber(isFormulaString(formula1) ? getFormulaResult(results?.[0]?.result?.[0][0]) : formula1),
+ formula2: transformDate2SerialNumber(isFormulaString(formula2) ? getFormulaResult(results?.[1]?.result?.[0][0]) : formula2),
};
}
diff --git a/packages/sheets-data-validation/src/validators/decimal-validator.ts b/packages/sheets-data-validation/src/validators/decimal-validator.ts
index 90fed3db12..a2a6e229d1 100644
--- a/packages/sheets-data-validation/src/validators/decimal-validator.ts
+++ b/packages/sheets-data-validation/src/validators/decimal-validator.ts
@@ -81,12 +81,12 @@ export class DecimalValidator extends BaseDataValidator<number> {
return +formula;
}
- async parseFormula(rule: IDataValidationRule, unitId: string, subUnitId: string) {
+ async parseFormula(rule: IDataValidationRule, unitId: string, subUnitId: string): Promise<IFormulaResult> {
const formulaInfo = await this._formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
const { formula1, formula2 } = rule;
- const formulaResult1 = getFormulaResult(formulaInfo?.[0]?.result);
- const formulaResult2 = getFormulaResult(formulaInfo?.[1]?.result);
+ const formulaResult1 = getFormulaResult(formulaInfo?.[0]?.result?.[0][0]);
+ const formulaResult2 = getFormulaResult(formulaInfo?.[1]?.result?.[0][0]);
const isFormulaValid = isLegalFormulaResult(String(formulaResult1)) && isLegalFormulaResult(String(formulaResult2));
const info = {
diff --git a/packages/sheets-data-validation/src/validators/list-validator.ts b/packages/sheets-data-validation/src/validators/list-validator.ts
index 8526d2cdb0..7feac8588a 100644
--- a/packages/sheets-data-validation/src/validators/list-validator.ts
+++ b/packages/sheets-data-validation/src/validators/list-validator.ts
@@ -149,11 +149,11 @@ export class ListValidator extends BaseDataValidator {
override async parseFormula(rule: IDataValidationRule, unitId: string, subUnitId: string): Promise<IFormulaResult<string[] | undefined>> {
const { formula1 = '' } = rule;
const results = await this.formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
- const formulaResult1 = getFormulaResult(results?.[0]?.result);
+ const formulaResult1 = getFormulaResult(results?.[0]?.result?.[0][0]);
const isFormulaValid = isLegalFormulaResult(String(formulaResult1));
return {
- formula1: isFormulaString(formula1) ? getRuleFormulaResultSet(results?.[0]?.result) : deserializeListOptions(formula1),
+ formula1: isFormulaString(formula1) ? getRuleFormulaResultSet(results?.[0]?.result?.[0][0]) : deserializeListOptions(formula1),
formula2: undefined,
isFormulaValid,
};
@@ -186,7 +186,7 @@ export class ListValidator extends BaseDataValidator {
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
const results = this.formulaService.getRuleFormulaResultSync(unitId, subUnitId, rule.uid);
- return isFormulaString(formula1) ? getRuleFormulaResultSet(results?.[0]?.result) : deserializeListOptions(formula1);
+ return isFormulaString(formula1) ? getRuleFormulaResultSet(results?.[0]?.result?.[0][0]) : deserializeListOptions(formula1);
}
async getListAsync(rule: IDataValidationRule, currentUnitId?: string, currentSubUnitId?: string) {
@@ -201,7 +201,7 @@ export class ListValidator extends BaseDataValidator {
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
const results = await this.formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
- return isFormulaString(formula1) ? getRuleFormulaResultSet(results?.[0]?.result) : deserializeListOptions(formula1);
+ return isFormulaString(formula1) ? getRuleFormulaResultSet(results?.[0]?.result?.[0][0]) : deserializeListOptions(formula1);
}
getListWithColor(rule: IDataValidationRule, currentUnitId?: string, currentSubUnitId?: string) {
diff --git a/packages/sheets-data-validation/src/validators/text-length-validator.ts b/packages/sheets-data-validation/src/validators/text-length-validator.ts
index ff03b63398..44d0822487 100644
--- a/packages/sheets-data-validation/src/validators/text-length-validator.ts
+++ b/packages/sheets-data-validation/src/validators/text-length-validator.ts
@@ -89,8 +89,8 @@ export class TextLengthValidator extends BaseDataValidator<number> {
const formulaInfo = await this._formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
const { formula1, formula2 } = rule;
- const formulaResult1 = getFormulaResult(formulaInfo?.[0]?.result);
- const formulaResult2 = getFormulaResult(formulaInfo?.[1]?.result);
+ const formulaResult1 = getFormulaResult(formulaInfo?.[0]?.result?.[0][0]);
+ const formulaResult2 = getFormulaResult(formulaInfo?.[1]?.result?.[0][0]);
const isFormulaValid = isLegalFormulaResult(String(formulaResult1)) && isLegalFormulaResult(String(formulaResult2));
return {
diff --git a/packages/sheets-data-validation/src/validators/whole-validator.ts b/packages/sheets-data-validation/src/validators/whole-validator.ts
index 2c8763fd7f..42c7311b07 100644
--- a/packages/sheets-data-validation/src/validators/whole-validator.ts
+++ b/packages/sheets-data-validation/src/validators/whole-validator.ts
@@ -68,12 +68,12 @@ export class WholeValidator extends BaseDataValidator<number> {
return +formula;
}
- override async parseFormula(rule: IDataValidationRule, unitId: string, subUnitId: string) {
+ override async parseFormula(rule: IDataValidationRule, unitId: string, subUnitId: string): Promise<IFormulaResult> {
const formulaInfo = await this._formulaService.getRuleFormulaResult(unitId, subUnitId, rule.uid);
const { formula1, formula2 } = rule;
- const formula1Result = isFormulaString(formula1) ? formulaInfo?.[0]?.result?.[0]?.[0]?.v : formula1;
- const formula2Result = isFormulaString(formula2) ? formulaInfo?.[1]?.result?.[0]?.[0]?.v : formula2;
+ const formula1Result = isFormulaString(formula1) ? formulaInfo?.[0]?.result?.[0]?.[0]?.[0][0]?.v : formula1;
+ const formula2Result = isFormulaString(formula2) ? formulaInfo?.[1]?.result?.[0]?.[0]?.[0][0]?.v : formula2;
const isFormulaValid = isLegalFormulaResult(`${formula1Result}`) && isLegalFormulaResult(`${formula2Result}`);
const info = {
diff --git a/packages/sheets-formula-ui/src/controllers/config.schema.ts b/packages/sheets-formula-ui/src/controllers/config.schema.ts
index 43ab276198..03baf16c0d 100644
--- a/packages/sheets-formula-ui/src/controllers/config.schema.ts
+++ b/packages/sheets-formula-ui/src/controllers/config.schema.ts
@@ -21,7 +21,7 @@ import type { MenuConfig } from '@univerjs/ui';
/**
* Base configuration for the plugin.
*/
-export const PLUGIN_CONFIG_KEY_BASE = 'sheets-formula.base.config';
+export const PLUGIN_CONFIG_KEY_BASE = 'sheets-formula-ui.base.config';
export const configSymbolBase = Symbol(PLUGIN_CONFIG_KEY_BASE);
diff --git a/packages/sheets-formula-ui/src/controllers/utils/__tests__/offset-formula-data.spec.ts b/packages/sheets-formula-ui/src/controllers/utils/__tests__/offset-formula-data.spec.ts
deleted file mode 100644
index 79769873c6..0000000000
--- a/packages/sheets-formula-ui/src/controllers/utils/__tests__/offset-formula-data.spec.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { describe, expect, it } from 'vitest';
-
-import { removeFormulaData } from '../offset-formula-data';
-
-describe('Utils offset formula data test', () => {
- describe('function removeFormulaData, remove sheet', () => {
- it('remove data', () => {
- const unitId = 'workbook-01';
- const sheetId = 'sheet-0011';
- const formulaData = {
- [unitId]: {
- [sheetId]: {
- 0: {
- 0: {
- f: '=SUM(A1)',
- },
- },
- },
- },
- };
-
- removeFormulaData(formulaData, unitId, sheetId);
-
- expect(formulaData).toStrictEqual({
- [unitId]: {},
- });
- });
-
- it('remove blank worksheet', () => {
- const unitId = 'workbook-01';
- const sheetId = 'sheet-0011';
- const formulaData = {
- [unitId]: {
- [sheetId]: {},
- },
- };
-
- removeFormulaData(formulaData, unitId, sheetId);
-
- expect(formulaData).toStrictEqual({
- [unitId]: {},
- });
- });
-
- it('remove blank workbook', () => {
- const unitId = 'workbook-01';
- const sheetId = 'sheet-0011';
- const formulaData = {
- [unitId]: {},
- };
-
- removeFormulaData(formulaData, unitId, sheetId);
-
- expect(formulaData).toStrictEqual({
- [unitId]: {},
- });
- });
- it('remove blank object', () => {
- const unitId = 'workbook-01';
- const sheetId = 'sheet-0011';
- const formulaData = {};
-
- removeFormulaData(formulaData, unitId, sheetId);
-
- expect(formulaData).toStrictEqual({});
- });
- });
-
- describe('function removeUnitFormulaData, remove unit', () => {
- it('remove data', () => {
- const unitId = 'workbook-01';
- const sheetId = 'sheet-0011';
- const formulaData = {
- [unitId]: {
- [sheetId]: {
- 0: {
- 0: {
- f: '=SUM(A1)',
- },
- },
- },
- },
- 'unit-2': {
- },
- };
-
- removeFormulaData(formulaData, unitId);
-
- expect(formulaData).toStrictEqual({
- 'unit-2': {},
- });
- });
-
- it('remove blank workbook', () => {
- const unitId = 'workbook-01';
- const formulaData = {
- [unitId]: {},
- 'unit-2': {},
- };
-
- removeFormulaData(formulaData, unitId);
-
- expect(formulaData).toStrictEqual({
- 'unit-2': {},
- });
- });
-
- it('remove blank object', () => {
- const unitId = 'workbook-01';
- const formulaData = {};
-
- removeFormulaData(formulaData, unitId);
-
- expect(formulaData).toStrictEqual({});
- });
- });
-});
diff --git a/packages/sheets-formula-ui/src/controllers/utils/__tests__/ref-range-formula.spec.ts b/packages/sheets-formula-ui/src/controllers/utils/__tests__/ref-range-formula.spec.ts
deleted file mode 100644
index 3efdf51f8e..0000000000
--- a/packages/sheets-formula-ui/src/controllers/utils/__tests__/ref-range-formula.spec.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IFormulaDataItem } from '@univerjs/engine-formula';
-
-import { describe, expect, it } from 'vitest';
-import { formulaDataItemToCellData, formulaDataToCellData, isFormulaDataItem } from '../ref-range-formula';
-
-describe('Ref range formula test', () => {
- describe('Util function', () => {
- it('Function formulaDataItemToCellData', () => {
- let formulaDataItem: IFormulaDataItem = {
- f: '=SUM(1)',
- };
-
- let result = formulaDataItemToCellData(formulaDataItem);
-
- expect(result).toStrictEqual({
- f: '=SUM(1)',
- si: null,
- });
-
- formulaDataItem = {
- f: '',
- si: 'id1',
- };
-
- result = formulaDataItemToCellData(formulaDataItem);
-
- expect(result).toStrictEqual({
- si: 'id1',
- f: null,
- });
-
- formulaDataItem = {
- f: '=SUM(1)',
- si: 'id1',
- };
-
- result = formulaDataItemToCellData(formulaDataItem);
-
- expect(result).toStrictEqual({
- f: '=SUM(1)',
- si: 'id1',
- });
-
- formulaDataItem = {
- f: '=SUM(1)',
- si: 'id1',
- x: 0,
- y: 0,
- };
-
- result = formulaDataItemToCellData(formulaDataItem);
-
- expect(result).toStrictEqual({
- f: '=SUM(1)',
- si: 'id1',
- });
-
- formulaDataItem = {
- f: '=SUM(1)',
- si: 'id1',
- x: 0,
- y: 1,
- };
-
- result = formulaDataItemToCellData(formulaDataItem);
-
- expect(result).toStrictEqual({
- si: 'id1',
- f: null,
- });
-
- formulaDataItem = {
- f: '',
- si: '',
- x: 0,
- y: 1,
- };
-
- result = formulaDataItemToCellData(formulaDataItem);
-
- expect(result).toStrictEqual({ f: null, si: null });
- });
-
- it('Function formulaDataToCellData', () => {
- const formulaData = {
- 0: {
- 0: {
- f: '=SUM(1)',
- },
- 1: {
- f: '',
- si: 'id1',
- },
- 2: {
- f: '=SUM(1)',
- si: 'id2',
- x: 0,
- y: 1,
- },
- },
- };
-
- const cellData = {
- 0: {
- 0: {
- f: '=SUM(1)',
- si: null,
- },
- 1: {
- f: null,
- si: 'id1',
- },
- 2: {
- f: null,
- si: 'id2',
- },
- },
- };
- expect(formulaDataToCellData(formulaData)).toStrictEqual(cellData);
- });
-
- it('isFormulaDataItem', () => {
- expect(isFormulaDataItem({ f: '=SUM(1)' })).toBeTruthy();
- expect(isFormulaDataItem({ f: '' })).toBeFalsy();
- expect(isFormulaDataItem({ f: '', si: 'id1' })).toBeTruthy();
- expect(isFormulaDataItem({ f: '', si: undefined })).toBeFalsy();
- });
- });
-});
diff --git a/packages/sheets-formula-ui/src/controllers/utils/offset-formula-data.ts b/packages/sheets-formula-ui/src/controllers/utils/offset-formula-data.ts
deleted file mode 100644
index 66680a9e79..0000000000
--- a/packages/sheets-formula-ui/src/controllers/utils/offset-formula-data.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IRange } from '@univerjs/core';
-import type { IArrayFormulaRangeType, IArrayFormulaUnitCellType, IFormulaData } from '@univerjs/engine-formula';
-
-export interface IRefRangeWithPosition {
- row: number;
- column: number;
- range: IRange;
-}
-
-export function checkFormulaDataNull(formulaData: IFormulaData, unitId: string, sheetId: string) {
- if (formulaData == null || formulaData[unitId] == null || formulaData[unitId]?.[sheetId] == null) {
- return true;
- }
-
- return false;
-}
-
-export function removeFormulaData(formulaData: IFormulaData | IArrayFormulaRangeType | IArrayFormulaUnitCellType, unitId: string, sheetId?: string) {
- if (sheetId) {
- if (formulaData && formulaData[unitId] && formulaData[unitId]?.[sheetId]) {
- delete formulaData[unitId]![sheetId];
- return {
- [unitId]: {
- [sheetId]: null,
- },
- };
- }
- } else {
- if (formulaData && formulaData[unitId]) {
- delete formulaData[unitId];
- return {
- [unitId]: null,
- };
- }
- }
-}
diff --git a/packages/sheets-formula-ui/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula-ui/src/controllers/utils/ref-range-formula.ts
deleted file mode 100644
index 794a38620c..0000000000
--- a/packages/sheets-formula-ui/src/controllers/utils/ref-range-formula.ts
+++ /dev/null
@@ -1,583 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
-import type { IFormulaData, IFormulaDataItem, IRangeChange } from '@univerjs/engine-formula';
-import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix } from '@univerjs/core';
-import { EffectRefRangId, handleDeleteRangeMoveLeft, handleDeleteRangeMoveUp, handleInsertCol, handleInsertRangeMoveDown, handleInsertRangeMoveRight, handleInsertRow, handleIRemoveCol, handleIRemoveRow, handleMoveCols, handleMoveRange, handleMoveRows, runRefRangeMutations, SetRangeValuesMutation } from '@univerjs/sheets';
-import { checkFormulaDataNull } from './offset-formula-data';
-
-export enum FormulaReferenceMoveType {
- MoveRange, // range
- MoveRows, // move rows
- MoveCols, // move columns
- InsertRow, // row
- InsertColumn, // column
- RemoveRow, // row
- RemoveColumn, // column
- DeleteMoveLeft, // range
- DeleteMoveUp, // range
- InsertMoveDown, // range
- InsertMoveRight, // range
- SetName,
- RemoveSheet,
-}
-
-export interface IFormulaReferenceMoveParam {
- type: FormulaReferenceMoveType;
- unitId: string;
- sheetId: string;
- range?: IRange;
- from?: IRange;
- to?: IRange;
- sheetName?: string;
-}
-
-export function getFormulaReferenceMoveUndoRedo(oldFormulaData: IFormulaData,
- newFormulaData: IFormulaData,
- formulaReferenceMoveParam: IFormulaReferenceMoveParam) {
- const { type } = formulaReferenceMoveParam;
-
- if (type === FormulaReferenceMoveType.SetName || type === FormulaReferenceMoveType.RemoveSheet) {
- return getFormulaReferenceSheet(oldFormulaData, newFormulaData);
- } else {
- return getFormulaReferenceRange(oldFormulaData, newFormulaData, formulaReferenceMoveParam);
- }
-}
-
-export function getFormulaReferenceSheet(oldFormulaData: IFormulaData,
- newFormulaData: IFormulaData) {
- const undos: IMutationInfo[] = [];
- const redos: IMutationInfo[] = [];
-
- Object.keys(newFormulaData).forEach((unitId) => {
- const newSheetData = newFormulaData[unitId];
- const oldSheetData = oldFormulaData[unitId];
-
- if (newSheetData == null) {
- return true;
- }
-
- if (oldSheetData == null) {
- return true;
- }
-
- Object.keys(newSheetData).forEach((subUnitId) => {
- const newSheetFormula = new ObjectMatrix(newSheetData[subUnitId] || {});
- const oldSheetFormula = new ObjectMatrix(oldSheetData[subUnitId] || {});
- const redoFormulaMatrix = new ObjectMatrix<Nullable<ICellData>>();
- const undoFormulaMatrix = new ObjectMatrix<Nullable<ICellData>>();
-
- newSheetFormula.forValue((r, c, cell) => {
- if (cell == null) {
- return true;
- }
- const newValue = formulaDataItemToCellData(cell);
-
- if (newValue === null) {
- return;
- }
-
- redoFormulaMatrix.setValue(r, c, newValue);
- undoFormulaMatrix.setValue(r, c, oldSheetFormula.getValue(r, c));
- });
-
- if (redoFormulaMatrix.getSizeOf() === 0) {
- return;
- }
-
- const redoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = {
- subUnitId,
- unitId,
- cellValue: redoFormulaMatrix.clone(),
- };
-
- const redoMutation = {
- id: SetRangeValuesMutation.id,
- params: redoSetRangeValuesMutationParams,
- };
-
- redos.push(redoMutation);
-
- const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = {
- subUnitId,
- unitId,
- cellValue: undoFormulaMatrix.clone(),
- };
-
- const undoMutation = {
- id: SetRangeValuesMutation.id,
- params: undoSetRangeValuesMutationParams,
- };
-
- undos.push(undoMutation);
- });
- });
-
- return {
- undos,
- redos,
- };
-}
-
-export function getFormulaReferenceRange(oldFormulaData: IFormulaData,
- newFormulaData: IFormulaData,
- formulaReferenceMoveParam: IFormulaReferenceMoveParam) {
- const { sheetId: subUnitId, unitId } = formulaReferenceMoveParam;
- const { redoFormulaData, undoFormulaData } = refRangeFormula(oldFormulaData, newFormulaData, formulaReferenceMoveParam);
-
- const redos: IMutationInfo[] = [];
- const undos: IMutationInfo[] = [];
-
- if (Object.keys(redoFormulaData).length !== 0) {
- const redoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = {
- subUnitId,
- unitId,
- cellValue: redoFormulaData,
- };
-
- const redoMutation = {
- id: SetRangeValuesMutation.id,
- params: redoSetRangeValuesMutationParams,
- };
-
- redos.push(redoMutation);
- }
-
- if (Object.keys(undoFormulaData).length !== 0) {
- const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = {
- subUnitId,
- unitId,
- cellValue: undoFormulaData,
- };
-
- const undoMutation = {
- id: SetRangeValuesMutation.id,
- params: undoSetRangeValuesMutationParams,
- };
-
- undos.push(undoMutation);
- }
-
- return {
- undos,
- redos,
- };
-}
-
-/**
- * For different Command operations, it may be necessary to perform traversal in reverse or in forward order, so first determine the type of Command and then perform traversal.
- * @param oldFormulaData
- * @param newFormulaData
- * @param formulaReferenceMoveParam
- * @returns
- */
-export function refRangeFormula(oldFormulaData: IFormulaData,
- newFormulaData: IFormulaData,
- formulaReferenceMoveParam: IFormulaReferenceMoveParam) {
- let redoFormulaData: IObjectMatrixPrimitiveType<Nullable<ICellData>> = {};
- let undoFormulaData: IObjectMatrixPrimitiveType<Nullable<ICellData>> = {};
-
- const { type, unitId, sheetId, range, from, to } = formulaReferenceMoveParam;
-
- if (checkFormulaDataNull(oldFormulaData, unitId, sheetId)) {
- return {
- redoFormulaData,
- undoFormulaData,
- };
- }
-
- const currentOldFormulaData = oldFormulaData[unitId]![sheetId];
- const currentNewFormulaData = newFormulaData[unitId]![sheetId];
-
- const oldFormulaMatrix = new ObjectMatrix(currentOldFormulaData || {});
- const newFormulaMatrix = new ObjectMatrix(currentNewFormulaData || {});
-
- const rangeList = processFormulaChanges(oldFormulaMatrix, type, from, to, range);
-
- redoFormulaData = getRedoFormulaData(rangeList, oldFormulaMatrix, newFormulaMatrix);
- undoFormulaData = getUndoFormulaData(rangeList, oldFormulaMatrix);
-
- return {
- redoFormulaData,
- undoFormulaData,
- };
-}
-
-function processFormulaChanges(oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, type: FormulaReferenceMoveType, from: Nullable<IRange>, to: Nullable<IRange>, range: Nullable<IRange>) {
- // When undoing and redoing, the traversal order may be different. Record the range list of all single formula offsets, and then retrieve the traversal as needed.
- const rangeList: IRangeChange[] = [];
-
- oldFormulaMatrix.forValue((row, column, cell) => {
- // Offset is only needed when there is a formula
- if (cell == null || !isFormulaDataItem(cell)) return true;
-
- const oldCell = cellToRange(row, column);
- let newCell = null;
- let isReverse = false;
-
- // Handle moves
- if ([FormulaReferenceMoveType.MoveRange, FormulaReferenceMoveType.MoveRows, FormulaReferenceMoveType.MoveCols].includes(type)) {
- newCell = handleMove(type, from, to, oldCell);
- } else if (range !== undefined && range !== null) { // Handle inserts and deletes
- const result = handleInsertDelete(type, range, oldCell);
- // When removing a cell containing a formula, newCell is null, but the formula value of oldCell is required when undoing it, newCell can be null
- newCell = result.newCell;
- isReverse = result.isReverse;
- }
-
- // Don't intercept newCell null here
-
- // Note: The formula may only update the reference and not offset the position. The situation where the position is not shifted cannot be intercepted here.
- isReverse ? rangeList.unshift({ oldCell, newCell }) : rangeList.push({ oldCell, newCell });
- });
-
- return rangeList;
-}
-
-function handleMove(type: FormulaReferenceMoveType, from: Nullable<IRange>, to: Nullable<IRange>, oldCell: IRange) {
- if (from == null || to == null) {
- return null;
- }
-
- switch (type) {
- case FormulaReferenceMoveType.MoveRange:
-
- return handleRefMoveRange(from, to, oldCell);
- case FormulaReferenceMoveType.MoveRows:
-
- return handleRefMoveRows(from, to, oldCell);
- case FormulaReferenceMoveType.MoveCols:
-
- return handleRefMoveCols(from, to, oldCell);
- default:
- return null;
- }
-}
-
-function handleInsertDelete(type: FormulaReferenceMoveType, range: IRange, oldCell: IRange) {
- let newCell: IRange | null = null;
- let isReverse = false;
-
- switch (type) {
- case FormulaReferenceMoveType.InsertRow:
- newCell = handleRefInsertRow(range, oldCell);
- isReverse = true;
- break;
- case FormulaReferenceMoveType.InsertColumn:
- newCell = handleRefInsertCol(range, oldCell);
- isReverse = true;
- break;
- case FormulaReferenceMoveType.RemoveRow:
- newCell = handleRefRemoveRow(range, oldCell);
- break;
- case FormulaReferenceMoveType.RemoveColumn:
- newCell = handleRefRemoveCol(range, oldCell);
- break;
- case FormulaReferenceMoveType.DeleteMoveLeft:
- newCell = handleRefDeleteMoveLeft(range, oldCell);
- break;
- case FormulaReferenceMoveType.DeleteMoveUp:
- newCell = handleRefDeleteMoveUp(range, oldCell);
- break;
- case FormulaReferenceMoveType.InsertMoveDown:
- newCell = handleRefInsertMoveDown(range, oldCell);
- isReverse = true;
- break;
- case FormulaReferenceMoveType.InsertMoveRight:
- newCell = handleRefInsertMoveRight(range, oldCell);
- isReverse = true;
- break;
- default:
- break;
- }
-
- return { newCell, isReverse };
-}
-
-function handleRefMoveRange(from: IRange, to: IRange, oldCell: IRange) {
- const operators = handleMoveRange(
- {
- id: EffectRefRangId.MoveRangeCommandId,
- params: { toRange: to, fromRange: from },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefMoveRows(from: IRange, to: IRange, oldCell: IRange) {
- const operators = handleMoveRows(
- {
- id: EffectRefRangId.MoveRowsCommandId,
- params: { toRange: to, fromRange: from },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefMoveCols(from: IRange, to: IRange, oldCell: IRange) {
- const operators = handleMoveCols(
- {
- id: EffectRefRangId.MoveColsCommandId,
- params: { toRange: to, fromRange: from },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefInsertRow(range: IRange, oldCell: IRange) {
- const operators = handleInsertRow(
- {
- id: EffectRefRangId.InsertRowCommandId,
- params: { range, unitId: '', subUnitId: '', direction: Direction.DOWN },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefInsertCol(range: IRange, oldCell: IRange) {
- const operators = handleInsertCol(
- {
- id: EffectRefRangId.InsertColCommandId,
- params: { range, unitId: '', subUnitId: '', direction: Direction.RIGHT },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefRemoveRow(range: IRange, oldCell: IRange) {
- const operators = handleIRemoveRow(
- {
- id: EffectRefRangId.RemoveRowCommandId,
- params: { range },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefRemoveCol(range: IRange, oldCell: IRange) {
- const operators = handleIRemoveCol(
- {
- id: EffectRefRangId.RemoveColCommandId,
- params: { range },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefDeleteMoveLeft(range: IRange, oldCell: IRange) {
- const operators = handleDeleteRangeMoveLeft(
- {
- id: EffectRefRangId.DeleteRangeMoveLeftCommandId,
- params: { range },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefDeleteMoveUp(range: IRange, oldCell: IRange) {
- const operators = handleDeleteRangeMoveUp(
- {
- id: EffectRefRangId.DeleteRangeMoveUpCommandId,
- params: { range },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefInsertMoveDown(range: IRange, oldCell: IRange) {
- const operators = handleInsertRangeMoveDown(
- {
- id: EffectRefRangId.InsertRangeMoveDownCommandId,
- params: { range },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-function handleRefInsertMoveRight(range: IRange, oldCell: IRange) {
- const operators = handleInsertRangeMoveRight(
- {
- id: EffectRefRangId.InsertRangeMoveRightCommandId,
- params: { range },
- },
- oldCell
- );
-
- return runRefRangeMutations(operators, oldCell);
-}
-
-/**
- * Delete the old value at the old position on the match, and add the new value at the new position (the new value first checks whether the old position has offset content, if so, use the new offset content, if not, take the old value)
- * @param rangeList
- * @param oldFormulaData
- * @param newFormulaData
- */
-function getRedoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, newFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>) {
- const redoFormulaData = new ObjectMatrix<Nullable<ICellData>>({});
-
- rangeList.forEach((item) => {
- const { oldCell, newCell } = item;
-
- const { startRow: oldStartRow, startColumn: oldStartColumn } = oldCell;
-
- const newFormula = newFormulaMatrix.getValue(oldStartRow, oldStartColumn) || oldFormulaMatrix.getValue(oldStartRow, oldStartColumn);
- // Use the formula result value to update the data to ensure accuracy, otherwise the new formula cannot be inferred from #REF
- const newValue = formulaDataItemToCellData(newFormula);
-
- redoFormulaData.setValue(oldStartRow, oldStartColumn, { f: null, si: null });
-
- if (newCell) {
- const { startRow: newStartRow, startColumn: newStartColumn } = newCell;
- redoFormulaData.setValue(newStartRow, newStartColumn, newValue);
- }
- });
-
- return redoFormulaData.clone();
-}
-
-/**
- * The old position on the match saves the old value, and the new position delete value(for formulaData)
- * @param rangeList
- * @param oldFormulaData
- * @param newFormulaData
- */
-function getUndoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>) {
- const undoFormulaData = new ObjectMatrix<Nullable<ICellData>>({});
-
- // Maintaining the correct assignment order prevents overwriting data
- rangeList.reverse().forEach((item) => {
- const { oldCell, newCell } = item;
-
- const { startRow: oldStartRow, startColumn: oldStartColumn } = oldCell;
-
- const oldFormula = oldFormulaMatrix.getValue(oldStartRow, oldStartColumn);
- const oldValue = formulaDataItemToCellData(oldFormula);
-
- if (newCell) {
- const { startRow: newStartRow, startColumn: newStartColumn } = newCell;
- undoFormulaData.setValue(newStartRow, newStartColumn, { f: null, si: null });
- }
-
- undoFormulaData.setValue(oldStartRow, oldStartColumn, oldValue);
- });
-
- return undoFormulaData.clone();
-}
-
-/**
- * Transfer the formulaDataItem to the cellData
- * ┌────────────────────────────────┬─────────────────┐
- * │ IFormulaDataItem │ ICellData │
- * ├──────────────────┬─────┬───┬───┼───────────┬─────┤
- * │ f │ si │ x │ y │ f │ si │
- * ├──────────────────┼─────┼───┼───┼───────────┼─────┤
- * │ =SUM(1) │ │ │ │ =SUM(1) │ │
- * │ │ id1 │ │ │ │ id1 │
- * │ =SUM(1) │ id1 │ │ │ =SUM(1) │ id1 │
- * │ =SUM(1) │ id1 │ 0 │ 0 │ =SUM(1) │ id1 │
- * │ =SUM(1) │ id1 │ 0 │ 1 │ │ id1 │
- * └──────────────────┴─────┴───┴───┴───────────┴─────┘
- */
-export function formulaDataItemToCellData(formulaDataItem: Nullable<IFormulaDataItem>): Nullable<ICellData> {
- if (formulaDataItem == null) {
- return;
- }
- const { f, si, x = 0, y = 0 } = formulaDataItem;
- const checkFormulaString = isFormulaString(f);
- const checkFormulaId = isFormulaId(si);
-
- if (!checkFormulaString && !checkFormulaId) {
- return {
- f: null,
- si: null,
- };
- }
-
- const cellData: ICellData = {};
-
- if (checkFormulaId) {
- cellData.si = si;
- }
-
- if (checkFormulaString && x === 0 && y === 0) {
- cellData.f = f;
- }
-
- if (cellData.f === undefined) {
- cellData.f = null;
- }
-
- if (cellData.si === undefined) {
- cellData.si = null;
- }
-
- return cellData;
-}
-
-/**
- * Convert formulaData to cellData
- * @param formulaData
- * @returns
- */
-export function formulaDataToCellData(formulaData: IObjectMatrixPrimitiveType<IFormulaDataItem | null>
-): IObjectMatrixPrimitiveType<Nullable<ICellData>> {
- const cellData = new ObjectMatrix<Nullable<ICellData>>({});
- const formulaDataMatrix = new ObjectMatrix(formulaData);
-
- formulaDataMatrix.forValue((r, c, formulaDataItem) => {
- const cellDataItem = formulaDataItemToCellData(formulaDataItem);
- cellData.setValue(r, c, cellDataItem);
- });
-
- return cellData.clone();
-}
-
-export function isFormulaDataItem(cell: IFormulaDataItem) {
- const formulaString = cell?.f || '';
- const formulaId = cell?.si || '';
-
- const checkFormulaString = isFormulaString(formulaString);
- const checkFormulaId = isFormulaId(formulaId);
-
- if (checkFormulaString || checkFormulaId) {
- return true;
- }
-
- return false;
-}
-
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useLeftAndRightArrow.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useLeftAndRightArrow.ts
index 646262a240..a3fcd0135c 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useLeftAndRightArrow.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useLeftAndRightArrow.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
+import type { Editor } from '@univerjs/docs-ui';
import { CommandType, DisposableCollection, ICommandService, useDependency } from '@univerjs/core';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { IShortcutService, KeyCode } from '@univerjs/ui';
import { useEffect } from 'react';
-import type { Editor } from '@univerjs/docs-ui';
export const useLeftAndRightArrow = (isNeed: boolean, editor?: Editor) => {
const commandService = useDependency(ICommandService);
diff --git a/packages/sheets-formula/package.json b/packages/sheets-formula/package.json
index df0831f782..91a793a305 100644
--- a/packages/sheets-formula/package.json
+++ b/packages/sheets-formula/package.json
@@ -22,7 +22,8 @@
"exports": {
".": "./src/index.ts",
"./*": "./src/*",
- "./facade": "./src/facade/index.ts"
+ "./facade": "./src/facade/index.ts",
+ "./locale/*": "./src/locale/*.ts"
},
"main": "./src/index.ts",
"types": "./lib/types/index.d.ts",
@@ -41,12 +42,16 @@
"require": "./lib/cjs/*",
"types": "./lib/types/index.d.ts"
},
+ "./lib/*": "./lib/*",
"./facade": {
"import": "./lib/es/facade.js",
"require": "./lib/cjs/facade.js",
"types": "./lib/types/facade/index.d.ts"
},
- "./lib/*": "./lib/*"
+ "./locale/*": {
+ "import": "./lib/locale/*.js",
+ "types": "./lib/types/locale/*.d.ts"
+ }
}
},
"directories": {
@@ -92,11 +97,15 @@
"require": "./lib/cjs/*",
"types": "./lib/types/index.d.ts"
},
+ "./lib/*": "./lib/*",
"./facade": {
"import": "./lib/es/facade.js",
"require": "./lib/cjs/facade.js",
"types": "./lib/types/facade/index.d.ts"
},
- "./lib/*": "./lib/*"
+ "./locale/*": {
+ "import": "./lib/locale/*.js",
+ "types": "./lib/types/locale/*.d.ts"
+ }
}
}
diff --git a/packages/sheets-formula/src/controllers/config.schema.ts b/packages/sheets-formula/src/controllers/config.schema.ts
index 9ba378e35b..785fb4320d 100644
--- a/packages/sheets-formula/src/controllers/config.schema.ts
+++ b/packages/sheets-formula/src/controllers/config.schema.ts
@@ -24,10 +24,32 @@ export const PLUGIN_CONFIG_KEY_BASE = 'sheets-formula.base.config';
export const configSymbolBase = Symbol(PLUGIN_CONFIG_KEY_BASE);
+export enum CalculationMode {
+ /**
+ * Force calculation of all formulas
+ */
+ FORCED,
+
+ /**
+ * Partial calculation, only cells with formulas but no v values are calculated
+ */
+ WHEN_EMPTY,
+
+ /**
+ * All formulas are not calculated
+ */
+ NO_CALCULATION,
+}
+
export interface IUniverSheetsFormulaBaseConfig {
notExecuteFormula?: boolean;
description?: IFunctionInfo[];
function?: Array<[Ctor<BaseFunction>, IFunctionNames]>;
+
+ /**
+ * Define the calculation mode during initialization, default is `WHEN_EMPTY`
+ */
+ initialFormulaComputing?: CalculationMode;
}
export const defaultPluginBaseConfig: IUniverSheetsFormulaBaseConfig = {};
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 328a06f94a..1c445f4939 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -22,18 +22,18 @@ import type {
IExecutionInProgressParams,
IFormulaDirtyData,
ISetFormulaCalculationNotificationMutation,
- ISetFormulaCalculationStartMutation,
-} from '@univerjs/engine-formula';
+ ISetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { Disposable, ICommandService } from '@univerjs/core';
+import type { IUniverSheetsFormulaBaseConfig } from './config.schema';
+import { Disposable, ICommandService, IConfigService, ILogService, Inject, LocaleService } from '@univerjs/core';
import {
+ FormulaDataModel,
FormulaExecutedStateType,
FormulaExecuteStageType,
IActiveDirtyManagerService,
SetFormulaCalculationNotificationMutation,
SetFormulaCalculationStartMutation,
- SetFormulaCalculationStopMutation,
-} from '@univerjs/engine-formula';
+ SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
import {
ClearSelectionFormatCommand,
SetBorderCommand,
@@ -41,6 +41,7 @@ import {
SetStyleCommand,
} from '@univerjs/sheets';
import { BehaviorSubject } from 'rxjs';
+import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from './config.schema';
/**
* This interface is for the progress bar to display the calculation progress.
@@ -50,6 +51,8 @@ export interface ICalculationProgress {
done: number;
/** The total number of formulas need to calculate. */
count: number;
+ /** The label of the calculation progress. */
+ label?: string;
}
const NilProgress: ICalculationProgress = { done: 0, count: 0 };
@@ -81,6 +84,8 @@ export class TriggerCalculationController extends Disposable {
private _restartCalculation = false;
+ private _calculationMode: CalculationMode = CalculationMode.WHEN_EMPTY;
+
/**
* The mark of forced calculation. If a new mutation triggers dirty area calculation during the forced calculation process, forced calculation is still required.
*/
@@ -90,23 +95,37 @@ export class TriggerCalculationController extends Disposable {
readonly progress$ = this._progress$.asObservable();
- private _emitProgress(): void {
- this._progress$.next({ done: this._doneCalculationTaskCount, count: this._totalCalculationTaskCount });
+ private _emitProgress(label?: string): void {
+ this._progress$.next({ done: this._doneCalculationTaskCount, count: this._totalCalculationTaskCount, label });
}
private _startProgress(): void {
+ this._doneCalculationTaskCount = 0;
+ this._totalCalculationTaskCount = 1;
+
+ const analyzing = this._localeService.t('formula.progress.analyzing');
+ this._emitProgress(analyzing);
+ }
+
+ private _calculateProgress(label: string): void {
if (this._executionInProgressParams) {
const { totalFormulasToCalculate, completedFormulasCount, totalArrayFormulasToCalculate, completedArrayFormulasCount } = this._executionInProgressParams;
this._doneCalculationTaskCount = completedFormulasCount + completedArrayFormulasCount;
this._totalCalculationTaskCount = totalFormulasToCalculate + totalArrayFormulasToCalculate;
- this._emitProgress();
+ if (this._totalCalculationTaskCount === 0) {
+ return;
+ }
+
+ this._emitProgress(label);
}
}
private _completeProgress(): void {
- this._doneCalculationTaskCount = this._totalCalculationTaskCount;
- this._emitProgress();
+ this._doneCalculationTaskCount = this._totalCalculationTaskCount = 1;
+
+ const done = this._localeService.t('formula.progress.done');
+ this._emitProgress(done);
}
clearProgress(): void {
@@ -117,10 +136,17 @@ export class TriggerCalculationController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
- @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService
+ @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,
+ @ILogService private readonly _logService: ILogService,
+ @IConfigService private readonly _configService: IConfigService,
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
) {
super();
+ const config = this._configService.getConfig<IUniverSheetsFormulaBaseConfig>(PLUGIN_CONFIG_KEY_BASE);
+ this._calculationMode = config?.initialFormulaComputing ?? CalculationMode.WHEN_EMPTY;
+
this._commandExecutedListener();
this._initialExecuteFormulaProcessListener();
this._initialExecuteFormula();
@@ -196,7 +222,7 @@ export class TriggerCalculationController extends Disposable {
const { dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, clearDependencyTreeCache } = params;
if (dirtyRanges != null) {
- allDirtyRanges.push(...dirtyRanges);
+ this._mergeDirtyRanges(allDirtyRanges, dirtyRanges);
}
if (dirtyNameMap != null) {
@@ -257,6 +283,37 @@ export class TriggerCalculationController extends Disposable {
};
}
+ /**
+ * dirtyRanges may overlap with the ranges in allDirtyRanges and need to be deduplicated
+ * @param allDirtyRanges
+ * @param dirtyRanges
+ */
+ private _mergeDirtyRanges(allDirtyRanges: IUnitRange[], dirtyRanges: IUnitRange[]) {
+ for (const range of dirtyRanges) {
+ let isDuplicate = false;
+ for (const existingRange of allDirtyRanges) {
+ // Check if the ranges are in the same unit and sheet
+ if (range.unitId === existingRange.unitId && range.sheetId === existingRange.sheetId) {
+ // Check if the ranges overlap
+ const { startRow, startColumn, endRow, endColumn } = range.range;
+ const { startRow: existingStartRow, startColumn: existingStartColumn, endRow: existingEndRow, endColumn: existingEndColumn } = existingRange.range;
+ if (
+ startRow === existingStartRow &&
+ startColumn === existingStartColumn &&
+ endRow === existingEndRow &&
+ endColumn === existingEndColumn
+ ) {
+ isDuplicate = true;
+ break;
+ }
+ }
+ }
+ if (!isDuplicate) {
+ allDirtyRanges.push(range);
+ }
+ }
+ }
+
private _mergeDirtyNameMap(allDirtyNameMap: IDirtyUnitSheetNameMap, dirtyNameMap: IDirtyUnitSheetNameMap) {
Object.keys(dirtyNameMap).forEach((unitId) => {
if (allDirtyNameMap[unitId] == null) {
@@ -302,10 +359,36 @@ export class TriggerCalculationController extends Disposable {
// eslint-disable-next-line max-lines-per-function, complexity
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (command.id === SetFormulaCalculationStartMutation.id) {
- const { forceCalculation } = command.params as ISetFormulaCalculationStartMutation;
+ const { forceCalculation = false } = command.params as ISetFormulaCalculationStartMutation;
+
if (forceCalculation) {
this._forceCalculating = true;
}
+
+ // In NO_CALCULATION mode, the following processes will not be triggered, so there is no need to start
+ if (this._calculationMode === CalculationMode.NO_CALCULATION) {
+ return;
+ }
+
+ // When calculations are started multiple times in succession, only the first time is recognized
+ if (calculationProcessCount === 0) {
+ this._startExecutionTime = performance.now();
+ }
+
+ // Increment the calculation process count and assign a new ID
+ calculationProcessCount++;
+
+ // Clear any existing timer to prevent duplicate executions
+ if (startDependencyTimer !== null) {
+ clearTimeout(startDependencyTimer);
+ startDependencyTimer = null;
+ }
+
+ // If the total calculation time exceeds 1s, a progress bar is displayed.
+ startDependencyTimer = setTimeout(() => {
+ startDependencyTimer = null;
+ this._startProgress();
+ }, 1000);
} else if (command.id === SetFormulaCalculationStopMutation.id) {
this.clearProgress();
}
@@ -321,30 +404,26 @@ export class TriggerCalculationController extends Disposable {
stage,
} = params.stageInfo;
- if (stage === FormulaExecuteStageType.START) {
- // When calculations are started multiple times in succession, only the first time is recognized
- if (calculationProcessCount === 0) {
- this._startExecutionTime = performance.now();
- }
-
- // Increment the calculation process count and assign a new ID
- calculationProcessCount++;
+ if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING) {
+ this._executionInProgressParams = params.stageInfo;
- // Clear any existing timer to prevent duplicate executions
- if (startDependencyTimer !== null) {
- clearTimeout(startDependencyTimer);
- startDependencyTimer = null;
+ if (startDependencyTimer === null) {
+ const calculating = this._localeService.t('formula.progress.calculating');
+ this._calculateProgress(calculating);
}
+ } else if (stage === FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA) {
+ this._executionInProgressParams = params.stageInfo;
- // If the total calculation time exceeds 1s, a progress bar is displayed.
- startDependencyTimer = setTimeout(() => {
- startDependencyTimer = null;
- }, 1000);
- } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING || stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {
+ if (startDependencyTimer === null) {
+ const arrayAnalysis = this._localeService.t('formula.progress.array-analysis');
+ this._calculateProgress(arrayAnalysis);
+ }
+ } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {
this._executionInProgressParams = params.stageInfo;
if (startDependencyTimer === null) {
- this._startProgress();
+ const arrayCalculation = this._localeService.t('formula.progress.array-calculation');
+ this._calculateProgress(arrayCalculation);
}
}
} else {
@@ -410,7 +489,7 @@ export class TriggerCalculationController extends Disposable {
this._executionInProgressParams = null;
}
- console.warn(`Execution result: ${result}`);
+ this._logService.debug('[TriggerCalculationController]', result);
}
})
);
@@ -429,13 +508,30 @@ export class TriggerCalculationController extends Disposable {
}
private _initialExecuteFormula() {
- this._commandService.executeCommand(
- SetFormulaCalculationStartMutation.id,
- {
- commands: [],
- forceCalculation: true,
- },
- lo
- );
+ const params = this._getDiryDataByCalculationMode(this._calculationMode);
+ this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, params, lo);
+ }
+
+ private _getDiryDataByCalculationMode(calculationMode: CalculationMode): IFormulaDirtyData {
+ const forceCalculation = calculationMode === CalculationMode.FORCED;
+
+ // loop all sheets cell data, and get the dirty data
+ const dirtyRanges: IUnitRange[] = calculationMode === CalculationMode.WHEN_EMPTY ? this._formulaDataModel.getFormulaDirtyRanges() : [];
+
+ const dirtyNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyDefinedNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
+ const dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
+ const clearDependencyTreeCache: IDirtyUnitSheetNameMap = {};
+
+ return {
+ forceCalculation,
+ dirtyRanges,
+ dirtyNameMap,
+ dirtyDefinedNameMap,
+ dirtyUnitFeatureMap,
+ dirtyUnitOtherFormulaMap,
+ clearDependencyTreeCache,
+ };
}
}
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index add83a2d8d..1185b57119 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -17,21 +17,25 @@
import type {
ICommandInfo,
IExecutionOptions,
+ IUnitRange,
Nullable,
Workbook,
} from '@univerjs/core';
-import type { IFormulaData, IFormulaDataItem, IUnitSheetNameMap } from '@univerjs/engine-formula';
+import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IFormulaData, IFormulaDataItem, IFormulaDirtyData, IUnitSheetNameMap } from '@univerjs/engine-formula';
import type {
IInsertSheetMutationParams,
IRemoveSheetMutationParams,
ISetRangeValuesMutationParams,
} from '@univerjs/sheets';
-import type { IFormulaReferenceMoveParam } from './utils/ref-range-formula';
+import type { IUniverSheetsFormulaBaseConfig } from './config.schema';
+import type { IFormulaReferenceMoveParam } from './utils/ref-range-formula';
import type { IUnitRangeWithOffset } from './utils/ref-range-move';
+
import {
Disposable,
ICommandService,
+ IConfigService,
Inject,
Injector,
IUniverInstanceService,
@@ -53,7 +57,6 @@ import { deserializeRangeWithSheetWithCache,
SetFormulaCalculationStartMutation,
SetFormulaDataMutation,
} from '@univerjs/engine-formula';
-
import {
ClearSelectionFormatCommand,
InsertSheetMutation,
@@ -64,6 +67,7 @@ import {
SheetInterceptorService,
} from '@univerjs/sheets';
import { map } from 'rxjs';
+import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from './config.schema';
import { removeFormulaData } from './utils/offset-formula-data';
import { checkIsSameUnitAndSheet, formulaDataToCellData, FormulaReferenceMoveType, getFormulaReferenceMoveUndoRedo, updateRefOffset } from './utils/ref-range-formula';
import { getNewRangeByMoveParam } from './utils/ref-range-move';
@@ -88,6 +92,7 @@ export class UpdateFormulaController extends Disposable {
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,
+ @IConfigService private readonly _configService: IConfigService,
@Inject(Injector) readonly _injector: Injector
) {
super();
@@ -259,7 +264,35 @@ export class UpdateFormulaController extends Disposable {
});
this._commandService.executeCommand(SetFormulaDataMutation.id, { formulaData: newFormulaData }, { onlyLocal: true });
- this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, { commands: [], forceCalculation: true }, { onlyLocal: true });
+
+ const config = this._configService.getConfig<IUniverSheetsFormulaBaseConfig>(PLUGIN_CONFIG_KEY_BASE);
+ const calculationMode = config?.initialFormulaComputing ?? CalculationMode.WHEN_EMPTY;
+ const params = this._getDiryDataByCalculationMode(calculationMode);
+
+ this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, params, { onlyLocal: true });
+ }
+
+ private _getDiryDataByCalculationMode(calculationMode: CalculationMode): IFormulaDirtyData {
+ const forceCalculation = calculationMode === CalculationMode.FORCED;
+
+ // loop all sheets cell data, and get the dirty data
+ const dirtyRanges: IUnitRange[] = calculationMode === CalculationMode.WHEN_EMPTY ? this._formulaDataModel.getFormulaDirtyRanges() : [];
+
+ const dirtyNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyDefinedNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
+ const dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
+ const clearDependencyTreeCache: IDirtyUnitSheetNameMap = {};
+
+ return {
+ forceCalculation,
+ dirtyRanges,
+ dirtyNameMap,
+ dirtyDefinedNameMap,
+ dirtyUnitFeatureMap,
+ dirtyUnitOtherFormulaMap,
+ clearDependencyTreeCache,
+ };
}
private _getUpdateFormula(command: ICommandInfo) {
diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts
deleted file mode 100644
index 87d3b93a97..0000000000
--- a/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { describe, expect, it } from 'vitest';
-
-import { ErrorType } from '@univerjs/engine-formula';
-import { CellValueType } from '@univerjs/core';
-import { extractFormulaError, extractFormulaNumber } from '../utils';
-
-describe('Test utils', () => {
- it('Function extractFormulaError', () => {
- expect(extractFormulaError({ v: ErrorType.DIV_BY_ZERO, f: '=1/0' })).toBe(ErrorType.DIV_BY_ZERO);
- expect(extractFormulaError({ v: ErrorType.NAME, f: '=S' })).toBe(ErrorType.NAME);
- expect(extractFormulaError({ v: ErrorType.VALUE, f: '=SUM(A1)' })).toBe(ErrorType.VALUE);
- expect(extractFormulaError({ v: ErrorType.NUM, f: '=SUM(A1)' })).toBe(ErrorType.NUM);
- expect(extractFormulaError({ v: ErrorType.NA, f: '=SUM(A1)' })).toBe(ErrorType.NA);
- expect(extractFormulaError({ v: ErrorType.CYCLE, f: '=SUM(A1)' })).toBe(ErrorType.CYCLE);
- expect(extractFormulaError({ v: ErrorType.REF, f: '=SUM(A1)' })).toBe(ErrorType.REF);
- expect(extractFormulaError({ v: ErrorType.SPILL, f: '=SUM(A1)' })).toBe(ErrorType.SPILL);
- expect(extractFormulaError({ v: ErrorType.CALC, f: '=SUM(A1)' })).toBe(ErrorType.CALC);
- expect(extractFormulaError({ v: ErrorType.ERROR, f: '=SUM(A1)' })).toBe(ErrorType.ERROR);
- expect(extractFormulaError({ v: ErrorType.CONNECT, f: '=SUM(A1)' })).toBe(ErrorType.CONNECT);
-
- expect(extractFormulaError({ v: ErrorType.NULL, f: '=SUM(A1)' })).toBe(ErrorType.NULL);
- expect(extractFormulaError({ v: ErrorType.NULL, f: '=SUM(A1)', si: 'id1' })).toBe(ErrorType.NULL);
- expect(extractFormulaError({ v: ErrorType.NULL, si: 'id1' })).toBe(ErrorType.NULL);
- expect(extractFormulaError({ v: ErrorType.NULL })).toBeNull();
-
- expect(extractFormulaError({ f: '=SUM(1)' })).toBeNull();
- expect(extractFormulaError({ si: 'id1' })).toBeNull();
- expect(extractFormulaError({ p: null })).toBeNull();
- expect(extractFormulaError({ v: 'test' })).toBeNull();
- expect(extractFormulaError({ v: 1 })).toBeNull();
- expect(extractFormulaError({})).toBeNull();
- expect(extractFormulaError(null)).toBeNull();
- expect(extractFormulaError(undefined)).toBeNull();
- });
-
- it('Function extractFormulaNumber', () => {
- const v = 0.07 / 0.1;
- expect(extractFormulaNumber({ v })).toBeNull();
- expect(extractFormulaNumber({ v, f: '=SUM(A1)' })).toBeNull();
- expect(extractFormulaNumber({ v, si: 'id1', f: '=SUM(A1)', t: CellValueType.NUMBER })).toBe(0.7);
- });
-});
diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
index 2882735b8b..2ba47f2c1f 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
@@ -114,7 +114,7 @@ export function getFormulaReferenceSheet(oldFormulaData: IFormulaData,
const redoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = {
subUnitId,
unitId,
- cellValue: redoFormulaMatrix.clone(),
+ cellValue: redoFormulaMatrix.getMatrix(),
};
const redoMutation = {
@@ -127,7 +127,7 @@ export function getFormulaReferenceSheet(oldFormulaData: IFormulaData,
const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = {
subUnitId,
unitId,
- cellValue: undoFormulaMatrix.clone(),
+ cellValue: undoFormulaMatrix.getMatrix(),
};
const undoMutation = {
@@ -478,7 +478,7 @@ function getRedoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectM
}
});
- return redoFormulaData.clone();
+ return redoFormulaData.getMatrix();
}
/**
@@ -507,7 +507,7 @@ function getUndoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectM
undoFormulaData.setValue(oldStartRow, oldStartColumn, oldValue);
});
- return undoFormulaData.clone();
+ return undoFormulaData.getMatrix();
}
/**
@@ -572,10 +572,16 @@ export function formulaDataToCellData(formulaData: IObjectMatrixPrimitiveType<IF
formulaDataMatrix.forValue((r, c, formulaDataItem) => {
const cellDataItem = formulaDataItemToCellData(formulaDataItem);
+
+ // Originally matrix clone would filter out undefined, but after changing to getMatrix, you need to filter manually here
+ if (!cellDataItem) {
+ return;
+ }
+
cellData.setValue(r, c, cellDataItem);
});
- return cellData.clone();
+ return cellData.getMatrix();
}
export function isFormulaDataItem(cell: IFormulaDataItem) {
diff --git a/packages/sheets-formula/src/controllers/utils/utils.ts b/packages/sheets-formula/src/controllers/utils/utils.ts
deleted file mode 100644
index b092d20df4..0000000000
--- a/packages/sheets-formula/src/controllers/utils/utils.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { ICellData, IContextService, Nullable } from '@univerjs/core';
-import type { ErrorType } from '@univerjs/engine-formula';
-import { CellValueType, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, isFormulaId, isFormulaString } from '@univerjs/core';
-import { ERROR_TYPE_SET, stripErrorMargin } from '@univerjs/engine-formula';
-
-export function whenEditorStandalone(contextService: IContextService) {
- return (
- contextService.getContextValue(FOCUSING_DOC) &&
- contextService.getContextValue(FOCUSING_UNIVER_EDITOR) &&
- contextService.getContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)
- );
-}
-
-/**
- * Extract the formula error from the cell
- * @param cell
- * @returns
- */
-export function extractFormulaError(cell: Nullable<ICellData>, isArrayFormulaCell: boolean = false) {
- // Must contain a formula
- if (!isArrayFormulaCell && !(isFormulaString(cell?.f) || isFormulaId(cell?.si))) {
- return null;
- }
-
- if (typeof cell?.v === 'string' && ERROR_TYPE_SET.has(cell.v as ErrorType)) {
- return cell.v as ErrorType;
- }
-
- return null;
-}
-
-/**
- * Extract the formula number from the cell, handle the precision issue
- * @param cell
- * @returns
- */
-export function extractFormulaNumber(cell: Nullable<ICellData>) {
- if ((isFormulaString(cell?.f) || isFormulaId(cell?.si)) && cell?.t === CellValueType.NUMBER && typeof cell?.v === 'number') {
- return stripErrorMargin(cell.v);
- }
- return null;
-}
diff --git a/packages/sheets-formula/src/facade/f-formula.ts b/packages/sheets-formula/src/facade/f-formula.ts
new file mode 100644
index 0000000000..d7f02baa4f
--- /dev/null
+++ b/packages/sheets-formula/src/facade/f-formula.ts
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { CalculationMode, IUniverSheetsFormulaBaseConfig } from '../controllers/config.schema';
+
+import { IConfigService, ILogService, LifecycleService, LifecycleStages } from '@univerjs/core';
+import { FFormula } from '@univerjs/engine-formula';
+import { PLUGIN_CONFIG_KEY_BASE } from '../controllers/config.schema';
+
+interface IFFormulaSheetsMixin {
+ /**
+ * Update the calculation mode of the formula.
+ * @param calculationMode
+ * @returns
+ */
+ setInitialFormulaComputing(calculationMode: CalculationMode): void;
+}
+
+class FFormulaSheetsMixin extends FFormula implements IFFormulaSheetsMixin {
+ override setInitialFormulaComputing(calculationMode: CalculationMode): void {
+ const lifecycleService = this._injector.get(LifecycleService);
+ const lifecycleStage = lifecycleService.stage;
+
+ const logService = this._injector.get(ILogService);
+ const configService = this._injector.get(IConfigService);
+
+ if (lifecycleStage > LifecycleStages.Starting) {
+ logService.warn('[FFormula]', 'CalculationMode is called after the Starting lifecycle and will take effect the next time the Univer Sheet is constructed. If you want it to take effect when the Univer Sheet is initialized this time, consider calling it before the Ready lifecycle or using configuration.');
+ }
+
+ const config = configService.getConfig<Partial<IUniverSheetsFormulaBaseConfig>>(PLUGIN_CONFIG_KEY_BASE);
+
+ if (!config) {
+ return;
+ }
+
+ config.initialFormulaComputing = calculationMode;
+ }
+}
+
+FFormula.extend(FFormulaSheetsMixin);
+declare module '@univerjs/engine-formula' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FFormula extends IFFormulaSheetsMixin {}
+}
diff --git a/packages/sheets-formula/src/facade/index.ts b/packages/sheets-formula/src/facade/index.ts
index 14bcba31dc..f443acac52 100644
--- a/packages/sheets-formula/src/facade/index.ts
+++ b/packages/sheets-formula/src/facade/index.ts
@@ -15,3 +15,4 @@
*/
import './f-univer';
+import './f-formula';
diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.ts
index 9efd581387..fd0198044e 100644
--- a/packages/sheets-formula/src/index.ts
+++ b/packages/sheets-formula/src/index.ts
@@ -18,6 +18,7 @@ export { type IInsertFunction, type IInsertFunctionCommandParams, InsertFunction
export { OtherFormulaMarkDirty } from './commands/mutations/formula.mutation';
export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';
export { TriggerCalculationController } from './controllers/trigger-calculation.controller';
+export { CalculationMode, type IUniverSheetsFormulaBaseConfig, PLUGIN_CONFIG_KEY_BASE } from './controllers/config.schema';
// #region - all commands
diff --git a/packages/sheets-formula/src/locale/en-US.ts b/packages/sheets-formula/src/locale/en-US.ts
new file mode 100644
index 0000000000..913a2167dc
--- /dev/null
+++ b/packages/sheets-formula/src/locale/en-US.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type zhCN from './zh-CN';
+
+const locale: typeof zhCN = {
+ formula: {
+ progress: {
+ analyzing: 'Analyzing',
+ calculating: 'Calculating',
+ 'array-analysis': 'Array Analysis',
+ 'array-calculation': 'Array Calculation',
+ done: 'Done',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-formula/src/locale/fa-IR.ts b/packages/sheets-formula/src/locale/fa-IR.ts
new file mode 100644
index 0000000000..19109d33fc
--- /dev/null
+++ b/packages/sheets-formula/src/locale/fa-IR.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type zhCN from './zh-CN';
+
+const locale: typeof zhCN = {
+ formula: {
+ progress: {
+ analyzing: 'در حال تحلیل',
+ calculating: 'در حال محاسبه',
+ 'array-analysis': 'تحلیل آرایه',
+ 'array-calculation': 'محاسبه آرایه',
+ done: 'تمام',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-formula/src/locale/ru-RU.ts b/packages/sheets-formula/src/locale/ru-RU.ts
new file mode 100644
index 0000000000..ab7ada5ac7
--- /dev/null
+++ b/packages/sheets-formula/src/locale/ru-RU.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type zhCN from './zh-CN';
+
+const locale: typeof zhCN = {
+ formula: {
+ progress: {
+ analyzing: 'Анализ',
+ calculating: 'Вычисление',
+ 'array-analysis': 'Анализ массива',
+ 'array-calculation': 'Вычисление массива',
+ done: 'Готово',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-formula/src/locale/vi-VN.ts b/packages/sheets-formula/src/locale/vi-VN.ts
new file mode 100644
index 0000000000..6e1a3bb48b
--- /dev/null
+++ b/packages/sheets-formula/src/locale/vi-VN.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type zhCN from './zh-CN';
+
+const locale: typeof zhCN = {
+ formula: {
+ progress: {
+ analyzing: 'Đang phân tích',
+ calculating: 'Đang tính toán',
+ 'array-analysis': 'Phân tích mảng',
+ 'array-calculation': 'Tính toán mảng',
+ done: 'Hoàn tất',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-formula/src/locale/zh-CN.ts b/packages/sheets-formula/src/locale/zh-CN.ts
new file mode 100644
index 0000000000..a3c3327992
--- /dev/null
+++ b/packages/sheets-formula/src/locale/zh-CN.ts
@@ -0,0 +1,29 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const locale = {
+ formula: {
+ progress: {
+ analyzing: '分析中',
+ calculating: '计算中',
+ 'array-analysis': '数组分析',
+ 'array-calculation': '数组计算',
+ done: '完成',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-formula/src/locale/zh-TW.ts b/packages/sheets-formula/src/locale/zh-TW.ts
new file mode 100644
index 0000000000..d2c87ab816
--- /dev/null
+++ b/packages/sheets-formula/src/locale/zh-TW.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type zhCN from './zh-CN';
+
+const locale: typeof zhCN = {
+ formula: {
+ progress: {
+ analyzing: '分析中',
+ calculating: '計算中',
+ 'array-analysis': '陣列分析',
+ 'array-calculation': '陣列計算',
+ done: '完成',
+ },
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-formula/src/services/formula-common.ts b/packages/sheets-formula/src/services/formula-common.ts
index 61dcbb006f..4f417f2cad 100644
--- a/packages/sheets-formula/src/services/formula-common.ts
+++ b/packages/sheets-formula/src/services/formula-common.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, Nullable } from '@univerjs/core';
+import type { ICellData, IObjectMatrixPrimitiveType, Nullable } from '@univerjs/core';
export enum FormulaResultStatus {
NOT_REGISTER = 1,
@@ -24,10 +24,10 @@ export enum FormulaResultStatus {
}
export interface IOtherFormulaResult {
- result?: Nullable<ICellData>[][];
+ result?: IObjectMatrixPrimitiveType<Nullable<ICellData>[][]>;
status: FormulaResultStatus;
formulaId: string;
- callbacks: Set<(value: Nullable<ICellData>[][]) => void>;
+ callbacks: Set<(value: IObjectMatrixPrimitiveType<Nullable<ICellData>[][]>) => void>;
extra?: Record<string, any>;
}
diff --git a/packages/sheets-formula/src/services/register-other-formula.service.ts b/packages/sheets-formula/src/services/register-other-formula.service.ts
index 88010fb446..d62ecae1a6 100644
--- a/packages/sheets-formula/src/services/register-other-formula.service.ts
+++ b/packages/sheets-formula/src/services/register-other-formula.service.ts
@@ -14,21 +14,30 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
-import { Disposable, ICommandService, Tools } from '@univerjs/core';
+import type { IRange, Nullable } from '@univerjs/core';
import type { IRemoveOtherFormulaMutationParams, ISetFormulaCalculationResultMutation, ISetOtherFormulaMutationParams } from '@univerjs/engine-formula';
-import { IActiveDirtyManagerService, RemoveOtherFormulaMutation, SetFormulaCalculationResultMutation, SetOtherFormulaMutation } from '@univerjs/engine-formula';
-import { bufferTime, filter, map, Subject } from 'rxjs';
import type { IOtherFormulaMarkDirtyParams } from '../commands/mutations/formula.mutation';
+import { Disposable, ICommandService, ObjectMatrix, Tools } from '@univerjs/core';
+import { IActiveDirtyManagerService, RemoveOtherFormulaMutation, SetFormulaCalculationResultMutation, SetOtherFormulaMutation } from '@univerjs/engine-formula';
+import { Subject } from 'rxjs';
import { OtherFormulaMarkDirty } from '../commands/mutations/formula.mutation';
import { FormulaResultStatus, type IOtherFormulaResult } from './formula-common';
export class RegisterOtherFormulaService extends Disposable {
private _formulaCacheMap: Map<string, Map<string, Map<string, IOtherFormulaResult>>> = new Map();
+ /**
+ * @deprecated Use _formulaChangeWithRange$ instead
+ */
private _formulaChange$ = new Subject<{ unitId: string; subUnitId: string; formulaText: string; formulaId: string }>();
+ /**
+ * @deprecated Use formulaChangeWithRange$ instead
+ */
public formulaChange$ = this._formulaChange$.asObservable();
+ private _formulaChangeWithRange$ = new Subject<{ unitId: string; subUnitId: string; formulaText: string; formulaId: string; ranges: IRange[] }>();
+ public formulaChangeWithRange$ = this._formulaChangeWithRange$.asObservable();
+
// FIXME: this design could be improved.
private _formulaResult$ = new Subject<Record<string, Record<string, IOtherFormulaResult[]>>>();
@@ -47,6 +56,7 @@ export class RegisterOtherFormulaService extends Disposable {
super.dispose();
this._formulaChange$.complete();
+ this._formulaChangeWithRange$.complete();
this._formulaResult$.complete();
}
@@ -84,29 +94,50 @@ export class RegisterOtherFormulaService extends Disposable {
},
});
- this.formulaChange$.pipe(bufferTime(16), filter((list) => !!list.length), map((list) => {
- return list.reduce((result, cur) => {
- const { unitId, subUnitId, formulaId, formulaText } = cur;
- if (!result[unitId]) {
- result[unitId] = {};
- }
- if (!result[unitId][subUnitId]) {
- result[unitId][subUnitId] = {};
- }
- result[unitId][subUnitId][formulaId] = { f: formulaText };
- return result;
- }, {} as { [unitId: string]: { [sunUnitId: string]: { [formulaId: string]: { f: string } } } });
- })).subscribe((result) => {
- for (const unitId in result) {
- for (const subUnitId in result[unitId]) {
- const value = result[unitId][subUnitId];
- const config: ISetOtherFormulaMutationParams = { unitId, subUnitId, formulaMap: value };
- this._commandService.executeCommand(SetOtherFormulaMutation.id, config).then(() => {
- this._commandService.executeCommand(OtherFormulaMarkDirty.id,
- { [unitId]: { [subUnitId]: value } } as unknown as IOtherFormulaMarkDirtyParams);
- });
- }
- }
+ // this.formulaChange$.pipe(bufferTime(16), filter((list) => !!list.length), map((list) => {
+ // return list.reduce((result, cur) => {
+ // const { unitId, subUnitId, formulaId, formulaText } = cur;
+ // if (!result[unitId]) {
+ // result[unitId] = {};
+ // }
+ // if (!result[unitId][subUnitId]) {
+ // result[unitId][subUnitId] = {};
+ // }
+ // result[unitId][subUnitId][formulaId] = { f: formulaText };
+ // return result;
+ // }, {} as { [unitId: string]: { [sunUnitId: string]: { [formulaId: string]: { f: string } } } });
+ // })).subscribe((result) => {
+ // for (const unitId in result) {
+ // for (const subUnitId in result[unitId]) {
+ // const value = result[unitId][subUnitId];
+ // const config: ISetOtherFormulaMutationParams = { unitId, subUnitId, formulaMap: value };
+ // this._commandService.executeCommand(SetOtherFormulaMutation.id, config).then(() => {
+ // this._commandService.executeCommand(OtherFormulaMarkDirty.id,
+ // { [unitId]: { [subUnitId]: value } } as unknown as IOtherFormulaMarkDirtyParams);
+ // });
+ // }
+ // }
+ // });
+
+ // Register formula that need to be marked dirty with formula and range list
+ this._formulaChangeWithRange$.subscribe((option) => {
+ const { unitId, subUnitId, formulaText, formulaId, ranges } = option;
+
+ const params: ISetOtherFormulaMutationParams = {
+ unitId,
+ subUnitId,
+ formulaMap: {
+ [formulaId]: {
+ f: formulaText,
+ ranges,
+ },
+ },
+ };
+
+ this._commandService.executeCommand(SetOtherFormulaMutation.id, params).then(() => {
+ this._commandService.executeCommand(OtherFormulaMarkDirty.id,
+ { [unitId]: { [subUnitId]: { [formulaId]: true } } });
+ });
});
}
@@ -130,8 +161,23 @@ export class RegisterOtherFormulaService extends Disposable {
for (const formulaId in subUnitData) {
const current = subUnitData[formulaId];
if (cacheMap.has(formulaId)) {
- const item = cacheMap.get(formulaId)!;
- item.result = current;
+ const item = cacheMap.get(formulaId);
+
+ if (!item) {
+ continue;
+ }
+
+ if (!item?.result) {
+ item.result = {};
+ }
+
+ const resultMatrix = new ObjectMatrix(current);
+ const resultObject = new ObjectMatrix(item?.result);
+
+ resultMatrix.forValue((row, col, value) => {
+ resultObject.setValue(row, col, value);
+ });
+
item.status = FormulaResultStatus.SUCCESS;
item.callbacks.forEach((callback) => {
callback(current);
@@ -147,6 +193,14 @@ export class RegisterOtherFormulaService extends Disposable {
}));
}
+ /**
+ * @deprecated Use registerFormulaWithRange instead
+ * @param unitId
+ * @param subUnitId
+ * @param formulaText
+ * @param extra
+ * @returns
+ */
registerFormula(unitId: string, subUnitId: string, formulaText: string, extra?: Record<string, any>) {
const formulaId = this._createFormulaId(unitId, subUnitId);
const cacheMap = this._ensureCacheMap(unitId, subUnitId);
@@ -167,6 +221,27 @@ export class RegisterOtherFormulaService extends Disposable {
return formulaId;
}
+ registerFormulaWithRange(unitId: string, subUnitId: string, formulaText: string, ranges: IRange[] = [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }], extra?: Record<string, any>) {
+ const formulaId = this._createFormulaId(unitId, subUnitId);
+ const cacheMap = this._ensureCacheMap(unitId, subUnitId);
+
+ cacheMap.set(formulaId, {
+ result: undefined,
+ status: FormulaResultStatus.WAIT,
+ formulaId,
+ callbacks: new Set(),
+ extra,
+ });
+ this._formulaChangeWithRange$.next({
+ unitId,
+ subUnitId,
+ formulaText,
+ formulaId,
+ ranges,
+ });
+ return formulaId;
+ }
+
deleteFormula(unitId: string, subUnitId: string, formulaIdList: string[]) {
const params: IRemoveOtherFormulaMutationParams = {
unitId,
diff --git a/packages/sheets/src/controllers/calculate-result-apply.controller.ts b/packages/sheets/src/controllers/calculate-result-apply.controller.ts
index 5411e70797..550727f286 100644
--- a/packages/sheets/src/controllers/calculate-result-apply.controller.ts
+++ b/packages/sheets/src/controllers/calculate-result-apply.controller.ts
@@ -47,22 +47,22 @@ export class CalculateResultApplyController extends Disposable {
// Update each calculated value, possibly involving all cells
const redoMutationsInfo: ICommandInfo[] = [];
- unitIds.forEach((unitId) => {
+ for (let i = 0; i < unitIds.length; i++) {
+ const unitId = unitIds[i];
const sheetData = unitData[unitId];
if (sheetData == null) {
- return true;
+ continue;
}
const sheetIds = Object.keys(sheetData);
- sheetIds.forEach((sheetId) => {
+ for (let j = 0; j < sheetIds.length; j++) {
+ const sheetId = sheetIds[j];
const cellData = sheetData[sheetId];
- // const arrayFormula = arrayFormulaRange[unitId][sheetId];
-
if (cellData == null) {
- return true;
+ continue;
}
const cellValue = this._getMergedCellData(unitId, sheetId, cellData);
@@ -77,8 +77,8 @@ export class CalculateResultApplyController extends Disposable {
id: SetRangeValuesMutation.id,
params: setRangeValuesMutation,
});
- });
- });
+ }
+ }
const result = redoMutationsInfo.every((m) =>
this._commandService.executeCommand(m.id, m.params, {
@@ -111,6 +111,6 @@ export class CalculateResultApplyController extends Disposable {
cellDataMatrix.setValue(row, col, newCell);
});
- return cellDataMatrix.clone();
+ return cellDataMatrix.getMatrix();
}
}
diff --git a/packages/ui/src/components/progress-bar/ProgressBar.tsx b/packages/ui/src/components/progress-bar/ProgressBar.tsx
index 27bff5714f..5960538460 100644
--- a/packages/ui/src/components/progress-bar/ProgressBar.tsx
+++ b/packages/ui/src/components/progress-bar/ProgressBar.tsx
@@ -15,12 +15,13 @@
*/
import { ThemeService, useDependency } from '@univerjs/core';
+import { Tooltip } from '@univerjs/design';
import { CloseSingle } from '@univerjs/icons';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.less';
export interface IProgressBarProps {
- progress: { done: number; count: number };
+ progress: { done: number; count: number; label?: string };
barColor?: string;
onTerminate?: () => void;
onClearProgress?: () => void; // Notify the parent component of the reset progress
@@ -28,7 +29,7 @@ export interface IProgressBarProps {
export function ProgressBar(props: IProgressBarProps) {
const { barColor, progress, onTerminate, onClearProgress } = props;
- const { count, done } = progress;
+ const { count, done, label = '' } = progress;
const themeService = useDependency(ThemeService);
const color = barColor ?? themeService.getCurrentTheme().primaryColor; ;
@@ -37,9 +38,6 @@ export function ProgressBar(props: IProgressBarProps) {
// Introduce a state variable for visibility
const [visible, setVisible] = useState(count > 0);
- const [prevCount, setPrevCount] = useState(0);
- const [prevDone, setPrevDone] = useState(0);
-
useEffect(() => {
if (!progressBarInnerRef.current) return;
@@ -48,44 +46,37 @@ export function ProgressBar(props: IProgressBarProps) {
// Hide immediately if both count and done are zero
if (count === 0 && done === 0) {
setVisible(false);
- }
- // Handle the special case if count and done are equal for the first time and not from a previous progress change
- else if (count === done && prevCount === 0 && prevDone === 0) {
- setVisible(true);
progressBarInner.style.width = '0%';
- requestAnimationFrame(() => {
- progressBarInner.style.width = '100%';
- });
}
// Update the width of the progress bar
else if (count > 0) {
setVisible(true);
- progressBarInner.style.width = `${Math.floor((done / count) * 100)}%`;
+
+ // Trigger the animation to prevent the progress bar from not being closed due to reaching 100% too quickly without animation
+ if (done === count) {
+ requestAnimationFrame(() => {
+ progressBarInner.style.width = `${Math.floor((done / count) * 100)}%`;
+ });
+ } else {
+ progressBarInner.style.width = `${Math.floor((done / count) * 100)}%`;
+ }
}
// Else, wait for the transition to end before hiding
// Listen for the transitionend event
const handleTransitionEnd = () => {
- if ((count === 0 && done === 0) || done === count) {
+ if (done === count) {
// Hide the progress bar after the animation finishes
setVisible(false);
- // Reset the width for future progress bars
- progressBarInner.style.width = '0%';
// Notify the parent component to reset the progress after the animation ends
// After the progress bar is completed 100%, the upper props data source may not be reset, resulting in count and done still being the previous values (displaying 100%) when the progress bar is triggered next time, so a message is reported here to trigger clearing.
- if (done === count && onClearProgress) {
- onClearProgress();
- }
+ onClearProgress && onClearProgress();
}
};
progressBarInner.addEventListener('transitionend', handleTransitionEnd);
- // Update prevCount and prevDone
- setPrevCount(count);
- setPrevDone(done);
-
// Clean up the event listener on unmount or when dependencies change
return () => {
progressBarInner.removeEventListener('transitionend', handleTransitionEnd);
@@ -94,6 +85,11 @@ export function ProgressBar(props: IProgressBarProps) {
return (
<div className={styles.progressBarContainer} style={{ display: visible ? 'flex' : 'none' }}>
+
+ <Tooltip showIfEllipsis title={label}>
+ <span className={styles.progressBarLabel}>{label}</span>
+ </Tooltip>
+
<div className={styles.progressBar}>
<div
ref={progressBarInnerRef}
diff --git a/packages/ui/src/components/progress-bar/index.module.less b/packages/ui/src/components/progress-bar/index.module.less
index f3c4947dcb..a1b62578c0 100644
--- a/packages/ui/src/components/progress-bar/index.module.less
+++ b/packages/ui/src/components/progress-bar/index.module.less
@@ -1,16 +1,30 @@
@height: 4px;
+@bar-width: 160px;
+@label-width: 98px;
.progress-bar {
- width: 160px;
+ width: @bar-width;
height: @height;
background-color: rgb(var(--border-color));
border-radius: var(--border-radius-lg);
- margin-right: 8px;
+ margin-right: var(--margin-xs);
&-container {
display: flex;
align-items: center;
- margin: 0 8px 0 8px;
+ margin: 0 var(--margin-xs) 0 var(--margin-xs);
+ }
+
+ &-label {
+ font-size: var(--font-size-xxs);
+ color: rgb(var(--text-color-secondary));
+ width: @label-width;
+ text-align: right;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin-right: var(--margin-xs);
+ line-height: 17px;
}
&-inner {
@@ -22,7 +36,7 @@
&-close-button {
background: none;
border: none;
- font-size: 12px;
+ font-size: var(--font-size-xxs);
color: rgb(var(--text-color));
cursor: pointer;
padding: 0;