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.

refactor(formula): rationalize architecture (#690)

Univerc7c6821fb008
diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.ts
index 3b614f27a0..62f0ea83ac 100644
--- a/packages/engine-formula/src/controller/calculate.controller.ts
+++ b/packages/engine-formula/src/controller/calculate.controller.ts
@@ -16,7 +16,7 @@ import type { ISetFormulaDataMutationParams } from '../commands/mutations/set-fo
import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';
import { FormulaDataModel } from '../models/formula-data.model';
import { IActiveDirtyManagerService } from '../services/active-dirty-manager.service';
-import { FormulaEngineService } from '../services/formula-engine.service';
+import { CalculateFormulaService } from '../services/calculate-formula.service';
import type { IAllRuntimeData } from '../services/runtime.service';
import { FormulaExecutedStateType } from '../services/runtime.service';
@@ -24,7 +24,7 @@ import { FormulaExecutedStateType } from '../services/runtime.service';
export class CalculateController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(CalculateFormulaService) private readonly _calculateFormulaService: CalculateFormulaService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService
@@ -45,7 +45,7 @@ export class CalculateController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo, options) => {
if (command.id === SetFormulaCalculationStopMutation.id) {
- this._formulaEngineService.stopFormulaExecution();
+ this._calculateFormulaService.stopFormulaExecution();
} else if (command.id === SetFormulaDataMutation.id) {
const formulaData = (command.params as ISetFormulaDataMutationParams).formulaData as IFormulaData;
this._formulaDataModel.setFormulaData(formulaData);
@@ -162,7 +162,7 @@ export class CalculateController extends Disposable {
// Synchronous to the main thread
// this._commandService.executeCommand(SetFormulaDataMutation.id, { formulaData });
- this._formulaEngineService.execute({
+ this._calculateFormulaService.execute({
formulaData,
arrayFormulaCellData,
forceCalculate,
@@ -177,7 +177,7 @@ export class CalculateController extends Disposable {
/**
* Assignment operation after formula calculation.
*/
- this._formulaEngineService.executionCompleteListener$.subscribe((data) => {
+ this._calculateFormulaService.executionCompleteListener$.subscribe((data) => {
const functionsExecutedState = data.functionsExecutedState;
switch (functionsExecutedState) {
case FormulaExecutedStateType.NOT_EXECUTED:
@@ -207,7 +207,7 @@ export class CalculateController extends Disposable {
/**
* Assignment operation after formula calculation.
*/
- this._formulaEngineService.executionInProgressListener$.subscribe((data) => {
+ this._calculateFormulaService.executionInProgressListener$.subscribe((data) => {
const {
totalFormulasToCalculate,
completedFormulasCount,
diff --git a/packages/engine-formula/src/controller/formula.controller.ts b/packages/engine-formula/src/controller/formula.controller.ts
index 60bf629357..e89a782470 100644
--- a/packages/engine-formula/src/controller/formula.controller.ts
+++ b/packages/engine-formula/src/controller/formula.controller.ts
@@ -1,5 +1,8 @@
import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { Ctor } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { FUNCTION_NAMES } from '../basics/function';
import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
import {
SetFormulaCalculationNotificationMutation,
@@ -8,10 +11,48 @@ import {
SetFormulaCalculationStopMutation,
} from '../commands/mutations/set-formula-calculation.mutation';
import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';
+import {
+ Average,
+ Compare,
+ Concatenate,
+ Count,
+ Divided,
+ Indirect,
+ Max,
+ Min,
+ Minus,
+ Multiply,
+ Offset,
+ Plus,
+ Power,
+ Sum,
+ Union,
+} from '../functions';
+import { functionArray } from '../functions/array/function-names';
+import type { BaseFunction } from '../functions/base-function';
+import { functionCompatibility } from '../functions/compatibility/function-names';
+import { functionCube } from '../functions/cube/function-names';
+import { functionDatabase } from '../functions/database/function-names';
+import { functionDate } from '../functions/date/function-names';
+import { functionEngineering } from '../functions/engineering/function-names';
+import { functionFinancial } from '../functions/financial/function-names';
+import { functionInformation } from '../functions/information/function-names';
+import { functionLogical } from '../functions/logical/function-names';
+import { functionLookup } from '../functions/lookup/function-names';
+import { functionMath } from '../functions/math/function-names';
+import { functionStatistical } from '../functions/statistical/function-names';
+import { functionText } from '../functions/text/function-names';
+import { functionUniver } from '../functions/univer/function-names';
+import { functionWeb } from '../functions/web/function-names';
+import { IFunctionService } from '../services/function.service';
@OnLifecycle(LifecycleStages.Ready, FormulaController)
export class FormulaController extends Disposable {
- constructor(@ICommandService private readonly _commandService: ICommandService) {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(Injector) private readonly _injector: Injector,
+ @IFunctionService private readonly _functionService: IFunctionService
+ ) {
super();
this._initialize();
@@ -19,6 +60,10 @@ export class FormulaController extends Disposable {
private _initialize(): void {
this._registerCommands();
+
+ this._registerFunctions();
+
+ this._initializeFunctions();
}
private _registerCommands(): void {
@@ -31,4 +76,62 @@ export class FormulaController extends Disposable {
SetFormulaCalculationResultMutation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
+
+ private _registerFunctions() {
+ const functions: BaseFunction[] = [
+ ...functionArray,
+ ...functionCompatibility,
+ ...functionCube,
+ ...functionDatabase,
+ ...functionDate,
+ ...functionEngineering,
+ ...functionFinancial,
+ ...functionInformation,
+ ...functionLogical,
+ ...functionLookup,
+ ...functionMath,
+ ...functionStatistical,
+ ...functionText,
+ ...functionUniver,
+ ...functionWeb,
+ ].map((registerObject) => {
+ const Func = registerObject[0] as Ctor<BaseFunction>;
+ const name = registerObject[1] as string;
+
+ return new Func(this._injector, name);
+ });
+
+ this._functionService.registerExecutors(...functions);
+ }
+
+ private _initializeFunctions() {
+ // new Sum(this._injector, FUNCTION_NAMES.SUM)
+ const functions: BaseFunction[] = [
+ // base function
+ [Compare, FUNCTION_NAMES.COMPARE],
+ [Divided, FUNCTION_NAMES.DIVIDED],
+ [Minus, FUNCTION_NAMES.MINUS],
+ [Multiply, FUNCTION_NAMES.MULTIPLY],
+ [Plus, FUNCTION_NAMES.PLUS],
+ [Union, FUNCTION_NAMES.UNION],
+
+ // static
+ [Average, FUNCTION_NAMES.AVERAGE],
+ [Concatenate, FUNCTION_NAMES.CONCATENATE],
+ [Count, FUNCTION_NAMES.COUNT],
+ [Indirect, FUNCTION_NAMES.INDIRECT],
+ [Max, FUNCTION_NAMES.MAX],
+ [Min, FUNCTION_NAMES.MIN],
+ [Offset, FUNCTION_NAMES.OFFSET],
+ [Power, FUNCTION_NAMES.POWER],
+ [Sum, FUNCTION_NAMES.SUM],
+ ].map((registerObject) => {
+ const Func = registerObject[0] as Ctor<BaseFunction>;
+ const name = registerObject[1] as string;
+
+ return new Func(this._injector, name);
+ });
+
+ this._functionService.registerExecutors(...functions);
+ }
}
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 56bbe1390a..bfc97110f1 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -7,6 +7,7 @@ import type { IDirtyUnitSheetNameMap, IFormulaData, IOtherFormulaData } from '..
import { ErrorType } from '../../basics/error-type';
import { prefixToken, suffixToken } from '../../basics/token';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
+import { IOtherFormulaManagerService } from '../../services/other-formula-manager.service';
import {
IPassiveDirtyManagerService,
type PassiveDirtyManagerService,
@@ -37,6 +38,7 @@ export class FormulaDependencyGenerator extends Disposable {
constructor(
@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,
@IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,
+ @IOtherFormulaManagerService private readonly _otherFormulaManagerService: IOtherFormulaManagerService,
@IPassiveDirtyManagerService
private readonly _passiveDirtyManagerService: PassiveDirtyManagerService,
@Inject(Interpreter) private readonly _interpreter: Interpreter,
@@ -59,7 +61,7 @@ export class FormulaDependencyGenerator extends Disposable {
const formulaData = this._currentConfigService.getFormulaData();
- const otherFormulaData = this._currentConfigService.getOtherFormulaData();
+ const otherFormulaData = this._otherFormulaManagerService.getOtherFormulaData();
const treeList = await this._generateTreeList(formulaData, otherFormulaData);
diff --git a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
index 6e72b3fde3..feff992b19 100644
--- a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
+++ b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts
@@ -3,12 +3,26 @@ import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Plug
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { CalculateController } from '../../controller/calculate.controller';
-import { FormulaController } from '../../controller/formula.controller';
-import { FormulaDataModel } from '../../models/formula-data.model';
-import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../../services/active-dirty-manager.service';
-import { FormulaService, IFormulaService } from '../../services/formula.service';
-import { FormulaEngineService } from '../../services/formula-engine.service';
+import { LexerTreeBuilder } from '../../engine/analysis/lexer';
+import { AstTreeBuilder } from '../../engine/analysis/parser';
+import { AstRootNodeFactory } from '../../engine/ast-node/ast-root-node';
+import { FunctionNodeFactory } from '../../engine/ast-node/function-node';
+import { LambdaNodeFactory } from '../../engine/ast-node/lambda-node';
+import { LambdaParameterNodeFactory } from '../../engine/ast-node/lambda-parameter-node';
+import { OperatorNodeFactory } from '../../engine/ast-node/operator-node';
+import { PrefixNodeFactory } from '../../engine/ast-node/prefix-node';
+import { ReferenceNodeFactory } from '../../engine/ast-node/reference-node';
+import { SuffixNodeFactory } from '../../engine/ast-node/suffix-node';
+import { UnionNodeFactory } from '../../engine/ast-node/union-node';
+import { ValueNodeFactory } from '../../engine/ast-node/value-node';
+import { FormulaDependencyGenerator } from '../../engine/dependency/formula-dependency';
+import { Interpreter } from '../../engine/interpreter/interpreter';
+import type { FormulaDataModel } from '../../models/formula-data.model';
+import { CalculateFormulaService } from '../../services/calculate-formula.service';
+import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../services/current-data.service';
+import { FunctionService, IFunctionService } from '../../services/function.service';
+import { IOtherFormulaManagerService, OtherFormulaManagerService } from '../../services/other-formula-manager.service';
+import { FormulaRuntimeService, IFormulaRuntimeService } from '../../services/runtime.service';
const TEST_WORKBOOK_DATA: IWorkbookData = {
id: 'test',
@@ -69,14 +83,28 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
}
override onStarting(injector: Injector): void {
- injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);
- injector.add([FormulaEngineService]);
- this._formulaDataModel = this._injector.createInstance(FormulaDataModel);
-
- injector.add([FormulaDataModel, { useValue: this._formulaDataModel }]);
- injector.add([FormulaController]);
- injector.add([IFormulaService, { useClass: FormulaService }]);
- injector.add([CalculateController]);
+ injector.add([CalculateFormulaService]);
+ injector.add([LexerTreeBuilder]);
+
+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);
+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);
+ injector.add([IFunctionService, { useClass: FunctionService }]);
+ injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);
+
+ injector.add([FormulaDependencyGenerator]);
+ injector.add([Interpreter]);
+ injector.add([AstTreeBuilder]);
+
+ injector.add([AstRootNodeFactory]);
+ injector.add([FunctionNodeFactory]);
+ injector.add([LambdaNodeFactory]);
+ injector.add([LambdaParameterNodeFactory]);
+ injector.add([OperatorNodeFactory]);
+ injector.add([PrefixNodeFactory]);
+ injector.add([ReferenceNodeFactory]);
+ injector.add([SuffixNodeFactory]);
+ injector.add([UnionNodeFactory]);
+ injector.add([ValueNodeFactory]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts b/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts
index 140b7445a6..8c81f58e98 100644
--- a/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts
+++ b/packages/engine-formula/src/functions/math/sumif/__tests__/sumif.spec.ts
@@ -3,14 +3,16 @@ import { ICommandService, IUniverInstanceService } from '@univerjs/core';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, it } from 'vitest';
-import type { FormulaEngineService } from '../../../../services/formula-engine.service';
+import type { LexerTreeBuilder } from '../../../../engine/analysis/lexer';
+import type { CalculateFormulaService } from '../../../../services/calculate-formula.service';
import { createCommandTestBed } from '../../../__tests__/create-command-test-bed';
describe('test sumif', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
- let formulaEngineService: FormulaEngineService;
+ let calculateFormulaService: CalculateFormulaService;
+ let lexerTreeBuilder: LexerTreeBuilder;
let getValue: (
startRow: number,
startColumn: number,
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 4cc610f62b..e8e65d1953 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -35,6 +35,7 @@ export {
type ISetFormulaDataMutationParams,
SetFormulaDataMutation,
} from './commands/mutations/set-formula-data.mutation';
+export { LexerTreeBuilder } from './engine/analysis/lexer';
export { LexerNode } from './engine/analysis/lexer-node';
export { ErrorValueObject } from './engine/other-object/error-value-object';
export { BaseReferenceObject, type FunctionVariantType } from './engine/reference-object/base-reference-object';
@@ -51,8 +52,10 @@ export { FormulaDataModel } from './models/formula-data.model';
export { initSheetFormulaData } from './models/formula-data.model';
export { BaseFormulaEnginePlugin } from './plugin';
export { IActiveDirtyManagerService } from './services/active-dirty-manager.service';
-export { FormulaEngineService } from './services/formula-engine.service';
+export { CalculateFormulaService } from './services/calculate-formula.service';
+export { FunctionService } from './services/function.service';
export { IFunctionService } from './services/function.service';
+export { type IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';
export { IPassiveDirtyManagerService, PassiveDirtyManagerService } from './services/passive-dirty-manager.service';
export { FormulaExecuteStageType, type IExecutionInProgressParams } from './services/runtime.service';
export { FormulaExecutedStateType, type IAllRuntimeData } from './services/runtime.service';
diff --git a/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
index 6dbb8c09a5..868a7c8487 100644
--- a/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
+++ b/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts
@@ -3,7 +3,8 @@ import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Plug
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { FormulaEngineService } from '../../services/formula-engine.service';
+import { LexerTreeBuilder } from '../../engine/analysis/lexer';
+import { CalculateFormulaService } from '../../services/calculate-formula.service';
import { FormulaDataModel } from '../formula-data.model';
const TEST_WORKBOOK_DATA: IWorkbookData = {
@@ -51,9 +52,9 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
}
override onStarting(injector: Injector): void {
- injector.add([FormulaEngineService]);
+ injector.add([CalculateFormulaService]);
injector.add([FormulaDataModel]);
-
+ injector.add([LexerTreeBuilder]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 44b03139aa..3cb0390cda 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -1,12 +1,5 @@
import type { ICellData, IRange, Nullable, ObjectMatrixPrimitiveType } from '@univerjs/core';
-import {
- Disposable,
- ICommandService,
- isFormulaId,
- isFormulaString,
- IUniverInstanceService,
- ObjectMatrix,
-} from '@univerjs/core';
+import { Disposable, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import type {
@@ -19,7 +12,7 @@ import type {
IUnitData,
IUnitSheetNameMap,
} from '../basics/common';
-import { FormulaEngineService } from '../services/formula-engine.service';
+import { LexerTreeBuilder } from '../engine/analysis/lexer';
export class FormulaDataModel extends Disposable {
private _formulaData: IFormulaData = {};
@@ -30,8 +23,7 @@ export class FormulaDataModel extends Disposable {
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder
) {
super();
}
@@ -317,7 +309,7 @@ export class FormulaDataModel extends Disposable {
} else if (typeof deleteFormula === 'string') {
const x = cell.x || 0;
const y = cell.y || 0;
- const offsetFormula = this._formulaEngineService.moveFormulaRefOffset(deleteFormula, x, y);
+ const offsetFormula = this._lexerTreeBuilder.moveFormulaRefOffset(deleteFormula, x, y);
deleteFormulaIdMap.set(formulaId, {
r,
c,
diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.ts
index ff6111b127..c42c0472cc 100644
--- a/packages/engine-formula/src/plugin.ts
+++ b/packages/engine-formula/src/plugin.ts
@@ -4,11 +4,30 @@ import { Inject, Injector } from '@wendellhu/redi';
import { CalculateController } from './controller/calculate.controller';
import { FormulaController } from './controller/formula.controller';
+import { LexerTreeBuilder } from './engine/analysis/lexer';
+import { AstTreeBuilder } from './engine/analysis/parser';
+import { AstRootNodeFactory } from './engine/ast-node/ast-root-node';
+import { FunctionNodeFactory } from './engine/ast-node/function-node';
+import { LambdaNodeFactory } from './engine/ast-node/lambda-node';
+import { LambdaParameterNodeFactory } from './engine/ast-node/lambda-parameter-node';
+import { OperatorNodeFactory } from './engine/ast-node/operator-node';
+import { PrefixNodeFactory } from './engine/ast-node/prefix-node';
+import { ReferenceNodeFactory } from './engine/ast-node/reference-node';
+import { SuffixNodeFactory } from './engine/ast-node/suffix-node';
+import { UnionNodeFactory } from './engine/ast-node/union-node';
+import { ValueNodeFactory } from './engine/ast-node/value-node';
+import { FormulaDependencyGenerator } from './engine/dependency/formula-dependency';
+import { Interpreter } from './engine/interpreter/interpreter';
import { FormulaDataModel } from './models/formula-data.model';
import { ActiveDirtyManagerService, IActiveDirtyManagerService } from './services/active-dirty-manager.service';
-import { FormulaService, IFormulaService } from './services/formula.service';
-import { FormulaEngineService } from './services/formula-engine.service';
+import { CalculateFormulaService } from './services/calculate-formula.service';
+import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from './services/current-data.service';
+import { DefinedNamesService, IDefinedNamesService } from './services/defined-names.service';
+import { FunctionService, IFunctionService } from './services/function.service';
+import { IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';
import { IPassiveDirtyManagerService, PassiveDirtyManagerService } from './services/passive-dirty-manager.service';
+import { FormulaRuntimeService, IFormulaRuntimeService } from './services/runtime.service';
+import { ISuperTableService, SuperTableService } from './services/super-table.service';
const PLUGIN_NAME = 'base-formula-engine';
@@ -17,8 +36,6 @@ interface IBaseFormulaEnginePlugin {
}
export class BaseFormulaEnginePlugin extends Plugin {
- private _formulaDataModel: FormulaDataModel | null = null;
-
constructor(
private _config: IBaseFormulaEnginePlugin,
@Inject(Injector) protected override _injector: Injector
@@ -35,11 +52,9 @@ export class BaseFormulaEnginePlugin extends Plugin {
const dependencies: Dependency[] = [
// Services
- [FormulaEngineService],
+ [LexerTreeBuilder],
+ [IFunctionService, { useClass: FunctionService }],
[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],
- [IPassiveDirtyManagerService, { useClass: PassiveDirtyManagerService }],
- // [IFormulaService, { useClass: FormulaService }],
-
// Models
[FormulaDataModel],
@@ -49,8 +64,34 @@ export class BaseFormulaEnginePlugin extends Plugin {
if (!this._config?.notExecuteFormula) {
// only worker
- dependencies.push([IFormulaService, { useClass: FormulaService }]);
- dependencies.push([CalculateController]);
+ dependencies.push(
+ // Services
+ [CalculateFormulaService],
+ [CalculateController],
+ [IPassiveDirtyManagerService, { useClass: PassiveDirtyManagerService }],
+ [IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],
+ [ISuperTableService, { useClass: SuperTableService }],
+ [IDefinedNamesService, { useClass: DefinedNamesService }],
+ [IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],
+ [IFormulaRuntimeService, { useClass: FormulaRuntimeService }],
+
+ // Calculation engine
+ [FormulaDependencyGenerator],
+ [Interpreter],
+ [AstTreeBuilder],
+
+ // AstNode factory
+ [AstRootNodeFactory],
+ [FunctionNodeFactory],
+ [LambdaNodeFactory],
+ [LambdaParameterNodeFactory],
+ [OperatorNodeFactory],
+ [PrefixNodeFactory],
+ [ReferenceNodeFactory],
+ [SuffixNodeFactory],
+ [UnionNodeFactory],
+ [ValueNodeFactory]
+ );
}
dependencies.forEach((dependency) => this._injector.add(dependency));
@@ -58,9 +99,5 @@ export class BaseFormulaEnginePlugin extends Plugin {
override onReady(): void {
this._injector.get(FormulaDataModel).initFormulaData();
-
- if (!this._config?.notExecuteFormula) {
- this._injector.get(IFormulaService).registerFunctions();
- }
}
}
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
new file mode 100644
index 0000000000..8cab32eb61
--- /dev/null
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -0,0 +1,336 @@
+import type { IUnitRange } from '@univerjs/core';
+import {
+ Disposable,
+ IConfigService,
+ LifecycleStages,
+ ObjectMatrix,
+ OnLifecycle,
+ requestImmediateMacroTask,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Subject } from 'rxjs';
+
+import type {
+ IArrayFormulaRangeType,
+ IFeatureDirtyRangeType,
+ IFormulaDatasetConfig,
+ IRuntimeUnitDataType,
+ IUnitExcludedCell,
+} from '../basics/common';
+import { ErrorType } from '../basics/error-type';
+import { LexerTreeBuilder } from '../engine/analysis/lexer';
+import type { LexerNode } from '../engine/analysis/lexer-node';
+import { AstTreeBuilder } from '../engine/analysis/parser';
+import { ErrorNode } from '../engine/ast-node/base-ast-node';
+import { FormulaDependencyGenerator } from '../engine/dependency/formula-dependency';
+import { Interpreter } from '../engine/interpreter/interpreter';
+import type { FunctionVariantType } from '../engine/reference-object/base-reference-object';
+import { IFormulaCurrentConfigService } from './current-data.service';
+import type { IAllRuntimeData, IExecutionInProgressParams } from './runtime.service';
+import { FormulaExecuteStageType, IFormulaRuntimeService } from './runtime.service';
+
+export const DEFAULT_CYCLE_REFERENCE_COUNT = 1;
+
+export const CYCLE_REFERENCE_COUNT = 'cycleReferenceCount';
+
+export const EVERY_N_FUNCTION_EXECUTION_PAUSE = 100;
+
+@OnLifecycle(LifecycleStages.Rendered, CalculateFormulaService)
+export class CalculateFormulaService extends Disposable {
+ private readonly _executionStartListener$ = new Subject<boolean>();
+
+ readonly executionStartListener$ = this._executionStartListener$.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(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
+ @IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,
+ @IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,
+ @Inject(FormulaDependencyGenerator) private readonly _formulaDependencyGenerator: FormulaDependencyGenerator,
+ @Inject(Interpreter) private readonly _interpreter: Interpreter,
+ @Inject(AstTreeBuilder) private readonly _astTreeBuilder: AstTreeBuilder
+ ) {
+ super();
+ }
+
+ override dispose(): void {}
+
+ /**
+ * Stop the execution of the formula.
+ */
+ stopFormulaExecution() {
+ this._runtimeService.stopExecution();
+ }
+
+ /**
+ * When the feature is loading,
+ * the pre-calculated content needs to be input to the formula engine in advance,
+ * so that the formula can read the correct values.
+ * @param featureId
+ * @param featureData
+ */
+ setRuntimeFeatureCellData(featureId: string, featureData: IRuntimeUnitDataType) {
+ this._runtimeService.setRuntimeFeatureCellData(featureId, featureData);
+ }
+
+ setRuntimeFeatureRange(featureId: string, featureRange: IFeatureDirtyRangeType) {
+ this._runtimeService.setRuntimeFeatureRange(featureId, featureRange);
+ }
+
+ /**
+ *
+ * @param unitId
+ * @param formulaData
+ * @param interpreterDatasetConfig
+ * @param forceCalculate force calculate all formula, and ignore dependency relationship
+ * @param dirtyRanges input external unit data for multi workbook
+ * @returns
+ */
+ async execute(formulaDatasetConfig: IFormulaDatasetConfig) {
+ this._executionStartListener$.next(true);
+
+ this._currentConfigService.load(formulaDatasetConfig);
+
+ this._runtimeService.reset();
+
+ const cycleReferenceCount = (this._configService.getConfig('CYCLE_REFERENCE_COUNT') ||
+ DEFAULT_CYCLE_REFERENCE_COUNT) as number;
+
+ for (let i = 0; i < cycleReferenceCount; i++) {
+ await this._execute();
+ const isCycleDependency = this._runtimeService.isCycleDependency();
+ if (!isCycleDependency) {
+ break;
+ }
+ }
+
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED);
+
+ this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
+
+ this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());
+ }
+
+ private async _execute() {
+ const executeState = await this._apply();
+
+ if (executeState == null) {
+ return;
+ }
+
+ const { arrayFormulaRange, runtimeFeatureRange } = executeState;
+
+ const { dirtyRanges, excludedCell } = this._getArrayFormulaDirtyRangeAndExcludedRange(
+ arrayFormulaRange,
+ runtimeFeatureRange
+ );
+
+ if (dirtyRanges == null || dirtyRanges.length === 0) {
+ return true;
+ }
+
+ this._currentConfigService.loadDirtyRangesAndExcludedCell(dirtyRanges, excludedCell);
+
+ await this._apply(true);
+
+ return true;
+ }
+
+ private _getArrayFormulaDirtyRangeAndExcludedRange(
+ arrayFormulaRange: IArrayFormulaRangeType,
+ runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType }
+ ) {
+ const dirtyRanges: IUnitRange[] = [];
+ const excludedCell: IUnitExcludedCell = {};
+ Object.keys(arrayFormulaRange).forEach((unitId) => {
+ const sheetArrayFormulaRange = arrayFormulaRange[unitId];
+ Object.keys(sheetArrayFormulaRange).forEach((sheetId) => {
+ const cellValue = new ObjectMatrix(sheetArrayFormulaRange[sheetId]);
+
+ if (cellValue == null) {
+ return true;
+ }
+
+ const newCellData = new ObjectMatrix<boolean>();
+
+ cellValue.forValue((row, column, range) => {
+ newCellData.setValue(row, column, true);
+
+ dirtyRanges.push({ unitId, sheetId, range });
+ });
+
+ if (excludedCell[unitId] == null) {
+ excludedCell[unitId] = {};
+ }
+
+ excludedCell[unitId][sheetId] = newCellData;
+ });
+ });
+
+ Object.keys(runtimeFeatureRange).forEach((featureId) => {
+ const arrayRange = runtimeFeatureRange[featureId];
+ Object.keys(arrayRange).forEach((unitId) => {
+ const sheetArrayFormulaRange = arrayRange[unitId];
+ Object.keys(sheetArrayFormulaRange).forEach((sheetId) => {
+ const ranges = sheetArrayFormulaRange[sheetId];
+
+ if (ranges == null) {
+ return true;
+ }
+
+ for (const range of ranges) {
+ dirtyRanges.push({ unitId, sheetId, range });
+ }
+ });
+ });
+ });
+
+ return { dirtyRanges, excludedCell };
+ }
+
+ private async _apply(isArrayFormulaState = false) {
+ if (isArrayFormulaState) {
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA);
+ } else {
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY);
+ }
+
+ this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
+
+ const treeList = await this._formulaDependencyGenerator.generate();
+
+ const interpreter = this._interpreter;
+
+ if (isArrayFormulaState) {
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_CALCULATION_ARRAY_FORMULA);
+
+ this._runtimeService.setTotalArrayFormulasToCalculate(treeList.length);
+ } else {
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_CALCULATION);
+
+ this._runtimeService.setTotalFormulasToCalculate(treeList.length);
+ }
+
+ this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
+
+ for (let i = 0, len = treeList.length; i < len; i++) {
+ /**
+ * For every functions, execute a setTimeout to wait for external command input.
+ */
+ await new Promise((resolve) => {
+ requestImmediateMacroTask(resolve);
+ });
+
+ if (this._runtimeService.isStopExecution()) {
+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
+ this._runtimeService.markedAsStopFunctionsExecuted();
+ this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());
+ return;
+ }
+
+ const tree = treeList[i];
+ const astNode = tree.node;
+ const getDirtyData = tree.getDirtyData;
+ let value: FunctionVariantType;
+
+ if (astNode == null && getDirtyData == null) {
+ throw new Error('AstNode or executor is null');
+ }
+
+ this._runtimeService.setCurrent(tree.row, tree.column, tree.subComponentId, tree.unitId);
+
+ if (getDirtyData != null && tree.featureId != null) {
+ /**
+ * Execute the dependencies registered by the feature,
+ * and return the dirty area marked by the feature,
+ * so as to allow the formulas depending on the dirty area to continue the calculation.
+ */
+ const { runtimeCellData, dirtyRanges } = getDirtyData(tree);
+
+ this._runtimeService.setRuntimeFeatureCellData(tree.featureId, runtimeCellData);
+
+ this._runtimeService.setRuntimeFeatureRange(tree.featureId, dirtyRanges);
+ } else if (astNode != null) {
+ if (interpreter.checkAsyncNode(astNode)) {
+ value = await interpreter.executeAsync(astNode);
+ } else {
+ value = interpreter.execute(astNode);
+ }
+
+ if (tree.formulaId != null) {
+ this._runtimeService.setRuntimeOtherData(tree.formulaId, value);
+ } else {
+ 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());
+ }
+
+ if (treeList.length > 0) {
+ this._runtimeService.markedAsSuccessfullyExecuted();
+ } else if (!isArrayFormulaState) {
+ this._runtimeService.markedAsNoFunctionsExecuted();
+ }
+
+ return this._runtimeService.getAllRuntimeData();
+ }
+
+ calculate(formulaString: string, transformSuffix: boolean = true) {
+ // TODO how to observe @alex
+ // this.getObserver('onBeforeFormulaCalculateObservable')?.notifyObservers(formulaString);
+ const lexerNode = this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix);
+
+ if (Object.values(ErrorType).includes(lexerNode as ErrorType)) {
+ return ErrorNode.create(lexerNode as ErrorType);
+ }
+
+ // this.lexerTreeBuilder.suffixExpressionHandler(lexerNode); // suffix Express, 1+(3*4=4)*5+1 convert to 134*4=5*1++
+
+ // console.log('sequence', this.lexerTreeBuilder.sequenceNodesBuilder(formulaString));
+
+ // this.getObserver('onAfterFormulaLexerObservable')?.notifyObservers(lexerNode);
+
+ // const astTreeBuilder = new AstTreeBuilder();
+
+ const astNode = this._astTreeBuilder.parse(lexerNode as LexerNode);
+
+ console.log('astNode', astNode?.serialize());
+
+ // const interpreter = Interpreter.create();
+
+ // if (astNode == null) {
+ // return;
+ // }
+
+ // if (interpreter.checkAsyncNode(astNode)) {
+ // const resultPromise = interpreter.executeAsync(astNode);
+
+ // resultPromise.then((value) => {
+ // console.log('formulaResult', value);
+ // });
+ // } else {
+ // console.log(interpreter.execute(astNode));
+ // }
+ }
+}
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 9e33d3e0f3..342a759856 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -8,7 +8,6 @@ import type {
IDirtyUnitSheetNameMap,
IFormulaData,
IFormulaDatasetConfig,
- IOtherFormulaData,
IRuntimeUnitDataType,
ISheetData,
IUnitData,
@@ -19,12 +18,12 @@ import type {
export const DEFAULT_DOCUMENT_SUB_COMPONENT_ID = '__default_document_sub_component_id20231101__';
export interface IFormulaCurrentConfigService {
+ load(config: IFormulaDatasetConfig): void;
+
getUnitData(): IUnitData;
getFormulaData(): IFormulaData;
- getOtherFormulaData(): IOtherFormulaData;
-
getSheetNameMap(): IUnitSheetNameMap;
isForceCalculate(): boolean;
@@ -51,8 +50,6 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _arrayFormulaCellData: IRuntimeUnitDataType = {};
- private _otherFormulaData: IOtherFormulaData = {};
-
private _formulaData: IFormulaData = {};
private _sheetNameMap: IUnitSheetNameMap = {};
@@ -98,10 +95,6 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return this._arrayFormulaCellData;
}
- getOtherFormulaData() {
- return this._otherFormulaData;
- }
-
getSheetNameMap() {
return this._sheetNameMap;
}
@@ -133,8 +126,6 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._sheetNameMap = unitSheetNameMap;
- this._otherFormulaData = this._loadOtherFormulaData();
-
this._forceCalculate = config.forceCalculate;
this._dirtyRanges = config.dirtyRanges;
@@ -183,82 +174,82 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return arrayFormulaCellData;
}
- private _loadOtherFormulaData() {
- const unitAllDoc = this._currentUniverService.getAllUniverDocsInstance();
+ // private _loadOtherFormulaData() {
+ // const unitAllDoc = this._currentUniverService.getAllUniverDocsInstance();
- const unitAllSlide = this._currentUniverService.getAllUniverSlidesInstance();
+ // const unitAllSlide = this._currentUniverService.getAllUniverSlidesInstance();
- const otherFormulaData: IOtherFormulaData = {};
+ // const otherFormulaData: IOtherFormulaData = {};
- for (const documentDataModel of unitAllDoc) {
- const unitId = documentDataModel.getUnitId();
+ // for (const documentDataModel of unitAllDoc) {
+ // const unitId = documentDataModel.getUnitId();
- if (otherFormulaData[unitId] == null) {
- otherFormulaData[unitId] = {};
- }
+ // if (otherFormulaData[unitId] == null) {
+ // otherFormulaData[unitId] = {};
+ // }
- if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
- otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
- }
+ // if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
+ // otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
+ // }
- const subComponent = otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID];
+ // const subComponent = otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID];
- const customRanges = documentDataModel.getBody()?.customRanges;
+ // const customRanges = documentDataModel.getBody()?.customRanges;
- if (customRanges == null) {
- continue;
- }
+ // if (customRanges == null) {
+ // continue;
+ // }
- for (const customRange of customRanges) {
- subComponent[customRange.rangeId] = {
- f: customRange.endIndex.toString(),
- };
- }
- }
+ // for (const customRange of customRanges) {
+ // subComponent[customRange.rangeId] = {
+ // f: customRange.endIndex.toString(),
+ // };
+ // }
+ // }
- for (const slide of unitAllSlide) {
- const unitId = slide.getUnitId();
+ // for (const slide of unitAllSlide) {
+ // const unitId = slide.getUnitId();
- if (otherFormulaData[unitId] == null) {
- otherFormulaData[unitId] = {};
- }
+ // if (otherFormulaData[unitId] == null) {
+ // otherFormulaData[unitId] = {};
+ // }
- if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
- otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
- }
+ // if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
+ // otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
+ // }
- const pages = slide.getPages();
+ // const pages = slide.getPages();
- if (pages == null) {
- continue;
- }
+ // if (pages == null) {
+ // continue;
+ // }
- const pageIds = Object.keys(pages);
+ // const pageIds = Object.keys(pages);
- for (const pageId of pageIds) {
- const page = pages[pageId];
+ // for (const pageId of pageIds) {
+ // const page = pages[pageId];
- const subComponent = otherFormulaData[unitId][pageId];
+ // const subComponent = otherFormulaData[unitId][pageId];
- const pageElements = page.pageElements;
+ // const pageElements = page.pageElements;
- if (pageElements == null) {
- continue;
- }
+ // if (pageElements == null) {
+ // continue;
+ // }
- const pageElementIds = Object.keys(pageElements);
+ // const pageElementIds = Object.keys(pageElements);
- for (const pageElementId of pageElementIds) {
- const pageElement = pageElements[pageElementId];
- subComponent[pageElementId] = {
- f: pageElement.title,
- };
- }
- }
- }
+ // for (const pageElementId of pageElementIds) {
+ // const pageElement = pageElements[pageElementId];
+ // subComponent[pageElementId] = {
+ // f: pageElement.title,
+ // };
+ // }
+ // }
+ // }
- return otherFormulaData;
- }
+ // return otherFormulaData;
+ // }
private _loadSheetData() {
const unitAllSheet = this._currentUniverService.getAllUniverSheetsInstance();
diff --git a/packages/engine-formula/src/services/formula-engine.service.ts b/packages/engine-formula/src/services/formula-engine.service.ts
deleted file mode 100644
index 86e031b96c..0000000000
--- a/packages/engine-formula/src/services/formula-engine.service.ts
+++ /dev/null
@@ -1,536 +0,0 @@
-import type { IUnitRange } from '@univerjs/core';
-import {
- Disposable,
- IConfigService,
- LifecycleStages,
- ObjectMatrix,
- OnLifecycle,
- requestImmediateMacroTask,
-} from '@univerjs/core';
-import type { Ctor, Dependency } from '@wendellhu/redi';
-import { Inject, Injector } from '@wendellhu/redi';
-import { Subject } from 'rxjs';
-
-import type {
- IArrayFormulaRangeType,
- IFeatureDirtyRangeType,
- IFormulaDatasetConfig,
- IRuntimeUnitDataType,
- IUnitExcludedCell,
-} from '../basics/common';
-import { ErrorType } from '../basics/error-type';
-import type { IFunctionInfo } from '../basics/function';
-import { FUNCTION_NAMES } from '../basics/function';
-import { LexerTreeBuilder } from '../engine/analysis/lexer';
-import type { LexerNode } from '../engine/analysis/lexer-node';
-import { AstTreeBuilder } from '../engine/analysis/parser';
-import { AstRootNodeFactory } from '../engine/ast-node/ast-root-node';
-import { ErrorNode } from '../engine/ast-node/base-ast-node';
-import { FunctionNodeFactory } from '../engine/ast-node/function-node';
-import { LambdaNodeFactory } from '../engine/ast-node/lambda-node';
-import { LambdaParameterNodeFactory } from '../engine/ast-node/lambda-parameter-node';
-import { OperatorNodeFactory } from '../engine/ast-node/operator-node';
-import { PrefixNodeFactory } from '../engine/ast-node/prefix-node';
-import { ReferenceNodeFactory } from '../engine/ast-node/reference-node';
-import { SuffixNodeFactory } from '../engine/ast-node/suffix-node';
-import { UnionNodeFactory } from '../engine/ast-node/union-node';
-import { ValueNodeFactory } from '../engine/ast-node/value-node';
-import { FormulaDependencyGenerator } from '../engine/dependency/formula-dependency';
-import { Interpreter } from '../engine/interpreter/interpreter';
-import type { FunctionVariantType } from '../engine/reference-object/base-reference-object';
-import {
- Average,
- Compare,
- Concatenate,
- Count,
- Divided,
- Indirect,
- Max,
- Min,
- Minus,
- Multiply,
- Offset,
- Plus,
- Power,
- Sum,
- Union,
-} from '../functions';
-import type { BaseFunction } from '../functions/base-function';
-import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from './current-data.service';
-import { DefinedNamesService, IDefinedNamesService } from './defined-names.service';
-import { FunctionService, IFunctionService } from './function.service';
-import type { IAllRuntimeData, IExecutionInProgressParams } from './runtime.service';
-import { FormulaExecuteStageType, FormulaRuntimeService, IFormulaRuntimeService } from './runtime.service';
-import { ISuperTableService, SuperTableService } from './super-table.service';
-
-export const DEFAULT_CYCLE_REFERENCE_COUNT = 1;
-
-export const CYCLE_REFERENCE_COUNT = 'cycleReferenceCount';
-
-export const EVERY_N_FUNCTION_EXECUTION_PAUSE = 100;
-
-@OnLifecycle(LifecycleStages.Rendered, FormulaEngineService)
-export class FormulaEngineService extends Disposable {
- private readonly _executionStartListener$ = new Subject<boolean>();
-
- readonly executionStartListener$ = this._executionStartListener$.asObservable();
-
- private readonly _executionCompleteListener$ = new Subject<IAllRuntimeData>();
-
- readonly executionCompleteListener$ = this._executionCompleteListener$.asObservable();
-
- private readonly _executionInProgressListener$ = new Subject<IExecutionInProgressParams>();
-
- readonly executionInProgressListener$ = this._executionInProgressListener$.asObservable();
-
- constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @IConfigService private readonly _configService: IConfigService
- ) {
- super();
- this._initializeDependencies();
- this._initializeFunctions();
- }
-
- override dispose(): void {}
-
- get currentConfigService() {
- return this._injector.get(IFormulaCurrentConfigService);
- }
-
- get runtimeService() {
- return this._injector.get(IFormulaRuntimeService);
- }
-
- get superTableService() {
- return this._injector.get(ISuperTableService);
- }
-
- get definedNamesService() {
- return this._injector.get(IDefinedNamesService);
- }
-
- get formulaDependencyGenerator() {
- return this._injector.get(FormulaDependencyGenerator);
- }
-
- get interpreter() {
- return this._injector.get(Interpreter);
- }
-
- get astTreeBuilder() {
- return this._injector.get(AstTreeBuilder);
- }
-
- get functionService() {
- return this._injector.get(IFunctionService);
- }
-
- get lexerTreeBuilder() {
- return this._injector.get(LexerTreeBuilder);
- }
-
- /**
- * Use register to register a function, new CustomFunction(inject, name)
- */
- registerFunction(...functions: BaseFunction[]) {
- this.functionService.registerExecutors(...functions);
- }
-
- /**
- * Obtain the operator of the function to reuse the calculation logic.
- * The argument type accepted by the function is: FunctionVariantType.
- * For instance, the sum formula capability is needed for the statistics bar.
- * You can obtain the calculation result by using
- * const sum = formulaService.getExecutor(FUNCTION_NAMES.SUM);
- * sum.calculate(new RangeReferenceObject(range, sheetId, unitId), ref2, re3).
- * @param functionName Function name, which can be obtained through the FUNCTION_NAMES enumeration.
- * @returns
- */
- getExecutor(functionName: FUNCTION_NAMES) {
- return this.functionService.getExecutor(functionName);
- }
-
- /**
- * Use register to register function description
- */
- registerDescription(...descriptions: IFunctionInfo[]) {
- this.functionService.registerDescriptions(...descriptions);
- }
-
- /**
- * Obtain all function descriptions registered to the formulaEngineService.
- * @returns
- */
- getDescriptions() {
- return this.functionService.getDescriptions();
- }
-
- builderLexerTree(formulaString: string) {
- const lexerNode = this.lexerTreeBuilder.treeBuilder(formulaString, false);
-
- if (Object.values(ErrorType).includes(lexerNode as ErrorType)) {
- return ErrorNode.create(lexerNode as ErrorType);
- }
- return lexerNode as LexerNode;
- }
-
- buildSequenceNodes(formulaString: string) {
- return this.lexerTreeBuilder.sequenceNodesBuilder(formulaString);
- }
-
- checkIfAddBracket(formulaString: string) {
- return this.lexerTreeBuilder.checkIfAddBracket(formulaString);
- }
-
- getFunctionAndParameter(formulaString: string, strIndex: number) {
- return this.lexerTreeBuilder.getFunctionAndParameter(formulaString, strIndex);
- }
-
- /**
- * Modify the formula text to offset the 'ref' text within it.
- * @param formulaString '=SUM(A1:B10)'
- * @param refOffsetX
- * @param refOffsetY
- * @returns
- */
- moveFormulaRefOffset(formulaString: string, refOffsetX: number, refOffsetY: number) {
- return this.lexerTreeBuilder.moveFormulaRefOffset(formulaString, refOffsetX, refOffsetY);
- }
-
- /**
- * Stop the execution of the formula.
- */
- stopFormulaExecution() {
- this.runtimeService.stopExecution();
- }
-
- /**
- * When the feature is loading,
- * the pre-calculated content needs to be input to the formula engine in advance,
- * so that the formula can read the correct values.
- * @param featureId
- * @param featureData
- */
- setRuntimeFeatureCellData(featureId: string, featureData: IRuntimeUnitDataType) {
- this.runtimeService.setRuntimeFeatureCellData(featureId, featureData);
- }
-
- setRuntimeFeatureRange(featureId: string, featureRange: IFeatureDirtyRangeType) {
- this.runtimeService.setRuntimeFeatureRange(featureId, featureRange);
- }
-
- /**
- *
- * @param unitId
- * @param formulaData
- * @param interpreterDatasetConfig
- * @param forceCalculate force calculate all formula, and ignore dependency relationship
- * @param dirtyRanges input external unit data for multi workbook
- * @returns
- */
- async execute(formulaDatasetConfig: IFormulaDatasetConfig) {
- this._executionStartListener$.next(true);
-
- this.currentConfigService.load(formulaDatasetConfig);
-
- this.runtimeService.reset();
-
- const cycleReferenceCount = (this._configService.getConfig('CYCLE_REFERENCE_COUNT') ||
- DEFAULT_CYCLE_REFERENCE_COUNT) as number;
-
- for (let i = 0; i < cycleReferenceCount; i++) {
- await this._execute();
- const isCycleDependency = this.runtimeService.isCycleDependency();
- if (!isCycleDependency) {
- break;
- }
- }
-
- this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED);
-
- this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
-
- this._executionCompleteListener$.next(this.runtimeService.getAllRuntimeData());
- }
-
- private async _execute() {
- const executeState = await this._apply();
-
- if (executeState == null) {
- return;
- }
-
- const { arrayFormulaRange, runtimeFeatureRange } = executeState;
-
- const { dirtyRanges, excludedCell } = this._getArrayFormulaDirtyRangeAndExcludedRange(
- arrayFormulaRange,
- runtimeFeatureRange
- );
-
- if (dirtyRanges == null || dirtyRanges.length === 0) {
- return true;
- }
-
- this.currentConfigService.loadDirtyRangesAndExcludedCell(dirtyRanges, excludedCell);
-
- await this._apply(true);
-
- return true;
- }
-
- private _getArrayFormulaDirtyRangeAndExcludedRange(
- arrayFormulaRange: IArrayFormulaRangeType,
- runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType }
- ) {
- const dirtyRanges: IUnitRange[] = [];
- const excludedCell: IUnitExcludedCell = {};
- Object.keys(arrayFormulaRange).forEach((unitId) => {
- const sheetArrayFormulaRange = arrayFormulaRange[unitId];
- Object.keys(sheetArrayFormulaRange).forEach((sheetId) => {
- const cellValue = new ObjectMatrix(sheetArrayFormulaRange[sheetId]);
-
- if (cellValue == null) {
- return true;
- }
-
- const newCellData = new ObjectMatrix<boolean>();
-
- cellValue.forValue((row, column, range) => {
- newCellData.setValue(row, column, true);
-
- dirtyRanges.push({ unitId, sheetId, range });
- });
-
- if (excludedCell[unitId] == null) {
- excludedCell[unitId] = {};
- }
-
- excludedCell[unitId][sheetId] = newCellData;
- });
- });
-
- Object.keys(runtimeFeatureRange).forEach((featureId) => {
- const arrayRange = runtimeFeatureRange[featureId];
- Object.keys(arrayRange).forEach((unitId) => {
- const sheetArrayFormulaRange = arrayRange[unitId];
- Object.keys(sheetArrayFormulaRange).forEach((sheetId) => {
- const ranges = sheetArrayFormulaRange[sheetId];
-
- if (ranges == null) {
- return true;
- }
-
- for (const range of ranges) {
- dirtyRanges.push({ unitId, sheetId, range });
- }
- });
- });
- });
-
- return { dirtyRanges, excludedCell };
- }
-
- private async _apply(isArrayFormulaState = false) {
- if (isArrayFormulaState) {
- this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA);
- } else {
- this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY);
- }
-
- this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
-
- const treeList = await this.formulaDependencyGenerator.generate();
-
- const interpreter = this.interpreter;
-
- if (isArrayFormulaState) {
- this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_CALCULATION_ARRAY_FORMULA);
-
- this.runtimeService.setTotalArrayFormulasToCalculate(treeList.length);
- } else {
- this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_CALCULATION);
-
- this.runtimeService.setTotalFormulasToCalculate(treeList.length);
- }
-
- this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
-
- for (let i = 0, len = treeList.length; i < len; i++) {
- /**
- * For every functions, execute a setTimeout to wait for external command input.
- */
- await new Promise((resolve) => {
- requestImmediateMacroTask(resolve);
- });
-
- if (this.runtimeService.isStopExecution()) {
- this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
- this.runtimeService.markedAsStopFunctionsExecuted();
- this._executionCompleteListener$.next(this.runtimeService.getAllRuntimeData());
- return;
- }
-
- const tree = treeList[i];
- const astNode = tree.node;
- const getDirtyData = tree.getDirtyData;
- let value: FunctionVariantType;
-
- if (astNode == null && getDirtyData == null) {
- throw new Error('AstNode or executor is null');
- }
-
- this.runtimeService.setCurrent(tree.row, tree.column, tree.subComponentId, tree.unitId);
-
- if (getDirtyData != null && tree.featureId != null) {
- /**
- * Execute the dependencies registered by the feature,
- * and return the dirty area marked by the feature,
- * so as to allow the formulas depending on the dirty area to continue the calculation.
- */
- const { runtimeCellData, dirtyRanges } = getDirtyData(tree);
-
- this.runtimeService.setRuntimeFeatureCellData(tree.featureId, runtimeCellData);
-
- this.runtimeService.setRuntimeFeatureRange(tree.featureId, dirtyRanges);
- } else if (astNode != null) {
- if (interpreter.checkAsyncNode(astNode)) {
- value = await interpreter.executeAsync(astNode);
- } else {
- value = interpreter.execute(astNode);
- }
-
- if (tree.formulaId != null) {
- this.runtimeService.setRuntimeOtherData(tree.formulaId, value);
- } else {
- 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());
- }
-
- if (treeList.length > 0) {
- this.runtimeService.markedAsSuccessfullyExecuted();
- } else if (!isArrayFormulaState) {
- this.runtimeService.markedAsNoFunctionsExecuted();
- }
-
- return this.runtimeService.getAllRuntimeData();
- }
-
- calculate(formulaString: string, transformSuffix: boolean = true) {
- // TODO how to observe @alex
- // this.getObserver('onBeforeFormulaCalculateObservable')?.notifyObservers(formulaString);
- const lexerNode = this.lexerTreeBuilder.treeBuilder(formulaString, transformSuffix);
-
- if (Object.values(ErrorType).includes(lexerNode as ErrorType)) {
- return ErrorNode.create(lexerNode as ErrorType);
- }
-
- // this.lexerTreeBuilder.suffixExpressionHandler(lexerNode); // suffix Express, 1+(3*4=4)*5+1 convert to 134*4=5*1++
-
- // console.log('sequence', this.lexerTreeBuilder.sequenceNodesBuilder(formulaString));
-
- // this.getObserver('onAfterFormulaLexerObservable')?.notifyObservers(lexerNode);
-
- // const astTreeBuilder = new AstTreeBuilder();
-
- const astNode = this.astTreeBuilder.parse(lexerNode as LexerNode);
-
- console.log('astNode', astNode?.serialize());
-
- // const interpreter = Interpreter.create();
-
- // if (astNode == null) {
- // return;
- // }
-
- // if (interpreter.checkAsyncNode(astNode)) {
- // const resultPromise = interpreter.executeAsync(astNode);
-
- // resultPromise.then((value) => {
- // console.log('formulaResult', value);
- // });
- // } else {
- // console.log(interpreter.execute(astNode));
- // }
- }
-
- private _initializeDependencies() {
- const dependencies: Dependency[] = [
- // Config or data services
- [IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],
- [IFormulaRuntimeService, { useClass: FormulaRuntimeService }],
-
- [ISuperTableService, { useClass: SuperTableService }],
- [IDefinedNamesService, { useClass: DefinedNamesService }],
- [IFunctionService, { useClass: FunctionService }],
-
- // [IPassiveDirtyManagerService, { useClass: PassiveDirtyManagerService }],
-
- // Calculation engine
- [FormulaDependencyGenerator],
- [Interpreter],
- [LexerTreeBuilder],
- [AstTreeBuilder],
-
- // AstNode factory
- [AstRootNodeFactory],
- [FunctionNodeFactory],
- [LambdaNodeFactory],
- [LambdaParameterNodeFactory],
- [OperatorNodeFactory],
- [PrefixNodeFactory],
- [ReferenceNodeFactory],
- [SuffixNodeFactory],
- [UnionNodeFactory],
- [ValueNodeFactory],
- ];
-
- dependencies.forEach((d) => {
- this._injector.add(d);
- });
- }
-
- private _initializeFunctions() {
- // new Sum(this._injector, FUNCTION_NAMES.SUM)
- const functions: BaseFunction[] = [
- // base function
- [Compare, FUNCTION_NAMES.COMPARE],
- [Divided, FUNCTION_NAMES.DIVIDED],
- [Minus, FUNCTION_NAMES.MINUS],
- [Multiply, FUNCTION_NAMES.MULTIPLY],
- [Plus, FUNCTION_NAMES.PLUS],
- [Union, FUNCTION_NAMES.UNION],
-
- // static
- [Average, FUNCTION_NAMES.AVERAGE],
- [Concatenate, FUNCTION_NAMES.CONCATENATE],
- [Count, FUNCTION_NAMES.COUNT],
- [Indirect, FUNCTION_NAMES.INDIRECT],
- [Max, FUNCTION_NAMES.MAX],
- [Min, FUNCTION_NAMES.MIN],
- [Offset, FUNCTION_NAMES.OFFSET],
- [Power, FUNCTION_NAMES.POWER],
- [Sum, FUNCTION_NAMES.SUM],
- ].map((registerObject) => {
- const Func = registerObject[0] as Ctor<BaseFunction>;
- const name = registerObject[1] as string;
-
- return new Func(this._injector, name);
- });
-
- this.functionService.registerExecutors(...functions);
- }
-}
diff --git a/packages/engine-formula/src/services/formula.service.ts b/packages/engine-formula/src/services/formula.service.ts
deleted file mode 100644
index 3b589965ac..0000000000
--- a/packages/engine-formula/src/services/formula.service.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { LifecycleStages, OnLifecycle } from '@univerjs/core';
-import type { Ctor, IDisposable } from '@wendellhu/redi';
-import { createIdentifier, Inject, Injector } from '@wendellhu/redi';
-
-import { functionArray } from '../functions/array/function-names';
-import type { BaseFunction } from '../functions/base-function';
-import { functionCompatibility } from '../functions/compatibility/function-names';
-import { functionCube } from '../functions/cube/function-names';
-import { functionDatabase } from '../functions/database/function-names';
-import { functionDate } from '../functions/date/function-names';
-import { functionEngineering } from '../functions/engineering/function-names';
-import { functionFinancial } from '../functions/financial/function-names';
-import { functionInformation } from '../functions/information/function-names';
-import { functionLogical } from '../functions/logical/function-names';
-import { functionLookup } from '../functions/lookup/function-names';
-import { functionMath } from '../functions/math/function-names';
-import { functionStatistical } from '../functions/statistical/function-names';
-import { functionText } from '../functions/text/function-names';
-import { functionUniver } from '../functions/univer/function-names';
-import { functionWeb } from '../functions/web/function-names';
-import { FormulaEngineService } from './formula-engine.service';
-
-export interface IFormulaService {
- registerFunctions(): void;
-}
-
-@OnLifecycle(LifecycleStages.Starting, FormulaService)
-export class FormulaService implements IFormulaService, IDisposable {
- constructor(
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService
- ) {}
-
- dispose(): void {}
-
- registerFunctions() {
- const functions: BaseFunction[] = [
- ...functionArray,
- ...functionCompatibility,
- ...functionCube,
- ...functionDatabase,
- ...functionDate,
- ...functionEngineering,
- ...functionFinancial,
- ...functionInformation,
- ...functionLogical,
- ...functionLookup,
- ...functionMath,
- ...functionStatistical,
- ...functionText,
- ...functionUniver,
- ...functionWeb,
- ].map((registerObject) => {
- const Func = registerObject[0] as Ctor<BaseFunction>;
- const name = registerObject[1] as string;
-
- return new Func(this._injector, name);
- });
-
- this._formulaEngineService.registerFunction(...functions);
- }
-}
-
-export const IFormulaService = createIdentifier<FormulaService>('formula-calculate.formula-service');
diff --git a/packages/engine-formula/src/services/function.service.ts b/packages/engine-formula/src/services/function.service.ts
index 8d6603fa03..528cb0db79 100644
--- a/packages/engine-formula/src/services/function.service.ts
+++ b/packages/engine-formula/src/services/function.service.ts
@@ -6,10 +6,23 @@ import type { FUNCTION_NAMES, IFunctionInfo } from '../basics/function';
import type { BaseFunction } from '../functions/base-function';
export interface IFunctionService {
+ /**
+ * Use register to register a function, new CustomFunction(inject, name)
+ */
registerExecutors(...functions: BaseFunction[]): void;
getExecutors(): Map<string, BaseFunction>;
+ /**
+ * Obtain the operator of the function to reuse the calculation logic.
+ * The argument type accepted by the function is: FunctionVariantType.
+ * For instance, the sum formula capability is needed for the statistics bar.
+ * You can obtain the calculation result by using
+ * const sum = formulaService.getExecutor(FUNCTION_NAMES.SUM);
+ * sum.calculate(new RangeReferenceObject(range, sheetId, unitId), ref2, re3).
+ * @param functionName Function name, which can be obtained through the FUNCTION_NAMES enumeration.
+ * @returns
+ */
getExecutor(functionToken: string): Nullable<BaseFunction>;
hasExecutor(functionToken: string): boolean;
diff --git a/packages/engine-formula/src/services/other-formula-manager.service.ts b/packages/engine-formula/src/services/other-formula-manager.service.ts
new file mode 100644
index 0000000000..29e06da99e
--- /dev/null
+++ b/packages/engine-formula/src/services/other-formula-manager.service.ts
@@ -0,0 +1,79 @@
+import type { Nullable } from '@univerjs/core';
+import { Disposable } from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
+
+import type { IFormulaDataItem, IOtherFormulaData } from '../basics/common';
+
+export interface IOtherFormulaManagerSearchParam {
+ unitId: string;
+ subComponentId: string;
+ formulaId: string;
+}
+
+export interface IOtherFormulaManagerInsertParam extends IOtherFormulaManagerSearchParam {
+ item: IFormulaDataItem;
+}
+
+export interface IOtherFormulaManagerService {
+ dispose(): void;
+
+ remove(searchParam: IOtherFormulaManagerSearchParam): void;
+
+ get(searchParam: IOtherFormulaManagerSearchParam): Nullable<IFormulaDataItem>;
+
+ has(searchParam: IOtherFormulaManagerSearchParam): boolean;
+
+ register(insertParam: IOtherFormulaManagerInsertParam): void;
+
+ getOtherFormulaData(): IOtherFormulaData;
+}
+
+/**
+ * Passively marked as dirty, register the reference and execution actions of the feature plugin.
+ * After execution, a dirty area and calculated data will be returned,
+ * causing the formula to be marked dirty again,
+ * thereby completing the calculation of the entire dependency tree.
+ */
+export class OtherFormulaManagerService extends Disposable implements IOtherFormulaManagerService {
+ private _otherFormulaData: IOtherFormulaData = {};
+
+ override dispose(): void {
+ this._otherFormulaData = {};
+ }
+
+ remove(searchParam: IOtherFormulaManagerSearchParam) {
+ const { unitId, subComponentId, formulaId } = searchParam;
+ delete this._otherFormulaData?.[unitId]?.[subComponentId]?.[formulaId];
+ }
+
+ get(searchParam: IOtherFormulaManagerSearchParam) {
+ const { unitId, subComponentId, formulaId } = searchParam;
+ return this._otherFormulaData[unitId]?.[subComponentId]?.[formulaId];
+ }
+
+ has(searchParam: IOtherFormulaManagerSearchParam) {
+ const { unitId, subComponentId, formulaId } = searchParam;
+ return this._otherFormulaData[unitId]?.[subComponentId]?.[formulaId] != null;
+ }
+
+ register(insertParam: IOtherFormulaManagerInsertParam) {
+ const { unitId, subComponentId, formulaId, item } = insertParam;
+ if (this._otherFormulaData[unitId]) {
+ this._otherFormulaData[unitId] = {};
+ }
+
+ if (this._otherFormulaData[unitId][subComponentId]) {
+ this._otherFormulaData[unitId][subComponentId] = {};
+ }
+
+ this._otherFormulaData[unitId][subComponentId][formulaId] = item;
+ }
+
+ getOtherFormulaData() {
+ return this._otherFormulaData;
+ }
+}
+
+export const IOtherFormulaManagerService = createIdentifier<OtherFormulaManagerService>(
+ 'univer.formula.other-formula-manager.service'
+);
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index 5879d650ec..6fe53410e7 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -142,6 +142,10 @@ export interface IFormulaRuntimeService {
getRuntimeFeatureRange(): { [featureId: string]: IFeatureDirtyRangeType };
getRuntimeFeatureCellData(): { [featureId: string]: IRuntimeUnitDataType };
+
+ setRuntimeFeatureCellData(featureId: string, featureData: IRuntimeUnitDataType): void;
+
+ setRuntimeFeatureRange(featureId: string, featureRange: IFeatureDirtyRangeType): void;
}
export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeService {
diff --git a/packages/engine-render/src/scene.input-manager.ts b/packages/engine-render/src/scene.input-manager.ts
index 28b589649e..0841612f44 100644
--- a/packages/engine-render/src/scene.input-manager.ts
+++ b/packages/engine-render/src/scene.input-manager.ts
@@ -16,7 +16,9 @@ export class InputManager {
static LongPressDelay = 500; // in milliseconds
/** Time in milliseconds with two consecutive clicks will be considered as a double or triple click */
- static DoubleOrTripleClickDelay = 500; // in milliseconds
+ static DoubleClickDelay = 500; // in milliseconds
+
+ static TripleClickDelay = 300; // in milliseconds
/** If you need to check double click without raising a single click at first click, enable this flag */
static ExclusiveDoubleClickMode = false;
@@ -55,8 +57,12 @@ export class InputManager {
private _delayedTimeout: NodeJS.Timeout | number = -1;
+ private _delayedTripeTimeout: NodeJS.Timeout | number = -1;
+
private _doubleClickOccurred = 0;
+ private _tripleClickState = false;
+
private _currentObject: Nullable<BaseObject | ThinScene>;
constructor(scene: ThinScene) {
@@ -332,7 +338,7 @@ export class InputManager {
this._delayedTimeout = setTimeout(() => {
this._resetDoubleClickParam();
- }, InputManager.DoubleOrTripleClickDelay);
+ }, InputManager.DoubleClickDelay);
const isMoveThreshold = this._isPointerSwiping(clientX, clientY);
@@ -342,23 +348,27 @@ export class InputManager {
this._doubleClickOccurred += 1;
- if (this._doubleClickOccurred === 2) {
- this._scene?.pick(Vector2.FromArray([evt.offsetX, evt.offsetY]))?.triggerDblclick(evt);
-
- if (this._scene.onDblclickObserver.hasObservers()) {
- this._scene.onDblclickObserver.notifyObservers(evt);
- }
- }
-
// eslint-disable-next-line no-magic-numbers
- if (this._doubleClickOccurred === 3) {
+ if (this._tripleClickState) {
this._scene?.pick(Vector2.FromArray([evt.offsetX, evt.offsetY]))?.triggerTripleClick(evt);
if (this._scene.onTripleClickObserver.hasObservers()) {
this._scene.onTripleClickObserver.notifyObservers(evt);
}
+ }
+ if (this._doubleClickOccurred === 2) {
+ this._scene?.pick(Vector2.FromArray([evt.offsetX, evt.offsetY]))?.triggerDblclick(evt);
+
+ if (this._scene.onDblclickObserver.hasObservers()) {
+ this._scene.onDblclickObserver.notifyObservers(evt);
+ }
this._resetDoubleClickParam();
+ this._tripleClickState = true;
+ clearTimeout(this._delayedTripeTimeout);
+ this._delayedTripeTimeout = setTimeout(() => {
+ this._tripleClickState = false;
+ }, InputManager.TripleClickDelay);
}
this._startingPosition.x = clientX;
diff --git a/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
index 3c6f99a484..45c7774c77 100644
--- a/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
@@ -1,6 +1,6 @@
import type { IWorkbookData } from '@univerjs/core';
import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, PluginType, Univer } from '@univerjs/core';
-import { FormulaEngineService } from '@univerjs/engine-formula';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SelectionManagerService } from '@univerjs/sheets';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -51,7 +51,7 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
override onStarting(injector: Injector): void {
injector.add([SelectionManagerService]);
- injector.add([FormulaEngineService]);
+ injector.add([LexerTreeBuilder]);
injector.add([IFormulaInputService, { useClass: FormulaInputService }]);
dependencies?.forEach((d) => injector.add(d));
diff --git a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
index 731fc5cf68..2b21235101 100644
--- a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
@@ -1,6 +1,6 @@
import type { IWorkbookData, Workbook } from '@univerjs/core';
import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, PluginType, Univer } from '@univerjs/core';
-import { FormulaEngineService } from '@univerjs/engine-formula';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SelectionManagerService } from '@univerjs/sheets';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -61,7 +61,7 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
override onStarting(injector: Injector): void {
injector.add([SelectionManagerService]);
- injector.add([FormulaEngineService]);
+ injector.add([LexerTreeBuilder]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
index 316e6d3eff..5fda25cc8e 100644
--- a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
@@ -7,6 +7,7 @@ import {
ThemeService,
UndoCommand,
} from '@univerjs/core';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import {
AddWorksheetMergeMutation,
NORMAL_SELECTION_PLUGIN_NAME,
@@ -53,6 +54,7 @@ describe('Test auto fill with formula', () => {
[SheetInterceptorService],
[ISelectionRenderService, { useClass: SelectionRenderService }],
[AutoFillController],
+ [LexerTreeBuilder],
[IAutoFillService, { useClass: AutoFillService }],
[IShortcutService, { useClass: DesktopShortcutService }],
[IPlatformService, { useClass: DesktopPlatformService }],
diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts
index 94bca7bb19..221f4d0e4e 100644
--- a/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/formula-clipboard.controller.spec.ts
@@ -1,6 +1,6 @@
import type { ICellData, IMutationInfo, Nullable, Univer } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
-import { FormulaEngineService } from '@univerjs/engine-formula';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { type ISetRangeValuesMutationParams, SetRangeValuesMutation } from '@univerjs/sheets';
import type { ICellDataWithSpanInfo } from '@univerjs/sheets-ui';
import { COPY_TYPE, ISelectionRenderService, SelectionRenderService } from '@univerjs/sheets-ui';
@@ -14,7 +14,7 @@ describe('Test paste with formula', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
- let formulaEngineService: FormulaEngineService;
+ let lexerTreeBuilder: LexerTreeBuilder;
let getValues: (
startRow: number,
startColumn: number,
@@ -25,11 +25,12 @@ describe('Test paste with formula', () => {
beforeEach(() => {
const testBed = createCommandTestBed(undefined, [
[ISelectionRenderService, { useClass: SelectionRenderService }],
+ [LexerTreeBuilder],
]);
univer = testBed.univer;
get = testBed.get;
commandService = get(ICommandService);
- formulaEngineService = get(FormulaEngineService);
+ lexerTreeBuilder = get(LexerTreeBuilder);
getValues = (
startRow: number,
@@ -146,7 +147,7 @@ describe('Test paste with formula', () => {
matrix,
accessor,
copyInfo,
- formulaEngineService
+ lexerTreeBuilder
);
removeFormulaId(redoUndoList.redos as Array<IMutationInfo<ISetRangeValuesMutationParams>>);
expect(redoUndoList).toStrictEqual(result);
diff --git a/packages/sheets-formula/src/controllers/formula-auto-fill.controller.ts b/packages/sheets-formula/src/controllers/formula-auto-fill.controller.ts
index ea95a7cc47..085ce4b990 100644
--- a/packages/sheets-formula/src/controllers/formula-auto-fill.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-auto-fill.controller.ts
@@ -8,7 +8,7 @@ import {
OnLifecycle,
Tools,
} from '@univerjs/core';
-import { FormulaEngineService } from '@univerjs/engine-formula';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import type { AutoFillService, IAutoFillRule, ICopyDataInTypeIndexInfo, ICopyDataPiece } from '@univerjs/sheets-ui';
import { APPLY_TYPE, DATA_TYPE, IAutoFillService } from '@univerjs/sheets-ui';
import { Inject } from '@wendellhu/redi';
@@ -17,7 +17,7 @@ import { Inject } from '@wendellhu/redi';
export class FormulaAutoFillController extends Disposable {
constructor(
@IAutoFillService private readonly _autoFillService: AutoFillService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder
) {
super();
@@ -80,7 +80,7 @@ export class FormulaAutoFillController extends Disposable {
formulaIdMap.set(index, formulaId);
const { offsetX, offsetY } = directionToOffset(step, direction);
- const shiftedFormula = this._formulaEngineService.moveFormulaRefOffset(
+ const shiftedFormula = this._lexerTreeBuilder.moveFormulaRefOffset(
originalFormula,
offsetX,
offsetY
diff --git a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
index b39355af19..472fbcb52d 100644
--- a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
@@ -8,7 +8,7 @@ import {
OnLifecycle,
Tools,
} from '@univerjs/core';
-import { FormulaEngineService } from '@univerjs/engine-formula';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '@univerjs/sheets';
import type { ICellDataWithSpanInfo, ISheetClipboardHook } from '@univerjs/sheets-ui';
@@ -24,7 +24,7 @@ export const DEFAULT_PASTE_FORMULA = 'default-paste-formula';
export class FormulaClipboardController extends Disposable {
constructor(
@IUniverInstanceService private readonly _currentUniverSheet: IUniverInstanceService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService,
@Inject(Injector) private readonly _injector: Injector
) {
@@ -61,7 +61,7 @@ export class FormulaClipboardController extends Disposable {
matrix,
accessor,
copyInfo,
- this._formulaEngineService,
+ this._lexerTreeBuilder,
true
)
);
@@ -87,7 +87,7 @@ export class FormulaClipboardController extends Disposable {
matrix,
accessor,
copyInfo,
- this._formulaEngineService
+ this._lexerTreeBuilder
)
);
},
@@ -107,7 +107,7 @@ export function getSetCellFormulaMutations(
copyType: COPY_TYPE;
copyRange?: IRange;
},
- formulaEngineService: FormulaEngineService,
+ lexerTreeBuilder: LexerTreeBuilder,
isSpecialPaste = false
) {
const redoMutationsInfo: IMutationInfo[] = [];
@@ -155,7 +155,7 @@ export function getSetCellFormulaMutations(
const offsetX = col + startColumn - (copyRangeStartColumn + colIndex);
const offsetY = row + startRow - (copyRangeStartRow + rowIndex);
- const shiftedFormula = formulaEngineService.moveFormulaRefOffset(originalFormula, offsetX, offsetY);
+ const shiftedFormula = lexerTreeBuilder.moveFormulaRefOffset(originalFormula, offsetX, offsetY);
valueObject.si = formulaId;
valueObject.f = shiftedFormula;
diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
index 58ba015627..ec1c494d58 100644
--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
@@ -9,7 +9,7 @@ import {
ThemeService,
toDisposable,
} from '@univerjs/core';
-import { FormulaDataModel, FormulaEngineService, SetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
+import { FormulaDataModel, LexerTreeBuilder, SetFormulaCalculationResultMutation } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import {
IEditorBridgeService,
@@ -26,7 +26,7 @@ export class FormulaEditorShowController extends Disposable {
constructor(
@Inject(IEditorBridgeService) private _editorBridgeService: IEditorBridgeService,
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@Inject(ThemeService) private readonly _themeService: ThemeService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
@@ -49,9 +49,16 @@ export class FormulaEditorShowController extends Disposable {
const { row, col, workbookId, worksheetId } = context;
const arrayFormulaMatrixRange = this._formulaDataModel.getArrayFormulaRange();
+ const arrayFormulaMatrixCell = this._formulaDataModel.getArrayFormulaCellData();
+
this._removeArrayFormulaRangeShape();
- if (value == null) {
+ if (
+ value == null ||
+ (value.v != null &&
+ value.v !== '' &&
+ arrayFormulaMatrixCell[workbookId]?.[worksheetId]?.[row]?.[col] == null)
+ ) {
return next(value);
}
@@ -85,7 +92,7 @@ export class FormulaEditorShowController extends Disposable {
formulaString = originItem.f;
}
- const newFormulaString = this._formulaEngineService.moveFormulaRefOffset(
+ const newFormulaString = this._lexerTreeBuilder.moveFormulaRefOffset(
formulaString,
x,
y
diff --git a/packages/sheets-formula/src/controllers/formula-input.controller.ts b/packages/sheets-formula/src/controllers/formula-input.controller.ts
index d6c7bec361..e2c283a772 100644
--- a/packages/sheets-formula/src/controllers/formula-input.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-input.controller.ts
@@ -9,7 +9,7 @@ import {
serializeRange,
toDisposable,
} from '@univerjs/core';
-import { FormulaEngineService, matchToken, sequenceNodeType } from '@univerjs/engine-formula';
+import { LexerTreeBuilder, matchToken, sequenceNodeType } from '@univerjs/engine-formula';
import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
import type { EditorBridgeService } from '@univerjs/sheets-ui';
import { getEditorObject, IEditorBridgeService } from '@univerjs/sheets-ui';
@@ -27,7 +27,7 @@ export class FormulaInputController extends Disposable {
@ICommandService private readonly _commandService: ICommandService,
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@IFormulaInputService private readonly _formulaInputService: IFormulaInputService
) {
@@ -91,7 +91,7 @@ export class FormulaInputController extends Disposable {
});
}
- const lastSequenceNodes = this._formulaEngineService.buildSequenceNodes(formulaString) || [];
+ const lastSequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString) || [];
this._formulaInputService.setSequenceNodes(lastSequenceNodes);
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 3ae40796d4..0413903b1b 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -27,10 +27,10 @@ import {
} from '@univerjs/docs';
import type { ISequenceNode } from '@univerjs/engine-formula';
import {
- FormulaEngineService,
generateStringWithSequence,
includeFormulaLexerToken,
isFormulaLexerToken,
+ LexerTreeBuilder,
matchToken,
normalizeSheetName,
sequenceNodeType,
@@ -128,7 +128,7 @@ export class PromptController extends Disposable {
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,
@Inject(IFormulaPromptService) private readonly _formulaPromptService: IFormulaPromptService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(ThemeService) private readonly _themeService: ThemeService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@@ -554,7 +554,7 @@ export class PromptController extends Disposable {
const dataStream = currentBody?.dataStream || '';
- const functionAndParameter = this._formulaEngineService.getFunctionAndParameter(dataStream, startOffset - 1);
+ const functionAndParameter = this._lexerTreeBuilder.getFunctionAndParameter(dataStream, startOffset - 1);
if (functionAndParameter == null) {
this._hideFunctionPanel();
@@ -713,9 +713,8 @@ export class PromptController extends Disposable {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);
const lastSequenceNodes =
- this._formulaEngineService.buildSequenceNodes(
- currentInputValue.replace(/\r/g, '').replace(/\n/g, '')
- ) || [];
+ this._lexerTreeBuilder.sequenceNodesBuilder(currentInputValue.replace(/\r/g, '').replace(/\n/g, '')) ||
+ [];
this._formulaInputService.setSequenceNodes(lastSequenceNodes);
@@ -783,7 +782,7 @@ export class PromptController extends Disposable {
// const dataStream = body.dataStream;
- // const sequenceNodes = this._formulaEngineService.buildSequenceNodes(
+ // const sequenceNodes = this._lexerTreeBuilder.buildSequenceNodes(
// dataStream.replace(/\r/g, '').replace(/\n/g, '')
// );
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index 1aade9fa4d..c934d247ea 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -17,9 +17,9 @@ import {
import type { IFormulaData, IFormulaDataItem, ISequenceNode, IUnitSheetNameMap } from '@univerjs/engine-formula';
import {
FormulaDataModel,
- FormulaEngineService,
generateStringWithSequence,
initSheetFormulaData,
+ LexerTreeBuilder,
sequenceNodeType,
SetArrayFormulaDataMutation,
SetFormulaDataMutation,
@@ -117,7 +117,7 @@ export class UpdateFormulaController extends Disposable {
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
@@ -626,7 +626,7 @@ export class UpdateFormulaController extends Disposable {
const { f: formulaString, x, y, si } = formulaDataItem;
- const sequenceNodes = this._formulaEngineService.buildSequenceNodes(formulaString);
+ const sequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString);
if (sequenceNodes == null) {
return true;
diff --git a/packages/sheets-formula/src/services/description.service.ts b/packages/sheets-formula/src/services/description.service.ts
index e8436c2fbd..5a49b5fb98 100644
--- a/packages/sheets-formula/src/services/description.service.ts
+++ b/packages/sheets-formula/src/services/description.service.ts
@@ -1,6 +1,6 @@
import { LocaleService } from '@univerjs/core';
import type { IFunctionInfo } from '@univerjs/engine-formula';
-import { FormulaEngineService } from '@univerjs/engine-formula';
+import { IFunctionService } from '@univerjs/engine-formula';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject } from '@wendellhu/redi';
@@ -46,7 +46,7 @@ export const IDescriptionService = createIdentifier<IDescriptionService>('formul
export class DescriptionService implements IDescriptionService, IDisposable {
constructor(
private _description: IFunctionInfo[],
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @IFunctionService private readonly _functionService: IFunctionService,
@Inject(LocaleService) private readonly _localeService: LocaleService
) {
this._initialize();
@@ -58,22 +58,22 @@ export class DescriptionService implements IDescriptionService, IDisposable {
}
getDescriptions() {
- return this._formulaEngineService.getDescriptions();
+ return this._functionService.getDescriptions();
}
hasFunction(searchText: string) {
- const functionList = this._formulaEngineService.getDescriptions();
+ const functionList = this._functionService.getDescriptions();
return functionList.get(searchText.toLocaleUpperCase()) !== undefined;
}
getFunctionInfo(searchText: string) {
- const functionList = this._formulaEngineService.getDescriptions();
+ const functionList = this._functionService.getDescriptions();
return functionList.get(searchText.toLocaleUpperCase());
}
getSearchListByName(searchText: string) {
const searchList: ISearchItem[] = [];
- const functionList = this._formulaEngineService.getDescriptions();
+ const functionList = this._functionService.getDescriptions();
searchText = searchText.toLocaleUpperCase();
functionList.forEach((item) => {
const { functionName, abstract } = item;
@@ -87,7 +87,7 @@ export class DescriptionService implements IDescriptionService, IDisposable {
getSearchListByType(type: number) {
const searchList: ISearchItem[] = [];
- const functionList = this._formulaEngineService.getDescriptions();
+ const functionList = this._functionService.getDescriptions();
functionList.forEach((item) => {
const { functionName, functionType, abstract } = item;
if (functionType === type || type === -1) {
@@ -120,6 +120,6 @@ export class DescriptionService implements IDescriptionService, IDisposable {
repeat: item.repeat,
})),
}));
- this._formulaEngineService.registerDescription(...functionListLocale);
+ this._functionService.registerDescriptions(...functionListLocale);
}
}
diff --git a/packages/sheets-formula/src/services/formula-input.service.ts b/packages/sheets-formula/src/services/formula-input.service.ts
index 1a5eaa3790..1d91b5eb53 100644
--- a/packages/sheets-formula/src/services/formula-input.service.ts
+++ b/packages/sheets-formula/src/services/formula-input.service.ts
@@ -1,7 +1,7 @@
import type { ISequenceNode } from '@univerjs/engine-formula';
-import { FormulaEngineService, sequenceNodeType } from '@univerjs/engine-formula';
+import { sequenceNodeType } from '@univerjs/engine-formula';
import type { IDisposable } from '@wendellhu/redi';
-import { createIdentifier, Inject } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
import { Subject } from 'rxjs';
@@ -81,8 +81,6 @@ export class FormulaInputService implements IFormulaInputService, IDisposable {
readonly inputFormula$ = this._inputFormula$.asObservable();
- constructor(@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService) {}
-
dispose(): void {
this._sequenceNodes = [];
}
diff --git a/packages/sheets-ui/src/controllers/editor/editing.controller.ts b/packages/sheets-ui/src/controllers/editor/editing.controller.ts
index 2cdee366b0..96d748c33e 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.controller.ts
@@ -9,7 +9,6 @@ import {
} from '@univerjs/core';
import { getDocObject } from '@univerjs/docs';
import type { ISheetData } from '@univerjs/engine-formula';
-import { FormulaEngineService } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import { takeUntil } from 'rxjs';
@@ -19,7 +18,6 @@ export class EditingController extends RxDisposable {
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
@Inject(IUndoRedoService) private readonly _undoRedoService: IUndoRedoService
) {
super();
diff --git a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
index e9b33c9757..0feecbefe3 100644
--- a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
@@ -18,7 +18,7 @@ import {
Tools,
} from '@univerjs/core';
import { MoveCursorOperation, MoveSelectionOperation } from '@univerjs/docs';
-import { FormulaEngineService, matchToken } from '@univerjs/engine-formula';
+import { LexerTreeBuilder, matchToken } from '@univerjs/engine-formula';
import type { IMouseEvent, IPointerEvent } from '@univerjs/engine-render';
import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
import {
@@ -66,7 +66,7 @@ export class EndEditController extends Disposable {
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
@IContextService private readonly _contextService: IContextService,
@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@IUndoRedoService private _undoRedoService: IUndoRedoService,
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
@@ -190,7 +190,7 @@ export class EndEditController extends Disposable {
if (cellData.f === newDataStream) {
return;
}
- const bracketCount = this._formulaEngineService.checkIfAddBracket(newDataStream);
+ const bracketCount = this._lexerTreeBuilder.checkIfAddBracket(newDataStream);
for (let i = 0; i < bracketCount; i++) {
newDataStream += matchToken.CLOSE_BRACKET;
}
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index bb0f5a37f1..f7c59710bd 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -8,7 +8,7 @@ import {
toDisposable,
} from '@univerjs/core';
import type { BaseValueObject, ISheetData } from '@univerjs/engine-formula';
-import { FormulaEngineService, RangeReferenceObject } from '@univerjs/engine-formula';
+import { IFunctionService, RangeReferenceObject } from '@univerjs/engine-formula';
import { SelectionManagerService } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
@@ -20,7 +20,7 @@ export class StatusBarController extends Disposable {
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
- @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @IFunctionService private readonly _functionService: IFunctionService,
@IStatusBarService private readonly _statusBarService: IStatusBarService
) {
super();
@@ -79,7 +79,7 @@ export class StatusBarController extends Disposable {
const functions = this._statusBarService.getFunctions();
const calcResult = functions.map((f) => {
- const executor = this._formulaEngineService.getExecutor(f);
+ const executor = this._functionService.getExecutor(f);
if (!executor) {
return undefined;
}
diff --git a/packages/sheets/src/sheets-plugin.ts b/packages/sheets/src/sheets-plugin.ts
index 52d7ea729f..5aba4774f9 100644
--- a/packages/sheets/src/sheets-plugin.ts
+++ b/packages/sheets/src/sheets-plugin.ts
@@ -59,11 +59,10 @@ export class SheetsPlugin extends Plugin {
[BasicWorksheetController],
[MergeCellController],
[ActiveDirtyController],
- [PassiveDirtyController],
];
if (!this._config?.notExecuteFormula) {
- dependencies.push([CalculateResultApplyController]);
+ dependencies.push([CalculateResultApplyController], [PassiveDirtyController]);
}
dependencies.forEach((d) => {