Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
chore(formula): defined name ref range move (#3488)
Dushusir69ffa5bef4b7
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 685300ab0d..860afdc5e7 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -138,6 +138,7 @@ export { type IUser, UserManagerService } from './services/user-manager/user-manexport * from './shared';export { isBlackColor, isWhiteColor } from './shared/color/color-kit';export { cellToRange } from './shared/common';+export { getIntersectRange } from './shared/range';export { nameCharacterCheck } from './shared/name';export { fromCallback, takeAfter } from './shared/rxjs';export { awaitTime } from './shared/timer';diff --git a/packages/core/src/shared/__tests__/range.spec.ts b/packages/core/src/shared/__tests__/range.spec.tsindex 09a5dd3b74..1bd6856cc7 100644--- a/packages/core/src/shared/__tests__/range.spec.ts+++ b/packages/core/src/shared/__tests__/range.spec.ts@@ -16,8 +16,8 @@import { describe, expect, it } from 'vitest';-import { AbsoluteRefType } from '../../sheets/typedef';-import { mergeHorizontalRanges, mergeRanges, mergeVerticalRanges, moveRangeByOffset, splitIntoGrid } from '../range';+import { AbsoluteRefType, RANGE_TYPE } from '../../sheets/typedef';+import { getIntersectRange, mergeHorizontalRanges, mergeRanges, mergeVerticalRanges, moveRangeByOffset, splitIntoGrid } from '../range';import type { IRange } from '../../sheets/typedef';const stringifyRanges = (ranges: IRange[]) => {@@ -465,3 +465,370 @@ describe('mergeRanges', () => {expect(stringifyRanges(mergeRanges(input))).toEqual(stringifyRanges(expected));});});++describe('test getIntersectRange', () => {+ it('normal x normal, gets normal', () => {+ const rect1 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ };++ const rect2 = {+ startRow: 2,+ startColumn: 2,+ endRow: 4,+ endColumn: 4,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: 2,+ startColumn: 2,+ endRow: 3,+ endColumn: 3,+ rangeType: RANGE_TYPE.NORMAL,+ });++ const rect3 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ };++ const rect4 = {+ startRow: 4,+ startColumn: 4,+ endRow: 5,+ endColumn: 5,+ };++ expect(getIntersectRange(rect3, rect4)).toBeNull();+ });++ it('normal x row, gets normal', () => {+ const rect1 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ };++ const rect2 = {+ startRow: 3,+ startColumn: Number.NaN,+ endRow: 4,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: 3,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ rangeType: RANGE_TYPE.NORMAL,+ });++ const rect3 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ };++ const rect4 = {+ startRow: 4,+ startColumn: 0,+ endRow: 5,+ endColumn: 999,+ rangeType: RANGE_TYPE.ROW,+ };++ expect(getIntersectRange(rect3, rect4)).toBeNull();+ });++ it('normal x column, gets normal', () => {+ const rect1 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ };++ const rect2 = {+ startRow: Number.NaN,+ startColumn: 3,+ endRow: Number.NaN,+ endColumn: 4,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: 1,+ startColumn: 3,+ endRow: 3,+ endColumn: 3,+ rangeType: RANGE_TYPE.NORMAL,+ });++ const rect3 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ };++ const rect4 = {+ startRow: 0,+ startColumn: 4,+ endRow: 999,+ endColumn: 5,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(getIntersectRange(rect3, rect4)).toBeNull();+ });++ it('normal x all, gets normal', () => {+ const rect1 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ };++ const rect2 = {+ startRow: Number.NaN,+ startColumn: Number.NaN,+ endRow: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ rangeType: RANGE_TYPE.NORMAL,+ });++ const rect3 = {+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ rangeType: RANGE_TYPE.NORMAL,+ };++ const rect4 = {+ startRow: 0,+ startColumn: 0,+ endRow: 999,+ endColumn: 19,+ rangeType: RANGE_TYPE.ALL,+ };++ expect(getIntersectRange(rect3, rect4)).toStrictEqual({+ startRow: 1,+ startColumn: 1,+ endRow: 3,+ endColumn: 3,+ rangeType: RANGE_TYPE.NORMAL,+ });+ });++ it('row x row, gets row', () => {+ const rect1 = {+ startRow: 1,+ startColumn: Number.NaN,+ endRow: 3,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ const rect2 = {+ startRow: 2,+ startColumn: 0,+ endRow: 4,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: 2,+ startColumn: 0,+ endRow: 3,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ });++ const rect3 = {+ startRow: 1,+ startColumn: Number.NaN,+ endRow: 3,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ const rect4 = {+ startRow: 4,+ startColumn: 0,+ endRow: 5,+ endColumn: 999,+ rangeType: RANGE_TYPE.ROW,+ };++ expect(getIntersectRange(rect3, rect4)).toBeNull();+ });++ it('row x column, gets normal', () => {+ const rect1 = {+ startRow: 1,+ startColumn: Number.NaN,+ endRow: 3,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ const rect2 = {+ startRow: Number.NaN,+ startColumn: 2,+ endRow: Number.NaN,+ endColumn: 4,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: 1,+ startColumn: 2,+ endRow: 3,+ endColumn: 4,+ rangeType: RANGE_TYPE.NORMAL,+ });+ });++ it('row x all, gets row', () => {+ const rect1 = {+ startRow: 1,+ startColumn: Number.NaN,+ endRow: 3,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ const rect2 = {+ startRow: Number.NaN,+ startColumn: Number.NaN,+ endRow: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: 1,+ startColumn: Number.NaN,+ endRow: 3,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ });+ });++ it('column x column, gets column', () => {+ const rect1 = {+ startRow: Number.NaN,+ startColumn: 1,+ endRow: Number.NaN,+ endColumn: 3,+ rangeType: RANGE_TYPE.COLUMN,+ };++ const rect2 = {+ startRow: Number.NaN,+ startColumn: 2,+ endRow: Number.NaN,+ endColumn: 4,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: Number.NaN,+ startColumn: 2,+ endRow: Number.NaN,+ endColumn: 3,+ rangeType: RANGE_TYPE.COLUMN,+ });++ const rect3 = {+ startRow: Number.NaN,+ startColumn: 1,+ endRow: Number.NaN,+ endColumn: 3,+ rangeType: RANGE_TYPE.COLUMN,+ };++ const rect4 = {+ startRow: 0,+ startColumn: 4,+ endRow: 999,+ endColumn: 5,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(getIntersectRange(rect3, rect4)).toBeNull();+ });++ it('column x all, gets column', () => {+ const rect1 = {+ startRow: Number.NaN,+ startColumn: 1,+ endRow: Number.NaN,+ endColumn: 3,+ rangeType: RANGE_TYPE.COLUMN,+ };++ const rect2 = {+ startRow: Number.NaN,+ startColumn: Number.NaN,+ endRow: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: Number.NaN,+ startColumn: 1,+ endRow: Number.NaN,+ endColumn: 3,+ rangeType: RANGE_TYPE.COLUMN,+ });+ });++ it('all x all, gets all', () => {+ const rect1 = {+ startRow: Number.NaN,+ startColumn: Number.NaN,+ endRow: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ const rect2 = {+ startRow: Number.NaN,+ startColumn: Number.NaN,+ endRow: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ expect(getIntersectRange(rect1, rect2)).toStrictEqual({+ startRow: Number.NaN,+ startColumn: Number.NaN,+ endRow: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ });+ });+});diff --git a/packages/core/src/shared/range.ts b/packages/core/src/shared/range.tsindex 3dec90bfbd..4ac7a7bd27 100644--- a/packages/core/src/shared/range.ts+++ b/packages/core/src/shared/range.ts@@ -14,9 +14,10 @@* limitations under the License.*/-import { AbsoluteRefType } from '../sheets/typedef';+import { AbsoluteRefType, RANGE_TYPE } from '../sheets/typedef';import { Rectangle } from './rectangle';import type { IRange } from '../sheets/typedef';+import type { Nullable } from './types';export function moveRangeByOffset(range: IRange, refOffsetX: number, refOffsetY: number, ignoreAbsolute = false): IRange {let newRange = { ...range };@@ -227,3 +228,158 @@ export function multiSubtractSingleRange(ranges: IRange[], toDelete: IRange) {});return Rectangle.mergeRanges(res);};++ /**+ * Computes the intersection of two ranges.+ * If there is an overlap between the two ranges, returns a new range representing the intersection.+ * If there is no overlap, returns null.+ *+ * @param src - The source range.+ * @param target - The target range.+ * @returns The intersected range or null if there is no intersection.+ */+export function getIntersectRange(src: IRange, target: IRange): Nullable<IRange> {+ const rowOverlap = getOverlap1D(+ src.startRow,+ src.endRow,+ target.startRow,+ target.endRow+ );+ const colOverlap = getOverlap1D(+ src.startColumn,+ src.endColumn,+ target.startColumn,+ target.endColumn+ );++ if (!rowOverlap || !colOverlap) {+ return null;+ }++ const [startRow, endRow] = rowOverlap;+ const [startColumn, endColumn] = colOverlap;++ // Determine rangeType based on input rangeTypes and overlaps+ const rangeType = determineRangeType(+ src.rangeType,+ target.rangeType,+ startRow,+ endRow,+ startColumn,+ endColumn+ );++ return {+ startRow,+ endRow,+ startColumn,+ endColumn,+ rangeType,+ };+}++/**+ * Computes the overlap between two one-dimensional ranges.+ * Treats NaN values as unbounded (from -Infinity to +Infinity).+ *+ * @param start1 - The start of the first range (inclusive). NaN indicates unbounded.+ * @param end1 - The end of the first range (exclusive). NaN indicates unbounded.+ * @param start2 - The start of the second range (inclusive). NaN indicates unbounded.+ * @param end2 - The end of the second range (exclusive). NaN indicates unbounded.+ * @returns A tuple containing the start and end of the overlap, or null if there is no overlap.+ */+function getOverlap1D(+ start1: number,+ end1: number,+ start2: number,+ end2: number+): [number, number] | null {+ // Treat NaN as unbounded (-Infinity to +Infinity)+ const s1 = isNaN(start1) ? -Infinity : start1;+ const e1 = isNaN(end1) ? Infinity : end1;+ const s2 = isNaN(start2) ? -Infinity : start2;+ const e2 = isNaN(end2) ? Infinity : end2;++ const start = Math.max(s1, s2);+ const end = Math.min(e1, e2);++ if (start <= end) {+ const resultStart = start === -Infinity ? Number.NaN : start;+ const resultEnd = end === Infinity ? Number.NaN : end;+ return [resultStart, resultEnd];+ } else {+ return null;+ }+}++/**+ * Determines the rangeType of the intersection based on the rangeTypes of the input ranges and the overlap.+ * The logic prioritizes the input rangeTypes and determines the intersection's rangeType accordingly.+ *+ * @param src - The source range.+ * @param target - The target range.+ * @param startRow - The start row of the overlap.+ * @param endRow - The end row of the overlap.+ * @param startColumn - The start column of the overlap.+ * @param endColumn - The end column of the overlap.+ * @returns The rangeType of the intersection.+ */+function determineRangeType(+ srcType: RANGE_TYPE | undefined,+ targetType: RANGE_TYPE | undefined,+ startRow: number,+ endRow: number,+ startColumn: number,+ endColumn: number+): RANGE_TYPE {+ // Default to NORMAL if types are undefined+ const resolvedSrcType = srcType !== undefined ? srcType : inferRangeType(startRow, endRow, startColumn, endColumn);+ const resolvedTargetType = targetType !== undefined ? targetType : inferRangeType(startRow, endRow, startColumn, endColumn);++ if (resolvedSrcType === RANGE_TYPE.ALL || resolvedTargetType === RANGE_TYPE.ALL) {+ // Intersection with ALL results in the other range's type+ if (resolvedSrcType === resolvedTargetType) {+ return resolvedSrcType;+ }+ return resolvedSrcType === RANGE_TYPE.ALL ? resolvedTargetType : resolvedSrcType;+ } else if (resolvedSrcType === resolvedTargetType) {+ // Both ranges have the same type+ return resolvedSrcType;+ } else if (resolvedSrcType === RANGE_TYPE.NORMAL || resolvedTargetType === RANGE_TYPE.NORMAL) {+ // Intersection with NORMAL results in NORMAL+ return RANGE_TYPE.NORMAL;+ } else {+ // Different types (ROW and COLUMN), intersection is NORMAL+ return RANGE_TYPE.NORMAL;+ }+}++/**+ * Infers the rangeType based on whether start and end rows or columns are NaN (unbounded).+ * Determines if the range represents rows, columns, normal range, or all cells.+ *+ * @param startRow - The start row of the range.+ * @param endRow - The end row of the range.+ * @param startColumn - The start column of the range.+ * @param endColumn - The end column of the range.+ * @returns The inferred rangeType.+ */+function inferRangeType(+ startRow: number,+ endRow: number,+ startColumn: number,+ endColumn: number+): RANGE_TYPE {+ const hasRow = !isNaN(startRow) && !isNaN(endRow);+ const hasColumn = !isNaN(startColumn) && !isNaN(endColumn);++ if (hasRow && hasColumn) {+ return RANGE_TYPE.NORMAL;+ } else if (hasRow) {+ return RANGE_TYPE.ROW;+ } else if (hasColumn) {+ return RANGE_TYPE.COLUMN;+ } else {+ return RANGE_TYPE.ALL;+ }+}diff --git a/packages/core/src/shared/rectangle.ts b/packages/core/src/shared/rectangle.tsindex 3ba26097c6..d0f7ae34e9 100644--- a/packages/core/src/shared/rectangle.ts+++ b/packages/core/src/shared/rectangle.ts@@ -109,6 +109,10 @@ export class Rectangle {return zx <= x && zy <= y;}+ /**+ *+ * @deprecated use `getIntersectRange` instead. This method does not handle NaN and does not return the correct rangeType+ */static getIntersects(src: IRange, target: IRange): Nullable<IRange> {const currentStartRow = src.startRow;const currentEndRow = src.endRow;diff --git a/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.tsindex dc1451c9f4..434cbcac4a 100644--- a/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts+++ b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts@@ -14,8 +14,9 @@* limitations under the License.*/-import type { IMutation } from '@univerjs/core';import { CommandType } from '@univerjs/core';+import type { IAccessor, IMutation } from '@univerjs/core';+import { IDefinedNamesService } from '../../services/defined-names.service';export interface ISetDefinedNameMutationSearchParam {unitId: string;@@ -29,6 +30,28 @@ export interface ISetDefinedNameMutationParam extends ISetDefinedNameMutationSealocalSheetId?: string;hidden?: boolean;}++/**+ * Generate undo mutation of a `SetDefinedNameMutation`+ * @param accessor+ * @param params+ * @returns+ */+export const SetDefinedNameMutationFactory = (+ accessor: IAccessor,+ params: ISetDefinedNameMutationParam+): ISetDefinedNameMutationParam => {+ const { unitId, id } = params;+ const definedNamesService = accessor.get(IDefinedNamesService);++ const definedName = definedNamesService.getValueById(unitId, id);++ return {+ ...definedName,+ unitId,+ };+};+/*** In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.* It requires setting local to true during execution.diff --git a/packages/engine-formula/src/controller/set-dependency.controller.ts b/packages/engine-formula/src/controller/set-dependency.controller.tsindex 2217b5f747..617de477f7 100644--- a/packages/engine-formula/src/controller/set-dependency.controller.ts+++ b/packages/engine-formula/src/controller/set-dependency.controller.ts@@ -15,13 +15,15 @@*/import type { ICommandInfo } from '@univerjs/core';+import type { ISetDefinedNameMutationParam } from '../commands/mutations/set-defined-name.mutation';+import type {IRemoveFeatureCalculationMutationParam,ISetFeatureCalculationMutation } from '../commands/mutations/set-feature-calculation.mutation';-import type { ISetFormulaDataMutationParams } from '../commands/mutations/set-formula-data.mutation';import type { IRemoveOtherFormulaMutationParams, ISetOtherFormulaMutationParams } from '../commands/mutations/set-other-formula.mutation';import { Disposable, ICommandService, ObjectMatrix } from '@univerjs/core';+import { SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';import {RemoveFeatureCalculationMutation,SetFeatureCalculationMutation,@@ -36,8 +38,7 @@ export class SetDependencyController extends Disposable {@ICommandService private readonly _commandService: ICommandService,@IFeatureCalculationManagerService@IDependencyManagerService private readonly _dependencyManagerService: IDependencyManagerService,- @IFeatureCalculationManagerService private readonly _featureCalculationManagerService: IFeatureCalculationManagerService- ) {+ @IFeatureCalculationManagerService private readonly _featureCalculationManagerService: IFeatureCalculationManagerService) {super();this._initialize();@@ -127,8 +128,23 @@ export class SetDependencyController extends Disposable {});});});+ } else if (command.id === SetDefinedNameMutation.id) {+ this._handleSetDefinedName(command);}}));}++ private _handleSetDefinedName(+ command: ICommandInfo+ ): void {+ const params = command.params as ISetDefinedNameMutationParam;+ if (params == null) {+ return;+ }++ const { unitId, name } = params;++ this._dependencyManagerService.removeFormulaDependencyByDefinedName(unitId, name);+ }}diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 7c806736cc..c1279af7ab 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -30,6 +30,7 @@ export type {IUnitData,IUnitSheetNameMap,} from './basics/common';+export { BooleanValue } from './basics/common';export { isInDirtyRange } from './basics/dirty';export { ERROR_TYPE_SET, ErrorType } from './basics/error-type';export { FunctionType, type IFunctionInfo, type IFunctionParam } from './basics/function';@@ -37,11 +38,49 @@ export { type IFunctionNames } from './basics/function';export { includeFormulaLexerToken, isFormulaLexerToken, normalizeSheetName } from './basics/match-token';export { convertUnitDataToRuntime } from './basics/runtime';export { compareToken, matchToken, operatorToken } from './basics/token';+export { matchRefDrawToken } from './basics/match-token';+export { isReferenceString } from './basics/regex';+export { RegisterFunctionMutation } from './commands/mutations/register-function.mutation';+export { type ISetArrayFormulaDataMutationParams, SetArrayFormulaDataMutation } from './commands/mutations/set-array-formula-data.mutation';+export { type ISetDefinedNameMutationParam, type ISetDefinedNameMutationSearchParam, RemoveDefinedNameMutation, SetDefinedNameMutation } from './commands/mutations/set-defined-name.mutation';+export { SetDefinedNameMutationFactory } from './commands/mutations/set-defined-name.mutation';+export { RemoveFeatureCalculationMutation, SetFeatureCalculationMutation } from './commands/mutations/set-feature-calculation.mutation';+export {+ type ISetFormulaCalculationNotificationMutation,+ type ISetFormulaCalculationResultMutation,+ type ISetFormulaCalculationStartMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+} from './commands/mutations/set-formula-calculation.mutation';+export { type ISetFormulaDataMutationParams, SetFormulaDataMutation } from './commands/mutations/set-formula-data.mutation';+export { type IRemoveOtherFormulaMutationParams, type ISetOtherFormulaMutationParams, RemoveOtherFormulaMutation, SetOtherFormulaMutation } from './commands/mutations/set-other-formula.mutation';+export { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from './commands/mutations/set-super-table.mutation';+export { CalculateController } from './controller/calculate.controller';+export { SetDefinedNameController } from './controller/set-defined-name.controller';+export { Lexer } from './engine/analysis/lexer';export { LexerNode } from './engine/analysis/lexer-node';export { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';+export { AstTreeBuilder } from './engine/analysis/parser';+export { AstRootNodeFactory } from './engine/ast-node/ast-root-node';+export { FunctionNodeFactory } from './engine/ast-node/function-node';+export { LambdaNodeFactory } from './engine/ast-node/lambda-node';+export { LambdaParameterNodeFactory } from './engine/ast-node/lambda-parameter-node';+export { OperatorNodeFactory } from './engine/ast-node/operator-node';+export { PrefixNodeFactory } from './engine/ast-node/prefix-node';+export { ReferenceNodeFactory } from './engine/ast-node/reference-node';+export { SuffixNodeFactory } from './engine/ast-node/suffix-node';+export { UnionNodeFactory } from './engine/ast-node/union-node';+export { ValueNodeFactory } from './engine/ast-node/value-node';+export { FormulaDependencyGenerator } from './engine/dependency/formula-dependency';+export { Interpreter } from './engine/interpreter/interpreter';export { BaseReferenceObject, type FunctionVariantType } from './engine/reference-object/base-reference-object';+export { AsyncArrayObject, AsyncObject } from './engine/reference-object/base-reference-object';export { RangeReferenceObject } from './engine/reference-object/range-reference-object';+export { strip, stripErrorMargin } from './engine/utils/math-kit';+export { handleNumfmtInCell } from './engine/utils/numfmt-kit';export { deserializeRangeForR1C1 } from './engine/utils/r1c1-reference';export {deserializeRangeWithSheet,@@ -57,22 +96,20 @@ export {serializeRangeWithSpreadsheet,singleReferenceToGrid,} from './engine/utils/reference';+export { handleRefStringInfo } from './engine/utils/reference';export { generateStringWithSequence, type ISequenceNode, sequenceNodeType } from './engine/utils/sequence';export { ArrayValueObject, ValueObjectFactory } from './engine/value-object/array-value-object';export { BaseValueObject, ErrorValueObject } from './engine/value-object/base-value-object';-export { BooleanValue } from './basics/common';export type { PrimitiveValueType } from './engine/value-object/primitive-object';-export { NumberValueObject } from './engine/value-object/primitive-object';-export { BooleanValueObject } from './engine/value-object/primitive-object';-export { NullValueObject, StringValueObject } from './engine/value-object/primitive-object';+export { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from './engine/value-object/primitive-object';export { functionArray } from './functions/array/function-map';export { FUNCTION_NAMES_ARRAY } from './functions/array/function-names';export { BaseFunction } from './functions/base-function';-export { CustomFunction } from './functions/custom-function';export { functionCompatibility } from './functions/compatibility/function-map';export { FUNCTION_NAMES_COMPATIBILITY } from './functions/compatibility/function-names';export { functionCube } from './functions/cube/function-map';export { FUNCTION_NAMES_CUBE } from './functions/cube/function-names';+export { CustomFunction } from './functions/custom-function';export { functionDatabase } from './functions/database/function-map';export { FUNCTION_NAMES_DATABASE } from './functions/database/function-names';export { functionDate } from './functions/date/function-map';@@ -81,8 +118,10 @@ export { functionEngineering } from './functions/engineering/function-map';export { FUNCTION_NAMES_ENGINEERING } from './functions/engineering/function-names';export { functionFinancial } from './functions/financial/function-map';export { FUNCTION_NAMES_FINANCIAL } from './functions/financial/function-names';+export { functionInformation } from './functions/information/function-map';export { FUNCTION_NAMES_INFORMATION } from './functions/information/function-names';+export { functionLogical } from './functions/logical/function-map';export { FUNCTION_NAMES_LOGICAL } from './functions/logical/function-names';export { functionLookup } from './functions/lookup/function-map';@@ -100,83 +139,21 @@ export { functionWeb } from './functions/web/function-map';export { FUNCTION_NAMES_WEB } from './functions/web/function-names';export { FormulaDataModel } from './models/formula-data.model';export { initSheetFormulaData } from './models/formula-data.model';+export type { IRangeChange } from './models/formula-data.model';export { UniverFormulaEnginePlugin } from './plugin';+export { IActiveDirtyManagerService } from './services/active-dirty-manager.service';+export { ActiveDirtyManagerService } from './services/active-dirty-manager.service';export { CalculateFormulaService } from './services/calculate-formula.service';-export {- FeatureCalculationManagerService,- IFeatureCalculationManagerService,-} from './services/feature-calculation-manager.service';+export { FormulaCurrentConfigService, IFormulaCurrentConfigService, type IFormulaDirtyData } from './services/current-data.service';+export { DefinedNamesService, type IDefinedNameMapItem, IDefinedNamesService, type IDefinedNamesServiceParam } from './services/defined-names.service';+export { IDependencyManagerService } from './services/dependency-manager.service';+export { DependencyManagerService } from './services/dependency-manager.service';+export { FeatureCalculationManagerService, IFeatureCalculationManagerService } from './services/feature-calculation-manager.service';export { FunctionService } from './services/function.service';export { IFunctionService } from './services/function.service';export { IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';export { FormulaExecuteStageType, type IExecutionInProgressParams } from './services/runtime.service';export { FormulaExecutedStateType, type IAllRuntimeData } from './services/runtime.service';-export { isReferenceString } from './basics/regex';-export { matchRefDrawToken } from './basics/match-token';-export { DefinedNamesService, type IDefinedNameMapItem, IDefinedNamesService, type IDefinedNamesServiceParam } from './services/defined-names.service';export { FormulaRuntimeService, IFormulaRuntimeService } from './services/runtime.service';-export { FormulaCurrentConfigService, IFormulaCurrentConfigService, type IFormulaDirtyData } from './services/current-data.service';--export { IActiveDirtyManagerService } from './services/active-dirty-manager.service';-export { ActiveDirtyManagerService } from './services/active-dirty-manager.service';--export type { IRangeChange } from './models/formula-data.model';-export { handleNumfmtInCell } from './engine/utils/numfmt-kit';-export { AsyncArrayObject } from './engine/reference-object/base-reference-object';-export { strip, stripErrorMargin } from './engine/utils/math-kit';-export { AsyncObject } from './engine/reference-object/base-reference-object';-export { Lexer } from './engine/analysis/lexer';-export { FormulaDependencyGenerator } from './engine/dependency/formula-dependency';export { ISuperTableService } from './services/super-table.service';export { SuperTableService } from './services/super-table.service';-export { Interpreter } from './engine/interpreter/interpreter';-export { AstTreeBuilder } from './engine/analysis/parser';-export { AstRootNodeFactory } from './engine/ast-node/ast-root-node';-export { FunctionNodeFactory } from './engine/ast-node/function-node';-export { LambdaNodeFactory } from './engine/ast-node/lambda-node';-export { LambdaParameterNodeFactory } from './engine/ast-node/lambda-parameter-node';-export { OperatorNodeFactory } from './engine/ast-node/operator-node';-export { PrefixNodeFactory } from './engine/ast-node/prefix-node';-export { ReferenceNodeFactory } from './engine/ast-node/reference-node';-export { SuffixNodeFactory } from './engine/ast-node/suffix-node';-export { UnionNodeFactory } from './engine/ast-node/union-node';-export { ValueNodeFactory } from './engine/ast-node/value-node';-export { IDependencyManagerService } from './services/dependency-manager.service';-export { DependencyManagerService } from './services/dependency-manager.service';-export { CalculateController } from './controller/calculate.controller';--// #region - all commands--export { RegisterFunctionMutation } from './commands/mutations/register-function.mutation';-export { type ISetArrayFormulaDataMutationParams, SetArrayFormulaDataMutation } from './commands/mutations/set-array-formula-data.mutation';-export {- type ISetDefinedNameMutationParam,- type ISetDefinedNameMutationSearchParam,- RemoveDefinedNameMutation,- SetDefinedNameMutation,-} from './commands/mutations/set-defined-name.mutation';-export { RemoveFeatureCalculationMutation, SetFeatureCalculationMutation } from './commands/mutations/set-feature-calculation.mutation';--export {- type ISetFormulaCalculationNotificationMutation,- type ISetFormulaCalculationResultMutation,- type ISetFormulaCalculationStartMutation,- SetFormulaCalculationNotificationMutation,- SetFormulaCalculationResultMutation,- SetFormulaCalculationStartMutation,- SetFormulaCalculationStopMutation,-} from './commands/mutations/set-formula-calculation.mutation';-export { type ISetFormulaDataMutationParams, SetFormulaDataMutation } from './commands/mutations/set-formula-data.mutation';-export {- type IRemoveOtherFormulaMutationParams,- type ISetOtherFormulaMutationParams,- RemoveOtherFormulaMutation,- SetOtherFormulaMutation,-} from './commands/mutations/set-other-formula.mutation';-export {- RemoveSuperTableMutation,- SetSuperTableMutation,- SetSuperTableOptionMutation,-} from './commands/mutations/set-super-table.mutation';--// #endregiondiff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex a36a682d04..9f0ca74f9a 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -14,12 +14,7 @@* limitations under the License.*/-import { Disposable, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable, Workbook } from '@univerjs/core';--import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';--import { clearArrayFormulaCellDataByCell, updateFormulaDataByCellValue } from './utils/formula-data-util';import type {IArrayFormulaRangeType,IArrayFormulaUnitCellType,@@ -30,8 +25,13 @@ import type {IUnitData,IUnitSheetNameMap,} from '../basics/common';+import type { IFormulaIdMap } from './utils/formula-data-util';+import { Disposable, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';+import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';+import { clearArrayFormulaCellDataByCell, updateFormulaDataByCellValue } from './utils/formula-data-util';+export interface IRangeChange {oldCell: IRange;newCell: IRange | null;@@ -70,11 +70,12 @@ export class FormulaDataModel extends Disposable {Object.keys(clearSheetData).forEach((sheetId) => {const clearCellMatrixData = clearSheetData[sheetId];- const rangeMatrix = this._arrayFormulaRange?.[unitId]?.[sheetId];- if (rangeMatrix == null) {+ const formulaRange = this._arrayFormulaRange?.[unitId]?.[sheetId];+ if (formulaRange == null) {return true;}+ const rangeMatrix = new ObjectMatrix<IRange>(formulaRange); // Original array formula range.let arrayFormulaCellMatrixData = new ObjectMatrix<Nullable<ICellData>>(); // Original array formula cell data.if (this._arrayFormulaCellData[unitId]?.[sheetId] != null) {@@ -84,16 +85,20 @@ export class FormulaDataModel extends Disposable {}clearCellMatrixData.forValue((row, column) => {- const range = rangeMatrix?.[row]?.[column];+ const range = rangeMatrix.getValue(row, column);if (range == null) {return true;}+const { startRow, startColumn, endRow, endColumn } = range;for (let r = startRow; r <= endRow; r++) {for (let c = startColumn; c <= endColumn; c++) {arrayFormulaCellMatrixData.setValue(r, c, null);}}++ // clear the array formula range+ rangeMatrix.realDeleteValue(row, column);});if (this._arrayFormulaCellData[unitId]) {diff --git a/packages/engine-formula/src/services/defined-names.service.ts b/packages/engine-formula/src/services/defined-names.service.tsindex 3db40a7e4c..8baf4ab877 100644--- a/packages/engine-formula/src/services/defined-names.service.ts+++ b/packages/engine-formula/src/services/defined-names.service.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import type { IUnitRange, Nullable } from '@univerjs/core';-import { createIdentifier, Disposable } from '@univerjs/core';-import type { Observable } from 'rxjs';+import { createIdentifier, Disposable, IUniverInstanceService } from '@univerjs/core';import { Subject } from 'rxjs';-import { serializeRange } from '../engine/utils/reference';+import type { IUnitRange, Nullable, Workbook, Worksheet } from '@univerjs/core';+import type { Observable } from 'rxjs';+import { handleRefStringInfo, serializeRange } from '../engine/utils/reference';export interface IDefinedNamesServiceParam {id: string;@@ -72,6 +72,9 @@ export interface IDefinedNamesService {focusRange$: Observable<IDefinedNamesServiceFocusParam>;focusRange(unitId: string, id: string): void;++ getWorksheetByRef(unitId: string, ref: string): Nullable<Worksheet>;+}export class DefinedNamesService extends Disposable implements IDefinedNamesService {@@ -96,7 +99,7 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServprivate readonly _focusRange$ = new Subject<IDefinedNamesServiceFocusParam>();readonly focusRange$ = this._focusRange$.asObservable();- constructor() {+ constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService) {super();// this.registerDefinedName('workbook-01', { id: 'test1', name: 'name-01', formulaOrRefString: '=sum(A1:B10)', comment: 'this is comment', localSheetId: 'sheet-0011', hidden: false });}@@ -105,11 +108,17 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServthis._definedNameMap = {};}+ getWorksheetByRef(unitId: string, ref: string) {+ const { sheetName } = handleRefStringInfo(ref);+ return this._univerInstanceService.getUnit<Workbook>(unitId)?.getSheetBySheetName(sheetName);+ }+focusRange(unitId: string, id: string) {const item = this.getValueById(unitId, id);if (item == null) {return;}+this._focusRange$.next({ ...item, unitId });}diff --git a/packages/engine-formula/src/services/dependency-manager.service.ts b/packages/engine-formula/src/services/dependency-manager.service.tsindex 635894fc50..67751c0425 100644--- a/packages/engine-formula/src/services/dependency-manager.service.ts+++ b/packages/engine-formula/src/services/dependency-manager.service.ts@@ -59,6 +59,8 @@ export interface IDependencyManagerService {getFormulaDependency(unitId: string, sheetId: string, row: number, column: number): Nullable<FormulaDependencyTree>;+ removeFormulaDependencyByDefinedName(unitId: string, definedName: string): void;+clearFormulaDependency(unitId: string, sheetId?: string): void;addDependencyRTreeCache(tree: FormulaDependencyTree): void;@@ -501,6 +503,21 @@ export class DependencyManagerService extends Disposable implements IDependencyM};}));}++ removeFormulaDependencyByDefinedName(unitId: string, definedName: string) {+ if (this._formulaData[unitId]) {+ Object.values(this._formulaData[unitId]).forEach((sheet) => {+ sheet.forValue((row, column, tree) => {+ if (tree?.node?.hasDefinedName(definedName)) {+ this._removeDependencyRTreeCache(tree);+ this.clearDependencyForTree(tree);+ sheet.realDeleteValue(row, column);+ this._removeTreeIdFromCache(tree);+ }+ });+ });+ }+ }}export const IDependencyManagerService = createIdentifier<DependencyManagerService>(diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.tsindex 2ada7c7318..e8e588a646 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts@@ -20,7 +20,7 @@ import { DocSelectionManagerService } from '@univerjs/docs';import { EditorService, IEditorService } from '@univerjs/docs-ui';import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { IRefSelectionsService, RangeProtectionRuleModel, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';+import { DefinedNameDataController, IRefSelectionsService, RangeProtectionRuleModel, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { EditorBridgeService, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {@@ -90,6 +90,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([LexerTreeBuilder]);injector.add([DocSelectionManagerService]);injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([DefinedNameDataController]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([SheetSkeletonManagerService]);@@ -103,6 +104,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?this._injector.get(SheetInterceptorService);this._injector.get(WorkbookPermissionService);this._injector.get(WorksheetPermissionService);+ this._injector.get(DefinedNameDataController);}override onReady(): void {@@ -112,7 +114,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?}univer.registerPlugin(TestPlugin);- const sheet = univer.createUniverSheet(workbookData || TEST_WORKBOOK_DATA_DEMO);+ const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData || TEST_WORKBOOK_DATA_DEMO);const univerInstanceService = injector.get(IUniverInstanceService);univerInstanceService.focusUnit('test');diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/update-defined-name.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/update-defined-name.controller.spec.tsnew file mode 100644index 0000000000..6e41e8478f--- /dev/null+++ b/packages/sheets-formula-ui/src/controllers/__tests__/update-defined-name.controller.spec.ts@@ -0,0 +1,757 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICellData, Injector, IWorkbookData, Nullable, Univer } from '@univerjs/core';+import type { IDeleteRangeMoveLeftCommandParams, IDeleteRangeMoveUpCommandParams, IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, InsertRangeMoveDownCommandParams, InsertRangeMoveRightCommandParams, IRemoveRowColCommandParams, IRemoveSheetCommandParams, ISetWorksheetNameCommandParams } from '@univerjs/sheets';+import { Direction, ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';+import { IDefinedNamesService, RemoveDefinedNameMutation, SetArrayFormulaDataMutation, SetDefinedNameController, SetDefinedNameMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';+import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetDefinedNameCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetsSelectionsService } from '@univerjs/sheets';++import { UpdateDefinedNameController } from '@univerjs/sheets-formula';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createCommandTestBed } from './create-command-test-bed';++const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {},+ name: 'Sheet1',+ },+ sheet2: {+ id: 'sheet2',+ cellData: {},+ name: 'Sheet2',+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: ['sheet1', 'sheet2'],+ styles: {},+ resources: [+ {+ name: 'SHEET_DEFINED_NAME_PLUGIN',+ data: '{"soAI3OK4sq":{"id":"soAI3OK4sq","name":"DefinedName1","formulaOrRefString":"Sheet1!$A$1:$B$2","comment":"","localSheetId":"AllDefaultWorkbook"},"qwert12345":{"id":"qwert12345","name":"DefinedName2","formulaOrRefString":"Sheet1!$1:$3","comment":"","localSheetId":"AllDefaultWorkbook"},"asdfg67890":{"id":"asdfg67890","name":"DefinedName3","formulaOrRefString":"Sheet1!$A:$C","comment":"","localSheetId":"AllDefaultWorkbook"}}',+ },+ ],+});++describe('Test update defined name', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let getValues: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number,+ sheetId?: string+ ) => Array<Array<Nullable<ICellData>>> | undefined;+ let getDefinedNameRef: (name?: string) => string | undefined;++ beforeEach(() => {+ const testBed = createCommandTestBed(TEST_WORKBOOK_DATA_DEMO(), [+ [UpdateDefinedNameController],+ [SetDefinedNameController],+ ]);+ univer = testBed.univer;+ get = testBed.get;++ get(UpdateDefinedNameController);+ get(SetDefinedNameController);++ commandService = get(ICommandService);+ commandService.registerCommand(MoveRangeCommand);+ commandService.registerCommand(MoveRangeMutation);++ commandService.registerCommand(MoveRowsCommand);+ commandService.registerCommand(MoveRowsMutation);++ commandService.registerCommand(MoveColsCommand);+ commandService.registerCommand(MoveColsMutation);++ commandService.registerCommand(InsertRowCommand);+ commandService.registerCommand(InsertRowMutation);++ commandService.registerCommand(InsertColCommand);+ commandService.registerCommand(InsertColMutation);++ commandService.registerCommand(RemoveRowCommand);+ commandService.registerCommand(RemoveRowMutation);++ commandService.registerCommand(RemoveColCommand);+ commandService.registerCommand(RemoveColMutation);++ commandService.registerCommand(DeleteRangeMoveLeftCommand);+ commandService.registerCommand(DeleteRangeMoveUpCommand);+ commandService.registerCommand(InsertRangeMoveDownCommand);+ commandService.registerCommand(InsertRangeMoveRightCommand);++ commandService.registerCommand(SetWorksheetNameCommand);+ commandService.registerCommand(SetWorksheetNameMutation);+ commandService.registerCommand(RemoveSheetCommand);+ commandService.registerCommand(RemoveSheetMutation);++ commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(SetRangeValuesCommand);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(SetFormulaDataMutation);+ commandService.registerCommand(SetArrayFormulaDataMutation);++ // set defined name+ commandService.registerCommand(SetDefinedNameCommand);+ commandService.registerCommand(SetDefinedNameMutation);+ commandService.registerCommand(RemoveDefinedNameMutation);++ getValues = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number,+ sheetId: string = 'sheet1'+ ): Array<Array<Nullable<ICellData>>> | undefined =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId(sheetId)+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValues();++ getDefinedNameRef = (name: string = 'DefinedName1') => {+ const definedNameService = get(IDefinedNamesService);+ const definedName = definedNameService.getValueByName('test', name);+ if (definedName) {+ return definedName.formulaOrRefString;+ }+ };+ });++ afterEach(() => {+ univer.dispose();+ });++ describe('update defined name', () => {+ it('Move range, update reference', async () => {+ const params: IMoveRangeCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ rangeType: 0,+ },+ toRange: {+ startRow: 0,+ startColumn: 3,+ endRow: 1,+ endColumn: 4,+ rangeType: 0,+ },+ };++ expect(await commandService.executeCommand(MoveRangeCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$D$1:$E$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$D$1:$E$2');+ });++ it('Move rows, update reference', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 1, startColumn: 0, endRow: 1, endColumn: 0, rangeType: RANGE_TYPE.ROW },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveRowsCommandParams = {+ fromRange: {+ startRow: 1,+ startColumn: 0,+ endRow: 1,+ endColumn: 19,+ rangeType: 1,+ },+ toRange: {+ startRow: 4,+ startColumn: 0,+ endRow: 4,+ endColumn: 19,+ rangeType: 1,+ },+ };++ expect(await commandService.executeCommand(MoveRowsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$4');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$4');+ });++ it('Move rows to range start', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 1, startColumn: 0, endRow: 1, endColumn: 0, rangeType: RANGE_TYPE.ROW },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveRowsCommandParams = {+ fromRange: {+ startRow: 1,+ startColumn: 0,+ endRow: 1,+ endColumn: 19,+ rangeType: 1,+ },+ toRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 0,+ endColumn: 19,+ rangeType: 1,+ },+ };++ expect(await commandService.executeCommand(MoveRowsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$2:$3');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$3');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$2:$3');+ });++ it('Move rows to range end', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.ROW },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveRowsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 0,+ endColumn: 19,+ rangeType: 1,+ },+ toRange: {+ startRow: 3,+ startColumn: 0,+ endRow: 3,+ endColumn: 19,+ rangeType: 1,+ },+ };++ expect(await commandService.executeCommand(MoveRowsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$3');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$2');+ });++ it('Move first row beyond the end', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.ROW },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveRowsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 0,+ endColumn: 19,+ rangeType: 1,+ },+ toRange: {+ startRow: 9,+ startColumn: 0,+ endRow: 9,+ endColumn: 19,+ rangeType: 1,+ },+ };++ expect(await commandService.executeCommand(MoveRowsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$3');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$2');+ });++ it('Move last row beyond the end', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 2, startColumn: 0, endRow: 2, endColumn: 0, rangeType: RANGE_TYPE.ROW },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveRowsCommandParams = {+ fromRange: {+ startRow: 2,+ startColumn: 0,+ endRow: 2,+ endColumn: 19,+ rangeType: 1,+ },+ toRange: {+ startRow: 9,+ startColumn: 0,+ endRow: 9,+ endColumn: 19,+ rangeType: 1,+ },+ };++ expect(await commandService.executeCommand(MoveRowsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$9');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$3');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName2')).toBe('Sheet1!$1:$9');+ });++ it('Move columns, update reference', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveColsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 999,+ endColumn: 0,+ rangeType: 2,+ },+ toRange: {+ startRow: 0,+ startColumn: 4,+ endRow: 999,+ endColumn: 4,+ rangeType: 2,+ },+ };++ expect(await commandService.executeCommand(MoveColsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$A$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$A$2');+ });++ it('Move columns to range start', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 1, endRow: 0, endColumn: 1, rangeType: RANGE_TYPE.COLUMN },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveColsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 1,+ endRow: 999,+ endColumn: 1,+ rangeType: 2,+ },+ toRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 999,+ endColumn: 0,+ rangeType: 2,+ },+ };++ expect(await commandService.executeCommand(MoveColsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$B:$C');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$C');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$B:$C');+ });++ it('Move columns to range end', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveColsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 999,+ endColumn: 0,+ rangeType: 2,+ },+ toRange: {+ startRow: 0,+ startColumn: 3,+ endRow: 999,+ endColumn: 3,+ rangeType: 2,+ },+ };++ expect(await commandService.executeCommand(MoveColsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$B');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$C');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$B');+ });++ it('Move first column beyond the end', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveColsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 999,+ endColumn: 0,+ rangeType: 2,+ },+ toRange: {+ startRow: 0,+ startColumn: 9,+ endRow: 999,+ endColumn: 9,+ rangeType: 2,+ },+ };++ expect(await commandService.executeCommand(MoveColsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$B');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$C');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$B');+ });++ it('Move last column beyond the end', async () => {+ const selectionManager = get(SheetsSelectionsService);++ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 2, endRow: 0, endColumn: 2, rangeType: RANGE_TYPE.COLUMN },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveColsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 2,+ endRow: 999,+ endColumn: 2,+ rangeType: 2,+ },+ toRange: {+ startRow: 0,+ startColumn: 9,+ endRow: 999,+ endColumn: 9,+ rangeType: 2,+ },+ };++ expect(await commandService.executeCommand(MoveColsCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$I');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$C');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef('DefinedName3')).toBe('Sheet1!$A:$I');+ });++ it('Insert row, update reference', async () => {+ const params: IInsertRowCommandParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: {+ startRow: 1,+ endRow: 1,+ startColumn: 0,+ endColumn: 19,+ },+ direction: Direction.UP,+ };++ expect(await commandService.executeCommand(InsertRowCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$3');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$3');+ });++ it('Insert column, update reference', async () => {+ const params: IInsertColCommandParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: {+ startColumn: 1,+ endColumn: 1,+ startRow: 0,+ endRow: 14,+ },+ direction: Direction.LEFT,+ cellValue: {},+ };++ expect(await commandService.executeCommand(InsertColCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$C$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$C$2');+ });++ it('Remove row, update reference', async () => {+ const params: IRemoveRowColCommandParams = {+ range: {+ startRow: 1,+ endRow: 1,+ startColumn: 0,+ endColumn: 19,+ },+ };++ expect(await commandService.executeCommand(RemoveRowCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$1');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$1');+ });++ it('Remove column, update reference', async () => {+ const params: IRemoveRowColCommandParams = {+ range: {+ startColumn: 1,+ endColumn: 1,+ startRow: 0,+ endRow: 2,+ },+ };++ expect(await commandService.executeCommand(RemoveColCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$A$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$A$2');+ });++ it('Delete move left, update reference', async () => {+ const params: IDeleteRangeMoveLeftCommandParams = {+ range: {+ startRow: 0,+ startColumn: 1,+ endRow: 1,+ endColumn: 1,+ rangeType: 0,+ },+ };++ expect(await commandService.executeCommand(DeleteRangeMoveLeftCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$A$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$A$2');+ });++ it('Delete move up, update reference', async () => {+ const params: IDeleteRangeMoveUpCommandParams = {+ range: {+ startRow: 1,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ rangeType: 0,+ },+ };++ expect(await commandService.executeCommand(DeleteRangeMoveUpCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$1');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$1');+ });++ it('Insert move down, update reference', async () => {+ const params: InsertRangeMoveDownCommandParams = {+ range: {+ startRow: 1,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ rangeType: 0,+ },+ };++ expect(await commandService.executeCommand(InsertRangeMoveDownCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$3');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$3');+ });++ it('Insert move right, update reference', async () => {+ const params: InsertRangeMoveRightCommandParams = {+ range: {+ startRow: 0,+ startColumn: 1,+ endRow: 1,+ endColumn: 1,+ rangeType: 0,+ },+ };++ expect(await commandService.executeCommand(InsertRangeMoveRightCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$C$2');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$B$2');++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1!$A$1:$C$2');+ });++ it('set worksheet name', async () => {+ const params: ISetWorksheetNameCommandParams = {+ subUnitId: 'sheet1',+ name: 'Sheet1Rename',+ };++ expect(await commandService.executeCommand(SetWorksheetNameCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('Sheet1Rename!$A$1:$B$2');+ });++ it('remove worksheet', async () => {+ const params: IRemoveSheetCommandParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ };++ expect(await commandService.executeCommand(RemoveSheetCommand.id, params)).toBeTruthy();+ expect(getDefinedNameRef()).toBe('#REF!');+ });+ });+});diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.tsindex e84fd4658d..e19ec8e934 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/update-formula.controller.spec.ts@@ -15,11 +15,11 @@*/import type { ICellData, Injector, IWorkbookData, Nullable, Univer, Workbook } from '@univerjs/core';+import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';import type { IDeleteRangeMoveLeftCommandParams, IDeleteRangeMoveUpCommandParams, IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, InsertRangeMoveDownCommandParams, InsertRangeMoveRightCommandParams, IRemoveRowColCommandParams, IRemoveSheetCommandParams, ISetRangeValuesCommandParams, ISetWorksheetNameCommandParams } from '@univerjs/sheets';import { CellValueType, Direction, ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';-import { SetArrayFormulaDataMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';-import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetsSelectionsService } from '@univerjs/sheets';-+import { RemoveDefinedNameMutation, SetArrayFormulaDataMutation, SetDefinedNameMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';+import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveDefinedNameCommand, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetDefinedNameCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetsSelectionsService } from '@univerjs/sheets';import { UpdateFormulaController } from '@univerjs/sheets-formula';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { createCommandTestBed } from './create-command-test-bed';@@ -260,6 +260,16 @@ const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({sheet2: {id: 'sheet2',cellData: {+ 2: {+ 0: {+ f: '=SUM(DefinedName1)',+ },+ },+ 9: {+ 9: {+ f: '=SUM(A2:C4)',+ },+ },},name: 'Sheet2',},@@ -268,9 +278,15 @@ const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({name: '',sheetOrder: ['sheet1', 'sheet2'],styles: {},+ resources: [+ {+ name: 'SHEET_DEFINED_NAME_PLUGIN',+ data: '{"soAI3OK4sq":{"id":"soAI3OK4sq","name":"DefinedName1","formulaOrRefString":"Sheet2!$A$1:$B$2","comment":"","localSheetId":"AllDefaultWorkbook"}}',+ },+ ],});-describe('Test insert function operation', () => {+describe('Test update formula ', () => {let univer: Univer;let get: Injector['get'];let commandService: ICommandService;@@ -278,7 +294,8 @@ describe('Test insert function operation', () => {startRow: number,startColumn: number,endRow: number,- endColumn: number+ endColumn: number,+ sheetId?: string) => Array<Array<Nullable<ICellData>>> | undefined;beforeEach(() => {@@ -327,15 +344,22 @@ describe('Test insert function operation', () => {commandService.registerCommand(SetFormulaDataMutation);commandService.registerCommand(SetArrayFormulaDataMutation);+ // set defined name+ commandService.registerCommand(SetDefinedNameCommand);+ commandService.registerCommand(RemoveDefinedNameCommand);+ commandService.registerCommand(SetDefinedNameMutation);+ commandService.registerCommand(RemoveDefinedNameMutation);+getValues = (startRow: number,startColumn: number,endRow: number,- endColumn: number+ endColumn: number,+ sheetId: string = 'sheet1'): Array<Array<Nullable<ICellData>>> | undefined =>get(IUniverInstanceService).getUnit<Workbook>('test')- ?.getSheetBySheetId('sheet1')+ ?.getSheetBySheetId(sheetId)?.getRange(startRow, startColumn, endRow, endColumn).getValues();@@ -529,6 +553,54 @@ describe('Test insert function operation', () => {expect(valuesRedo2).toStrictEqual([[{ f: '=SUM(A1:B9)' }], [{ v: 1, t: CellValueType.NUMBER }]]);});+ it('Move rows, reduce scope', async () => {+ const workbook = get(IUniverInstanceService).getUnit<Workbook>('test');+ const sheet2 = workbook?.getSheetBySheetId('sheet2');+ if (!sheet2) {+ throw new Error('sheet2 not found');+ }+ workbook?.setActiveSheet(sheet2);++ const selectionManager = get(SheetsSelectionsService);+ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 2, startColumn: 0, endRow: 2, endColumn: 19, rangeType: RANGE_TYPE.ROW },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveRowsCommandParams = {+ fromRange: {+ startRow: 2,+ startColumn: 0,+ endRow: 2,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ },+ toRange: {+ startRow: 7,+ startColumn: 0,+ endRow: 7,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ },+ };++ expect(await commandService.executeCommand(MoveRowsCommand.id, params)).toBeTruthy();+ const values = getValues(9, 9, 9, 9, 'sheet2');+ expect(values).toStrictEqual([[{ f: '=SUM(A2:C3)' }]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo2 = getValues(9, 9, 9, 9, 'sheet2');+ expect(valuesUndo2).toStrictEqual([[{ f: '=SUM(A2:C4)' }]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(9, 9, 9, 9, 'sheet2');+ expect(valuesRedo).toStrictEqual([[{ f: '=SUM(A2:C3)' }]]);+ });+it('Move columns, update reference', async () => {const selectionManager = get(SheetsSelectionsService);@@ -619,6 +691,54 @@ describe('Test insert function operation', () => {expect(valuesRedo2).toStrictEqual([[{ f: '=SUM(A1:I2)' }, { v: 1, t: CellValueType.NUMBER }]]);});+ it('Move columns, reduce scope', async () => {+ const workbook = get(IUniverInstanceService).getUnit<Workbook>('test');+ const sheet2 = workbook?.getSheetBySheetId('sheet2');+ if (!sheet2) {+ throw new Error('sheet2 not found');+ }+ workbook?.setActiveSheet(sheet2);++ const selectionManager = get(SheetsSelectionsService);+ // A1+ selectionManager.addSelections([+ {+ range: { startRow: 0, startColumn: 1, endRow: 999, endColumn: 1, rangeType: RANGE_TYPE.COLUMN },+ primary: null,+ style: null,+ },+ ]);++ const params: IMoveRowsCommandParams = {+ fromRange: {+ startRow: 0,+ startColumn: 1,+ endRow: 999,+ endColumn: 1,+ rangeType: RANGE_TYPE.COLUMN,+ },+ toRange: {+ startRow: 0,+ startColumn: 7,+ endRow: 999,+ endColumn: 7,+ rangeType: RANGE_TYPE.COLUMN,+ },+ };++ expect(await commandService.executeCommand(MoveColsCommand.id, params)).toBeTruthy();+ const values = getValues(9, 9, 9, 9, 'sheet2');+ expect(values).toStrictEqual([[{ f: '=SUM(A2:B4)' }]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo2 = getValues(9, 9, 9, 9, 'sheet2');+ expect(valuesUndo2).toStrictEqual([[{ f: '=SUM(A2:C4)' }]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(9, 9, 9, 9, 'sheet2');+ expect(valuesRedo).toStrictEqual([[{ f: '=SUM(A2:B4)' }]]);+ });+it('Insert row, update reference', async () => {const params: IInsertRowCommandParams = {unitId: 'test',@@ -1298,7 +1418,7 @@ describe('Test insert function operation', () => {expect(valuesRedo).toStrictEqual([[{ f: '=A1:C2' }]]);});- it('set name', async () => {+ it('set worksheet name', async () => {const params: ISetWorksheetNameCommandParams = {subUnitId: 'sheet2',name: 'Sheet2Rename',@@ -1309,7 +1429,37 @@ describe('Test insert function operation', () => {expect(values).toStrictEqual([[{ f: '=Sheet2Rename!A1:B2' }]]);});- it('remove sheet', async () => {+ it('set defined name', async () => {+ const params: ISetDefinedNameMutationParam = {+ unitId: 'test',+ id: 'soAI3OK4sq',+ name: 'DefinedName2',+ formulaOrRefString: 'Sheet2!$A$1:$B$2',+ comment: '',+ localSheetId: 'AllDefaultWorkbook',+ };++ expect(await commandService.executeCommand(SetDefinedNameCommand.id, params)).toBeTruthy();+ const values = getValues(2, 0, 2, 0, 'sheet2');+ expect(values).toStrictEqual([[{ f: '=SUM(DefinedName2)' }]]);+ });++ it('remove defined name', async () => {+ const params: ISetDefinedNameMutationParam = {+ unitId: 'test',+ id: 'soAI3OK4sq',+ name: 'DefinedName1',+ formulaOrRefString: 'Sheet2!$A$1:$B$2',+ comment: '',+ localSheetId: 'AllDefaultWorkbook',+ };++ expect(await commandService.executeCommand(RemoveDefinedNameCommand.id, params)).toBeTruthy();+ const values = getValues(2, 0, 2, 0, 'sheet2');+ expect(values).toStrictEqual([[{ f: '=SUM(#REF!)' }]]);+ });++ it('remove worksheet', async () => {const params: IRemoveSheetCommandParams = {unitId: 'test',subUnitId: 'sheet2',diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.tsindex bf5a40c629..d1094829ab 100644--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts@@ -28,7 +28,6 @@ import type {IRemoveRowsMutationParams,IRemoveSheetMutationParams,IReorderRangeMutationParams,- ISetDefinedNameCommandParams,ISetRangeValuesMutationParams,} from '@univerjs/sheets';import {@@ -50,7 +49,6 @@ import {RemoveRowMutation,RemoveSheetMutation,ReorderRangeMutation,- SetDefinedNameCommand,SetRangeValuesMutation,SetStyleCommand,} from '@univerjs/sheets';@@ -264,17 +262,6 @@ export class ActiveDirtyController extends Disposable {return { dirtyDefinedNameMap: this._getDefinedNameMutation(params) };},});-- this._activeDirtyManagerService.register(SetDefinedNameCommand.id, {- commandId: SetDefinedNameCommand.id,- getDirtyData: (command: ICommandInfo) => {- const params = command.params as ISetDefinedNameCommandParams;- const { oldDefinedName, newDefinedName } = params;- return { dirtyDefinedNameMap: this._getDefinedNameMutation({ ...newDefinedName, name: oldDefinedName.name }) };-- // return { dirtyDefinedNameMap: this._getDefinedNameMutation(params) };- },- });}private _getDefinedNameMutation(definedName: ISetDefinedNameMutationParam) {diff --git a/packages/sheets-formula/src/controllers/defined-name.controller.ts b/packages/sheets-formula/src/controllers/defined-name.controller.tsindex 66108b381d..e8132ec995 100644--- a/packages/sheets-formula/src/controllers/defined-name.controller.ts+++ b/packages/sheets-formula/src/controllers/defined-name.controller.ts@@ -16,7 +16,6 @@import type { ICommandInfo, IExecutionOptions, Nullable, Workbook } from '@univerjs/core';import type { IFunctionInfo, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';-import type { ISetDefinedNameCommandParams } from '@univerjs/sheets';import {Disposable,ICommandService,@@ -24,8 +23,9 @@ import {toDisposable,UniverInstanceType,} from '@univerjs/core';-import { FunctionType, IDefinedNamesService } from '@univerjs/engine-formula';-import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SetDefinedNameCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';+import { FunctionType, IDefinedNamesService, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';+import { SetWorksheetActiveOperation } from '@univerjs/sheets';+import { IDescriptionService } from '../services/description.service';export const SCOPE_WORKBOOK_VALUE = 'AllDefaultWorkbook';@@ -84,16 +84,15 @@ export class DefinedNameController extends Disposable {if (command.id === SetWorksheetActiveOperation.id) {this._unregisterDescriptionsForNotInSheetId();this._registerDescriptions();- } else if (command.id === InsertDefinedNameCommand.id) {+ }+ // Since command interception will supplement mutation, it is necessary to monitor mutation changes here+ // SetDefinedNameMutation and RemoveDefinedNameMutation already cover all possible Defined Name updates+ else if (command.id === SetDefinedNameMutation.id) {const param = command.params as ISetDefinedNameMutationParam;this._registerDescription(param);- } else if (command.id === RemoveDefinedNameCommand.id) {+ } else if (command.id === RemoveDefinedNameMutation.id) {const param = command.params as ISetDefinedNameMutationParam;this._unregisterDescription(param);- } else if (command.id === SetDefinedNameCommand.id) {- const param = command.params as ISetDefinedNameCommandParams;- this._unregisterDescription(param.oldDefinedName);- this._registerDescription(param.newDefinedName);}}));diff --git a/packages/sheets-formula/src/controllers/update-defined-name.controller.ts b/packages/sheets-formula/src/controllers/update-defined-name.controller.tsnew file mode 100644index 0000000000..268d3a813b--- /dev/null+++ b/packages/sheets-formula/src/controllers/update-defined-name.controller.ts@@ -0,0 +1,219 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IMutationInfo, Nullable, Workbook } from '@univerjs/core';+import type { IDefinedNamesServiceParam, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';+import type { IUnitRangeWithOffset } from './utils/ref-range-move';+import {+ Disposable,+ Inject,+ IUniverInstanceService,+ UniverInstanceType,+} from '@univerjs/core';+import { deserializeRangeWithSheet, ErrorType, generateStringWithSequence, IDefinedNamesService, LexerTreeBuilder, sequenceNodeType, serializeRangeToRefString, SetDefinedNameMutation } from '@univerjs/engine-formula';+import { RemoveDefinedNameCommand, SetDefinedNameCommand, SheetInterceptorService } from '@univerjs/sheets';+import { FormulaReferenceMoveType, type IFormulaReferenceMoveParam, updateRefOffset } from './utils/ref-range-formula';+import { getNewRangeByMoveParam } from './utils/ref-range-move';+import { getReferenceMoveParams } from './utils/ref-range-param';++export class UpdateDefinedNameController extends Disposable {+ constructor(+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder++ ) {+ super();++ this._initialize();+ }++ private _initialize() {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ // remove defined name when sheet is removed+ this.disposeWithMe(+ this._sheetInterceptorService.interceptCommand({+ getMutations: (command) => {+ // Exclude processing in getReferenceMoveParams, SetDefinedNameCommand is only handled in UpdateFormulaController+ if (command.id === SetDefinedNameCommand.id || command.id === RemoveDefinedNameCommand.id) {+ return {+ redos: [],+ undos: [],+ };+ }++ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);++ if (workbook == null) {+ return {+ redos: [],+ undos: [],+ };+ }++ const result = getReferenceMoveParams(workbook, command);++ if (!result) {+ return {+ redos: [],+ undos: [],+ };+ }++ return this._getUpdateDefinedNameMutations(workbook, result);+ },+ })+ );+ }++ // eslint-disable-next-line max-lines-per-function+ private _getUpdateDefinedNameMutations(workbook: Workbook, moveParams: IFormulaReferenceMoveParam) {+ const { type, unitId, sheetId } = moveParams;+ const definedNames = this._definedNamesService.getDefinedNameMap(unitId);++ if (!definedNames) {+ return {+ redos: [],+ undos: [],+ };+ }++ const redoMutations: IMutationInfo<ISetDefinedNameMutationParam>[] = [];+ const undoMutations: IMutationInfo<ISetDefinedNameMutationParam>[] = [];++ // eslint-disable-next-line max-lines-per-function+ Object.values(definedNames).forEach((item) => {+ const { formulaOrRefString } = item;+ const sequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaOrRefString);+ if (sequenceNodes == null) {+ return true;+ }++ let shouldModify = false;+ const refChangeIds: number[] = [];+ for (let i = 0, len = sequenceNodes.length; i < len; i++) {+ const node = sequenceNodes[i];+ if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {+ continue;+ }+ const { token } = node;++ const sequenceGrid = deserializeRangeWithSheet(token);++ const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;+ const sequenceSheetId = workbook.getSheetBySheetName(sheetName)?.getSheetId() || '';++ const sequenceUnitRangeWidthOffset: IUnitRangeWithOffset = {+ range,+ sheetId: sequenceSheetId,+ unitId: sequenceUnitId,+ sheetName,+ refOffsetX: 0,+ refOffsetY: 0,+ };++ let newRefString: Nullable<string> = null;++ if (type === FormulaReferenceMoveType.RemoveSheet) {+ newRefString = this._removeSheet(item, unitId, sheetId);+ } else if (type === FormulaReferenceMoveType.SetName) {+ const {+ sheetId: userSheetId,+ sheetName: newSheetName,+ } = moveParams;+ if (newSheetName == null) {+ continue;+ }++ if (sequenceSheetId == null || sequenceSheetId.length === 0) {+ continue;+ }++ if (userSheetId !== sequenceSheetId) {+ continue;+ }++ newRefString = serializeRangeToRefString({+ range,+ sheetName: newSheetName,+ unitId: sequenceUnitId,+ });+ } else {+ newRefString = getNewRangeByMoveParam(+ sequenceUnitRangeWidthOffset,+ moveParams,+ unitId,+ sheetId+ );+ }++ if (newRefString != null) {+ sequenceNodes[i] = {+ ...node,+ token: newRefString,+ };+ shouldModify = true;+ refChangeIds.push(i);+ }+ }++ if (!shouldModify) {+ return true;+ }++ const newSequenceString = generateStringWithSequence(updateRefOffset(sequenceNodes, refChangeIds));++ const redoMutation = {+ id: SetDefinedNameMutation.id,+ params: {+ unitId,+ ...item,+ formulaOrRefString: newSequenceString,+ },+ };+ redoMutations.push(redoMutation);++ const undoMutation = {+ id: SetDefinedNameMutation.id,+ params: {+ unitId,+ ...item,+ },+ };+ undoMutations.push(undoMutation);+ });++ return {+ redos: redoMutations,+ undos: undoMutations,+ };+ }++ private _removeSheet(item: IDefinedNamesServiceParam, unitId: string, subUnitId: string) {+ const { formulaOrRefString } = item;+ const sheetId = this._definedNamesService.getWorksheetByRef(unitId, formulaOrRefString)?.getSheetId();++ if (sheetId === subUnitId) {+ return ErrorType.REF;+ }++ return null;+ }+}diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex d202632266..b4ca43b85c 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -17,46 +17,34 @@import type {ICommandInfo,IExecutionOptions,- IRange,- IUnitRange,Nullable,- Workbook } from '@univerjs/core';-import type { IFormulaData, IFormulaDataItem, ISequenceNode, IUnitSheetNameMap } from '@univerjs/engine-formula';+ Workbook,+} from '@univerjs/core';+import type { IFormulaData, IFormulaDataItem, IUnitSheetNameMap } from '@univerjs/engine-formula';import type {- IDeleteRangeMoveLeftCommandParams,- IDeleteRangeMoveUpCommandParams,- IInsertColCommandParams,- IInsertRowCommandParams,IInsertSheetMutationParams,- IMoveColsCommandParams,- IMoveRangeCommandParams,- IMoveRowsCommandParams,- InsertRangeMoveDownCommandParams,- InsertRangeMoveRightCommandParams,- IRemoveRowColCommandParams,- IRemoveSheetCommandParams,IRemoveSheetMutationParams,ISetRangeValuesMutationParams,- ISetWorksheetNameCommandParams,} from '@univerjs/sheets';+import type { IFormulaReferenceMoveParam } from './utils/ref-range-formula';+import type { IUnitRangeWithOffset } from './utils/ref-range-move';import {- Direction,Disposable,ICommandService,Inject,Injector,IUniverInstanceService,ObjectMatrix,- RANGE_TYPE,- Rectangle,Tools,UniverInstanceType,} from '@univerjs/core';+import { deserializeRangeWithSheet,ErrorType,FormulaDataModel,generateStringWithSequence,+ IDefinedNamesService,initSheetFormulaData,LexerTreeBuilder,sequenceNodeType,@@ -68,82 +56,18 @@ import { deserializeRangeWithSheet,import {ClearSelectionFormatCommand,- DeleteRangeMoveLeftCommand,- DeleteRangeMoveUpCommand,- EffectRefRangId,- handleDeleteRangeMoveLeft,- handleDeleteRangeMoveUp,- handleInsertCol,- handleInsertRangeMoveDown,- handleInsertRangeMoveRight,- handleInsertRow,- handleIRemoveCol,- handleIRemoveRow,- handleMoveCols,- handleMoveRange,- handleMoveRows,- InsertColCommand,- InsertRangeMoveDownCommand,- InsertRangeMoveRightCommand,- InsertRowCommand,InsertSheetMutation,- MoveColsCommand,- MoveRangeCommand,- MoveRowsCommand,- RemoveColCommand,- RemoveRowCommand,- RemoveSheetCommand,RemoveSheetMutation,- runRefRangeMutations,SetBorderCommand,SetRangeValuesMutation,SetStyleCommand,- SetWorksheetNameCommand,SheetInterceptorService,} from '@univerjs/sheets';import { map } from 'rxjs';import { removeFormulaData } from './utils/offset-formula-data';-import { formulaDataToCellData, getFormulaReferenceMoveUndoRedo } from './utils/ref-range-formula';--interface IUnitRangeWithOffset extends IUnitRange {- refOffsetX: number;- refOffsetY: number;- sheetName: string;-}--enum FormulaReferenceMoveType {- MoveRange, // range- MoveRows, // move rows- MoveCols, // move columns- InsertRow, // row- InsertColumn, // column- RemoveRow, // row- RemoveColumn, // column- DeleteMoveLeft, // range- DeleteMoveUp, // range- InsertMoveDown, // range- InsertMoveRight, // range- SetName,- RemoveSheet,-}--interface IFormulaReferenceMoveParam {- type: FormulaReferenceMoveType;- unitId: string;- sheetId: string;- range?: IRange;- from?: IRange;- to?: IRange;- sheetName?: string;-}--enum OriginRangeEdgeType {- UP,- DOWN,- LEFT,- RIGHT,- ALL,-}+import { checkIsSameUnitAndSheet, formulaDataToCellData, FormulaReferenceMoveType, getFormulaReferenceMoveUndoRedo, updateRefOffset } from './utils/ref-range-formula';+import { getNewRangeByMoveParam } from './utils/ref-range-move';+import { getReferenceMoveParams } from './utils/ref-range-param';/*** Update formula process@@ -163,6 +87,7 @@ export class UpdateFormulaController extends Disposable {@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,@Inject(Injector) readonly _injector: Injector) {super();@@ -337,51 +262,17 @@ export class UpdateFormulaController extends Disposable {}private _getUpdateFormula(command: ICommandInfo) {- const { id } = command;- let result: Nullable<IFormulaReferenceMoveParam> = null;-- switch (id) {- case MoveRangeCommand.id:- result = this._handleMoveRange(command as ICommandInfo<IMoveRangeCommandParams>);- break;- case MoveRowsCommand.id:- result = this._handleMoveRows(command as ICommandInfo<IMoveRowsCommandParams>);- break;- case MoveColsCommand.id:- result = this._handleMoveCols(command as ICommandInfo<IMoveColsCommandParams>);- break;- case InsertRowCommand.id:- result = this._handleInsertRow(command as ICommandInfo<IInsertRowCommandParams>);- break;- case InsertColCommand.id:- result = this._handleInsertCol(command as ICommandInfo<IInsertColCommandParams>);- break;- case InsertRangeMoveRightCommand.id:- result = this._handleInsertRangeMoveRight(command as ICommandInfo<InsertRangeMoveRightCommandParams>);- break;- case InsertRangeMoveDownCommand.id:- result = this._handleInsertRangeMoveDown(command as ICommandInfo<InsertRangeMoveDownCommandParams>);- break;- case RemoveRowCommand.id:- result = this._handleRemoveRow(command as ICommandInfo<IRemoveRowColCommandParams>);- break;- case RemoveColCommand.id:- result = this._handleRemoveCol(command as ICommandInfo<IRemoveRowColCommandParams>);- break;- case DeleteRangeMoveUpCommand.id:- result = this._handleDeleteRangeMoveUp(command as ICommandInfo<IDeleteRangeMoveUpCommandParams>);- break;- case DeleteRangeMoveLeftCommand.id:- result = this._handleDeleteRangeMoveLeft(command as ICommandInfo<IDeleteRangeMoveLeftCommandParams>);- break;- case SetWorksheetNameCommand.id:- result = this._handleSetWorksheetName(command as ICommandInfo<ISetWorksheetNameCommandParams>);- break;- case RemoveSheetCommand.id:- result = this._handleRemoveWorksheet(command as ICommandInfo<IRemoveSheetCommandParams>);- break;+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);++ if (!workbook) {+ return {+ undos: [],+ redos: [],+ };}+ const result = getReferenceMoveParams(workbook, command);+if (result) {const { unitSheetNameMap } = this._formulaDataModel.getCalculateData();const oldFormulaData = this._formulaDataModel.getFormulaData();@@ -407,251 +298,6 @@ export class UpdateFormulaController extends Disposable {};}- private _handleMoveRange(command: ICommandInfo<IMoveRangeCommandParams>) {- const { params } = command;- if (!params) return null;-- const { fromRange, toRange } = params;- if (!fromRange || !toRange) return null;-- const { unitId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.MoveRange,- from: fromRange,- to: toRange,- unitId,- sheetId,- };- }-- private _handleMoveRows(command: ICommandInfo<IMoveRowsCommandParams>) {- const { params } = command;- if (!params) return null;-- const {- fromRange: { startRow: fromStartRow, endRow: fromEndRow },- toRange: { startRow: toStartRow, endRow: toEndRow },- } = params;-- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const unitId = workbook.getUnitId();- const worksheet = workbook.getActiveSheet();- if (!worksheet) return null;-- const sheetId = worksheet.getSheetId();-- const from = {- startRow: fromStartRow,- startColumn: 0,- endRow: fromEndRow,- endColumn: worksheet.getColumnCount() - 1,- rangeType: RANGE_TYPE.ROW,- };- const to = {- startRow: toStartRow,- startColumn: 0,- endRow: toEndRow,- endColumn: worksheet.getColumnCount() - 1,- rangeType: RANGE_TYPE.ROW,- };-- return {- type: FormulaReferenceMoveType.MoveRows,- from,- to,- unitId,- sheetId,- };- }-- private _handleMoveCols(command: ICommandInfo<IMoveColsCommandParams>) {- const { params } = command;- if (!params) return null;-- const {- fromRange: { startColumn: fromStartCol, endColumn: fromEndCol },- toRange: { startColumn: toStartCol, endColumn: toEndCol },- } = params;-- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const unitId = workbook.getUnitId();- const worksheet = workbook.getActiveSheet();- if (!worksheet) return null;-- const sheetId = worksheet.getSheetId();-- const from = {- startRow: 0,- startColumn: fromStartCol,- endRow: worksheet.getRowCount() - 1,- endColumn: fromEndCol,- rangeType: RANGE_TYPE.COLUMN,- };- const to = {- startRow: 0,- startColumn: toStartCol,- endRow: worksheet.getRowCount() - 1,- endColumn: toEndCol,- rangeType: RANGE_TYPE.COLUMN,- };-- return {- type: FormulaReferenceMoveType.MoveCols,- from,- to,- unitId,- sheetId,- };- }-- private _handleInsertRow(command: ICommandInfo<IInsertRowCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range, unitId, subUnitId } = params;- return {- type: FormulaReferenceMoveType.InsertRow,- range,- unitId,- sheetId: subUnitId,- };- }-- private _handleInsertCol(command: ICommandInfo<IInsertColCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range, unitId, subUnitId } = params;- return {- type: FormulaReferenceMoveType.InsertColumn,- range,- unitId,- sheetId: subUnitId,- };- }-- private _handleInsertRangeMoveRight(command: ICommandInfo<InsertRangeMoveRightCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range } = params;- const { unitId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.InsertMoveRight,- range,- unitId,- sheetId,- };- }-- private _handleInsertRangeMoveDown(command: ICommandInfo<InsertRangeMoveDownCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range } = params;- const { unitId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.InsertMoveDown,- range,- unitId,- sheetId,- };- }-- private _handleRemoveRow(command: ICommandInfo<IRemoveRowColCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range } = params;- const { unitId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.RemoveRow,- range,- unitId,- sheetId,- };- }-- private _handleRemoveCol(command: ICommandInfo<IRemoveRowColCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range } = params;- const { unitId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.RemoveColumn,- range,- unitId,- sheetId,- };- }-- private _handleDeleteRangeMoveUp(command: ICommandInfo<IDeleteRangeMoveUpCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range } = params;- const { unitId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.DeleteMoveUp,- range,- unitId,- sheetId,- };- }-- private _handleDeleteRangeMoveLeft(command: ICommandInfo<IDeleteRangeMoveLeftCommandParams>) {- const { params } = command;- if (!params) return null;-- const { range } = params;- const { unitId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.DeleteMoveLeft,- range,- unitId,- sheetId,- };- }-- private _handleSetWorksheetName(command: ICommandInfo<ISetWorksheetNameCommandParams>) {- const { params } = command;- if (!params) return null;-- const { unitId, subUnitId, name } = params;-- const { unitId: workbookId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.SetName,- unitId: unitId || workbookId,- sheetId: subUnitId || sheetId,- sheetName: name,- };- }-- private _handleRemoveWorksheet(command: ICommandInfo<IRemoveSheetCommandParams>) {- const { params } = command;- if (!params) return null;-- const { unitId, subUnitId } = params;-- const { unitId: workbookId, sheetId } = this._getCurrentSheetInfo();-- return {- type: FormulaReferenceMoveType.RemoveSheet,- unitId: unitId || workbookId,- sheetId: subUnitId || sheetId,- };- }-// eslint-disable-next-line max-lines-per-functionprivate _getFormulaReferenceMoveInfo(formulaData: IFormulaData,@@ -705,10 +351,49 @@ export class UpdateFormulaController extends Disposable {const refChangeIds: number[] = [];for (let i = 0, len = sequenceNodes.length; i < len; i++) {const node = sequenceNodes[i];- if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {++ if (typeof node === 'string') {+ continue;+ }++ const { token, nodeType } = node;+ const { type } = formulaReferenceMoveParam;++ // The impact of defined name changes on formula calculation+ // 1. ref range only changes formulaOrRefString to trigger recalculation+ // 2. set defined name command, change name to trigger formula update, otherwise trigger recalculation+ // 3. remove defined name command, change name to #REF! to trigger formula update+ // 4. insert defined name No processing required+ // 5. remove sheet, trigger recalculation+ // FIXME: Why is the node type of defined name 3?+ if ((type === FormulaReferenceMoveType.SetDefinedName || type === FormulaReferenceMoveType.RemoveDefinedName) && (nodeType === sequenceNodeType.DEFINED_NAME || nodeType === sequenceNodeType.FUNCTION)) {+ const { definedNameId, definedName } = formulaReferenceMoveParam;+ if (definedNameId === undefined || definedName === undefined) {+ continue;+ }++ const oldDefinedName = this._definedNamesService.getValueById(unitId, definedNameId);+ if (oldDefinedName === undefined || oldDefinedName === null) {+ continue;+ }++ // Make sure the current token is the defined name to be updated.+ if (oldDefinedName.name !== token) {+ continue;+ }++ // Update the defined name in the formula, if the defined name is removed, update the token to #REF!+ sequenceNodes[i] = {+ ...node,+ token: type === FormulaReferenceMoveType.SetDefinedName ? definedName : ErrorType.REF,+ };+ shouldModify = true;+ refChangeIds.push(i);++ continue;+ } else if (nodeType !== sequenceNodeType.REFERENCE) {continue;}- const { token } = node;const sequenceGrid = deserializeRangeWithSheet(token);@@ -717,22 +402,22 @@ export class UpdateFormulaController extends Disposable {const mapUnitId =sequenceUnitId == null || sequenceUnitId.length === 0 ? unitId : sequenceUnitId;- const sequenceSheetId = unitSheetNameMap?.[mapUnitId]?.[sheetName];+ const sequenceSheetId = unitSheetNameMap?.[mapUnitId]?.[sheetName] || '';if (- !this._checkIsSameUnitAndSheet(+ !checkIsSameUnitAndSheet(formulaReferenceMoveParam.unitId,formulaReferenceMoveParam.sheetId,unitId,sheetId,sequenceUnitId,- sequenceSheetId || ''+ sequenceSheetId)) {continue;}- const sequenceUnitRangeWidthOffset = {+ const sequenceUnitRangeWidthOffset: IUnitRangeWithOffset = {range,sheetId: sequenceSheetId,unitId: sequenceUnitId,@@ -743,7 +428,7 @@ export class UpdateFormulaController extends Disposable {let newRefString: Nullable<string> = null;- if (formulaReferenceMoveParam.type === FormulaReferenceMoveType.SetName) {+ if (type === FormulaReferenceMoveType.SetName) {const {unitId: userUnitId,sheetId: userSheetId,@@ -766,7 +451,7 @@ export class UpdateFormulaController extends Disposable {sheetName: newSheetName,unitId: sequenceUnitId,});- } else if (formulaReferenceMoveParam.type === FormulaReferenceMoveType.RemoveSheet) {+ } else if (type === FormulaReferenceMoveType.RemoveSheet) {const {unitId: userUnitId,sheetId: userSheetId,@@ -782,9 +467,9 @@ export class UpdateFormulaController extends Disposable {}newRefString = ErrorType.REF;- } else {- newRefString = this._getNewRangeByMoveParam(- sequenceUnitRangeWidthOffset as IUnitRangeWithOffset,+ } else if (type !== FormulaReferenceMoveType.SetDefinedName) {+ newRefString = getNewRangeByMoveParam(+ sequenceUnitRangeWidthOffset,formulaReferenceMoveParam,unitId,sheetId@@ -806,7 +491,7 @@ export class UpdateFormulaController extends Disposable {return true;}- const newSequenceNodes = this._updateRefOffset(sequenceNodes, refChangeIds, x, y);+ const newSequenceNodes = updateRefOffset(sequenceNodes, refChangeIds, x, y);newFormulaDataItem.setValue(row, column, {f: `=${generateStringWithSequence(newSequenceNodes)}`,@@ -821,606 +506,4 @@ export class UpdateFormulaController extends Disposable {return { newFormulaData };}-- // eslint-disable-next-line- private _getNewRangeByMoveParam(- unitRangeWidthOffset: IUnitRangeWithOffset,- formulaReferenceMoveParam: IFormulaReferenceMoveParam,- currentFormulaUnitId: string,- currentFormulaSheetId: string- ) {- const { type, unitId: userUnitId, sheetId: userSheetId, range, from, to } = formulaReferenceMoveParam;-- const {- range: unitRange,- sheetId: sequenceRangeSheetId,- unitId: sequenceRangeUnitId,- sheetName: sequenceRangeSheetName,- refOffsetX,- refOffsetY,- } = unitRangeWidthOffset;-- if (- !this._checkIsSameUnitAndSheet(- userUnitId,- userSheetId,- currentFormulaUnitId,- currentFormulaSheetId,- sequenceRangeUnitId,- sequenceRangeSheetId- )- ) {- return;- }-- const sequenceRange = Rectangle.moveOffset(unitRange, refOffsetX, refOffsetY);- let newRange: Nullable<IRange> = null;-- if (type === FormulaReferenceMoveType.MoveRange) {- if (from == null || to == null) {- return;- }-- const moveEdge = this._checkMoveEdge(sequenceRange, from);-- const remainRange = Rectangle.getIntersects(sequenceRange, from);-- if (remainRange == null || moveEdge !== OriginRangeEdgeType.ALL) {- return;- }-- const operators = handleMoveRange(- { id: EffectRefRangId.MoveRangeCommandId, params: { toRange: to, fromRange: from } },- remainRange- );-- const result = runRefRangeMutations(operators, remainRange);-- if (result == null) {- return ErrorType.REF;- }-- newRange = this._getMoveNewRange(moveEdge, result, from, to, sequenceRange, remainRange);- } else if (type === FormulaReferenceMoveType.MoveRows) {- if (from == null || to == null) {- return;- }-- const moveEdge = this._checkMoveEdge(sequenceRange, from);-- let remainRange = Rectangle.getIntersects(sequenceRange, from);-- if (- remainRange == null &&- ((from.endRow < sequenceRange.startRow && to.endRow < sequenceRange.startRow) || (from.startRow > sequenceRange.endRow && to.startRow > sequenceRange.endRow))- ) {- return;- }-- if (remainRange == null) {- remainRange = {- startRow: sequenceRange.startRow,- endRow: sequenceRange.endRow,- startColumn: sequenceRange.startColumn,- endColumn: sequenceRange.endColumn,- rangeType: RANGE_TYPE.NORMAL,- };- }-- const operators = handleMoveRows(- { id: EffectRefRangId.MoveRowsCommandId, params: { toRange: to, fromRange: from } },- remainRange- );-- const result = runRefRangeMutations(operators, remainRange);-- if (result == null) {- return ErrorType.REF;- }-- newRange = this._getMoveNewRange(moveEdge, result, from, to, sequenceRange, remainRange);- } else if (type === FormulaReferenceMoveType.MoveCols) {- if (from == null || to == null) {- return;- }-- const moveEdge = this._checkMoveEdge(sequenceRange, from);-- let remainRange = Rectangle.getIntersects(sequenceRange, from);-- if (- remainRange == null &&- ((from.endColumn < sequenceRange.startColumn && to.endColumn < sequenceRange.startColumn) || (from.startColumn > sequenceRange.endColumn && to.startColumn > sequenceRange.endColumn))- ) {- return;- }-- if (remainRange == null) {- remainRange = {- startRow: sequenceRange.startRow,- endRow: sequenceRange.endRow,- startColumn: sequenceRange.startColumn,- endColumn: sequenceRange.endColumn,- rangeType: RANGE_TYPE.NORMAL,- };- }-- const operators = handleMoveCols(- { id: EffectRefRangId.MoveColsCommandId, params: { toRange: to, fromRange: from } },- remainRange- );-- const result = runRefRangeMutations(operators, remainRange);-- if (result == null) {- return ErrorType.REF;- }-- newRange = this._getMoveNewRange(moveEdge, result, from, to, sequenceRange, remainRange);- }-- if (range != null) {- if (type === FormulaReferenceMoveType.InsertRow) {- const operators = handleInsertRow(- {- id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: Direction.DOWN },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return;- }-- newRange = {- ...sequenceRange,- ...result,- };- } else if (type === FormulaReferenceMoveType.InsertColumn) {- const operators = handleInsertCol(- {- id: EffectRefRangId.InsertColCommandId,- params: { range, unitId: '', subUnitId: '', direction: Direction.RIGHT },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return;- }-- newRange = {- ...sequenceRange,- ...result,- };- } else if (type === FormulaReferenceMoveType.RemoveRow) {- const operators = handleIRemoveRow(- {- id: EffectRefRangId.RemoveRowCommandId,- params: { range },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return ErrorType.REF;- }-- newRange = {- ...sequenceRange,- ...result,- };- } else if (type === FormulaReferenceMoveType.RemoveColumn) {- const operators = handleIRemoveCol(- {- id: EffectRefRangId.RemoveColCommandId,- params: { range },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return ErrorType.REF;- }-- newRange = {- ...sequenceRange,- ...result,- };- } else if (type === FormulaReferenceMoveType.DeleteMoveLeft) {- const operators = handleDeleteRangeMoveLeft(- {- id: EffectRefRangId.DeleteRangeMoveLeftCommandId,- params: { range },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return ErrorType.REF;- }-- newRange = {- ...sequenceRange,- ...result,- };- } else if (type === FormulaReferenceMoveType.DeleteMoveUp) {- const operators = handleDeleteRangeMoveUp(- {- id: EffectRefRangId.DeleteRangeMoveUpCommandId,- params: { range },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return ErrorType.REF;- }-- newRange = {- ...sequenceRange,- ...result,- };- } else if (type === FormulaReferenceMoveType.InsertMoveDown) {- const operators = handleInsertRangeMoveDown(- {- id: EffectRefRangId.InsertRangeMoveDownCommandId,- params: { range },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return;- }-- newRange = {- ...sequenceRange,- ...result,- };- } else if (type === FormulaReferenceMoveType.InsertMoveRight) {- const operators = handleInsertRangeMoveRight(- {- id: EffectRefRangId.InsertRangeMoveRightCommandId,- params: { range },- },- sequenceRange- );-- const result = runRefRangeMutations(operators, sequenceRange);-- if (result == null) {- return;- }-- newRange = {- ...sequenceRange,- ...result,- };- }- }-- if (newRange == null) {- return;- }-- return serializeRangeToRefString({- range: newRange,- sheetName: sequenceRangeSheetName,- unitId: sequenceRangeUnitId,- });- }-- private _checkIsSameUnitAndSheet(- userUnitId: string,- userSheetId: string,- currentFormulaUnitId: string,- currentFormulaSheetId: string,- sequenceRangeUnitId: string,- sequenceRangeSheetId: string- ) {- if (- (sequenceRangeUnitId == null || sequenceRangeUnitId.length === 0) &&- (sequenceRangeSheetId == null || sequenceRangeSheetId.length === 0)- ) {- if (userUnitId === currentFormulaUnitId && userSheetId === currentFormulaSheetId) {- return true;- }- } else if (- (userUnitId === sequenceRangeUnitId || sequenceRangeUnitId == null || sequenceRangeUnitId.length === 0) &&- userSheetId === sequenceRangeSheetId- ) {- return true;- }-- return false;- }-- /**- * Update all ref nodes to the latest offset state.- */- private _updateRefOffset(- sequenceNodes: Array<string | ISequenceNode>,- refChangeIds: number[],- refOffsetX: number = 0,- refOffsetY: number = 0- ) {- const newSequenceNodes: Array<string | ISequenceNode> = [];- for (let i = 0, len = sequenceNodes.length; i < len; i++) {- const node = sequenceNodes[i];- if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE || refChangeIds.includes(i)) {- newSequenceNodes.push(node);- continue;- }-- const { token } = node;-- const sequenceGrid = deserializeRangeWithSheet(token);-- const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;-- const newRange = Rectangle.moveOffset(range, refOffsetX, refOffsetY);-- newSequenceNodes.push({- ...node,- token: serializeRangeToRefString({- range: newRange,- unitId: sequenceUnitId,- sheetName,- }),- });- }-- return newSequenceNodes;- }-- /**- * Determine the range of the moving selection,- * and check if it is at the edge of the reference range of the formula.- * @param originRange- * @param fromRange- */- // eslint-disable-next-line- private _checkMoveEdge(originRange: IRange, fromRange: IRange): Nullable<OriginRangeEdgeType> {- const { startRow, startColumn, endRow, endColumn } = originRange;-- const {- startRow: fromStartRow,- startColumn: fromStartColumn,- endRow: fromEndRow,- endColumn: fromEndColumn,- } = fromRange;-- if (- startRow >= fromStartRow &&- endRow <= fromEndRow &&- startColumn >= fromStartColumn &&- endColumn <= fromEndColumn- ) {- return OriginRangeEdgeType.ALL;- }-- if (- startColumn >= fromStartColumn &&- endColumn <= fromEndColumn &&- startRow >= fromStartRow &&- startRow <= fromEndRow &&- endRow > fromEndRow- ) {- return OriginRangeEdgeType.UP;- }-- if (- startColumn >= fromStartColumn &&- endColumn <= fromEndColumn &&- endRow >= fromStartRow &&- endRow <= fromEndRow &&- startRow < fromStartRow- ) {- return OriginRangeEdgeType.DOWN;- }-- if (- startRow >= fromStartRow &&- endRow <= fromEndRow &&- startColumn >= fromStartColumn &&- startColumn <= fromEndColumn &&- endColumn > fromEndColumn- ) {- return OriginRangeEdgeType.LEFT;- }-- if (- startRow >= fromStartRow &&- endRow <= fromEndRow &&- endColumn >= fromStartColumn &&- endColumn <= fromEndColumn &&- startColumn < fromStartColumn- ) {- return OriginRangeEdgeType.RIGHT;- }- }-- /**- * Calculate the new ref information for the moving selection.- * @param moveEdge the 'from' range lie on the edge of the original range, or does it completely cover the original range- * @param result The original range is divided by 'from' and moved to a new position range.- * @param from The initial range of the moving selection.- * @param to The result range after moving the initial range.- * @param origin The original target range.- * @param remain "The range subtracted from the initial range by 'from'.- * @returns- */- // eslint-disable-next-line- private _getMoveNewRange(- moveEdge: Nullable<OriginRangeEdgeType>,- result: IRange,- from: IRange,- to: IRange,- origin: IRange,- remain: IRange- ) {- const { startRow, endRow, startColumn, endColumn } = result;-- const {- startRow: fromStartRow,- startColumn: fromStartColumn,- endRow: fromEndRow,- endColumn: fromEndColumn,- rangeType: fromRangeType = RANGE_TYPE.NORMAL,- } = from;-- const { startRow: toStartRow, startColumn: toStartColumn, endRow: toEndRow, endColumn: toEndColumn } = to;-- const {- startRow: remainStartRow,- endRow: remainEndRow,- startColumn: remainStartColumn,- endColumn: remainEndColumn,- } = remain;-- const {- startRow: originStartRow,- endRow: originEndRow,- startColumn: originStartColumn,- endColumn: originEndColumn,- } = origin;-- const newRange = { ...origin };-- if (moveEdge === OriginRangeEdgeType.UP) {- if (startColumn === originStartColumn && endColumn === originEndColumn) {- if (startRow < originStartRow) {- newRange.startRow = startRow;- } else if (startRow >= originEndRow) {- newRange.endRow -= fromEndRow + 1 - originStartRow;- } else {- return;- }- } else {- return;- }- } else if (moveEdge === OriginRangeEdgeType.DOWN) {- if (startColumn === originStartColumn && endColumn === originEndColumn) {- if (endRow > originEndRow) {- newRange.endRow = endRow;- } else if (endRow <= originStartRow) {- newRange.startRow += originEndRow - fromStartRow + 1;- } else {- return;- }- } else {- return;- }- } else if (moveEdge === OriginRangeEdgeType.LEFT) {- if (startRow === originStartRow && endRow === originEndRow) {- if (startColumn < originStartColumn) {- newRange.startColumn = startColumn;- } else if (startColumn >= originEndColumn) {- newRange.endColumn -= fromEndColumn + 1 - originStartColumn;- } else {- return;- }- } else {- return;- }- } else if (moveEdge === OriginRangeEdgeType.RIGHT) {- if (startRow === originStartRow && endRow === originEndRow) {- if (endColumn > originEndColumn) {- newRange.endColumn = endColumn;- } else if (endColumn <= originStartColumn) {- newRange.startColumn += originEndColumn - fromStartColumn + 1;- } else {- return;- }- } else {- return;- }- } else if (moveEdge === OriginRangeEdgeType.ALL) {- newRange.startRow = startRow;- newRange.startColumn = startColumn;- newRange.endRow = endRow;- newRange.endColumn = endColumn;- } else if (fromStartColumn <= originStartColumn && fromEndColumn >= originEndColumn) {- if (from.endRow < originStartRow) {- if (toStartRow >= originStartRow) {- newRange.startRow -= fromEndRow - fromStartRow + 1;- }- if (toStartRow >= originEndRow) {- newRange.endRow -= fromEndRow - fromStartRow + 1;- }- } else if (from.startRow > originEndRow) {- if (toEndRow <= originEndRow) {- newRange.endRow += fromEndRow - fromStartRow + 1;- }- if (toEndRow <= originStartRow) {- newRange.startRow += fromEndRow - fromStartRow + 1;- }- }- } else if (fromStartRow <= originStartRow && fromEndRow >= originEndRow) {- if (from.endColumn < originStartColumn) {- if (toStartColumn >= originStartColumn) {- newRange.startColumn -= fromEndColumn - fromStartColumn + 1;- }- if (toStartColumn >= originEndColumn) {- newRange.endColumn -= fromEndColumn - fromStartColumn + 1;- }- } else if (from.startColumn > originEndColumn) {- if (toEndColumn <= originEndColumn) {- newRange.endColumn += fromEndColumn - fromStartColumn + 1;- }- if (toEndColumn <= originStartColumn) {- newRange.startColumn += fromEndColumn - fromStartColumn + 1;- }- }- } else if (- ((toStartColumn <= remainEndColumn + 1 && toEndColumn >= originEndColumn) ||- (toStartColumn <= originStartColumn && toEndColumn >= remainStartColumn - 1)) &&- toStartRow <= originStartRow &&- toEndRow >= originEndRow- ) {- newRange.startRow = startRow;- newRange.startColumn = startColumn;- newRange.endRow = endRow;- newRange.endColumn = endColumn;- } else if (- ((toStartRow <= remainEndRow + 1 && toEndRow >= originEndRow) ||- (toStartRow <= originStartRow && toEndRow >= remainStartRow - 1)) &&- toStartColumn <= originStartColumn &&- toEndColumn >= originEndColumn- ) {- newRange.startRow = startRow;- newRange.startColumn = startColumn;- newRange.endRow = endRow;- newRange.endColumn = endColumn;- }-- return newRange;- }-- private _getCurrentSheetInfo() {- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const unitId = workbook.getUnitId();- const sheetId = workbook.getActiveSheet()?.getSheetId() || '';-- return {- unitId,- sheetId,- };- }}diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-move.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-move.spec.tsnew file mode 100644index 0000000000..86c7055515--- /dev/null+++ b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-move.spec.ts@@ -0,0 +1,336 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { RANGE_TYPE } from '@univerjs/core';++import { describe, expect, it } from 'vitest';+import { checkMoveEdge, OriginRangeEdgeType } from '../ref-range-move';++describe('checkMoveEdge', () => {+ it('should return ALL when originRange is completely within fromRange', () => {+ const originRange = {+ startRow: 2,+ endRow: 4,+ startColumn: 2,+ endColumn: 4,+ };++ const fromRange = {+ startRow: 1,+ endRow: 5,+ startColumn: 1,+ endColumn: 5,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.ALL);+ });++ it('should return UP when fromRange is at the top edge of originRange', () => {+ const originRange = {+ startRow: 2,+ endRow: 6,+ startColumn: 2,+ endColumn: 4,+ };++ const fromRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 2,+ endColumn: 4,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.UP);+ });++ it('should return DOWN when fromRange is at the bottom edge of originRange', () => {+ const originRange = {+ startRow: 1,+ endRow: 4,+ startColumn: 2,+ endColumn: 4,+ };++ const fromRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 2,+ endColumn: 4,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.DOWN);+ });++ it('should return LEFT when fromRange is at the left edge of originRange', () => {+ const originRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 2,+ endColumn: 6,+ };++ const fromRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 2,+ endColumn: 5,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.LEFT);+ });++ it('should return RIGHT when fromRange is at the right edge of originRange', () => {+ const originRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 1,+ endColumn: 4,+ };++ const fromRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 2,+ endColumn: 4,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.RIGHT);+ });++ it('should return null when fromRange is outside originRange', () => {+ const originRange = {+ startRow: 6,+ endRow: 8,+ startColumn: 6,+ endColumn: 8,+ };++ const fromRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 2,+ endColumn: 5,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBeNull();+ });++ it('should handle NaN values correctly when originRange is an entire row', () => {+ const originRange = {+ startRow: 2,+ endRow: 3,+ startColumn: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ const fromRange = {+ startRow: 2,+ endRow: 2,+ startColumn: 0,+ endColumn: 10,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBeNull();++ const originRange2 = {+ startRow: 2,+ endRow: 3,+ startColumn: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ const fromRange2 = {+ startRow: 2,+ endRow: 2,+ startColumn: 0,+ endColumn: 10,+ rangeType: RANGE_TYPE.ROW,+ };++ expect(checkMoveEdge(originRange2, fromRange2)).toBe(OriginRangeEdgeType.UP);+ });++ it('should handle NaN values correctly when originRange is an entire column', () => {+ const originRange = {+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: 3,+ endColumn: 4,+ rangeType: RANGE_TYPE.COLUMN,+ };++ const fromRange = {+ startRow: 0,+ endRow: 10,+ startColumn: 3,+ endColumn: 3,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBeNull();++ const originRange2 = {+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: 3,+ endColumn: 4,+ rangeType: RANGE_TYPE.COLUMN,+ };++ const fromRange2 = {+ startRow: 0,+ endRow: 10,+ startColumn: 3,+ endColumn: 3,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(checkMoveEdge(originRange2, fromRange2)).toBe(OriginRangeEdgeType.LEFT);+ });++ it('should handle NaN values correctly when originRange is the entire sheet', () => {+ const originRange = {+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ const fromRange = {+ startRow: 0,+ endRow: 100,+ startColumn: 0,+ endColumn: 100,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBeNull();++ const originRange2 = {+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ const fromRange2 = {+ startRow: 0,+ endRow: 100,+ startColumn: 0,+ endColumn: 100,+ rangeType: RANGE_TYPE.ALL,+ };++ expect(checkMoveEdge(originRange2, fromRange2)).toBe(OriginRangeEdgeType.ALL);+ });++ it('should return UP when fromRange is at the top edge of originRange (an entire row)', () => {+ const originRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 1,+ endColumn: 10,+ };++ const fromRange = {+ startRow: 2,+ endRow: 4,+ startColumn: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.UP);+ });++ it('should return DOWN when fromRange is at the bottom edge of originRange (an entire row)', () => {+ const originRange = {+ startRow: 2,+ endRow: 5,+ startColumn: 1,+ endColumn: 10,+ };++ const fromRange = {+ startRow: 3,+ endRow: 5,+ startColumn: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ROW,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.DOWN);+ });++ it('should return LEFT when fromRange is at the left edge of originRange (an entire column)', () => {+ const originRange = {+ startRow: 1,+ endRow: 10,+ startColumn: 3,+ endColumn: 5,+ };++ const fromRange = {+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: 3,+ endColumn: 4,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.LEFT);+ });++ it('should return RIGHT when fromRange is at the right edge of originRange (an entire column)', () => {+ const originRange = {+ startRow: 1,+ endRow: 10,+ startColumn: 2,+ endColumn: 4,+ };++ const fromRange = {+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: 3,+ endColumn: 4,+ rangeType: RANGE_TYPE.COLUMN,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.RIGHT);+ });++ it('should handle when fromRange is entirely unbounded (entire sheet)', () => {+ const originRange = {+ startRow: 0,+ endRow: 100,+ startColumn: 0,+ endColumn: 100,+ };++ const fromRange = {+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: Number.NaN,+ endColumn: Number.NaN,+ rangeType: RANGE_TYPE.ALL,+ };++ expect(checkMoveEdge(originRange, fromRange)).toBe(OriginRangeEdgeType.ALL);+ });+});diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.tsindex 2a85859634..61d45d7926 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix } from '@univerjs/core';-import { EffectRefRangId, handleDeleteRangeMoveLeft, handleDeleteRangeMoveUp, handleInsertCol, handleInsertRangeMoveDown, handleInsertRangeMoveRight, handleInsertRow, handleIRemoveCol, handleIRemoveRow, handleMoveCols, handleMoveRange, handleMoveRows, runRefRangeMutations, SetRangeValuesMutation } from '@univerjs/sheets';import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';-import type { IFormulaData, IFormulaDataItem, IRangeChange } from '@univerjs/engine-formula';import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';+import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix, Rectangle } from '@univerjs/core';+import { deserializeRangeWithSheet, type IFormulaData, type IFormulaDataItem, type IRangeChange, type ISequenceNode, sequenceNodeType, serializeRangeToRefString } from '@univerjs/engine-formula';+import { EffectRefRangId, handleDeleteRangeMoveLeft, handleDeleteRangeMoveUp, handleInsertCol, handleInsertRangeMoveDown, handleInsertRangeMoveRight, handleInsertRow, handleIRemoveCol, handleIRemoveRow, handleMoveCols, handleMoveRange, handleMoveRows, runRefRangeMutations, SetRangeValuesMutation } from '@univerjs/sheets';import { checkFormulaDataNull } from './offset-formula-data';export enum FormulaReferenceMoveType {@@ -35,6 +35,8 @@ export enum FormulaReferenceMoveType {InsertMoveRight, // rangeSetName,RemoveSheet,+ SetDefinedName, // update defined name+ RemoveDefinedName, // remove defined name}export interface IFormulaReferenceMoveParam {@@ -45,14 +47,23 @@ export interface IFormulaReferenceMoveParam {from?: IRange;to?: IRange;sheetName?: string;+ definedNameId?: string; // defined name id+ definedName?: string; // new defined name}+const formulaReferenceSheetList = [+ FormulaReferenceMoveType.SetName,+ FormulaReferenceMoveType.RemoveSheet,+ FormulaReferenceMoveType.SetDefinedName,+ FormulaReferenceMoveType.RemoveDefinedName,+];+export function getFormulaReferenceMoveUndoRedo(oldFormulaData: IFormulaData,newFormulaData: IFormulaData,formulaReferenceMoveParam: IFormulaReferenceMoveParam) {const { type } = formulaReferenceMoveParam;- if (type === FormulaReferenceMoveType.SetName || type === FormulaReferenceMoveType.RemoveSheet) {+ if (formulaReferenceSheetList.includes(type)) {return getFormulaReferenceSheet(oldFormulaData, newFormulaData);} else {return getFormulaReferenceRange(oldFormulaData, newFormulaData, formulaReferenceMoveParam);@@ -581,3 +592,62 @@ export function isFormulaDataItem(cell: IFormulaDataItem) {return false;}+export function checkIsSameUnitAndSheet(+ userUnitId: string,+ userSheetId: string,+ currentFormulaUnitId: string,+ currentFormulaSheetId: string,+ sequenceRangeUnitId: string,+ sequenceRangeSheetId: string+) {+ if (+ (sequenceRangeUnitId == null || sequenceRangeUnitId.length === 0) &&+ (sequenceRangeSheetId == null || sequenceRangeSheetId.length === 0)+ ) {+ if (userUnitId === currentFormulaUnitId && userSheetId === currentFormulaSheetId) {+ return true;+ }+ } else if (+ (userUnitId === sequenceRangeUnitId || sequenceRangeUnitId == null || sequenceRangeUnitId.length === 0) &&+ userSheetId === sequenceRangeSheetId+ ) {+ return true;+ }++ return false;+}++export function updateRefOffset(+ sequenceNodes: Array<string | ISequenceNode>,+ refChangeIds: number[],+ refOffsetX: number = 0,+ refOffsetY: number = 0+) {+ const newSequenceNodes: Array<string | ISequenceNode> = [];+ for (let i = 0, len = sequenceNodes.length; i < len; i++) {+ const node = sequenceNodes[i];+ if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE || refChangeIds.includes(i)) {+ newSequenceNodes.push(node);+ continue;+ }++ const { token } = node;++ const sequenceGrid = deserializeRangeWithSheet(token);++ const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;++ const newRange = Rectangle.moveOffset(range, refOffsetX, refOffsetY);++ newSequenceNodes.push({+ ...node,+ token: serializeRangeToRefString({+ range: newRange,+ unitId: sequenceUnitId,+ sheetName,+ }),+ });+ }++ return newSequenceNodes;+}diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-move.ts b/packages/sheets-formula/src/controllers/utils/ref-range-move.tsnew file mode 100644index 0000000000..e9b844bd61--- /dev/null+++ b/packages/sheets-formula/src/controllers/utils/ref-range-move.ts@@ -0,0 +1,655 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type {+ IRange,+ IUnitRange,+ Nullable,+} from '@univerjs/core';+import {+ Direction,+ getIntersectRange,+ RANGE_TYPE,+ Rectangle,+} from '@univerjs/core';++import { ErrorType, serializeRangeToRefString } from '@univerjs/engine-formula';++import {+ EffectRefRangId,+ handleDeleteRangeMoveLeft,+ handleDeleteRangeMoveUp,+ handleInsertCol,+ handleInsertRangeMoveDown,+ handleInsertRangeMoveRight,+ handleInsertRow,+ handleIRemoveCol,+ handleIRemoveRow,+ handleMoveCols,+ handleMoveRange,+ handleMoveRows,+ runRefRangeMutations,+} from '@univerjs/sheets';+import { checkIsSameUnitAndSheet, FormulaReferenceMoveType, type IFormulaReferenceMoveParam } from './ref-range-formula';++export interface IUnitRangeWithOffset extends IUnitRange {+ refOffsetX: number;+ refOffsetY: number;+ sheetName: string;+}++export enum OriginRangeEdgeType {+ UP,+ DOWN,+ LEFT,+ RIGHT,+ ALL,+}++// eslint-disable-next-line max-lines-per-function, complexity+export function getNewRangeByMoveParam(+ unitRangeWidthOffset: IUnitRangeWithOffset,+ formulaReferenceMoveParam: IFormulaReferenceMoveParam,+ currentFormulaUnitId: string,+ currentFormulaSheetId: string+) {+ const { type, unitId: userUnitId, sheetId: userSheetId, range, from, to } = formulaReferenceMoveParam;++ const {+ range: unitRange,+ sheetId: sequenceRangeSheetId,+ unitId: sequenceRangeUnitId,+ sheetName: sequenceRangeSheetName,+ refOffsetX,+ refOffsetY,+ } = unitRangeWidthOffset;++ if (+ !checkIsSameUnitAndSheet(+ userUnitId,+ userSheetId,+ currentFormulaUnitId,+ currentFormulaSheetId,+ sequenceRangeUnitId,+ sequenceRangeSheetId+ )+ ) {+ return;+ }++ const sequenceRange = Rectangle.moveOffset(unitRange, refOffsetX, refOffsetY);+ let newRange: Nullable<IRange> = null;++ if (type === FormulaReferenceMoveType.MoveRange) {+ if (from == null || to == null) {+ return;+ }++ const moveEdge = checkMoveEdge(sequenceRange, from);++ const remainRange = getIntersectRange(sequenceRange, from);++ if (remainRange == null || moveEdge !== OriginRangeEdgeType.ALL) {+ return;+ }++ const operators = handleMoveRange(+ { id: EffectRefRangId.MoveRangeCommandId, params: { toRange: to, fromRange: from } },+ remainRange+ );++ const result = runRefRangeMutations(operators, remainRange);++ if (result == null) {+ return ErrorType.REF;+ }++ newRange = getMoveNewRange(moveEdge, result, from, to, sequenceRange, remainRange);+ } else if (type === FormulaReferenceMoveType.MoveRows) {+ if (from == null || to == null) {+ return;+ }++ const moveEdge = checkMoveEdge(sequenceRange, from);++ let remainRange = getIntersectRange(sequenceRange, from);++ if (+ remainRange == null &&+ ((from.endRow < sequenceRange.startRow && to.endRow < sequenceRange.startRow) || (from.startRow > sequenceRange.endRow && to.startRow > sequenceRange.endRow))+ ) {+ return;+ }++ if (remainRange == null) {+ remainRange = {+ startRow: sequenceRange.startRow,+ endRow: sequenceRange.endRow,+ startColumn: sequenceRange.startColumn,+ endColumn: sequenceRange.endColumn,+ rangeType: RANGE_TYPE.NORMAL,+ };+ }++ const operators = handleMoveRows(+ { id: EffectRefRangId.MoveRowsCommandId, params: { toRange: to, fromRange: from } },+ remainRange+ );++ const result = runRefRangeMutations(operators, remainRange);++ if (result == null) {+ return ErrorType.REF;+ }++ newRange = getMoveNewRange(moveEdge, result, from, to, sequenceRange, remainRange);+ } else if (type === FormulaReferenceMoveType.MoveCols) {+ if (from == null || to == null) {+ return;+ }++ const moveEdge = checkMoveEdge(sequenceRange, from);++ let remainRange = getIntersectRange(sequenceRange, from);++ if (+ remainRange == null &&+ ((from.endColumn < sequenceRange.startColumn && to.endColumn < sequenceRange.startColumn) || (from.startColumn > sequenceRange.endColumn && to.startColumn > sequenceRange.endColumn))+ ) {+ return;+ }++ if (remainRange == null) {+ remainRange = {+ startRow: sequenceRange.startRow,+ endRow: sequenceRange.endRow,+ startColumn: sequenceRange.startColumn,+ endColumn: sequenceRange.endColumn,+ rangeType: RANGE_TYPE.NORMAL,+ };+ }++ const operators = handleMoveCols(+ { id: EffectRefRangId.MoveColsCommandId, params: { toRange: to, fromRange: from } },+ remainRange+ );++ const result = runRefRangeMutations(operators, remainRange);++ if (result == null) {+ return ErrorType.REF;+ }++ newRange = getMoveNewRange(moveEdge, result, from, to, sequenceRange, remainRange);+ }++ if (range != null) {+ if (type === FormulaReferenceMoveType.InsertRow) {+ const operators = handleInsertRow(+ {+ id: EffectRefRangId.InsertRowCommandId,+ params: { range, unitId: '', subUnitId: '', direction: Direction.DOWN },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ } else if (type === FormulaReferenceMoveType.InsertColumn) {+ const operators = handleInsertCol(+ {+ id: EffectRefRangId.InsertColCommandId,+ params: { range, unitId: '', subUnitId: '', direction: Direction.RIGHT },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ } else if (type === FormulaReferenceMoveType.RemoveRow) {+ const operators = handleIRemoveRow(+ {+ id: EffectRefRangId.RemoveRowCommandId,+ params: { range },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return ErrorType.REF;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ } else if (type === FormulaReferenceMoveType.RemoveColumn) {+ const operators = handleIRemoveCol(+ {+ id: EffectRefRangId.RemoveColCommandId,+ params: { range },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return ErrorType.REF;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ } else if (type === FormulaReferenceMoveType.DeleteMoveLeft) {+ const operators = handleDeleteRangeMoveLeft(+ {+ id: EffectRefRangId.DeleteRangeMoveLeftCommandId,+ params: { range },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return ErrorType.REF;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ } else if (type === FormulaReferenceMoveType.DeleteMoveUp) {+ const operators = handleDeleteRangeMoveUp(+ {+ id: EffectRefRangId.DeleteRangeMoveUpCommandId,+ params: { range },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return ErrorType.REF;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ } else if (type === FormulaReferenceMoveType.InsertMoveDown) {+ const operators = handleInsertRangeMoveDown(+ {+ id: EffectRefRangId.InsertRangeMoveDownCommandId,+ params: { range },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ } else if (type === FormulaReferenceMoveType.InsertMoveRight) {+ const operators = handleInsertRangeMoveRight(+ {+ id: EffectRefRangId.InsertRangeMoveRightCommandId,+ params: { range },+ },+ sequenceRange+ );++ const result = runRefRangeMutations(operators, sequenceRange);++ if (result == null) {+ return;+ }++ newRange = {+ ...sequenceRange,+ ...result,+ };+ }+ }++ if (newRange == null) {+ return;+ }++ return serializeRangeToRefString({+ range: newRange,+ sheetName: sequenceRangeSheetName,+ unitId: sequenceRangeUnitId,+ });+}++/**+ * Calculate the new ref information for the moving selection.+ * @param moveEdge the 'from' range lie on the edge of the original range, or does it completely cover the original range+ * @param result The original range is divided by 'from' and moved to a new position range.+ * @param from The initial range of the moving selection.+ * @param to The result range after moving the initial range.+ * @param origin The original target range.+ * @param remain "The range subtracted from the initial range by 'from'.+ * @returns+ */+// eslint-disable-next-line+function getMoveNewRange(+ moveEdge: Nullable<OriginRangeEdgeType>,+ result: IRange,+ from: IRange,+ to: IRange,+ origin: IRange,+ remain: IRange+) {+ const { startRow, endRow, startColumn, endColumn, rangeType } = getStartEndValue(result);++ const {+ startRow: fromStartRow,+ startColumn: fromStartColumn,+ endRow: fromEndRow,+ endColumn: fromEndColumn,+ rangeType: fromRangeType = RANGE_TYPE.NORMAL,+ } = getStartEndValue(from);++ const { startRow: toStartRow, startColumn: toStartColumn, endRow: toEndRow, endColumn: toEndColumn } = getStartEndValue(to);++ const {+ startRow: remainStartRow,+ endRow: remainEndRow,+ startColumn: remainStartColumn,+ endColumn: remainEndColumn,+ } = getStartEndValue(remain);++ const {+ startRow: originStartRow,+ endRow: originEndRow,+ startColumn: originStartColumn,+ endColumn: originEndColumn,+ rangeType: originRangeType = RANGE_TYPE.NORMAL,+ } = getStartEndValue(origin);++ const newRange = { ...origin };++ function rowsCover(): boolean {+ if (rangeType === RANGE_TYPE.COLUMN && originRangeType === RANGE_TYPE.COLUMN) {+ return true;+ }+ return startColumn >= originStartColumn && endColumn <= originEndColumn;+ }++ function columnsCover(): boolean {+ if (rangeType === RANGE_TYPE.ROW && originRangeType === RANGE_TYPE.ROW) {+ return true;+ }+ return startRow >= originStartRow && endRow <= originEndRow;+ }++ if (moveEdge === OriginRangeEdgeType.UP) {+ if (rowsCover()) {+ if (startRow < originStartRow) {+ newRange.startRow = startRow;+ } else if (startRow >= originEndRow) {+ newRange.endRow -= fromEndRow + 1 - originStartRow;+ } else {+ return;+ }+ } else {+ return;+ }+ } else if (moveEdge === OriginRangeEdgeType.DOWN) {+ if (rowsCover()) {+ if (endRow > originEndRow) {+ newRange.endRow = endRow;+ } else if (endRow <= originStartRow) {+ newRange.startRow += originEndRow - fromStartRow + 1;+ } else {+ return;+ }+ } else {+ return;+ }+ } else if (moveEdge === OriginRangeEdgeType.LEFT) {+ if (columnsCover()) {+ if (startColumn < originStartColumn) {+ newRange.startColumn = startColumn;+ } else if (startColumn >= originEndColumn) {+ newRange.endColumn -= fromEndColumn + 1 - originStartColumn;+ } else {+ return;+ }+ } else {+ return;+ }+ } else if (moveEdge === OriginRangeEdgeType.RIGHT) {+ if (columnsCover()) {+ if (endColumn > originEndColumn) {+ newRange.endColumn = endColumn;+ } else if (endColumn <= originStartColumn) {+ newRange.startColumn += originEndColumn - fromStartColumn + 1;+ } else {+ return;+ }+ } else {+ return;+ }+ } else if (moveEdge === OriginRangeEdgeType.ALL) {+ newRange.startRow = startRow;+ newRange.startColumn = startColumn;+ newRange.endRow = endRow;+ newRange.endColumn = endColumn;+ } else if ((fromStartColumn <= originStartColumn && fromEndColumn >= originEndColumn) || (fromRangeType === RANGE_TYPE.ROW && originRangeType === RANGE_TYPE.ROW)) { // For the entire row, originStartColumn and originEndColumn may be NaN+ if (from.endRow < originStartRow) {+ if (toStartRow >= originStartRow) {+ newRange.startRow -= fromEndRow - fromStartRow + 1;+ }+ if (toStartRow >= originEndRow) {+ newRange.endRow -= fromEndRow - fromStartRow + 1;+ }+ } else if (from.startRow > originEndRow) {+ if (toEndRow <= originEndRow) {+ newRange.endRow += fromEndRow - fromStartRow + 1;+ }+ if (toEndRow <= originStartRow) {+ newRange.startRow += fromEndRow - fromStartRow + 1;+ }+ } else if (from.startRow >= originStartRow && from.endRow <= originEndRow) { // from range is in the middle of the original range+ if (toStartRow <= originStartRow) {+ newRange.startRow += fromEndRow - fromStartRow + 1;+ } else if (toStartRow >= originEndRow) {+ newRange.endRow -= fromEndRow - fromStartRow + 1;+ }+ }+ } else if ((fromStartRow <= originStartRow && fromEndRow >= originEndRow) || (fromRangeType === RANGE_TYPE.COLUMN && originRangeType === RANGE_TYPE.COLUMN)) { // For the entire column, originStartRow and originEndRow may be NaN+ if (from.endColumn < originStartColumn) {+ if (toStartColumn >= originStartColumn) {+ newRange.startColumn -= fromEndColumn - fromStartColumn + 1;+ }+ if (toStartColumn >= originEndColumn) {+ newRange.endColumn -= fromEndColumn - fromStartColumn + 1;+ }+ } else if (from.startColumn > originEndColumn) {+ if (toEndColumn <= originEndColumn) {+ newRange.endColumn += fromEndColumn - fromStartColumn + 1;+ }+ if (toEndColumn <= originStartColumn) {+ newRange.startColumn += fromEndColumn - fromStartColumn + 1;+ }+ } else if (from.startColumn >= originStartColumn && from.endColumn <= originEndColumn) { // from range is in the middle of the original range+ if (toStartColumn <= originStartColumn) {+ newRange.startColumn += fromEndColumn - fromStartColumn + 1;+ } else if (toStartColumn >= originEndColumn) {+ newRange.endColumn -= fromEndColumn - fromStartColumn + 1;+ }+ }+ } else if (+ ((toStartColumn <= remainEndColumn + 1 && toEndColumn >= originEndColumn) ||+ (toStartColumn <= originStartColumn && toEndColumn >= remainStartColumn - 1)) &&+ toStartRow <= originStartRow &&+ toEndRow >= originEndRow+ ) {+ newRange.startRow = startRow;+ newRange.startColumn = startColumn;+ newRange.endRow = endRow;+ newRange.endColumn = endColumn;+ } else if (+ ((toStartRow <= remainEndRow + 1 && toEndRow >= originEndRow) ||+ (toStartRow <= originStartRow && toEndRow >= remainStartRow - 1)) &&+ toStartColumn <= originStartColumn &&+ toEndColumn >= originEndColumn+ ) {+ newRange.startRow = startRow;+ newRange.startColumn = startColumn;+ newRange.endRow = endRow;+ newRange.endColumn = endColumn;+ } else {+ // By default, the offset of result is taken+ newRange.startRow = startRow;+ newRange.startColumn = startColumn;+ newRange.endRow = endRow;+ newRange.endColumn = endColumn;+ }++ return newRange;+}++/**+ * Determine the range of the moving selection,+ * and check if it is at the edge of the reference range of the formula.+ * @param originRange+ * @param fromRange+ */+export function checkMoveEdge(originRange: IRange, fromRange: IRange): Nullable<OriginRangeEdgeType> {+ const startRow = getStartValue(originRange.startRow);+ const endRow = getEndValue(originRange.endRow);+ const startColumn = getStartValue(originRange.startColumn);+ const endColumn = getEndValue(originRange.endColumn);++ const fromStartRow = getStartValue(fromRange.startRow);+ const fromEndRow = getEndValue(fromRange.endRow);+ const fromStartColumn = getStartValue(fromRange.startColumn);+ const fromEndColumn = getEndValue(fromRange.endColumn);++ function rowsCover(): boolean {+ if (originRange.rangeType === RANGE_TYPE.COLUMN && fromRange.rangeType === RANGE_TYPE.COLUMN) {+ return true;+ }+ return startRow >= fromStartRow && endRow <= fromEndRow;+ }++ function columnsCover(): boolean {+ if (originRange.rangeType === RANGE_TYPE.ROW && fromRange.rangeType === RANGE_TYPE.ROW) {+ return true;+ }+ return startColumn >= fromStartColumn && endColumn <= fromEndColumn;+ }++ function allCover(): boolean {+ return originRange.rangeType === RANGE_TYPE.ALL && fromRange.rangeType === RANGE_TYPE.ALL;+ }++ if ((rowsCover() && columnsCover()) || allCover()) {+ return OriginRangeEdgeType.ALL;+ }++ if (+ columnsCover() &&+ startRow >= fromStartRow &&+ startRow <= fromEndRow &&+ endRow > fromEndRow+ ) {+ return OriginRangeEdgeType.UP;+ }++ if (+ columnsCover() &&+ endRow >= fromStartRow &&+ endRow <= fromEndRow &&+ startRow < fromStartRow+ ) {+ return OriginRangeEdgeType.DOWN;+ }++ if (+ rowsCover() &&+ startColumn >= fromStartColumn &&+ startColumn <= fromEndColumn &&+ endColumn > fromEndColumn+ ) {+ return OriginRangeEdgeType.LEFT;+ }++ if (+ rowsCover() &&+ endColumn >= fromStartColumn &&+ endColumn <= fromEndColumn &&+ startColumn < fromStartColumn+ ) {+ return OriginRangeEdgeType.RIGHT;+ }++ return null; // Return null if no edge type matches+}++// Helper functions to get start values, treating NaN as unbounded+function getStartValue(value: number): number {+ // If value is NaN, treat as -Infinity (unbounded start)+ return isNaN(value) ? -Infinity : value;+}++// Helper functions to get end values, treating NaN as unbounded+function getEndValue(value: number): number {+ // If value is NaN, treat as Infinity (unbounded end)+ return isNaN(value) ? Infinity : value;+}++function getStartEndValue(range: IRange) {+ const { startRow, endRow, startColumn, endColumn } = range;+ return {+ ...range,+ startRow: getStartValue(startRow),+ endRow: getEndValue(endRow),+ startColumn: getStartValue(startColumn),+ endColumn: getEndValue(endColumn),+ };+}diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-param.ts b/packages/sheets-formula/src/controllers/utils/ref-range-param.tsnew file mode 100644index 0000000000..826ffa94a5--- /dev/null+++ b/packages/sheets-formula/src/controllers/utils/ref-range-param.ts@@ -0,0 +1,401 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type {+ ICommandInfo,+ Nullable,+ Workbook,+} from '@univerjs/core';++import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';++import type {+ IDeleteRangeMoveLeftCommandParams,+ IDeleteRangeMoveUpCommandParams,+ IInsertColCommandParams,+ IInsertRowCommandParams,+ IMoveColsCommandParams,+ IMoveRangeCommandParams,+ IMoveRowsCommandParams,+ InsertRangeMoveDownCommandParams,+ InsertRangeMoveRightCommandParams,+ IRemoveRowColCommandParams,+ IRemoveSheetCommandParams,+ ISetWorksheetNameCommandParams,+} from '@univerjs/sheets';+import {+ RANGE_TYPE,+} from '@univerjs/core';+import {+ DeleteRangeMoveLeftCommand,+ DeleteRangeMoveUpCommand,+ InsertColCommand,+ InsertRangeMoveDownCommand,+ InsertRangeMoveRightCommand,+ InsertRowCommand,+ MoveColsCommand,+ MoveRangeCommand,+ MoveRowsCommand,+ RemoveColCommand,+ RemoveDefinedNameCommand,+ RemoveRowCommand,+ RemoveSheetCommand,+ SetDefinedNameCommand,+ SetWorksheetNameCommand,+} from '@univerjs/sheets';+import { FormulaReferenceMoveType, type IFormulaReferenceMoveParam } from './ref-range-formula';++export function getReferenceMoveParams(workbook: Workbook, command: ICommandInfo) {+ const { id } = command;+ let result: Nullable<IFormulaReferenceMoveParam> = null;++ switch (id) {+ case MoveRangeCommand.id:+ result = handleRefMoveRange(command as ICommandInfo<IMoveRangeCommandParams>, workbook);+ break;+ case MoveRowsCommand.id:+ result = handleRefMoveRows(command as ICommandInfo<IMoveRowsCommandParams>, workbook);+ break;+ case MoveColsCommand.id:+ result = handleRefMoveCols(command as ICommandInfo<IMoveColsCommandParams>, workbook);+ break;+ case InsertRowCommand.id:+ result = handleRefInsertRow(command as ICommandInfo<IInsertRowCommandParams>);+ break;+ case InsertColCommand.id:+ result = handleRefInsertCol(command as ICommandInfo<IInsertColCommandParams>);+ break;+ case InsertRangeMoveRightCommand.id:+ result = handleRefInsertRangeMoveRight(command as ICommandInfo<InsertRangeMoveRightCommandParams>, workbook);+ break;+ case InsertRangeMoveDownCommand.id:+ result = handleRefInsertRangeMoveDown(command as ICommandInfo<InsertRangeMoveDownCommandParams>, workbook);+ break;+ case RemoveRowCommand.id:+ result = handleRefRemoveRow(command as ICommandInfo<IRemoveRowColCommandParams>, workbook);+ break;+ case RemoveColCommand.id:+ result = handleRefRemoveCol(command as ICommandInfo<IRemoveRowColCommandParams>, workbook);+ break;+ case DeleteRangeMoveUpCommand.id:+ result = handleRefDeleteRangeMoveUp(command as ICommandInfo<IDeleteRangeMoveUpCommandParams>, workbook);+ break;+ case DeleteRangeMoveLeftCommand.id:+ result = handleRefDeleteRangeMoveLeft(command as ICommandInfo<IDeleteRangeMoveLeftCommandParams>, workbook);+ break;+ case SetWorksheetNameCommand.id:+ result = handleRefSetWorksheetName(command as ICommandInfo<ISetWorksheetNameCommandParams>, workbook);+ break;+ case RemoveSheetCommand.id:+ result = handleRefRemoveWorksheet(command as ICommandInfo<IRemoveSheetCommandParams>, workbook);+ break;+ case SetDefinedNameCommand.id:+ result = handleRefSetDefinedName(command as ICommandInfo<ISetDefinedNameMutationParam>, workbook);+ break;+ case RemoveDefinedNameCommand.id:+ result = handleRefRemoveDefinedName(command as ICommandInfo<ISetDefinedNameMutationParam>, workbook);+ break;+ }++ return result;+}++function getCurrentSheetInfo(workbook: Workbook) {+ const unitId = workbook.getUnitId();+ const sheetId = workbook.getActiveSheet()?.getSheetId() || '';++ return {+ unitId,+ sheetId,+ };+}++function handleRefMoveRange(command: ICommandInfo<IMoveRangeCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { fromRange, toRange } = params;+ if (!fromRange || !toRange) return null;++ const { unitId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.MoveRange,+ from: fromRange,+ to: toRange,+ unitId,+ sheetId,+ };+}++function handleRefMoveRows(command: ICommandInfo<IMoveRowsCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const {+ fromRange: { startRow: fromStartRow, endRow: fromEndRow },+ toRange: { startRow: toStartRow, endRow: toEndRow },+ } = params;++ const unitId = workbook.getUnitId();+ const worksheet = workbook.getActiveSheet();+ if (!worksheet) return null;++ const sheetId = worksheet.getSheetId();++ const from = {+ startRow: fromStartRow,+ startColumn: 0,+ endRow: fromEndRow,+ endColumn: worksheet.getColumnCount() - 1,+ rangeType: RANGE_TYPE.ROW,+ };+ const to = {+ startRow: toStartRow,+ startColumn: 0,+ endRow: toEndRow,+ endColumn: worksheet.getColumnCount() - 1,+ rangeType: RANGE_TYPE.ROW,+ };++ return {+ type: FormulaReferenceMoveType.MoveRows,+ from,+ to,+ unitId,+ sheetId,+ };+}++function handleRefMoveCols(command: ICommandInfo<IMoveColsCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const {+ fromRange: { startColumn: fromStartCol, endColumn: fromEndCol },+ toRange: { startColumn: toStartCol, endColumn: toEndCol },+ } = params;++ const unitId = workbook.getUnitId();+ const worksheet = workbook.getActiveSheet();+ if (!worksheet) return null;++ const sheetId = worksheet.getSheetId();++ const from = {+ startRow: 0,+ startColumn: fromStartCol,+ endRow: worksheet.getRowCount() - 1,+ endColumn: fromEndCol,+ rangeType: RANGE_TYPE.COLUMN,+ };+ const to = {+ startRow: 0,+ startColumn: toStartCol,+ endRow: worksheet.getRowCount() - 1,+ endColumn: toEndCol,+ rangeType: RANGE_TYPE.COLUMN,+ };++ return {+ type: FormulaReferenceMoveType.MoveCols,+ from,+ to,+ unitId,+ sheetId,+ };+}++function handleRefInsertRow(command: ICommandInfo<IInsertRowCommandParams>) {+ const { params } = command;+ if (!params) return null;++ const { range, unitId, subUnitId } = params;+ return {+ type: FormulaReferenceMoveType.InsertRow,+ range,+ unitId,+ sheetId: subUnitId,+ };+}++function handleRefInsertCol(command: ICommandInfo<IInsertColCommandParams>) {+ const { params } = command;+ if (!params) return null;++ const { range, unitId, subUnitId } = params;+ return {+ type: FormulaReferenceMoveType.InsertColumn,+ range,+ unitId,+ sheetId: subUnitId,+ };+}++function handleRefInsertRangeMoveRight(command: ICommandInfo<InsertRangeMoveRightCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { range } = params;+ const { unitId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.InsertMoveRight,+ range,+ unitId,+ sheetId,+ };+}++function handleRefInsertRangeMoveDown(command: ICommandInfo<InsertRangeMoveDownCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { range } = params;+ const { unitId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.InsertMoveDown,+ range,+ unitId,+ sheetId,+ };+}++function handleRefRemoveRow(command: ICommandInfo<IRemoveRowColCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { range } = params;+ const { unitId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.RemoveRow,+ range,+ unitId,+ sheetId,+ };+}++function handleRefRemoveCol(command: ICommandInfo<IRemoveRowColCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { range } = params;+ const { unitId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.RemoveColumn,+ range,+ unitId,+ sheetId,+ };+}++function handleRefDeleteRangeMoveUp(command: ICommandInfo<IDeleteRangeMoveUpCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { range } = params;+ const { unitId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.DeleteMoveUp,+ range,+ unitId,+ sheetId,+ };+}++function handleRefDeleteRangeMoveLeft(command: ICommandInfo<IDeleteRangeMoveLeftCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { range } = params;+ const { unitId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.DeleteMoveLeft,+ range,+ unitId,+ sheetId,+ };+}++function handleRefSetWorksheetName(command: ICommandInfo<ISetWorksheetNameCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { unitId, subUnitId, name } = params;++ const { unitId: workbookId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.SetName,+ unitId: unitId || workbookId,+ sheetId: subUnitId || sheetId,+ sheetName: name,+ };+}++function handleRefRemoveWorksheet(command: ICommandInfo<IRemoveSheetCommandParams>, workbook: Workbook) {+ const { params } = command;+ if (!params) return null;++ const { unitId, subUnitId } = params;++ const { unitId: workbookId, sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.RemoveSheet,+ unitId: unitId || workbookId,+ sheetId: subUnitId || sheetId,+ };+}++function handleRefSetDefinedName(command: ICommandInfo<ISetDefinedNameMutationParam>, workbook: Workbook): Nullable<IFormulaReferenceMoveParam> {+ const { params } = command;+ if (!params) return null;++ const { unitId, name, id } = params;++ const { sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.SetDefinedName,+ unitId,+ sheetId,+ definedName: name,+ definedNameId: id,+ };+}++function handleRefRemoveDefinedName(command: ICommandInfo<ISetDefinedNameMutationParam>, workbook: Workbook): Nullable<IFormulaReferenceMoveParam> {+ const { params } = command;+ if (!params) return null;++ const { unitId, name, id } = params;++ const { sheetId } = getCurrentSheetInfo(workbook);++ return {+ type: FormulaReferenceMoveType.RemoveDefinedName,+ unitId,+ sheetId,+ definedName: name,+ definedNameId: id,+ };+}diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.tsindex 34496ed79d..4e1b72da87 100644--- a/packages/sheets-formula/src/index.ts+++ b/packages/sheets-formula/src/index.ts@@ -16,7 +16,7 @@export { type IInsertFunction, type IInsertFunctionCommandParams, InsertFunctionCommand } from './commands/commands/insert-function.command';export { OtherFormulaMarkDirty } from './commands/mutations/formula.mutation';-+export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';// #region - all commandsexport { UpdateFormulaController } from './controllers/update-formula.controller';diff --git a/packages/sheets-formula/src/sheets-formula.plugin.ts b/packages/sheets-formula/src/sheets-formula.plugin.tsindex b87d5e0108..a45e8bf9b5 100644--- a/packages/sheets-formula/src/sheets-formula.plugin.ts+++ b/packages/sheets-formula/src/sheets-formula.plugin.ts@@ -23,6 +23,7 @@ import { DependentOn, IConfigService, Inject, Injector, Plugin, UniverInstanceTyimport { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { fromModule, IRPCChannelService, toModule } from '@univerjs/rpc';+import { UniverSheetsPlugin } from '@univerjs/sheets';import { SHEETS_FORMULA_PLUGIN_NAME } from './common/plugin-name';import { ActiveDirtyController } from './controllers/active-dirty.controller';@@ -36,6 +37,7 @@ import {import { DefinedNameController } from './controllers/defined-name.controller';import { FormulaController } from './controllers/formula.controller';import { TriggerCalculationController } from './controllers/trigger-calculation.controller';+import { UpdateDefinedNameController } from './controllers/update-defined-name.controller';import { UpdateFormulaController } from './controllers/update-formula.controller';import { DescriptionService, IDescriptionService } from './services/description.service';import { FormulaRefRangeService } from './services/formula-ref-range.service';@@ -99,6 +101,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {[UpdateFormulaController],[ActiveDirtyController],[DefinedNameController],+ [UpdateDefinedNameController],];// If the plugin do not execute formula, it should delegate a remote proxy.@@ -119,6 +122,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {this._injector.get(ActiveDirtyController);this._injector.get(ArrayFormulaCellInterceptorController);this._injector.get(UpdateFormulaController);+ this._injector.get(UpdateDefinedNameController);}override onRendered(): void {diff --git a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts b/packages/sheets-hyper-link-ui/src/services/resolver.service.tsindex c9fd333d2f..4fd039698f 100644--- a/packages/sheets-hyper-link-ui/src/services/resolver.service.ts+++ b/packages/sheets-hyper-link-ui/src/services/resolver.service.ts@@ -14,6 +14,11 @@* limitations under the License.*/+import type { IRange, Workbook, Worksheet } from '@univerjs/core';+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';+import type { IUniverSheetsHyperLinkUIConfig } from '../controllers/config.schema';+import type { ISheetHyperLinkInfo } from '../types/interfaces/i-sheet-hyper-link-info';+import type { ISheetUrlParams } from '../types/interfaces/i-sheet-url-params';import { ICommandService, IConfigService, Inject, isValidRange, IUniverInstanceService, LocaleService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';import { MessageType } from '@univerjs/design';import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';@@ -21,12 +26,7 @@ import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/simport { ERROR_RANGE, SheetHyperLinkType } from '@univerjs/sheets-hyper-link';import { ScrollToRangeOperation } from '@univerjs/sheets-ui';import { IMessageService } from '@univerjs/ui';-import type { IRange, Workbook, Worksheet } from '@univerjs/core';-import type { ISetSelectionsOperationParams } from '@univerjs/sheets';import { PLUGIN_CONFIG_KEY } from '../controllers/config.schema';-import type { IUniverSheetsHyperLinkUIConfig } from '../controllers/config.schema';-import type { ISheetHyperLinkInfo } from '../types/interfaces/i-sheet-hyper-link-info';-import type { ISheetUrlParams } from '../types/interfaces/i-sheet-url-params';function getContainRange(range: IRange, worksheet: Worksheet) {const mergedCells = worksheet.getMergeData();@@ -126,6 +126,33 @@ export class SheetsHyperLinkResolverService {}const unitId = workbook.getUnitId();if (rangeid) {+ const item = this._definedNamesService.getValueById(unitId, rangeid);+ if (!item) {+ return;+ }++ const { formulaOrRefString } = item;+ const worksheet = this._definedNamesService.getWorksheetByRef(unitId, formulaOrRefString);++ if (!worksheet) {+ this._messageService.show({+ content: this._localeService.t('hyperLink.message.refError'),+ type: MessageType.Error,+ });+ return;+ }++ const isHidden = worksheet.isSheetHidden();++ // The worksheet may be hidden+ if (isHidden) {+ this._messageService.show({+ content: this._localeService.t('hyperLink.message.hiddenSheet'),+ type: MessageType.Error,+ });+ return;+ }+this.navigateToDefineName(unitId, rangeid);}diff --git a/packages/sheets-ui/src/controllers/utils/char-tools.ts b/packages/sheets-ui/src/controllers/utils/char-tools.tsindex 655c08f3b6..4e02b7fdee 100644--- a/packages/sheets-ui/src/controllers/utils/char-tools.ts+++ b/packages/sheets-ui/src/controllers/utils/char-tools.ts@@ -15,8 +15,8 @@*/import { LocaleType, numfmt } from '@univerjs/core';-import type { IFunctionService, ISequenceNode, LexerTreeBuilder } from '@univerjs/engine-formula';import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';+import type { IFunctionService, ISequenceNode, LexerTreeBuilder } from '@univerjs/engine-formula';const fullWidthToHalfWidthMap: { [key: string]: string } = {'0': '0', '1': '1', '2': '2', '3': '3', '4': '4',diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsxindex 9e73e1f15b..0892de9b05 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx@@ -14,19 +14,19 @@* limitations under the License.*/-import React, { useEffect, useState } from 'react';--import type { Nullable, Workbook } from '@univerjs/core';import { ICommandService, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';-import { CheckMarkSingle, DeleteSingle, IncreaseSingle } from '@univerjs/icons';-import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';++import { Confirm, Tooltip } from '@univerjs/design';import { IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';+import { CheckMarkSingle, DeleteSingle, IncreaseSingle } from '@univerjs/icons';+import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SetDefinedNameCommand, SetWorksheetShowCommand, SheetsSelectionsService } from '@univerjs/sheets';import clsx from 'clsx';-import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SetDefinedNameCommand, SheetsSelectionsService } from '@univerjs/sheets';-import { Confirm, Tooltip } from '@univerjs/design';-import styles from './index.module.less';-import { DefinedNameInput } from './DefinedNameInput';+import React, { useEffect, useState } from 'react';+import type { Nullable, Workbook } from '@univerjs/core';+import type { IDefinedNamesServiceParam, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';import { SCOPE_WORKBOOK_VALUE } from './component-name';+import { DefinedNameInput } from './DefinedNameInput';+import styles from './index.module.less';export const DefinedNameContainer = () => {const commandService = useDependency(ICommandService);@@ -73,9 +73,8 @@ export const DefinedNameContainer = () => {id = Tools.generateRandomId(10);commandService.executeCommand(InsertDefinedNameCommand.id, { id, unitId, name, formulaOrRefString, comment, localSheetId, hidden });} else {- const oldDefinedName = definedNamesService.getValueById(unitId, id);- const newDefinedName = { id, unitId, name, formulaOrRefString, comment, localSheetId, hidden };- commandService.executeCommand(SetDefinedNameCommand.id, { unitId, oldDefinedName: { ...oldDefinedName, unitId }, newDefinedName });+ const newDefinedName: ISetDefinedNameMutationParam = { id, unitId, name, formulaOrRefString, comment, localSheetId, hidden };+ commandService.executeCommand(SetDefinedNameCommand.id, newDefinedName);}setEditState(false);setEditorKey(null);@@ -95,8 +94,20 @@ export const DefinedNameContainer = () => {setDeleteConformKey(null);}- const focusDefinedName = (definedName: IDefinedNamesServiceParam) => {- definedNamesService.focusRange(unitId, definedName.id);+ const focusDefinedName = async (definedName: IDefinedNamesServiceParam) => {+ // The worksheet may be hidden, so we need to show it first+ const { formulaOrRefString, id } = definedName;+ const worksheet = definedNamesService.getWorksheetByRef(unitId, formulaOrRefString);+ if (!worksheet) {+ return;+ }++ const isHidden = worksheet.isSheetHidden();+ if (isHidden) {+ await commandService.executeCommand(SetWorksheetShowCommand.id, { unitId, subUnitId: worksheet.getSheetId() });+ }++ definedNamesService.focusRange(unitId, id);};const getInsertDefinedName = () => {diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsxindex 85feb6513f..9ee2c4a6fb 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameOverlay.tsx@@ -14,12 +14,13 @@* limitations under the License.*/-import React, { useEffect, useState } from 'react';+import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';+import { IDefinedNamesService } from '@univerjs/engine-formula';+import { SetWorksheetShowCommand } from '@univerjs/sheets';+import React, { useEffect, useState } from 'react';import type { Workbook } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';-import { IDefinedNamesService } from '@univerjs/engine-formula';import { SidebarDefinedNameOperation } from '../../commands/operations/sidebar-defined-name.operation';import styles from './index.module.less';@@ -59,8 +60,20 @@ export function DefinedNameOverlay(props: IDefinedNameOverlayProps) {commandService.executeCommand(SidebarDefinedNameOperation.id, { value: 'open' });};- const focusDefinedName = (definedName: IDefinedNamesServiceParam) => {- definedNamesService.focusRange(unitId, definedName.id);+ const focusDefinedName = async (definedName: IDefinedNamesServiceParam) => {+ // The worksheet may be hidden, so we need to show it first+ const { formulaOrRefString, id } = definedName;+ const worksheet = definedNamesService.getWorksheetByRef(unitId, formulaOrRefString);+ if (!worksheet) {+ return;+ }++ const isHidden = worksheet.isSheetHidden();+ if (isHidden) {+ await commandService.executeCommand(SetWorksheetShowCommand.id, { unitId, subUnitId: worksheet.getSheetId() });+ }++ definedNamesService.focusRange(unitId, id);};return (diff --git a/packages/sheets/src/commands/commands/remove-defined-name.command.ts b/packages/sheets/src/commands/commands/remove-defined-name.command.tsindex 1ebabfcbba..c426d24c42 100644--- a/packages/sheets/src/commands/commands/remove-defined-name.command.ts+++ b/packages/sheets/src/commands/commands/remove-defined-name.command.ts@@ -19,8 +19,10 @@ import {CommandType,ICommandService,IUndoRedoService,+ sequenceExecute,} from '@univerjs/core';import { type ISetDefinedNameMutationParam, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';+import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';/*** The command to remove new defined name@@ -31,22 +33,35 @@ export const RemoveDefinedNameCommand: ICommand = {handler: (accessor: IAccessor, params?: ISetDefinedNameMutationParam) => {const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);+ const sheetInterceptorService = accessor.get(SheetInterceptorService);if (!params) return false;- // prepare do mutationsconst removeSheetMutationParams: ISetDefinedNameMutationParam = {...params,};- // execute do mutations and add undo mutations to undo stack if completed- const result = commandService.syncExecuteCommand(RemoveDefinedNameMutation.id, removeSheetMutationParams);+ const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: RemoveDefinedNameCommand.id, params });++ const redos = [+ ...(interceptorCommands.preRedos ?? []),+ { id: RemoveDefinedNameMutation.id, params: removeSheetMutationParams },+ ...interceptorCommands.redos,+ ];++ const undos = [+ ...(interceptorCommands.preUndos ?? []),+ { id: SetDefinedNameMutation.id, params: removeSheetMutationParams },+ ...interceptorCommands.undos,+ ];++ const result = sequenceExecute(redos, commandService);if (result) {undoRedoService.pushUndoRedo({unitID: params.unitId,- undoMutations: [{ id: SetDefinedNameMutation.id, params: removeSheetMutationParams }],- redoMutations: [{ id: RemoveDefinedNameMutation.id, params: removeSheetMutationParams }],+ undoMutations: undos.filter(Boolean),+ redoMutations: redos.filter(Boolean),});return true;diff --git a/packages/sheets/src/commands/commands/set-defined-name.command.ts b/packages/sheets/src/commands/commands/set-defined-name.command.tsindex bceab2ec00..223b4204ee 100644--- a/packages/sheets/src/commands/commands/set-defined-name.command.ts+++ b/packages/sheets/src/commands/commands/set-defined-name.command.ts@@ -19,35 +19,56 @@ import {CommandType,ICommandService,IUndoRedoService,+ sequenceExecute,} from '@univerjs/core';-import { type ISetDefinedNameMutationParam, SetDefinedNameMutation } from '@univerjs/engine-formula';--export interface ISetDefinedNameCommandParams {- unitId: string;- oldDefinedName: ISetDefinedNameMutationParam;- newDefinedName: ISetDefinedNameMutationParam;-}+import { type ISetDefinedNameMutationParam, RemoveDefinedNameMutation, SetDefinedNameMutation, SetDefinedNameMutationFactory } from '@univerjs/engine-formula';+import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';/*** The command to update defined name+ *+ * 1. The old defined name can be obtained through IDefinedNamesService, and does not need to be passed in from the outside, making the command input more concise++ 2. Unlike InsertDefinedNameCommand, the old defined name needs to be deleted here at the same time. Because the command interception in UpdateDefinedNameController will add SetDefinedNameMutation or RemoveDefinedNameMutation, it results in that in DefinedNameController, only mutations can be listened to to update Function Description (commands cannot be listened to), so it is necessary to ensure that each mutation triggered by the command has completed all work.*/export const SetDefinedNameCommand: ICommand = {id: 'sheet.command.set-defined-name',type: CommandType.COMMAND,- handler: (accessor: IAccessor, params?: ISetDefinedNameCommandParams) => {+ handler: (accessor: IAccessor, params: ISetDefinedNameMutationParam) => {const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);+ const sheetInterceptorService = accessor.get(SheetInterceptorService);if (!params) return false;- // execute do mutations and add undo mutations to undo stack if completed- const result = commandService.syncExecuteCommand(SetDefinedNameMutation.id, params.newDefinedName);+ const newDefinedNameMutationParams: ISetDefinedNameMutationParam = {+ ...params,+ };+ const oldDefinedNameMutationParams: ISetDefinedNameMutationParam = SetDefinedNameMutationFactory(accessor, params);++ const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: SetDefinedNameCommand.id, params });++ const redos = [+ ...(interceptorCommands.preRedos ?? []),+ { id: RemoveDefinedNameMutation.id, params: oldDefinedNameMutationParams },+ { id: SetDefinedNameMutation.id, params: newDefinedNameMutationParams },+ ...interceptorCommands.redos,+ ];++ const undos = [+ ...(interceptorCommands.preUndos ?? []),+ { id: RemoveDefinedNameMutation.id, params: newDefinedNameMutationParams },+ { id: SetDefinedNameMutation.id, params: oldDefinedNameMutationParams },+ ...interceptorCommands.undos,+ ];++ const result = sequenceExecute(redos, commandService);if (result) {undoRedoService.pushUndoRedo({unitID: params.unitId,- undoMutations: [{ id: SetDefinedNameMutation.id, params: params.oldDefinedName }],- redoMutations: [{ id: SetDefinedNameMutation.id, params: params.newDefinedName }],+ undoMutations: undos.filter(Boolean),+ redoMutations: redos.filter(Boolean),});return true;@@ -56,3 +77,4 @@ export const SetDefinedNameCommand: ICommand = {return false;},};+diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 2710422553..1c82a9fae9 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -235,7 +235,8 @@ export {SetSelectedColsVisibleCommand,SetSpecificColsVisibleCommand,} from './commands/commands/set-col-visible.command';-export { type ISetDefinedNameCommandParams, SetDefinedNameCommand } from './commands/commands/set-defined-name.command';++export { SetDefinedNameCommand } from './commands/commands/set-defined-name.command';export { SetFrozenCancelCommand } from './commands/commands/set-frozen-cancel.command';export { SetFrozenCommand } from './commands/commands/set-frozen.command';export { SetHideGridlinesCommand } from './commands/commands/set-hide-gridlines.command';