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
fix(formula): preserve array origin and invalidate stale spills (#7992)
Univerf8c2e4495bd3
diff --git a/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.tsindex 2792b30944..bc34870ce1 100644--- a/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts+++ b/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts@@ -311,7 +311,7 @@ describe('CalculateController', () => {expect(commandService.executeCommand).toHaveBeenCalledWith(SetArrayFormulaDataMutation.id,expect.anything(),- { onlyLocal: true }+ { onlyLocal: true, fromFormula: true });expect(commandService.executeCommand).toHaveBeenCalledWith(SetImageFormulaDataMutation.id,diff --git a/packages/engine-formula/src/controllers/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.tsindex d97b852587..1715cbad6f 100644--- a/packages/engine-formula/src/controllers/calculate.controller.ts+++ b/packages/engine-formula/src/controllers/calculate.controller.ts@@ -15,6 +15,7 @@*/import type { ICommandInfo } from '@univerjs/core';+import { Disposable, ICommandService, Inject } from '@univerjs/core';import type { ISetArrayFormulaDataMutationParams } from '../commands/mutations/set-array-formula-data.mutation';import type {ISetFormulaCalculationStartMutation,@@ -29,7 +30,6 @@ import type {} from '../engine/dependency/dependency-tree';import type { IFormulaDirtyData } from '../services/current-data.service';import type { IAllRuntimeData } from '../services/runtime.service';-import { Disposable, ICommandService, Inject } from '@univerjs/core';import { convertRuntimeToUnitData } from '../basics/runtime';import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';import {@@ -320,6 +320,7 @@ export class CalculateController extends Disposable {},{onlyLocal: true,+ fromFormula: true,});}diff --git a/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts b/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.tsindex 625a3eefed..2e99d9c694 100644--- a/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts+++ b/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { ICellData } from '@univerjs/core';import { CellValueType, ObjectMatrix } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { CellReferenceObject } from '../cell-reference-object';@@ -170,4 +171,31 @@ describe('CellReferenceObject', () => {expect(valueObject.isNumber()).toBe(true);expect(valueObject.getValue()).toBe(43497);});++ it.each([{ v: 20 }, { v: 0 }, { v: false }, { v: '' }])('invalidates a removed spill after its anchor becomes $v while preserving unrelated caches', (value) => {+ const reference = new CellReferenceObject('A1');+ reference.setDefaultUnitId('unit-1');+ reference.setDefaultSheetId('sheet-1');+ reference.setArrayFormulaRange({ 'unit-1': { 'sheet-1': { 0: {+ 0: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 0 },+ 3: { startRow: 0, endRow: 2, startColumn: 3, endColumn: 3 },+ } } } });+ reference.setArrayFormulaCellData({ 'unit-1': { 'sheet-1': new ObjectMatrix({+ 0: { 0: { v: 1 }, 3: { v: 4 } },+ 1: { 0: { v: 2 }, 3: { v: 5 } },+ 2: { 0: { v: 3 }, 3: { v: 6 } },+ }) } });+ const runtime = new ObjectMatrix<ICellData>({ 0: { 0: value } });+ reference.setRuntimeData({ 'unit-1': { 'sheet-1': runtime } });+ const range = reference.unionBy(new CellReferenceObject('A3'));+ if (!(range instanceof RangeReferenceObject)) {+ throw new TypeError('Expected a range reference');+ }+ expect(range.getCellData(0, 0)).toEqual(value);+ expect(range.getCellData(1, 0)).toBeNull();+ expect(range.getCellData(2, 0)).toBeNull();+ expect(reference.getCellData(1, 3)).toEqual({ v: 5 });+ runtime.setValue(0, 0, { ...value, f: '=SEQUENCE(3)' });+ expect(range.getCellData(1, 0)).toEqual({ v: 2 });+ });});diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.tsindex d0baf9aee2..9aff4efad2 100644--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts@@ -573,7 +573,12 @@ export class BaseReferenceObject extends ObjectClassType {let isInRuntimeArrayFormulaRange = false;activeArrayFormulaRangeMatrix.forValue((_row, _column, range) => {- if (row >= range.startRow && row <= range.endRow && column >= range.startColumn && column <= range.endColumn && activeRuntimeArrayFormulaRangeMatrix.getValue(_row, _column)) {+ if (!(row >= range.startRow && row <= range.endRow && column >= range.startColumn && column <= range.endColumn)) {+ return;+ }+ const runtimeAnchor = activeRuntimeData?.getValue(_row, _column);+ const anchorCalculated = runtimeAnchor && !isFormulaString(runtimeAnchor.f) && !isFormulaId(runtimeAnchor.si);+ if (activeRuntimeArrayFormulaRangeMatrix.getValue(_row, _column) || anchorCalculated) {isInRuntimeArrayFormulaRange = true;return false;}diff --git a/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts b/packages/engine-formula/src/engine/reference-object/cell-reference-object.tsindex 09fb6ecd0f..191d643f39 100644--- a/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts+++ b/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts@@ -15,9 +15,7 @@*/import type { IRange } from '@univerjs/core';-import { ErrorType } from '../../basics/error-type';-import { deserializeRangeWithSheetWithCache } from '../utils/reference-cache';import { ErrorValueObject } from '../value-object/base-value-object';import { BaseReferenceObject } from './base-reference-object';@@ -122,8 +120,12 @@ export class CellReferenceObject extends BaseReferenceObject {rangeReferenceObject.setArrayFormulaCellData(this.getArrayFormulaCellData());+ rangeReferenceObject.setArrayFormulaRange(this.getArrayFormulaRange());+rangeReferenceObject.setRuntimeArrayFormulaCellData(this.getRuntimeArrayFormulaCellData());+ rangeReferenceObject.setRuntimeArrayFormulaRange(this.getRuntimeArrayFormulaRange());+rangeReferenceObject.setRuntimeFeatureCellData(this.getRuntimeFeatureCellData());const forceSheetId = this.getForcedSheetId();diff --git a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.tsindex dadf2f2168..fbb7db3325 100644--- a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts@@ -15,10 +15,10 @@*/import type { ICellData } from '@univerjs/core';-import type { IFormulaDatasetConfig } from '../../basics/common';-import type { IAllRuntimeData } from '../runtime.service';import { IConfigService, Injector, ObjectMatrix } from '@univerjs/core';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { IFormulaDatasetConfig } from '../../basics/common';+import type { IAllRuntimeData } from '../runtime.service';import { ErrorType } from '../../basics/error-type';import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../../config/config';import { Lexer } from '../../engine/analysis/lexer';@@ -60,6 +60,7 @@ function createService() {getDirtyData: vi.fn(() => ({})),getDirtyDefinedNameMap: vi.fn(() => ({})),getExecuteUnitId: vi.fn(() => 'unit'),+ getArrayFormulaRange: vi.fn(() => ({})),};const runtimeService = {setFormulaExecuteStage: vi.fn(),@@ -87,6 +88,7 @@ function createService() {runtimeFeatureCellData: {},dependencyTreeModelData: [],})),+ getUnitData: vi.fn(() => ({})),setTotalArrayFormulasToCalculate: vi.fn(),setTotalFormulasToCalculate: vi.fn(),setCompletedArrayFormulasCount: vi.fn(),@@ -135,6 +137,7 @@ function createService() {getDirtyData = currentConfigService.getDirtyData;getDirtyDefinedNameMap = currentConfigService.getDirtyDefinedNameMap;getExecuteUnitId = currentConfigService.getExecuteUnitId;+ getArrayFormulaRange = currentConfigService.getArrayFormulaRange;}class TestRuntimeService {@@ -151,6 +154,7 @@ function createService() {setRuntimeFeatureRange = runtimeService.setRuntimeFeatureRange;stopExecution = runtimeService.stopExecution;getAllRuntimeData = runtimeService.getAllRuntimeData;+ getUnitData = runtimeService.getUnitData;setTotalArrayFormulasToCalculate = runtimeService.setTotalArrayFormulasToCalculate;setTotalFormulasToCalculate = runtimeService.setTotalFormulasToCalculate;setCompletedArrayFormulasCount = runtimeService.setCompletedArrayFormulasCount;diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.tsindex 6a37fcc879..1258080f47 100644--- a/packages/engine-formula/src/services/calculate-formula.service.ts+++ b/packages/engine-formula/src/services/calculate-formula.service.ts@@ -16,6 +16,21 @@import type { ICellData, IUnitRange, IWorkbookCalculationSettings } from '@univerjs/core';import type { Observable } from 'rxjs';+import {+ AsyncLock,+ CellValueType,+ createIdentifier,+ Disposable,+ IConfigService,+ Inject,+ isFormulaId,+ isFormulaString,+ normalizeWorkbookCalculationSettings,+ ObjectMatrix,+ Rectangle,+ requestImmediateMacroTask,+} from '@univerjs/core';+import { Subject } from 'rxjs';import type {IArrayFormulaRangeType,IFeatureDirtyRangeType,@@ -38,18 +53,6 @@ import type { BaseReferenceObject, FunctionVariantType } from '../engine/referenimport type { ArrayValueObject } from '../engine/value-object/array-value-object';import type { BaseValueObject } from '../engine/value-object/base-value-object';import type { IAllRuntimeData, IExecutionInProgressParams } from './runtime.service';-import {- AsyncLock,- CellValueType,- createIdentifier,- Disposable,- IConfigService,- Inject,- normalizeWorkbookCalculationSettings,- ObjectMatrix,- requestImmediateMacroTask,-} from '@univerjs/core';-import { Subject } from 'rxjs';import { ErrorType } from '../basics/error-type';import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../config/config';@@ -337,6 +340,23 @@ export class CalculateFormulaService extends Disposable implements ICalculateFordirtyRanges.push({ unitId, sheetId, range });});+ const previousRanges = new ObjectMatrix(this._currentConfigService.getArrayFormulaRange()[unitId]?.[sheetId]);+ const runtimeData = this._runtimeService.getUnitData()[unitId]?.[sheetId];+ previousRanges.forValue((row, column, range) => {+ const runtimeAnchor = runtimeData?.getValue(row, column);+ if (!runtimeAnchor || isFormulaString(runtimeAnchor.f) || isFormulaId(runtimeAnchor.si) ||+ (range.startRow === range.endRow && range.startColumn === range.endColumn)) {+ return;+ }++ newCellData.setValue(row, column, true);+ const newRange = cellValue.getValue(row, column);+ // Removed spill cells can have dependents outside the new footprint.+ if (!newRange || !Rectangle.contains(newRange, range)) {+ dirtyRanges.push({ unitId, sheetId, range });+ }+ });+if (excludedCell[unitId] == null) {excludedCell[unitId] = Object.create(null);}diff --git a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.tsindex bcffed23fe..777f882819 100644--- a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts@@ -16,7 +16,8 @@import type { Dependency, ICellData, IWorkbookData, Nullable, Workbook } from '@univerjs/core';import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';-import { CellValueType, ICommandService, IConfigService, IUniverInstanceService, LocaleType, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import { CellValueType, ICommandService, IConfigService, IUniverInstanceService, LocaleType, LogLevel, RedoCommand, UndoCommand, Univer, UniverInstanceType } from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';import {FormulaDataModel,IDefinedNamesService,@@ -25,12 +26,16 @@ import {SetDefinedNameMutation,SetFormulaDataMutation,SetTriggerFormulaCalculationStartMutation,+ UniverFormulaEnginePlugin,} from '@univerjs/engine-formula';-import { InsertSheetMutation, MoveRangeCommand, MoveRangeMutation, RemoveDefinedNameCommand, RemoveSheetCommand, RemoveSheetMutation, SetDefinedNameCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetStyleCommand, SetWorksheetNameCommand, SheetInterceptorService } from '@univerjs/sheets';+import { InsertSheetMutation, MoveRangeCommand, MoveRangeMutation, RemoveDefinedNameCommand, RemoveSheetCommand, RemoveSheetMutation, SetDefinedNameCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetStyleCommand, SetWorksheetNameCommand, SheetInterceptorService, UniverSheetsPlugin } from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../../config/config';import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { UniverSheetsFormulaPlugin } from '../../plugin';import { UpdateFormulaController } from '../update-formula.controller';+import '@univerjs/sheets/facade';+import '../../facade/index';function createWorkbookData(): IWorkbookData {return {@@ -215,6 +220,94 @@ describe('UpdateFormulaController', () => {expect(values).toEqual([[null, { f: '=SUM(A1:B2)' }]]);});+ it('preserves source and other-sheet references when cutting a formula across sheets, undoing and redoing', async () => {+ const workbook = testBed.injector.get(IUniverInstanceService).getUnit<Workbook>('test')!;+ const source = workbook.getSheetBySheetId('sheet1')!;+ const target = workbook.getSheetBySheetId('sheet2')!;+ const original = '=SUM(A1:B2)+SUM(Sheet2!A1:B2)';+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: { 5: { 2: { f: original } } },+ });++ expect(await commandService.executeCommand(MoveRangeCommand.id, {+ fromUnitId: 'test',+ fromSubUnitId: 'sheet1',+ toUnitId: 'test',+ toSubUnitId: 'sheet2',+ fromRange: { startRow: 5, endRow: 5, startColumn: 2, endColumn: 2 },+ toRange: { startRow: 7, endRow: 7, startColumn: 3, endColumn: 3 },+ })).toBe(true);+ const expected = '=SUM(Sheet1!A1:B2)+SUM(Sheet2!A1:B2)';+ expect(target.getCell(7, 3)?.f).toBe(expected);+ expect(source.getCell(5, 2)?.f).toBeFalsy();++ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(source.getCell(5, 2)?.f).toBe(original);+ expect(target.getCell(7, 3)?.f).toBeFalsy();+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(target.getCell(7, 3)?.f).toBe(expected);+ });++ it('unpacks shared followers when moving a reference used only by their anchor, with undo and redo', async () => {+ const sheet = testBed.injector.get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 10: { 0: { v: 10 }, 2: { f: '=A11', si: 'shared-move' } },+ 11: { 0: { v: 20 }, 2: { si: 'shared-move' } },+ },+ });+ expect(await commandService.executeCommand(MoveRangeCommand.id, {+ fromRange: { startRow: 10, endRow: 10, startColumn: 0, endColumn: 0 },+ toRange: { startRow: 10, endRow: 10, startColumn: 1, endColumn: 1 },+ })).toBe(true);+ expect(sheet.getCell(10, 2)?.f).toBe('=B11');+ expect(sheet.getCell(11, 2)?.f).toBe('=A12');++ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(sheet.getCell(10, 2)?.f).toBe('=A11');+ expect(sheet.getCell(11, 2)?.si).toBe('shared-move');+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(sheet.getCell(10, 2)?.f).toBe('=B11');+ expect(sheet.getCell(11, 2)?.f).toBe('=A12');+ });++ it.each([+ {+ id: 'sheet.command.set-table-config',+ params: { unitId: 'test', oldTableName: 'Sales', name: 'Revenue' },+ expected: '=SUM(Revenue[Amount])+SUM(Other[Amount])+SUM(Revenue[Units])+SUM(Revenue[[#Data],[Amount]])',+ },+ {+ id: 'sheet.command.delete-table',+ params: { unitId: 'test', tableName: 'Sales' },+ expected: '=SUM(#REF!)+SUM(Other[Amount])+SUM(#REF!)+SUM(#REF!)',+ },+ {+ id: 'sheet.command.table-remove-column-at',+ params: { unitId: 'test', subUnitId: 'sheet1', tableName: 'Sales', removedColumnNames: ['Amount'] },+ expected: '=SUM(#REF!)+SUM(Other[Amount])+SUM(Sales[Units])+SUM(#REF!)',+ },+ ])('preserves unaffected table references and reversible formula updates for $id', ({ id, params, expected }) => {+ const original = '=SUM(Sales[Amount])+SUM(Other[Amount])+SUM(Sales[Units])+SUM(Sales[[#Data],[Amount]])';+ const sheet = testBed.injector.get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: { 10: { 1: { f: original } } },+ });+ const result = testBed.injector.get(SheetInterceptorService).onCommandExecute({ id, params });+ for (const mutations of [result.redos, result.undos, result.redos]) {+ for (const mutation of mutations) {+ expect(commandService.syncExecuteCommand(mutation.id, mutation.params)).toBe(true);+ }+ expect(sheet.getCell(10, 1)?.f).toBe(mutations === result.undos ? original : expected);+ }+ });+it('should rewrite formulas when referenced sheets change', () => {const sheetInterceptorService = testBed.injector.get(SheetInterceptorService);@@ -938,3 +1031,96 @@ describe('UpdateFormulaController', () => {);});});++describe('UpdateFormulaController spill cache integration', () => {+ it.each([+ { formula: '=SEQUENCE($A$1)', horizontal: false, scale: 1 },+ { formula: '=SEQUENCE(1,$A$1)', horizontal: true, scale: 1 },+ { formula: '=FILTER($M$1:$M$5,$M$1:$M$5<=$A$1)', horizontal: false, scale: 1 },+ { formula: '=SEQUENCE($A$1)*10', horizontal: false, scale: 10 },+ ])('updates removed spill cells and their dependents for $formula', async ({ formula, horizontal, scale }) => {+ const range = horizontal ? 'H1:L1' : 'H1:H5';+ const tail = horizontal ? 'L1' : 'H5';+ const removedRange = horizontal ? 'J1:L1' : 'H3:H5';+ const cellData: NonNullable<IWorkbookData['sheets'][string]['cellData']> = {+ 0: { 0: { v: 5 }, 7: { f: formula }, 13: { f: `=SUM(${range})` } },+ 1: { 13: { f: `=${tail}` } },+ 2: { 13: { f: `=SUM(${removedRange})` } },+ 3: { 13: { f: '=N1*2' } },+ };+ for (let row = 0; row < 5; row++) {+ (cellData[row] ??= {})[12] = { v: row + 1 };+ }+ const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: {} }, logLevel: LogLevel.SILENT });+ univer.registerPlugin(UniverSheetsPlugin);+ univer.registerPlugin(UniverFormulaEnginePlugin);+ univer.registerPlugin(UniverSheetsFormulaPlugin, { initialFormulaComputing: CalculationMode.NO_CALCULATION });+ const api = FUniver.newAPI(univer);+ const book = api.createWorkbook({+ id: 'spill-cache',+ sheetOrder: ['data', 'check'],+ sheets: {+ data: { id: 'data', name: 'Data', rowCount: 20, columnCount: 20, cellData },+ check: { id: 'check', name: 'Check', rowCount: 5, columnCount: 3, cellData: { 0: { 0: { f: `=SUM(Data!${range})` } } } },+ },+ });+ const sheet = book.getSheetByName('Data')!;+ const calculator = api.getFormula();+ univer.__getInjector().get(IUniverInstanceService).focusUnit(book.getId());+ let calculationIndex = 0;+ async function calculate(action: () => unknown): Promise<void> {+ calculationIndex++;+ let subscription: { dispose(): void };+ let timer: ReturnType<typeof setTimeout>;+ const completed = new Promise<void>((resolve, reject) => {+ subscription = calculator.calculationEnd(() => resolve());+ timer = setTimeout(() => reject(new Error(`Spill calculation ${calculationIndex} timed out`)), 5000);+ });+ try {+ action();+ await completed;+ } finally {+ clearTimeout(timer!);+ subscription!.dispose();+ }+ }+ function expectValues(count: number, scalar = false): void {+ const sum = scalar ? 99 : count * (count + 1) / 2 * scale;+ expect(sheet.getRange('N1').getValue()).toBe(sum);+ expect(sheet.getRange('N2').getValue()).toBe(!scalar && count === 5 ? 5 * scale : 0);+ expect(sheet.getRange('N3').getValue()).toBe(scalar ? 0 : Array.from({ length: Math.max(0, count - 2) }, (_, index) => (index + 3) * scale).reduce((a, b) => a + b, 0));+ expect(sheet.getRange('N4').getValue()).toBe(sum * 2);+ expect(book.getSheetByName('Check')!.getRange('A1').getValue()).toBe(sum);+ for (let index = 0; index < 5; index++) {+ const address = horizontal ? `${String.fromCharCode(72 + index)}1` : `H${index + 1}`;+ const expected = scalar ? (index === 0 ? 99 : null) : (index < count ? (index + 1) * scale : null);+ expect(sheet.getRange(address).getValue() ?? null).toBe(expected);+ }+ }+ try {+ await calculate(() => calculator.executeCalculation());+ expectValues(5);+ for (const count of [2, 1, 5, 1, 3]) {+ await calculate(() => sheet.getRange('A1').setValue(count));+ expectValues(count);+ await calculate(() => calculator.executeCalculation());+ expectValues(count);+ }+ await calculate(() => sheet.getRange(tail).setValue(100));+ await calculate(() => sheet.getRange('A1').setValue(5));+ expect(sheet.getRange('H1').getValue()).toBe('#SPILL!');+ expect(sheet.getRange(tail).getValue()).toBe(100);+ await calculate(() => sheet.getRange(tail).clearContent());+ expectValues(5);+ await calculate(() => sheet.getRange('H1').setFormula('=99'));+ expectValues(1, true);+ const commands = univer.__getInjector().get(ICommandService);+ await calculate(() => expect(commands.syncExecuteCommand(UndoCommand.id)).toBe(true));+ expectValues(5);+ await calculate(() => expect(commands.syncExecuteCommand(RedoCommand.id)).toBe(true));+ expectValues(1, true);+ } finally {+ univer.dispose();+ }+ });+});diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex cc5e97076c..be34d4cacc 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -23,15 +23,12 @@ import type {Nullable,Workbook,} from '@univerjs/core';-import type { IDirtyUnitDefinedNameMap, IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IFormulaData, IFormulaDataItem, IFormulaDirtyData, IUnitSheetNameMap } from '@univerjs/engine-formula';+import type { IDirtyUnitDefinedNameMap, IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IFormulaData, IFormulaDataItem, IFormulaDirtyData, ISequenceNode, IUnitSheetNameMap } from '@univerjs/engine-formula';import type {IInsertSheetMutationParams,IRemoveSheetMutationParams,ISetRangeValuesMutationParams,} from '@univerjs/sheets';-import type { IUniverSheetsFormulaBaseConfig } from '../config/config';-import type { IFormulaReferenceMoveParam } from './utils/ref-range-formula';-import type { IUnitRangeWithOffset } from './utils/ref-range-move';import {Disposable,ICommandService,@@ -56,12 +53,29 @@ import {SheetInterceptorService,} from '@univerjs/sheets';import { map } from 'rxjs';+import type { IUniverSheetsFormulaBaseConfig } from '../config/config';+import type { IFormulaReferenceMoveParam } from './utils/ref-range-formula';+import type { IUnitRangeWithOffset } from './utils/ref-range-move';import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../config/config';import { removeFormulaData } from './utils/offset-formula-data';import { checkIsSameUnitAndSheet, formulaDataToCellData, FormulaReferenceMoveType, getFormulaReferenceMoveUndoRedo, updateRefOffset } from './utils/ref-range-formula';import { getNewRangeByMoveParam } from './utils/ref-range-move';import { getReferenceMoveParams } from './utils/ref-range-param';+interface IFormulaReferenceMoveContext {+ unitId: string;+ sheetId: string;+ unitSheetNameMap: IUnitSheetNameMap;+ params: IFormulaReferenceMoveParam;+ modifiedSharedFormulaIds: string[];+}++interface ICrossSheetCutFormula {+ fromRow: number;+ fromColumn: number;+ formulaString: string;+}+/*** Update formula process*@@ -129,6 +143,22 @@ export class UpdateFormulaController extends Disposable {.subscribe((unitId) => this._handleWorkbookDisposed(unitId)));}+ private _getEditedArrayFormulaDirtyRanges(params: ISetRangeValuesMutationParams): IUnitRange[] {+ const { subUnitId: sheetId, unitId, cellValue } = params;+ const previousRanges = this._formulaDataModel.getArrayFormulaRange()[unitId]?.[sheetId];+ const dirtyRanges: IUnitRange[] = [];+ if (previousRanges) {+ new ObjectMatrix(cellValue).forValue((row, column) => {+ const range = previousRanges[row]?.[column];+ if (range && (range.startRow !== range.endRow || range.startColumn !== range.endColumn)) {+ dirtyRanges.push({ unitId, sheetId, range });+ }+ });+ }++ return dirtyRanges;+ }+private _handleSetRangeValuesMutation(params: ISetRangeValuesMutationParams) {const { subUnitId: sheetId, unitId, cellValue } = params;@@ -136,10 +166,15 @@ export class UpdateFormulaController extends Disposable {return;}+ const dirtyRanges = this._getEditedArrayFormulaDirtyRanges(params);const newSheetFormulaData = this._formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);const arrayFormulaCellDataChanged = this._formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, cellValue);const arrayFormulaRangeChanged = this._formulaDataModel.updateArrayFormulaRange(unitId, sheetId, cellValue);+ if (dirtyRanges.length > 0) {+ this._commandService.syncExecuteCommand(SetTriggerFormulaCalculationStartMutation.id, { dirtyRanges }, { onlyLocal: true });+ }+if (Object.keys(newSheetFormulaData).length === 0) {if (arrayFormulaCellDataChanged || arrayFormulaRangeChanged) {this._commandService.executeCommand(@@ -355,21 +390,19 @@ export class UpdateFormulaController extends Disposable {unitSheetNameMap: IUnitSheetNameMap,formulaReferenceMoveParam: IFormulaReferenceMoveParam) {- if (!Tools.isDefine(formulaData)) return { newFormulaData: {} };+ if (!Tools.isDefine(formulaData)) {+ return { newFormulaData: {} };+ }const formulaDataKeys = Object.keys(formulaData);- if (formulaDataKeys.length === 0) return { newFormulaData: {} };+ if (formulaDataKeys.length === 0) {+ return { newFormulaData: {} };+ }const newFormulaData: IFormulaData = Object.create(null);- const { unitId: fromUnitId, sheetId: fromSheetId, sheetName: fromSheetName, targetUnitId, targetSheetId, type, from, to } = formulaReferenceMoveParam;-- const inCrossSheetCutRangeNewFormulas: Array<{- fromRow: number;- fromColumn: number;- formulaString: string;- }> = [];+ const inCrossSheetCutRangeNewFormulas: ICrossSheetCutFormula[] = [];for (const unitId of formulaDataKeys) {const sheetData = formulaData[unitId];@@ -388,308 +421,283 @@ export class UpdateFormulaController extends Disposable {const matrixData = new ObjectMatrix(sheetData[sheetId] || {});const newFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();const shouldModifySi: string[] = [];+ const context: IFormulaReferenceMoveContext = {+ unitId,+ sheetId,+ unitSheetNameMap,+ params: formulaReferenceMoveParam,+ modifiedSharedFormulaIds: shouldModifySi,+ };matrixData.forValue((row, column, formulaDataItem) => {- if (!formulaDataItem) return true;-- const { f: formulaString, x, y, si } = formulaDataItem;-- if (type === FormulaReferenceMoveType.SetUnitName) {- const { oldUnitName, unitName } = formulaReferenceMoveParam;- if (!oldUnitName || !unitName) return true;- const nextFormula = refactorFormulaUnitQualifier(formulaString, oldUnitName, unitName);- if (nextFormula !== formulaString) newFormulaDataItem.setValue(row, column, { f: nextFormula });- return true;+ const formula = this._getMovedFormula(formulaDataItem, row, column, context, inCrossSheetCutRangeNewFormulas);+ if (formula != null) {+ newFormulaDataItem.setValue(row, column, { f: formula });}+ });++ if (newFormulaData[unitId]) {+ newFormulaData[unitId]![sheetId] = newFormulaDataItem.clone();+ }+ }+ }- const sequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString);+ appendCrossSheetCutFormulas(newFormulaData, inCrossSheetCutRangeNewFormulas, formulaReferenceMoveParam);- if (sequenceNodes == null) {- return true;- }+ return { newFormulaData };+ }- let shouldModify = false;- const refChangeIds: number[] = [];-- // Whether the formula cell is in the moved range and the move is a cross-worksheet cut operation- const inCrossSheetCutRange = type === FormulaReferenceMoveType.MoveRange &&- (targetUnitId !== fromUnitId || targetSheetId !== fromSheetId) &&- unitId === fromUnitId &&- sheetId === fromSheetId &&- from &&- from.startRow <= row &&- row <= from.endRow &&- from.startColumn <= column &&- column <= from.endColumn;- const inCrossSheetCutRangeSequenceNodes = [...sequenceNodes];-- for (let i = 0, len = sequenceNodes.length; i < len; i++) {- const node = sequenceNodes[i];-- if (typeof node === 'string') {- continue;- }-- const { token, nodeType } = node;-- // 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 ((type === FormulaReferenceMoveType.SetSuperTableName || type === FormulaReferenceMoveType.RemoveSuperTableName || type === FormulaReferenceMoveType.RemoveSuperTableColumn) && (nodeType === sequenceNodeType.TABLE || nodeType === sequenceNodeType.FUNCTION)) {- const { oldTableName, tableName, tableColumnNames } = formulaReferenceMoveParam;- if (oldTableName === undefined || (type === FormulaReferenceMoveType.SetSuperTableName && tableName === undefined)) {- continue;- }-- const { tableName: tokenTableName, columnStruct = '' } = splitTableStructuredRef(token);- if (tokenTableName !== oldTableName) {- continue;- }-- if (type === FormulaReferenceMoveType.RemoveSuperTableColumn && !tableReferenceContainsColumn(columnStruct, tableColumnNames)) {- continue;- }-- sequenceNodes[i] = {- ...node,- token: type === FormulaReferenceMoveType.SetSuperTableName ? `${tableName}${columnStruct}` : ErrorType.REF,- };- const nextNode = sequenceNodes[i + 1];- if ((type === FormulaReferenceMoveType.RemoveSuperTableName || type === FormulaReferenceMoveType.RemoveSuperTableColumn) && typeof nextNode === 'string' && nextNode.startsWith(']')) {- sequenceNodes[i + 1] = nextNode.slice(1);- }- shouldModify = true;- refChangeIds.push(i);-- continue;- } else if (nodeType !== sequenceNodeType.REFERENCE) {- continue;- }-- const sequenceGrid = deserializeRangeWithSheetWithCache(token);-- const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;-- const mapUnitId =- sequenceUnitId == null || sequenceUnitId.length === 0 ? unitId : sequenceUnitId;-- const sequenceSheetId = unitSheetNameMap?.[mapUnitId]?.[sheetName] || '';-- if (- !checkIsSameUnitAndSheet(- formulaReferenceMoveParam.unitId,- formulaReferenceMoveParam.sheetId,- unitId,- sheetId,- sequenceUnitId,- sequenceSheetId- )- ) {- continue;- }-- const sequenceUnitRangeWidthOffset: IUnitRangeWithOffset = {- range,- sheetId: sequenceSheetId,- unitId: sequenceUnitId,- sheetName,- refOffsetX: x || 0,- refOffsetY: y || 0,- };-- let newRefString: Nullable<string> = null;-- if (type === FormulaReferenceMoveType.SetName) {- const {- unitId: userUnitId,- sheetId: userSheetId,- sheetName: newSheetName,- } = formulaReferenceMoveParam;- if (newSheetName == null) {- continue;- }-- if (sequenceSheetId == null || sequenceSheetId.length === 0) {- continue;- }-- if (userSheetId !== sequenceSheetId) {- continue;- }-- newRefString = serializeRangeToRefString({- range,- sheetName: newSheetName,- unitId: sequenceUnitId,- });- } else if (type === FormulaReferenceMoveType.RemoveSheet) {- const {- unitId: userUnitId,- sheetId: userSheetId,- sheetName: newSheetName,- } = formulaReferenceMoveParam;-- if (sequenceSheetId == null || sequenceSheetId.length === 0) {- continue;- }-- if (userSheetId !== sequenceSheetId) {- continue;- }-- newRefString = ErrorType.REF;- } else if (type !== FormulaReferenceMoveType.SetDefinedName) {- newRefString = getNewRangeByMoveParam(- sequenceUnitRangeWidthOffset,- formulaReferenceMoveParam,- unitId,- sheetId,- {- inCrossSheetCutRange,- }- );- }-- if (newRefString != null) {- sequenceNodes[i] = {- ...node,- token: newRefString,- };- shouldModify = true;- refChangeIds.push(i);- // newRefString = ErrorType.REF;-- // If the formula cell has an si, it means the formula cell is source of other same si cells, so the si cells needs to be updated.- if (si && (x ?? 0) === 0 && (y ?? 0) === 0) shouldModifySi.push(si);- }-- /**- * If the reference sequence range is not affected by the move, and the move is a cross-worksheet cut operation, it may be necessary to rewrite the sheet name in the ref string after move, to make sure the ref still works after move.- * For example, if a formula cell is `=SUM(A1:A5)` in Sheet1, and formula cell cut to Sheet2, the formula should be rewritten to `=SUM(Sheet1!A1:A5)`, otherwise it will become `=SUM(A1:A5)` and reference the wrong range in Sheet2.- */- if (inCrossSheetCutRange) {- if (newRefString != null) {- inCrossSheetCutRangeSequenceNodes[i] = {- ...node,- token: newRefString,- };- } else if ((!sequenceUnitId || sequenceUnitId === fromUnitId) && (!sequenceSheetId || sequenceSheetId === fromSheetId)) {- /**- * Only the reference range is in the from worksheet need to rewrite the sheet name, otherwise the ref string will be rewritten unnecessarily when moving between other worksheets.- * For example, if a formula cell is `=SUM(Sheet3!A1:A5)` in Sheet1, and formula cell cut to Sheet2, the formula should not be rewritten, otherwise it will become `=SUM(Sheet1!A1:A5)` and reference the wrong range in Sheet1, while the original ref is referencing Sheet3 and should not be affected by the move between Sheet1 and Sheet2.- */- const sequenceRange = Rectangle.moveOffset(range, x || 0, y || 0);- inCrossSheetCutRangeSequenceNodes[i] = {- ...node,- token: serializeRangeToRefString({- range: sequenceRange,- sheetName: fromSheetName || sheetName,- unitId: targetUnitId !== fromUnitId ? fromUnitId : '',- }),- };- shouldModify = true;- }- }- }+ private _getMovedFormula(+ item: Nullable<IFormulaDataItem>,+ row: number,+ column: number,+ context: IFormulaReferenceMoveContext,+ crossSheetFormulas: ICrossSheetCutFormula[]+ ): Nullable<string> {+ if (!item) {+ return null;+ }+ const { f: formulaString, x, y } = item;+ const { unitId, sheetId, params, modifiedSharedFormulaIds } = context;+ if (params.type === FormulaReferenceMoveType.SetUnitName) {+ const { oldUnitName, unitName } = params;+ if (!oldUnitName || !unitName) {+ return null;+ }+ const nextFormula = refactorFormulaUnitQualifier(formulaString, oldUnitName, unitName);+ return nextFormula !== formulaString ? nextFormula : null;+ }- if (!shouldModify) {- /**- * If the operation is a move type, and the formula cell has si and is the same as the current shouldModifySi, unpack the si to f.- * Or the source formula cell is in the moved range.- * This is to ensure that the si formula can be recalculated correctly after the move.- */- if (- si &&- [FormulaReferenceMoveType.MoveRows, FormulaReferenceMoveType.MoveCols, FormulaReferenceMoveType.MoveRange].includes(type)- ) {- if (from && from.startRow <= row && row <= from.endRow && from.startColumn <= column && column <= from.endColumn) {- if ((x ?? 0) === 0 && (y ?? 0) === 0) shouldModifySi.push(si);- } else if (!shouldModifySi.includes(si)) {- return true;- }- } else {- return true;- }- }+ const sequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString);+ if (sequenceNodes == null) {+ return null;+ }+ const refChangeIds: number[] = [];+ const inCrossSheetCutRange = isInCrossSheetCutRange(unitId, sheetId, row, column, params);+ const crossSheetNodes = [...sequenceNodes];+ const shouldModify = this._updateFormulaReferenceNodes(sequenceNodes, item, context, refChangeIds, inCrossSheetCutRange ? crossSheetNodes : null);+ if (!shouldModify && !shouldUnpackSharedFormula(item, row, column, params, modifiedSharedFormulaIds)) {+ return null;+ }- if (inCrossSheetCutRange) {- const newSequenceNodes = updateRefOffset(inCrossSheetCutRangeSequenceNodes, refChangeIds, x, y);- inCrossSheetCutRangeNewFormulas.push({- fromRow: row,- fromColumn: column,- formulaString: `=${generateStringWithSequence(newSequenceNodes)}`,- });- return true;- }+ const newSequenceNodes = updateRefOffset(inCrossSheetCutRange ? crossSheetNodes : sequenceNodes, refChangeIds, x, y);+ const formula = `=${generateStringWithSequence(newSequenceNodes)}`;+ if (inCrossSheetCutRange) {+ crossSheetFormulas.push({ fromRow: row, fromColumn: column, formulaString: formula });+ return null;+ }+ return formula;+ }- const newSequenceNodes = updateRefOffset(sequenceNodes, refChangeIds, x, y);+ private _updateFormulaReferenceNodes(+ sequenceNodes: Array<string | ISequenceNode>,+ item: IFormulaDataItem,+ context: IFormulaReferenceMoveContext,+ refChangeIds: number[],+ crossSheetNodes: Nullable<Array<string | ISequenceNode>>+ ): boolean {+ const { unitId, sheetId, params, modifiedSharedFormulaIds } = context;+ const { x, y, si } = item;+ let shouldModify = false;+ for (let i = 0, len = sequenceNodes.length; i < len; i++) {+ const node = sequenceNodes[i];+ if (typeof node === 'string') {+ continue;+ }- newFormulaDataItem.setValue(row, column, {- f: `=${generateStringWithSequence(newSequenceNodes)}`,- });- });+ const definedNameToken = this._getDefinedNameReferenceToken(node, unitId, params);+ if (definedNameToken != null) {+ sequenceNodes[i] = { ...node, token: definedNameToken };+ shouldModify = true;+ refChangeIds.push(i);+ continue;+ }+ if (updateTableReference(sequenceNodes, i, node, params)) {+ shouldModify = true;+ refChangeIds.push(i);+ continue;+ }+ if (node.nodeType !== sequenceNodeType.REFERENCE) {+ continue;+ }- if (newFormulaData[unitId]) {- newFormulaData[unitId]![sheetId] = newFormulaDataItem.clone();+ const reference = getReferenceWithOffset(node.token, item, context);+ if (reference == null) {+ continue;+ }+ const newRefString = getMovedReferenceToken(reference, params, unitId, sheetId, crossSheetNodes != null);+ if (newRefString != null) {+ sequenceNodes[i] = { ...node, token: newRefString };+ shouldModify = true;+ refChangeIds.push(i);+ // Shared followers must be unpacked after their anchor reference changes.+ if (si && (x ?? 0) === 0 && (y ?? 0) === 0) {+ modifiedSharedFormulaIds.push(si);+ }+ }+ if (crossSheetNodes != null) {+ const movedNode = getCrossSheetCutReference(node, reference, newRefString, params);+ if (movedNode != null) {+ crossSheetNodes[i] = movedNode;+ shouldModify = true;}}}+ return shouldModify;+ }- if (inCrossSheetCutRangeNewFormulas.length > 0 && targetUnitId && targetSheetId) {- if (!newFormulaData[targetUnitId]) {- newFormulaData[targetUnitId] = Object.create(null);- }+ private _getDefinedNameReferenceToken(node: ISequenceNode, unitId: string, params: IFormulaReferenceMoveParam): Nullable<string> {+ const { type, definedNameId, definedName } = params;+ if (type !== FormulaReferenceMoveType.SetDefinedName && type !== FormulaReferenceMoveType.RemoveDefinedName) {+ return null;+ }+ if (node.nodeType !== sequenceNodeType.DEFINED_NAME && node.nodeType !== sequenceNodeType.FUNCTION) {+ return null;+ }+ if (definedNameId === undefined || definedName === undefined) {+ return null;+ }- if (!newFormulaData[targetUnitId]![targetSheetId]) {- newFormulaData[targetUnitId]![targetSheetId] = Object.create(null);- }+ const oldDefinedName = this._definedNamesService.getValueById(unitId, definedNameId);+ if (oldDefinedName == null || oldDefinedName.name !== node.token) {+ return null;+ }- for (const newFormula of inCrossSheetCutRangeNewFormulas) {- const { fromRow, fromColumn, formulaString } = newFormula;- const targetRow = fromRow + ((to?.startRow ?? 0) - (from?.startRow ?? 0));- const targetColumn = fromColumn + ((to?.startColumn ?? 0) - (from?.startColumn ?? 0));+ return type === FormulaReferenceMoveType.SetDefinedName ? definedName : ErrorType.REF;+ }+}- if (!newFormulaData[targetUnitId]![targetSheetId]![targetRow]) {- newFormulaData[targetUnitId]![targetSheetId]![targetRow] = Object.create(null);- }+function getReferenceWithOffset(token: string, item: IFormulaDataItem, context: IFormulaReferenceMoveContext): Nullable<IUnitRangeWithOffset> {+ const { unitId, sheetId, unitSheetNameMap, params } = context;+ const { range, sheetName, unitId: sequenceUnitId } = deserializeRangeWithSheetWithCache(token);+ const mapUnitId = sequenceUnitId == null || sequenceUnitId.length === 0 ? unitId : sequenceUnitId;+ const sequenceSheetId = unitSheetNameMap?.[mapUnitId]?.[sheetName] || '';+ if (!checkIsSameUnitAndSheet(params.unitId, params.sheetId, unitId, sheetId, sequenceUnitId, sequenceSheetId)) {+ return null;+ }+ return {+ range,+ sheetId: sequenceSheetId,+ unitId: sequenceUnitId,+ sheetName,+ refOffsetX: item.x || 0,+ refOffsetY: item.y || 0,+ };+}- newFormulaData[targetUnitId]![targetSheetId]![targetRow][targetColumn] = {- f: formulaString,- };- }+function appendCrossSheetCutFormulas(data: IFormulaData, formulas: ICrossSheetCutFormula[], params: IFormulaReferenceMoveParam): void {+ const { targetUnitId, targetSheetId, from, to } = params;+ if (formulas.length === 0 || !targetUnitId || !targetSheetId) {+ return;+ }+ if (!data[targetUnitId]) {+ data[targetUnitId] = Object.create(null);+ }+ if (!data[targetUnitId]![targetSheetId]) {+ data[targetUnitId]![targetSheetId] = Object.create(null);+ }+ for (const { fromRow, fromColumn, formulaString } of formulas) {+ const targetRow = fromRow + ((to?.startRow ?? 0) - (from?.startRow ?? 0));+ const targetColumn = fromColumn + ((to?.startColumn ?? 0) - (from?.startColumn ?? 0));+ if (!data[targetUnitId]![targetSheetId]![targetRow]) {+ data[targetUnitId]![targetSheetId]![targetRow] = Object.create(null);}+ data[targetUnitId]![targetSheetId]![targetRow][targetColumn] = { f: formulaString };+ }+}- return { newFormulaData };+function isInCrossSheetCutRange(unitId: string, sheetId: string, row: number, column: number, params: IFormulaReferenceMoveParam): boolean {+ const { type, unitId: fromUnitId, sheetId: fromSheetId, targetUnitId, targetSheetId, from } = params;+ return type === FormulaReferenceMoveType.MoveRange &&+ (targetUnitId !== fromUnitId || targetSheetId !== fromSheetId) &&+ unitId === fromUnitId && sheetId === fromSheetId &&+ from != null && from.startRow <= row && row <= from.endRow &&+ from.startColumn <= column && column <= from.endColumn;+}++function updateTableReference(sequenceNodes: Array<string | ISequenceNode>, index: number, node: ISequenceNode, params: IFormulaReferenceMoveParam): boolean {+ const { type, oldTableName, tableName, tableColumnNames } = params;+ if (type !== FormulaReferenceMoveType.SetSuperTableName && type !== FormulaReferenceMoveType.RemoveSuperTableName && type !== FormulaReferenceMoveType.RemoveSuperTableColumn) {+ return false;+ }+ if (node.nodeType !== sequenceNodeType.TABLE && node.nodeType !== sequenceNodeType.FUNCTION) {+ return false;+ }+ if (oldTableName === undefined || (type === FormulaReferenceMoveType.SetSuperTableName && tableName === undefined)) {+ return false;+ }++ const { tableName: tokenTableName, columnStruct = '' } = splitTableStructuredRef(node.token);+ if (tokenTableName !== oldTableName) {+ return false;+ }+ if (type === FormulaReferenceMoveType.RemoveSuperTableColumn && !tableReferenceContainsColumn(columnStruct, tableColumnNames)) {+ return false;+ }++ sequenceNodes[index] = {+ ...node,+ token: type === FormulaReferenceMoveType.SetSuperTableName ? `${tableName}${columnStruct}` : ErrorType.REF,+ };+ const nextNode = sequenceNodes[index + 1];+ if ((type === FormulaReferenceMoveType.RemoveSuperTableName || type === FormulaReferenceMoveType.RemoveSuperTableColumn) && typeof nextNode === 'string' && nextNode.startsWith(']')) {+ sequenceNodes[index + 1] = nextNode.slice(1);+ }+ return true;+}++function getMovedReferenceToken(reference: IUnitRangeWithOffset, params: IFormulaReferenceMoveParam, unitId: string, sheetId: string, inCrossSheetCutRange: boolean): Nullable<string> {+ const { type, sheetId: affectedSheetId, sheetName } = params;+ if (type === FormulaReferenceMoveType.SetName || type === FormulaReferenceMoveType.RemoveSheet) {+ if (!reference.sheetId || affectedSheetId !== reference.sheetId) {+ return null;+ }+ if (type === FormulaReferenceMoveType.RemoveSheet) {+ return ErrorType.REF;+ }+ if (sheetName == null) {+ return null;+ }+ return serializeRangeToRefString({ range: reference.range, sheetName, unitId: reference.unitId });+ }+ if (type === FormulaReferenceMoveType.SetDefinedName) {+ return null;+ }+ return getNewRangeByMoveParam(reference, params, unitId, sheetId, { inCrossSheetCutRange });+}++function getCrossSheetCutReference(node: ISequenceNode, reference: IUnitRangeWithOffset, newRefString: Nullable<string>, params: IFormulaReferenceMoveParam): Nullable<ISequenceNode> {+ if (newRefString != null) {+ return { ...node, token: newRefString };+ }+ const { unitId, sheetId, targetUnitId, sheetName } = params;+ if ((reference.unitId && reference.unitId !== unitId) || (reference.sheetId && reference.sheetId !== sheetId)) {+ return null;+ }+ // Unaffected references to the source sheet need an explicit qualifier after a cross-sheet cut.+ return {+ ...node,+ token: serializeRangeToRefString({+ range: Rectangle.moveOffset(reference.range, reference.refOffsetX || 0, reference.refOffsetY || 0),+ sheetName: sheetName || reference.sheetName,+ unitId: targetUnitId !== unitId ? unitId : '',+ }),+ };+}++function shouldUnpackSharedFormula(item: IFormulaDataItem, row: number, column: number, params: IFormulaReferenceMoveParam, modifiedIds: string[]): boolean {+ const { si, x, y } = item;+ const { type, from } = params;+ if (!si || ![FormulaReferenceMoveType.MoveRows, FormulaReferenceMoveType.MoveCols, FormulaReferenceMoveType.MoveRange].includes(type)) {+ return false;+ }+ if (from && from.startRow <= row && row <= from.endRow && from.startColumn <= column && column <= from.endColumn) {+ if ((x ?? 0) === 0 && (y ?? 0) === 0) {+ modifiedIds.push(si);+ }+ return true;}+ return modifiedIds.includes(si);}/**