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.

fix(formula): fix progress bar not loaded (#3790)

Wenzhao Hu065dadc400e2
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml
index 7f53222133..757705c23c 100644
--- a/.github/workflows/playwright.yml
+++ b/.github/workflows/playwright.yml
@@ -31,7 +31,7 @@ jobs:
- name: 🚀 Deploy to Vercel
uses: amondnet/vercel-action@v25
if: failure()
- id: vercel-e2e-report
+ id: vercel-e2e-report # we only need to upload to Vercel if this CI fails
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.ORG_ID }}
diff --git a/packages-experimental/uniui/src/plugin.ts b/packages-experimental/uniui/src/plugin.ts
index a16e0f5c51..df45197726 100644
--- a/packages-experimental/uniui/src/plugin.ts
+++ b/packages-experimental/uniui/src/plugin.ts
@@ -52,7 +52,6 @@ import {
IMessageService,
INotificationService,
IPlatformService,
- IProgressService,
IShortcutService,
ISidebarService,
IUIController,
@@ -61,7 +60,6 @@ import {
MenuManagerService,
MenuService,
PlatformService,
- ProgressService,
SharedController,
ShortcutPanelController,
ShortcutPanelService,
@@ -127,7 +125,6 @@ export class UniverUniUIPlugin extends Plugin {
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
[ILocalFileService, { useClass: DesktopLocalFileService }],
[ICanvasPopupService, { useClass: CanvasPopupService }],
- [IProgressService, { useClass: ProgressService }],
[CanvasFloatDomService],
[IUIController, {
useFactory: () => this._injector.createInstance(UniverUniUIController, this._config),
diff --git a/packages-experimental/uniui/src/views/uni-toolbar/UniFormulaBar.tsx b/packages-experimental/uniui/src/views/uni-toolbar/UniFormulaBar.tsx
index 07819ffb5d..407c1a91fc 100644
--- a/packages-experimental/uniui/src/views/uni-toolbar/UniFormulaBar.tsx
+++ b/packages-experimental/uniui/src/views/uni-toolbar/UniFormulaBar.tsx
@@ -21,7 +21,7 @@ import { DeviceInputEventType } from '@univerjs/engine-render';
import { CheckMarkSingle, CloseSingle, FxSingle } from '@univerjs/icons';
import { RangeProtectionPermissionEditPoint, RangeProtectionRuleModel, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetSetCellValuePermission } from '@univerjs/sheets';
import { IEditorBridgeService, IFormulaEditorManagerService, useActiveWorkbook } from '@univerjs/sheets-ui';
-import { KeyCode, ProgressBar } from '@univerjs/ui';
+import { KeyCode } from '@univerjs/ui';
import clsx from 'clsx';
import React, { useCallback, useLayoutEffect, useState } from 'react';
import { EMPTY, merge, switchMap } from 'rxjs';
@@ -230,7 +230,6 @@ export function FormulaBar() {
<CheckMarkSingle />
</span>
</div>
- <ProgressBar barColor={progressBarColor} />
</div>
);
}
diff --git a/packages/core/src/shared/r-tree.ts b/packages/core/src/shared/r-tree.ts
index 2d68c605ed..357d1dbe65 100644
--- a/packages/core/src/shared/r-tree.ts
+++ b/packages/core/src/shared/r-tree.ts
@@ -19,18 +19,20 @@ import type { IUnitRange } from '../sheets/typedef';
import KDBush from 'kdbush';
import RBush from 'rbush';
+type StringOrNumber = string | number;
+
export interface IRTreeItem extends IUnitRange {
- id: string;
+ id: StringOrNumber;
}
interface IRBushItem extends BBox {
- id: string;
+ id: StringOrNumber;
}
interface IRdTreeItem {
x: number;
y: number;
- ids: Set<string>;
+ ids: Set<StringOrNumber>;
}
export interface IRTreeData {
@@ -43,7 +45,7 @@ export class RTree {
private _tree: Map<string, Map<string, RBush<IRBushItem>>> = new Map();
// unitId -> subUnitId -> row -> column -> ids
- private _oneCellCache = new Map<string, Map<string, Map<number, Map<number, Set<string>>>>>();
+ private _oneCellCache = new Map<string, Map<string, Map<number, Map<number, Set<StringOrNumber>>>>>();
private _kdTree: Map<string, Map<string, { tree: KDBush; items: IRdTreeItem[] } | undefined>> = new Map();
@@ -68,7 +70,7 @@ export class RTree {
return this._tree.get(unitId)!.get(subUnitId)!;
}
- private _getOneCellCache(unitId: string, subUnitId: string, row: number, column: number): Set<string> {
+ private _getOneCellCache(unitId: string, subUnitId: string, row: number, column: number): Set<StringOrNumber> {
if (!this._oneCellCache.has(unitId)) {
this._oneCellCache.set(unitId, new Map());
}
@@ -85,7 +87,7 @@ export class RTree {
return this._oneCellCache.get(unitId)!.get(subUnitId)!.get(row)!.get(column)!;
}
- private _removeOneCellCache(unitId: string, subUnitId: string, row: number, column: number, id: string) {
+ private _removeOneCellCache(unitId: string, subUnitId: string, row: number, column: number, id: StringOrNumber) {
const unitCache = this._oneCellCache.get(unitId);
if (!unitCache) return;
@@ -101,11 +103,11 @@ export class RTree {
cellCache.delete(id);
}
- private _insertOneCellCache(unitId: string, subUnitId: string, row: number, column: number, id: string) {
+ private _insertOneCellCache(unitId: string, subUnitId: string, row: number, column: number, id: StringOrNumber) {
this._getOneCellCache(unitId, subUnitId, row, column).add(id);
}
- private _getRdTreeItems(map: Map<number, Map<number, Set<string>>>) {
+ private _getRdTreeItems(map: Map<number, Map<number, Set<StringOrNumber>>>) {
const items: IRdTreeItem[] = [];
for (const [y, innerMap] of map) {
@@ -121,7 +123,7 @@ export class RTree {
return items;
}
- private _searchByOneCellCache(search: IUnitRange): string[] {
+ private _searchByOneCellCache(search: IUnitRange): StringOrNumber[] {
const { unitId, sheetId: subUnitId, range } = search;
const { startRow, startColumn, endRow, endColumn } = range;
const searchObject = this._kdTree.get(unitId)?.get(subUnitId);
@@ -133,7 +135,7 @@ export class RTree {
const indexes = tree.range(startColumn, startRow, endColumn, endRow);
- const result: string[] = [];
+ const result: StringOrNumber[] = [];
for (const index of indexes) {
const item = items[index];
@@ -221,13 +223,16 @@ export class RTree {
}
}
- search(search: IUnitRange): string[] {
+ search(search: IUnitRange): StringOrNumber[] {
const { unitId, sheetId: subUnitId, range } = search;
- const results: string[] = [];
+ const results: StringOrNumber[] = [];
if (this._enableOneCellCache && this._enableOneCellCache) {
- results.push(...this._searchByOneCellCache(search));
+ const oneCellResults = this._searchByOneCellCache(search);
+ for (const result of oneCellResults) {
+ results.push(result);
+ }
}
const tree = this._tree.get(unitId)?.get(subUnitId);
@@ -235,18 +240,22 @@ export class RTree {
return results;
}
- results.push(...(tree.search({
+ const searchData = tree.search({
minX: range.startColumn,
minY: range.startRow,
maxX: range.endColumn,
maxY: range.endRow,
- }) as unknown as IRTreeItem[]).map((item) => item.id));
+ }) as unknown as IRTreeItem[];
+
+ for (const item of searchData) {
+ results.push(item.id);
+ }
return results;
}
- bulkSearch(searchList: IUnitRange[]): Set<string> {
- const result = new Set<string>();
+ bulkSearch(searchList: IUnitRange[]): Set<StringOrNumber> {
+ const result = new Set<StringOrNumber>();
for (const search of searchList) {
const items = this.search(search);
for (const item of items) {
diff --git a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
index bae88ec4bf..a5bc0260f4 100644
--- a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
@@ -26,7 +26,6 @@ import { CommandType } from '@univerjs/core';
export interface ISetFormulaCalculationStartMutation extends IFormulaDirtyData {
options: Nullable<IExecutionOptions>;
- forceCalculation: boolean;
}
/**
* TODO: @DR-Univer
diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.ts
index a5ff778267..d84a892b2a 100644
--- a/packages/engine-formula/src/controller/calculate.controller.ts
+++ b/packages/engine-formula/src/controller/calculate.controller.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-import type { ICommandInfo, IUnitRange } from '@univerjs/core';
-import type { IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetDefinedNameMap, IDirtyUnitSheetNameMap, IFormulaData } from '../basics/common';
+import type { ICommandInfo } from '@univerjs/core';
+import type { IFormulaData } from '../basics/common';
import type { ISetArrayFormulaDataMutationParams } from '../commands/mutations/set-array-formula-data.mutation';
import type { ISetFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';
import type { ISetFormulaDataMutationParams } from '../commands/mutations/set-formula-data.mutation';
-import type { IAllRuntimeData } from '../services/runtime.service';
+import type { IFormulaDirtyData } from '../services/current-data.service';
import { Disposable, ICommandService, Inject } from '@univerjs/core';
import { convertRuntimeToUnitData } from '../basics/runtime';
import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
@@ -33,7 +33,7 @@ import {
import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';
import { FormulaDataModel } from '../models/formula-data.model';
import { CalculateFormulaService } from '../services/calculate-formula.service';
-import { FormulaExecutedStateType } from '../services/runtime.service';
+import { FormulaExecutedStateType, type IAllRuntimeData } from '../services/runtime.service';
export class CalculateController extends Disposable {
constructor(
@@ -49,8 +49,6 @@ export class CalculateController extends Disposable {
private _initialize(): void {
this._commandExecutedListener();
this._initialExecuteFormulaListener();
-
- this._initialExecuteFormulaProcessListener();
}
private _commandExecutedListener() {
@@ -66,13 +64,7 @@ export class CalculateController extends Disposable {
} else if (command.id === SetFormulaCalculationStartMutation.id) {
const params = command.params as ISetFormulaCalculationStartMutation;
- if (params.forceCalculation === true) {
- this._calculate(true);
- } else {
- const { dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, clearDependencyTreeCache } = params;
-
- this._calculate(false, dirtyRanges, dirtyNameMap, dirtyDefinedNameMap, dirtyUnitFeatureMap, dirtyUnitOtherFormulaMap, clearDependencyTreeCache);
- }
+ this._calculate(params);
} else if (command.id === SetArrayFormulaDataMutation.id) {
const params = command.params as ISetArrayFormulaDataMutationParams;
@@ -90,14 +82,9 @@ export class CalculateController extends Disposable {
}
private async _calculate(
- forceCalculate: boolean = false,
- dirtyRanges: IUnitRange[] = [],
- dirtyNameMap: IDirtyUnitSheetNameMap = {},
- dirtyDefinedNameMap: IDirtyUnitSheetDefinedNameMap = {},
- dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {},
- dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {},
- clearDependencyTreeCache: IDirtyUnitSheetNameMap = {}
+ formulaDirtyData: Partial<IFormulaDirtyData>
) {
+ const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {} } = formulaDirtyData;
if (
dirtyRanges.length === 0 &&
Object.keys(dirtyNameMap).length === 0 &&
@@ -159,9 +146,7 @@ export class CalculateController extends Disposable {
}
);
});
- }
- private _initialExecuteFormulaProcessListener() {
/**
* Assignment operation after formula calculation.
*/
diff --git a/packages/engine-formula/src/controller/config.schema.ts b/packages/engine-formula/src/controller/config.schema.ts
index 804a84348b..2e5c212eb5 100644
--- a/packages/engine-formula/src/controller/config.schema.ts
+++ b/packages/engine-formula/src/controller/config.schema.ts
@@ -15,8 +15,8 @@
*/
import type { Ctor } from '@univerjs/core';
-import type { BaseFunction } from '../functions/base-function';
import type { IFunctionNames } from '../basics/function';
+import type { BaseFunction } from '../functions/base-function';
export const PLUGIN_CONFIG_KEY = 'engine-formula.config';
@@ -25,6 +25,12 @@ export const configSymbol = Symbol(PLUGIN_CONFIG_KEY);
export interface IUniverEngineFormulaConfig {
notExecuteFormula?: boolean;
function?: Array<[Ctor<BaseFunction>, IFunctionNames]>;
+
+ /**
+ * The formula calculation quantity interval for waiting for the main thread message in the worker. Each time the formula calculates the `intervalCount` quantity, it will receive a main thread message to support stopping the calculation. Default is 500
+ */
+ intervalCount?: number;
+
}
export const defaultPluginConfig: IUniverEngineFormulaConfig = {};
diff --git a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
index 64bc150ae1..15a02a3fee 100644
--- a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
+++ b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts
@@ -39,7 +39,8 @@ import {
DEFAULT_TOKEN_TYPE_PARAMETER,
DEFAULT_TOKEN_TYPE_ROOT,
} from '../../basics/token-type';
-import { deserializeRangeWithSheet, isReferenceStringWithEffectiveColumn, replaceRefPrefixString, serializeRangeToRefString } from '../utils/reference';
+import { isReferenceStringWithEffectiveColumn, replaceRefPrefixString, serializeRangeToRefString } from '../utils/reference';
+import { deserializeRangeWithSheetWithCache } from '../utils/reference-cache';
import { generateStringWithSequence, sequenceNodeType } from '../utils/sequence';
import { LexerNode } from './lexer-node';
@@ -281,7 +282,7 @@ export class LexerTreeBuilder extends Disposable {
if (node.nodeType === sequenceNodeType.REFERENCE) {
const { token, endIndex } = node;
- const sequenceGrid = deserializeRangeWithSheet(token);
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
if (sequenceGrid == null) {
continue;
}
@@ -344,7 +345,7 @@ export class LexerTreeBuilder extends Disposable {
const { token } = node;
- const sequenceGrid = deserializeRangeWithSheet(token);
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
const { sheetName, unitId: sequenceUnitId } = sequenceGrid;
diff --git a/packages/engine-formula/src/engine/ast-node/base-ast-node.ts b/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
index fb0fb676d6..acf0d33089 100644
--- a/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/base-ast-node.ts
@@ -26,7 +26,7 @@ import { NodeType } from './node-type';
interface IAstNodeNodeJson {
token: string;
children?: IAstNodeNodeJson[];
- nodeType: string;
+ nodeType: number;
}
export type LambdaPrivacyVarType = Map<string, Nullable<BaseAstNode>>;
diff --git a/packages/engine-formula/src/engine/ast-node/node-type.ts b/packages/engine-formula/src/engine/ast-node/node-type.ts
index 3103ab65b9..0e02ba6e1b 100644
--- a/packages/engine-formula/src/engine/ast-node/node-type.ts
+++ b/packages/engine-formula/src/engine/ast-node/node-type.ts
@@ -15,19 +15,19 @@
*/
export enum NodeType {
- REFERENCE = 'ReferenceNode',
- VALUE = 'ValueNode',
- OPERATOR = 'OperatorNode',
- FUNCTION = 'FunctionNode',
- LAMBDA = 'LambdaNode',
- LAMBDA_PARAMETER = 'LambdaNodeParameter',
- ERROR = 'ErrorNode',
- BASE = 'Base',
- ROOT = 'Root',
- UNION = 'UnionNode',
- PREFIX = 'PrefixNode',
- SUFFIX = 'SuffixNode',
- NULL = 'NullNode',
+ REFERENCE = 1,
+ VALUE = 2,
+ OPERATOR = 3,
+ FUNCTION = 4,
+ LAMBDA = 5,
+ LAMBDA_PARAMETER = 6,
+ ERROR = 7,
+ BASE = 8,
+ ROOT = 9,
+ UNION = 10,
+ PREFIX = 11,
+ SUFFIX = 12,
+ NULL = 13,
}
export const NODE_ORDER_MAP = new Map([
diff --git a/packages/engine-formula/src/engine/dependency/dependency-tree.ts b/packages/engine-formula/src/engine/dependency/dependency-tree.ts
index c0c97bd9d9..1428b387d7 100644
--- a/packages/engine-formula/src/engine/dependency/dependency-tree.ts
+++ b/packages/engine-formula/src/engine/dependency/dependency-tree.ts
@@ -26,7 +26,6 @@ import type { IFormulaDirtyData } from '../../services/current-data.service';
import type { IAllRuntimeData } from '../../services/runtime.service';
import type { IExecuteAstNodeData } from '../utils/ast-node-tool';
-import { generateRandomId } from '@univerjs/core';
export enum FDtreeStateType {
DEFAULT,
@@ -44,13 +43,13 @@ export enum FDtreeStateType {
* is used to determine the order of formula calculations.
*/
export class FormulaDependencyTree {
- treeId: string = '';
+ treeId: number = -1;
nodeData: Nullable<IExecuteAstNodeData>;
- children: Set<string> = new Set();
+ children: Set<number> = new Set();
- parents: Set<string> = new Set();
+ parents: Set<number> = new Set();
formula: string = '';
@@ -74,12 +73,8 @@ export class FormulaDependencyTree {
isCache: boolean = false;
- constructor(treeId?: string) {
- if (treeId != null) {
- this.treeId = treeId;
- } else {
- this.treeId = generateRandomId(8);
- }
+ constructor(treeId: number) {
+ this.treeId = treeId;
}
toJson() {
@@ -227,7 +222,7 @@ export class FormulaDependencyTree {
this.rangeList.push(...ranges);
}
- hasChildren(treeId: string) {
+ hasChildren(treeId: number) {
return this.children.has(treeId);
}
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 2beecb0e92..459580838b 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -51,9 +51,9 @@ interface IFeatureFormulaParam {
featureId: string;
}
-function generateRandomDependencyTreeId(dependencyManagerService: IDependencyManagerService): string {
+function generateRandomDependencyTreeId(dependencyManagerService: IDependencyManagerService): number {
const idNum = dependencyManagerService.getLastTreeId() || 0;
- return idNum.toString();
+ return idNum;
}
export class FormulaDependencyGenerator extends Disposable {
@@ -132,9 +132,9 @@ export class FormulaDependencyGenerator extends Disposable {
}
private _isCyclicUtil(
- treeId: string,
- visited: Set<string>,
- recursionStack: Set<string>
+ treeId: number,
+ visited: Set<number>,
+ recursionStack: Set<number>
) {
const node = this._dependencyManagerService.getTreeById(treeId);
if (node == null) {
@@ -160,8 +160,8 @@ export class FormulaDependencyGenerator extends Disposable {
}
private _checkIsCycleDependency(treeList: FormulaDependencyTree[]) {
- const visited = new Set<string>();
- const recursionStack = new Set<string>();
+ const visited = new Set<number>();
+ const recursionStack = new Set<number>();
// Call the recursive helper function to detect cycle in different
// DFS trees
@@ -727,7 +727,7 @@ export class FormulaDependencyGenerator extends Disposable {
featureTree = this._getFeatureFormulaTree(featureId, params);
newTreeList.push(featureTree);
}
- featureTree.parents = new Set<string>();
+ featureTree.parents = new Set<number>();
intersectTrees.forEach((tree) => {
if (tree.hasChildren(featureTree!.treeId)) {
return;
@@ -748,7 +748,7 @@ export class FormulaDependencyGenerator extends Disposable {
const featureMap = this._featureCalculationManagerService.getReferenceExecutorMap();
newTreeList.forEach((tree) => {
- const newChildren = new Set<string>();
+ const newChildren = new Set<number>();
for (const childTreeId of tree.children) {
const child = this._dependencyManagerService.getTreeById(childTreeId);
if (!child) {
@@ -762,7 +762,7 @@ export class FormulaDependencyGenerator extends Disposable {
}
tree.children = newChildren;
- const newParents = new Set<string>();
+ const newParents = new Set<number>();
for (const parentTreeId of tree.parents) {
const parent = this._dependencyManagerService.getTreeById(parentTreeId);
if (!parent) {
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index c1279af7ab..d503e9be8d 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -152,8 +152,7 @@ export { FeatureCalculationManagerService, IFeatureCalculationManagerService } f
export { FunctionService } from './services/function.service';
export { IFunctionService } from './services/function.service';
export { IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';
-export { FormulaExecuteStageType, type IExecutionInProgressParams } from './services/runtime.service';
-export { FormulaExecutedStateType, type IAllRuntimeData } from './services/runtime.service';
-export { FormulaRuntimeService, IFormulaRuntimeService } from './services/runtime.service';
+export { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeService, type IAllRuntimeData, type IExecutionInProgressParams, IFormulaRuntimeService } from './services/runtime.service';
export { ISuperTableService } from './services/super-table.service';
export { SuperTableService } from './services/super-table.service';
+export { deserializeRangeWithSheetWithCache } from './engine/utils/reference-cache';
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index 23ecec92d7..e860f19a03 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -22,8 +22,9 @@ import type {
IRuntimeUnitDataType,
IUnitExcludedCell,
} from '../basics/common';
-import type { LexerNode } from '../engine/analysis/lexer-node';
+import type { IUniverEngineFormulaConfig } from '../controller/config.schema';
+import type { LexerNode } from '../engine/analysis/lexer-node';
import type { IAllRuntimeData, IExecutionInProgressParams } from './runtime.service';
import {
Disposable,
@@ -35,6 +36,7 @@ import {
import { Subject } from 'rxjs';
import { ErrorType } from '../basics/error-type';
import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';
+import { PLUGIN_CONFIG_KEY } from '../controller/config.schema';
import { Lexer } from '../engine/analysis/lexer';
import { AstTreeBuilder } from '../engine/analysis/parser';
import { ErrorNode } from '../engine/ast-node/base-ast-node';
@@ -46,23 +48,21 @@ import { FormulaExecuteStageType, IFormulaRuntimeService } from './runtime.servi
export const DEFAULT_CYCLE_REFERENCE_COUNT = 1;
+export const DEFAULT_INTERVAL_COUNT = 500;
+
export const CYCLE_REFERENCE_COUNT = 'cycleReferenceCount';
export const EVERY_N_FUNCTION_EXECUTION_PAUSE = 100;
export class CalculateFormulaService extends Disposable {
- private readonly _executionStartListener$ = new Subject<boolean>();
+ private readonly _executionInProgressListener$ = new Subject<IExecutionInProgressParams>();
- readonly executionStartListener$ = this._executionStartListener$.asObservable();
+ readonly executionInProgressListener$ = this._executionInProgressListener$.asObservable();
private readonly _executionCompleteListener$ = new Subject<IAllRuntimeData>();
readonly executionCompleteListener$ = this._executionCompleteListener$.asObservable();
- private readonly _executionInProgressListener$ = new Subject<IExecutionInProgressParams>();
-
- readonly executionInProgressListener$ = this._executionInProgressListener$.asObservable();
-
constructor(
@IConfigService private readonly _configService: IConfigService,
@Inject(Lexer) private readonly _lexer: Lexer,
@@ -98,7 +98,8 @@ export class CalculateFormulaService extends Disposable {
}
async execute(formulaDatasetConfig: IFormulaDatasetConfig) {
- this._executionStartListener$.next(true);
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START);
+ this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
this._currentConfigService.load(formulaDatasetConfig);
@@ -243,25 +244,44 @@ export class CalculateFormulaService extends Disposable {
let pendingTasks: (() => void)[] = [];
+ const config = this._configService.getConfig(PLUGIN_CONFIG_KEY) as IUniverEngineFormulaConfig;
+ const intervalCount = config?.intervalCount || DEFAULT_INTERVAL_COUNT;
+
for (let i = 0, len = treeList.length; i < len; i++) {
+ const tree = treeList[i];
+ const nodeData = tree.nodeData;
+ const getDirtyData = tree.getDirtyData;
+
+ // Execute the await every 100 iterations
+ if (i % intervalCount === 0) {
/**
* For every functions, execute a setTimeout to wait for external command input.
*/
- await new Promise((resolve) => {
- const calCancelTask = requestImmediateMacroTask(resolve);
- pendingTasks.push(calCancelTask);
- });
+ await new Promise((resolve) => {
+ const calCancelTask = requestImmediateMacroTask(resolve);
+ pendingTasks.push(calCancelTask);
+ });
- const tree = treeList[i];
- const nodeData = tree.nodeData;
- const getDirtyData = tree.getDirtyData;
- let value: FunctionVariantType;
+ if (isArrayFormulaState) {
+ this._runtimeService.setFormulaExecuteStage(
+ FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA
+ );
+
+ this._runtimeService.setCompletedArrayFormulasCount(i + 1);
+ } else {
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CURRENTLY_CALCULATING);
+
+ this._runtimeService.setCompletedFormulasCount(i + 1);
+ }
+
+ this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
- if (this._runtimeService.isStopExecution() || (nodeData == null && getDirtyData == null)) {
- this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
- this._runtimeService.markedAsStopFunctionsExecuted();
- this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());
- return;
+ if (this._runtimeService.isStopExecution() || (nodeData == null && getDirtyData == null)) {
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
+ this._runtimeService.markedAsStopFunctionsExecuted();
+ this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());
+ return;
+ }
}
this._runtimeService.setCurrent(
@@ -273,6 +293,8 @@ export class CalculateFormulaService extends Disposable {
tree.unitId
);
+ let value: FunctionVariantType;
+
if (getDirtyData != null && tree.featureId != null) {
/**
* Execute the dependencies registered by the feature,
@@ -297,20 +319,6 @@ export class CalculateFormulaService extends Disposable {
this._runtimeService.setRuntimeData(value);
}
}
-
- if (isArrayFormulaState) {
- this._runtimeService.setFormulaExecuteStage(
- FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA
- );
-
- this._runtimeService.setCompletedArrayFormulasCount(i + 1);
- } else {
- this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CURRENTLY_CALCULATING);
-
- this._runtimeService.setCompletedFormulasCount(i + 1);
- }
-
- this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
}
// clear all pending tasks
diff --git a/packages/engine-formula/src/services/dependency-manager.service.ts b/packages/engine-formula/src/services/dependency-manager.service.ts
index 329af68571..036edea9b2 100644
--- a/packages/engine-formula/src/services/dependency-manager.service.ts
+++ b/packages/engine-formula/src/services/dependency-manager.service.ts
@@ -14,20 +14,20 @@
* limitations under the License.
*/
-import type { IUnitRange, Nullable } from '@univerjs/core';
+import type { IRTreeItem, IUnitRange, Nullable } from '@univerjs/core';
import type { FormulaDependencyTree } from '../engine/dependency/dependency-tree';
import { createIdentifier, Disposable, ObjectMatrix, RTree } from '@univerjs/core';
export interface IOtherFormulaDependencyParam {
- [unitId: string]: Nullable<{ [sheetId: string]: { [formulaId: string]: Nullable<string> } }>;
+ [unitId: string]: Nullable<{ [sheetId: string]: { [formulaId: string]: Nullable<number> } }>;
}
export interface IFeatureFormulaDependencyParam {
- [unitId: string]: Nullable<{ [sheetId: string]: { [featureId: string]: Nullable<string> } }>;
+ [unitId: string]: Nullable<{ [sheetId: string]: { [featureId: string]: Nullable<number> } }>;
}
export interface IFormulaDependencyParam {
- [unitId: string]: Nullable<{ [sheetId: string]: ObjectMatrix< string> }>;
+ [unitId: string]: Nullable<{ [sheetId: string]: ObjectMatrix< number> }>;
}
export interface IDependencyManagerService {
@@ -65,7 +65,7 @@ export interface IDependencyManagerService {
addDependencyRTreeCache(tree: FormulaDependencyTree): void;
- searchDependency(search: IUnitRange[]): Set<string>;
+ searchDependency(search: IUnitRange[]): Set<number>;
getLastTreeId(): number;
@@ -77,7 +77,7 @@ export interface IDependencyManagerService {
openKdTree(): void;
closeKdTree(): void;
- getTreeById(treeId: string): Nullable<FormulaDependencyTree>;
+ getTreeById(treeId: number): Nullable<FormulaDependencyTree>;
}
/**
@@ -93,7 +93,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
private _formulaData: IFormulaDependencyParam = {};
- private _allTreeMap: Map<string, FormulaDependencyTree> = new Map();
+ private _allTreeMap: Map<number, FormulaDependencyTree> = new Map();
private _dependencyRTreeCache: RTree = new RTree(true); // true: open kd-tree search state
@@ -105,6 +105,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
this._formulaData = {};
this._dependencyRTreeCache.dispose();
this._restDependencyTreeId();
+ this._allTreeMap.clear();
}
/**
@@ -178,7 +179,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
return trees;
}
- getTreeById(treeId: string) {
+ getTreeById(treeId: number) {
return this._allTreeMap.get(treeId);
}
@@ -194,8 +195,8 @@ export class DependencyManagerService extends Disposable implements IDependencyM
return allTrees;
}
- searchDependency(search: IUnitRange[]): Set<string> {
- return this._dependencyRTreeCache.bulkSearch(search);
+ searchDependency(search: IUnitRange[]): Set<number> {
+ return this._dependencyRTreeCache.bulkSearch(search) as Set<number>;
}
/**
@@ -204,7 +205,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
* @param shouldBeBuildTrees FormulaDependencyTree[] | FormulaDependencyTreeCache
*/
private _buildDependencyTree(allTrees: FormulaDependencyTree[], shouldBeBuildTrees: FormulaDependencyTree[]) {
- const shouldBeBuildTreeMap = new Map<string, FormulaDependencyTree>();
+ const shouldBeBuildTreeMap = new Map<number, FormulaDependencyTree>();
for (let i = 0; i < shouldBeBuildTrees.length; i++) {
const tree = shouldBeBuildTrees[i];
shouldBeBuildTreeMap.set(tree.treeId, tree);
@@ -217,7 +218,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
const searchResults = this._dependencyRTreeCache.search(RTreeItem);
for (let j = 0; j < searchResults.length; j++) {
- const id = searchResults[j];
+ const id = searchResults[j] as number;
const shouldBeBuildTree = shouldBeBuildTreeMap.get(id);
if (shouldBeBuildTree && tree !== shouldBeBuildTree && !shouldBeBuildTree.hasChildren(tree.treeId)) {
@@ -237,7 +238,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
* @param dependencyTrees
*/
private _buildReverseDependency(allTrees: FormulaDependencyTree[], dependencyTrees: FormulaDependencyTree[]) {
- const allTreeMap = new Map<string, FormulaDependencyTree>();
+ const allTreeMap = new Map<number, FormulaDependencyTree>();
for (let i = 0; i < allTrees.length; i++) {
const tree = allTrees[i];
@@ -251,7 +252,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
const searchResults = this._dependencyRTreeCache.search(RTreeItem);
for (let j = 0; j < searchResults.length; j++) {
- const id = searchResults[j];
+ const id = searchResults[j] as number;
const allTree = allTreeMap.get(id);
if (allTree && tree !== allTree && !allTree.hasChildren(tree.treeId)) {
@@ -279,31 +280,15 @@ export class DependencyManagerService extends Disposable implements IDependencyM
const allTreeMap = this._allTreeMap;
- parents.forEach((parentTreeId) => {
+ for (const parentTreeId of parents) {
const parent = allTreeMap.get(parentTreeId);
parent?.children.delete(shouldBeClearTree.treeId);
- });
+ }
- children.forEach((childTreeId) => {
+ for (const childTreeId of children) {
const child = allTreeMap.get(childTreeId);
child?.parents.delete(shouldBeClearTree.treeId);
- });
-
- const parentsArray: FormulaDependencyTree[] = [];
- const childrenArray: FormulaDependencyTree[] = [];
-
- allTreeMap.forEach((tree) => {
- if (tree.parents.has(tree.treeId)) {
- parentsArray.push(tree);
- }
-
- if (tree.children.has(tree.treeId)) {
- childrenArray.push(tree);
- }
- });
-
- this._buildDependencyTree(parentsArray, childrenArray);
- this._buildReverseDependency(parentsArray, childrenArray);
+ }
shouldBeClearTree.dispose();
}
@@ -333,7 +318,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
if (this._otherFormulaData[unitId] && this._otherFormulaData[unitId]![sheetId]) {
formulaIds.forEach((formulaId) => {
const deleteTreeId = this._otherFormulaData[unitId]![sheetId][formulaId];
- const deleteTree = this._allTreeMap.get(deleteTreeId || '');
+ if (deleteTreeId == null) {
+ return;
+ }
+ const deleteTree = this._allTreeMap.get(deleteTreeId);
this._removeDependencyRTreeCache(deleteTree);
this.clearDependencyForTree(deleteTree);
delete this._otherFormulaData[unitId]![sheetId][formulaId];
@@ -343,7 +331,11 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
getOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string) {
- return this._allTreeMap.get(this._otherFormulaData[unitId]?.[sheetId]?.[formulaId] || '');
+ let treeId = this._otherFormulaData[unitId]?.[sheetId]?.[formulaId];
+ if (treeId == null) {
+ treeId = -1;
+ }
+ return this._allTreeMap.get(treeId);
}
hasOtherFormulaDependency(unitId: string, sheetId: string, formulaId: string) {
@@ -354,7 +346,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
if (sheetId && this._otherFormulaData[unitId] && this._otherFormulaData[unitId]![sheetId]) {
this._removeDependencyRTreeCacheById(unitId, sheetId);
Object.values(this._otherFormulaData[unitId]![sheetId]).forEach((formulaTreeId) => {
- const formula = this._allTreeMap.get(formulaTreeId || '');
+ if (formulaTreeId == null) {
+ return;
+ }
+ const formula = this._allTreeMap.get(formulaTreeId);
this.clearDependencyForTree(formula);
this._removeAllTreeMap(formulaTreeId);
});
@@ -368,7 +363,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
this._removeDependencyRTreeCacheById(unitId, sheetId);
Object.values(unitOtherData[sheetId]!).forEach((formulaTreeId) => {
- const formula = this._allTreeMap.get(formulaTreeId || '');
+ if (formulaTreeId == null) {
+ return;
+ }
+ const formula = this._allTreeMap.get(formulaTreeId);
this.clearDependencyForTree(formula);
this._removeAllTreeMap(formulaTreeId);
});
@@ -394,7 +392,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
if (this._featureFormulaData[unitId] && this._featureFormulaData[unitId]![sheetId]) {
featureIds.forEach((featureId) => {
const deleteTreeId = this._featureFormulaData[unitId]![sheetId][featureId];
- const deleteTree = this._allTreeMap.get(deleteTreeId || '');
+ if (deleteTreeId == null) {
+ return;
+ }
+ const deleteTree = this._allTreeMap.get(deleteTreeId);
this._removeDependencyRTreeCache(deleteTree);
this.clearDependencyForTree(deleteTree);
delete this._featureFormulaData[unitId]![sheetId][featureId];
@@ -407,7 +408,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
if (sheetId && this._featureFormulaData[unitId] && this._featureFormulaData[unitId]![sheetId]) {
this._removeDependencyRTreeCacheById(unitId, sheetId);
Object.values(this._featureFormulaData[unitId]![sheetId]).forEach((featureTreeId) => {
- const feature = this._allTreeMap.get(featureTreeId || '');
+ if (featureTreeId == null) {
+ return;
+ }
+ const feature = this._allTreeMap.get(featureTreeId);
this._removeDependencyRTreeCache(feature);
this.clearDependencyForTree(feature);
this._removeAllTreeMap(featureTreeId);
@@ -422,7 +426,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
this._removeDependencyRTreeCacheById(unitId, sheetId);
Object.values(unitFeatureData[sheetId]!).forEach((featureTreeId) => {
- const feature = this._allTreeMap.get(featureTreeId || '');
+ if (featureTreeId == null) {
+ return;
+ }
+ const feature = this._allTreeMap.get(featureTreeId);
this.clearDependencyForTree(feature);
this._removeAllTreeMap(featureTreeId);
});
@@ -433,7 +440,11 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
getFeatureFormulaDependency(unitId: string, sheetId: string, featureId: string) {
- return this._allTreeMap.get(this._featureFormulaData[unitId]?.[sheetId]?.[featureId] || '');
+ const treeId = this._featureFormulaData[unitId]?.[sheetId]?.[featureId];
+ if (treeId == null) {
+ return null;
+ }
+ return this._allTreeMap.get(treeId);
}
addFormulaDependency(unitId: string, sheetId: string, row: number, column: number, dependencyTree: FormulaDependencyTree) {
@@ -441,7 +452,7 @@ export class DependencyManagerService extends Disposable implements IDependencyM
this._formulaData[unitId] = {};
}
if (!this._formulaData[unitId]![sheetId]) {
- this._formulaData[unitId]![sheetId] = new ObjectMatrix<string>();
+ this._formulaData[unitId]![sheetId] = new ObjectMatrix<number>();
}
this._formulaData[unitId]![sheetId].setValue(row, column, dependencyTree.treeId);
this._allTreeMap.set(dependencyTree.treeId, dependencyTree);
@@ -450,7 +461,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
removeFormulaDependency(unitId: string, sheetId: string, row: number, column: number) {
if (this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {
const deleteTreeId = this._formulaData[unitId]![sheetId].getValue(row, column);
- const deleteTree = this._allTreeMap.get(deleteTreeId || '');
+ if (deleteTreeId == null) {
+ return;
+ }
+ const deleteTree = this._allTreeMap.get(deleteTreeId);
this._removeDependencyRTreeCache(deleteTree);
this.clearDependencyForTree(deleteTree);
this._formulaData[unitId]![sheetId].realDeleteValue(row, column);
@@ -462,7 +476,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
if (sheetId && this._formulaData[unitId] && this._formulaData[unitId]![sheetId]) {
this._removeDependencyRTreeCacheById(unitId, sheetId);
this._formulaData[unitId]![sheetId].forValue((row, column, treeId) => {
- const tree = this._allTreeMap.get(treeId || '');
+ if (treeId == null) {
+ return true;
+ }
+ const tree = this._allTreeMap.get(treeId);
this.clearDependencyForTree(tree);
this._removeAllTreeMap(treeId);
});
@@ -476,7 +493,10 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
this._removeDependencyRTreeCacheById(unitId, sheetId);
unitFormulaData[sheetId].forValue((row, column, treeId) => {
- const tree = this._allTreeMap.get(treeId || '');
+ if (treeId == null) {
+ return true;
+ }
+ const tree = this._allTreeMap.get(treeId);
this.clearDependencyForTree(tree);
this._removeAllTreeMap(treeId);
});
@@ -495,16 +515,28 @@ export class DependencyManagerService extends Disposable implements IDependencyM
}
getFormulaDependency(unitId: string, sheetId: string, row: number, column: number) {
- return this._allTreeMap.get(this._formulaData[unitId]?.[sheetId]?.getValue(row, column) || '');
+ const treeId = this._formulaData[unitId]?.[sheetId]?.getValue(row, column);
+ if (treeId == null) {
+ return null;
+ }
+ return this._allTreeMap.get(treeId);
}
addDependencyRTreeCache(tree: FormulaDependencyTree) {
- this._dependencyRTreeCache.bulkInsert(tree.rangeList.map((range) => {
- return {
- ...range,
+ const searchRanges: IRTreeItem[] = [];
+ for (let i = 0; i < tree.rangeList.length; i++) {
+ const unitRangeWithNum = tree.rangeList[i];
+ const { unitId, sheetId, range } = unitRangeWithNum;
+
+ searchRanges.push({
+ unitId,
+ sheetId,
+ range,
id: tree.treeId,
- };
- }));
+ });
+ }
+
+ this._dependencyRTreeCache.bulkInsert(searchRanges);
}
private _restDependencyTreeId() {
@@ -525,19 +557,28 @@ export class DependencyManagerService extends Disposable implements IDependencyM
if (tree == null) {
return;
}
- this._dependencyRTreeCache.bulkRemove(tree.rangeList.map((range) => {
- return {
- ...range,
+
+ const searchRanges: IRTreeItem[] = [];
+ for (let i = 0; i < tree.rangeList.length; i++) {
+ const unitRangeWithNum = tree.rangeList[i];
+ const { unitId, sheetId, range } = unitRangeWithNum;
+
+ searchRanges.push({
+ unitId,
+ sheetId,
+ range,
id: tree.treeId,
- };
- }));
+ });
+ }
+
+ this._dependencyRTreeCache.bulkRemove(searchRanges);
}
removeFormulaDependencyByDefinedName(unitId: string, definedName: string) {
if (this._formulaData[unitId]) {
Object.values(this._formulaData[unitId]).forEach((sheet) => {
sheet.forValue((row, column, treeId) => {
- const tree = this._allTreeMap.get(treeId || '');
+ const tree = this._allTreeMap.get(treeId);
if (tree?.nodeData?.node.hasDefinedName(definedName)) {
this._removeDependencyRTreeCache(tree);
this.clearDependencyForTree(tree);
@@ -556,8 +597,11 @@ export class DependencyManagerService extends Disposable implements IDependencyM
this._dependencyRTreeCache.closeKdTree();
}
- private _removeAllTreeMap(treeId: Nullable<string>) {
- this._allTreeMap.delete(treeId || '');
+ private _removeAllTreeMap(treeId: Nullable<number>) {
+ if (treeId == null) {
+ return;
+ }
+ this._allTreeMap.delete(treeId);
}
}
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index 9be2de3a51..7523de25dd 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -47,6 +47,7 @@ import { IFormulaCurrentConfigService } from './current-data.service';
*/
export enum FormulaExecuteStageType {
IDLE,
+ START,
START_DEPENDENCY,
START_CALCULATION,
CURRENTLY_CALCULATING,
@@ -272,6 +273,14 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
return this._isCycleDependency;
}
+ setFormulaCycleIndex(index: number) {
+ this._formulaCycleIndex = index;
+ }
+
+ getFormulaCycleIndex() {
+ return this._formulaCycleIndex;
+ }
+
setTotalArrayFormulasToCalculate(value: number) {
this._totalArrayFormulasToCalculate = value;
}
@@ -304,14 +313,6 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
return this._completedFormulasCount;
}
- setFormulaCycleIndex(index: number) {
- this._formulaCycleIndex = index;
- }
-
- getFormulaCycleIndex() {
- return this._formulaCycleIndex;
- }
-
markedAsSuccessfullyExecuted() {
this._functionsExecutedState = FormulaExecutedStateType.SUCCESS;
}
@@ -361,9 +362,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
this.markedAsInitialFunctionsExecuted();
this._stopState = false;
-
this._isCycleDependency = false;
-
this._totalFormulasToCalculate = 0;
this._completedFormulasCount = 0;
}
@@ -462,12 +461,12 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
const arrayFormulaRange = this._unitArrayFormulaRange[unitId]!;
- let arrayData = new ObjectMatrix<IRange>();
-
- if (arrayFormulaRange[sheetId]) {
- arrayData = new ObjectMatrix(arrayFormulaRange[sheetId]);
+ if (arrayFormulaRange[sheetId] === null || arrayFormulaRange[sheetId] === undefined) {
+ arrayFormulaRange[sheetId] = {};
}
+ const arrayData = new ObjectMatrix<IRange>(arrayFormulaRange[sheetId]);
+
if (this._runtimeArrayFormulaCellData[unitId] === undefined) {
this._runtimeArrayFormulaCellData[unitId] = {};
}
@@ -523,10 +522,9 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
endColumn: endColumn - startColumn + column,
};
+ // Do not use getData to synchronize arrayData to arrayFormulaRange[sheetId] anymore, they are already linked, otherwise it will cause performance issues
arrayData.setValue(row, column, arrayRange);
- arrayFormulaRange[sheetId] = arrayData.getData();
-
if (
this._checkIfArrayFormulaRangeHasData(unitId, sheetId, row, column, arrayRange) ||
this._checkIfArrayFormulaExceeded(rowCount, columnCount, arrayRange)
diff --git a/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
index 21a1de0569..a9a32c8612 100644
--- a/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
+++ b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
@@ -15,12 +15,12 @@
*/
import type { ICellData, Injector, IStyleData, Nullable } from '@univerjs/core';
+import type { FUniver } from '../../facade';
import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { SetArrayFormulaDataMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
+
import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';
import { beforeEach, describe, expect, it } from 'vitest';
-
-import { SetArrayFormulaDataMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
-import type { FUniver } from '../../facade';
import { createFormulaTestBed } from './create-formula-test-bed';
describe('Test FFormula', () => {
diff --git a/packages/facade/src/apis/sheets/f-formula.ts b/packages/facade/src/apis/sheets/f-formula.ts
index 246b7efd60..bc6a0f6fcd 100644
--- a/packages/facade/src/apis/sheets/f-formula.ts
+++ b/packages/facade/src/apis/sheets/f-formula.ts
@@ -44,9 +44,9 @@ export class FFormula {
);
}
- /**
- * Stop the calculation of the formula.
- */
+ /**
+ * Stop the calculation of the formula.
+ */
stopCalculation(): void {
this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});
}
diff --git a/packages/sheets-data-validation/src/controllers/dv-formula.controller.ts b/packages/sheets-data-validation/src/controllers/dv-formula.controller.ts
index f779935e38..88fb1caa89 100644
--- a/packages/sheets-data-validation/src/controllers/dv-formula.controller.ts
+++ b/packages/sheets-data-validation/src/controllers/dv-formula.controller.ts
@@ -16,7 +16,7 @@
import type { ICellDataForSheetInterceptor, Nullable, Workbook, Worksheet } from '@univerjs/core';
import { Disposable, Inject, IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
-import { deserializeRangeWithSheet, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { deserializeRangeWithSheetWithCache, LexerTreeBuilder } from '@univerjs/engine-formula';
import { UnitAction } from '@univerjs/protocol';
import { type ICellPermission, WorksheetViewPermission } from '@univerjs/sheets';
@@ -40,7 +40,7 @@ export class DataValidationFormulaController extends Disposable {
continue;
}
const { token } = node;
- const sequenceGrid = deserializeRangeWithSheet(token);
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
let targetSheet: Nullable<Worksheet> = workbook.getActiveSheet();
const unitId = workbook.getUnitId();
diff --git a/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
index 0737f4f844..7115e8e199 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
@@ -18,6 +18,7 @@ import type { Dependency } from '@univerjs/core';
import { connectInjector, Disposable, ICommandService, Inject, Injector, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { SheetsUIPart } from '@univerjs/sheets-ui';
import { BuiltInUIPart, ComponentManager, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';
import { SheetOnlyPasteFormulaCommand } from '../commands/commands/formula-clipboard.command';
import { SelectEditorFormulaOperation } from '../commands/operations/editor-formula.operation';
@@ -26,6 +27,7 @@ import { InsertFunctionOperation } from '../commands/operations/insert-function.
import { MoreFunctionsOperation } from '../commands/operations/more-functions.operation';
import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
import { SearchFunctionOperation } from '../commands/operations/search-function.operation';
+import { FormulaProgressBar } from '../views/formula-progress/FormulaProgress';
import { RenderFormulaPromptContent } from '../views/FormulaPromptContainer';
import { MORE_FUNCTIONS_COMPONENT } from '../views/more-functions/interface';
import { MoreFunctions } from '../views/more-functions/MoreFunctions';
@@ -93,9 +95,8 @@ export class FormulaUIController extends Disposable {
}
private _registerComponents(): void {
- this.disposeWithMe(
- this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(RenderFormulaPromptContent, this._injector))
- );
+ this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(RenderFormulaPromptContent, this._injector)));
+ this.disposeWithMe(this._uiPartsService.registerComponent(SheetsUIPart.FORMULA_AUX, () => connectInjector(FormulaProgressBar, this._injector)));
this._componentManager.register(MORE_FUNCTIONS_COMPONENT, MoreFunctions);
}
diff --git a/packages/sheets-formula-ui/src/views/formula-progress/FormulaProgress.tsx b/packages/sheets-formula-ui/src/views/formula-progress/FormulaProgress.tsx
new file mode 100644
index 0000000000..ba7a66a7b1
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-progress/FormulaProgress.tsx
@@ -0,0 +1,37 @@
+/**
+ * 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 { ICommandService, useDependency, useObservable } from '@univerjs/core';
+import { SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
+import { TriggerCalculationController } from '@univerjs/sheets-formula';
+import { ProgressBar } from '@univerjs/ui';
+import React, { useCallback } from 'react';
+
+export function FormulaProgressBar() {
+ const triggerCalculationController = useDependency(TriggerCalculationController);
+ const commandService = useDependency(ICommandService);
+ const progress = useObservable(triggerCalculationController.progress$)!;
+
+ const terminateCalculation = useCallback(() => {
+ commandService.executeCommand(SetFormulaCalculationStopMutation.id);
+ }, [commandService]);
+
+ const clearProgress = useCallback(() => {
+ triggerCalculationController.clearProgress();
+ }, [triggerCalculationController]);
+
+ return <ProgressBar progress={progress} onTerminate={terminateCalculation} onClearProgress={clearProgress} />;
+}
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index c2a819f0bc..328a06f94a 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -22,9 +22,10 @@ import type {
IExecutionInProgressParams,
IFormulaDirtyData,
ISetFormulaCalculationNotificationMutation,
+ ISetFormulaCalculationStartMutation,
} from '@univerjs/engine-formula';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { Disposable, ICommandService, throttle } from '@univerjs/core';
+import { Disposable, ICommandService } from '@univerjs/core';
import {
FormulaExecutedStateType,
FormulaExecuteStageType,
@@ -45,10 +46,12 @@ import { BehaviorSubject } from 'rxjs';
* This interface is for the progress bar to display the calculation progress.
*/
export interface ICalculationProgress {
+ /** Task that already completed. */
done: number;
/** The total number of formulas need to calculate. */
count: number;
}
+
const NilProgress: ICalculationProgress = { done: 0, count: 0 };
const lo = { onlyLocal: true };
@@ -70,17 +73,48 @@ export class TriggerCalculationController extends Disposable {
private _startExecutionTime: number = 0;
- private _formulaCalculationDoneCount: number = 0;
+ private _totalCalculationTaskCount: number = 0;
- private _arrayFormulaCalculationDoneCount: number = 0;
+ private _doneCalculationTaskCount: number = 0;
private _executionInProgressParams: Nullable<IExecutionInProgressParams> = null;
private _restartCalculation = false;
+ /**
+ * The mark of forced calculation. If a new mutation triggers dirty area calculation during the forced calculation process, forced calculation is still required.
+ */
+ private _forceCalculating = false;
+
private readonly _progress$ = new BehaviorSubject<ICalculationProgress>(NilProgress);
+
readonly progress$ = this._progress$.asObservable();
+ private _emitProgress(): void {
+ this._progress$.next({ done: this._doneCalculationTaskCount, count: this._totalCalculationTaskCount });
+ }
+
+ private _startProgress(): void {
+ if (this._executionInProgressParams) {
+ const { totalFormulasToCalculate, completedFormulasCount, totalArrayFormulasToCalculate, completedArrayFormulasCount } = this._executionInProgressParams;
+ this._doneCalculationTaskCount = completedFormulasCount + completedArrayFormulasCount;
+ this._totalCalculationTaskCount = totalFormulasToCalculate + totalArrayFormulasToCalculate;
+
+ this._emitProgress();
+ }
+ }
+
+ private _completeProgress(): void {
+ this._doneCalculationTaskCount = this._totalCalculationTaskCount;
+ this._emitProgress();
+ }
+
+ clearProgress(): void {
+ this._doneCalculationTaskCount = 0;
+ this._totalCalculationTaskCount = 0;
+ this._emitProgress();
+ }
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService
@@ -90,7 +124,6 @@ export class TriggerCalculationController extends Disposable {
this._commandExecutedListener();
this._initialExecuteFormulaProcessListener();
this._initialExecuteFormula();
- this._initialProgressBar();
}
override dispose(): void {
@@ -132,11 +165,9 @@ export class TriggerCalculationController extends Disposable {
this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, { ...this._executingDirtyData }, lo);
} else {
this._restartCalculation = true;
- this._commandService.executeCommand(SetFormulaCalculationStopMutation.id);
+ this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});
}
- this._startExecutionTime = performance.now();
-
this._waitingCommandQueue = [];
}, 100);
})
@@ -221,7 +252,7 @@ export class TriggerCalculationController extends Disposable {
dirtyDefinedNameMap: allDirtyDefinedNameMap,
dirtyUnitFeatureMap: allDirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,
- forceCalculation: false,
+ forceCalculation: !!this._forceCalculating,
clearDependencyTreeCache: allClearDependencyTreeCache,
};
}
@@ -263,18 +294,22 @@ export class TriggerCalculationController extends Disposable {
// eslint-disable-next-line max-lines-per-function
private _initialExecuteFormulaProcessListener() {
// Assignment operation after formula calculation.
- const debouncedFormulaPushTask = throttle(this._pushFormulaTask.bind(this), 300);
- const debouncedArrayFormulaPushTask = throttle(this._pushArrayFormulaTask.bind(this), 300);
let startDependencyTimer: NodeJS.Timeout | null = null;
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(
- // eslint-disable-next-line complexity, max-lines-per-function
+
+ // eslint-disable-next-line max-lines-per-function, complexity
this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === SetFormulaCalculationStartMutation.id) {
+ const { forceCalculation } = command.params as ISetFormulaCalculationStartMutation;
+ if (forceCalculation) {
+ this._forceCalculating = true;
+ }
+ } else if (command.id === SetFormulaCalculationStopMutation.id) {
+ this.clearProgress();
+ }
+
if (command.id !== SetFormulaCalculationNotificationMutation.id) {
return;
}
@@ -283,14 +318,15 @@ export class TriggerCalculationController extends Disposable {
if (params.stageInfo != null) {
const {
- totalFormulasToCalculate,
- completedFormulasCount,
- totalArrayFormulasToCalculate,
- completedArrayFormulasCount,
stage,
} = params.stageInfo;
- if (stage === FormulaExecuteStageType.START_DEPENDENCY) {
+ if (stage === FormulaExecuteStageType.START) {
+ // When calculations are started multiple times in succession, only the first time is recognized
+ if (calculationProcessCount === 0) {
+ this._startExecutionTime = performance.now();
+ }
+
// Increment the calculation process count and assign a new ID
calculationProcessCount++;
@@ -300,48 +336,17 @@ export class TriggerCalculationController extends Disposable {
startDependencyTimer = null;
}
- // If the total calculation time exceeds 1s, a progress bar is displayed. The first progress shows 5%
+ // If the total calculation time exceeds 1s, a progress bar is displayed.
startDependencyTimer = setTimeout(() => {
- // Ignore progress deviations, and finally the complete method ensures the correct completion of the progress
- const taskCount = (formulaCalculationCount - this._formulaCalculationDoneCount) + (arrayFormulaCalculationCount - this._arrayFormulaCalculationDoneCount) + 100;
- // this._progressService.insertTaskCount(taskCount);
- // this._progressService.pushTask({ count: 5 });
startDependencyTimer = null;
}, 1000);
- } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING) {
- // Each start of calculation of statistics once
- if (completedFormulasCount === 1 && !needStartFormulaProgress) {
- needStartFormulaProgress = true;
- if (startDependencyTimer) {
- formulaCalculationCount += totalFormulasToCalculate;
- } else {
- // this._progressService.insertTaskCount(totalFormulasToCalculate);
- }
- }
+ } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING || stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {
+ this._executionInProgressParams = params.stageInfo;
- if (startDependencyTimer) {
- this._formulaCalculationDoneCount = completedFormulasCount;
- } else {
- debouncedFormulaPushTask(completedFormulasCount);
- }
- } else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {
- if (completedArrayFormulasCount === 1 && !needStartArrayFormulaProgress) {
- needStartArrayFormulaProgress = true;
- if (startDependencyTimer) {
- arrayFormulaCalculationCount += totalArrayFormulasToCalculate;
- } else {
- // this._progressService.insertTaskCount(totalArrayFormulasToCalculate);
- }
- }
-
- if (startDependencyTimer) {
- this._arrayFormulaCalculationDoneCount = completedArrayFormulasCount;
- } else {
- debouncedArrayFormulaPushTask(completedArrayFormulasCount);
+ if (startDependencyTimer === null) {
+ this._startProgress();
}
}
-
- this._executionInProgressParams = params.stageInfo;
} else {
const state = params.functionsExecutedState;
let result = '';
@@ -356,13 +361,16 @@ export class TriggerCalculationController extends Disposable {
break;
case FormulaExecutedStateType.STOP_EXECUTION:
result = 'The execution of the formula has been stopped';
- // this._executingCommandQueue = [];
- // this._progressService.stop();
calculationProcessCount = 0;
break;
case FormulaExecutedStateType.SUCCESS:
- result = `Formula calculation succeeded, Total time consumed: ${performance.now() - this._startExecutionTime
- } ms`;
+ result = 'Formula calculation succeeded';
+
+ // When the calculation is stopped and then a successful calculation is triggered, the value is -1
+ if (calculationProcessCount === 0 || calculationProcessCount === -1) {
+ result += `. Total time consumed: ${performance.now() - this._startExecutionTime} ms`;
+ }
+
this._resetExecutingDirtyData();
break;
case FormulaExecutedStateType.INITIAL:
@@ -371,22 +379,22 @@ export class TriggerCalculationController extends Disposable {
break;
}
- if (calculationProcessCount === 0) {
+ // When the calculation is stopped and then a successful calculation is triggered, the value is -1
+ if (calculationProcessCount === 0 || calculationProcessCount === -1) {
if (startDependencyTimer) {
// The total calculation time does not exceed 1s, and the progress bar is not displayed.
clearTimeout(startDependencyTimer);
startDependencyTimer = null;
+ this.clearProgress();
} else {
// Manually hide the progress bar only if no other calculations are in process
- if (state === FormulaExecutedStateType.SUCCESS) {
- // this._progressService.complete();
- }
+ this._completeProgress();
}
- this._formulaCalculationDoneCount = 0;
- this._arrayFormulaCalculationDoneCount = 0;
- needStartFormulaProgress = false;
- needStartArrayFormulaProgress = false;
+ calculationProcessCount = 0;
+ this._doneCalculationTaskCount = 0;
+ this._totalCalculationTaskCount = 0;
+ this._forceCalculating = false;
}
if (state === FormulaExecutedStateType.STOP_EXECUTION && this._restartCalculation) {
@@ -402,7 +410,7 @@ export class TriggerCalculationController extends Disposable {
this._executionInProgressParams = null;
}
- console.warn(`execution result${result}`);
+ console.warn(`Execution result: ${result}`);
}
})
);
@@ -430,44 +438,4 @@ export class TriggerCalculationController extends Disposable {
lo
);
}
-
- /**
- * The user manually stops the progress bar
- */
- private _initialProgressBar() {
- // TODO: expose method to stop calculation
- // this.disposeWithMe(this._progressService.progressVisible$.subscribe((isVisible) => {
- // if (!isVisible) {
- // this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});
- // }
- // }));
- }
-
- /**
- * Update progress by completed count
- * @param completedCount
- */
- 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/sheets-formula/src/controllers/update-defined-name.controller.ts b/packages/sheets-formula/src/controllers/update-defined-name.controller.ts
index 268d3a813b..e95c2784b8 100644
--- a/packages/sheets-formula/src/controllers/update-defined-name.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-defined-name.controller.ts
@@ -23,7 +23,7 @@ import {
IUniverInstanceService,
UniverInstanceType,
} from '@univerjs/core';
-import { deserializeRangeWithSheet, ErrorType, generateStringWithSequence, IDefinedNamesService, LexerTreeBuilder, sequenceNodeType, serializeRangeToRefString, SetDefinedNameMutation } from '@univerjs/engine-formula';
+import { deserializeRangeWithSheetWithCache, ErrorType, generateStringWithSequence, IDefinedNamesService, LexerTreeBuilder, sequenceNodeType, serializeRangeToRefString, SetDefinedNameMutation } from '@univerjs/engine-formula';
import { RemoveDefinedNameCommand, SetDefinedNameCommand, SheetInterceptorService } from '@univerjs/sheets';
import { FormulaReferenceMoveType, type IFormulaReferenceMoveParam, updateRefOffset } from './utils/ref-range-formula';
import { getNewRangeByMoveParam } from './utils/ref-range-move';
@@ -115,7 +115,7 @@ export class UpdateDefinedNameController extends Disposable {
}
const { token } = node;
- const sequenceGrid = deserializeRangeWithSheet(token);
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;
const sequenceSheetId = workbook.getSheetBySheetName(sheetName)?.getSheetId() || '';
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index b4ca43b85c..add83a2d8d 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -40,7 +40,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
-import { deserializeRangeWithSheet,
+import { deserializeRangeWithSheetWithCache,
ErrorType,
FormulaDataModel,
generateStringWithSequence,
@@ -164,6 +164,7 @@ export class UpdateFormulaController extends Disposable {
this._formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, cellValue);
this._formulaDataModel.updateArrayFormulaRange(unitId, sheetId, cellValue);
+ // TODO@Dushusir: When the amount of data is large, the communication overhead is high. The main thread and the worker update their own models to reduce the communication overhead.
this._commandService.executeCommand(
SetFormulaDataMutation.id,
{
@@ -395,7 +396,7 @@ export class UpdateFormulaController extends Disposable {
continue;
}
- const sequenceGrid = deserializeRangeWithSheet(token);
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;
diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
index 61d45d7926..2882735b8b 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
@@ -17,7 +17,7 @@
import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { cellToRange, Direction, isFormulaId, isFormulaString, ObjectMatrix, Rectangle } from '@univerjs/core';
-import { deserializeRangeWithSheet, type IFormulaData, type IFormulaDataItem, type IRangeChange, type ISequenceNode, sequenceNodeType, serializeRangeToRefString } from '@univerjs/engine-formula';
+import { deserializeRangeWithSheetWithCache, type IFormulaData, type IFormulaDataItem, type IRangeChange, type ISequenceNode, sequenceNodeType, serializeRangeToRefString } from '@univerjs/engine-formula';
import { EffectRefRangId, handleDeleteRangeMoveLeft, handleDeleteRangeMoveUp, handleInsertCol, handleInsertRangeMoveDown, handleInsertRangeMoveRight, handleInsertRow, handleIRemoveCol, handleIRemoveRow, handleMoveCols, handleMoveRange, handleMoveRows, runRefRangeMutations, SetRangeValuesMutation } from '@univerjs/sheets';
import { checkFormulaDataNull } from './offset-formula-data';
@@ -633,7 +633,7 @@ export function updateRefOffset(
const { token } = node;
- const sequenceGrid = deserializeRangeWithSheet(token);
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;
diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.ts
index 4e1b72da87..9efd581387 100644
--- a/packages/sheets-formula/src/index.ts
+++ b/packages/sheets-formula/src/index.ts
@@ -17,6 +17,8 @@
export { type IInsertFunction, type IInsertFunctionCommandParams, InsertFunctionCommand } from './commands/commands/insert-function.command';
export { OtherFormulaMarkDirty } from './commands/mutations/formula.mutation';
export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';
+export { TriggerCalculationController } from './controllers/trigger-calculation.controller';
+
// #region - all commands
export { UpdateFormulaController } from './controllers/update-formula.controller';
diff --git a/packages/sheets-formula/src/services/formula-ref-range.service.ts b/packages/sheets-formula/src/services/formula-ref-range.service.ts
index 320b6ba8bb..8383638d35 100644
--- a/packages/sheets-formula/src/services/formula-ref-range.service.ts
+++ b/packages/sheets-formula/src/services/formula-ref-range.service.ts
@@ -17,7 +17,7 @@
import type { IDisposable, IMutationInfo, IRange, Workbook } from '@univerjs/core';
import type { EffectRefRangeParams } from '@univerjs/sheets';
import { Disposable, DisposableCollection, Inject, IUniverInstanceService, moveRangeByOffset, UniverInstanceType } from '@univerjs/core';
-import { deserializeRangeWithSheet, ErrorType, generateStringWithSequence, LexerTreeBuilder, sequenceNodeType, serializeRange, serializeRangeWithSheet, serializeRangeWithSpreadsheet } from '@univerjs/engine-formula';
+import { deserializeRangeWithSheetWithCache, ErrorType, generateStringWithSequence, LexerTreeBuilder, sequenceNodeType, serializeRange, serializeRangeWithSheet, serializeRangeWithSpreadsheet } from '@univerjs/engine-formula';
import { handleDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';
export type FormulaChangeMap = Record<string, Record<string, Record<string, string>>>;
@@ -50,7 +50,7 @@ export class FormulaRefRangeService extends Disposable {
const transformSequenceNodes = sequenceNodes?.map((node) => {
if (typeof node === 'object' && node.nodeType === sequenceNodeType.REFERENCE) {
- const gridRangeName = deserializeRangeWithSheet(node.token);
+ const gridRangeName = deserializeRangeWithSheetWithCache(node.token);
const { range, unitId: rangeUnitId, sheetName: rangeSheetName } = gridRangeName;
const workbook = this._univerInstanceService.getUnit<Workbook>(rangeUnitId || unitId);
const worksheet = rangeSheetName ? workbook?.getSheetBySheetName(rangeSheetName) : workbook?.getSheetBySheetId(subUnitId);
@@ -143,7 +143,7 @@ export class FormulaRefRangeService extends Disposable {
sequenceNodes?.forEach((node) => {
if (typeof node === 'object' && node.nodeType === sequenceNodeType.REFERENCE) {
- const gridRangeName = deserializeRangeWithSheet(node.token);
+ const gridRangeName = deserializeRangeWithSheetWithCache(node.token);
const { range, unitId: rangeUnitId, sheetName: rangeSheetName } = gridRangeName;
const workbook = this._univerInstanceService.getUnit<Workbook>(rangeUnitId || unitId);
const worksheet = rangeSheetName ? workbook?.getSheetBySheetName(rangeSheetName) : workbook?.getSheetBySheetId(subUnitId);
diff --git a/packages/sheets-ui/src/consts/ui-name.ts b/packages/sheets-ui/src/consts/ui-name.ts
index c19c165b49..0e0a7698b1 100644
--- a/packages/sheets-ui/src/consts/ui-name.ts
+++ b/packages/sheets-ui/src/consts/ui-name.ts
@@ -17,4 +17,5 @@
export enum SheetsUIPart {
FILTER_PANEL_EMBED_POINT = 'filter-panel-embed-point',
SHEETS_FOOTER = 'sheets-footer',
+ FORMULA_AUX = 'formula-aux',
}
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts
index 23223c0560..ad3d7d403b 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-base.controller.ts
@@ -23,7 +23,7 @@ import type { ISheetPasteParams } from '../../commands/commands/clipboard.comman
import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
import { CustomCommandExecutionError, Disposable, DisposableCollection, FOCUSING_EDITOR_STANDALONE, ICommandService, IContextService, Inject, IPermissionService, isICellData, IUniverInstanceService, LocaleService, ObjectMatrix, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';
import { IMEInputCommand, InsertCommand } from '@univerjs/docs-ui';
-import { deserializeRangeWithSheet, IDefinedNamesService, LexerTreeBuilder, operatorToken, sequenceNodeType } from '@univerjs/engine-formula';
+import { deserializeRangeWithSheet, deserializeRangeWithSheetWithCache, IDefinedNamesService, LexerTreeBuilder, operatorToken, sequenceNodeType } from '@univerjs/engine-formula';
import { UnitAction } from '@univerjs/protocol';
import { ClearSelectionContentCommand, DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeltaColumnWidthCommand, DeltaRowHeightCommand, getSheetCommandTarget, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, MoveColsCommand, MoveRangeCommand, MoveRowsCommand, RangeProtectionPermissionEditPoint, RangeProtectionPermissionViewPoint, RangeProtectionRuleModel, SetBackgroundColorCommand, SetColWidthCommand, SetRangeValuesCommand, SetRowHeightCommand, SetSelectedColsVisibleCommand, SetSelectedRowsVisibleCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetNameCommand, SetWorksheetNameMutation, SetWorksheetOrderCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetShowCommand, SheetsSelectionsService, WorkbookCopyPermission, WorkbookEditablePermission, WorkbookHideSheetPermission, WorkbookManageCollaboratorPermission, WorkbookMoveSheetPermission, WorkbookRenameSheetPermission, WorksheetCopyPermission, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetSetCellStylePermission, WorksheetSetCellValuePermission, WorksheetSetColumnStylePermission, WorksheetSetRowStylePermission, WorksheetViewPermission } from '@univerjs/sheets';
import { IDialogService } from '@univerjs/ui';
@@ -666,7 +666,7 @@ export class SheetPermissionInterceptorBaseController extends Disposable {
continue;
}
const { token } = node;
- const sequenceGrid = deserializeRangeWithSheet(token);
+ const sequenceGrid = deserializeRangeWithSheetWithCache(token);
const workbook = sequenceGrid.unitId ? this._univerInstanceService.getUnit<Workbook>(sequenceGrid.unitId) : this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
if (!workbook) return true;
let targetSheet: Nullable<Worksheet> = sequenceGrid.sheetName ? workbook.getSheetBySheetName(sequenceGrid.sheetName) : workbook.getActiveSheet();
diff --git a/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
index 483217a84f..65014a7af6 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/sheet.render-controller.ts
@@ -29,8 +29,8 @@ import {
SpreadsheetRowHeader,
Viewport,
} from '@univerjs/engine-render';
-import { COMMAND_LISTENER_SKELETON_CHANGE, COMMAND_LISTENER_VALUE_CHANGE, MoveRangeMutation, SetRangeValuesMutation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { COMMAND_LISTENER_SKELETON_CHANGE, COMMAND_LISTENER_VALUE_CHANGE, MoveRangeMutation, SetRangeValuesMutation, SetWorksheetActiveOperation } from '@univerjs/sheets';
import { ITelemetryService } from '@univerjs/telemetry';
import { Subject, withLatestFrom } from 'rxjs';
import {
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 1ebc8cae0c..71703b6ae7 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -15,19 +15,18 @@
*/
import type { IDocumentData, Nullable, Workbook } from '@univerjs/core';
-import { BooleanNumber, DEFAULT_EMPTY_DOCUMENT_VALUE, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DocumentFlavor, HorizontalAlign, IPermissionService, IUniverInstanceService, Rectangle, ThemeService, UniverInstanceType, useDependency, useObservable, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { BooleanNumber, DEFAULT_EMPTY_DOCUMENT_VALUE, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DocumentFlavor, HorizontalAlign, IPermissionService, IUniverInstanceService, Rectangle, UniverInstanceType, useDependency, useObservable, VerticalAlign, WrapStrategy } from '@univerjs/core';
import { TextEditor } from '@univerjs/docs-ui';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { CheckMarkSingle, CloseSingle, DropdownSingle, FxSingle } from '@univerjs/icons';
import { RangeProtectionPermissionEditPoint, RangeProtectionRuleModel, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetProtectionRuleModel, WorksheetSetCellValuePermission } from '@univerjs/sheets';
-import { KeyCode, ProgressBar } from '@univerjs/ui';
+import { ComponentContainer, KeyCode, useComponentsOfPart } from '@univerjs/ui';
import clsx from 'clsx';
-
import React, { useEffect, useLayoutEffect, useState } from 'react';
import { EMPTY, merge, switchMap } from 'rxjs';
import { useActiveWorkbook } from '../../components/hook';
+import { SheetsUIPart } from '../../consts/ui-name';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
-
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { DefinedName } from '../defined-name/DefinedName';
import styles from './index.module.less';
@@ -43,17 +42,18 @@ export function FormulaBar() {
const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
const editorBridgeService = useDependency(IEditorBridgeService);
- const themeService = useDependency(ThemeService);
- const progressBarColor = themeService.getCurrentTheme().primaryColor;
- const [disable, setDisable] = useState<boolean>(false);
- const univerInstanceService = useDependency(IUniverInstanceService);
- const selectionManager = useDependency(SheetsSelectionsService);
const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);
const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const selectionManager = useDependency(SheetsSelectionsService);
const permissionService = useDependency(IPermissionService);
+
+ const [disable, setDisable] = useState<boolean>(false);
const currentWorkbook = useActiveWorkbook();
const workbook = useObservable(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), undefined, undefined, [])!;
+ const formulaAuxUIParts = useComponentsOfPart(SheetsUIPart.FORMULA_AUX);
+
function getPermissionIds(unitId: string, subUnitId: string): string[] {
return [
new WorkbookEditablePermission(unitId).id,
@@ -257,7 +257,7 @@ export function FormulaBar() {
</div>
</div>
- <ProgressBar barColor={progressBarColor} />
+ <ComponentContainer key="formula-aux" components={formulaAuxUIParts}></ComponentContainer>
</div>
);
}
diff --git a/packages/ui/src/components/progress-bar/ProgressBar.tsx b/packages/ui/src/components/progress-bar/ProgressBar.tsx
index 76c5d38474..27bff5714f 100644
--- a/packages/ui/src/components/progress-bar/ProgressBar.tsx
+++ b/packages/ui/src/components/progress-bar/ProgressBar.tsx
@@ -14,58 +14,83 @@
* limitations under the License.
*/
-import { useDependency } from '@univerjs/core';
-import React, { useEffect, useRef, useState } from 'react';
+import { ThemeService, useDependency } from '@univerjs/core';
import { CloseSingle } from '@univerjs/icons';
-import type { IProgressStep } from '../../services/progress/progress.service';
-import { IProgressService } from '../../services/progress/progress.service';
+import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.less';
export interface IProgressBarProps {
- barColor: string;
+ progress: { done: number; count: number };
+ barColor?: string;
+ onTerminate?: () => void;
+ onClearProgress?: () => void; // Notify the parent component of the reset progress
}
export function ProgressBar(props: IProgressBarProps) {
- const { barColor } = props;
- const progressService = useDependency(IProgressService);
+ const { barColor, progress, onTerminate, onClearProgress } = props;
+ const { count, done } = progress;
+
+ const themeService = useDependency(ThemeService);
+ const color = barColor ?? themeService.getCurrentTheme().primaryColor; ;
+
const progressBarInnerRef = useRef<HTMLDivElement>(null);
- const [visible, setVisible] = useState(false);
+ // Introduce a state variable for visibility
+ const [visible, setVisible] = useState(count > 0);
+
+ const [prevCount, setPrevCount] = useState(0);
+ const [prevDone, setPrevDone] = useState(0);
useEffect(() => {
- const progressVisible = progressService.progressVisible$.subscribe((isVisible) => {
- if (!isVisible) {
- // Wait for the progress animation to complete before hiding the progress bar
- setTimeout(() => {
- setVisible(isVisible);
- if (progressBarInnerRef.current) {
- progressBarInnerRef.current.style.width = '0%';
- }
- }, 500);
- } else {
- setVisible(isVisible);
- }
- });
+ if (!progressBarInnerRef.current) return;
+
+ const progressBarInner = progressBarInnerRef.current;
- const progressChange = progressService.progressChange$.subscribe((task: IProgressStep) => {
- const { step } = task;
+ // Hide immediately if both count and done are zero
+ if (count === 0 && done === 0) {
+ setVisible(false);
+ }
+ // Handle the special case if count and done are equal for the first time and not from a previous progress change
+ else if (count === done && prevCount === 0 && prevDone === 0) {
+ setVisible(true);
+ progressBarInner.style.width = '0%';
+ requestAnimationFrame(() => {
+ progressBarInner.style.width = '100%';
+ });
+ }
+ // Update the width of the progress bar
+ else if (count > 0) {
+ setVisible(true);
+ progressBarInner.style.width = `${Math.floor((done / count) * 100)}%`;
+ }
+ // Else, wait for the transition to end before hiding
- // 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}%`;
+ // Listen for the transitionend event
+ const handleTransitionEnd = () => {
+ if ((count === 0 && done === 0) || done === count) {
+ // Hide the progress bar after the animation finishes
+ setVisible(false);
+ // Reset the width for future progress bars
+ progressBarInner.style.width = '0%';
+
+ // Notify the parent component to reset the progress after the animation ends
+ // After the progress bar is completed 100%, the upper props data source may not be reset, resulting in count and done still being the previous values (displaying 100%) when the progress bar is triggered next time, so a message is reported here to trigger clearing.
+ if (done === count && onClearProgress) {
+ onClearProgress();
+ }
}
- });
+ };
+
+ progressBarInner.addEventListener('transitionend', handleTransitionEnd);
+
+ // Update prevCount and prevDone
+ setPrevCount(count);
+ setPrevDone(done);
+ // Clean up the event listener on unmount or when dependencies change
return () => {
- progressVisible.unsubscribe();
- progressChange.unsubscribe();
+ progressBarInner.removeEventListener('transitionend', handleTransitionEnd);
};
- }, []);
-
- function handleClose() {
- progressService.stop();
- };
+ }, [count, done]);
return (
<div className={styles.progressBarContainer} style={{ display: visible ? 'flex' : 'none' }}>
@@ -74,12 +99,14 @@ export function ProgressBar(props: IProgressBarProps) {
ref={progressBarInnerRef}
className={styles.progressBarInner}
style={{
- backgroundColor: barColor,
+ backgroundColor: color,
}}
/>
</div>
- <div className={styles.progressBarCloseButton} onClick={handleClose}><CloseSingle /></div>
-
+ <div className={styles.progressBarCloseButton} onClick={onTerminate}>
+ {' '}
+ <CloseSingle />
+ </div>
</div>
);
};
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index c5a5e7a9bb..ea164f1a01 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -100,7 +100,6 @@ export { INotificationService } from './services/notification/notification.servi
export { BuiltInUIPart, IUIPartsService, UIPartsService } from './services/parts/parts.service';
export { IPlatformService, PlatformService } from './services/platform/platform.service';
export { CanvasPopupService, ICanvasPopupService, type IPopup } from './services/popup/canvas-popup.service';
-export { type IProgressCount, IProgressService, type IProgressStep, ProgressService } from './services/progress/progress.service';
export { KeyCode, MetaKeys } from './services/shortcut/keycode';
export { type IShortcutItem, IShortcutService, ShortcutService } from './services/shortcut/shortcut.service';
export { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';
diff --git a/packages/ui/src/mobile-ui-plugin.ts b/packages/ui/src/mobile-ui-plugin.ts
index 0c0fc1f49c..0d30ae5676 100644
--- a/packages/ui/src/mobile-ui-plugin.ts
+++ b/packages/ui/src/mobile-ui-plugin.ts
@@ -45,7 +45,6 @@ import { INotificationService } from './services/notification/notification.servi
import { IUIPartsService, UIPartsService } from './services/parts/parts.service';
import { IPlatformService, PlatformService } from './services/platform/platform.service';
import { CanvasPopupService, ICanvasPopupService } from './services/popup/canvas-popup.service';
-import { IProgressService, ProgressService } from './services/progress/progress.service';
import { IShortcutService, ShortcutService } from './services/shortcut/shortcut.service';
import { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';
import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';
@@ -94,7 +93,6 @@ export class UniverMobileUIPlugin extends Plugin {
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
[ICanvasPopupService, { useClass: CanvasPopupService }],
- [IProgressService, { useClass: ProgressService }],
[CanvasFloatDomService],
// controllers
diff --git a/packages/ui/src/services/__tests__/progress.service.spec.ts b/packages/ui/src/services/__tests__/progress.service.spec.ts
deleted file mode 100644
index 875265aeaa..0000000000
--- a/packages/ui/src/services/__tests__/progress.service.spec.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * 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) => { /* empty */ },
- complete: () => {
- changeCompleted = true;
- },
- });
-
- const visibleSubscription = result.current.progressVisible$.subscribe({
- next: (visible) => { /* empty */ },
- 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/parts/parts.service.ts b/packages/ui/src/services/parts/parts.service.ts
index faff3d8b15..a0b078488f 100644
--- a/packages/ui/src/services/parts/parts.service.ts
+++ b/packages/ui/src/services/parts/parts.service.ts
@@ -15,11 +15,10 @@
*/
import type { IDisposable } from '@univerjs/core';
+import type { ComponentType } from '../../common/component-manager';
import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';
import { type Observable, Subject } from 'rxjs';
-import type { ComponentType } from '../../common/component-manager';
-
type ComponentRenderer = () => ComponentType;
type ComponentPartKey = BuiltInUIPart | string;
diff --git a/packages/ui/src/services/progress/progress.service.ts b/packages/ui/src/services/progress/progress.service.ts
deleted file mode 100644
index 999e5bdb16..0000000000
--- a/packages/ui/src/services/progress/progress.service.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-/**
- * 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 type { IDisposable } from '@univerjs/core';
-import type { Observable } from 'rxjs';
-import { createIdentifier, Disposable } from '@univerjs/core';
-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
- this._progress$.complete();
- */
- 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;
-
- /**
- * Get the total number of tasks
- */
- getTaskCount(): number;
-}
-
-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);
- }
-
- getTaskCount(): number {
- return this._taskCount;
- }
-
- 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 7bde95ecd6..785464588d 100644
--- a/packages/ui/src/ui-plugin.ts
+++ b/packages/ui/src/ui-plugin.ts
@@ -50,7 +50,6 @@ import { INotificationService } from './services/notification/notification.servi
import { IUIPartsService, UIPartsService } from './services/parts/parts.service';
import { IPlatformService, PlatformService } from './services/platform/platform.service';
import { CanvasPopupService, ICanvasPopupService } from './services/popup/canvas-popup.service';
-import { IProgressService, ProgressService } from './services/progress/progress.service';
import { IShortcutService, ShortcutService } from './services/shortcut/shortcut.service';
import { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';
import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';
@@ -112,7 +111,6 @@ export class UniverUIPlugin extends Plugin {
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
[ILocalFileService, { useClass: DesktopLocalFileService }],
[ICanvasPopupService, { useClass: CanvasPopupService }],
- [IProgressService, { useClass: ProgressService }],
[CanvasFloatDomService],
[IUIController, {
useFactory: (injector: Injector) => injector.createInstance(DesktopUIController, this._config),