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): progress for multiple calculation (#2342)
Dushusir1169af4c0f4b
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.tsindex 99d48845ee..bd97afc0de 100644--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts@@ -71,7 +71,7 @@ describe('arrayValueObject test', () => {]);});- it('row==0,1,;column=,,2', () => {+ it('row==0,1,;column=,,2,first undefined', () => {expect(originArrayValueObject.slice(undefined, [2, 3])?.toValue()).toStrictEqual([[3], [8], [13]]);});@@ -477,4 +477,10 @@ describe('arrayValueObject test', () => {expect(transpose.getFirstCell().getValue()).toStrictEqual(false);});});+ describe('Test utils', () => {+ it('ArrayValueObject static createByArray', () => {+ const arrayValueObject = ArrayValueObject.createByArray([['cell1', 2, null], ['1', false, true]]);+ expect(arrayValueObject.toValue()).toStrictEqual([['cell1', 2, 0], [1, false, true]]);+ });+ });});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 d30d63dcd5..3251ccc090 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@@ -101,10 +101,35 @@ export function transformToValue(array: Nullable<BaseValueObject>[][] = []) {}export class ArrayValueObject extends BaseValueObject {+ /**+ * Create an array value object based on the string or IArrayValueObject data.+ * @param rawValue+ * @returns+ */static create(rawValue: string | IArrayValueObject) {return new ArrayValueObject(rawValue);}+ /**+ * Create an array value object based on the array data.+ * @param array+ * @returns+ */+ static createByArray(array: Array<Array<number | string | boolean | null>>) {+ const calculateValueList = transformToValueObject(array);+ const arrayValueObjectData: IArrayValueObject = {+ calculateValueList,+ rowCount: array.length,+ columnCount: array[0].length || 0,+ unitId: '',+ sheetId: '',+ row: -1,+ column: -1,+ };++ return new ArrayValueObject(arrayValueObjectData);+ }+private _values: Nullable<BaseValueObject>[][] = [];private _rowCount: number = -1;diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 2c5509b700..70dabcae1b 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -150,3 +150,4 @@ export { IActiveDirtyManagerService } from './services/active-dirty-manager.servexport type { IRangeChange } from './models/formula-data.model';export { handleNumfmtInCell } from './engine/utils/numfmt-kit';+export { AsyncArrayObject } from './engine/reference-object/base-reference-object';diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex 2af4e97ec9..2d356f6301 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -54,6 +54,8 @@ export class TriggerCalculationController extends Disposable {private _formulaCalculationDoneCount: number = 0;+ private _arrayFormulaCalculationDoneCount: number = 0;+constructor(@ICommandService private readonly _commandService: ICommandService,@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,@@ -225,11 +227,14 @@ export class TriggerCalculationController extends Disposable {/*** Assignment operation after formula calculation.*/- const debouncedPushTask = throttle(this._pushTask.bind(this), 300);+ const debouncedFormulaPushTask = throttle(this._pushFormulaTask.bind(this), 300);+ const debouncedArrayFormulaPushTask = throttle(this._pushArrayFormulaTask.bind(this), 300);let startDependencyTimer: NodeJS.Timeout | null = null;- let needStartProgress = false;- let formulaInsertTaskCount = false;- let arrayFormulaInsertTaskCount = false;+ let calculationProcessCount = 0; // Multiple calculations are performed in parallel, but only one progress bar is displayed, and the progress is only closed after the last calculation is completed.+ let formulaCalculationCount = 0;+ let arrayFormulaCalculationCount = 0;+ let needStartFormulaProgress = false;+ let needStartArrayFormulaProgress = false;this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {@@ -249,6 +254,9 @@ export class TriggerCalculationController extends Disposable {} = params.stageInfo;if (stage === FormulaExecuteStageType.START_DEPENDENCY) {+ // Increment the calculation process count and assign a new ID+ calculationProcessCount++;+// Clear any existing timer to prevent duplicate executionsif (startDependencyTimer !== null) {clearTimeout(startDependencyTimer);@@ -258,24 +266,42 @@ export class TriggerCalculationController extends Disposable {// If the total calculation time exceeds 1s, a progress bar is displayed. The first progress shows 5%startDependencyTimer = setTimeout(() => {// Ignore progress deviations, and finally the complete method ensures the correct completion of the progress- this._progressService.insertTaskCount(100);+ const taskCount = (formulaCalculationCount - this._formulaCalculationDoneCount) + (arrayFormulaCalculationCount - this._arrayFormulaCalculationDoneCount) + 100;+ this._progressService.insertTaskCount(taskCount);this._progressService.pushTask({ count: 5 });- needStartProgress = true;-startDependencyTimer = null;}, 1000);} else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING) {- if (!formulaInsertTaskCount && needStartProgress) {- formulaInsertTaskCount = true;- this._progressService.insertTaskCount(totalFormulasToCalculate);+ // Each start of calculation of statistics once+ if (completedFormulasCount === 1 && !needStartFormulaProgress) {+ needStartFormulaProgress = true;+ if (startDependencyTimer) {+ formulaCalculationCount += totalFormulasToCalculate;+ } else {+ this._progressService.insertTaskCount(totalFormulasToCalculate);+ }+ }++ if (startDependencyTimer) {+ this._formulaCalculationDoneCount = completedFormulasCount;+ } else {+ debouncedFormulaPushTask(completedFormulasCount);}- debouncedPushTask(completedFormulasCount);} else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {- if (!arrayFormulaInsertTaskCount && needStartProgress) {- arrayFormulaInsertTaskCount = true;- this._progressService.insertTaskCount(totalArrayFormulasToCalculate);+ if (completedArrayFormulasCount === 1 && !needStartArrayFormulaProgress) {+ needStartArrayFormulaProgress = true;+ if (startDependencyTimer) {+ arrayFormulaCalculationCount += totalArrayFormulasToCalculate;+ } else {+ this._progressService.insertTaskCount(totalArrayFormulasToCalculate);+ }+ }++ if (startDependencyTimer) {+ this._arrayFormulaCalculationDoneCount = completedArrayFormulasCount;+ } else {+ debouncedArrayFormulaPushTask(completedArrayFormulasCount);}- debouncedPushTask(completedArrayFormulasCount);}// if (totalArrayFormulasToCalculate > 0) {@@ -312,22 +338,27 @@ export class TriggerCalculationController extends Disposable {break;}- if (startDependencyTimer) {- // The total calculation time does not exceed 1s, and the progress bar is not displayed.- clearTimeout(startDependencyTimer);- startDependencyTimer = null;- } else {- // Manually hide the progress bar to prevent the progress bar from not being hidden due to pushTask statistical errors- if (state === FormulaExecutedStateType.SUCCESS) {- this._progressService.complete();- } else if (state === FormulaExecutedStateType.STOP_EXECUTION) {- this._progressService.stop();+ // Decrement the calculation process count+ calculationProcessCount--;++ if (calculationProcessCount === 0) {+ if (startDependencyTimer) {+ // The total calculation time does not exceed 1s, and the progress bar is not displayed.+ clearTimeout(startDependencyTimer);+ startDependencyTimer = null;+ } else {+ // Manually hide the progress bar only if no other calculations are in process+ if (state === FormulaExecutedStateType.SUCCESS) {+ this._progressService.complete();+ } else if (state === FormulaExecutedStateType.STOP_EXECUTION) {+ this._progressService.stop();+ }}- formulaInsertTaskCount = false;- arrayFormulaInsertTaskCount = false;- needStartProgress = false;this._formulaCalculationDoneCount = 0;+ this._arrayFormulaCalculationDoneCount = 0;+ needStartFormulaProgress = false;+ needStartArrayFormulaProgress = false;}console.warn(`execution result${result}`);@@ -353,9 +384,27 @@ export class TriggerCalculationController extends Disposable {* Update progress by completed count* @param completedCount*/- private _pushTask(completedCount: number) {+ private _pushFormulaTask(completedCount: number) {+ if (this._progressService.getTaskCount() === 0) {+ return;+ }+const count = completedCount - this._formulaCalculationDoneCount;this._formulaCalculationDoneCount = completedCount;this._progressService.pushTask({ count });}++ /**+ * Update progress by completed count+ * @param completedCount+ */+ private _pushArrayFormulaTask(completedCount: number) {+ if (this._progressService.getTaskCount() === 0) {+ return;+ }++ const count = completedCount - this._arrayFormulaCalculationDoneCount;+ this._arrayFormulaCalculationDoneCount = completedCount;+ this._progressService.pushTask({ count });+ }}diff --git a/packages/ui/src/components/progress-bar/ProgressBar.tsx b/packages/ui/src/components/progress-bar/ProgressBar.tsxindex eeb5fa2d2e..81fbe93b52 100644--- a/packages/ui/src/components/progress-bar/ProgressBar.tsx+++ b/packages/ui/src/components/progress-bar/ProgressBar.tsx@@ -15,7 +15,7 @@*/import { useDependency } from '@wendellhu/redi/react-bindings';-import React, { useEffect, useState } from 'react';+import React, { useEffect, useRef, useState } from 'react';import type { IProgressStep } from '../../services/progress/progress.service';import { IProgressService } from '../../services/progress/progress.service';import styles from './index.module.less';@@ -27,8 +27,7 @@ export interface IProgressBarProps {export function ProgressBar(props: IProgressBarProps) {const { barColor } = props;const progressService = useDependency(IProgressService);-- const [progress, setProgress] = useState(0);+ const progressBarInnerRef = useRef<HTMLDivElement>(null);const [visible, setVisible] = useState(false);useEffect(() => {@@ -37,7 +36,9 @@ export function ProgressBar(props: IProgressBarProps) {// Wait for the progress animation to complete before hiding the progress barsetTimeout(() => {setVisible(isVisible);- setProgress(0);+ if (progressBarInnerRef.current) {+ progressBarInnerRef.current.style.width = '0%';+ }}, 500);} else {setVisible(isVisible);@@ -46,10 +47,13 @@ export function ProgressBar(props: IProgressBarProps) {const progressChange = progressService.progressChange$.subscribe((task: IProgressStep) => {const { step } = task;- setProgress((currentProgress) => {- const newProgress = currentProgress + (1 - currentProgress) * step;- return newProgress;- });++ // UseState asynchronous updates will not be reflected in the UI in time, so we use direct DOM manipulation+ if (progressBarInnerRef.current) {+ const currentProgress = Number.parseFloat(progressBarInnerRef.current.style.width) || 0;+ const newProgress = currentProgress + (100 - currentProgress) * step;+ progressBarInnerRef.current.style.width = `${newProgress}%`;+ }});return () => {@@ -61,9 +65,9 @@ export function ProgressBar(props: IProgressBarProps) {return (<div className={styles.progressBar} style={{ display: visible ? 'block' : 'none' }}><div+ ref={progressBarInnerRef}className={styles.progressBarInner}style={{- width: `${Math.floor(progress * 100)}%`,backgroundColor: barColor,}}/>diff --git a/packages/ui/src/services/progress/progress.service.ts b/packages/ui/src/services/progress/progress.service.tsindex da5ae5340e..ba56d56275 100644--- a/packages/ui/src/services/progress/progress.service.ts+++ b/packages/ui/src/services/progress/progress.service.ts@@ -53,6 +53,11 @@ export interface IProgressService {* Interrupt and hide the progress bar directly*/stop(): void;++ /**+ * Get the total number of tasks+ */+ getTaskCount(): number;}export class ProgressService extends Disposable implements IProgressService, IDisposable {@@ -137,6 +142,10 @@ export class ProgressService extends Disposable implements IProgressService, IDithis._progressVisible$.next(false);}+ getTaskCount(): number {+ return this._taskCount;+ }+private _clear() {this._taskCount = 0;}