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
feat(formula): enable cancellation of ongoing formula calculations (#2661)
Dushusir5d80993cd76a
diff --git a/packages/engine-formula/src/engine/value-object/array-value-object.ts b/packages/engine-formula/src/engine/value-object/array-value-object.tsindex d03718f852..c76aaef037 100644--- a/packages/engine-formula/src/engine/value-object/array-value-object.ts+++ b/packages/engine-formula/src/engine/value-object/array-value-object.ts@@ -272,6 +272,10 @@ export class ArrayValueObject extends BaseValueObject {return v;}+ getValueOrDefault(row: number, column: number) {+ return this.get(row, column) || this._defaultValue;+ }+set(row: number, column: number, value: Nullable<BaseValueObject>) {if (row >= this._rowCount || column >= this._columnCount) {throw new Error('Exceeding array bounds.');@@ -1551,7 +1555,7 @@ export class ArrayValueObject extends BaseValueObject {}for (let r = 0; r < rowCount; r++) {- const currentValue = this._values?.[r]?.[column];+ const currentValue = this.getValueOrDefault(r, column);if (result[r] == null) {result[r] = [];}@@ -1654,6 +1658,7 @@ export class ArrayValueObject extends BaseValueObject {);}+ // eslint-disable-next-line max-lines-per-function, complexityprivate _batchOperatorArray(valueObject: BaseValueObject,batchOperatorType: BatchOperatorType,@@ -1673,8 +1678,6 @@ export class ArrayValueObject extends BaseValueObject {const result: BaseValueObject[][] = [];- const valueObjectList = (valueObject as ArrayValueObject).getArrayValue();-const currentCalculateType = this._checkArrayCalculateType(this as ArrayValueObject);const opCalculateType = this._checkArrayCalculateType(valueObject as ArrayValueObject);@@ -1684,24 +1687,24 @@ export class ArrayValueObject extends BaseValueObject {for (let c = 0; c < columnCount; c++) {let currentValue: Nullable<BaseValueObject>;if (currentCalculateType === ArrayCalculateType.SINGLE) {- currentValue = this._values?.[0]?.[0];+ currentValue = this.getValueOrDefault(0, 0);} else if (currentCalculateType === ArrayCalculateType.ROW) {- currentValue = this._values?.[0]?.[c];+ currentValue = this.getValueOrDefault(0, c);} else if (currentCalculateType === ArrayCalculateType.COLUMN) {- currentValue = this._values?.[r]?.[0];+ currentValue = this.getValueOrDefault(r, 0);} else {- currentValue = this._values?.[r]?.[c];+ currentValue = this.getValueOrDefault(r, c);}let opValue: Nullable<BaseValueObject>;if (opCalculateType === ArrayCalculateType.SINGLE) {- opValue = valueObjectList?.[0]?.[0];+ opValue = (valueObject as ArrayValueObject).getValueOrDefault(0, 0);} else if (opCalculateType === ArrayCalculateType.ROW) {- opValue = valueObjectList?.[0]?.[c];+ opValue = (valueObject as ArrayValueObject).getValueOrDefault(0, c);} else if (opCalculateType === ArrayCalculateType.COLUMN) {- opValue = valueObjectList?.[r]?.[0];+ opValue = (valueObject as ArrayValueObject).getValueOrDefault(r, 0);} else {- opValue = valueObjectList?.[r]?.[c];+ opValue = (valueObject as ArrayValueObject).getValueOrDefault(r, c);}if (currentValue && opValue) {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 22a89b5c52..43ae50a298 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@@ -206,6 +206,55 @@ const TEST_WORKBOOK_DATA_DEMO = (): IWorkbookData => ({f: '=Sheet2!A1:B2',},},+ 18: {+ 0: {+ v: 1,+ },+ 1: {+ f: '=SUM(A19)',+ t: 2,+ v: 1,+ },+ },+ 19: {+ 0: {+ v: 2,+ },+ 1: {+ f: '=SUM(A20)',+ si: 'id1',+ t: 2,+ v: 2,+ },+ },+ 20: {+ 0: {+ v: 3,+ },+ 1: {+ si: 'id1',+ t: 2,+ v: 3,+ },+ },+ 21: {+ 2: {+ f: '=OFFSET(A1,1,1)',+ v: 0,+ t: 2,+ },+ 3: {+ f: '=OFFSET(B1,1,1)',+ si: 'id2',+ v: 1,+ t: 2,+ },+ 4: {+ si: 'id2',+ v: 1,+ t: 2,+ },+ },},name: 'Sheet1',},@@ -363,6 +412,37 @@ describe('Test insert function operation', () => {expect(valuesRedo).toStrictEqual([[{}, { f: '=SUM(A1:B2)' }]]);});+ it('Move range, update reference with si ', async () => {+ const params: IMoveRangeCommandParams = {+ fromRange: {+ startRow: 18,+ startColumn: 1,+ endRow: 20,+ endColumn: 1,+ rangeType: 0,+ },+ toRange: {+ startRow: 18,+ startColumn: 2,+ endRow: 20,+ endColumn: 2,+ rangeType: 0,+ },+ };++ expect(await commandService.executeCommand(MoveRangeCommand.id, params)).toBeTruthy();+ const values = getValues(18, 1, 20, 2);+ expect(values).toStrictEqual([[{}, { f: '=SUM(A19)', t: 2, v: 1 }], [{}, { f: '=SUM(A20)', si: 'id1', t: 2, v: 2 }], [{}, { si: 'id1', t: 2, v: 3 }]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo = getValues(18, 1, 20, 2);+ expect(valuesUndo).toStrictEqual([[{ f: '=SUM(A19)', t: 2, v: 1 }, {}], [{ f: '=SUM(A20)', si: 'id1', t: 2, v: 2 }, {}], [{ si: 'id1', t: 2, v: 3 }, {}]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(18, 1, 20, 2);+ expect(valuesRedo).toStrictEqual([[{}, { f: '=SUM(A19)', t: 2, v: 1 }], [{}, { f: '=SUM(A20)', si: 'id1', t: 2, v: 2 }], [{}, { si: 'id1', t: 2, v: 3 }]]);+ });+it('Move rows, update reference', async () => {const selectionManager = get(SheetsSelectionsService);@@ -848,6 +928,70 @@ describe('Test insert function operation', () => {expect(valuesRedo3).toStrictEqual([[{ f: '=SUM(A8)' }, { f: '=SUM(#REF!)' }, { f: '=SUM(B8)' }, {}]]);});+ it('Remove column, update reference and position, contains #REF', async () => {+ const params: IRemoveRowColCommandParams = {+ range: {+ startColumn: 0,+ endColumn: 1,+ startRow: 0,+ endRow: 2,+ },+ };++ expect(await commandService.executeCommand(RemoveColCommand.id, params)).toBeTruthy();+ const values = getValues(21, 0, 21, 4);++ // Ignore the calculation results and only verify the offset information+ expect(values).toStrictEqual([[{+ f: '=OFFSET(#REF!,1,1)',+ v: 0,+ t: 2,+ }, {+ f: '=OFFSET(#REF!,1,1)',+ si: 'id2',+ v: 1,+ t: 2,+ }, {+ f: '=OFFSET(A1,1,1)',+ v: 1,+ t: 2,+ }, {}, {}]]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ const valuesUndo = getValues(21, 0, 21, 4);+ expect(valuesUndo).toStrictEqual([[{ }, { }, {+ f: '=OFFSET(A1,1,1)',+ v: 0,+ t: 2,+ }, {+ f: '=OFFSET(B1,1,1)',+ si: 'id2',+ v: 1,+ t: 2,+ }, {+ si: 'id2',+ v: 1,+ t: 2,+ }]]);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ const valuesRedo = getValues(21, 0, 21, 4);+ expect(valuesRedo).toStrictEqual([[{+ f: '=OFFSET(#REF!,1,1)',+ v: 0,+ t: 2,+ }, {+ f: '=OFFSET(#REF!,1,1)',+ si: 'id2',+ v: 1,+ t: 2,+ }, {+ f: '=OFFSET(A1,1,1)',+ v: 1,+ t: 2,+ }, {}, {}]]);+ });+it('Remove column, removed column contains formula', async () => {const params: IRemoveRowColCommandParams = {range: {diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex 106d717a5d..f70936e2b6 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -87,6 +87,8 @@ export class TriggerCalculationController extends Disposable {this._initialExecuteFormulaProcessListener();this._initialExecuteFormula();++ this._initialProgressBar();}private _commandExecutedListener() {@@ -448,6 +450,17 @@ export class TriggerCalculationController extends Disposable {);}+ /**+ * The user manually stops the progress bar+ */+ private _initialProgressBar() {+ this.disposeWithMe(this._progressService.progressVisible$.subscribe((isVisible) => {+ if (!isVisible) {+ this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});+ }+ }));+ }+/*** Update progress by completed count* @param completedCountdiff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex ab621b404d..25fe291ab3 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -108,7 +108,6 @@ import { Inject, Injector } from '@wendellhu/redi';import { filter, map, merge } from 'rxjs';import { IEditorService } from '@univerjs/ui';-import type { IRefRangeWithPosition } from './utils/offset-formula-data';import { removeFormulaData } from './utils/offset-formula-data';import { getFormulaReferenceMoveUndoRedo } from './utils/ref-range-formula';@@ -688,23 +687,21 @@ export class UpdateFormulaController extends Disposable {};}+ // eslint-disable-next-line max-lines-per-functionprivate _getFormulaReferenceMoveInfo(formulaData: IFormulaData,unitSheetNameMap: IUnitSheetNameMap,formulaReferenceMoveParam: IFormulaReferenceMoveParam) {- if (!Tools.isDefine(formulaData)) return { newFormulaData: {}, oldFormulaData: {}, refRanges: [] };+ if (!Tools.isDefine(formulaData)) return { newFormulaData: {}, oldFormulaData: {} };const formulaDataKeys = Object.keys(formulaData);- if (formulaDataKeys.length === 0) return { newFormulaData: {}, oldFormulaData: {}, refRanges: [] };+ if (formulaDataKeys.length === 0) return { newFormulaData: {}, oldFormulaData: {} };const oldFormulaData: IFormulaData = {};const newFormulaData: IFormulaData = {};- // Return all reference ranges. If the operation affects the reference range, you need to clear arrayFormulaRange and arrayFormulaCellData.- const refRanges: IRefRangeWithPosition[] = [];-for (const unitId of formulaDataKeys) {const sheetData = formulaData[unitId];@@ -725,9 +722,9 @@ export class UpdateFormulaController extends Disposable {for (const sheetId of sheetDataKeys) {const matrixData = new ObjectMatrix(sheetData[sheetId] || {});- const oldFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();const newFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();+ // eslint-disable-next-line max-lines-per-function, complexitymatrixData.forValue((row, column, formulaDataItem) => {if (!formulaDataItem) return true;@@ -752,9 +749,6 @@ export class UpdateFormulaController extends Disposable {const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;- // store ref range- refRanges.push({ row, column, range });-const mapUnitId =sequenceUnitId == null || sequenceUnitId.length === 0 ? unitId : sequenceUnitId;@@ -849,32 +843,26 @@ export class UpdateFormulaController extends Disposable {const newSequenceNodes = this._updateRefOffset(sequenceNodes, refChangeIds, x, y);- oldFormulaDataItem.setValue(row, column, {- f: formulaString,- x,- y,- si,- });-- newFormulaDataItem.setValue(row, column, {- f: `=${generateStringWithSequence(newSequenceNodes)}`,- x,- y,- si,- });+ // The formula f that originally depended on si has been actually calculated and does not require si and x,y.+ if ((x !== undefined && (x > 0)) || (y !== undefined && (y > 0))) {+ newFormulaDataItem.setValue(row, column, {+ f: `=${generateStringWithSequence(newSequenceNodes)}`,+ });+ } else {+ newFormulaDataItem.setValue(row, column, {+ f: `=${generateStringWithSequence(newSequenceNodes)}`,+ si,+ });+ }});- if (oldFormulaData[unitId]) {- oldFormulaData[unitId]![sheetId] = oldFormulaDataItem.getData();- }-if (newFormulaData[unitId]) {newFormulaData[unitId]![sheetId] = newFormulaDataItem.getData();}}}- return { newFormulaData, oldFormulaData, refRanges };+ return { newFormulaData };}private _getNewRangeByMoveParam(diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.tsindex bca2de296e..19783e120d 100644--- a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.ts+++ b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-formula.spec.ts@@ -17,7 +17,7 @@import { describe, expect, it } from 'vitest';import type { IFormulaDataItem } from '@univerjs/engine-formula';-import { formulaDataItemToCellData, formulaDataItemToCellDataFormula, isFormulaDataItem } from '../ref-range-formula';+import { formulaDataItemToCellData, isFormulaDataItem } from '../ref-range-formula';describe('Ref range formula test', () => {describe('Util function', () => {@@ -30,6 +30,7 @@ describe('Ref range formula test', () => {expect(result).toStrictEqual({f: '=SUM(1)',+ si: null,});formulaDataItem = {@@ -41,6 +42,7 @@ describe('Ref range formula test', () => {expect(result).toStrictEqual({si: 'id1',+ f: null,});formulaDataItem = {@@ -80,6 +82,7 @@ describe('Ref range formula test', () => {expect(result).toStrictEqual({si: 'id1',+ f: null,});formulaDataItem = {@@ -94,77 +97,6 @@ describe('Ref range formula test', () => {expect(result).toStrictEqual({ f: null, si: null });});- it('Function formulaDataItemToCellDataFormula', () => {- let formulaDataItem: IFormulaDataItem = {- f: '=SUM(1)',- };-- let result = formulaDataItemToCellDataFormula(formulaDataItem);-- expect(result).toStrictEqual({- f: '=SUM(1)',- });-- formulaDataItem = {- f: '',- si: 'id1',- };-- result = formulaDataItemToCellDataFormula(formulaDataItem);-- expect(result).toStrictEqual({- si: 'id1',- });-- formulaDataItem = {- f: '=SUM(1)',- si: 'id1',- };-- result = formulaDataItemToCellDataFormula(formulaDataItem);-- expect(result).toStrictEqual({- f: '=SUM(1)',- });-- formulaDataItem = {- f: '=SUM(1)',- si: 'id1',- x: 0,- y: 0,- };-- result = formulaDataItemToCellDataFormula(formulaDataItem);-- expect(result).toStrictEqual({- f: '=SUM(1)',- });-- formulaDataItem = {- f: '=SUM(1)',- si: 'id1',- x: 0,- y: 1,- };-- result = formulaDataItemToCellDataFormula(formulaDataItem);-- expect(result).toStrictEqual({- f: '=SUM(1)',- });-- formulaDataItem = {- f: '',- si: '',- x: 0,- y: 1,- };-- result = formulaDataItemToCellDataFormula(formulaDataItem);-- expect(result).toStrictEqual({ f: null, si: null });- });-it('isFormulaDataItem', () => {expect(isFormulaDataItem({ f: '=SUM(1)' })).toBeTruthy();expect(isFormulaDataItem({ f: '' })).toBeFalsy();diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.tsindex c0c50a232b..f73785bc87 100644--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts@@ -457,7 +457,7 @@ function getRedoFormulaData(rangeList: IRangeChange[], oldFormulaMatrix: ObjectMconst newFormula = newFormulaMatrix.getValue(oldStartRow, oldStartColumn) || oldFormulaMatrix.getValue(oldStartRow, oldStartColumn);// Use the formula result value to update the data to ensure accuracy, otherwise the new formula cannot be inferred from #REF- const newValue = formulaDataItemToCellDataFormula(newFormula);+ const newValue = formulaDataItemToCellData(newFormula);redoFormulaData.setValue(oldStartRow, oldStartColumn, { f: null, si: null });@@ -538,48 +538,12 @@ export function formulaDataItemToCellData(formulaDataItem: Nullable<IFormulaDatacellData.f = f;}- return cellData;-}--/**- * Transfer the formulaDataItem to the cellData, contains formula- * ┌────────────────────────────────┬─────────────────┐- * │ IFormulaDataItem │ ICellData │- * ├──────────────────┬─────┬───┬───┼───────────┬─────┤- * │ f │ si │ x │ y │ f │ si │- * ├──────────────────┼─────┼───┼───┼───────────┼─────┤- * │ =SUM(1) │ │ │ │ =SUM(1) │ │- * │ │ id1 │ │ │ │ id1 │- * │ =SUM(1) │ id1 │ │ │ =SUM(1) │ │- * │ =SUM(1) │ id1 │ 0 │ 0 │ =SUM(1) │ │- * │ =SUM(1) │ id1 │ 0 │ 1 │ =SUM(1) │ │- * └──────────────────┴─────┴───┴───┴───────────┴─────┘- *- * The fifth case: The value f of the formula is already the result value. If the formula content of si contains #REF, it cannot be obtained from the formula offset of si, and the result value must be stored directly- */-export function formulaDataItemToCellDataFormula(formulaDataItem: Nullable<IFormulaDataItem>): Nullable<ICellData> {- if (formulaDataItem == null) {- return;+ if (cellData.f === undefined) {+ cellData.f = null;}- const { f, si } = formulaDataItem;- const checkFormulaString = isFormulaString(f);- const checkFormulaId = isFormulaId(si);- if (!checkFormulaString && !checkFormulaId) {- return {- f: null,- si: null,- };- }-- const cellData: ICellData = {};-- if (checkFormulaString) {- cellData.f = f;- }-- if (checkFormulaId && !checkFormulaString) {- cellData.si = si;+ if (cellData.si === undefined) {+ cellData.si = null;}return cellData;diff --git a/packages/ui/src/components/progress-bar/ProgressBar.tsx b/packages/ui/src/components/progress-bar/ProgressBar.tsxindex 81fbe93b52..7e5ffcf91f 100644--- a/packages/ui/src/components/progress-bar/ProgressBar.tsx+++ b/packages/ui/src/components/progress-bar/ProgressBar.tsx@@ -16,6 +16,7 @@import { useDependency } from '@wendellhu/redi/react-bindings';import React, { useEffect, useRef, useState } from 'react';+import { CloseSingle } from '@univerjs/icons';import type { IProgressStep } from '../../services/progress/progress.service';import { IProgressService } from '../../services/progress/progress.service';import styles from './index.module.less';@@ -62,15 +63,23 @@ export function ProgressBar(props: IProgressBarProps) {};}, []);+ function handleClose() {+ progressService.stop();+ };+return (- <div className={styles.progressBar} style={{ display: visible ? 'block' : 'none' }}>- <div- ref={progressBarInnerRef}- className={styles.progressBarInner}- style={{- backgroundColor: barColor,- }}- />+ <div className={styles.progressBarContainer} style={{ display: visible ? 'flex' : 'none' }}>+ <div className={styles.progressBar}>+ <div+ ref={progressBarInnerRef}+ className={styles.progressBarInner}+ style={{+ backgroundColor: barColor,+ }}+ />+ </div>+ <div className={styles.progressBarCloseButton} onClick={handleClose}><CloseSingle /></div>+</div>);};diff --git a/packages/ui/src/components/progress-bar/index.module.less b/packages/ui/src/components/progress-bar/index.module.lessindex 0f4f903166..f3c4947dcb 100644--- a/packages/ui/src/components/progress-bar/index.module.less+++ b/packages/ui/src/components/progress-bar/index.module.less@@ -1,15 +1,38 @@@height: 4px;-.progress-bar {- margin: 12px 8px 0 8px;+.progress-bar {width: 160px;height: @height;background-color: rgb(var(--border-color));border-radius: var(--border-radius-lg);+ margin-right: 8px;++ &-container {+ display: flex;+ align-items: center;+ margin: 0 8px 0 8px;+ }&-inner {height: @height;border-radius: var(--border-radius-lg);transition: width 0.5s;}++ &-close-button {+ background: none;+ border: none;+ font-size: 12px;+ color: rgb(var(--text-color));+ cursor: pointer;+ padding: 0;+ margin: 0;+ line-height: 1;+ display: flex;+ align-items: center;++ &:hover {+ color: rgb(var(--text-color-secondary));+ }+ }}