Skip to content

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.

feat(formula): formula calculation progress (#1985)

Dushusirad1d6325122d
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 4e5436cd9c..de13275a71 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -72,7 +72,7 @@ univer.registerPlugin(UniverSheetsNumfmtPlugin);
univer.registerPlugin(DebuggerPlugin);
univer.registerPlugin(UniverSheetsZenEditorPlugin);
univer.registerPlugin(UniverFormulaEnginePlugin, {
- notExecuteFormula: false,
+ notExecuteFormula: true,
});
univer.registerPlugin(UniverSheetsFormulaPlugin);
univer.registerPlugin(UniverRPCMainThreadPlugin, {
diff --git a/packages/sheets-formula/src/controllers/array-formula-display.controller.ts b/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
index 31d0f02d78..97667c093a 100644
--- a/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
+++ b/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
@@ -68,17 +68,11 @@ export class ArrayFormulaDisplayController extends Disposable {
handler: (cell, location, next) => {
const { unitId, subUnitId, row, col } = location;
const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();
- const arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();
const cellData = arrayFormulaCellData?.[unitId]?.[subUnitId]?.[row]?.[col];
- const cellRange = arrayFormulaRange?.[unitId]?.[subUnitId]?.[row]?.[col];
if (cellData == null) {
return next(cell);
}
- if (cellRange != null && cellRange.startRow === row && cellRange.startColumn === col) {
- return next(cell);
- }
-
// const numfmtItemMap = this._formulaDataModel.getNumfmtItemMap();
// const numfmtItem = numfmtItemMap[unitId]?.[subUnitId]?.[row]?.[col];
@@ -110,10 +104,11 @@ export class ArrayFormulaDisplayController extends Disposable {
// };
// }
+ // The cell in the upper left corner of the array formula also triggers the default value determination
if (cellData.v == null && cellData.t == null) {
return next({ ...cell,
...cellData,
- v: 0,
+ v: 0, // Default value for empty cell
t: CellValueType.NUMBER,
});
}
diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
index 5d9b4af700..4be2f6433e 100644
--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
@@ -213,7 +213,7 @@ export class FormulaEditorShowController extends Disposable {
if (cell && cell.v == null && cell.t == null && cell.f != null) {
return next({ ...cell,
- v: 0,
+ v: null, // Default value for empty cell, information displayed before calculation
t: CellValueType.NUMBER,
});
}
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 991e6227f8..bf8911d2dc 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -15,18 +15,21 @@
*/
import type { ICommandInfo, IUnitRange } from '@univerjs/core';
-import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Disposable, ICommandService, LifecycleStages, OnLifecycle, throttle } from '@univerjs/core';
import type {
IDirtyUnitFeatureMap,
IDirtyUnitOtherFormulaMap,
IDirtyUnitSheetNameMap,
- ISetFormulaCalculationNotificationMutation } from '@univerjs/engine-formula';
+ ISetFormulaCalculationNotificationMutation,
+} from '@univerjs/engine-formula';
import {
FormulaDataModel,
FormulaExecutedStateType,
+ FormulaExecuteStageType,
IActiveDirtyManagerService,
SetFormulaCalculationNotificationMutation,
- SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+ SetFormulaCalculationStartMutation,
+} from '@univerjs/engine-formula';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import {
ClearSelectionFormatCommand,
@@ -35,6 +38,7 @@ import {
SetRangeValuesMutation,
SetStyleCommand,
} from '@univerjs/sheets';
+import { IProgressService } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
@@ -48,11 +52,14 @@ export class TriggerCalculationController extends Disposable {
private _startExecutionTime: number = 0;
+ private _formulaCalculationDoneCount: number = 0;
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,
@Inject(INumfmtService) private readonly _numfmtService: INumfmtService,
- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(IProgressService) private readonly _progressService: IProgressService
) {
super();
@@ -208,7 +215,7 @@ export class TriggerCalculationController extends Disposable {
}
Object.keys(dirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId]).forEach((featureIdOrFormulaId) => {
allDirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId][featureIdOrFormulaId] =
- dirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId]![featureIdOrFormulaId] || false;
+ dirtyUnitFeatureOrOtherFormulaMap[unitId]![sheetId]![featureIdOrFormulaId] || false;
});
});
});
@@ -218,6 +225,10 @@ export class TriggerCalculationController extends Disposable {
/**
* Assignment operation after formula calculation.
*/
+ const debouncedPushTask = throttle(this._pushTask.bind(this), 300);
+ let startDependencyTimer: NodeJS.Timeout | null;
+ let formulaInsertTaskCount = false;
+ let arrayFormulaInsertTaskCount = false;
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
@@ -235,15 +246,40 @@ export class TriggerCalculationController extends Disposable {
completedArrayFormulasCount,
stage,
} = params.stageInfo;
- if (totalArrayFormulasToCalculate > 0) {
- // console.log(
- // `Stage ${stage} Array formula.There are ${totalArrayFormulasToCalculate} functions to be executed, ${completedArrayFormulasCount} complete.`
- // );
- } else {
- // console.log(
- // `Stage ${stage} .There are ${totalFormulasToCalculate} functions to be executed, ${completedFormulasCount} complete.`
- // );
+
+ if (stage === FormulaExecuteStageType.START_DEPENDENCY) {
+ // 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);
+ this._progressService.pushTask({ count: 5 });
+
+ startDependencyTimer = null;
+ }, 1000);
+ } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING) {
+ if (!formulaInsertTaskCount && !startDependencyTimer) {
+ formulaInsertTaskCount = true;
+ this._progressService.insertTaskCount(totalFormulasToCalculate);
+ }
+ debouncedPushTask(completedFormulasCount);
+ } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {
+ if (!arrayFormulaInsertTaskCount && !startDependencyTimer) {
+ arrayFormulaInsertTaskCount = true;
+ this._progressService.insertTaskCount(totalArrayFormulasToCalculate);
+ }
+ debouncedPushTask(completedArrayFormulasCount);
}
+
+
+ // if (totalArrayFormulasToCalculate > 0) {
+ // console.warn(
+ // `Stage ${stage} Array formula.There are ${totalArrayFormulasToCalculate} functions to be executed, ${completedArrayFormulasCount} complete.`
+ // );
+ // } else {
+ // console.warn(
+ // `Stage ${stage} .There are ${totalFormulasToCalculate} functions to be executed, ${completedFormulasCount} complete.`
+ // );
+ // }
} else {
const state = params.functionsExecutedState;
let result = '';
@@ -259,8 +295,7 @@ export class TriggerCalculationController extends Disposable {
this._executingCommandQueue = [];
break;
case FormulaExecutedStateType.SUCCESS:
- result = `Formula calculation succeeded, Total time consumed: ${
- performance.now() - this._startExecutionTime
+ result = `Formula calculation succeeded, Total time consumed: ${performance.now() - this._startExecutionTime
} ms`;
this._executingCommandQueue = [];
break;
@@ -269,6 +304,25 @@ export class TriggerCalculationController extends Disposable {
this._executingCommandQueue = [];
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();
+ }
+
+ formulaInsertTaskCount = false;
+ arrayFormulaInsertTaskCount = false;
+ this._formulaCalculationDoneCount = 0;
+ }
+
+
console.warn(`execution result${result}`);
}
})
@@ -287,4 +341,14 @@ export class TriggerCalculationController extends Disposable {
}
);
}
+
+ /**
+ * Update progress by completed count
+ * @param completedCount
+ */
+ private _pushTask(completedCount: number) {
+ const count = completedCount - this._formulaCalculationDoneCount;
+ this._formulaCalculationDoneCount = completedCount;
+ this._progressService.pushTask({ count });
+ }
}
diff --git a/packages/sheets-ui/src/views/defined-name/index.module.less b/packages/sheets-ui/src/views/defined-name/index.module.less
index 32a1ad5b38..838e0bef76 100644
--- a/packages/sheets-ui/src/views/defined-name/index.module.less
+++ b/packages/sheets-ui/src/views/defined-name/index.module.less
@@ -9,6 +9,10 @@
height: 100%;
+ width: 100px;
+
+ box-sizing: border-box;
+
&-drop-down {
display: flex;
align-items: center;
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 89ae211348..2e3c1ce483 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -18,7 +18,7 @@ import type { Nullable } from '@univerjs/core';
import { DEFAULT_EMPTY_DOCUMENT_VALUE, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { CheckMarkSingle, CloseSingle, DropdownSingle, FxSingle } from '@univerjs/icons';
-import { KeyCode, TextEditor } from '@univerjs/ui';
+import { KeyCode, ProgressBar, TextEditor } from '@univerjs/ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import clsx from 'clsx';
import React, { useEffect, useState } from 'react';
@@ -175,6 +175,8 @@ export function FormulaBar() {
</div>
</div>
</div>
+
+ <ProgressBar />
</div>
);
}
diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
index 2a842557eb..f27417334e 100644
--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
@@ -48,7 +48,9 @@ export function RenderSheetHeader() {
if (!workbook) return null;
return (
- <FormulaBar />
+ <>
+ <FormulaBar />
+ </>
);
}
diff --git a/packages/ui/src/components/progress-bar/ProgressBar.tsx b/packages/ui/src/components/progress-bar/ProgressBar.tsx
new file mode 100644
index 0000000000..466507b41d
--- /dev/null
+++ b/packages/ui/src/components/progress-bar/ProgressBar.tsx
@@ -0,0 +1,69 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ThemeService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import type { IProgressStep } from '../../services/progress/progress.service';
+import { IProgressService } from '../../services/progress/progress.service';
+import styles from './index.module.less';
+
+export function ProgressBar() {
+ const themeService = useDependency(ThemeService);
+ const progressService = useDependency(IProgressService);
+ const barColor = themeService.getCurrentTheme().primaryColor;
+ const [progress, setProgress] = useState(0);
+ const [visible, setVisible] = useState(false);
+
+ useEffect(() => {
+ const progressVisible = progressService.progressVisible$.subscribe((isVisible) => {
+ if (!isVisible) {
+ // Wait for the progress animation to complete before hiding the progress bar
+ setTimeout(() => {
+ setVisible(isVisible);
+ setProgress(0);
+ }, 500);
+ } else {
+ setVisible(isVisible);
+ }
+ });
+
+ const progressChange = progressService.progressChange$.subscribe((task: IProgressStep) => {
+ const { step } = task;
+ setProgress((currentProgress) => {
+ const newProgress = currentProgress + (1 - currentProgress) * step;
+ return newProgress;
+ });
+ });
+
+ return () => {
+ progressVisible.unsubscribe();
+ progressChange.unsubscribe();
+ };
+ }, []);
+
+ return (
+ <div className={styles.progressBar} style={{ display: visible ? 'block' : 'none' }}>
+ <div
+ className={styles.progressBarInner}
+ style={{
+ width: `${Math.floor(progress * 100)}%`,
+ backgroundColor: barColor,
+ }}
+ />
+ </div>
+ );
+};
diff --git a/packages/ui/src/components/progress-bar/index.module.less b/packages/ui/src/components/progress-bar/index.module.less
new file mode 100644
index 0000000000..0f4f903166
--- /dev/null
+++ b/packages/ui/src/components/progress-bar/index.module.less
@@ -0,0 +1,15 @@
+@height: 4px;
+.progress-bar {
+ margin: 12px 8px 0 8px;
+
+ width: 160px;
+ height: @height;
+ background-color: rgb(var(--border-color));
+ border-radius: var(--border-radius-lg);
+
+ &-inner {
+ height: @height;
+ border-radius: var(--border-radius-lg);
+ transition: width 0.5s;
+ }
+}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 1e8f704ee4..e1ae25f9bd 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -84,3 +84,5 @@ export { IRangeSelectorService } from './services/range-selector/range-selector.
export { DesktopLocalStorageService } from './services/local-storage/local-storage.service';
export { useActiveWorkbook, useActiveWorksheet } from './views/hooks/active';
export { CanvasPopupService, ICanvasPopupService } from './services/popup/canvas-popup.service';
+export { ProgressBar } from './components/progress-bar/ProgressBar';
+export { IProgressService } from './services/progress/progress.service';
diff --git a/packages/ui/src/services/__tests__/progress.service.spec.ts b/packages/ui/src/services/__tests__/progress.service.spec.ts
new file mode 100644
index 0000000000..0c4765d514
--- /dev/null
+++ b/packages/ui/src/services/__tests__/progress.service.spec.ts
@@ -0,0 +1,172 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { act, renderHook } from '@testing-library/react-hooks';
+import type { IProgressStep } from '../progress/progress.service';
+import { ProgressService } from '../progress/progress.service';
+
+describe('ProgressService', () => {
+ let service: ProgressService;
+
+ beforeEach(() => {
+ service = new ProgressService();
+ });
+
+ it('initializes with correct default values', () => {
+ expect(service).toBeTruthy();
+
+ const { result } = renderHook(() => ({
+ progressChange$: service.progressChange$,
+ progressVisible$: service.progressVisible$,
+ }));
+
+ expect(result.current.progressChange$).toBeDefined();
+ expect(result.current.progressVisible$).toBeDefined();
+ });
+
+ it('pushTask should emit step change and handle task count', () => {
+ const { result } = renderHook(() => ({
+ progressChange$: service.progressChange$,
+ progressVisible$: service.progressVisible$,
+ }));
+
+ const steps: IProgressStep[] = [];
+ result.current.progressChange$.subscribe((step) => steps.push(step));
+ const visibilities: boolean[] = [];
+ result.current.progressVisible$.subscribe((visible) => visibilities.push(visible));
+
+ act(() => {
+ service.insertTaskCount(10);
+ service.pushTask({ count: 5 });
+ });
+ expect(steps).toEqual([{ step: 0.5 }]);
+
+ act(() => {
+ service.pushTask({ count: 5 });
+ });
+ expect(steps).toEqual([{ step: 0.5 }, { step: 1 }]);
+ expect(visibilities).toEqual([true, false]);
+ });
+
+ it('pushTask should emit step change and handle task count, exceeded the total number of tasks', () => {
+ const { result } = renderHook(() => ({
+ progressChange$: service.progressChange$,
+ progressVisible$: service.progressVisible$,
+ }));
+
+ const steps: IProgressStep[] = [];
+ result.current.progressChange$.subscribe((step) => steps.push(step));
+ const visibilities: boolean[] = [];
+ result.current.progressVisible$.subscribe((visible) => visibilities.push(visible));
+
+ act(() => {
+ service.insertTaskCount(10);
+ service.pushTask({ count: 5 });
+ });
+ expect(steps).toEqual([{ step: 0.5 }]);
+
+ act(() => {
+ service.pushTask({ count: 10 });
+ });
+ expect(steps).toEqual([{ step: 0.5 }, { step: 1 }]);
+ expect(visibilities).toEqual([true, false]);
+ });
+
+ it('insertTaskCount should make progress visible if task count was zero', () => {
+ const { result } = renderHook(() => ({
+ progressVisible$: service.progressVisible$,
+ }));
+
+ const visibilities: boolean[] = [];
+ result.current.progressVisible$.subscribe((visible) => visibilities.push(visible));
+
+ act(() => {
+ service.insertTaskCount(1);
+ });
+ expect(visibilities).toEqual([true]);
+ });
+
+ it('complete should set progress to 100% and hide the progress bar', () => {
+ const { result } = renderHook(() => ({
+ progressChange$: service.progressChange$,
+ progressVisible$: service.progressVisible$,
+ }));
+
+ const steps: IProgressStep[] = [];
+ result.current.progressChange$.subscribe((step) => steps.push(step));
+ const visibilities: boolean[] = [];
+ result.current.progressVisible$.subscribe((visible) => visibilities.push(visible));
+
+ act(() => {
+ service.insertTaskCount(10);
+ service.complete();
+ });
+ expect(steps).toEqual([{ step: 1 }]);
+ expect(visibilities).toEqual([true, false]);
+ });
+
+ it('stop should hide the progress bar without completing', () => {
+ const { result } = renderHook(() => ({
+ progressVisible$: service.progressVisible$,
+ }));
+
+ const visibilities: boolean[] = [];
+ result.current.progressVisible$.subscribe((visible) => visibilities.push(visible));
+
+ act(() => {
+ service.insertTaskCount(10);
+ service.stop();
+ });
+ expect(visibilities).toEqual([true, false]);
+ });
+
+ it('dispose should complete all observables', () => {
+ const { result } = renderHook(() => ({
+ progressChange$: service.progressChange$,
+ progressVisible$: service.progressVisible$,
+ }));
+
+ let changeCompleted = false;
+ let visibleCompleted = false;
+
+ const changeSubscription = result.current.progressChange$.subscribe({
+ next: (step) => {},
+ complete: () => {
+ changeCompleted = true;
+ },
+ });
+
+ const visibleSubscription = result.current.progressVisible$.subscribe({
+ next: (visible) => {},
+ complete: () => {
+ visibleCompleted = true;
+ },
+ });
+
+ act(() => {
+ service.dispose();
+ });
+
+ // Assert that both subscriptions have been completed
+ expect(changeCompleted).toBe(true);
+ expect(visibleCompleted).toBe(true);
+
+ // Cleanup subscriptions
+ changeSubscription.unsubscribe();
+ visibleSubscription.unsubscribe();
+ });
+});
diff --git a/packages/ui/src/services/progress/progress.service.ts b/packages/ui/src/services/progress/progress.service.ts
new file mode 100644
index 0000000000..da5ae5340e
--- /dev/null
+++ b/packages/ui/src/services/progress/progress.service.ts
@@ -0,0 +1,147 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Disposable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import { Subject } from 'rxjs';
+
+export interface IProgressCount {
+ count: number;
+}
+
+export interface IProgressStep {
+ step: number;
+}
+
+export interface IProgressService {
+ progressChange$: Observable<IProgressStep>;
+ progressVisible$: Observable<boolean>;
+
+ /**
+ * Append subtask quantity during loading, when the number of added subtasks reaches the total number of tasks, the loading is completed.
+ * @param task
+ */
+ pushTask(task: IProgressCount): void;
+
+ /**
+ * Insert a new number of tasks, do not set the start loading mechanism, when insertTaskCount finds that the original number of tasks is 0, it starts loading
+ * @param count
+ */
+ insertTaskCount(count: number): void;
+
+ /**
+ * Complete loading, hide the progress bar after automatically progressing to 100%
+ */
+ complete(): void;
+
+ /**
+ * Interrupt and hide the progress bar directly
+ */
+ stop(): void;
+}
+
+export class ProgressService extends Disposable implements IProgressService, IDisposable {
+ /**
+ * The total number of tasks remaining
+ */
+ private _taskCount: number = 0;
+
+ private readonly _progressChange$ = new Subject<IProgressStep>();
+
+ private readonly _progressVisible$ = new Subject<boolean>();
+
+ readonly progressChange$ = this._progressChange$.asObservable();
+
+ readonly progressVisible$ = this._progressVisible$.asObservable();
+
+ override dispose(): void {
+ super.dispose();
+ this._clear();
+ this._progressChange$.complete();
+ this._progressVisible$.complete();
+ }
+
+ pushTask(task: IProgressCount) {
+ if (this._taskCount === 0) {
+ return;
+ }
+
+ const { count } = task;
+ if (count <= 0) {
+ return;
+ }
+
+ const step = Math.min(1, count / this._taskCount);
+
+ this._progressChange$.next({
+ step,
+ });
+
+ this._taskCount -= count;
+
+ if (this._taskCount < 0) {
+ this._taskCount = 0;
+ }
+
+ if (this._taskCount === 0) {
+ this._progressVisible$.next(false);
+ }
+ }
+
+ insertTaskCount(count: number) {
+ if (count <= 0) {
+ return;
+ }
+
+ if (this._taskCount === 0) {
+ this._progressVisible$.next(true);
+ }
+
+ this._taskCount += count;
+ }
+
+ complete() {
+ if (this._taskCount === 0) {
+ return;
+ }
+
+ this._progressChange$.next({
+ step: 1,
+ });
+
+ this._clear();
+ this._progressVisible$.next(false);
+ }
+
+ stop(): void {
+ if (this._taskCount === 0) {
+ return;
+ }
+
+ this._clear();
+ this._progressVisible$.next(false);
+ }
+
+ private _clear() {
+ this._taskCount = 0;
+ }
+}
+
+export const IProgressService = createIdentifier<IProgressService>(
+ 'univer.progress.service'
+);
diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.ts
index 41f615b6e2..73b901d864 100644
--- a/packages/ui/src/ui-plugin.ts
+++ b/packages/ui/src/ui-plugin.ts
@@ -54,6 +54,7 @@ import { DesktopZenZoneService } from './services/zen-zone/desktop-zen-zone.serv
import { IZenZoneService } from './services/zen-zone/zen-zone.service';
import { EditorService, IEditorService } from './services/editor/editor.service';
import { IRangeSelectorService, RangeSelectorService } from './services/range-selector/range-selector.service';
+import { IProgressService, ProgressService } from './services/progress/progress.service';
const PLUGIN_NAME = 'ui';
@@ -118,7 +119,7 @@ export class UniverUIPlugin extends Plugin {
[IEditorService, { useClass: EditorService }],
[IRangeSelectorService, { useClass: RangeSelectorService }],
[ICanvasPopupService, { useClass: CanvasPopupService }],
-
+ [IProgressService, { useClass: ProgressService }],
// controllers
[IUIController, { useClass: DesktopUIController }],
[SharedController],