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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
perf(formula): dependency maintain (#1638)
Univerb745845c9ad9
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.tsindex 9c1c5529a7..cd369c2116 100644--- a/packages/engine-formula/src/basics/common.ts+++ b/packages/engine-formula/src/basics/common.ts@@ -112,7 +112,7 @@ export interface IFeatureDirtyRangeType {export interface IArrayFormulaUnitCellType extends IRuntimeUnitDataPrimitiveType {}export interface IFormulaData {- [unitId: string]: Nullable<{ [sheetId: string]: IObjectMatrixPrimitiveType<IFormulaDataItem> }>;+ [unitId: string]: Nullable<{ [sheetId: string]: Nullable<IObjectMatrixPrimitiveType<Nullable<IFormulaDataItem>>> }>;}export interface IOtherFormulaData {diff --git a/packages/engine-formula/src/controller/set-dependency.controller.ts b/packages/engine-formula/src/controller/set-dependency.controller.tsnew file mode 100644index 0000000000..a93453b1dd--- /dev/null+++ b/packages/engine-formula/src/controller/set-dependency.controller.ts@@ -0,0 +1,98 @@+/**+ * 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 { ICommandInfo } from '@univerjs/core';+import { Disposable, ICommandService, LifecycleStages, ObjectMatrix, OnLifecycle } from '@univerjs/core';++import {+ RemoveFeatureCalculationMutation,+ SetFeatureCalculationMutation,+} from '../commands/mutations/set-feature-calculation.mutation';+import { IFeatureCalculationManagerService } from '../services/feature-calculation-manager.service';+import { IDependencyManagerService } from '../services/dependency-manager.service';+import type { IRemoveOtherFormulaMutationParams, ISetOtherFormulaMutationParams } from '../commands/mutations/set-other-formula.mutation';+import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';+import type { ISetFormulaDataMutationParams } from '../commands/mutations/set-formula-data.mutation';+import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';++@OnLifecycle(LifecycleStages.Ready, SetDependencyController)+export class SetDependencyController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @IFeatureCalculationManagerService+ @IDependencyManagerService private readonly _dependencyManagerService: IDependencyManagerService+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === RemoveFeatureCalculationMutation.id || command.id === SetFeatureCalculationMutation.id) {+ const params = command.params as { featureId: string };+ if (params == null) {+ return;+ }+ const { featureId } = params;+ this._dependencyManagerService.removeFeatureFormulaDependency(featureId);+ } else if (command.id === RemoveOtherFormulaMutation.id) {+ const params = command.params as IRemoveOtherFormulaMutationParams;+ if (params == null) {+ return;+ }++ this._dependencyManagerService.removeOtherFormulaDependency(params.unitId, params.subUnitId, params.formulaIdList);+ } else if (command.id === SetOtherFormulaMutation.id) {+ const params = command.params as ISetOtherFormulaMutationParams;+ if (params == null) {+ return;+ }++ const formulaMap = params.formulaMap;+ const formulaIdList: string[] = [];+ Object.keys(formulaMap).forEach((formulaId) => {+ formulaIdList.push(formulaId);+ });+ this._dependencyManagerService.removeOtherFormulaDependency(params.unitId, params.subUnitId, formulaIdList);+ } else if (command.id === SetFormulaDataMutation.id) {+ const formulaData = (command.params as ISetFormulaDataMutationParams).formulaData;+ Object.keys(formulaData).forEach((unitId) => {+ if (formulaData[unitId] == null) {+ return true;+ }+ Object.keys(formulaData[unitId]!).forEach((subUnitId) => {+ const formulaDataItem = formulaData[unitId]![subUnitId];+ if (formulaDataItem == null) {+ this._dependencyManagerService.clearFormulaDependency(unitId, subUnitId);+ return true;+ }++ new ObjectMatrix(formulaDataItem).forValue((row, column) => {+ this._dependencyManagerService.removeFormulaDependency(unitId, subUnitId, row, column);+ });+ });+ });+ }+ })+ );+ }+}diff --git a/packages/engine-formula/src/controller/set-other-formula.controller.ts b/packages/engine-formula/src/controller/set-other-formula.controller.tsindex 5948850dcb..009b488c20 100644--- a/packages/engine-formula/src/controller/set-other-formula.controller.ts+++ b/packages/engine-formula/src/controller/set-other-formula.controller.ts@@ -22,12 +22,14 @@ import {} from '../services/other-formula-manager.service';import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';import type { IRemoveOtherFormulaMutationParams, ISetOtherFormulaMutationParams } from '../commands/mutations/set-other-formula.mutation';+import { IDependencyManagerService } from '../services/dependency-manager.service';@OnLifecycle(LifecycleStages.Ready, SetOtherFormulaController)export class SetOtherFormulaController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,- @IOtherFormulaManagerService private readonly _otherFormulaManagerService: IOtherFormulaManagerService+ @IOtherFormulaManagerService private readonly _otherFormulaManagerService: IOtherFormulaManagerService,+ @IDependencyManagerService private readonly _dependencyManagerService: IDependencyManagerService) {super();diff --git a/packages/engine-formula/src/engine/dependency/dependency-tree.ts b/packages/engine-formula/src/engine/dependency/dependency-tree.tsindex 2c45d7566f..4f05bb43ad 100644--- a/packages/engine-formula/src/engine/dependency/dependency-tree.ts+++ b/packages/engine-formula/src/engine/dependency/dependency-tree.ts@@ -77,6 +77,8 @@ export class FormulaDependencyTree extends Disposable {private _state = FDtreeStateType.DEFAULT;override dispose(): void {+ super.dispose();+this.children.forEach((tree) => {tree.dispose();});@@ -87,6 +89,10 @@ export class FormulaDependencyTree extends Disposable {this.node?.dispose();}+ resetState() {+ this._state = FDtreeStateType.DEFAULT;+ }+setAdded() {this._state = FDtreeStateType.ADDED;}@@ -153,28 +159,18 @@ export class FormulaDependencyTree extends Disposable {}const dependencyRanges = sheetRangeMap.get(sheetId)!;-const excludedCell = unitExcludedCell?.[unitId]?.[sheetId];-- let {- startRow: rangeStartRow,- endRow: rangeEndRow,- startColumn: rangeStartColumn,- endColumn: rangeEndColumn,- } = range;+ 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;}@@ -182,12 +178,7 @@ export class FormulaDependencyTree extends Disposable {for (const dependencyRange of dependencyRanges) {const { startRow, startColumn, endRow, endColumn } = dependencyRange;- if (- rangeStartRow > endRow ||- rangeEndRow < startRow ||- rangeStartColumn > endColumn ||- rangeEndColumn < startColumn- ) {+ if (rangeStartRow > endRow || rangeEndRow < startRow || rangeStartColumn > endColumn || rangeEndColumn < startColumn) {continue;} else {let isInclude = true;@@ -196,12 +187,7 @@ export class FormulaDependencyTree extends Disposable {* This is because its impact was already considered during the first calculation.*/excludedCell?.forValue((row, column) => {- if (- row >= rangeStartRow &&- row <= rangeEndRow &&- column >= rangeStartColumn &&- column <= rangeEndColumn- ) {+ if (row >= rangeStartRow && row <= rangeEndRow && column >= rangeStartColumn && column <= rangeEndColumn) {isInclude = false;return false;}@@ -278,6 +264,10 @@ export class FormulaDependencyTreeCache extends Disposable {return this._cacheItems.size;}+ get length() {+ return this._cacheItems.size;+ }+add(unitRangeWithToken: IUnitRangeWithToken, tree: FormulaDependencyTree) {const { token } = unitRangeWithToken;if (!this._cacheItems.has(token)) {diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.tsindex 22753c8830..02fb99006c 100644--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts@@ -38,6 +38,7 @@ import { Interpreter } from '../interpreter/interpreter';import type { BaseReferenceObject } from '../reference-object/base-reference-object';import type { PreCalculateNodeType } from '../utils/node-type';import { serializeRangeToRefString } from '../utils/reference';+import { IDependencyManagerService } from '../../services/dependency-manager.service';import type { IUnitRangeWithToken } from './dependency-tree';import { FormulaDependencyTree, FormulaDependencyTreeCache } from './dependency-tree';@@ -59,7 +60,8 @@ export class FormulaDependencyGenerator extends Disposable {private readonly _featureCalculationManagerService: IFeatureCalculationManagerService,@Inject(Interpreter) private readonly _interpreter: Interpreter,@Inject(AstTreeBuilder) private readonly _astTreeBuilder: AstTreeBuilder,- @Inject(Lexer) private readonly _lexer: Lexer+ @Inject(Lexer) private readonly _lexer: Lexer,+ @IDependencyManagerService private readonly _dependencyManagerService: IDependencyManagerService) {super();}@@ -152,48 +154,81 @@ export class FormulaDependencyGenerator extends Disposable {const treeList: FormulaDependencyTree[] = [];- /**- * Register formulas in the sheet.- */- for (const unitId of formulaDataKeys) {- const sheetData = formulaData[unitId];- if (sheetData == null) {- continue;- }+ this._registerFormulas(formulaDataKeys, formulaData, unitData, treeList);- const sheetDataKeys = Object.keys(sheetData);+ this._registerOtherFormulas(otherFormulaData, otherFormulaDataKeys, treeList);- for (const sheetId of sheetDataKeys) {- const matrixData = new ObjectMatrix(sheetData[sheetId]);+ this._registerFeatureFormulas(treeList);- matrixData.forValue((row, column, formulaDataItem) => {- // const formulaString = formulaDataItem.f;- if (formulaDataItem == null) {- return true;- }- const { f: formulaString, x, y } = formulaDataItem;- const node = this._generateAstNode(formulaString, x, y);- const FDtree = new FormulaDependencyTree();+ const dependencyTreeCache = new FormulaDependencyTreeCache();- const sheetItem = unitData[unitId][sheetId];+ for (let i = 0, len = treeList.length; i < len; i++) {+ const tree = treeList[i];- FDtree.node = node;- FDtree.formula = formulaString;- FDtree.unitId = unitId;- FDtree.subUnitId = sheetId;- FDtree.row = row;- FDtree.column = column;+ this._runtimeService.setCurrent(+ tree.row,+ tree.column,+ tree.rowCount,+ tree.columnCount,+ tree.subUnitId,+ tree.unitId+ );- FDtree.rowCount = sheetItem.rowCount;- FDtree.columnCount = sheetItem.columnCount;+ if (tree.node == null) {+ continue;+ }- treeList.push(FDtree);- });+ const rangeList = await this._getRangeListByNode(tree.node);++ for (let r = 0, rLen = rangeList.length; r < rLen; r++) {+ const range = rangeList[r];+ tree.pushRangeList(range);++ dependencyTreeCache.add(range, tree);}}+ return { treeList, dependencyTreeCache };+ }++ private _registerFeatureFormulas(treeList: FormulaDependencyTree[]) {+ /**+ * Register the external application relying on 'ref' into the formula system,+ * which can determine the execution timing of the external application+ * registration Executor based on the dependency relationship.+ */+ this._featureCalculationManagerService.getReferenceExecutorMap().forEach((params, featureId) => {+ const { unitId, subUnitId, dependencyRanges, getDirtyData } = params;++ if (this._dependencyManagerService.hasFeatureFormulaDependency(unitId, subUnitId, featureId)) {+ return true;+ }++ const FDtree = new FormulaDependencyTree();++ FDtree.unitId = unitId;+ FDtree.subUnitId = subUnitId;++ FDtree.getDirtyData = getDirtyData;++ FDtree.featureId = featureId;++ FDtree.rangeList = dependencyRanges.map((range) => {+ return {+ gridRange: range,+ token: serializeRangeToRefString({ ...range, sheetName: this._currentConfigService.getSheetName(range.unitId, range.sheetId) }),+ };+ });++ this._dependencyManagerService.addFeatureFormulaDependency(featureId, FDtree);++ treeList.push(FDtree);+ });+ }++ private _registerOtherFormulas(otherFormulaData: IOtherFormulaData, otherFormulaDataKeys: string[], treeList: FormulaDependencyTree[]) {/*** Register formulas in doc, slide, and other types of applications.*/@@ -216,6 +251,10 @@ export class FormulaDependencyGenerator extends Disposable {const subFormulaDataKeys = Object.keys(subFormulaData);for (const subFormulaDataId of subFormulaDataKeys) {+ if (this._dependencyManagerService.hasOtherFormulaDependency(unitId, subUnitId, subFormulaDataId)) {+ continue;+ }+const formulaDataItem = subFormulaData[subFormulaDataId];const { f: formulaString } = formulaDataItem;@@ -231,66 +270,63 @@ export class FormulaDependencyGenerator extends Disposable {FDtree.formulaId = subFormulaDataId;+ this._dependencyManagerService.addOtherFormulaDependency(unitId, subUnitId, subFormulaDataId, FDtree);+treeList.push(FDtree);}}}+ }+ private _registerFormulas(formulaDataKeys: string[], formulaData: IFormulaData, unitData: IUnitData, treeList: FormulaDependencyTree[]) {/**- * Register the external application relying on 'ref' into the formula system,- * which can determine the execution timing of the external application- * registration Executor based on the dependency relationship.+ * Register formulas in the sheet.*/- this._featureCalculationManagerService.getReferenceExecutorMap().forEach((params, featureId) => {- const { unitId, subUnitId, dependencyRanges, getDirtyData } = params;- const FDtree = new FormulaDependencyTree();+ for (const unitId of formulaDataKeys) {+ const sheetData = formulaData[unitId];- FDtree.unitId = unitId;- FDtree.subUnitId = subUnitId;+ if (sheetData == null) {+ continue;+ }- FDtree.getDirtyData = getDirtyData;+ const sheetDataKeys = Object.keys(sheetData);- FDtree.featureId = featureId;+ for (const sheetId of sheetDataKeys) {+ const matrixData = new ObjectMatrix(sheetData[sheetId] || {});- FDtree.rangeList = dependencyRanges.map((range) => {- return {- gridRange: range,- token: serializeRangeToRefString({ ...range, sheetName: this._currentConfigService.getSheetName(range.unitId, range.sheetId) }),- };- });+ matrixData.forValue((row, column, formulaDataItem) => {+ // const formulaString = formulaDataItem.f;+ if (formulaDataItem == null) {+ return true;+ }+ const { f: formulaString, x, y } = formulaDataItem;- treeList.push(FDtree);- });+ if (this._dependencyManagerService.hasFormulaDependency(unitId, sheetId, row, column)) {+ return true;+ }- const dependencyTreeCache = new FormulaDependencyTreeCache();+ const node = this._generateAstNode(formulaString, x, y);- for (let i = 0, len = treeList.length; i < len; i++) {- const tree = treeList[i];+ const FDtree = new FormulaDependencyTree();- this._runtimeService.setCurrent(- tree.row,- tree.column,- tree.rowCount,- tree.columnCount,- tree.subUnitId,- tree.unitId- );+ const sheetItem = unitData[unitId][sheetId];- if (tree.node == null) {- continue;- }+ FDtree.node = node;+ FDtree.formula = formulaString;+ FDtree.unitId = unitId;+ FDtree.subUnitId = sheetId;+ FDtree.row = row;+ FDtree.column = column;- const rangeList = await this._getRangeListByNode(tree.node);+ FDtree.rowCount = sheetItem.rowCount;+ FDtree.columnCount = sheetItem.columnCount;- for (let r = 0, rLen = rangeList.length; r < rLen; r++) {- const range = rangeList[r];- tree.pushRangeList(range);+ this._dependencyManagerService.addFormulaDependency(unitId, sheetId, row, column, FDtree);- dependencyTreeCache.add(range, tree);+ treeList.push(FDtree);+ });}}-- return { treeList, dependencyTreeCache };}/**@@ -501,29 +537,31 @@ export class FormulaDependencyGenerator extends Disposable {const existTree = new Set<FormulaDependencyTree>();const forceCalculate = this._currentConfigService.isForceCalculate();- let dependencyAlgorithm = true;+ let allTree: FormulaDependencyTree[] = [];if (dependencyTreeCache.size() > treeList.length) {- dependencyAlgorithm = false;+ allTree = this._dependencyManagerService.buildDependencyTree(treeList);+ } else {+ allTree = this._dependencyManagerService.buildDependencyTree(dependencyTreeCache);}- for (let i = 0, len = treeList.length; i < len; i++) {- const tree = treeList[i];+ 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;- }+ // if (dependencyAlgorithm) {+ // dependencyTreeCache.dependency(tree);+ // } else {+ // for (let m = 0, mLen = treeList.length; m < mLen; m++) {+ // const treeMatch = treeList[m];+ // if (tree === treeMatch) {+ // continue;+ // }- if (tree.dependency(treeMatch)) {- tree.pushChildren(treeMatch);- }- }- }+ // if (tree.dependency(treeMatch)) {+ // tree.pushChildren(treeMatch);+ // }+ // }+ // }/*** forceCalculate: Mandatory calculation, adding all formulas to dependencies@@ -550,15 +588,9 @@ export class FormulaDependencyGenerator extends Disposable {return newTreeList;}- /**- * Determine whether all ranges of the current node exist within the dirty area.- * If they are within the dirty area, return true, indicating that this node needs to be calculated.- * @param tree- */- private _includeTree(tree: FormulaDependencyTree) {+ private _includeTreeFeature(tree: FormulaDependencyTree) {const unitId = tree.unitId;const subUnitId = tree.subUnitId;-/*** Perform active dirty detection for the feature.*/@@ -571,6 +603,12 @@ export class FormulaDependencyGenerator extends Disposable {}}+ return false;+ }++ private _includeOtherFormula(tree: FormulaDependencyTree) {+ const unitId = tree.unitId;+ const subUnitId = tree.subUnitId;/*** Specify a specific other formula for flagging a functionality as dirty.*/@@ -583,6 +621,10 @@ export class FormulaDependencyGenerator extends Disposable {}}+ return false;+ }++ private _includeDefinedName(tree: FormulaDependencyTree) {/*** Detect whether the dirty map contains a defined name.*/@@ -593,6 +635,30 @@ export class FormulaDependencyGenerator extends Disposable {return true;}}+ return false;+ }++ /**+ * Determine whether all ranges of the current node exist within the dirty area.+ * If they are within the dirty area, return true, indicating that this node needs to be calculated.+ * @param tree+ */+ private _includeTree(tree: FormulaDependencyTree) {+ const unitId = tree.unitId;+ const subUnitId = tree.subUnitId;++ if (this._includeTreeFeature(tree) === true) {+ return true;+ }+++ if (this._includeOtherFormula(tree) === true) {+ return true;+ }++ if (this._includeDefinedName(tree) === true) {+ return true;+ }const excludedCell = this._currentConfigService.getExcludedRange()?.[unitId]?.[subUnitId];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.tsindex 32a8d658a3..fb08f0dba1 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@@ -222,16 +222,16 @@ export class ArrayValueObject extends BaseValueObject {}get(row: number, column: number) {- const rowValues = this._values[row];- if (rowValues == null) {- return null;- }+ // const rowValues = this._values[row];+ // if (rowValues == null) {+ // return null;+ // }- const v = rowValues[column];- if (v == null) {- return null;- }- return v;+ // const v = rowValues[column];+ // if (v == null) {+ // return null;+ // }+ return this._values[row]?.[column];}getRealValue(row: number, column: number) {@@ -355,11 +355,17 @@ export class ArrayValueObject extends BaseValueObject {* @param takeArray*/pick(takeArray: ArrayValueObject) {+ const newValue = this.pickRaw(takeArray);++ return this._createNewArray(newValue, 1, newValue[0].length);+ }++ pickRaw(takeArray: ArrayValueObject) {const takeArrayRowCount = takeArray.getRowCount();const takeArrayColumnCount = takeArray.getColumnCount();if (takeArrayRowCount !== this._rowCount || takeArrayColumnCount !== this._columnCount) {- return this._createNewArray([[NullValueObject.create()]], 1, 1);+ return [[NullValueObject.create()]];}const newValue: Nullable<BaseValueObject>[][] = [];@@ -369,18 +375,19 @@ export class ArrayValueObject extends BaseValueObject {for (let r = 0; r < takeArrayRowCount; r++) {for (let c = 0; c < takeArrayColumnCount; c++) {const takeCell = takeArray.get(r, c);- const value = this.get(r, c);+if (takeCell == null || takeCell.isError()) {continue;}if ((takeCell as BaseValueObject).getValue() === true) {+ const value = this.get(r, c);newValue[0].push(value);}}}- return this._createNewArray(newValue, 1, newValue[0].length);+ return newValue;}/**diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.tsindex 29c5098b87..a5a819e718 100644--- a/packages/engine-formula/src/functions/base-function.ts+++ b/packages/engine-formula/src/functions/base-function.ts@@ -263,40 +263,40 @@ export class BaseFunction extends Disposable {return resultValue;}- equalSearch(value: BaseValueObject, searchArray: ArrayValueObject, resultArray: ArrayValueObject, isFirst = true) {- const resultArrayValue = resultArray.pick(searchArray.isEqual(value) as ArrayValueObject);-- let resultValue: BaseValueObject;-- if (isFirst) {- resultValue = resultArrayValue.getFirstCell();- } else {- resultValue = resultArrayValue.getLastCell();+ private _getOneFirstByRaw(array: Nullable<BaseValueObject>[][]) {+ if (array.length === 0) {+ return ErrorValueObject.create(ErrorType.NA);}- if (resultValue.isNull()) {+ return array[0][0] || ErrorValueObject.create(ErrorType.NA);+ }++ private _getOneLastByRaw(array: Nullable<BaseValueObject>[][]) {+ if (array.length === 0) {return ErrorValueObject.create(ErrorType.NA);}- return resultValue;+ return array[array.length - 1][array[0].length - 1] || ErrorValueObject.create(ErrorType.NA);}- fuzzySearch(value: BaseValueObject, searchArray: ArrayValueObject, resultArray: ArrayValueObject, isFirst = true) {- const resultArrayValue = resultArray.pick(searchArray.compare(value, compareToken.EQUALS) as ArrayValueObject);-- let resultValue: BaseValueObject;+ equalSearch(value: BaseValueObject, searchArray: ArrayValueObject, resultArray: ArrayValueObject, isFirst = true) {+ const resultArrayValue = resultArray.pickRaw(searchArray.isEqual(value) as ArrayValueObject);if (isFirst) {- resultValue = resultArrayValue.getFirstCell();- } else {- resultValue = resultArrayValue.getLastCell();+ return this._getOneFirstByRaw(resultArrayValue);}- if (resultValue.isNull()) {- return ErrorValueObject.create(ErrorType.NA);+ return this._getOneLastByRaw(resultArrayValue);+ }++ fuzzySearch(value: BaseValueObject, searchArray: ArrayValueObject, resultArray: ArrayValueObject, isFirst = true) {+ const resultArrayValue = resultArray.pickRaw(searchArray.compare(value, compareToken.EQUALS) as ArrayValueObject);++ if (isFirst) {+ return this._getOneFirstByRaw(resultArrayValue);}- return resultValue;+ return this._getOneLastByRaw(resultArrayValue);}orderSearch(diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex b47d30a440..67ab5d5a16 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -272,7 +272,7 @@ export class FormulaDataModel extends Disposable {}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) {@@ -380,7 +380,7 @@ export class FormulaDataModel extends Disposable {workbookFormulaData[sheetId] = {};}- const sheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem>(workbookFormulaData[sheetId]);+ const sheetFormulaDataMatrix = new ObjectMatrix<Nullable<IFormulaDataItem>>(workbookFormulaData[sheetId] || {});const newSheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem | null>();cellMatrix.forValue((r, c, cell) => {@@ -404,8 +404,8 @@ export class FormulaDataModel extends Disposable {sheetFormulaDataMatrix.setValue(r, c, { f, si: formulaId, x, y });newSheetFormulaDataMatrix.setValue(r, c, { f, si: formulaId, x, y });} else if (typeof deleteFormula === 'string') {- const x = cell.x || 0;- const y = cell.y || 0;+ const x = cell?.x || 0;+ const y = cell?.y || 0;const offsetFormula = this._lexerTreeBuilder.moveFormulaRefOffset(deleteFormula, x, y);deleteFormulaIdMap.set(formulaId, {@@ -535,11 +535,14 @@ export class FormulaDataModel extends Disposable {return null;}- const cellMatrix = new ObjectMatrix(workbookFormulaData[sheetId]);+ const cellMatrix = new ObjectMatrix(workbookFormulaData[sheetId] || {});let formulaDataItem: Nullable<IFormulaDataItem> = null;cellMatrix.forValue((row, column, item) => {+ if (item == null) {+ return true;+ }const { f, si, x = 0, y = 0 } = item;if (si === sId && f.length > 0 && x === 0 && y === 0) {@@ -568,7 +571,7 @@ export class FormulaDataModel extends Disposable {return formulaIdMap;}- const sheetFormulaDataMatrix = new ObjectMatrix(workbookFormulaData[sheetId]);+ const sheetFormulaDataMatrix = new ObjectMatrix(workbookFormulaData[sheetId] || {});sheetFormulaDataMatrix.forValue((r, c, cell) => {const formulaString = cell?.f || '';diff --git a/packages/engine-formula/src/models/utils/formula-data-util.ts b/packages/engine-formula/src/models/utils/formula-data-util.tsindex ed40080fce..af4d6d45db 100644--- a/packages/engine-formula/src/models/utils/formula-data-util.ts+++ b/packages/engine-formula/src/models/utils/formula-data-util.ts@@ -24,7 +24,7 @@ export interface IFormulaIdMap {c: number;}-export function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatrix<IFormulaDataItem>, newSheetFormulaDataMatrix: ObjectMatrix<IFormulaDataItem | null>, formulaIdMap: Map<string, IFormulaIdMap>, deleteFormulaIdMap: Map<string, string | IFormulaIdMap>, r: number, c: number, cell: Nullable<ICellData>) {+export function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>, newSheetFormulaDataMatrix: ObjectMatrix<IFormulaDataItem | null>, formulaIdMap: Map<string, IFormulaIdMap>, deleteFormulaIdMap: Map<string, string | IFormulaIdMap>, r: number, c: number, cell: Nullable<ICellData>) {const formulaString = cell?.f || '';const formulaId = cell?.si || '';diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex ef5dcad848..5c20693b12 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -55,6 +55,8 @@ import { IOtherFormulaManagerService, OtherFormulaManagerService } from './serviimport { FormulaRuntimeService, IFormulaRuntimeService } from './services/runtime.service';import { ISuperTableService, SuperTableService } from './services/super-table.service';import { ActiveDirtyManagerService, IActiveDirtyManagerService } from './services/active-dirty-manager.service';+import { DependencyManagerService, IDependencyManagerService } from './services/dependency-manager.service';+import { SetDependencyController } from './controller/set-dependency.controller';const PLUGIN_NAME = 'base-formula-engine';@@ -113,11 +115,13 @@ export class UniverFormulaEnginePlugin extends Plugin {[IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],[IFormulaRuntimeService, { useClass: FormulaRuntimeService }],[IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],+ [IDependencyManagerService, { useClass: DependencyManagerService }],//Controller[CalculateController],[SetOtherFormulaController],[RegisterFunctionController],+ [SetDependencyController],// Calculation engine[FormulaDependencyGenerator],diff --git a/packages/engine-formula/src/services/dependency-manager.service.ts b/packages/engine-formula/src/services/dependency-manager.service.tsnew file mode 100644index 0000000000..fd362b64a4--- /dev/null+++ b/packages/engine-formula/src/services/dependency-manager.service.ts@@ -0,0 +1,261 @@+/**+ * 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 { Disposable, ObjectMatrix } from '@univerjs/core';+import { createIdentifier } from '@wendellhu/redi';+import { FormulaDependencyTreeCache } from '../engine/dependency/dependency-tree';+import type { FormulaDependencyTree } from '../engine/dependency/dependency-tree';++export interface IOtherFormulaDependencyParam {+ [unitId: string]: Nullable<{ [sheetId: string]: { [formulaId: string]: Nullable<FormulaDependencyTree> } }>;+}++export interface IFormulaDependencyParam {+ [unitId: string]: Nullable<{ [sheetId: string]: ObjectMatrix<Nullable<FormulaDependencyTree>> }>;+}++export interface IDependencyManagerService {+ dispose(): void;++ getAllTree(): FormulaDependencyTree[];++ buildDependencyTree(shouldBeBuildTrees: FormulaDependencyTree[] | FormulaDependencyTreeCache): FormulaDependencyTree[];++ clearDependencyForTree(shouldBeClearTree: Nullable<FormulaDependencyTree>): void;++ reset(): void;++ addOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string, dependencyTree: FormulaDependencyTree): void;++ removeOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string[]): void;++ hasOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string): boolean;++ addFeatureFormulaDependency(featureId: string, dependencyTree: FormulaDependencyTree): void;++ removeFeatureFormulaDependency(featureId: string): void;++ hasFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string): boolean;++ addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: FormulaDependencyTree): void;++ removeFormulaDependency(unitId: string, sheetId: string, row: number, column: number): void;++ hasFormulaDependency(unitId: string, sheetId: string, row: number, column: number): boolean;++ clearFormulaDependency(unitId: string, sheetId: string): void;+}++/**+ * Passively marked as dirty, register the reference and execution actions of the feature plugin.+ * After execution, a dirty area and calculated data will be returned,+ * causing the formula to be marked dirty again,+ * thereby completing the calculation of the entire dependency tree.+ */+export class DependencyManagerService extends Disposable implements IDependencyManagerService {+ private _otherFormulaData: IOtherFormulaDependencyParam = {};++ private _featureFormulaData: Map<string, FormulaDependencyTree> = new Map();++ private _formulaData: IFormulaDependencyParam = {};++ override dispose(): void {+ this._otherFormulaData = {};+ this._featureFormulaData.clear();+ this._formulaData = {};+ }++ /**+ * Get all FormulaDependencyTree from _otherFormulaData, _featureFormulaData, _formulaData+ * return FormulaDependencyTree[]+ */+ getAllTree() {+ const trees: FormulaDependencyTree[] = [];++ Object.values(this._otherFormulaData).forEach((unit) => {+ if (unit == null) {+ return true;+ }+ Object.values(unit).forEach((sheet) => {+ Object.values(sheet).forEach((formula) => {+ if (formula) {+ formula.resetState();+ trees.push(formula);+ }+ });+ });+ });++ this._featureFormulaData.forEach((feature) => {+ if (feature) {+ feature.resetState();+ trees.push(feature);+ }+ });++ Object.values(this._formulaData).map((unit) => {+ if (unit == null) {+ return [];+ }+ return Object.values(unit).forEach((sheet) => {+ return sheet.forValue((row, col, item) => {+ if (item) {+ item.resetState();+ trees.push(item);+ }+ });+ });+ });++ return trees;+ }++ buildDependencyTree(shouldBeBuildTrees: FormulaDependencyTree[] | FormulaDependencyTreeCache): FormulaDependencyTree[] {+ const allTrees = this.getAllTree();+ if (shouldBeBuildTrees.length === 0) {+ return allTrees;+ }+ this._buildDependencyTree(allTrees, shouldBeBuildTrees);+ return allTrees;+ }++ /**+ * Build the dependency relationship between the trees.+ * @param allTrees all FormulaDependencyTree+ * @param shouldBeBuildTrees FormulaDependencyTree[] | FormulaDependencyTreeCache+ */+ private _buildDependencyTree(allTrees: FormulaDependencyTree[], shouldBeBuildTrees: FormulaDependencyTree[] | FormulaDependencyTreeCache) {+ allTrees.forEach((tree) => {+ if (shouldBeBuildTrees instanceof FormulaDependencyTreeCache) {+ shouldBeBuildTrees.dependency(tree);+ } else {+ shouldBeBuildTrees.forEach((shouldBeBuildTree) => {+ if (tree === shouldBeBuildTree) {+ return true;+ }++ if (shouldBeBuildTree.dependency(tree)) {+ shouldBeBuildTree.pushChildren(tree);+ }+ });+ }+ });+ }++ /**+ * 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;++ parents.forEach((parent) => {+ parent.children = parent.children.filter((child) => child !== shouldBeClearTree);+ });++ children.forEach((child) => {+ child.parents = child.parents.filter((parent) => parent !== shouldBeClearTree);+ });++ this._buildDependencyTree(parents, children);++ shouldBeClearTree.dispose();+ }++ reset() {+ this._otherFormulaData = {};+ this._featureFormulaData.clear();+ this._formulaData = {};+ }++ addOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string, dependencyTree: FormulaDependencyTree) {+ if (!this._otherFormulaData[unitId]) {+ this._otherFormulaData[unitId] = {};+ }+ if (!this._otherFormulaData[unitId]![sheetId]) {+ this._otherFormulaData[unitId]![sheetId] = {};+ }+ this._otherFormulaData[unitId]![sheetId][formulaId] = dependencyTree;+ }++ removeOtherFormulaDependency(unitId: string, sheetId: string, formulaIds: string[]) {+ if (this._otherFormulaData[unitId] && this._otherFormulaData[unitId]![sheetId]) {+ formulaIds.forEach((formulaId) => {+ const deleteTree = this._otherFormulaData[unitId]![sheetId][formulaId];+ this.clearDependencyForTree(deleteTree);+ delete this._otherFormulaData[unitId]![sheetId][formulaId];+ });+ }+ }++ hasOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string) {+ return this._otherFormulaData[unitId]?.[sheetId]?.[formulaId] != null;+ }++ addFeatureFormulaDependency(featureId: string, dependencyTree: FormulaDependencyTree) {+ this._featureFormulaData.set(featureId, dependencyTree);+ }++ removeFeatureFormulaDependency(featureId: string) {+ const deleteTree = this._featureFormulaData.get(featureId);+ this.clearDependencyForTree(deleteTree);+ this._featureFormulaData.delete(featureId);+ }++ hasFeatureFormulaDependency(featureId: string) {+ return this._featureFormulaData.has(featureId);+ }++ addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: FormulaDependencyTree) {+ if (!this._formulaData[unitId]) {+ this._formulaData[unitId] = {};+ }+ if (!this._formulaData[unitId]![sheetId]) {+ this._formulaData[unitId]![sheetId] = new ObjectMatrix<Nullable<FormulaDependencyTree>>();+ }+ this._formulaData[unitId]![sheetId].setValue(row, column, dependencyTree);+ }++ removeFormulaDependency(unitId: string, sheetId: string, row: number, column: number) {+ if (this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {+ const deleteTree = this._formulaData[unitId]![sheetId].getValue(row, column);+ this.clearDependencyForTree(deleteTree);+ this._formulaData[unitId]![sheetId].realDeleteValue(row, column);+ }+ }++ clearFormulaDependency(unitId: string, sheetId: string) {+ if (this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {+ this._formulaData[unitId]![sheetId].reset();+ }+ }++ hasFormulaDependency(unitId: string, sheetId: string, row: number, column: number) {+ return this._formulaData[unitId]?.[sheetId]?.getValue(row, column) != null;+ }+}++export const IDependencyManagerService = createIdentifier<DependencyManagerService>(+ 'univer.formula.dependency-manager.service'+);diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex de63e12893..53142c658e 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -666,7 +666,7 @@ export class UpdateFormulaController extends Disposable {}for (const sheetId of sheetDataKeys) {- const matrixData = new ObjectMatrix(sheetData[sheetId]);+ const matrixData = new ObjectMatrix(sheetData[sheetId] || {});const oldFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();const newFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/offset-formula-data.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/offset-formula-data.spec.tsindex 8edec1d3c5..cea55150f5 100644--- a/packages/sheets-formula/src/controllers/utils/__tests__/offset-formula-data.spec.ts+++ b/packages/sheets-formula/src/controllers/utils/__tests__/offset-formula-data.spec.ts@@ -14,1304 +14,12 @@* limitations under the License.*/-import { cellToRange } from '@univerjs/core';-import type {- IDeleteRangeMoveLeftCommandParams,- IDeleteRangeMoveUpCommandParams,- IMoveRowsCommandParams,- InsertRangeMoveDownCommandParams,- InsertRangeMoveRightCommandParams,- IRemoveRowColCommandParams,-} from '@univerjs/sheets';-import {- DeleteRangeMoveLeftCommand,- DeleteRangeMoveUpCommand,- InsertColCommand,- InsertRangeMoveDownCommand,- InsertRangeMoveRightCommand,- InsertRowCommand,- MoveColsCommand,- MoveRangeCommand,- MoveRowsCommand,- RemoveColCommand,- RemoveRowCommand,-} from '@univerjs/sheets';+import { describe, expect, it } from 'vitest';-import { offsetArrayFormula, offsetFormula, removeFormulaData } from '../offset-formula-data';+import { removeFormulaData } from '../offset-formula-data';describe('Utils offset formula data test', () => {- describe('function offsetFormula', () => {- it('move range normal formula', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(A5)',- },- },- },- },- };-- const command = {- id: MoveRangeCommand.id,- params: {- fromRange: {- startRow: 0,- startColumn: 3,- endRow: 0,- endColumn: 3,- },- toRange: {- startRow: 3,- startColumn: 3,- endRow: 3,- endColumn: 3,- },- },- };-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: null,- },- 3: {- 3: {- f: '=SUM(A5)',- },- },- },- },- });- });- it('move range array formula with first cell', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaCellData = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- v: '1',- },- },- 1: {- 3: {- v: '2',- },- },- 2: {- 3: {- v: '3',- },- },- },- },- };- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- startRow: 0,- startColumn: 3,- endRow: 2,- endColumn: 3,- },- },- },- },- };-- const command = {- id: MoveRangeCommand.id,- params: {- fromRange: {- startRow: 0,- startColumn: 3,- endRow: 0,- endColumn: 3,- },- toRange: {- startRow: 3,- startColumn: 3,- endRow: 3,- endColumn: 3,- },- },- };-- const newFormulaData = offsetFormula(- arrayFormulaCellData,- command,- unitId,- sheetId,- null,- arrayFormulaRange- );- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: null,- },- 1: {- 3: null,- },- 2: {- 3: null,- },- 3: {- 3: {- v: '1',- },- },- },- },- });- });- it('move range array formula with not first cell', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaCellData = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- v: '1',- },- },- 1: {- 3: {- v: '2',- },- },- 2: {- 3: {- v: '3',- },- },- 3: {- 3: {- v: '4',- },- },- },- },- };- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- startRow: 0,- startColumn: 3,- endRow: 2,- endColumn: 3,- },- },- },- },- };-- const command = {- id: MoveRangeCommand.id,- params: {- fromRange: {- startRow: 1,- startColumn: 3,- endRow: 1,- endColumn: 3,- },- toRange: {- startRow: 3,- startColumn: 3,- endRow: 3,- endColumn: 3,- },- },- };-- const newFormulaData = offsetFormula(- arrayFormulaCellData,- command,- unitId,- sheetId,- null,- arrayFormulaRange- );- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: {- v: '1',- },- },- 1: {- 3: {- v: '2',- },- },- 2: {- 3: {- v: '3',- },- },- 3: {- 3: null,- },- },- },- });- });- it('move rows', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(A5)',- },- },- },- },- };-- const command = {- id: MoveRowsCommand.id,- params: {- fromRange: cellToRange(0, 1),- toRange: cellToRange(4, 1),- } as IMoveRowsCommandParams,- };-- const selections = [- {- range: {- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 19,- rangeType: 1,- },- primary: {- actualRow: 0,- actualColumn: 0,- isMerged: false,- isMergedMainCell: false,- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 0,- },- style: {- strokeWidth: 2,- stroke: '#409f11',- fill: 'rgba(53, 50, 43, 0.1)',- widgets: {},- widgetSize: 6,- widgetStrokeWidth: 1,- widgetStroke: '#ffffff',- hasAutoFill: true,- AutofillSize: 6,- AutofillStrokeWidth: 1,- AutofillStroke: '#ffffff',- hasRowHeader: true,- rowHeaderFill: 'rgba(53, 50, 43, 0.1)',- rowHeaderStroke: '#409f11',- rowHeaderStrokeWidth: 1,- hasColumnHeader: true,- columnHeaderFill: 'rgba(53, 50, 43, 0.1)',- columnHeaderStroke: '#409f11',- columnHeaderStrokeWidth: 1,- },- },- ];-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId, selections);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 3: {- 3: {- f: '=SUM(A5)',- },- },- },- },- });- });- it('move columns', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 0: {- f: '=SUM(E2)',- },- },- },- },- };-- const command = {- id: MoveColsCommand.id,- params: {- fromRange: cellToRange(1, 0),- toRange: cellToRange(1, 4),- } as IMoveRowsCommandParams,- };-- const selections = [- {- range: {- startRow: 0,- startColumn: 0,- endRow: 999,- endColumn: 0,- rangeType: 2,- },- primary: {- actualRow: 0,- actualColumn: 0,- isMerged: false,- isMergedMainCell: false,- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 0,- },- style: {- strokeWidth: 2,- stroke: '#409f11',- fill: 'rgba(53, 50, 43, 0.1)',- widgets: {},- widgetSize: 6,- widgetStrokeWidth: 1,- widgetStroke: '#ffffff',- hasAutoFill: true,- AutofillSize: 6,- AutofillStrokeWidth: 1,- AutofillStroke: '#ffffff',- hasRowHeader: true,- rowHeaderFill: 'rgba(53, 50, 43, 0.1)',- rowHeaderStroke: '#409f11',- rowHeaderStrokeWidth: 1,- hasColumnHeader: true,- columnHeaderFill: 'rgba(53, 50, 43, 0.1)',- columnHeaderStroke: '#409f11',- columnHeaderStrokeWidth: 1,- },- },- ];-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId, selections);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(E2)',- },- },- },- },- });- });- it('insert row', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(A1)',- },- },- 1: {- 3: {- f: '=SUM(A3)',- },- },- },- },- };-- const command = {- id: InsertRowCommand.id,- params: {- unitId,- subUnitId: sheetId,- direction: 2,- range: {- startRow: 1,- endRow: 1,- startColumn: 0,- endColumn: 19,- },- },- };-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(A1)',- },- },- 2: {- 3: {- f: '=SUM(A3)',- },- },- },- },- });- });- it('insert row, handle arrayFormulaCellData, with arrayFormulaRange and refRanges', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaCellData = {- [unitId]: {- [sheetId]: {- 4: {- 0: {- v: 1,- t: 2,- },- },- 5: {- 0: {- v: 2,- t: 2,- },- },- 6: {- 0: {- v: 3,- t: 2,- },- },- },- },- };-- const command = {- id: InsertRowCommand.id,- params: {- unitId,- subUnitId: sheetId,- direction: 0,- range: {- startRow: 3,- endRow: 3,- startColumn: 0,- endColumn: 19,- },- cellValue: {},- },- };-- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 4: {- 0: {- startRow: 4,- startColumn: 0,- endRow: 6,- endColumn: 0,- },- },- },- },- };-- const refRanges = [- {- row: 4,- column: 0,- range: {- startRow: 0,- startColumn: 0,- endRow: 2,- endColumn: 0,- startAbsoluteRefType: 0,- endAbsoluteRefType: 0,- },- },- ];-- const newFormulaData = offsetFormula(- arrayFormulaCellData,- command,- unitId,- sheetId,- null,- arrayFormulaRange,- refRanges- );- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 4: {- 0: null,- },- 5: {- 0: null,- },- 6: {- 0: null,- },- },- },- });- });- it('insert row, handle arrayFormulaRange', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 4: {- 0: {- startRow: 4,- startColumn: 0,- endRow: 6,- endColumn: 0,- },- },- },- },- };-- const command = {- id: InsertRowCommand.id,- params: {- unitId,- subUnitId: sheetId,- direction: 0,- range: {- startRow: 3,- endRow: 3,- startColumn: 0,- endColumn: 19,- },- cellValue: {},- },- };- const newFormulaData = offsetFormula(arrayFormulaRange, command, unitId, sheetId, null, arrayFormulaRange);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 4: {- 0: null,- },- 5: {- 0: null,- },- 6: {- 0: null,- },- },- },- });- });- it('insert column', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 2: {- f: '=SUM(C2)',- },- 3: {- f: '=SUM(D2)',- },- },- },- },- };-- const command = {- id: InsertColCommand.id,- params: {- unitId,- subUnitId: sheetId,- direction: 1,- range: {- startColumn: 1,- endColumn: 1,- startRow: 0,- endRow: 3,- },- },- };-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(C2)',- },- 4: {- f: '=SUM(D2)',- },- },- },- },- });- });- it('insert range move right', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 2: {- f: '=SUM(B2)',- },- 3: {- f: '=SUM(C2)',- },- },- },- },- };-- const command = {- id: InsertRangeMoveRightCommand.id,- params: {- range: {- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 0,- rangeType: 0,- },- } as InsertRangeMoveRightCommandParams,- };-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(B2)',- },- 4: {- f: '=SUM(C2)',- },- },- },- },- });- });- it('insert range move down', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(A2)',- },- },- 1: {- 3: {- f: '=SUM(A3)',- },- },- },- },- };-- const command = {- id: InsertRangeMoveDownCommand.id,- params: {- range: {- startRow: 0,- startColumn: 3,- endRow: 0,- endColumn: 3,- rangeType: 0,- },- } as InsertRangeMoveDownCommandParams,- };-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- // '0': {},- 1: {- 3: {- f: '=SUM(A2)',- },- },- 2: {- 3: {- f: '=SUM(A3)',- },- },- },- },- });- });- it('remove row', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 1: {- 3: {- f: '=SUM(A1)',- },- },- 2: {- 3: {- f: '=SUM(A2)',- },- },- },- },- };-- const command = {- id: RemoveRowCommand.id,- params: {- range: {- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 19,- rangeType: 1,- },- } as IRemoveRowColCommandParams,- };- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(A1)',- },- },- 1: {- 3: {- f: '=SUM(A2)',- },- },- },- },- });- });- it('remove row, handle arrayFormulaCellData, with arrayFormulaRange and refRanges', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaCellData = {- [unitId]: {- [sheetId]: {- 4: {- 0: {- v: 1,- t: 2,- },- },- 5: {- 0: {- v: 2,- t: 2,- },- },- 6: {- 0: {- v: 3,- t: 2,- },- },- },- },- };-- const command = {- id: RemoveRowCommand.id,- params: {- range: {- startRow: 1,- startColumn: 0,- endRow: 1,- endColumn: 19,- rangeType: 1,- },- },- };-- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 4: {- 0: {- startRow: 4,- startColumn: 0,- endRow: 6,- endColumn: 0,- },- },- },- },- };-- const refRanges = [- {- row: 4,- column: 0,- range: {- startRow: 0,- startColumn: 0,- endRow: 2,- endColumn: 0,- startAbsoluteRefType: 0,- endAbsoluteRefType: 0,- },- },- ];-- const newFormulaData = offsetFormula(- arrayFormulaCellData,- command,- unitId,- sheetId,- null,- arrayFormulaRange,- refRanges- );- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 4: {- 0: null,- },- 5: {- 0: null,- },- 6: {- 0: null,- },- },- },- });- });- it('remove row, handle arrayFormulaRange', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 4: {- 0: {- startRow: 4,- startColumn: 0,- endRow: 6,- endColumn: 0,- },- },- },- },- };-- const command = {- id: RemoveRowCommand.id,- params: {- range: {- startRow: 1,- startColumn: 0,- endRow: 1,- endColumn: 19,- rangeType: 1,- },- },- };- const newFormulaData = offsetFormula(arrayFormulaRange, command, unitId, sheetId, null, arrayFormulaRange);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 4: {- 0: null,- },- 5: {- 0: null,- },- 6: {- 0: null,- },- },- },- });- });- it('remove column', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 2: {- f: '=SUM(C2)',- },- 3: {- f: '=SUM(D2)',- },- },- },- },- };-- const command = {- id: RemoveColCommand.id,- params: {- range: {- startRow: 0,- startColumn: 0,- endRow: 999,- endColumn: 0,- rangeType: 2,- },- } as IRemoveRowColCommandParams,- };- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 1: {- f: '=SUM(C2)',- },- 2: {- f: '=SUM(D2)',- },- },- },- },- });- });- it('remove column, handle arrayFormulaCellData, with arrayFormulaRange and refRanges', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaCellData = {- [unitId]: {- [sheetId]: {- 0: {- 4: {- v: 1,- t: 2,- },- 5: {- v: 2,- t: 2,- },- 6: {- v: 3,- t: 2,- },- },- },- },- };-- const command = {- id: RemoveColCommand.id,- params: {- range: {- startRow: 0,- startColumn: 1,- endRow: 999,- endColumn: 1,- rangeType: 2,- },- },- };-- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 0: {- 4: {- startRow: 0,- startColumn: 4,- endRow: 0,- endColumn: 6,- },- },- },- },- };-- const refRanges = [- {- row: 0,- column: 4,- range: {- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 2,- startAbsoluteRefType: 0,- endAbsoluteRefType: 0,- },- },- ];-- const newFormulaData = offsetFormula(- arrayFormulaCellData,- command,- unitId,- sheetId,- null,- arrayFormulaRange,- refRanges- );- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 4: null,- 5: null,- 6: null,- },- },- },- });- });- it('remove column, handle arrayFormulaRange', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaRange = {- [unitId]: {- [sheetId]: {- 0: {- 4: {- startRow: 0,- startColumn: 4,- endRow: 0,- endColumn: 6,- },- },- },- },- };-- const command = {- id: RemoveColCommand.id,- params: {- range: {- startRow: 0,- startColumn: 1,- endRow: 999,- endColumn: 1,- rangeType: 2,- },- },- };- const newFormulaData = offsetFormula(arrayFormulaRange, command, unitId, sheetId, null, arrayFormulaRange);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 4: null,- 5: null,- 6: null,- },- },- },- });- });- it('delete range move up', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 1: {- 3: {- f: '=SUM(A2)',- },- },- 2: {- 3: {- f: '=SUM(A3)',- },- },- },- },- };-- const command = {- id: DeleteRangeMoveUpCommand.id,- params: {- range: {- startRow: 0,- startColumn: 3,- endRow: 0,- endColumn: 3,- rangeType: 0,- },- } as IDeleteRangeMoveUpCommandParams,- };-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 3: {- f: '=SUM(A2)',- },- },- 1: {- 3: {- f: '=SUM(A3)',- },- },- // '2': {},- },- },- });- });- it('delete range move left', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const formulaData = {- [unitId]: {- [sheetId]: {- 0: {- 2: {- f: '=SUM(B2)',- },- 3: {- f: '=SUM(C2)',- },- },- },- },- };-- const command = {- id: DeleteRangeMoveLeftCommand.id,- params: {- range: {- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 0,- rangeType: 0,- },- } as IDeleteRangeMoveLeftCommandParams,- };-- const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);- expect(newFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 0: {- 1: {- f: '=SUM(B2)',- },- 2: {- f: '=SUM(C2)',- },- },- },- },- });- });- });- describe('function offsetArrayFormula', () => {- it('offset array formula data', () => {- const unitId = 'workbook-01';- const sheetId = 'sheet-0011';- const arrayFormulaData = {- [unitId]: {- [sheetId]: {- 7: {- 0: {- startRow: 6,- startColumn: 0,- endRow: 9,- endColumn: 3,- },- 5: {- startRow: 6,- startColumn: 5,- endRow: 9,- endColumn: 8,- },- },- },- },- };-- const command = {- id: DeleteRangeMoveLeftCommand.id,- params: {- range: {- startRow: 0,- startColumn: 0,- endRow: 0,- endColumn: 0,- rangeType: 0,- },- },- };-- const newArrayFormulaData = offsetArrayFormula(arrayFormulaData, command, unitId, sheetId);- expect(newArrayFormulaData).toStrictEqual({- [unitId]: {- [sheetId]: {- 7: {- 0: {- startRow: 7,- startColumn: 0,- endRow: 10,- endColumn: 3,- },- 5: {- startRow: 7,- startColumn: 5,- endRow: 10,- endColumn: 8,- },- },- },- },- });- });- });-describe('function removeFormulaData', () => {it('remove data', () => {const unitId = 'workbook-01';diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/redo-undo-formula-data.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/redo-undo-formula-data.spec.tsdeleted file mode 100644index 77b3b3ee3b..0000000000--- a/packages/sheets-formula/src/controllers/utils/__tests__/redo-undo-formula-data.spec.ts+++ /dev/null@@ -1,165 +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 { UndoCommand } from '@univerjs/core';-import { MoveRangeMutation } from '@univerjs/sheets';-import { describe, expect, it } from 'vitest';--import { handleRedoUndoMoveRange } from '../redo-undo-formula-data';--describe('Utils redo undo formula data test', () => {- describe('function handleRedoUndoMoveRange', () => {- it('move range array formula with first cell, undo', () => {- const unitId = 'workbook-01';- const subUnitId = 'sheet1';-- const command = {- id: MoveRangeMutation.id,- type: 2,- params: {- from: {- value: {- 4: {- 0: {- f: '=A1:A3',- v: 1,- t: 2,- },- },- },- subUnitId,- },- to: {- value: {- 4: {- 2: null,- },- },- subUnitId,- },- unitId,- trigger: UndoCommand.id,- },- };-- const formulaData = {- [unitId]: {- [subUnitId]: {- 4: {- 2: {- f: '=A1:A3',- },- },- },- },- };-- const arrayFormulaRange = {- [unitId]: {- [subUnitId]: {- 4: {- 2: {- startRow: 4,- startColumn: 2,- endRow: 6,- endColumn: 2,- },- },- },- },- };-- const arrayFormulaCellData = {- [unitId]: {- [subUnitId]: {- 4: {- 0: null,- 2: {- v: 1,- t: 2,- },- },- 5: {- 0: null,- 2: {- v: 2,- t: 2,- },- },- 6: {- 0: null,- 2: {- v: 3,- t: 2,- },- },- },- },- };-- handleRedoUndoMoveRange(command, formulaData, arrayFormulaRange, arrayFormulaCellData);-- expect(formulaData).toStrictEqual({- [unitId]: {- [subUnitId]: {- 4: {- 0: {- f: '=A1:A3',- },- },- },- },- });- expect(arrayFormulaRange).toStrictEqual({- [unitId]: {- [subUnitId]: {- 4: {- 0: {- startRow: 4,- startColumn: 2,- endRow: 6,- endColumn: 2,- },- 2: null,- },- },- },- });-- expect(arrayFormulaCellData).toStrictEqual({- [unitId]: {- [subUnitId]: {- 4: {- 0: {- v: 1,- t: 2,- },- 2: null,- },- 5: {- 0: null,- 2: null,- },- 6: {- 0: null,- 2: null,- },- },- },- });- });- });-});diff --git a/packages/sheets-formula/src/controllers/utils/offset-formula-data.ts b/packages/sheets-formula/src/controllers/utils/offset-formula-data.tsindex c691ddcb7f..e5b5db3a06 100644--- a/packages/sheets-formula/src/controllers/utils/offset-formula-data.ts+++ b/packages/sheets-formula/src/controllers/utils/offset-formula-data.ts@@ -14,41 +14,8 @@* limitations under the License.*/-import type { ICommandInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';-import { Dimension, ObjectMatrix, RANGE_TYPE } from '@univerjs/core';-import type { IArrayFormulaRangeType } from '@univerjs/engine-formula';-import type {- IDeleteRangeMoveLeftCommandParams,- IDeleteRangeMoveUpCommandParams,- IInsertColCommandParams,- IInsertRowCommandParams,- IMoveColsCommandParams,- IMoveRangeCommandParams,- IMoveRowsCommandParams,- InsertRangeMoveDownCommandParams,- InsertRangeMoveRightCommandParams,- IRemoveRowColCommandParams,- ISelectionWithStyle,-} from '@univerjs/sheets';-import {- DeleteRangeMoveLeftCommand,- DeleteRangeMoveUpCommand,- handleDeleteRangeMutation,- handleInsertRangeMutation,- InsertColCommand,- InsertRangeMoveDownCommand,- InsertRangeMoveRightCommand,- InsertRowCommand,- MoveColsCommand,- MoveRangeCommand,- MoveRowsCommand,- RemoveColCommand,- RemoveRowCommand,-} from '@univerjs/sheets';--interface IFormulaDataGenerics<T> {- [unitId: string]: Nullable<{ [sheetId: string]: IObjectMatrixPrimitiveType<T> }>;-}+import type { IRange } from '@univerjs/core';+import type { IArrayFormulaRangeType, IArrayFormulaUnitCellType, IFormulaData } from '@univerjs/engine-formula';export interface IRefRangeWithPosition {row: number;@@ -56,337 +23,7 @@ export interface IRefRangeWithPosition {range: IRange;}-export function offsetFormula<T>(- formulaData: IFormulaDataGenerics<T>,- command: ICommandInfo,- unitId: string,- sheetId: string,- selections?: Readonly<Nullable<ISelectionWithStyle[]>>,- formulaRangeData?: IFormulaDataGenerics<IRange>,- refRanges?: IRefRangeWithPosition[]-): IFormulaDataGenerics<T> {- const { id } = command;-- if (checkFormulaDataNull(formulaData, unitId, sheetId)) return formulaData;-- const formulaMatrix = new ObjectMatrix(formulaData[unitId]![sheetId]);- const formulaRangeMatrix = formulaRangeData && new ObjectMatrix(formulaRangeData[unitId]![sheetId]);-- switch (id) {- case MoveRangeCommand.id:- handleMoveRange<T>(formulaMatrix, command as ICommandInfo<IMoveRangeCommandParams>, formulaRangeMatrix);- break;- case MoveRowsCommand.id:- handleMoveRows<T>(formulaMatrix, command as ICommandInfo<IMoveRowsCommandParams>, selections);- break;- case MoveColsCommand.id:- handleMoveCols<T>(formulaMatrix, command as ICommandInfo<IMoveColsCommandParams>, selections);- break;- case InsertRowCommand.id:- handleInsertRow<T>(- formulaMatrix,- command as ICommandInfo<IInsertRowCommandParams>,- formulaRangeMatrix,- refRanges- );- break;- case InsertColCommand.id:- handleInsertCol<T>(- formulaMatrix,- command as ICommandInfo<IInsertColCommandParams>,- formulaRangeMatrix,- refRanges- );- break;- case InsertRangeMoveRightCommand.id:- handleInsertRangeMoveRight<T>(formulaMatrix, command as ICommandInfo<InsertRangeMoveRightCommandParams>);- break;- case InsertRangeMoveDownCommand.id:- handleInsertRangeMoveDown<T>(formulaMatrix, command as ICommandInfo<InsertRangeMoveDownCommandParams>);- break;- case RemoveRowCommand.id:- handleRemoveRow<T>(- formulaMatrix,- command as ICommandInfo<IRemoveRowColCommandParams>,- formulaRangeMatrix,- refRanges- );- break;- case RemoveColCommand.id:- handleRemoveCol<T>(- formulaMatrix,- command as ICommandInfo<IRemoveRowColCommandParams>,- formulaRangeMatrix,- refRanges- );- break;- case DeleteRangeMoveUpCommand.id:- handleDeleteRangeMoveUp<T>(formulaMatrix, command as ICommandInfo<IDeleteRangeMoveUpCommandParams>);- break;- case DeleteRangeMoveLeftCommand.id:- handleDeleteRangeMoveLeft<T>(formulaMatrix, command as ICommandInfo<IDeleteRangeMoveLeftCommandParams>);- break;- }-- return formulaData;-}--function handleMoveRange<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IMoveRangeCommandParams>,- formulaRangeMatrix?: ObjectMatrix<IRange>-) {- const { params } = command;- if (!params) return;-- const { fromRange, toRange } = params;-- moveRangeUpdateFormulaData(fromRange, toRange, formulaMatrix, formulaMatrix, formulaRangeMatrix);-}--function handleMoveRows<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IMoveRowsCommandParams>,- selections?: Readonly<Nullable<ISelectionWithStyle[]>>-) {- const { params } = command;- if (!params) return;-- const {- fromRange: { startRow: fromRow },- toRange: { startRow: toRow },- } = params;-- const filteredSelections = selections?.filter(- (selection) =>- selection.range.rangeType === RANGE_TYPE.ROW &&- selection.range.startRow <= fromRow &&- fromRow <= selection.range.endRow- );-- if (filteredSelections?.length !== 1) return;-- const rangeToMove = filteredSelections[0].range;- const fromRowNumber = rangeToMove.startRow;- const count = rangeToMove.endRow - rangeToMove.startRow + 1;-- formulaMatrix.moveRows(fromRowNumber, count, toRow);-}--function handleMoveCols<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IMoveColsCommandParams>,- selections?: Readonly<Nullable<ISelectionWithStyle[]>>-) {- const { params } = command;- if (!params) return;-- const {- fromRange: { startColumn: fromCol },- toRange: { startColumn: toCol },- } = params;-- const filteredSelections = selections?.filter(- (selection) =>- selection.range.rangeType === RANGE_TYPE.COLUMN &&- selection.range.startColumn <= fromCol &&- fromCol <= selection.range.endColumn- );-- if (filteredSelections?.length !== 1) return;-- const rangeToMove = filteredSelections[0].range;- const fromColNumber = rangeToMove.startColumn;- const count = rangeToMove.endColumn - rangeToMove.startColumn + 1;-- formulaMatrix.moveColumns(fromColNumber, count, toCol);-}--function handleInsertRow<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IInsertRowCommandParams>,- formulaRangeMatrix?: ObjectMatrix<IRange>,- refRanges?: IRefRangeWithPosition[]-) {- const { params } = command;- if (!params) return;-- const { range } = params;-- if (formulaRangeMatrix) {- removeFormulaArrayRow(range, formulaMatrix, formulaRangeMatrix, refRanges);- return;- }-- // Handle formula data- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;- // Offset formula range- handleInsertRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.ROWS);-}--function handleInsertCol<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IInsertColCommandParams>,- formulaRangeMatrix?: ObjectMatrix<IRange>,- refRanges?: IRefRangeWithPosition[]-) {- const { params } = command;- if (!params) return;-- const { range } = params;-- if (formulaRangeMatrix) {- removeFormulaArrayColumn(range, formulaMatrix, formulaRangeMatrix, refRanges);- return;- }-- // Handle formula data- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;- // Offset formula range- handleInsertRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.COLUMNS);-}--function handleInsertRangeMoveRight<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<InsertRangeMoveRightCommandParams>-) {- const { params } = command;- if (!params) return;-- const { range } = params;- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;-- handleInsertRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.COLUMNS);-}--function handleInsertRangeMoveDown<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<InsertRangeMoveDownCommandParams>-) {- const { params } = command;- if (!params) return;-- const { range } = params;- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;-- handleInsertRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.ROWS);-}--function handleRemoveRow<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IRemoveRowColCommandParams>,- formulaRangeMatrix?: ObjectMatrix<IRange>,- refRanges?: IRefRangeWithPosition[]-) {- const { params } = command;- if (!params) return;-- const { range } = params;-- if (formulaRangeMatrix) {- removeFormulaArrayRow(range, formulaMatrix, formulaRangeMatrix, refRanges);- return;- }-- // Handle formula data- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;- // Offset formula range- handleDeleteRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.ROWS);-}--function handleRemoveCol<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IRemoveRowColCommandParams>,- formulaRangeMatrix?: ObjectMatrix<IRange>,- refRanges?: IRefRangeWithPosition[]-) {- const { params } = command;- if (!params) return;-- const { range } = params;-- if (formulaRangeMatrix) {- removeFormulaArrayColumn(range, formulaMatrix, formulaRangeMatrix, refRanges);- return;- }-- // Handle formula data- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;- // Offset formula range- handleDeleteRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.COLUMNS);-}--function handleDeleteRangeMoveUp<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IDeleteRangeMoveUpCommandParams>-) {- const { params } = command;- if (!params) return;-- const { range } = params;- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;-- handleDeleteRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.ROWS);-}--function handleDeleteRangeMoveLeft<T>(- formulaMatrix: ObjectMatrix<T>,- command: ICommandInfo<IDeleteRangeMoveLeftCommandParams>-) {- const { params } = command;- if (!params) return;-- const { range } = params;- const lastEndRow = formulaMatrix.getLength() - 1;- const lastEndColumn = formulaMatrix.getRange().endColumn;-- handleDeleteRangeMutation(formulaMatrix, range, lastEndRow, lastEndColumn, Dimension.COLUMNS);-}--export function offsetArrayFormula(- arrayFormulaRange: IArrayFormulaRangeType,- command: ICommandInfo,- unitId: string,- sheetId: string-) {- if (checkFormulaDataNull(arrayFormulaRange, unitId, sheetId)) return arrayFormulaRange;- if (arrayFormulaRange[unitId]?.[sheetId] == null) {- return arrayFormulaRange;- }- const arrayFormulaRangeMatrix = new ObjectMatrix(arrayFormulaRange[unitId]![sheetId]);- arrayFormulaRangeMatrix.forValue((row, column, range) => {- if (range == null) {- return true;- }- const { startRow, startColumn, endRow, endColumn } = range;- if (row === startRow && column === startColumn) {- return true;- }-- const rows = endRow - startRow;- const columns = endColumn - startColumn;-- const newRange = {- startRow: row,- startColumn: column,- endRow: row + rows,- endColumn: column + columns,- };-- arrayFormulaRangeMatrix.setValue(row, column, newRange);- });-- return arrayFormulaRange;-}--export function checkFormulaDataNull<T>(formulaData: IFormulaDataGenerics<T>, unitId: string, sheetId: string) {+export function checkFormulaDataNull(formulaData: IFormulaData, unitId: string, sheetId: string) {if (formulaData == null || formulaData[unitId] == null || formulaData[unitId]?.[sheetId] == null) {return true;}@@ -394,7 +31,7 @@ export function checkFormulaDataNull<T>(formulaData: IFormulaDataGenerics<T>, unreturn false;}-export function removeFormulaData<T>(formulaData: IFormulaDataGenerics<T>, unitId: string, sheetId: string) {+export function removeFormulaData(formulaData: IFormulaData | IArrayFormulaRangeType | IArrayFormulaUnitCellType, unitId: string, sheetId: string) {if (formulaData && formulaData[unitId] && formulaData[unitId]?.[sheetId]) {delete formulaData[unitId]![sheetId];return {@@ -404,150 +41,3 @@ export function removeFormulaData<T>(formulaData: IFormulaDataGenerics<T>, unitI};}}-export function removeValueFormulaArray<T>(formulaRange: IRange, formulaMatrix: ObjectMatrix<T>) {- const { startRow, endRow, startColumn, endColumn } = formulaRange;- for (let r = startRow; r <= endRow; r++) {- for (let c = startColumn; c <= endColumn; c++) {- formulaMatrix.setValue(r, c, null as T);- }- }-}--export function inFormulaRange(row: number, column: number, formulaMatrix?: ObjectMatrix<IRange>) {- if (!formulaMatrix) return false;-- let result = false;- formulaMatrix.forValue((r, c, range) => {- if (!range) return;-- const { startRow, endRow, startColumn, endColumn } = range;-- if (startRow <= row && row <= endRow && startColumn <= column && column <= endColumn) {- result = true;- return false;- }- });-- return result;-}--export function moveRangeUpdateFormulaData<T>(- fromRange: IRange,- toRange: IRange,- fromArrayFormulaCellDataMatrix: ObjectMatrix<T>,- toArrayFormulaCellDataMatrix: ObjectMatrix<T>,- arrayFormulaRangeMatrix?: ObjectMatrix<IRange>-) {- const {- startRow: fromStartRow,- endRow: fromEndRow,- startColumn: fromStartColumn,- endColumn: fromEndColumn,- } = fromRange;-- const { startRow: toStartRow, endRow: toEndRow, startColumn: toStartColumn, endColumn: toEndColumn } = toRange;-- const cacheMatrix = new ObjectMatrix<T>();-- for (let r = fromStartRow; r <= fromEndRow; r++) {- for (let c = fromStartColumn; c <= fromEndColumn; c++) {- const cacheValue = fromArrayFormulaCellDataMatrix.getValue(r, c);-- // If the moved area has an array formula,- // move the first cell, you need to clear the contents of the array formula.- // move the no-first cell, do not change the original data, set the new area to null- const formulaRange = arrayFormulaRangeMatrix && arrayFormulaRangeMatrix.getValue(r, c);- if (formulaRange) {- cacheMatrix.setValue(r - fromStartRow, c - fromStartColumn, cacheValue);- removeValueFormulaArray(formulaRange, fromArrayFormulaCellDataMatrix);- continue;- } else if (inFormulaRange(r, c, arrayFormulaRangeMatrix)) {- cacheMatrix.setValue(r - fromStartRow, c - fromStartColumn, null as T);- continue;- }-- cacheMatrix.setValue(r - fromStartRow, c - fromStartColumn, cacheValue);- fromArrayFormulaCellDataMatrix.setValue(r, c, null as T);- }- }-- for (let r = toStartRow; r <= toEndRow; r++) {- for (let c = toStartColumn; c <= toEndColumn; c++) {- const cacheValue = cacheMatrix.getValue(r - toStartRow, c - toStartColumn);- toArrayFormulaCellDataMatrix.setValue(r, c, cacheValue);- }- }-}--/**- * Handle arrayFormulaRange and arrayFormulaCellData. If removing rows affects the array formula, the array formula cell data needs to be cleared and will be regenerated during recalculation.- * @param range- * @param formulaMatrix- * @param formulaRangeMatrix- * @param refRanges- */-export function removeFormulaArrayRow<T>(- range: IRange,- formulaMatrix: ObjectMatrix<T>,- formulaRangeMatrix: ObjectMatrix<IRange>,- refRanges?: IRefRangeWithPosition[]-) {- const { endRow } = range;- // 1. Above the first line of ArrayFormula- formulaRangeMatrix.forValue((row, column, range) => {- if (!range) return;-- const { startRow: formulaRangeStartRow } = range;- if (endRow <= formulaRangeStartRow) {- removeValueFormulaArray(range, formulaMatrix);- }- });-- // 2. Above the last line of refRanges- refRanges?.forEach(({ row, column, range }) => {- if (!range) return;-- const { endRow: refRangeEndRow } = range;- if (endRow <= refRangeEndRow) {- // The formula cell position corresponding to refRange- const removeRange = formulaRangeMatrix?.getValue(row, column);- removeRange && removeValueFormulaArray(removeRange, formulaMatrix);- }- });-}--/**- * Handle arrayFormulaRange and arrayFormulaCellData. If removing columns affects the array formula, the array formula cell data needs to be cleared and will be regenerated during recalculation.- * @param range- * @param formulaRangeMatrix- * @param refRanges- */-export function removeFormulaArrayColumn<T>(- range: IRange,- formulaMatrix: ObjectMatrix<T>,- formulaRangeMatrix: ObjectMatrix<IRange>,- refRanges?: IRefRangeWithPosition[]-) {- const { endColumn } = range;- // 1. Left of the first column of ArrayFormula- formulaRangeMatrix.forValue((row, column, range) => {- if (!range) return;-- const { startColumn: formulaRangeStartColumn } = range;- if (endColumn <= formulaRangeStartColumn) {- removeValueFormulaArray(range, formulaMatrix);- }- });-- // 2. Left of the last column of refRanges- refRanges?.forEach(({ row, column, range }) => {- if (!range) return;-- const { endColumn: refRangeEndColumn } = range;- if (endColumn <= refRangeEndColumn) {- // The formula cell position corresponding to refRange- const removeRange = formulaRangeMatrix?.getValue(row, column);- removeRange && removeValueFormulaArray(removeRange, formulaMatrix);- }- });-}diff --git a/packages/sheets-formula/src/controllers/utils/redo-undo-formula-data.ts b/packages/sheets-formula/src/controllers/utils/redo-undo-formula-data.tsdeleted file mode 100644index 6519253ec2..0000000000--- a/packages/sheets-formula/src/controllers/utils/redo-undo-formula-data.ts+++ /dev/null@@ -1,146 +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, ICommandInfo, IMutationCommonParams, Nullable } from '@univerjs/core';-import { isFormulaId, isFormulaString, ObjectMatrix, UndoCommand } from '@univerjs/core';-import type { IArrayFormulaRangeType, IArrayFormulaUnitCellType, IFormulaData } from '@univerjs/engine-formula';-import type { IMoveRangeMutationParams } from '@univerjs/sheets';--import { checkFormulaDataNull, moveRangeUpdateFormulaData } from './offset-formula-data';--export function handleRedoUndoMoveRange(- command: ICommandInfo<IMoveRangeMutationParams>,- formulaData: IFormulaData,- arrayFormulaRange: IArrayFormulaRangeType,- arrayFormulaCellData: IArrayFormulaUnitCellType-) {- const { params } = command;- if (!params) return;-- const { unitId } = params;- let { from, to } = params;-- if ((command.params as IMutationCommonParams).trigger === UndoCommand.id) {- from = params.to;- to = params.from;- }-- const { subUnitId: fromSubUnitId, value: fromValue } = from;- const { subUnitId: toSubUnitId, value: toValue } = to;-- if (- checkFormulaDataNull(formulaData, unitId, fromSubUnitId) ||- checkFormulaDataNull(formulaData, unitId, toSubUnitId) ||- checkFormulaDataNull(arrayFormulaRange, unitId, fromSubUnitId) ||- checkFormulaDataNull(arrayFormulaRange, unitId, toSubUnitId) ||- checkFormulaDataNull(arrayFormulaCellData, unitId, fromSubUnitId) ||- checkFormulaDataNull(arrayFormulaCellData, unitId, toSubUnitId)- ) {- return;- }-- const fromValueMatrix = new ObjectMatrix(fromValue);- const toValueMatrix = new ObjectMatrix(toValue);-- setFormulaData(fromValueMatrix, formulaData, unitId, fromSubUnitId);- setFormulaData(toValueMatrix, formulaData, unitId, toSubUnitId);- setArrayFormulaData(- fromValueMatrix,- toValueMatrix,- arrayFormulaRange,- arrayFormulaCellData,- unitId,- fromSubUnitId,- toSubUnitId- );-}--function setFormulaData(- valueMatrix: ObjectMatrix<Nullable<ICellData>>,- formulaData: IFormulaData,- unitId: string,- subUnitId: string-) {- if (!formulaData[unitId]) {- formulaData[unitId] = {};- }-- valueMatrix.forValue((r, c, newVal) => {- if (!formulaData[unitId]![subUnitId][r]) {- formulaData[unitId]![subUnitId][r] = {};- }-- if (!newVal) {- delete formulaData[unitId]![subUnitId][r][c];- return;- }-- const formulaString = newVal?.f || '';- const formulaId = newVal?.si || '';-- const checkFormulaString = isFormulaString(formulaString);- const checkFormulaId = isFormulaId(formulaId);-- if (checkFormulaString && checkFormulaId) {- formulaData[unitId]![subUnitId][r][c] = {- f: formulaString,- si: formulaId,- };- } else if (checkFormulaString && !checkFormulaId) {- formulaData[unitId]![subUnitId][r][c] = {- f: formulaString,- };- } else if (!checkFormulaString && checkFormulaId) {- formulaData[unitId]![subUnitId][r][c] = {- f: '',- si: formulaId,- };- } else if (!checkFormulaString && !checkFormulaId) {- delete formulaData[unitId]![subUnitId][r][c];- }- });-}--function setArrayFormulaData(- fromValueMatrix: ObjectMatrix<Nullable<ICellData>>,- toValueMatrix: ObjectMatrix<Nullable<ICellData>>,- arrayFormulaRange: IArrayFormulaRangeType,- arrayFormulaCellData: IArrayFormulaUnitCellType,- unitId: string,- fromSubUnitId: string,- toSubUnitId: string-) {- const fromArrayFormulaCellDataMatrix = new ObjectMatrix(arrayFormulaCellData?.[unitId]?.[fromSubUnitId] ?? {});- const toArrayFormulaCellDataMatrix = new ObjectMatrix(arrayFormulaCellData?.[unitId]?.[toSubUnitId] ?? {});- const fromArrayFormulaRangeMatrix = new ObjectMatrix(arrayFormulaRange?.[unitId]?.[fromSubUnitId] ?? {});- const toArrayFormulaRangeMatrix = new ObjectMatrix(arrayFormulaRange?.[unitId]?.[toSubUnitId] ?? {});-- // We need set toValueMatrix value to fromValueMatrix value- const fromRange = fromValueMatrix.getDataRange();- const toRange = toValueMatrix.getDataRange();-- // update arrayFormulaCellData- moveRangeUpdateFormulaData(- fromRange,- toRange,- fromArrayFormulaCellDataMatrix,- toArrayFormulaCellDataMatrix,- fromArrayFormulaRangeMatrix- );-- // update arrayFormulaRange- moveRangeUpdateFormulaData(fromRange, toRange, fromArrayFormulaRangeMatrix, toArrayFormulaRangeMatrix);-}diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.tsindex 23990aba40..e39904cf6e 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts@@ -77,12 +77,15 @@ export function getFormulaReferenceSheet(oldFormulaData: IFormulaData,}Object.keys(newSheetData).forEach((subUnitId) => {- const newSheetFormula = new ObjectMatrix(newSheetData[subUnitId]);- const oldSheetFormula = new ObjectMatrix(oldSheetData[subUnitId]);- const redoFormulaMatrix = new ObjectMatrix<ICellData>();- const undoFormulaMatrix = new ObjectMatrix<ICellData>();+ 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) {@@ -201,13 +204,17 @@ export function refRangeFormula(oldFormulaData: IFormulaData,const currentOldFormulaData = oldFormulaData[unitId]![sheetId];const currentNewFormulaData = newFormulaData[unitId]![sheetId];- const oldFormulaMatrix = new ObjectMatrix(currentOldFormulaData);- const newFormulaMatrix = new ObjectMatrix(currentNewFormulaData);+ const oldFormulaMatrix = new ObjectMatrix(currentOldFormulaData || {});+ const newFormulaMatrix = new ObjectMatrix(currentNewFormulaData || {});// 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[] = [];let isReverse = false;oldFormulaMatrix.forValue((row, column, cell) => {+ if (cell == null) {+ return true;+ }+// Offset is only needed when there is a formulaif (!isFormulaDataItem(cell)) {return;@@ -439,8 +446,8 @@ function handleRefInsertMoveRight(range: IRange, oldCell: IRange) {* @param oldFormulaData* @param newFormulaData*/-function getRedoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMatrix<IFormulaDataItem>, newFormulaMatrix: ObjectMatrix<IFormulaDataItem>) {- const redoFormulaData = new ObjectMatrix<ICellData | null>({});+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;@@ -464,8 +471,8 @@ function getRedoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectM* @param oldFormulaData* @param newFormulaData*/-function getUndoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMatrix<IFormulaDataItem>) {- const undoFormulaData = new ObjectMatrix<ICellData | null>({});+function getUndoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMatrix<Nullable<IFormulaDataItem>>) {+ const undoFormulaData = new ObjectMatrix<Nullable<ICellData>>({});rangeList.forEach((item) => {const { oldCell, newCell } = item;@@ -497,7 +504,10 @@ function getUndoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectM* │ =SUM(1) │ id1 │ 0 │ 1 │ │ id1 │* └──────────────────┴─────┴───┴───┴───────────┴─────┘*/-export function formulaDataItemToCellData(formulaDataItem: IFormulaDataItem): ICellData | null {+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);