Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(facade): add FFormula api (#3144)

Dushusir610be1f39d65
diff --git a/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts
index 7f8a4aa8cf..618bd50ee1 100644
--- a/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts
+++ b/packages/engine-formula/src/engine/utils/__tests__/math-kit.spec.ts
@@ -227,8 +227,13 @@ describe('Test math kit', () => {
});
it('Function getFractionalPart', () => {
- expect(stripErrorMargin(getFractionalPart(123.456))).toBe(0.456000000000003);
- expect(stripErrorMargin(getFractionalPart(-123.456))).toBe(-0.456000000000003);
+ expect(stripErrorMargin(getFractionalPart(123.456))).toBe(0.456);
+ expect(stripErrorMargin(getFractionalPart(-123.456))).toBe(-0.456);
expect(getFractionalPart(123)).toBe(0);
});
+
+ it('Function stripErrorMargin', () => {
+ expect(stripErrorMargin(0.1 + 0.2)).toBe(0.3);
+ expect(stripErrorMargin(30.2 - 30)).toBe(0.2);
+ });
});
diff --git a/packages/engine-formula/src/engine/utils/math-kit.ts b/packages/engine-formula/src/engine/utils/math-kit.ts
index ae4d398ce3..6dd8c12fa8 100644
--- a/packages/engine-formula/src/engine/utils/math-kit.ts
+++ b/packages/engine-formula/src/engine/utils/math-kit.ts
@@ -180,21 +180,27 @@ export function strip(num: number, precision = 15) {
* @param right
* @returns
*/
-export function withinErrorMargin(left: number, right: number) {
- return Math.abs(left - right) < Number.EPSILON;
+export function withinErrorMargin(left: number, right: number, tolerance = Number.EPSILON) {
+ return Math.abs(left - right) < tolerance;
}
/**
* Tolerance for the results of accuracy issues to tolerate certain errors
*
- * Why 12?
+ * Why is precision 12?
This is an empirical choice. Generally, choosing 12 can solve most of the 0001 and 0009 problems. e.g. floor(5,1.23) = 0.0800000000000001
+
+ why is tolerance 1e-10?
+ Since the value of Number.EPSILON is too small to be applicable to all floating-point precision processing, for most application scenarios, the error range of 1e-10 can tolerate common floating-point errors.
+ For example, =30.2 - 30 displayed as 0.2 in Excel
* @param num
+ * @param precision
+ * @param tolerance
* @returns
*/
-export function stripErrorMargin(num: number, precision = 12) {
+export function stripErrorMargin(num: number, precision = 12, tolerance = 1e-10) {
const stripResult = strip(num, precision);
- return withinErrorMargin(num, stripResult) ? stripResult : strip(num);
+ return withinErrorMargin(num, stripResult, tolerance) ? stripResult : strip(num);
}
/**
diff --git a/packages/engine-formula/src/functions/date/time/__tests__/index.spec.ts b/packages/engine-formula/src/functions/date/time/__tests__/index.spec.ts
index 4fd88aa270..f8a2e48cc5 100644
--- a/packages/engine-formula/src/functions/date/time/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/date/time/__tests__/index.spec.ts
@@ -48,7 +48,7 @@ describe('Test time function', () => {
const minute = NumberValueObject.create(750); // 750 minutes = 12 hours, 30 minutes
const second = NumberValueObject.create(3661); // 3661 seconds = 1 hour, 1 minute, 1 second
const result = testFunction.calculate(hour, minute, second);
- expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([[0.688206018518518]]); // 16:31:01
+ expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([[0.688206018519]]); // 16:31:01
});
it('Negative values', () => {
@@ -72,7 +72,7 @@ describe('Test time function', () => {
const minute = NumberValueObject.create(45);
const second = NumberValueObject.create(30);
const result = testFunction.calculate(hour, minute, second);
- expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([[0.531597222222222, 0.0315972222222222, ErrorType.NUM, ErrorType.VALUE]]);
+ expect(stripArrayValue(transformToValue(result.getArrayValue()))).toStrictEqual([[0.531597222222, 0.0315972222222, ErrorType.NUM, ErrorType.VALUE]]);
});
it('Handling leap values in hours, minutes, and seconds', () => {
diff --git a/packages/engine-formula/src/functions/text/len/index.ts b/packages/engine-formula/src/functions/text/len/index.ts
index 19c3e360b7..f69655cff9 100644
--- a/packages/engine-formula/src/functions/text/len/index.ts
+++ b/packages/engine-formula/src/functions/text/len/index.ts
@@ -50,7 +50,8 @@ export class Len extends BaseFunction {
if (text.isNumber()) {
const numberValue = text.getValue() as number;
- const numberValueString = stripErrorMargin(numberValue).toString();
+ // Specify Number.EPSILON to not discard necessary digits in the case of non-precision errors, for example, the length of 1/3 is 17
+ const numberValueString = stripErrorMargin(numberValue, 12, Number.EPSILON).toString();
return NumberValueObject.create(numberValueString.length);
}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 4f69747c55..c4a367b6be 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -118,13 +118,32 @@ export { IFormulaRuntimeService, FormulaRuntimeService } from './services/runtim
export { IFormulaCurrentConfigService, FormulaCurrentConfigService, type IFormulaDirtyData } from './services/current-data.service';
export { IActiveDirtyManagerService } from './services/active-dirty-manager.service';
+export { ActiveDirtyManagerService } from './services/active-dirty-manager.service';
export type { IRangeChange } from './models/formula-data.model';
export { handleNumfmtInCell } from './engine/utils/numfmt-kit';
export { AsyncArrayObject } from './engine/reference-object/base-reference-object';
export { strip, stripErrorMargin } from './engine/utils/math-kit';
export { AsyncObject } from './engine/reference-object/base-reference-object';
-
+export { Lexer } from './engine/analysis/lexer';
+export { FormulaDependencyGenerator } from './engine/dependency/formula-dependency';
+export { ISuperTableService } from './services/super-table.service';
+export { SuperTableService } from './services/super-table.service';
+export { Interpreter } from './engine/interpreter/interpreter';
+export { AstTreeBuilder } from './engine/analysis/parser';
+export { AstRootNodeFactory } from './engine/ast-node/ast-root-node';
+export { FunctionNodeFactory } from './engine/ast-node/function-node';
+export { LambdaNodeFactory } from './engine/ast-node/lambda-node';
+export { LambdaParameterNodeFactory } from './engine/ast-node/lambda-parameter-node';
+export { OperatorNodeFactory } from './engine/ast-node/operator-node';
+export { PrefixNodeFactory } from './engine/ast-node/prefix-node';
+export { ReferenceNodeFactory } from './engine/ast-node/reference-node';
+export { SuffixNodeFactory } from './engine/ast-node/suffix-node';
+export { UnionNodeFactory } from './engine/ast-node/union-node';
+export { ValueNodeFactory } from './engine/ast-node/value-node';
+export { IDependencyManagerService } from './services/dependency-manager.service';
+export { DependencyManagerService } from './services/dependency-manager.service';
+export { CalculateController } from './controller/calculate.controller';
// #region - all commands
export { RegisterFunctionMutation } from './commands/mutations/register-function.mutation';
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index 8d6f665c97..325debb58d 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -30,7 +30,7 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
-import { FormulaDataModel, FunctionService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { ActiveDirtyManagerService, AstRootNodeFactory, AstTreeBuilder, CalculateController, CalculateFormulaService, DefinedNamesService, DependencyManagerService, FeatureCalculationManagerService, FormulaCurrentConfigService, FormulaDataModel, FormulaDependencyGenerator, FormulaRuntimeService, FunctionNodeFactory, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IDependencyManagerService, IFeatureCalculationManagerService, IFormulaCurrentConfigService, IFormulaRuntimeService, IFunctionService, Interpreter, IOtherFormulaManagerService, ISuperTableService, LambdaNodeFactory, LambdaParameterNodeFactory, Lexer, LexerTreeBuilder, OperatorNodeFactory, OtherFormulaManagerService, PrefixNodeFactory, ReferenceNodeFactory, SuffixNodeFactory, SuperTableService, UnionNodeFactory, ValueNodeFactory } from '@univerjs/engine-formula';
import { ISocketService, WebSocketService } from '@univerjs/network';
import {
RangeProtectionRuleModel,
@@ -58,7 +58,6 @@ import { IPlatformService, IShortcutService, PlatformService, ShortcutService }
import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
import { UniverDataValidationPlugin } from '@univerjs/data-validation';
import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, DataValidationModel, SheetDataValidationManager, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
-import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '@univerjs/engine-formula/services/active-dirty-manager.service.js';
import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import { FUniver } from '../facade';
@@ -146,7 +145,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
},
]);
- injector.add([IFunctionService, { useClass: FunctionService }]);
+ // injector.add([IFunctionService, { useClass: FunctionService }]);
injector.add([ISocketService, { useClass: WebSocketService }]);
injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
@@ -156,7 +155,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
injector.add([IPlatformService, { useClass: PlatformService }]);
injector.add([SheetSkeletonManagerService]);
injector.add([FormulaDataModel]);
- injector.add([LexerTreeBuilder]);
+ // injector.add([LexerTreeBuilder]);
injector.add([RefRangeService]);
injector.add([WorksheetPermissionService]);
injector.add([WorkbookPermissionService]);
@@ -164,6 +163,8 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
injector.add([RangeProtectionRuleModel]);
injector.add([WorksheetProtectionRuleModel]);
+ registerFormulaDependencies(injector);
+
const renderManagerService = injector.get(IRenderManagerService);
renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService] as Dependency);
renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetRenderController] as Dependency);
@@ -235,3 +236,34 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
injector,
};
}
+
+function registerFormulaDependencies(injector: Injector) {
+ injector.add([CalculateFormulaService]);
+ injector.add([Lexer]);
+ injector.add([LexerTreeBuilder]);
+
+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);
+ injector.add([IDependencyManagerService, { useClass: DependencyManagerService }]);
+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);
+ injector.add([IFunctionService, { useClass: FunctionService }]);
+ injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);
+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);
+ injector.add([ISuperTableService, { useClass: SuperTableService }]);
+ injector.add([CalculateController]);
+
+ injector.add([IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }]);
+ 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]);
+}
diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.ts
index 9d9f680efd..9227a70140 100644
--- a/packages/facade/src/apis/facade.ts
+++ b/packages/facade/src/apis/facade.ts
@@ -61,6 +61,7 @@ import { FSheetHooks } from './sheets/f-sheet-hooks';
import { FHooks } from './f-hooks';
import { FDataValidationBuilder } from './sheets/f-data-validation-builder';
import { FPermission } from './sheets/f-permission';
+import { FFormula } from './sheets/f-formula';
export class FUniver {
static BorderStyle = BorderStyleTypes;
@@ -306,6 +307,10 @@ export class FUniver {
});
}
+ getFormula(): FFormula {
+ return this._injector.createInstance(FFormula);
+ }
+
// #region
/**
diff --git a/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
index eb1a1ee695..623ea5ba48 100644
--- a/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
@@ -27,7 +27,7 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
-import { FunctionService, IFunctionService } from '@univerjs/engine-formula';
+import { FunctionService, IFunctionService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { ISocketService, WebSocketService } from '@univerjs/network';
import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import {
@@ -102,6 +102,7 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depen
injector.get(LocaleService).load({ zhCN, enUS });
univer.registerPlugin(TestPlugin);
+ univer.registerPlugin(UniverFormulaEnginePlugin);
const sheet = univer.createUniverSheet(workbookData || getTestWorkbookDataDemo());
const univerInstanceService = injector.get(IUniverInstanceService);
diff --git a/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
new file mode 100644
index 0000000000..8728abc00a
--- /dev/null
+++ b/packages/facade/src/apis/sheets/__tests__/f-formula.spec.ts
@@ -0,0 +1,105 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICellData, Injector, IStyleData, Nullable } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { SetArrayFormulaDataMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
+import type { FUniver } from '../../facade';
+import { createFacadeTestBed } from '../../__tests__/create-test-bed';
+
+describe('Test FFormula', () => {
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let univerAPI: FUniver;
+ let getValueByPosition: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Nullable<ICellData>;
+ let getStyleByPosition: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Nullable<IStyleData>;
+
+ beforeEach(() => {
+ const testBed = createFacadeTestBed();
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetStyleCommand);
+ commandService.registerCommand(SetVerticalTextAlignCommand);
+ commandService.registerCommand(SetHorizontalTextAlignCommand);
+ commandService.registerCommand(SetTextWrapCommand);
+ commandService.registerCommand(SetFormulaCalculationStartMutation);
+ commandService.registerCommand(SetFormulaCalculationStopMutation);
+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetArrayFormulaDataMutation);
+
+ getValueByPosition = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Nullable<ICellData> =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValue();
+
+ getStyleByPosition = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Nullable<IStyleData> => {
+ const value = getValueByPosition(startRow, startColumn, endRow, endColumn);
+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();
+ if (value && styles) {
+ return styles.getStyleByCell(value);
+ }
+ };
+ });
+
+ it('FFormula executeCalculation', () => {
+ const formula = univerAPI.getFormula();
+
+ formula.calculationStart((forceCalculate) => {
+ expect(forceCalculate).toBe(true);
+ });
+
+ formula.calculationProcessing((stageInfo) => {
+ expect(stageInfo).toBeDefined();
+ });
+
+ formula.calculationEnd((functionsExecutedState) => {
+ expect(functionsExecutedState).toBeDefined();
+ });
+
+ formula.executeCalculation();
+ formula.stopCalculation();
+ });
+});
diff --git a/packages/facade/src/apis/sheets/f-formula.ts b/packages/facade/src/apis/sheets/f-formula.ts
new file mode 100644
index 0000000000..ea4b4d6ea3
--- /dev/null
+++ b/packages/facade/src/apis/sheets/f-formula.ts
@@ -0,0 +1,99 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IDisposable } from '@univerjs/core';
+import { ICommandService } from '@univerjs/core';
+import type { FormulaExecutedStateType, IExecutionInProgressParams, ISetFormulaCalculationNotificationMutation, ISetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import { SetFormulaCalculationNotificationMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
+
+/**
+ * This interface class provides methods to modify the behavior of the operation formula.
+ */
+export class FFormula {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ }
+
+ /**
+ * Start the calculation of the formula.
+ */
+ executeCalculation(): void {
+ this._commandService.executeCommand(
+ SetFormulaCalculationStartMutation.id,
+ {
+ commands: [],
+ forceCalculation: true,
+ },
+ {
+ onlyLocal: true,
+ }
+ );
+ }
+
+ /**
+ * Stop the calculation of the formula.
+ */
+ stopCalculation(): void {
+ this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});
+ }
+
+ /**
+ * Listening calculation starts.
+ */
+ calculationStart(callback: (forceCalculation: boolean) => void): IDisposable {
+ return this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === SetFormulaCalculationStartMutation.id) {
+ const params = command.params as ISetFormulaCalculationStartMutation;
+ callback(params.forceCalculation);
+ }
+ });
+ }
+
+ /**
+ * Listening calculation ends.
+ */
+ calculationEnd(callback: (functionsExecutedState: FormulaExecutedStateType) => void): IDisposable {
+ return this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== SetFormulaCalculationNotificationMutation.id) {
+ return;
+ }
+
+ const params = command.params as ISetFormulaCalculationNotificationMutation;
+
+ if (params.functionsExecutedState !== undefined) {
+ callback(params.functionsExecutedState);
+ }
+ });
+ }
+
+ /**
+ * Listening calculation processing.
+ */
+ calculationProcessing(callback: (stageInfo: IExecutionInProgressParams) => void): IDisposable {
+ return this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== SetFormulaCalculationNotificationMutation.id) {
+ return;
+ }
+
+ const params = command.params as ISetFormulaCalculationNotificationMutation;
+
+ if (params.stageInfo !== undefined) {
+ callback(params.stageInfo);
+ }
+ });
+ }
+}