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.

fix(formula): fix table formula references (#6946)

wpxp123456e25270722000
diff --git a/packages/core/src/shared/tools.ts b/packages/core/src/shared/tools.ts
index 70ebb7d930..c26f33c30c 100644
--- a/packages/core/src/shared/tools.ts
+++ b/packages/core/src/shared/tools.ts
@@ -540,7 +540,15 @@ export const isNodeEnv = () => {
* @returns {RegExp} The generated regular expression
*/
export function createREGEXFromWildChar(wildChar: string): RegExp {
- const escaped = wildChar.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const escaped = escapeRegExp(wildChar);
const regexpStr = escaped.replace(/\\\*/g, '.*').replace(/\\\?/g, '.');
return new RegExp(`^${regexpStr}$`, 'i');
}
+
+/**
+ * Escapes characters that have special meaning in a regular expression so the
+ * returned string can be safely embedded in a RegExp pattern as literal text.
+ */
+export function escapeRegExp(str: string): string {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index a86d5a097b..7cc0fd8454 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -100,8 +100,12 @@ export interface IDirtyUnitSheetNameMap {
[unitId: string]: Nullable<{ [sheetId: string]: string }>;
}
-export interface IDirtyUnitSheetDefinedNameMap {
- [unitId: string]: Nullable<{ [name: string]: string }>;
+export interface IDirtyUnitDefinedNameMap {
+ [unitId: string]: Nullable<{ [definedName: string]: string }>;
+}
+
+export interface IDirtyUnitSuperTableMap {
+ [unitId: string]: Nullable<{ [tableName: string]: string }>;
}
export interface IDirtyUnitFeatureMap {
@@ -215,7 +219,8 @@ export interface IFormulaDatasetConfig {
forceCalculate: boolean;
dirtyRanges: IUnitRange[];
dirtyNameMap: IDirtyUnitSheetNameMap;
- dirtyDefinedNameMap: IDirtyUnitSheetNameMap;
+ dirtyDefinedNameMap: IDirtyUnitDefinedNameMap;
+ dirtySuperTableMap?: IDirtyUnitSuperTableMap;
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap;
clearDependencyTreeCache?: IUnitSheetIdToNameMap;
diff --git a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
index 6f6b288cee..e4224b3a7a 100644
--- a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts
@@ -27,6 +27,7 @@ export interface ISetSuperTableMutationSearchParam {
}
export interface ISetSuperTableMutationParam extends ISetSuperTableMutationSearchParam {
+ oldTableName?: string;
reference: ISuperTable;
}
/**
diff --git a/packages/engine-formula/src/controllers/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.ts
index 8b0e563705..b5f0dc8e88 100644
--- a/packages/engine-formula/src/controllers/calculate.controller.ts
+++ b/packages/engine-formula/src/controllers/calculate.controller.ts
@@ -98,7 +98,7 @@ export class CalculateController extends Disposable {
private async _calculate(
formulaDirtyData: Partial<IFormulaDirtyData>
) {
- const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {}, maxIteration = DEFAULT_CYCLE_REFERENCE_COUNT, rowData, isCalculateTreeModel = false } = formulaDirtyData;
+ const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtySuperTableMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {}, maxIteration = DEFAULT_CYCLE_REFERENCE_COUNT, rowData, isCalculateTreeModel = false } = formulaDirtyData;
const formulaData = this._formulaDataModel.getFormulaData();
const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();
@@ -113,6 +113,7 @@ export class CalculateController extends Disposable {
dirtyRanges,
dirtyNameMap,
dirtyDefinedNameMap,
+ dirtySuperTableMap,
dirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap,
clearDependencyTreeCache,
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 a725a842d4..c9d852945c 100644
--- a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
@@ -15,7 +15,7 @@
*/
import type { IRange, Nullable } from '@univerjs/core';
-import type { IDirtyUnitSheetDefinedNameMap, IExprTreeNode, ISuperTable } from '../../basics/common';
+import type { IDirtyUnitDefinedNameMap, IExprTreeNode, ISuperTable } from '../../basics/common';
import type { IFunctionNames } from '../../basics/function';
import type { IDefinedNamesServiceParam } from '../../services/defined-names.service';
@@ -78,7 +78,7 @@ export const FormulaSequenceNodeCache = new FormulaAstLRU<Array<string | ISequen
interface IInjectDefinedNameParam {
unitId: Nullable<string>;
getValueByName(unitId: string, name: string): Nullable<IDefinedNamesServiceParam>;
- getDirtyDefinedNameMap(): IDirtyUnitSheetDefinedNameMap;
+ getDirtyDefinedNameMap(): IDirtyUnitDefinedNameMap;
getSheetName: (unitId: string, sheetId: string) => string;
}
diff --git a/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts
index ea7148d749..f4ab96fefe 100644
--- a/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts
+++ b/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts
@@ -22,7 +22,10 @@ describe('generateAstNode defined name cache invalidation', () => {
FORMULA_AST_CACHE.clear();
});
- function createHarness(dirtyDefinedNameMap: Record<string, Record<string, string>>) {
+ function createHarness(
+ dirtyDefinedNameMap: Record<string, Record<string, string>>,
+ dirtySuperTableMap: Record<string, Record<string, string>> = {}
+ ) {
let parseCount = 0;
const node = {
hasDefinedName: () => false,
@@ -39,6 +42,7 @@ describe('generateAstNode defined name cache invalidation', () => {
};
const currentConfigService = {
getDirtyDefinedNameMap: () => dirtyDefinedNameMap,
+ getDirtySuperTableMap: () => dirtySuperTableMap,
getExecuteUnitId: () => 'unit-1',
};
@@ -149,4 +153,54 @@ describe('generateAstNode defined name cache invalidation', () => {
expect(harness.getParseCount()).toBe(1);
});
+
+ it('does not reuse cache when formula references a dirty super table in the same unit', () => {
+ const harness = createHarness({}, {
+ 'unit-1': {
+ Table1: '1',
+ },
+ });
+
+ generateAstNode(
+ 'unit-1',
+ '=SUM(Table1[col1])',
+ harness.lexer as never,
+ harness.astTreeBuilder as never,
+ harness.currentConfigService as never
+ );
+ generateAstNode(
+ 'unit-1',
+ '=SUM(Table1[col1])',
+ harness.lexer as never,
+ harness.astTreeBuilder as never,
+ harness.currentConfigService as never
+ );
+
+ expect(harness.getParseCount()).toBe(2);
+ });
+
+ it('reuses cache when formula references a dirty super table in another unit', () => {
+ const harness = createHarness({}, {
+ 'unit-2': {
+ Table1: '1',
+ },
+ });
+
+ generateAstNode(
+ 'unit-1',
+ '=SUM(Table1[col1])',
+ harness.lexer as never,
+ harness.astTreeBuilder as never,
+ harness.currentConfigService as never
+ );
+ generateAstNode(
+ 'unit-1',
+ '=SUM(Table1[col1])',
+ harness.lexer as never,
+ harness.astTreeBuilder as never,
+ harness.currentConfigService as never
+ );
+
+ expect(harness.getParseCount()).toBe(1);
+ });
});
diff --git a/packages/engine-formula/src/engine/utils/compare.ts b/packages/engine-formula/src/engine/utils/compare.ts
index 5e73d8aac9..37159413fe 100644
--- a/packages/engine-formula/src/engine/utils/compare.ts
+++ b/packages/engine-formula/src/engine/utils/compare.ts
@@ -48,7 +48,7 @@ export function isWildcard(str: string) {
}
export function isMatchWildcard(currentValue: string, value: string) {
- const pattern = escapeRegExp(value).replace(/~?[*?]/g, (match) => {
+ const pattern = escapeRegExpForWildcard(value).replace(/~?[*?]/g, (match) => {
if (match.startsWith('~')) {
return `\\${match.substring(1)}`;
}
@@ -101,7 +101,8 @@ export function compareWithWildcard(currentValue: string, value: string, operato
return result;
}
-export function escapeRegExp(str: string) {
+function escapeRegExpForWildcard(str: string) {
+ // Keep * and ? unescaped so wildcard replacement can handle them below.
return str.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
diff --git a/packages/engine-formula/src/engine/utils/generate-ast-node.ts b/packages/engine-formula/src/engine/utils/generate-ast-node.ts
index 60c51a3315..e473625200 100644
--- a/packages/engine-formula/src/engine/utils/generate-ast-node.ts
+++ b/packages/engine-formula/src/engine/utils/generate-ast-node.ts
@@ -23,6 +23,7 @@ import type { AstTreeBuilder } from '../analysis/parser';
import type { AstRootNode } from '../ast-node/ast-root-node';
import type { BaseAstNode } from '../ast-node/base-ast-node';
import type { IFormulaDependencyTree } from '../dependency/dependency-tree';
+import { escapeRegExp } from '@univerjs/core';
import { FormulaAstLRU } from '../../basics/cache-lru';
import { ERROR_TYPE_SET } from '../../basics/error-type';
import { ErrorNode } from '../ast-node/base-ast-node';
@@ -31,11 +32,16 @@ const FORMULA_CACHE_LRU_COUNT = 5000;
export const FORMULA_AST_CACHE = new FormulaAstLRU<AstRootNode>(FORMULA_CACHE_LRU_COUNT);
+type IDirtyStringMap = Record<string, string>;
+
+const DIRTY_DEFINED_NAME_SET_CACHE = new WeakMap<IDirtyStringMap, Set<string>>();
+const DIRTY_SUPER_TABLE_PATTERN_CACHE = new WeakMap<IDirtyStringMap, RegExp | null>();
+
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}`);
- const noCache = checkIsChangedByDefinedName(unitId, formulaString, currentConfigService);
+ const noCache = checkIsChangedByDefinedName(unitId, formulaString, currentConfigService) || checkIsChangedBySuperTable(unitId, formulaString, currentConfigService);
if (!noCache && astNode && !isDirtyDefinedForNode(astNode, currentConfigService)) {
// astNode.setRefOffset(refOffsetX, refOffsetY);
@@ -75,22 +81,53 @@ function checkIsChangedByDefinedName(unitId: string, formula: string, currentCon
return false;
}
- const formulaText = normalizeFormulaText(formula);
- const names = Object.keys(unitDefinedNameMap);
- for (let i = 0, len = names.length; i < len; i++) {
- // Dirty defined-name entries use the changed formula text as the key.
- if (normalizeFormulaText(names[i]) === formulaText) {
- return true;
- }
- }
-
- return false;
+ // Dirty defined-name entries use the changed formula text as the key.
+ return getNormalizedDirtyDefinedNameSet(unitDefinedNameMap).has(normalizeFormulaText(formula));
}
function normalizeFormulaText(formula: string): string {
return formula.startsWith('=') ? formula.slice(1) : formula;
}
+function checkIsChangedBySuperTable(unitId: string, formula: string, currentConfigService: IFormulaCurrentConfigService): boolean {
+ const getDirtySuperTableMap = currentConfigService.getDirtySuperTableMap?.bind(currentConfigService);
+ const changedSuperTableMap = getDirtySuperTableMap?.();
+ const unitSuperTableMap = changedSuperTableMap?.[unitId];
+
+ if (unitSuperTableMap == null) {
+ return false;
+ }
+
+ const tableReferencePattern = getDirtySuperTableReferencePattern(unitSuperTableMap);
+ return tableReferencePattern?.test(normalizeFormulaText(formula)) ?? false;
+}
+
+function getNormalizedDirtyDefinedNameSet(unitDefinedNameMap: IDirtyStringMap): Set<string> {
+ let normalizedNameSet = DIRTY_DEFINED_NAME_SET_CACHE.get(unitDefinedNameMap);
+ if (normalizedNameSet == null) {
+ normalizedNameSet = new Set(Object.keys(unitDefinedNameMap).map(normalizeFormulaText));
+ DIRTY_DEFINED_NAME_SET_CACHE.set(unitDefinedNameMap, normalizedNameSet);
+ }
+
+ return normalizedNameSet;
+}
+
+function getDirtySuperTableReferencePattern(unitSuperTableMap: IDirtyStringMap): RegExp | null {
+ let tableReferencePattern = DIRTY_SUPER_TABLE_PATTERN_CACHE.get(unitSuperTableMap);
+ if (tableReferencePattern === undefined) {
+ const escapedTableNames = Object.keys(unitSuperTableMap)
+ .filter((tableName) => tableName.length > 0)
+ .map(escapeRegExp);
+
+ tableReferencePattern = escapedTableNames.length > 0
+ ? new RegExp(`(^|[^A-Za-z0-9_])(?:${escapedTableNames.join('|')})(\\s*\\[|$|[^A-Za-z0-9_])`, 'i')
+ : null;
+ DIRTY_SUPER_TABLE_PATTERN_CACHE.set(unitSuperTableMap, tableReferencePattern);
+ }
+
+ return tableReferencePattern;
+}
+
function isDirtyDefinedForNode(node: BaseAstNode, currentConfigService: IFormulaCurrentConfigService) {
const definedNameMap = currentConfigService.getDirtyDefinedNameMap();
const executeUnitId = currentConfigService.getExecuteUnitId();
diff --git a/packages/engine-formula/src/functions/text/textsplit/index.ts b/packages/engine-formula/src/functions/text/textsplit/index.ts
index cf92d2a588..44fd69dc4b 100644
--- a/packages/engine-formula/src/functions/text/textsplit/index.ts
+++ b/packages/engine-formula/src/functions/text/textsplit/index.ts
@@ -15,6 +15,7 @@
*/
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { escapeRegExp } from '@univerjs/core';
import { ErrorType } from '../../../basics/error-type';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
import { ArrayValueObject } from '../../../engine/value-object/array-value-object';
@@ -261,10 +262,6 @@ export class Textsplit extends BaseFunction {
value += '';
- return this._escapeRegExp(value);
- }
-
- private _escapeRegExp(string: string): string {
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return escapeRegExp(value);
}
}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 7b071c3e13..c98d2b5dac 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -18,10 +18,11 @@ export type {
IArrayFormulaEmbeddedMap,
IArrayFormulaRangeType,
IArrayFormulaUnitCellType,
+ IDirtyUnitDefinedNameMap,
IDirtyUnitFeatureMap,
IDirtyUnitOtherFormulaMap,
- IDirtyUnitSheetDefinedNameMap,
IDirtyUnitSheetNameMap,
+ IDirtyUnitSuperTableMap,
IFeatureDirtyRangeType,
IFormulaData,
IFormulaDataItem,
diff --git a/packages/engine-formula/src/services/active-dirty-manager.service.ts b/packages/engine-formula/src/services/active-dirty-manager.service.ts
index 29cd49ea7a..6f7bb63788 100644
--- a/packages/engine-formula/src/services/active-dirty-manager.service.ts
+++ b/packages/engine-formula/src/services/active-dirty-manager.service.ts
@@ -15,7 +15,7 @@
*/
import type { ICommandInfo, IUnitRange, Nullable } from '@univerjs/core';
-import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetDefinedNameMap, IDirtyUnitSheetNameMap } from '../basics/common';
+import type { IDirtyUnitDefinedNameMap, IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IDirtyUnitSuperTableMap } from '../basics/common';
import { createIdentifier, Disposable } from '@univerjs/core';
export interface IDirtyConversionManagerParams {
@@ -24,7 +24,8 @@ export interface IDirtyConversionManagerParams {
forceCalculation?: boolean;
dirtyRanges?: IUnitRange[];
dirtyNameMap?: IDirtyUnitSheetNameMap;
- dirtyDefinedNameMap?: IDirtyUnitSheetDefinedNameMap;
+ dirtyDefinedNameMap?: IDirtyUnitDefinedNameMap;
+ dirtySuperTableMap?: IDirtyUnitSuperTableMap;
dirtyUnitFeatureMap?: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap?: IDirtyUnitOtherFormulaMap;
clearDependencyTreeCache?: IDirtyUnitSheetNameMap;
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index aa19178409..1f756167df 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -17,10 +17,11 @@
import type { IUnitRange, LocaleType, Nullable, Workbook } from '@univerjs/core';
import type {
IArrayFormulaRangeType,
+ IDirtyUnitDefinedNameMap,
IDirtyUnitFeatureMap,
IDirtyUnitOtherFormulaMap,
- IDirtyUnitSheetDefinedNameMap,
IDirtyUnitSheetNameMap,
+ IDirtyUnitSuperTableMap,
IFormulaData,
IFormulaDatasetConfig,
IRuntimeUnitDataType,
@@ -41,7 +42,8 @@ export interface IFormulaDirtyData {
forceCalculation: boolean;
dirtyRanges: IUnitRange[];
dirtyNameMap: IDirtyUnitSheetNameMap;
- dirtyDefinedNameMap: IDirtyUnitSheetDefinedNameMap;
+ dirtyDefinedNameMap: IDirtyUnitDefinedNameMap;
+ dirtySuperTableMap?: IDirtyUnitSuperTableMap;
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap;
clearDependencyTreeCache: IDirtyUnitSheetNameMap; // unitId -> sheetId
@@ -70,7 +72,9 @@ export interface IFormulaCurrentConfigService {
getDirtyNameMap(): IDirtyUnitSheetNameMap;
- getDirtyDefinedNameMap(): IDirtyUnitSheetDefinedNameMap;
+ getDirtyDefinedNameMap(): IDirtyUnitDefinedNameMap;
+
+ getDirtySuperTableMap(): IDirtyUnitSuperTableMap;
getDirtyUnitFeatureMap(): IDirtyUnitFeatureMap;
@@ -139,7 +143,9 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _dirtyNameMap: IDirtyUnitSheetNameMap = {};
- private _dirtyDefinedNameMap: IDirtyUnitSheetDefinedNameMap = {};
+ private _dirtyDefinedNameMap: IDirtyUnitDefinedNameMap = {};
+
+ private _dirtySuperTableMap: IDirtyUnitSuperTableMap = {};
private _dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
@@ -173,6 +179,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._dirtyRanges = [];
this._dirtyNameMap = {};
this._dirtyDefinedNameMap = {};
+ this._dirtySuperTableMap = {};
this._dirtyUnitFeatureMap = {};
this._dirtyUnitOtherFormulaMap = {};
this._excludedCell = {};
@@ -239,6 +246,10 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return this._dirtyDefinedNameMap;
}
+ getDirtySuperTableMap() {
+ return this._dirtySuperTableMap;
+ }
+
getDirtyUnitFeatureMap() {
return this._dirtyUnitFeatureMap;
}
@@ -339,6 +350,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._dirtyDefinedNameMap = config.dirtyDefinedNameMap;
+ this._dirtySuperTableMap = config.dirtySuperTableMap || {};
+
this._dirtyUnitFeatureMap = config.dirtyUnitFeatureMap;
this._dirtyUnitOtherFormulaMap = config.dirtyUnitOtherFormulaMap;
@@ -371,6 +384,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
dirtyRanges: this._dirtyRanges,
dirtyNameMap: this._dirtyNameMap,
dirtyDefinedNameMap: this._dirtyDefinedNameMap,
+ dirtySuperTableMap: this._dirtySuperTableMap,
dirtyUnitFeatureMap: this._dirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap: this._dirtyUnitOtherFormulaMap,
clearDependencyTreeCache: this._clearDependencyTreeCache,
diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
index f0fc085f1d..41a2a5cf83 100644
--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
@@ -33,6 +33,7 @@ import {
CommandType,
Disposable,
EDITOR_ACTIVATED,
+ escapeRegExp,
fromCallback,
groupBy,
ICommandService,
@@ -957,10 +958,6 @@ export class SheetFindModel extends FindModel {
}
}
-function escapeRegExp(text: string) {
- return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-}
-
/**
* This module is responsible for searching and replacing in the sheets.
* It also adds the search results to the search view by highlighting them.
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts
new file mode 100644
index 0000000000..5fe6c6b3ee
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts
@@ -0,0 +1,33 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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 { FunctionType, sequenceNodeType } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { getFormulaReplaceResult } from '../use-formula-search';
+
+describe('getFormulaReplaceResult', () => {
+ it('does not append an open bracket when replacing table names', () => {
+ expect(getFormulaReplaceResult(
+ [{ nodeType: sequenceNodeType.FUNCTION, token: 'Ord', startIndex: 0, endIndex: 2 }],
+ 0,
+ 'Orders',
+ FunctionType.Table
+ )).toEqual({
+ text: 'Orders',
+ offset: -3,
+ });
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
index 28802e1f4d..74f37ad92e 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
@@ -26,6 +26,26 @@ import { findIndexFromSequenceNodes } from '../../range-selector/utils/find-inde
import { sequenceNodeToText } from '../../range-selector/utils/sequence-node-to-text';
import { useStateRef } from './use-state-ref';
+function shouldAppendOpenBracket(functionType: FunctionType): boolean {
+ return functionType !== FunctionType.DefinedName && functionType !== FunctionType.Table;
+}
+
+export function getFormulaReplaceResult(nodes: INode[], index: number, formulaName: string, functionType: FunctionType) {
+ const cloneNodes = [...nodes];
+ if (index !== -1) {
+ const lastNodes = cloneNodes.splice(index + 1);
+ const oldNode = cloneNodes.pop() || '';
+ let offset = (typeof oldNode === 'string' ? oldNode.length : oldNode.token.length) - formulaName.length;
+ cloneNodes.push(formulaName);
+ if (lastNodes[0] !== matchToken.OPEN_BRACKET && shouldAppendOpenBracket(functionType)) {
+ cloneNodes.push(matchToken.OPEN_BRACKET);
+ offset--;
+ }
+ const text = sequenceNodeToText([...cloneNodes, ...lastNodes]);
+ return { text, offset };
+ }
+}
+
export const useFormulaSearch = (isNeed: boolean, nodes: INode[] = [], editor?: Editor) => {
const descriptionService = useDependency(IDescriptionService);
@@ -85,19 +105,7 @@ export const useFormulaSearch = (isNeed: boolean, nodes: INode[] = [], editor?:
}, [isNeed]);
const handlerFormulaReplace = (formulaName: string, functionType: FunctionType) => {
- const cloneNodes = [...stateRef.current.nodes];
- if (indexRef.current !== -1) {
- const lastNodes = cloneNodes.splice(indexRef.current + 1);
- const oldNode = cloneNodes.pop() || '';
- let offset = (typeof oldNode === 'string' ? oldNode.length : oldNode.token.length) - formulaName.length;
- cloneNodes.push(formulaName);
- if (lastNodes[0] !== matchToken.OPEN_BRACKET && functionType !== FunctionType.DefinedName) {
- cloneNodes.push(matchToken.OPEN_BRACKET);
- offset--;
- }
- const text = sequenceNodeToText([...cloneNodes, ...lastNodes]);
- return { text, offset };
- }
+ return getFormulaReplaceResult(stateRef.current.nodes, indexRef.current, formulaName, functionType);
};
return {
searchList,
diff --git a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
index b11305b4d8..bb1f3d363b 100644
--- a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
@@ -25,6 +25,7 @@ import {
IActiveDirtyManagerService,
RemoveDefinedNameMutation,
SetDefinedNameMutation,
+ SetSuperTableMutation,
SetTriggerFormulaCalculationStartMutation,
} from '@univerjs/engine-formula';
import {
@@ -408,4 +409,53 @@ describe('ActiveDirtyController', () => {
},
});
});
+
+ it('should dirty the table range and clear dependency cache when a super table changes', () => {
+ testBed = createControllerTestBed();
+ testBed.injector.get(ActiveDirtyController);
+
+ expect(getDirtyData(testBed, {
+ id: SetSuperTableMutation.id,
+ params: {
+ unitId: 'test',
+ tableName: 'Table1',
+ reference: {
+ sheetId: 'sheet1',
+ range: {
+ startRow: 0,
+ startColumn: 1,
+ endRow: 5,
+ endColumn: 2,
+ },
+ titleMap: new Map([
+ ['Column1', 0],
+ ['Column3', 1],
+ ]),
+ },
+ },
+ } as ICommandInfo)).toEqual({
+ dirtyRanges: [
+ {
+ unitId: 'test',
+ sheetId: 'sheet1',
+ range: {
+ startRow: 0,
+ startColumn: 1,
+ endRow: 5,
+ endColumn: 2,
+ },
+ },
+ ],
+ dirtySuperTableMap: {
+ test: {
+ Table1: '1',
+ },
+ },
+ clearDependencyTreeCache: {
+ test: {
+ sheet1: '1',
+ },
+ },
+ });
+ });
});
diff --git a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
index c3eed4cd35..4b241a9319 100644
--- a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
@@ -185,7 +185,7 @@ describe('TriggerCalculationController', () => {
{ unitId: 'test', sheetId: 'sheet1', range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 } },
],
dirtyNameMap: { test: { sheet1: '1' } },
- dirtyDefinedNameMap: { test: { sheet1: '1' } },
+ dirtyDefinedNameMap: { test: { definedNameA: '1' } },
dirtyUnitFeatureMap: { test: { sheet1: { featureA: true } } },
dirtyUnitOtherFormulaMap: { test: { sheet1: { formulaA: true } } },
clearDependencyTreeCache: { test: { sheet1: '1' } },
@@ -229,7 +229,7 @@ describe('TriggerCalculationController', () => {
{ unitId: 'test', sheetId: 'sheet1', range: { startRow: 2, startColumn: 0, endRow: 3, endColumn: 1 } },
],
dirtyNameMap: { test: { sheet1: '1' } },
- dirtyDefinedNameMap: { test: { sheet1: '1' } },
+ dirtyDefinedNameMap: { test: { definedNameA: '1' } },
dirtyUnitFeatureMap: { test: { sheet1: { featureA: true, featureB: false } } },
dirtyUnitOtherFormulaMap: { test: { sheet1: { formulaA: true } } },
clearDependencyTreeCache: { test: { sheet1: '1' } },
diff --git a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
index abefb80cb0..25192272a9 100644
--- a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts
@@ -15,11 +15,18 @@
*/
import type { Dependency, ICellData, IWorkbookData, Nullable, Workbook } from '@univerjs/core';
-import { CellValueType, ICommandService, IConfigService, IUniverInstanceService, LocaleType, UniverInstanceType } from '@univerjs/core';
-import { FormulaDataModel, SetArrayFormulaDataMutation, SetFormulaDataMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';
-import { InsertSheetMutation, MoveRangeCommand, MoveRangeMutation, RemoveSheetCommand, RemoveSheetMutation, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetStyleCommand, SetWorksheetNameCommand, SheetInterceptorService } from '@univerjs/sheets';
+import { CellValueType, ICommandService, IConfigService, IUniverInstanceService, LocaleType, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';
+import {
+ FormulaDataModel,
+ IDefinedNamesService,
+ RemoveDefinedNameMutation,
+ SetArrayFormulaDataMutation,
+ SetDefinedNameMutation,
+ SetFormulaDataMutation,
+ SetTriggerFormulaCalculationStartMutation,
+} from '@univerjs/engine-formula';
+import { InsertSheetMutation, MoveRangeCommand, MoveRangeMutation, RemoveDefinedNameCommand, RemoveSheetCommand, RemoveSheetMutation, SetDefinedNameCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetStyleCommand, SetWorksheetNameCommand, SheetInterceptorService } from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../../config/config';
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
import { UpdateFormulaController } from '../update-formula.controller';
@@ -50,6 +57,10 @@ function createWorkbookData(): IWorkbookData {
2: { f: '=SUM(A1:B2)' },
3: { v: 1, t: CellValueType.NUMBER },
},
+ 6: {
+ 0: { f: '=SUM(RANGE_NAME)' },
+ 1: { f: '=RANGE_NAME' },
+ },
},
},
sheet2: {
@@ -62,6 +73,10 @@ function createWorkbookData(): IWorkbookData {
0: { f: '=Sheet1!A1:B2' },
1: { f: '=RANGE_NAME' },
},
+ 1: {
+ 0: { f: '=RANGE_NAME' },
+ 1: { f: '=RANGE_NAME+SUM(RANGE_NAME)' },
+ },
},
},
},
@@ -70,7 +85,9 @@ function createWorkbookData(): IWorkbookData {
}
function createControllerTestBed() {
- const dependencies: Dependency[] = [[UpdateFormulaController]];
+ const dependencies: Dependency[] = [
+ [UpdateFormulaController],
+ ];
return createFacadeTestBed(createWorkbookData(), dependencies);
}
@@ -79,11 +96,13 @@ describe('UpdateFormulaController', () => {
let testBed: ReturnType<typeof createControllerTestBed>;
let commandService: ICommandService;
let formulaDataModel: FormulaDataModel;
+ let definedNamesService: IDefinedNamesService;
beforeEach(() => {
testBed = createControllerTestBed();
commandService = testBed.injector.get(ICommandService);
formulaDataModel = testBed.injector.get(FormulaDataModel);
+ definedNamesService = testBed.injector.get(IDefinedNamesService);
commandService.registerCommand(MoveRangeCommand);
commandService.registerCommand(MoveRangeMutation);
@@ -92,9 +111,21 @@ describe('UpdateFormulaController', () => {
commandService.registerCommand(SetSelectionsOperation);
commandService.registerCommand(SetRangeValuesCommand);
commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetDefinedNameCommand);
+ commandService.registerCommand(RemoveDefinedNameCommand);
+ commandService.registerCommand(SetDefinedNameMutation);
+ commandService.registerCommand(RemoveDefinedNameMutation);
commandService.registerCommand(SetFormulaDataMutation);
commandService.registerCommand(SetArrayFormulaDataMutation);
+ definedNamesService.registerDefinedName('test', {
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ comment: '',
+ });
+
testBed.injector.get(UpdateFormulaController);
});
@@ -224,6 +255,424 @@ describe('UpdateFormulaController', () => {
]));
});
+ it('should sync defined-name formulas when a defined name is renamed, undone, and redone', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet2?.[0]?.[1]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(0, 1, 0, 1)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RENAMED_RANGE',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getFormula()).toBe('=RENAMED_RANGE');
+ expect(getCellFormula()).toBe('=RENAMED_RANGE');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=RANGE_NAME');
+ expect(getCellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=RENAMED_RANGE');
+ expect(getCellFormula()).toBe('=RENAMED_RANGE');
+ });
+
+ it('should sync defined-name formulas when a defined name is removed, undone, and redone', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet2?.[0]?.[1]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(0, 1, 0, 1)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(RemoveDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getFormula()).toBe('=#REF!');
+ expect(getCellFormula()).toBe('=#REF!');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=RANGE_NAME');
+ expect(getCellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=#REF!');
+ expect(getCellFormula()).toBe('=#REF!');
+ });
+
+ it('should keep defined-name formulas synchronized when the defined name range changes, then undo and redo', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet2?.[0]?.[1]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(0, 1, 0, 1)
+ .getValue()
+ ?.f;
+ const getDefinedNameRef = () => definedNamesService.getValueById('test', 'range-name')?.formulaOrRefString;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: '=SUM(Sheet1!$C$1:$C$2)',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getFormula()).toBe('=RANGE_NAME');
+ expect(getCellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');
+ expect(getFormula()).toBe('=RANGE_NAME');
+ expect(getCellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getFormula()).toBe('=RANGE_NAME');
+ expect(getCellFormula()).toBe('=RANGE_NAME');
+ });
+
+ it('should sync defined-name formulas wrapped by functions when renamed, undone, and redone', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet1?.[6]?.[0]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(6, 0, 6, 0)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RENAMED_RANGE',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getFormula()).toBe('=SUM(RENAMED_RANGE)');
+ expect(getCellFormula()).toBe('=SUM(RENAMED_RANGE)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=SUM(RENAMED_RANGE)');
+ expect(getCellFormula()).toBe('=SUM(RENAMED_RANGE)');
+ });
+
+ it('should sync defined-name formulas wrapped by functions when removed, undone, and redone', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet1?.[6]?.[0]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(6, 0, 6, 0)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(RemoveDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getFormula()).toBe('=SUM(#REF!)');
+ expect(getCellFormula()).toBe('=SUM(#REF!)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=SUM(#REF!)');
+ expect(getCellFormula()).toBe('=SUM(#REF!)');
+ });
+
+ it('should keep function-wrapped defined-name formulas synchronized when the defined name range changes, then undo and redo', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet1?.[6]?.[0]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(6, 0, 6, 0)
+ .getValue()
+ ?.f;
+ const getDefinedNameRef = () => definedNamesService.getValueById('test', 'range-name')?.formulaOrRefString;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: '=SUM(Sheet1!$C$1:$C$2)',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getFormula()).toBe('=SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');
+ expect(getFormula()).toBe('=SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getFormula()).toBe('=SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=SUM(RANGE_NAME)');
+ });
+
+ it('should sync multiple defined-name formulas across sheets when renamed, undone, and redone', async () => {
+ const getSheet1Formula = () => formulaDataModel.getFormulaData().test?.sheet1?.[6]?.[1]?.f;
+ const getSheet2Formula = () => formulaDataModel.getFormulaData().test?.sheet2?.[1]?.[0]?.f;
+ const getSheet1CellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(6, 1, 6, 1)
+ .getValue()
+ ?.f;
+ const getSheet2CellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(1, 0, 1, 0)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RENAMED_RANGE',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getSheet1Formula()).toBe('=RENAMED_RANGE');
+ expect(getSheet2Formula()).toBe('=RENAMED_RANGE');
+ expect(getSheet1CellFormula()).toBe('=RENAMED_RANGE');
+ expect(getSheet2CellFormula()).toBe('=RENAMED_RANGE');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getSheet1Formula()).toBe('=RANGE_NAME');
+ expect(getSheet2Formula()).toBe('=RANGE_NAME');
+ expect(getSheet1CellFormula()).toBe('=RANGE_NAME');
+ expect(getSheet2CellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getSheet1Formula()).toBe('=RENAMED_RANGE');
+ expect(getSheet2Formula()).toBe('=RENAMED_RANGE');
+ expect(getSheet1CellFormula()).toBe('=RENAMED_RANGE');
+ expect(getSheet2CellFormula()).toBe('=RENAMED_RANGE');
+ });
+
+ it('should sync multiple defined-name formulas across sheets when removed, undone, and redone', async () => {
+ const getSheet1Formula = () => formulaDataModel.getFormulaData().test?.sheet1?.[6]?.[1]?.f;
+ const getSheet2Formula = () => formulaDataModel.getFormulaData().test?.sheet2?.[1]?.[0]?.f;
+ const getSheet1CellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(6, 1, 6, 1)
+ .getValue()
+ ?.f;
+ const getSheet2CellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(1, 0, 1, 0)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(RemoveDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getSheet1Formula()).toBe('=#REF!');
+ expect(getSheet2Formula()).toBe('=#REF!');
+ expect(getSheet1CellFormula()).toBe('=#REF!');
+ expect(getSheet2CellFormula()).toBe('=#REF!');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getSheet1Formula()).toBe('=RANGE_NAME');
+ expect(getSheet2Formula()).toBe('=RANGE_NAME');
+ expect(getSheet1CellFormula()).toBe('=RANGE_NAME');
+ expect(getSheet2CellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getSheet1Formula()).toBe('=#REF!');
+ expect(getSheet2Formula()).toBe('=#REF!');
+ expect(getSheet1CellFormula()).toBe('=#REF!');
+ expect(getSheet2CellFormula()).toBe('=#REF!');
+ });
+
+ it('should keep multiple defined-name formulas across sheets synchronized when the defined name range changes, then undo and redo', async () => {
+ const getSheet1Formula = () => formulaDataModel.getFormulaData().test?.sheet1?.[6]?.[1]?.f;
+ const getSheet2Formula = () => formulaDataModel.getFormulaData().test?.sheet2?.[1]?.[0]?.f;
+ const getSheet1CellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(6, 1, 6, 1)
+ .getValue()
+ ?.f;
+ const getSheet2CellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(1, 0, 1, 0)
+ .getValue()
+ ?.f;
+ const getDefinedNameRef = () => definedNamesService.getValueById('test', 'range-name')?.formulaOrRefString;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: '=SUM(Sheet1!$C$1:$C$2)',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getSheet1Formula()).toBe('=RANGE_NAME');
+ expect(getSheet2Formula()).toBe('=RANGE_NAME');
+ expect(getSheet1CellFormula()).toBe('=RANGE_NAME');
+ expect(getSheet2CellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');
+ expect(getSheet1Formula()).toBe('=RANGE_NAME');
+ expect(getSheet2Formula()).toBe('=RANGE_NAME');
+ expect(getSheet1CellFormula()).toBe('=RANGE_NAME');
+ expect(getSheet2CellFormula()).toBe('=RANGE_NAME');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getSheet1Formula()).toBe('=RANGE_NAME');
+ expect(getSheet2Formula()).toBe('=RANGE_NAME');
+ expect(getSheet1CellFormula()).toBe('=RANGE_NAME');
+ expect(getSheet2CellFormula()).toBe('=RANGE_NAME');
+ });
+
+ it('should sync every occurrence of a defined name in one formula when renamed, undone, and redone', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet2?.[1]?.[1]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(1, 1, 1, 1)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RENAMED_RANGE',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getFormula()).toBe('=RENAMED_RANGE+SUM(RENAMED_RANGE)');
+ expect(getCellFormula()).toBe('=RENAMED_RANGE+SUM(RENAMED_RANGE)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=RENAMED_RANGE+SUM(RENAMED_RANGE)');
+ expect(getCellFormula()).toBe('=RENAMED_RANGE+SUM(RENAMED_RANGE)');
+ });
+
+ it('should sync every occurrence of a defined name in one formula when removed, undone, and redone', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet2?.[1]?.[1]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(1, 1, 1, 1)
+ .getValue()
+ ?.f;
+
+ expect(await commandService.executeCommand(RemoveDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: 'Sheet1!$A$1:$B$2',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getFormula()).toBe('=#REF!+SUM(#REF!)');
+ expect(getCellFormula()).toBe('=#REF!+SUM(#REF!)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula()).toBe('=#REF!+SUM(#REF!)');
+ expect(getCellFormula()).toBe('=#REF!+SUM(#REF!)');
+ });
+
+ it('should keep every occurrence of a defined name in one formula synchronized when the defined name range changes, then undo and redo', async () => {
+ const getFormula = () => formulaDataModel.getFormulaData().test?.sheet2?.[1]?.[1]?.f;
+ const getCellFormula = () => testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet2')
+ ?.getRange(1, 1, 1, 1)
+ .getValue()
+ ?.f;
+ const getDefinedNameRef = () => definedNamesService.getValueById('test', 'range-name')?.formulaOrRefString;
+
+ expect(await commandService.executeCommand(SetDefinedNameCommand.id, {
+ unitId: 'test',
+ id: 'range-name',
+ name: 'RANGE_NAME',
+ formulaOrRefString: '=SUM(Sheet1!$C$1:$C$2)',
+ localSheetId: 'AllDefaultWorkbook',
+ })).toBe(true);
+
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');
+ expect(getFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getDefinedNameRef()).toBe('=SUM(Sheet1!$C$1:$C$2)');
+ expect(getFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+ expect(getCellFormula()).toBe('=RANGE_NAME+SUM(RANGE_NAME)');
+ });
+
it('should sync formula data for value mutations and ignore style-only updates', async () => {
const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index 6aad13c65a..f7c7b606e2 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -15,7 +15,7 @@
*/
import type { ICellData, ICommandInfo, IObjectMatrixPrimitiveType, IRange, IUnitRange, Nullable } from '@univerjs/core';
-import type { IDirtyUnitSheetDefinedNameMap, IDirtyUnitSheetNameMap, IFormulaDirtyData, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
+import type { IDirtyUnitDefinedNameMap, IDirtyUnitSheetNameMap, IFormulaDirtyData, ISetDefinedNameMutationParam, ISetSuperTableMutationParam } from '@univerjs/engine-formula';
import type {
IInsertColMutationParams,
IInsertRowMutationParams,
@@ -37,7 +37,7 @@ import {
IUniverInstanceService,
ObjectMatrix,
} from '@univerjs/core';
-import { FormulaDataModel, IActiveDirtyManagerService, RemoveDefinedNameMutation, SetDefinedNameMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import { FormulaDataModel, IActiveDirtyManagerService, RemoveDefinedNameMutation, SetDefinedNameMutation, SetSuperTableMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import {
InsertColMutation,
InsertRowMutation,
@@ -98,6 +98,8 @@ export class ActiveDirtyController extends Disposable {
this._initialSheet();
this._initialDefinedName();
+
+ this._initialSuperTable();
}
private _initialMove() {
@@ -309,17 +311,42 @@ export class ActiveDirtyController extends Disposable {
});
}
- private _getDefinedNameMutation(definedName: ISetDefinedNameMutationParam) {
- const { unitId, name, formulaOrRefString } = definedName;
- const result: IDirtyUnitSheetDefinedNameMap = {};
+ private _initialSuperTable() {
+ this._activeDirtyManagerService.register(SetSuperTableMutation.id, {
+ commandId: SetSuperTableMutation.id,
+ getDirtyData: (command: ICommandInfo) => {
+ const params = command.params as ISetSuperTableMutationParam;
+ const { unitId, reference } = params;
+ const { sheetId, range } = reference;
+
+ return {
+ dirtyRanges: [{ unitId, sheetId, range }],
+ dirtySuperTableMap: {
+ [unitId]: {
+ [params.tableName]: '1',
+ },
+ },
+ clearDependencyTreeCache: {
+ [unitId]: {
+ [sheetId]: '1',
+ },
+ },
+ };
+ },
+ });
+ }
+
+ private _getDefinedNameMutation(definedName: ISetDefinedNameMutationParam | null | undefined): IDirtyUnitDefinedNameMap {
if (definedName == null) {
return {};
}
- result[unitId] = {};
-
- result[unitId]![name] = formulaOrRefString;
-
+ const { unitId, name: definedNameName, formulaOrRefString } = definedName;
+ const result: IDirtyUnitDefinedNameMap = {
+ [unitId]: {
+ [definedNameName]: formulaOrRefString,
+ },
+ };
return result;
}
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 4e49527086..7d442bf299 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -16,9 +16,11 @@
import type { ICommandInfo, IUnitRange, Nullable, Workbook } from '@univerjs/core';
import type {
+ IDirtyUnitDefinedNameMap,
IDirtyUnitFeatureMap,
IDirtyUnitOtherFormulaMap,
IDirtyUnitSheetNameMap,
+ IDirtyUnitSuperTableMap,
IExecutionInProgressParams,
IFormulaDirtyData,
ISetFormulaCalculationNotificationMutation,
@@ -66,6 +68,8 @@ const NilProgress: ICalculationProgress = { done: 0, count: 0 };
const lo = { onlyLocal: true };
+type IDirtyUnitStringMap = Record<string, Nullable<Record<string, string>>>;
+
export class TriggerCalculationController extends Disposable {
private _waitingCommandQueue: ICommandInfo[] = [];
@@ -74,6 +78,7 @@ export class TriggerCalculationController extends Disposable {
dirtyRanges: [],
dirtyNameMap: {},
dirtyDefinedNameMap: {},
+ dirtySuperTableMap: {},
dirtyUnitFeatureMap: {},
dirtyUnitOtherFormulaMap: {},
clearDependencyTreeCache: {},
@@ -232,7 +237,8 @@ export class TriggerCalculationController extends Disposable {
private _generateDirty(commands: ICommandInfo[]) {
const allDirtyRanges: IUnitRange[] = [];
const allDirtyNameMap: IDirtyUnitSheetNameMap = {};
- const allDirtyDefinedNameMap: IDirtyUnitSheetNameMap = {};
+ const allDirtyDefinedNameMap: IDirtyUnitDefinedNameMap = {};
+ const allDirtySuperTableMap: IDirtyUnitSuperTableMap = {};
const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
const allDirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
const allClearDependencyTreeCache: IDirtyUnitSheetNameMap = {};
@@ -249,18 +255,22 @@ export class TriggerCalculationController extends Disposable {
const params = conversion.getDirtyData(command);
- const { dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, clearDependencyTreeCache, forceCalculation = false } = params;
+ const { dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtySuperTableMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, clearDependencyTreeCache, forceCalculation = false } = params;
if (dirtyRanges != null) {
this._mergeDirtyRanges(allDirtyRanges, dirtyRanges);
}
if (dirtyNameMap != null) {
- this._mergeDirtyNameMap(allDirtyNameMap, dirtyNameMap);
+ this._mergeDirtyUnitStringMap(allDirtyNameMap, dirtyNameMap);
}
if (dirtyDefinedNameMap != null) {
- this._mergeDirtyNameMap(allDirtyDefinedNameMap, dirtyDefinedNameMap);
+ this._mergeDirtyUnitStringMap(allDirtyDefinedNameMap, dirtyDefinedNameMap);
+ }
+
+ if (dirtySuperTableMap != null) {
+ this._mergeDirtyUnitStringMap(allDirtySuperTableMap, dirtySuperTableMap);
}
if (dirtyUnitFeatureMap != null) {
@@ -272,7 +282,7 @@ export class TriggerCalculationController extends Disposable {
}
if (clearDependencyTreeCache != null) {
- this._mergeDirtyNameMap(allClearDependencyTreeCache, clearDependencyTreeCache);
+ this._mergeDirtyUnitStringMap(allClearDependencyTreeCache, clearDependencyTreeCache);
}
allForceCalculation = allForceCalculation || forceCalculation;
@@ -282,6 +292,7 @@ export class TriggerCalculationController extends Disposable {
dirtyRanges: allDirtyRanges,
dirtyNameMap: allDirtyNameMap,
dirtyDefinedNameMap: allDirtyDefinedNameMap,
+ dirtySuperTableMap: allDirtySuperTableMap,
dirtyUnitFeatureMap: allDirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,
forceCalculation: allForceCalculation,
@@ -293,16 +304,18 @@ export class TriggerCalculationController extends Disposable {
private _mergeDirty(dirtyData1: IFormulaDirtyData, dirtyData2: IFormulaDirtyData) {
const allDirtyRanges: IUnitRange[] = [...dirtyData1.dirtyRanges, ...dirtyData2.dirtyRanges];
const allDirtyNameMap: IDirtyUnitSheetNameMap = { ...dirtyData1.dirtyNameMap };
- const allDirtyDefinedNameMap: IDirtyUnitSheetNameMap = { ...dirtyData1.dirtyDefinedNameMap };
+ const allDirtyDefinedNameMap: IDirtyUnitDefinedNameMap = { ...dirtyData1.dirtyDefinedNameMap };
+ const allDirtySuperTableMap: IDirtyUnitSuperTableMap = { ...dirtyData1.dirtySuperTableMap };
const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = { ...dirtyData1.dirtyUnitFeatureMap };
const allDirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = { ...dirtyData1.dirtyUnitOtherFormulaMap };
const allClearDependencyTreeCache: IDirtyUnitSheetNameMap = { ...dirtyData1.clearDependencyTreeCache };
- this._mergeDirtyNameMap(allDirtyNameMap, dirtyData2.dirtyNameMap);
- this._mergeDirtyNameMap(allDirtyDefinedNameMap, dirtyData2.dirtyDefinedNameMap);
+ this._mergeDirtyUnitStringMap(allDirtyNameMap, dirtyData2.dirtyNameMap);
+ this._mergeDirtyUnitStringMap(allDirtyDefinedNameMap, dirtyData2.dirtyDefinedNameMap);
+ this._mergeDirtyUnitStringMap(allDirtySuperTableMap, dirtyData2.dirtySuperTableMap || {});
this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitFeatureMap, dirtyData2.dirtyUnitFeatureMap);
this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitOtherFormulaMap, dirtyData2.dirtyUnitOtherFormulaMap);
- this._mergeDirtyNameMap(allClearDependencyTreeCache, dirtyData2.clearDependencyTreeCache);
+ this._mergeDirtyUnitStringMap(allClearDependencyTreeCache, dirtyData2.clearDependencyTreeCache);
const allForceCalculating = dirtyData1.forceCalculation || dirtyData2.forceCalculation;
@@ -310,6 +323,7 @@ export class TriggerCalculationController extends Disposable {
dirtyRanges: allDirtyRanges,
dirtyNameMap: allDirtyNameMap,
dirtyDefinedNameMap: allDirtyDefinedNameMap,
+ dirtySuperTableMap: allDirtySuperTableMap,
dirtyUnitFeatureMap: allDirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,
forceCalculation: allForceCalculating,
@@ -348,15 +362,15 @@ export class TriggerCalculationController extends Disposable {
}
}
- private _mergeDirtyNameMap(allDirtyNameMap: IDirtyUnitSheetNameMap, dirtyNameMap: IDirtyUnitSheetNameMap) {
- Object.keys(dirtyNameMap).forEach((unitId) => {
- if (allDirtyNameMap[unitId] == null) {
- allDirtyNameMap[unitId] = {};
+ private _mergeDirtyUnitStringMap(allDirtyMap: IDirtyUnitStringMap, dirtyMap: IDirtyUnitStringMap) {
+ Object.keys(dirtyMap).forEach((unitId) => {
+ if (allDirtyMap[unitId] == null) {
+ allDirtyMap[unitId] = {};
}
- Object.keys(dirtyNameMap[unitId]!).forEach((sheetId) => {
- if (dirtyNameMap[unitId]?.[sheetId]) {
- allDirtyNameMap[unitId]![sheetId] = dirtyNameMap[unitId]![sheetId];
+ Object.keys(dirtyMap[unitId]!).forEach((dirtyKey) => {
+ if (dirtyMap[unitId]?.[dirtyKey]) {
+ allDirtyMap[unitId]![dirtyKey] = dirtyMap[unitId]![dirtyKey];
}
});
});
@@ -522,6 +536,7 @@ export class TriggerCalculationController extends Disposable {
dirtyRanges: [],
dirtyNameMap: {},
dirtyDefinedNameMap: {},
+ dirtySuperTableMap: {},
dirtyUnitFeatureMap: {},
dirtyUnitOtherFormulaMap: {},
forceCalculation: false,
@@ -544,7 +559,8 @@ export class TriggerCalculationController extends Disposable {
const dirtyRanges: IUnitRange[] = calculationMode === CalculationMode.WHEN_EMPTY ? this._formulaDataModel.getFormulaDirtyRanges() : [];
const dirtyNameMap: IDirtyUnitSheetNameMap = {};
- const dirtyDefinedNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyDefinedNameMap: IDirtyUnitDefinedNameMap = {};
+ const dirtySuperTableMap: IDirtyUnitSuperTableMap = {};
const dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
const dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
const clearDependencyTreeCache: IDirtyUnitSheetNameMap = {};
@@ -554,6 +570,7 @@ export class TriggerCalculationController extends Disposable {
dirtyRanges,
dirtyNameMap,
dirtyDefinedNameMap,
+ dirtySuperTableMap,
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 789f43e845..17ce000cbb 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -22,7 +22,7 @@ import type {
Nullable,
Workbook,
} from '@univerjs/core';
-import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IFormulaData, IFormulaDataItem, IFormulaDirtyData, IUnitSheetNameMap } from '@univerjs/engine-formula';
+import type { IDirtyUnitDefinedNameMap, IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IFormulaData, IFormulaDataItem, IFormulaDirtyData, IUnitSheetNameMap } from '@univerjs/engine-formula';
import type {
IInsertSheetMutationParams,
IRemoveSheetMutationParams,
@@ -43,7 +43,7 @@ import {
Tools,
UniverInstanceType,
} from '@univerjs/core';
-import { deserializeRangeWithSheetWithCache, ErrorType, FormulaDataModel, generateStringWithSequence, IDefinedNamesService, initSheetFormulaData, LexerTreeBuilder, sequenceNodeType, serializeRangeToRefString, SetArrayFormulaDataMutation, SetFormulaDataMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import { deserializeRangeWithSheetWithCache, ErrorType, FormulaDataModel, generateStringWithSequence, IDefinedNamesService, initSheetFormulaData, LexerTreeBuilder, sequenceNodeType, serializeRangeToRefString, SetArrayFormulaDataMutation, SetFormulaDataMutation, SetTriggerFormulaCalculationStartMutation, splitTableStructuredRef } from '@univerjs/engine-formula';
import {
ClearSelectionFormatCommand,
InsertSheetMutation,
@@ -297,7 +297,7 @@ export class UpdateFormulaController extends Disposable {
const dirtyRanges: IUnitRange[] = calculationMode === CalculationMode.WHEN_EMPTY ? this._formulaDataModel.getFormulaDirtyRanges() : [];
const dirtyNameMap: IDirtyUnitSheetNameMap = {};
- const dirtyDefinedNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyDefinedNameMap: IDirtyUnitDefinedNameMap = {};
const dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
const dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
const clearDependencyTreeCache: IDirtyUnitSheetNameMap = {};
@@ -457,6 +457,33 @@ export class UpdateFormulaController extends Disposable {
shouldModify = true;
refChangeIds.push(i);
+ continue;
+ } else if ((type === FormulaReferenceMoveType.SetSuperTableName || type === FormulaReferenceMoveType.RemoveSuperTableName || type === FormulaReferenceMoveType.RemoveSuperTableColumn) && (nodeType === sequenceNodeType.TABLE || nodeType === sequenceNodeType.FUNCTION)) {
+ const { oldTableName, tableName, tableColumnNames } = formulaReferenceMoveParam;
+ if (oldTableName === undefined || (type === FormulaReferenceMoveType.SetSuperTableName && tableName === undefined)) {
+ continue;
+ }
+
+ const { tableName: tokenTableName, columnStruct = '' } = splitTableStructuredRef(token);
+ if (tokenTableName !== oldTableName) {
+ continue;
+ }
+
+ if (type === FormulaReferenceMoveType.RemoveSuperTableColumn && !tableReferenceContainsColumn(columnStruct, tableColumnNames)) {
+ continue;
+ }
+
+ sequenceNodes[i] = {
+ ...node,
+ token: type === FormulaReferenceMoveType.SetSuperTableName ? `${tableName}${columnStruct}` : ErrorType.REF,
+ };
+ const nextNode = sequenceNodes[i + 1];
+ if ((type === FormulaReferenceMoveType.RemoveSuperTableName || type === FormulaReferenceMoveType.RemoveSuperTableColumn) && typeof nextNode === 'string' && nextNode.startsWith(']')) {
+ sequenceNodes[i + 1] = nextNode.slice(1);
+ }
+ shouldModify = true;
+ refChangeIds.push(i);
+
continue;
} else if (nodeType !== sequenceNodeType.REFERENCE) {
continue;
@@ -658,3 +685,22 @@ export class UpdateFormulaController extends Disposable {
return { newFormulaData };
}
}
+
+function tableReferenceContainsColumn(columnStruct: string, columnNames: string[] | undefined): boolean {
+ if (!columnNames?.length || columnStruct.length === 0) {
+ return false;
+ }
+
+ const columnNameSet = new Set(columnNames);
+ const completedColumnStruct = columnStruct.endsWith(']') ? columnStruct : `${columnStruct}]`;
+ const columnMatches = completedColumnStruct.matchAll(/\[([^\]]+)\]/g);
+
+ for (const match of columnMatches) {
+ const columnName = match[1].replace(/^\[/, '').trim();
+ if (!columnName.startsWith('#') && columnNameSet.has(columnName)) {
+ return true;
+ }
+ }
+
+ return false;
+}
diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts
index 1085018720..9c9e17e596 100644
--- a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts
+++ b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts
@@ -290,6 +290,52 @@ describe('getReferenceMoveParams', () => {
definedName: 'Revenue',
definedNameId: 'defined-name-id',
});
+ expect(getReferenceMoveParams(workbook, {
+ id: 'sheet.command.set-table-config',
+ params: {
+ unitId: 'test',
+ tableId: 'table-id',
+ name: 'Sales',
+ oldTableName: 'Orders',
+ },
+ })).toEqual({
+ type: FormulaReferenceMoveType.SetSuperTableName,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ tableName: 'Sales',
+ oldTableName: 'Orders',
+ });
+ expect(getReferenceMoveParams(workbook, {
+ id: 'sheet.command.delete-table',
+ params: {
+ unitId: 'test',
+ tableId: 'table-id',
+ tableName: 'Orders',
+ },
+ })).toEqual({
+ type: FormulaReferenceMoveType.RemoveSuperTableName,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ oldTableName: 'Orders',
+ });
+ expect(getReferenceMoveParams(workbook, {
+ id: 'sheet.command.table-remove-column-at',
+ params: {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'table-id',
+ range: { startRow: 0, endRow: 11, startColumn: 1, endColumn: 1 },
+ tableName: 'Orders',
+ removedColumnNames: ['1'],
+ },
+ })).toEqual({
+ type: FormulaReferenceMoveType.RemoveSuperTableColumn,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ range: { startRow: 0, endRow: 11, startColumn: 1, endColumn: 1 },
+ oldTableName: 'Orders',
+ tableColumnNames: ['1'],
+ });
testBed.univer.dispose();
});
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 7e83222f34..ec7b9a2479 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
@@ -38,6 +38,9 @@ export enum FormulaReferenceMoveType {
RemoveSheet,
SetDefinedName, // update defined name
RemoveDefinedName, // remove defined name
+ SetSuperTableName, // update super table name
+ RemoveSuperTableName, // remove super table name
+ RemoveSuperTableColumn, // remove super table column
}
export interface IFormulaReferenceMoveParam {
@@ -59,6 +62,9 @@ export interface IFormulaReferenceMoveParam {
* new defined name
*/
definedName?: string;
+ oldTableName?: string;
+ tableName?: string;
+ tableColumnNames?: string[];
/**
* The filtered rows contained in the range, used for remove rows operation, etc.
*/
@@ -70,12 +76,14 @@ const formulaReferenceSheetList = [
FormulaReferenceMoveType.RemoveSheet,
FormulaReferenceMoveType.SetDefinedName,
FormulaReferenceMoveType.RemoveDefinedName,
+ FormulaReferenceMoveType.SetSuperTableName,
+ FormulaReferenceMoveType.RemoveSuperTableName,
];
export function getFormulaReferenceMoveUndoRedo(oldFormulaData: IFormulaData, newFormulaData: IFormulaData, formulaReferenceMoveParam: IFormulaReferenceMoveParam) {
const { type } = formulaReferenceMoveParam;
- if (formulaReferenceSheetList.includes(type)) {
+ if (formulaReferenceSheetList.includes(type) || (type === FormulaReferenceMoveType.RemoveSuperTableColumn && formulaReferenceMoveParam.range == null)) {
return getFormulaReferenceSheet(oldFormulaData, newFormulaData);
} else {
return getFormulaReferenceRange(oldFormulaData, newFormulaData, formulaReferenceMoveParam);
@@ -366,6 +374,7 @@ function handleInsertDelete(oldCell: IRange, formulaReferenceMoveParam: IFormula
newCell = handleRefRemoveRow(range, oldCell, rangeFilteredRows);
break;
case FormulaReferenceMoveType.RemoveColumn:
+ case FormulaReferenceMoveType.RemoveSuperTableColumn:
newCell = handleRefRemoveCol(range, oldCell);
break;
case FormulaReferenceMoveType.DeleteMoveLeft:
diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-param.ts b/packages/sheets-formula/src/controllers/utils/ref-range-param.ts
index a43856b0d7..226e78c0f0 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-param.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-param.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommandInfo, Nullable, Workbook } from '@univerjs/core';
+import type { ICommandInfo, IRange, Nullable, Workbook } from '@univerjs/core';
import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
import type {
IDeleteRangeMoveLeftCommandParams,
@@ -51,6 +51,30 @@ import {
} from '@univerjs/sheets';
import { FormulaReferenceMoveType } from './ref-range-formula';
+const SET_SHEET_TABLE_COMMAND_ID = 'sheet.command.set-table-config';
+const DELETE_SHEET_TABLE_COMMAND_ID = 'sheet.command.delete-table';
+const REMOVE_SHEET_TABLE_COLUMN_AT_COMMAND_ID = 'sheet.command.table-remove-column-at';
+const REMOVE_SHEET_TABLE_COLUMN_COMMAND_ID = 'sheet.command.table-remove-col';
+
+interface ISetSheetTableNameCommandParam {
+ unitId: string;
+ name?: string;
+ oldTableName?: string;
+}
+
+interface IDeleteSheetTableCommandParam {
+ unitId: string;
+ tableName?: string;
+}
+
+interface IRemoveSheetTableColumnCommandParam {
+ unitId: string;
+ subUnitId?: string;
+ range?: IRange;
+ tableName?: string;
+ removedColumnNames?: string[];
+}
+
export function getReferenceMoveParams(workbook: Workbook, command: ICommandInfo) {
const { id } = command;
let result: Nullable<IFormulaReferenceMoveParam> = null;
@@ -101,6 +125,16 @@ export function getReferenceMoveParams(workbook: Workbook, command: ICommandInfo
case RemoveDefinedNameCommand.id:
result = handleRefRemoveDefinedName(command as ICommandInfo<ISetDefinedNameMutationParam>, workbook);
break;
+ case SET_SHEET_TABLE_COMMAND_ID:
+ result = handleRefSetSheetTableName(command as ICommandInfo<ISetSheetTableNameCommandParam>, workbook);
+ break;
+ case DELETE_SHEET_TABLE_COMMAND_ID:
+ result = handleRefRemoveSheetTableName(command as ICommandInfo<IDeleteSheetTableCommandParam>, workbook);
+ break;
+ case REMOVE_SHEET_TABLE_COLUMN_AT_COMMAND_ID:
+ case REMOVE_SHEET_TABLE_COLUMN_COMMAND_ID:
+ result = handleRefRemoveSheetTableColumn(command as ICommandInfo<IRemoveSheetTableColumnCommandParam>, workbook);
+ break;
}
return result;
@@ -410,3 +444,51 @@ function handleRefRemoveDefinedName(command: ICommandInfo<ISetDefinedNameMutatio
definedNameId: id,
};
}
+
+function handleRefSetSheetTableName(command: ICommandInfo<ISetSheetTableNameCommandParam>, workbook: Workbook): Nullable<IFormulaReferenceMoveParam> {
+ const { params } = command;
+ if (!params || !params.name || !params.oldTableName || params.oldTableName === params.name) return null;
+
+ const { unitId, name: tableName, oldTableName } = params;
+ const { sheetId } = getCurrentSheetInfo(workbook);
+
+ return {
+ type: FormulaReferenceMoveType.SetSuperTableName,
+ unitId,
+ sheetId,
+ tableName,
+ oldTableName,
+ };
+}
+
+function handleRefRemoveSheetTableName(command: ICommandInfo<IDeleteSheetTableCommandParam>, workbook: Workbook): Nullable<IFormulaReferenceMoveParam> {
+ const { params } = command;
+ if (!params || !params.tableName) return null;
+
+ const { unitId, tableName } = params;
+ const { sheetId } = getCurrentSheetInfo(workbook);
+
+ return {
+ type: FormulaReferenceMoveType.RemoveSuperTableName,
+ unitId,
+ sheetId,
+ oldTableName: tableName,
+ };
+}
+
+function handleRefRemoveSheetTableColumn(command: ICommandInfo<IRemoveSheetTableColumnCommandParam>, workbook: Workbook): Nullable<IFormulaReferenceMoveParam> {
+ const { params } = command;
+ if (!params || !params.tableName || !params.removedColumnNames?.length) return null;
+
+ const { unitId, subUnitId, range, tableName, removedColumnNames } = params;
+ const { sheetId } = getCurrentSheetInfo(workbook);
+
+ return {
+ type: FormulaReferenceMoveType.RemoveSuperTableColumn,
+ unitId,
+ sheetId: subUnitId || sheetId,
+ range,
+ oldTableName: tableName,
+ tableColumnNames: removedColumnNames,
+ };
+}
diff --git a/packages/sheets-table/package.json b/packages/sheets-table/package.json
index 6adb5a0a00..889d0ee785 100644
--- a/packages/sheets-table/package.json
+++ b/packages/sheets-table/package.json
@@ -84,6 +84,8 @@
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/sheets-formula": "workspace:*",
"rxjs": "^7.8.2",
"typescript": "^6.0.3",
"vitest": "^4.1.5"
diff --git a/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
index a660757142..501d1660c8 100644
--- a/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
+++ b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
@@ -15,7 +15,7 @@
*/
import { ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
-import { SheetsSelectionsService } from '@univerjs/sheets';
+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
import { SheetsTableController } from '../../../controllers/sheets-table.controller';
@@ -207,15 +207,22 @@ describe('sheet-table-row-col commands', () => {
const syncExecuteCommand = vi.fn(() => true);
const pushUndoRedo = vi.fn();
+ const onCommandExecute = vi.fn(() => ({
+ preRedos: [{ id: 'formula.redo.before', params: { phase: 'pre' } }],
+ redos: [{ id: 'formula.redo.after', params: { phase: 'post' } }],
+ preUndos: [{ id: 'formula.undo.before', params: { phase: 'pre' } }],
+ undos: [{ id: 'formula.undo.after', params: { phase: 'post' } }],
+ }));
const table = {
getId: () => 't1',
getSubunitId: () => 's1',
getRange: () => ({ startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 }),
getTableInfo: () => ({
+ name: 'Table',
columns: [
- { id: 'c1', displayName: 'Column 1' },
- { id: 'c2', displayName: 'Column 2' },
- { id: 'c3', displayName: 'Column 3' },
+ { id: 'c1', displayName: '1' },
+ { id: 'c2', displayName: '2' },
+ { id: 'c3', displayName: '3' },
],
}),
};
@@ -224,6 +231,7 @@ describe('sheet-table-row-col commands', () => {
[TableManager, { getTableById: () => table }],
[ICommandService, { syncExecuteCommand }],
[IUndoRedoService, { pushUndoRedo }],
+ [SheetInterceptorService, { onCommandExecute }],
]);
expect(SheetTableRemoveColumnAtCommand.handler(accessor, {
@@ -233,7 +241,32 @@ describe('sheet-table-row-col commands', () => {
index: 2,
count: 1,
})).toBe(true);
- expect(syncExecuteCommand).toHaveBeenCalled();
- expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({ unitID: 'u1' }));
+ expect(onCommandExecute).toHaveBeenCalledWith({
+ id: SheetTableRemoveColumnAtCommand.id,
+ params: expect.objectContaining({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ tableName: 'Table',
+ removedColumnNames: ['2'],
+ }),
+ });
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string, unknown, unknown?]>).map(([id]) => id)).toEqual([
+ 'formula.redo.before',
+ 'sheet.mutation.set-sheet-table',
+ 'formula.redo.after',
+ 'move-redo',
+ ]);
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'u1',
+ undoMutations: expect.arrayContaining([
+ expect.objectContaining({ id: 'formula.undo.before' }),
+ expect.objectContaining({ id: 'formula.undo.after' }),
+ ]),
+ redoMutations: expect.arrayContaining([
+ expect.objectContaining({ id: 'formula.redo.before' }),
+ expect.objectContaining({ id: 'formula.redo.after' }),
+ ]),
+ }));
});
});
diff --git a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
index 59009f0e80..50241b99f5 100644
--- a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
+++ b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
@@ -16,7 +16,7 @@
import { ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { IDefinedNamesService } from '@univerjs/engine-formula';
-import { AddRangeThemeMutation, RemoveRangeThemeMutation, SheetRangeThemeModel } from '@univerjs/sheets';
+import { AddRangeThemeMutation, RemoveRangeThemeMutation, SheetInterceptorService, SheetRangeThemeModel } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
import { TableManager } from '../../../model/table-manager';
import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../../../types/type';
@@ -99,6 +99,12 @@ describe('sheets-table commands', () => {
it('DeleteSheetTableCommand should build undo mutations from table snapshot', () => {
const syncExecuteCommand = vi.fn(() => true);
const pushUndoRedo = vi.fn();
+ const onCommandExecute = vi.fn(() => ({
+ preRedos: [{ id: 'formula.redo.before', params: { phase: 'pre' } }],
+ redos: [{ id: 'formula.redo.after', params: { phase: 'post' } }],
+ preUndos: [{ id: 'formula.undo.before', params: { phase: 'pre' } }],
+ undos: [{ id: 'formula.undo.after', params: { phase: 'post' } }],
+ }));
const tableSnapshot = {
id: 't1',
name: 'Table1',
@@ -113,15 +119,30 @@ describe('sheets-table commands', () => {
[ICommandService, { syncExecuteCommand }],
[TableManager, tableManager],
[ILogService, { error: vi.fn() }],
+ [SheetInterceptorService, { onCommandExecute }],
]);
const result = DeleteSheetTableCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' });
expect(result).toBe(true);
- expect(syncExecuteCommand).toHaveBeenCalledWith(DeleteSheetTableMutation.id, { unitId: 'u1', subUnitId: 's1', tableId: 't1' }, undefined);
+ expect(onCommandExecute).toHaveBeenCalledWith({
+ id: DeleteSheetTableCommand.id,
+ params: {
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ tableName: 'Table1',
+ },
+ });
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string, unknown, unknown?]>).map(([id]) => id)).toEqual([
+ 'formula.redo.before',
+ DeleteSheetTableMutation.id,
+ 'formula.redo.after',
+ ]);
expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
unitID: 'u1',
undoMutations: [
+ expect.objectContaining({ id: 'formula.undo.before' }),
expect.objectContaining({
id: AddSheetTableMutation.id,
params: expect.objectContaining({
@@ -129,6 +150,12 @@ describe('sheets-table commands', () => {
name: 'Table1',
}),
}),
+ expect.objectContaining({ id: 'formula.undo.after' }),
+ ],
+ redoMutations: [
+ expect.objectContaining({ id: 'formula.redo.before' }),
+ expect.objectContaining({ id: DeleteSheetTableMutation.id }),
+ expect.objectContaining({ id: 'formula.redo.after' }),
],
}));
});
@@ -182,6 +209,12 @@ describe('sheets-table commands', () => {
it('SetSheetTableCommand should execute mutation and build inverse undo config', () => {
const executeCommand = vi.fn();
const pushUndoRedo = vi.fn();
+ const onCommandExecute = vi.fn(() => ({
+ preRedos: [{ id: 'formula.redo.before', params: { phase: 'pre' } }],
+ redos: [{ id: 'formula.redo.after', params: { phase: 'post' } }],
+ preUndos: [{ id: 'formula.undo.before', params: { phase: 'pre' } }],
+ undos: [{ id: 'formula.undo.after', params: { phase: 'post' } }],
+ }));
const table = {
getDisplayName: () => 'OldName',
getRange: () => ({ startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 }),
@@ -197,6 +230,7 @@ describe('sheets-table commands', () => {
[ICommandService, { executeCommand }],
[IUndoRedoService, { pushUndoRedo }],
[ILogService, { warn: vi.fn() }],
+ [SheetInterceptorService, { onCommandExecute }],
]);
const result = SetSheetTableCommand.handler(accessor, {
@@ -216,21 +250,24 @@ describe('sheets-table commands', () => {
});
expect(result).toBe(true);
- expect(executeCommand).toHaveBeenCalledWith(
- SetSheetTableMutation.id,
- expect.objectContaining({
+ expect(onCommandExecute).toHaveBeenCalledWith({
+ id: SetSheetTableCommand.id,
+ params: expect.objectContaining({
unitId: 'u1',
- subUnitId: 's1',
tableId: 't1',
- config: expect.objectContaining({
- name: 'NewName',
- theme: 'theme-new',
- }),
- })
- );
+ name: 'NewName',
+ oldTableName: 'OldName',
+ }),
+ });
+ expect(executeCommand.mock.calls.map(([id]) => id)).toEqual([
+ 'formula.redo.before',
+ SetSheetTableMutation.id,
+ 'formula.redo.after',
+ ]);
expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
undoMutations: [
+ expect.objectContaining({ id: 'formula.undo.before' }),
expect.objectContaining({
id: SetSheetTableMutation.id,
params: expect.objectContaining({
@@ -241,6 +278,12 @@ describe('sheets-table commands', () => {
}),
}),
}),
+ expect.objectContaining({ id: 'formula.undo.after' }),
+ ],
+ redoMutations: [
+ expect.objectContaining({ id: 'formula.redo.before' }),
+ expect.objectContaining({ id: SetSheetTableMutation.id }),
+ expect.objectContaining({ id: 'formula.redo.after' }),
],
}));
});
diff --git a/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
index e33450e39b..c118e23b23 100644
--- a/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
+++ b/packages/sheets-table/src/commands/commands/delete-sheet-table.command.ts
@@ -17,7 +17,7 @@
import type { ICommand, IMutationInfo } from '@univerjs/core';
import type { IDeleteSheetTableParams } from '../mutations/delete-sheet-table.mutation';
import { CommandType, ICommandService, ILogService, IUndoRedoService, sequenceExecute } from '@univerjs/core';
-
+import { SheetInterceptorService } from '@univerjs/sheets';
import { TableManager } from '../../model/table-manager';
import { AddSheetTableMutation } from '../mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from '../mutations/delete-sheet-table.mutation';
@@ -45,7 +45,19 @@ export const DeleteSheetTableCommand: ICommand<IDeleteSheetTableParams> = {
return false;
}
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+ const interceptorCommands = sheetInterceptorService.onCommandExecute({
+ id: DeleteSheetTableCommand.id,
+ params: {
+ ...params,
+ tableName: tableConfig.name,
+ },
+ });
+
+ redos.push(...(interceptorCommands.preRedos ?? []));
redos.push({ id: DeleteSheetTableMutation.id, params: { ...params } });
+ redos.push(...interceptorCommands.redos);
+ undos.push(...(interceptorCommands.preUndos ?? []));
undos.push({
id: AddSheetTableMutation.id,
params: {
@@ -57,6 +69,7 @@ export const DeleteSheetTableCommand: ICommand<IDeleteSheetTableParams> = {
options: tableConfig.options,
},
});
+ undos.push(...interceptorCommands.undos);
const res = sequenceExecute(redos, commandService);
diff --git a/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts b/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts
index dee21d282e..a23c7138a5 100644
--- a/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts
+++ b/packages/sheets-table/src/commands/commands/set-sheet-table.command.ts
@@ -16,9 +16,9 @@
import type { ICommand } from '@univerjs/core';
import type { ITableSetConfig } from '../../types/type';
-import type { ISetSheetTableMutationParams } from '../mutations/set-sheet-table.mutation';
import { CommandType, ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { IDefinedNamesService } from '@univerjs/engine-formula';
+import { SheetInterceptorService } from '@univerjs/sheets';
import { TableManager } from '../../model/table-manager';
import { IRangeOperationTypeEnum } from '../../types/type';
import { getExistingNamesSet } from '../../util';
@@ -28,6 +28,7 @@ import { SetSheetTableMutation } from '../mutations/set-sheet-table.mutation';
export interface ISetSheetTableCommandParams extends ITableSetConfig {
unitId: string;
tableId: string;
+ oldTableName?: string;
}
export const SetSheetTableCommand: ICommand<ISetSheetTableCommandParams> = {
@@ -94,30 +95,42 @@ export const SetSheetTableCommand: ICommand<ISetSheetTableCommandParams> = {
tableId,
config: newTableConfig,
};
+ const undoParams = {
+ unitId,
+ subUnitId: table.getSubunitId(),
+ tableId,
+ config: oldTableConfig,
+ };
+
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+ const interceptorCommands = sheetInterceptorService.onCommandExecute({
+ id: SetSheetTableCommand.id,
+ params: {
+ ...params,
+ oldTableName: oldTableConfig.name,
+ },
+ });
+ const redos = [
+ ...(interceptorCommands.preRedos ?? []),
+ { id: SetSheetTableMutation.id, params: redoParams },
+ ...interceptorCommands.redos,
+ ];
+ const undos = [
+ ...(interceptorCommands.preUndos ?? []),
+ { id: SetSheetTableMutation.id, params: undoParams },
+ ...interceptorCommands.undos,
+ ];
const commandService = accessor.get(ICommandService);
- commandService.executeCommand<ISetSheetTableMutationParams>(SetSheetTableMutation.id, redoParams);
+ redos.forEach((mutation) => {
+ commandService.executeCommand(mutation.id, mutation.params);
+ });
const undoRedoService = accessor.get(IUndoRedoService);
undoRedoService.pushUndoRedo({
unitID: unitId,
- undoMutations: [
- {
- id: SetSheetTableMutation.id,
- params: {
- unitId,
- subUnitId: table.getSubunitId(),
- tableId,
- config: oldTableConfig,
- },
- },
- ],
- redoMutations: [
- {
- id: SetSheetTableMutation.id,
- params: redoParams,
- },
- ],
+ undoMutations: undos,
+ redoMutations: redos,
});
return true;
diff --git a/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts b/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts
index dcae0043bf..e4e004066d 100644
--- a/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts
+++ b/packages/sheets-table/src/commands/commands/sheet-table-row-col.command.ts
@@ -19,7 +19,7 @@
import type { IAccessor, ICommand, IMutationInfo } from '@univerjs/core';
import type { ITableColumnJson } from '../../types/type';
import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, sequenceExecute } from '@univerjs/core';
-import { getMoveRangeUndoRedoMutations, getSheetCommandTarget, InsertColMutation, InsertRowMutation, RemoveColMutation, RemoveRowMutation, SheetsSelectionsService } from '@univerjs/sheets';
+import { getMoveRangeUndoRedoMutations, getSheetCommandTarget, InsertColMutation, InsertRowMutation, RemoveColMutation, RemoveRowMutation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { SheetsTableController } from '../../controllers/sheets-table.controller';
import { TableManager } from '../../model/table-manager';
import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../../types/type';
@@ -599,48 +599,67 @@ export const SheetTableRemoveColumnAtCommand: ICommand<ISheetTableInsertAtComman
return false;
}
+ const tableInfo = table.getTableInfo();
const columns: ITableColumnJson[] = [];
const gap = index - oldRange.startColumn;
for (let i = 0; i < count; i++) {
- const column = table.getTableInfo().columns[gap + i];
+ const column = tableInfo.columns[gap + i];
if (column) {
columns.push(column);
}
}
- const redos: IMutationInfo[] = [{
- id: SetSheetTableMutation.id,
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+ const interceptorCommands = sheetInterceptorService.onCommandExecute({
+ id: SheetTableRemoveColumnAtCommand.id,
params: {
- unitId,
- subUnitId,
- tableId,
- config: {
- rowColOperation: {
- operationType: IRangeOperationTypeEnum.Delete,
- rowColType: IRowColTypeEnum.Col,
- index,
- count,
+ ...params,
+ tableName: tableInfo.name,
+ removedColumnNames: columns.map((column) => column.displayName),
+ },
+ });
+
+ const redos: IMutationInfo[] = [
+ ...(interceptorCommands.preRedos ?? []),
+ {
+ id: SetSheetTableMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ tableId,
+ config: {
+ rowColOperation: {
+ operationType: IRangeOperationTypeEnum.Delete,
+ rowColType: IRowColTypeEnum.Col,
+ index,
+ count,
+ },
},
},
},
- }];
- const undos: IMutationInfo[] = [{
- id: SetSheetTableMutation.id,
- params: {
- unitId,
- subUnitId,
- tableId,
- config: {
- rowColOperation: {
- operationType: IRangeOperationTypeEnum.Insert,
- rowColType: IRowColTypeEnum.Col,
- index,
- count,
- columnsJson: columns,
+ ...interceptorCommands.redos,
+ ];
+ const undos: IMutationInfo[] = [
+ ...(interceptorCommands.preUndos ?? []),
+ {
+ id: SetSheetTableMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ tableId,
+ config: {
+ rowColOperation: {
+ operationType: IRangeOperationTypeEnum.Insert,
+ rowColType: IRowColTypeEnum.Col,
+ index,
+ count,
+ columnsJson: columns,
+ },
},
},
},
- }];
+ ...interceptorCommands.undos,
+ ];
const colContentIndex = target.worksheet.getCellMatrix().getDataRange().endColumn;
if (index + count <= colContentIndex) {
@@ -831,14 +850,27 @@ export const SheetTableRemoveColCommand: ICommand<ISheetTableRowColOperationComm
},
});
+ const tableInfo = table.getTableInfo();
const columns: ITableColumnJson[] = [];
const gap = range.startColumn - oldRange.startColumn;
for (let i = 0; i < removeColCount; i++) {
- const column = table.getTableInfo().columns[gap + i];
+ const column = tableInfo.columns[gap + i];
if (column) {
columns.push(column);
}
}
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+ const interceptorCommands = sheetInterceptorService.onCommandExecute({
+ id: SheetTableRemoveColCommand.id,
+ params: {
+ ...params,
+ tableName: tableInfo.name,
+ removedColumnNames: columns.map((column) => column.displayName),
+ },
+ });
+ redos.unshift(...(interceptorCommands.preRedos ?? []));
+ redos.push(...interceptorCommands.redos);
+ undos.unshift(...(interceptorCommands.preUndos ?? []));
undos.push({
id: SetSheetTableMutation.id,
params: {
@@ -856,6 +888,7 @@ export const SheetTableRemoveColCommand: ICommand<ISheetTableRowColOperationComm
},
},
});
+ undos.push(...interceptorCommands.undos);
const worksheet = target.worksheet;
const colContentIndex = worksheet.getCellMatrix().getDataRange().endColumn;
diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
new file mode 100644
index 0000000000..2584b0d218
--- /dev/null
+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts
@@ -0,0 +1,845 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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 { Dependency, ICellData, IWorkbookData, Nullable, UnitModel, Workbook } from '@univerjs/core';
+import type { BaseAstNode, BaseFunction, IUnitData } from '@univerjs/engine-formula';
+import type { IRender } from '@univerjs/engine-render';
+import {
+ CellValueType,
+ ICommandService,
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ ObjectMatrix,
+ Plugin,
+ RANGE_TYPE,
+ RedoCommand,
+ set,
+ ThemeService,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ AstRootNodeFactory,
+ AstTreeBuilder,
+ CalculateFormulaService,
+ DefinedNamesService,
+ FormulaCurrentConfigService,
+ FormulaDataModel,
+ FormulaDependencyGenerator,
+ FormulaRuntimeService,
+ functionMath,
+ FunctionNodeFactory,
+ FunctionService,
+ generateExecuteAstNodeData,
+ getObjectValue,
+ HyperlinkEngineFormulaService,
+ ICalculateFormulaService,
+ IDefinedNamesService,
+ IFormulaCurrentConfigService,
+ IFormulaDependencyGenerator,
+ IFormulaRuntimeService,
+ IFunctionService,
+ IHyperlinkEngineFormulaService,
+ Interpreter,
+ IOtherFormulaManagerService,
+ ISheetRowFilteredService,
+ ISuperTableService,
+ LambdaNodeFactory,
+ LambdaParameterNodeFactory,
+ Lexer,
+ LexerNode,
+ LexerTreeBuilder,
+ OperatorNodeFactory,
+ OtherFormulaManagerService,
+ PrefixNodeFactory,
+ ReferenceNodeFactory,
+ RemoveSuperTableMutation,
+ SetArrayFormulaDataMutation,
+ SetFormulaDataMutation,
+ SetSuperTableMutation,
+ SheetRowFilteredService,
+ SuffixNodeFactory,
+ SuperTableService,
+ UnionNodeFactory,
+ ValueNodeFactory,
+} from '@univerjs/engine-formula';
+import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { InsertColMutation, InsertRowMutation, MoveRangeCommand, MoveRangeMutation, RangeProtectionRuleModel, RefRangeService, RemoveColByRangeCommand, RemoveColCommand, RemoveColMutation, RemoveRowByRangeCommand, RemoveRowCommand, RemoveRowMutation, SetRangeValuesCommand, SetRangeValuesMutation, SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { UpdateFormulaController } from '@univerjs/sheets-formula';
+import enUS from '@univerjs/sheets/locale/en-US';
+import zhCN from '@univerjs/sheets/locale/zh-CN';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DeleteSheetTableCommand } from '../../commands/commands/delete-sheet-table.command';
+import { SetSheetTableCommand } from '../../commands/commands/set-sheet-table.command';
+import { SheetTableInsertColumnAtCommand, SheetTableRemoveColumnAtCommand } from '../../commands/commands/sheet-table-row-col.command';
+import { AddSheetTableMutation } from '../../commands/mutations/add-sheet-table.mutation';
+import { DeleteSheetTableMutation } from '../../commands/mutations/delete-sheet-table.mutation';
+import { SetSheetTableMutation } from '../../commands/mutations/set-sheet-table.mutation';
+import { TableManager } from '../../model/table-manager';
+import { SheetTableService } from '../../services/table.service';
+import { SheetTableFormulaController } from '../sheet-table-formula.controller';
+import { SheetTableRefRangeController } from '../sheet-table-ref-range.controller';
+
+interface ITestBed {
+ univer: Univer;
+ sheet: UnitModel<IWorkbookData>;
+ injector: Injector;
+}
+
+class RenderManagerServiceTestBed extends RenderManagerService {
+ override createRender(unitId: string): IRender {
+ const renderer = this._createRender(unitId, new Engine('', { elementHeight: 100, elementWidth: 100 }));
+ return renderer;
+ }
+}
+
+function createFacadeTestBed(workbookData: IWorkbookData, dependencies: Dependency[]): ITestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ const injector = this._injector;
+ injector.add([SheetsSelectionsService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([IFunctionService, { useClass: FunctionService }]);
+ injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerServiceTestBed }]);
+ injector.add([SheetSkeletonService]);
+ injector.add([FormulaDataModel]);
+ injector.add([LexerTreeBuilder]);
+ injector.add([RefRangeService]);
+ injector.add([WorksheetPermissionService]);
+ injector.add([WorkbookPermissionService]);
+ injector.add([WorksheetProtectionPointModel]);
+ injector.add([RangeProtectionRuleModel]);
+ injector.add([WorksheetProtectionRuleModel]);
+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);
+
+ dependencies.forEach((d) => injector.add(d));
+
+ this._injector.get(SheetInterceptorService);
+ this._injector.get(WorkbookPermissionService);
+ this._injector.get(WorksheetPermissionService);
+ }
+ }
+
+ injector.get(LocaleService).load({ zhCN, enUS });
+
+ const themeService = injector.get(ThemeService);
+ const theme = themeService.getCurrentTheme();
+ const newTheme = set(theme, 'black', '#35322b');
+ themeService.setTheme(newTheme);
+
+ univer.registerPlugin(TestPlugin);
+
+ const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData);
+ injector.get(IUniverInstanceService).focusUnit('test');
+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ return {
+ univer,
+ sheet,
+ injector,
+ };
+}
+
+function createWorkbookData(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'test',
+ sheetOrder: ['sheet1', 'sheet2'],
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {
+ 0: {
+ 0: { v: 'product', t: CellValueType.STRING },
+ 1: { v: 'amount', t: CellValueType.STRING },
+ 2: { v: 'tax', t: CellValueType.STRING },
+ },
+ 1: {
+ 0: { v: 'A', t: CellValueType.STRING },
+ 1: { v: 10, t: CellValueType.NUMBER },
+ 2: { v: 1, t: CellValueType.NUMBER },
+ },
+ 2: {
+ 0: { v: 'B', t: CellValueType.STRING },
+ 1: { v: 20, t: CellValueType.NUMBER },
+ 2: { v: 2, t: CellValueType.NUMBER },
+ },
+ 3: {
+ 0: { v: 'C', t: CellValueType.STRING },
+ 1: { v: 30, t: CellValueType.NUMBER },
+ 2: { v: 3, t: CellValueType.NUMBER },
+ },
+ 5: {
+ 4: { f: '=SUM(Orders[amount])' },
+ 5: { f: '="Orders[amount]"' },
+ 6: { f: '=Table[1]' },
+ 7: { f: '=Table[2]' },
+ 8: { f: '="Table[1]"' },
+ },
+ 6: {
+ 4: { f: '=SUM(Orders[amount],Orders[amount])' },
+ },
+ 7: {
+ 4: { f: '=SUM(Orders[amount])' },
+ },
+ },
+ },
+ sheet2: {
+ id: 'sheet2',
+ name: 'Sheet2',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {
+ 2: {
+ 0: { f: '=SUM(Orders)' },
+ },
+ 3: {
+ 0: { f: '=SUM(Orders[amount])' },
+ },
+ 4: {
+ 0: { f: '=SUM(Orders[amount],Orders[tax])' },
+ },
+ },
+ },
+ },
+ styles: {},
+ };
+}
+
+function createControllerTestBed() {
+ const dependencies: Dependency[] = [
+ [ICalculateFormulaService, { useClass: CalculateFormulaService }],
+ [Lexer],
+ [IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],
+ [IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }],
+ [IFormulaRuntimeService, { useClass: FormulaRuntimeService }],
+ [IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],
+ [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],
+ [IFormulaDependencyGenerator, { useClass: FormulaDependencyGenerator }],
+ [Interpreter],
+ [AstTreeBuilder],
+ [AstRootNodeFactory],
+ [FunctionNodeFactory],
+ [LambdaNodeFactory],
+ [LambdaParameterNodeFactory],
+ [OperatorNodeFactory],
+ [PrefixNodeFactory],
+ [ReferenceNodeFactory],
+ [SuffixNodeFactory],
+ [UnionNodeFactory],
+ [ValueNodeFactory],
+ [ISuperTableService, { useClass: SuperTableService }],
+ [TableManager],
+ [SheetTableService],
+ [SheetTableFormulaController],
+ [SheetTableRefRangeController],
+ [UpdateFormulaController],
+ ];
+
+ return createFacadeTestBed(createWorkbookData(), dependencies);
+}
+
+describe('Sheet table formula integration', () => {
+ let testBed: ReturnType<typeof createControllerTestBed>;
+ let commandService: ICommandService;
+ let formulaDataModel: FormulaDataModel;
+ let calculate: (formula: string, row?: number, column?: number, sheetId?: string) => string | number | boolean | null | (string | number | boolean | null)[][];
+
+ function getFormula(unitId: string, sheetId: string, row: number, column: number) {
+ return formulaDataModel.getFormulaData()[unitId]?.[sheetId]?.[row]?.[column]?.f;
+ }
+
+ function getCellFormula(sheetId: string, row: number, column: number) {
+ return testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId(sheetId)
+ ?.getRange(row, column, row, column)
+ .getValue()
+ ?.f;
+ }
+
+ function getAllUnitData() {
+ const workbook = testBed.injector.get(IUniverInstanceService).getUnit<Workbook>('test')!;
+ const sheetData: IUnitData[string] = {};
+
+ workbook.getSheets().forEach((sheet) => {
+ const sheetConfig = sheet.getConfig();
+ sheetData[sheet.getSheetId()] = {
+ cellData: new ObjectMatrix(sheetConfig.cellData),
+ rowCount: sheetConfig.rowCount,
+ columnCount: sheetConfig.columnCount,
+ rowData: sheetConfig.rowData ?? {},
+ columnData: sheetConfig.columnData ?? {},
+ };
+ });
+
+ return {
+ [workbook.getUnitId()]: sheetData,
+ };
+ }
+
+ function calculateCellFormula(unitId: string, sheetId: string, row: number, column: number) {
+ const formula = getFormula(unitId, sheetId, row, column);
+ expect(formula).toBeDefined();
+
+ return calculate(formula!, row, column, sheetId);
+ }
+
+ beforeEach(() => {
+ testBed = createControllerTestBed();
+ commandService = testBed.injector.get(ICommandService);
+ formulaDataModel = testBed.injector.get(FormulaDataModel);
+
+ commandService.registerCommand(RemoveRowCommand);
+ commandService.registerCommand(RemoveColCommand);
+ commandService.registerCommand(MoveRangeCommand);
+ commandService.registerCommand(MoveRangeMutation);
+ commandService.registerCommand(RemoveRowByRangeCommand);
+ commandService.registerCommand(RemoveColByRangeCommand);
+ commandService.registerCommand(RemoveRowMutation);
+ commandService.registerCommand(RemoveColMutation);
+ commandService.registerCommand(InsertRowMutation);
+ commandService.registerCommand(InsertColMutation);
+ commandService.registerCommand(AddSheetTableMutation);
+ commandService.registerCommand(DeleteSheetTableCommand);
+ commandService.registerCommand(DeleteSheetTableMutation);
+ commandService.registerCommand(SetSheetTableCommand);
+ commandService.registerCommand(SetSheetTableMutation);
+ commandService.registerCommand(SheetTableInsertColumnAtCommand);
+ commandService.registerCommand(SheetTableRemoveColumnAtCommand);
+ commandService.registerCommand(SetSuperTableMutation);
+ commandService.registerCommand(RemoveSuperTableMutation);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetFormulaDataMutation);
+ commandService.registerCommand(SetArrayFormulaDataMutation);
+
+ testBed.injector.get(SheetTableFormulaController);
+ testBed.injector.get(SheetTableRefRangeController);
+ testBed.injector.get(UpdateFormulaController);
+
+ commandService.syncExecuteCommand(AddSheetTableMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ name: 'Orders',
+ range: {
+ startRow: 0,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 2,
+ },
+ header: ['product', 'amount', 'tax'],
+ options: {
+ columns: [
+ { id: 'product-column', displayName: 'product' },
+ { id: 'amount-column', displayName: 'amount' },
+ { id: 'tax-column', displayName: 'tax' },
+ ],
+ },
+ });
+
+ const functionService = testBed.injector.get(IFunctionService);
+ const mathFunctions = functionMath as Array<[new (name: string) => BaseFunction, string]>;
+ functionService.registerExecutors(...mathFunctions.map(([FunctionCtor, name]) => new FunctionCtor(name)));
+
+ calculate = (formula: string, row = 0, column = 0, sheetId = 'sheet1') => {
+ const workbook = testBed.injector.get(IUniverInstanceService).getUnit<Workbook>('test')!;
+ const worksheet = workbook.getSheetBySheetId(sheetId)!;
+ const formulaCurrentConfigService = testBed.injector.get(IFormulaCurrentConfigService);
+ const formulaRuntimeService = testBed.injector.get(IFormulaRuntimeService);
+
+ formulaCurrentConfigService.load({
+ formulaData: formulaDataModel.getFormulaData(),
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: false,
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtySuperTableMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ excludedCell: {},
+ allUnitData: getAllUnitData(),
+ });
+ formulaRuntimeService.setCurrent(row, column, worksheet.getRowCount(), worksheet.getColumnCount(), sheetId, workbook.getUnitId());
+
+ const lexerNode = testBed.injector.get(Lexer).treeBuilder(formula);
+ if (!(lexerNode instanceof LexerNode)) {
+ throw new TypeError(`Failed to parse formula: ${formula}`);
+ }
+ const astNode = testBed.injector.get(AstTreeBuilder).parse(lexerNode);
+ const result = testBed.injector.get(Interpreter).execute(generateExecuteAstNodeData(astNode as BaseAstNode));
+
+ return getObjectValue(result);
+ };
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ testBed?.univer.dispose();
+ });
+
+ it('should sync table formulas when a table is renamed, undone, and redone', async () => {
+ expect(await commandService.executeCommand(SetSheetTableCommand.id, {
+ unitId: 'test',
+ tableId: 'orders-table',
+ name: 'Sales',
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(Sales[amount])');
+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(Sales[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(Orders[amount])');
+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(Orders[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(Sales[amount])');
+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(Sales[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+ });
+
+ it('should sync wrapped repeated table references when a table is renamed, removed, and has a referenced column removed', async () => {
+ expect(calculateCellFormula('test', 'sheet1', 6, 4)).toBe(120);
+
+ expect(await commandService.executeCommand(SetSheetTableCommand.id, {
+ unitId: 'test',
+ tableId: 'orders-table',
+ name: 'Sales',
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(Sales[amount],Sales[amount])');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(Sales[amount],Sales[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 6, 4)).toBe(120);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(Sales[amount],Sales[amount])');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(Sales[amount],Sales[amount])');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+
+ expect(await commandService.executeCommand(SheetTableRemoveColumnAtCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ index: 1,
+ count: 1,
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+
+ expect(await commandService.executeCommand(DeleteSheetTableCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(Orders[amount],Orders[amount])');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+ expect(getCellFormula('sheet1', 6, 4)).toBe('=SUM(#REF!,#REF!)');
+ });
+
+ it('should sync multiple table formulas across sheets when a table changes, then undo and redo', async () => {
+ expect(calculateCellFormula('test', 'sheet1', 7, 4)).toBe(60);
+ expect(calculateCellFormula('test', 'sheet2', 3, 0)).toBe(60);
+ expect(calculateCellFormula('test', 'sheet2', 4, 0)).toBe(66);
+
+ expect(await commandService.executeCommand(SetSheetTableCommand.id, {
+ unitId: 'test',
+ tableId: 'orders-table',
+ name: 'Sales',
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(Sales[amount])');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(Sales[amount])');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(Sales[amount],Sales[tax])');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(Orders[amount])');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(Orders[amount])');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(Orders[amount],Orders[tax])');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(Sales[amount])');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(Sales[amount])');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(Sales[amount],Sales[tax])');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(Orders[amount])');
+
+ expect(await commandService.executeCommand(SheetTableRemoveColumnAtCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ index: 1,
+ count: 1,
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(#REF!,Orders[tax])');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(Orders[amount])');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(Orders[amount])');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(Orders[amount],Orders[tax])');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(#REF!,Orders[tax])');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(Orders[amount])');
+
+ expect(await commandService.executeCommand(DeleteSheetTableCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(#REF!,#REF!)');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(Orders[amount])');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(Orders[amount])');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(Orders[amount],Orders[tax])');
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 7, 4)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 3, 0)).toBe('=SUM(#REF!)');
+ expect(getFormula('test', 'sheet2', 4, 0)).toBe('=SUM(#REF!,#REF!)');
+ });
+
+ it('should recalculate table formulas when table columns shrink, then undo and redo the column insertion', async () => {
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(66);
+
+ expect(await commandService.executeCommand(SheetTableRemoveColumnAtCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ index: 2,
+ count: 1,
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getCellFormula('sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(60);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getCellFormula('sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(66);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getCellFormula('sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(60);
+ });
+
+ it('should recalculate table formulas when table columns are inserted, undone, and redone', async () => {
+ const tableManager = testBed.injector.get(TableManager);
+ const getTableRange = () => tableManager.getTableById('test', 'orders-table')?.getRange();
+
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(66);
+ expect(getTableRange()).toMatchObject({ startColumn: 0, endColumn: 2 });
+
+ expect(await commandService.executeCommand(SheetTableInsertColumnAtCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ index: 2,
+ count: 1,
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getCellFormula('sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getTableRange()).toMatchObject({ startColumn: 0, endColumn: 3 });
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(66);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getCellFormula('sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getTableRange()).toMatchObject({ startColumn: 0, endColumn: 2 });
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(66);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getCellFormula('sheet2', 2, 0)).toBe('=SUM(Orders)');
+ expect(getTableRange()).toMatchObject({ startColumn: 0, endColumn: 3 });
+ expect(calculateCellFormula('test', 'sheet2', 2, 0)).toBe(66);
+ });
+
+ it('should recalculate table column formulas when worksheet rows are removed, undone, and redone', async () => {
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+
+ expect(await commandService.executeCommand(RemoveRowCommand.id, {
+ range: {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 0,
+ endColumn: 19,
+ rangeType: RANGE_TYPE.ROW,
+ },
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 4, 4)).toBe('=SUM(Orders[amount])');
+ expect(getCellFormula('sheet1', 4, 4)).toBe('=SUM(Orders[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 4, 4)).toBe(40);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 4, 4)).toBe('=SUM(Orders[amount])');
+ expect(getCellFormula('sheet1', 4, 4)).toBe('=SUM(Orders[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 4, 4)).toBe(40);
+ });
+
+ it('should sync table column formulas when worksheet columns are removed, undone, and redone', async () => {
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+
+ expect(await commandService.executeCommand(RemoveColCommand.id, {
+ range: {
+ startRow: 0,
+ endRow: 19,
+ startColumn: 1,
+ endColumn: 1,
+ rangeType: RANGE_TYPE.COLUMN,
+ },
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 5, 3)).toBe('=SUM(#REF!)');
+ expect(getCellFormula('sheet1', 5, 3)).toBe('=SUM(#REF!)');
+ expect(calculate('=SUM(#REF!)', 5, 3)).toBe('#REF!');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(Orders[amount])');
+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(Orders[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 5, 3)).toBe('=SUM(#REF!)');
+ expect(getCellFormula('sheet1', 5, 3)).toBe('=SUM(#REF!)');
+ expect(calculate('=SUM(#REF!)', 5, 3)).toBe('#REF!');
+ });
+
+ it('should sync table formulas when a table is deleted, undone, and redone', async () => {
+ expect(await commandService.executeCommand(DeleteSheetTableCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'orders-table',
+ })).toBe(true);
+
+ expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(#REF!)');
+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(#REF!)');
+ expect(calculate('=SUM(#REF!)', 5, 4)).toBe('#REF!');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(Orders[amount])');
+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(Orders[amount])');
+ expect(calculateCellFormula('test', 'sheet1', 5, 4)).toBe(60);
+
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(getFormula('test', 'sheet1', 5, 4)).toBe('=SUM(#REF!)');
+ expect(getCellFormula('sheet1', 5, 4)).toBe('=SUM(#REF!)');
+ expect(calculate('=SUM(#REF!)', 5, 4)).toBe('#REF!');
+ });
+
+ it('should rewrite formulas when a referenced table is renamed', async () => {
+ const sheetInterceptorService = testBed.injector.get(SheetInterceptorService);
+ const renameTableResult = sheetInterceptorService.onCommandExecute({
+ id: 'sheet.command.set-table-config',
+ params: {
+ unitId: 'test',
+ tableId: 'table-1',
+ name: 'Sales',
+ oldTableName: 'Orders',
+ },
+ });
+
+ for (const mutation of renameTableResult.redos) {
+ await commandService.executeCommand(mutation.id, mutation.params);
+ }
+
+ const values = testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(5, 4, 5, 4)
+ .getValues() as Array<Array<Nullable<ICellData>>>;
+
+ expect(values).toEqual([[{ f: '=SUM(Sales[amount])' }]]);
+
+ const stringLiteralValues = testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(5, 5, 5, 5)
+ .getValues() as Array<Array<Nullable<ICellData>>>;
+
+ expect(stringLiteralValues).toEqual([[{ f: '="Orders[amount]"' }]]);
+ });
+
+ it('should rewrite formulas when a referenced table is removed', async () => {
+ const sheetInterceptorService = testBed.injector.get(SheetInterceptorService);
+ const removeTableResult = sheetInterceptorService.onCommandExecute({
+ id: 'sheet.command.delete-table',
+ params: {
+ unitId: 'test',
+ tableId: 'table-1',
+ tableName: 'Orders',
+ },
+ });
+
+ for (const mutation of removeTableResult.redos) {
+ await commandService.executeCommand(mutation.id, mutation.params);
+ }
+
+ const values = testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(5, 4, 5, 4)
+ .getValues() as Array<Array<Nullable<ICellData>>>;
+
+ expect(values).toEqual([[{ f: '=SUM(#REF!)' }]]);
+
+ const stringLiteralValues = testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(5, 5, 5, 5)
+ .getValues() as Array<Array<Nullable<ICellData>>>;
+
+ expect(stringLiteralValues).toEqual([[{ f: '="Orders[amount]"' }]]);
+ });
+
+ it('should rewrite numeric table column references when the referenced table column is removed', async () => {
+ const sheetInterceptorService = testBed.injector.get(SheetInterceptorService);
+ const removeTableColumnResult = sheetInterceptorService.onCommandExecute({
+ id: 'sheet.command.table-remove-column-at',
+ params: {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'table-1',
+ tableName: 'Table',
+ removedColumnNames: ['1'],
+ },
+ });
+
+ for (const mutation of removeTableColumnResult.redos) {
+ await commandService.executeCommand(mutation.id, mutation.params);
+ }
+
+ const values = testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(5, 6, 5, 8)
+ .getValues() as Array<Array<Nullable<ICellData>>>;
+
+ expect(values).toEqual([[
+ { f: '=#REF!' },
+ { f: '=Table[2]' },
+ { f: '="Table[1]"' },
+ ]]);
+ });
+
+ it('should move formula cells when worksheet column removal deletes a referenced table column', async () => {
+ const sheetInterceptorService = testBed.injector.get(SheetInterceptorService);
+ const removeTableColumnResult = sheetInterceptorService.onCommandExecute({
+ id: 'sheet.command.table-remove-col',
+ params: {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ tableId: 'table-1',
+ tableName: 'Table',
+ range: { startRow: 0, endRow: 19, startColumn: 0, endColumn: 0 },
+ removedColumnNames: ['1'],
+ },
+ });
+
+ for (const mutation of removeTableColumnResult.redos) {
+ await commandService.executeCommand(mutation.id, mutation.params);
+ }
+
+ const values = testBed.injector
+ .get(IUniverInstanceService)
+ .getUnit<Workbook>('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(5, 5, 5, 8)
+ .getValues() as Array<Array<Nullable<ICellData>>>;
+
+ expect(values).toEqual([[{ f: '=#REF!' }, { f: '=Table[2]' }, { f: '="Table[1]"' }, null]]);
+ });
+});
diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-ref-range.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-ref-range.controller.spec.ts
index cf8d518bd6..a4de728daa 100644
--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-ref-range.controller.spec.ts
+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-ref-range.controller.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { InsertRowMutation } from '@univerjs/sheets';
+import { InsertRowMutation, RemoveColCommand } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
import { SheetTableRefRangeController } from '../sheet-table-ref-range.controller';
@@ -75,4 +75,88 @@ describe('SheetTableRefRangeController', () => {
controller.dispose();
});
+
+ it('should include table formula reference mutations when worksheet column removal deletes table columns', () => {
+ let interceptCommandConfig: any;
+ const tableColumn = {
+ toJSON: () => ({ id: 'c1', displayName: '1' }),
+ };
+ const table = {
+ getId: () => 't1',
+ getRange: () => ({ startRow: 0, endRow: 5, startColumn: 1, endColumn: 3 }),
+ getTableInfo: () => ({ name: 'Table' }),
+ getTableColumnByIndex: vi.fn(() => tableColumn),
+ toJSON: () => ({
+ id: 't1',
+ name: 'Table',
+ range: { startRow: 0, endRow: 5, startColumn: 1, endColumn: 3 },
+ options: { showHeader: true },
+ filters: {},
+ columns: [{ id: 'c1', displayName: '1' }, { id: 'c2', displayName: '2' }, { id: 'c3', displayName: '3' }],
+ }),
+ };
+ const workbook = {
+ getUnitId: () => 'u1',
+ getActiveSheet: () => ({ getSheetId: () => 's1' }),
+ };
+ const onCommandExecute = vi.fn(() => ({
+ preRedos: [{ id: 'formula.pre-redo', params: {} }],
+ redos: [{ id: 'formula.redo', params: {} }],
+ preUndos: [{ id: 'formula.pre-undo', params: {} }],
+ undos: [{ id: 'formula.undo', params: {} }],
+ }));
+
+ const controller = new SheetTableRefRangeController(
+ { onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })) } as any,
+ {} as any,
+ { getCurrentUnitOfType: () => workbook } as any,
+ {} as any,
+ {
+ interceptCommand: vi.fn((config: any) => {
+ interceptCommandConfig = config;
+ return { dispose: vi.fn() };
+ }),
+ onCommandExecute,
+ } as any,
+ {
+ getTablesBySubunitId: vi.fn(() => [table]),
+ } as any,
+ { t: () => 'Column' } as any
+ );
+
+ const result = interceptCommandConfig.getMutations({
+ id: RemoveColCommand.id,
+ params: {
+ range: { startRow: 0, endRow: 99, startColumn: 1, endColumn: 1 },
+ },
+ });
+
+ expect(onCommandExecute).toHaveBeenCalledWith({
+ id: 'sheet.command.table-remove-col',
+ params: {
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ tableName: 'Table',
+ range: { startRow: 0, endRow: 99, startColumn: 1, endColumn: 1 },
+ removedColumnNames: ['1'],
+ },
+ });
+ expect(result.preRedos.map((mutation: any) => mutation.id)).toEqual([]);
+ expect(result.redos.map((mutation: any) => mutation.id)).toEqual([
+ 'formula.pre-redo',
+ 'formula.redo',
+ 'sheet.mutation.set-sheet-table',
+ ]);
+ expect(result.preUndos.map((mutation: any) => mutation.id)).toEqual([
+ 'sheet.mutation.delete-table',
+ ]);
+ expect(result.undos.map((mutation: any) => mutation.id)).toEqual([
+ 'sheet.mutation.add-table',
+ 'formula.pre-undo',
+ 'formula.undo',
+ ]);
+
+ controller.dispose();
+ });
});
diff --git a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
index f447170969..95637a6ef4 100644
--- a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
+++ b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts
@@ -72,12 +72,12 @@ export class SheetTableFormulaController extends Disposable {
if (!table) {
return;
}
- this._updateSuperTable(unitId, table);
+ this._updateSuperTable(unitId, table, oldTableName);
})
);
}
- private _updateSuperTable(unitId: string, table: Table) {
+ private _updateSuperTable(unitId: string, table: Table, oldTableName?: string) {
const tableInfo = table.getTableInfo();
const name = tableInfo.name;
const columns = tableInfo.columns;
@@ -88,6 +88,7 @@ export class SheetTableFormulaController extends Disposable {
this._commandService.executeCommand<ISetSuperTableMutationParam>(SetSuperTableMutation.id, {
unitId,
tableName: name,
+ oldTableName,
reference: {
range: tableInfo.range,
sheetId: tableInfo.subUnitId,
diff --git a/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts b/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
index cea810a7a9..311f0c0eec 100644
--- a/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
+++ b/packages/sheets-table/src/controllers/sheet-table-ref-range.controller.ts
@@ -19,7 +19,7 @@
import type { IMutationInfo, Workbook } from '@univerjs/core';
import type { IInsertColCommandParams, IInsertRowCommandParams, IInsertRowMutationParams, IRemoveRowColCommandParams } from '@univerjs/sheets';
-import type { ITableColumnJson } from '../types/type';
+import type { ITableColumnJson, ITableJson } from '../types/type';
import { Disposable, ICommandService, Inject, Injector, IUniverInstanceService, LocaleService, Rectangle } from '@univerjs/core';
import { getSheetCommandTarget, InsertColCommand, InsertColMutation, InsertRowCommand, InsertRowMutation, RefRangeService, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, SheetInterceptorService } from '@univerjs/sheets';
import { AddSheetTableMutation } from '../commands/mutations/add-sheet-table.mutation';
@@ -29,6 +29,9 @@ import { TableManager } from '../model/table-manager';
import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../types/type';
import { convertCellDataToString, getColumnName } from '../util';
+const SHEET_TABLE_REMOVE_COL_COMMAND_ID = 'sheet.command.table-remove-col';
+const DELETE_SHEET_TABLE_COMMAND_ID = 'sheet.command.delete-table';
+
export class SheetTableRefRangeController extends Disposable {
constructor(
@Inject(ICommandService) private readonly _commandService: ICommandService,
@@ -48,6 +51,7 @@ export class SheetTableRefRangeController extends Disposable {
private _initCommandInterceptor() {
const self = this;
this._sheetInterceptorService.interceptCommand({
+ priority: -1,
getMutations(commandInfo) {
const defaultReturn = { redos: [], undos: [] };
const { id, params } = commandInfo;
@@ -318,6 +322,17 @@ export class SheetTableRefRangeController extends Disposable {
const tableRange = table.getRange();
if (Rectangle.intersects(tableRange, range)) {
if (range.startColumn <= tableRange.startColumn && range.endColumn >= tableRange.endColumn) {
+ const tableInfo = table.getTableInfo();
+ const formulaMutations = this._sheetInterceptorService.onCommandExecute({
+ id: DELETE_SHEET_TABLE_COMMAND_ID,
+ params: {
+ unitId,
+ subUnitId,
+ tableId: table.getId(),
+ tableName: tableInfo.name,
+ },
+ });
+ preRedos.push(...(formulaMutations.preRedos ?? []), ...formulaMutations.redos);
preRedos.push({
id: DeleteSheetTableMutation.id,
params: {
@@ -349,7 +364,9 @@ export class SheetTableRefRangeController extends Disposable {
options: tableJson.options,
},
});
+ undos.push(...(formulaMutations.preUndos ?? []), ...formulaMutations.undos);
} else if (range.startColumn <= tableRange.startColumn && range.endColumn >= tableRange.startColumn) {
+ const tableJson = table.toJSON();
const removeColumnCount = range.endColumn - tableRange.startColumn + 1;
redos.push({
id: SetSheetTableMutation.id,
@@ -374,24 +391,18 @@ export class SheetTableRefRangeController extends Disposable {
columns.push(column.toJSON());
}
}
- undos.push({
- id: SetSheetTableMutation.id,
- params: {
- unitId,
- subUnitId,
- tableId: table.getId(),
- config: {
- rowColOperation: {
- operationType: IRangeOperationTypeEnum.Insert,
- rowColType: IRowColTypeEnum.Col,
- index: tableRange.startColumn,
- count: removeColumnCount,
- columnsJson: columns,
- },
- },
- },
+ preUndos.push(this._getDeleteTableMutation(unitId, subUnitId, table.getId()));
+ undos.push(this._getAddTableMutation(unitId, subUnitId, tableJson));
+ this._appendTableColumnFormulaMutations(redos, undos, {
+ unitId,
+ subUnitId,
+ tableId: table.getId(),
+ tableName: table.getTableInfo().name,
+ range,
+ columns,
});
} else if (range.startColumn > tableRange.startColumn && range.endColumn > tableRange.endColumn) {
+ const tableJson = table.toJSON();
const removeColumnCount = tableRange.endColumn - range.startColumn + 1;
redos.push({
id: SetSheetTableMutation.id,
@@ -418,25 +429,18 @@ export class SheetTableRefRangeController extends Disposable {
columns.push(column.toJSON());
}
}
-
- undos.push({
- id: SetSheetTableMutation.id,
- params: {
- unitId,
- subUnitId,
- tableId: table.getId(),
- config: {
- rowColOperation: {
- operationType: IRangeOperationTypeEnum.Insert,
- rowColType: IRowColTypeEnum.Col,
- index: range.startColumn,
- count: removeColCount,
- columnsJson: columns,
- },
- },
- },
+ preUndos.push(this._getDeleteTableMutation(unitId, subUnitId, table.getId()));
+ undos.push(this._getAddTableMutation(unitId, subUnitId, tableJson));
+ this._appendTableColumnFormulaMutations(redos, undos, {
+ unitId,
+ subUnitId,
+ tableId: table.getId(),
+ tableName: table.getTableInfo().name,
+ range,
+ columns,
});
} else if (range.startColumn > tableRange.startColumn && range.endColumn <= tableRange.endColumn) {
+ const tableJson = table.toJSON();
redos.push({
id: SetSheetTableMutation.id,
params: {
@@ -462,22 +466,15 @@ export class SheetTableRefRangeController extends Disposable {
columns.push(column.toJSON());
}
}
- undos.push({
- id: SetSheetTableMutation.id,
- params: {
- unitId,
- subUnitId,
- tableId: table.getId(),
- config: {
- rowColOperation: {
- operationType: IRangeOperationTypeEnum.Insert,
- rowColType: IRowColTypeEnum.Col,
- index: range.startColumn,
- count: removeColCount,
- columnsJson: columns,
- },
- },
- },
+ preUndos.push(this._getDeleteTableMutation(unitId, subUnitId, table.getId()));
+ undos.push(this._getAddTableMutation(unitId, subUnitId, tableJson));
+ this._appendTableColumnFormulaMutations(redos, undos, {
+ unitId,
+ subUnitId,
+ tableId: table.getId(),
+ tableName: table.getTableInfo().name,
+ range,
+ columns,
});
}
}
@@ -486,6 +483,71 @@ export class SheetTableRefRangeController extends Disposable {
return { undos, redos, preRedos, preUndos };
}
+ private _getDeleteTableMutation(unitId: string, subUnitId: string, tableId: string): IMutationInfo {
+ return {
+ id: DeleteSheetTableMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ tableId,
+ },
+ };
+ }
+
+ private _getAddTableMutation(unitId: string, subUnitId: string, tableJson: ITableJson): IMutationInfo {
+ const header = tableJson.columns.map((column) => column.displayName);
+
+ return {
+ id: AddSheetTableMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ tableId: tableJson.id,
+ name: tableJson.name,
+ header,
+ range: tableJson.range,
+ options: {
+ ...tableJson.options,
+ columns: tableJson.columns,
+ filters: tableJson.filters.tableColumnFilterList,
+ },
+ },
+ };
+ }
+
+ private _appendTableColumnFormulaMutations(
+ redos: IMutationInfo[],
+ undos: IMutationInfo[],
+ info: {
+ unitId: string;
+ subUnitId: string;
+ tableId: string;
+ tableName: string;
+ range: IRemoveRowColCommandParams['range'];
+ columns: ITableColumnJson[];
+ }
+ ) {
+ const removedColumnNames = info.columns.map((column) => column.displayName);
+ if (!removedColumnNames.length) {
+ return;
+ }
+
+ const formulaMutations = this._sheetInterceptorService.onCommandExecute({
+ id: SHEET_TABLE_REMOVE_COL_COMMAND_ID,
+ params: {
+ unitId: info.unitId,
+ subUnitId: info.subUnitId,
+ tableId: info.tableId,
+ tableName: info.tableName,
+ range: info.range,
+ removedColumnNames,
+ },
+ });
+
+ redos.splice(Math.max(redos.length - 1, 0), 0, ...(formulaMutations.preRedos ?? []), ...formulaMutations.redos);
+ undos.push(...(formulaMutations.preUndos ?? []), ...formulaMutations.undos);
+ }
+
private _initCommandListener() {
this._commandService.onCommandExecuted((commandInfo) => {
if (commandInfo.id === InsertRowMutation.id) {
diff --git a/packages/sheets/src/basics/split-range-text.ts b/packages/sheets/src/basics/split-range-text.ts
index 72be1fa145..01c90b8776 100644
--- a/packages/sheets/src/basics/split-range-text.ts
+++ b/packages/sheets/src/basics/split-range-text.ts
@@ -15,7 +15,7 @@
*/
import type { ICellData, IDocumentData, IRange, Nullable, Worksheet } from '@univerjs/core';
-import { CellValueType, Range } from '@univerjs/core';
+import { CellValueType, escapeRegExp, Range } from '@univerjs/core';
/**
* The default delimiter to split the text.
@@ -139,10 +139,6 @@ function getDelimiterRegexItem(delimiter: SplitDelimiterEnum, treatMultipleDelim
return new RegExp(allStr);
}
-function escapeRegExp(str: string) {
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-}
-
const getStringFromDataStream = (data: IDocumentData): string => {
const dataStream = data.body?.dataStream.replace(/\r\n$/, '') || '';
return dataStream;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 15e03dd35b..96e5a4e928 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2468,6 +2468,12 @@ importers:
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/sheets-formula':
+ specifier: workspace:*
+ version: link:../sheets-formula
rxjs:
specifier: ^7.8.2
version: 7.8.2