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 formula spill blockers (#6909)
Univerf15d008a964e
diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.tsindex 115c5fe0df..435d516b97 100644--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts@@ -323,6 +323,63 @@ describe('Test formula data model', () => {const formulaData = formulaDataModel.getArrayFormulaCellData();expect(formulaData).toStrictEqual(result);});++ it('should clear only edited array formula cell data when editing a spill cell', () => {+ const unitId = 'test';+ const sheetId = 'sheet1';++ formulaDataModel.setArrayFormulaRange({+ [unitId]: {+ [sheetId]: {+ 0: {+ 3: {+ startRow: 0,+ startColumn: 3,+ endRow: 1,+ endColumn: 3,+ },+ },+ },+ },+ });++ formulaDataModel.setArrayFormulaCellData({+ [unitId]: {+ [sheetId]: {+ 0: {+ 3: {+ v: 1,+ },+ },+ 1: {+ 3: {+ v: 2,+ },+ },+ },+ },+ });++ formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, {+ 1: {+ 3: {+ v: 111,+ },+ },+ });++ expect(formulaDataModel.getArrayFormulaCellData()).toStrictEqual({+ [unitId]: {+ [sheetId]: {+ 0: {+ 3: {+ v: 1,+ },+ },+ },+ },+ });+ });});describe('getFormulaStringByCell', () => {@@ -397,16 +454,7 @@ describe('Test formula data model', () => {},});- expect(formulaDataModel.getArrayFormulaCellData().test?.sheet1).toEqual({- 0: {- 0: null,- 1: null,- },- 1: {- 0: null,- 1: null,- },- });+ expect(formulaDataModel.getArrayFormulaCellData().test?.sheet1).toEqual({});});it('should merge array formula range and cell data', () => {diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex e69165a069..62c9902a46 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -93,7 +93,7 @@ export class FormulaDataModel extends Disposable {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);+ arrayFormulaCellMatrixData.realDeleteValue(r, c);}}@@ -141,13 +141,17 @@ export class FormulaDataModel extends Disposable {const { startRow, startColumn, endRow, endColumn } = arrayFormulaRange;for (let r = startRow; r <= endRow; r++) {for (let c = startColumn; c <= endColumn; c++) {- arrayFormulaCellMatrixData.setValue(r, c, null);+ arrayFormulaCellMatrixData.realDeleteValue(r, c);}}});cellMatrixData.forValue((row, column, cellData) => {- arrayFormulaCellMatrixData.setValue(row, column, cellData);+ if (cellData == null) {+ arrayFormulaCellMatrixData.realDeleteValue(row, column);+ } else {+ arrayFormulaCellMatrixData.setValue(row, column, cellData);+ }});if (this._arrayFormulaCellData[unitId]) {@@ -457,14 +461,24 @@ export class FormulaDataModel extends Disposable {const arrayFormulaRange = this._arrayFormulaRange[unitId]?.[sheetId];- if (!arrayFormulaRange) return;+ if (!arrayFormulaRange) return false;const arrayFormulaRangeMatrix = new ObjectMatrix(arrayFormulaRange);const cellMatrix = new ObjectMatrix(cellValue);+ let changed = false;- cellMatrix.forValue((r, c, cell) => {- arrayFormulaRangeMatrix.realDeleteValue(r, c);+ cellMatrix.forValue((r, c) => {+ if (arrayFormulaRangeMatrix.getValue(r, c) != null) {+ arrayFormulaRangeMatrix.realDeleteValue(r, c);+ changed = true;+ }});++ if (changed && this._arrayFormulaRange[unitId]) {+ this._arrayFormulaRange[unitId]![sheetId] = arrayFormulaRangeMatrix.getData();+ }++ return changed;}updateArrayFormulaCellData(@@ -476,21 +490,28 @@ export class FormulaDataModel extends Disposable {const arrayFormulaRange = this._arrayFormulaRange[unitId]?.[sheetId];- if (!arrayFormulaRange) return;+ if (!arrayFormulaRange) return false;const arrayFormulaRangeMatrix = new ObjectMatrix(arrayFormulaRange);const arrayFormulaCellData = this._arrayFormulaCellData[unitId]?.[sheetId];- if (!arrayFormulaCellData) return;+ if (!arrayFormulaCellData) return false;const arrayFormulaCellDataMatrix = new ObjectMatrix(arrayFormulaCellData);const cellMatrix = new ObjectMatrix(cellValue);+ let changed = false;- cellMatrix.forValue((r, c, cell) => {- clearArrayFormulaCellDataByCell(arrayFormulaRangeMatrix, arrayFormulaCellDataMatrix, r, c);+ cellMatrix.forValue((r, c) => {+ changed = clearArrayFormulaCellDataByCell(arrayFormulaRangeMatrix, arrayFormulaCellDataMatrix, r, c) || changed;});++ if (changed && this._arrayFormulaCellData[unitId]) {+ this._arrayFormulaCellData[unitId]![sheetId] = arrayFormulaCellDataMatrix.getData();+ }++ return changed;}updateImageFormulaData(unitId: string, sheetId: string, cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>) {diff --git a/packages/engine-formula/src/models/utils/formula-data-util.ts b/packages/engine-formula/src/models/utils/formula-data-util.tsindex 64da1a2a6c..12261213c7 100644--- a/packages/engine-formula/src/models/utils/formula-data-util.ts+++ b/packages/engine-formula/src/models/utils/formula-data-util.ts@@ -93,10 +93,21 @@ export function updateFormulaDataByCellValue(sheetFormulaDataMatrix: ObjectMatriexport function clearArrayFormulaCellDataByCell(arrayFormulaRangeMatrix: ObjectMatrix<IRange>, arrayFormulaCellDataMatrix: ObjectMatrix<Nullable<ICellData>>, r: number, c: number) {const arrayFormulaRangeValue = arrayFormulaRangeMatrix?.getValue(r, c);+if (arrayFormulaRangeValue == null) {- return true;+ let changed = false;+ arrayFormulaRangeMatrix.forValue((_, __, range) => {+ if (Rectangle.contains(range, cellToRange(r, c))) {+ arrayFormulaCellDataMatrix.realDeleteValue(r, c);+ changed = true;+ return false;+ }+ });++ return changed;}+ const targetArrayFormulaRange = arrayFormulaRangeValue;const intersection: IRange[] = [];arrayFormulaRangeMatrix.forValue((rangeRow, rangeCol, range) => {// skip the current range@@ -104,12 +115,12 @@ export function clearArrayFormulaCellDataByCell(arrayFormulaRangeMatrix: ObjectMreturn;}- if (Rectangle.intersects(range, arrayFormulaRangeValue)) {+ if (Rectangle.intersects(range, targetArrayFormulaRange)) {intersection.push(range);}});- const { startRow, startColumn, endRow, endColumn } = arrayFormulaRangeValue;+ const { startRow, startColumn, endRow, endColumn } = targetArrayFormulaRange;for (let row = startRow; row <= endRow; row++) {for (let col = startColumn; col <= endColumn; col++) {@@ -131,4 +142,6 @@ export function clearArrayFormulaCellDataByCell(arrayFormulaRangeMatrix: ObjectM}}}++ return true;}diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.tsindex 32dbe1e5ba..55330992f0 100644--- a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts@@ -245,6 +245,148 @@ describe('FormulaRuntimeService', () => {expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(9, 9)?.v).toBe(ErrorType.SPILL);});+ it('should not treat previous cells of the same array formula as spill blockers', () => {+ const { runtime, unitDataMatrix, arrayFormulaCellData, arrayFormulaRange } = createRuntimeService();+ arrayFormulaRange.unit.sheet = {+ 3: {+ 3: {+ startRow: 3,+ startColumn: 3,+ endRow: 4,+ endColumn: 4,+ },+ },+ };+ unitDataMatrix.setValue(3, 4, { v: 12 });+ arrayFormulaCellData.setValue(3, 4, { v: 12 });++ runtime.setCurrent(3, 3, 10, 10, 'sheet', 'unit');+ const twoByTwo = createNewArray(+ [+ [NumberValueObject.create(11), NumberValueObject.create(12)],+ [NumberValueObject.create(21), NumberValueObject.create(22)],+ ],+ 2,+ 2+ );++ runtime.setRuntimeData(twoByTwo as never);+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 3)?.v).toBe(11);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(3, 4)?.v).toBe(12);+ });++ it('should return #SPILL when a real value is entered into the previous array formula range', () => {+ const { runtime, unitDataMatrix, arrayFormulaCellData, arrayFormulaRange } = createRuntimeService();+ arrayFormulaRange.unit.sheet = {+ 3: {+ 3: {+ startRow: 3,+ startColumn: 3,+ endRow: 4,+ endColumn: 4,+ },+ },+ };+ unitDataMatrix.setValue(3, 4, { v: 12 });+ unitDataMatrix.setValue(4, 3, { v: 21 });+ unitDataMatrix.setValue(4, 4, { v: 111 });+ arrayFormulaCellData.setValue(3, 3, { v: 11 });+ arrayFormulaCellData.setValue(3, 4, { v: 12 });+ arrayFormulaCellData.setValue(4, 3, { v: 21 });++ runtime.setCurrent(3, 3, 10, 10, 'sheet', 'unit');+ const twoByTwo = createNewArray(+ [+ [NumberValueObject.create(11), NumberValueObject.create(12)],+ [NumberValueObject.create(21), NumberValueObject.create(22)],+ ],+ 2,+ 2+ );++ runtime.setRuntimeData(twoByTwo as never);+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 3)?.v).toBe(ErrorType.SPILL);+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 4)).toBeNull();+ expect(runtime.getUnitData().unit?.sheet?.getValue(4, 3)).toBeNull();+ expect(runtime.getUnitData().unit?.sheet?.getValue(4, 4)?.v).toBe(111);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(3, 3)?.v).toBe(ErrorType.SPILL);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(4, 4)).toBeUndefined();+ });++ it('should not mark real spill blockers as array formula cell data', () => {+ const { runtime, unitDataMatrix, arrayFormulaCellData, arrayFormulaRange } = createRuntimeService();+ arrayFormulaRange.unit.sheet = {+ 3: {+ 3: {+ startRow: 3,+ startColumn: 3,+ endRow: 4,+ endColumn: 4,+ },+ },+ };+ unitDataMatrix.setValue(3, 4, { v: 12 });+ unitDataMatrix.setValue(4, 3, { v: 222 });+ unitDataMatrix.setValue(4, 4, { v: 111 });+ arrayFormulaCellData.setValue(3, 3, { v: ErrorType.SPILL });+ arrayFormulaCellData.setValue(3, 4, { v: 12 });++ runtime.setCurrent(3, 3, 10, 10, 'sheet', 'unit');+ const twoByTwo = createNewArray(+ [+ [NumberValueObject.create(11), NumberValueObject.create(12)],+ [NumberValueObject.create(21), NumberValueObject.create(22)],+ ],+ 2,+ 2+ );++ runtime.setRuntimeData(twoByTwo as never);+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 3)?.v).toBe(ErrorType.SPILL);+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 4)).toBeNull();+ expect(runtime.getUnitData().unit?.sheet?.getValue(4, 3)?.v).toBe(222);+ expect(runtime.getUnitData().unit?.sheet?.getValue(4, 4)?.v).toBe(111);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(3, 3)?.v).toBe(ErrorType.SPILL);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(4, 3)).toBeUndefined();+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(4, 4)).toBeUndefined();+ });++ it('should preserve a real blocker even when stale array formula cell data still has the edited cell', () => {+ const { runtime, unitDataMatrix, arrayFormulaCellData, arrayFormulaRange } = createRuntimeService();+ arrayFormulaRange.unit.sheet = {+ 3: {+ 3: {+ startRow: 3,+ startColumn: 3,+ endRow: 4,+ endColumn: 4,+ },+ },+ };+ unitDataMatrix.setValue(3, 4, { v: 12 });+ unitDataMatrix.setValue(4, 3, { v: 222 });+ arrayFormulaCellData.setValue(3, 3, { v: 11 });+ arrayFormulaCellData.setValue(3, 4, { v: 12 });+ arrayFormulaCellData.setValue(4, 3, { v: 21 });++ runtime.setCurrent(3, 3, 10, 10, 'sheet', 'unit');+ const twoByTwo = createNewArray(+ [+ [NumberValueObject.create(11), NumberValueObject.create(12)],+ [NumberValueObject.create(21), NumberValueObject.create(22)],+ ],+ 2,+ 2+ );++ runtime.setRuntimeData(twoByTwo as never);+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 3)?.v).toBe(ErrorType.SPILL);+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 4)).toBeNull();+ expect(runtime.getUnitData().unit?.sheet?.getValue(4, 3)?.v).toBe(222);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(3, 3)?.v).toBe(ErrorType.SPILL);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(4, 3)).toBeUndefined();+ });+it('should manage feature caches and embedded map', () => {const { runtime } = createRuntimeService();runtime.setCurrent(4, 5, 20, 20, 'sheet', 'unit');diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.tsindex 0c21580eb6..2afe480bb1 100644--- a/packages/engine-formula/src/services/runtime.service.ts+++ b/packages/engine-formula/src/services/runtime.service.ts@@ -581,10 +581,10 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime// Do not use getData to synchronize arrayData to arrayFormulaRange[sheetId] anymore, they are already linked, otherwise it will cause performance issuesarrayData.setValue(row, column, arrayRange);- if (- this._checkIfArrayFormulaRangeHasData(unitId, sheetId, row, column, arrayRange) ||- this._checkIfArrayFormulaExceeded(rowCount, columnCount, arrayRange)- ) {+ const hasDataInArrayFormulaRange = this._checkIfArrayFormulaRangeHasData(unitId, sheetId, row, column, arrayRange);+ const isArrayFormulaExceeded = this._checkIfArrayFormulaExceeded(rowCount, columnCount, arrayRange);++ if (hasDataInArrayFormulaRange || isArrayFormulaExceeded) {const errorObject = this._getValueObjectOfRuntimeData(ErrorValueObject.create(ErrorType.SPILL));sheetData.setValue(row, column, errorObject);clearArrayUnitData.setValue(row, column, errorObject);@@ -604,23 +604,30 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime* In this case, you need to clear the previous range data to prevent other formulas from referencing the old values.*/const unitData = this._currentConfigService.getUnitData();+ const arrayData = this._currentConfigService.getArrayFormulaCellData();+ const previousArrayFormulaRange =+ this._currentConfigService.getArrayFormulaRange()[unitId]?.[sheetId]?.[row]?.[column];objectValueRefOrArray.iterator((_, rowIndex, columnIndex) => {const currentRow = rowIndex - startRow + row;const currentColumn = columnIndex - startColumn + column;const cell = unitData[unitId]?.[sheetId]?.cellData.getValue(currentRow, currentColumn);+ const arrayDataCell = arrayData?.[unitId]?.[sheetId]?.getValue(currentRow, currentColumn);+ const shouldClearPreviousCellOfCurrentArrayFormula = this._arrayCellHasData(arrayDataCell) &&+ this._isInArrayFormulaRange(previousArrayFormulaRange, currentRow, currentColumn) &&+ (cell == null || this._isSameCellValue(cell, arrayDataCell));if (rowIndex === startRow && columnIndex === startColumn) {runtimeArrayUnitData.setValue(row, column, errorObject);+ } else if (shouldClearPreviousCellOfCurrentArrayFormula) {+ sheetData.setValue(currentRow, currentColumn, null);} else if (cell != null) {if (cell.v == null) {cell.v = '';}- runtimeArrayUnitData.setValue(currentRow, currentColumn, cell);+ sheetData.setValue(currentRow, currentColumn, { ...cell });} // To determine whether a cell has a value, in addition to cell != null, other array formulas may get undefined (displayed as 0). In this case, the value of the existing array formula cannot be modified.else if (this._isInOtherArrayFormulaRange(unitId, sheetId, row, column, currentRow, currentColumn)) {return true;- } else {- runtimeArrayUnitData.setValue(currentRow, currentColumn, { v: '' });}});} else {@@ -825,8 +832,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime// this._runtimeArrayFormulaCellData data is incomplete, use the data on configServiceconst arrayData = this._currentConfigService.getArrayFormulaCellData();- const unitArrayFormulaRange =- this._unitArrayFormulaRange[formulaUnitId]?.[formulaSheetId]?.[formulaRow]?.[formulaColumn];+ const previousArrayFormulaRange =+ this._currentConfigService.getArrayFormulaRange()[formulaUnitId]?.[formulaSheetId]?.[formulaRow]?.[formulaColumn];for (let r = startRow; r <= endRow; r++) {for (let c = startColumn; c <= endColumn; c++) {@@ -843,13 +850,20 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst currentCell = unitData?.[formulaUnitId]?.[formulaSheetId]?.cellData?.getValue(r, c);const featureCell = this._getRuntimeFeatureCellValue(r, c, formulaSheetId, formulaUnitId);+ const isPreviousCellOfCurrentArrayFormula = this._arrayCellHasData(arrayDataCell) &&+ this._isInArrayFormulaRange(previousArrayFormulaRange, r, c) &&+ (currentCell == null || this._isSameCellValue(currentCell, arrayDataCell));+ const hasRuntimeCell = !isNullCellForFormula(cell);+ const isInOtherArrayFormulaRange = this._isInOtherArrayFormulaRange(formulaUnitId, formulaSheetId, formulaRow, formulaColumn, r, c);+ const currentCellBlocks = !isNullCellForFormula(currentCell) && !isPreviousCellOfCurrentArrayFormula;+ const featureCellBlocks = !isNullCellForFormula(featureCell);// arrayDataCell may display 0 as {v: null}. Although it is an empty cell, it is considered to have a value.if (- !isNullCellForFormula(cell) ||- this._isInOtherArrayFormulaRange(formulaUnitId, formulaSheetId, formulaRow, formulaColumn, r, c) ||- !isNullCellForFormula(currentCell) ||- !isNullCellForFormula(featureCell)+ hasRuntimeCell ||+ isInOtherArrayFormulaRange ||+ currentCellBlocks ||+ featureCellBlocks) {return true;}@@ -926,6 +940,10 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimereturn false;}+ private _isSameCellValue(cell: Nullable<ICellData>, arrayDataCell: Nullable<ICellData>) {+ return cell?.v === arrayDataCell?.v && cell?.t === arrayDataCell?.t;+ }+private _checkIfArrayFormulaExceeded(rowCount: number, columnCount: number, arrayRange: IRange) {if (arrayRange.endRow >= rowCount || arrayRange.endColumn >= columnCount) {return true;diff --git a/packages/sheets-formula/src/controllers/__tests__/array-formula-spill.worker.spec.ts b/packages/sheets-formula/src/controllers/__tests__/array-formula-spill.worker.spec.tsnew file mode 100644index 0000000000..5c3c91932c--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/array-formula-spill.worker.spec.ts@@ -0,0 +1,312 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';+import type { FFormula } from '@univerjs/engine-formula/facade';+import type { IMessageProtocol } from '@univerjs/rpc';+import { ICommandService, ILogService, Inject, Injector, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import {+ CalculateController,+ ErrorType,+ FormulaDataModel,+ SetArrayFormulaDataMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ UniverFormulaEnginePlugin,+} from '@univerjs/engine-formula';+import {+ ChannelService,+ DataSyncPrimaryController,+ DataSyncReplicaController,+ IRemoteInstanceService,+ IRemoteSyncService,+ IRPCChannelService,+ RemoteSyncPrimaryService,+ WebWorkerRemoteInstanceService,+} from '@univerjs/rpc';+import { SetRangeValuesMutation, UniverSheetsPlugin } from '@univerjs/sheets';+import { ReplaySubject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { UniverRemoteSheetsFormulaPlugin, UniverSheetsFormulaPlugin } from '../../plugin';++import '@univerjs/engine-formula/facade';++const unitId = 'test';+const subUnitId = 'sheet1';++function createPairedMessageProtocols(): [IMessageProtocol, IMessageProtocol] {+ const mainToWorker$ = new ReplaySubject<unknown>(1);+ const workerToMain$ = new ReplaySubject<unknown>(1);++ return [+ {+ send(message: unknown) {+ mainToWorker$.next(message);+ },+ onMessage: workerToMain$.asObservable(),+ },+ {+ send(message: unknown) {+ workerToMain$.next(message);+ },+ onMessage: mainToWorker$.asObservable(),+ },+ ];+}++function waitForMicrotasks(count = 4): Promise<void> {+ let promise = Promise.resolve();+ for (let i = 0; i < count; i++) {+ promise = promise.then(() => undefined);+ }++ return promise;+}++function registerCommand(commandService: ICommandService, command: ICommand) {+ try {+ commandService.registerCommand(command);+ } catch (error) {+ if (!(error instanceof Error) || !error.message.includes('has been registered before')) {+ throw error;+ }+ }+}++async function waitForCondition(condition: () => boolean): Promise<void> {+ for (let i = 0; i < 20; i++) {+ if (condition()) {+ return;+ }++ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ }++ throw new Error('Timed out waiting for condition.');+}++function createWorkbookData(): IWorkbookData {+ const sourceCellData: NonNullable<IWorkbookData['sheets'][string]['cellData']> = {};++ for (let row = 2; row <= 9; row++) {+ sourceCellData[row] = {};+ for (let column = 2; column <= 6; column++) {+ sourceCellData[row]![column] = {+ v: row + column,+ t: 2,+ };+ }+ }++ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: [subUnitId],+ styles: {},+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet1',+ rowCount: 30,+ columnCount: 20,+ cellData: {+ ...sourceCellData,+ 12: {+ 6: {+ f: '=C3:G10',+ },+ },+ },+ },+ },+ };+}++function createWorkerFormulaTestBed() {+ const [mainProtocol, workerProtocol] = createPairedMessageProtocols();++ class MainRPCPlugin extends Plugin {+ static override pluginName = 'test-main-rpc-plugin';++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ this._injector.add([IRPCChannelService, {+ // eslint-disable-next-line react/no-unnecessary-use-prefix+ useFactory: () => new ChannelService(mainProtocol),+ }]);+ this._injector.add([DataSyncPrimaryController]);+ this._injector.add([IRemoteSyncService, { useClass: RemoteSyncPrimaryService }]);+ this._injector.get(DataSyncPrimaryController);+ }+ }++ class WorkerRPCPlugin extends Plugin {+ static override pluginName = 'test-worker-rpc-plugin';++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ this._injector.add([IRPCChannelService, {+ // eslint-disable-next-line react/no-unnecessary-use-prefix+ useFactory: () => new ChannelService(workerProtocol),+ }]);+ this._injector.add([IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]);+ this._injector.add([DataSyncReplicaController]);+ this._injector.get(DataSyncReplicaController);+ }+ }++ const workerUniver = new Univer({+ locale: LocaleType.EN_US,+ logLevel: LogLevel.SILENT,+ });+ workerUniver.registerPlugins([+ [UniverSheetsPlugin, { onlyRegisterFormulaRelatedMutations: true }],+ [UniverFormulaEnginePlugin],+ [WorkerRPCPlugin],+ [UniverRemoteSheetsFormulaPlugin],+ ]);++ const mainUniver = new Univer({+ locale: LocaleType.EN_US,+ logLevel: LogLevel.SILENT,+ });+ mainUniver.registerPlugins([+ [MainRPCPlugin],+ [UniverSheetsPlugin, { notExecuteFormula: true }],+ [UniverFormulaEnginePlugin, { notExecuteFormula: true }],+ [UniverSheetsFormulaPlugin, { notExecuteFormula: true }],+ ]);++ const mainInjector = mainUniver.__getInjector();+ const workerInjector = workerUniver.__getInjector();+ const mainCommandService = mainInjector.get(ICommandService);+ const workerCommandService = workerInjector.get(ICommandService);++ mainInjector.get(ILogService).setLogLevel(LogLevel.SILENT);+ workerInjector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const sheet = mainUniver.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ return {+ commandService: mainCommandService,+ formulaDataModel: mainInjector.get(FormulaDataModel),+ mainUniver,+ sheet,+ workerCommandService,+ workerFormulaEngine: FUniver.newAPI(workerUniver).getFormula() as FFormula,+ workerInjector,+ workerInstanceService: workerInjector.get(IUniverInstanceService),+ workerUniver,+ };+}++describe('Array formula SPILL with worker formula calculation', () => {+ let testBed: ReturnType<typeof createWorkerFormulaTestBed>;+ let commandService: ICommandService;+ let formulaDataModel: FormulaDataModel;+ let worksheet: Worksheet;++ beforeEach(() => {+ testBed = createWorkerFormulaTestBed();+ commandService = testBed.commandService;+ formulaDataModel = testBed.formulaDataModel;+ worksheet = testBed.sheet.getSheetBySheetId(subUnitId) as Worksheet;+ });++ afterEach(() => {+ testBed.mainUniver.dispose();+ testBed.workerUniver.dispose();+ });++ async function calculateInWorker() {+ await waitForCondition(() => testBed.workerInstanceService.getUnit(unitId) != null);+ [+ SetArrayFormulaDataMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ SetRangeValuesMutation,+ ].forEach((command) => {+ registerCommand(commandService, command);+ registerCommand(testBed.workerCommandService, command);+ });+ testBed.workerInjector.get(CalculateController);++ const calculationEnd = testBed.workerFormulaEngine.onCalculationEnd();+ testBed.workerCommandService.syncExecuteCommand(SetFormulaCalculationStartMutation.id, { forceCalculation: true }, { onlyLocal: true });+ await calculationEnd;+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ await waitForMicrotasks(12);+ }++ async function setCell(row: number, column: number, value: number) {+ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId,+ subUnitId,+ cellValue: {+ [row]: {+ [column]: {+ v: value,+ t: 2,+ },+ },+ },+ });+ }++ it('should preserve multiple real blockers inside a spilled array reference formula', async () => {+ await calculateInWorker();++ expect(formulaDataModel.getArrayFormulaRange()[unitId]?.[subUnitId]?.[12]?.[6]).toEqual({+ startRow: 12,+ startColumn: 6,+ endRow: 19,+ endColumn: 10,+ });++ await setCell(14, 9, 333);+ await calculateInWorker();++ expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);+ expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();++ await setCell(15, 9, 444);+ await calculateInWorker();++ expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);+ expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);+ expect(worksheet.getCellRaw(15, 9)?.v).toBe(444);+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[15]?.[9]).toBeUndefined();+ });+});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 d7b2e25323..abefb80cb0 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@@ -255,6 +255,59 @@ describe('UpdateFormulaController', () => {expect(executeCommandSpy.mock.calls.filter(([id]) => id === SetFormulaDataMutation.id)).toHaveLength(formulaSyncCallCount);});+ it('should sync array formula data when editing a spill cell without formula data changes', async () => {+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');+ formulaDataModel.setArrayFormulaRange({+ test: {+ sheet1: {+ 5: {+ 5: {+ startRow: 5,+ startColumn: 5,+ endRow: 6,+ endColumn: 6,+ },+ },+ },+ },+ });+ formulaDataModel.setArrayFormulaCellData({+ test: {+ sheet1: {+ 5: {+ 5: { v: 1 },+ 6: { v: 2 },+ },+ 6: {+ 5: { v: 3 },+ 6: { v: 4 },+ },+ },+ },+ });++ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 6: {+ 6: { v: 111 },+ },+ },+ });++ expect(formulaDataModel.getArrayFormulaCellData().test?.sheet1).toEqual({+ 5: {+ 5: { v: 1 },+ 6: { v: 2 },+ },+ 6: {+ 5: { v: 3 },+ },+ });+ expect(executeCommandSpy.mock.calls.some(([id]) => id === SetArrayFormulaDataMutation.id)).toBe(true);+ });+it('should initialize formula data for added sheets and workbooks, then clear removed sheets', async () => {const configService = testBed.injector.get(IConfigService);const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex 9e1b003ebb..fb641cf8ab 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -143,8 +143,24 @@ export class UpdateFormulaController extends Disposable {}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 (Object.keys(newSheetFormulaData).length === 0) {+ if (arrayFormulaCellDataChanged || arrayFormulaRangeChanged) {+ this._commandService.executeCommand(+ SetArrayFormulaDataMutation.id,+ {+ arrayFormulaRange: this._formulaDataModel.getArrayFormulaRange(),+ arrayFormulaCellData: this._formulaDataModel.getArrayFormulaCellData(),+ },+ {+ onlyLocal: true,+ remove: true, // remove array formula range shape+ }+ );+ }+return;}@@ -168,10 +184,6 @@ export class UpdateFormulaController extends Disposable {});- // update formula model- this._formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, cellValue);- this._formulaDataModel.updateArrayFormulaRange(unitId, sheetId, cellValue);-// update image formula datathis._formulaDataModel.updateImageFormulaData(unitId, sheetId, cellValue);diff --git a/packages/sheets/src/controllers/__tests__/formula/array-formula-spill.spec.ts b/packages/sheets/src/controllers/__tests__/formula/array-formula-spill.spec.tsnew file mode 100644index 0000000000..d80d064a86--- /dev/null+++ b/packages/sheets/src/controllers/__tests__/formula/array-formula-spill.spec.ts@@ -0,0 +1,144 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IWorkbookData, Worksheet } from '@univerjs/core';+import type { FFormula } from '@univerjs/engine-formula/facade';+import { ICommandService, LocaleType } from '@univerjs/core';+import {+ ErrorType,+ FormulaDataModel,+ SetArrayFormulaDataMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+} from '@univerjs/engine-formula';+import { beforeEach, describe, expect, it } from 'vitest';+import { SetRangeValuesMutation } from '../../../commands/mutations/set-range-values.mutation';+import { createFunctionTestBed } from './create-function-test-bed';++import '@univerjs/engine-formula/facade';++const unitId = 'test';+const subUnitId = 'sheet1';++function createWorkbookData(): IWorkbookData {+ const sourceCellData: NonNullable<IWorkbookData['sheets'][string]['cellData']> = {};++ for (let row = 2; row <= 9; row++) {+ sourceCellData[row] = {};+ for (let column = 2; column <= 6; column++) {+ sourceCellData[row]![column] = {+ v: row + column,+ t: 2,+ };+ }+ }++ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: [subUnitId],+ styles: {},+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet1',+ rowCount: 30,+ columnCount: 20,+ cellData: {+ ...sourceCellData,+ 12: {+ 6: {+ f: '=C3:G10',+ },+ },+ },+ },+ },+ };+}++describe('Array formula SPILL with real formula calculation', () => {+ let commandService: ICommandService;+ let formulaEngine: FFormula;+ let formulaDataModel: FormulaDataModel;+ let worksheet: Worksheet;++ beforeEach(async () => {+ const testBed = createFunctionTestBed(createWorkbookData());+ commandService = testBed.get(ICommandService);+ formulaEngine = testBed.api.getFormula() as FFormula;+ formulaDataModel = testBed.get(FormulaDataModel);+ worksheet = testBed.sheet.getSheetBySheetId(subUnitId) as Worksheet;++ commandService.registerCommand(SetFormulaCalculationStartMutation);+ commandService.registerCommand(SetFormulaCalculationStopMutation);+ commandService.registerCommand(SetFormulaCalculationResultMutation);+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);+ commandService.registerCommand(SetArrayFormulaDataMutation);+ commandService.registerCommand(SetRangeValuesMutation);++ await calculate();+ });++ async function calculate() {+ commandService.syncExecuteCommand(SetFormulaCalculationStartMutation.id, { forceCalculation: true }, { onlyLocal: true });+ await formulaEngine.onCalculationEnd();+ }++ async function setCell(row: number, column: number, value: number) {+ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId,+ subUnitId,+ cellValue: {+ [row]: {+ [column]: {+ v: value,+ t: 2,+ },+ },+ },+ });+ }++ it('should preserve multiple real blockers inside a spilled array reference formula', async () => {+ expect(formulaDataModel.getArrayFormulaRange()[unitId]?.[subUnitId]?.[12]?.[6]).toEqual({+ startRow: 12,+ startColumn: 6,+ endRow: 19,+ endColumn: 10,+ });++ await setCell(14, 9, 333);+ await calculate();++ expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);+ expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();++ await setCell(15, 9, 444);+ await calculate();++ expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);+ expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);+ expect(worksheet.getCellRaw(15, 9)?.v).toBe(444);+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[15]?.[9]).toBeUndefined();+ });+});