Skip to content

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

feat(formula): add register async function (#4399)

#FF0000c8d287b2a494
diff --git a/packages/engine-formula/src/engine/ast-node/function-node.ts b/packages/engine-formula/src/engine/ast-node/function-node.ts
index e2f2eafdb4..f219b3011a 100644
--- a/packages/engine-formula/src/engine/ast-node/function-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/function-node.ts
@@ -22,8 +22,8 @@ import type {
AsyncObject,
BaseReferenceObject,
FunctionVariantType,
- NodeValueType,
-} from '../reference-object/base-reference-object';
+ NodeValueType } from '../reference-object/base-reference-object';
+import type { FormulaFunctionValueType } from '../value-object/primitive-object';
import { Inject, Injector } from '@univerjs/core';
import { AstNodePromiseType } from '../../basics/common';
import { ErrorType } from '../../basics/error-type';
@@ -32,6 +32,7 @@ import { FormulaDataModel } from '../../models/formula-data.model';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
import { IDefinedNamesService } from '../../services/defined-names.service';
import { IFunctionService } from '../../services/function.service';
+
import { IFormulaRuntimeService } from '../../services/runtime.service';
import { prefixHandler } from '../utils/prefixHandler';
import { ArrayValueObject, transformToValueObject, ValueObjectFactory } from '../value-object/array-value-object';
@@ -96,7 +97,7 @@ export class FunctionNode extends BaseAstNode {
}
}
- const resultVariant = this._calculate(variants);
+ const resultVariant = await this._calculateAsync(variants);
let result: FunctionVariantType;
if (resultVariant.isAsyncObject() || resultVariant.isAsyncArrayObject()) {
result = await (resultVariant as AsyncObject | AsyncArrayObject).getValue();
@@ -202,52 +203,90 @@ export class FunctionNode extends BaseAstNode {
}
}
+ /**
+ * Transform the result of a custom function to a NodeValueType.
+ */
+ private _handleCustomResult(resultVariantCustom: FormulaFunctionValueType): NodeValueType {
+ if (typeof resultVariantCustom !== 'object' || resultVariantCustom == null) {
+ return ValueObjectFactory.create(resultVariantCustom);
+ }
+
+ const arrayValues = transformToValueObject(resultVariantCustom);
+ return ArrayValueObject.create({
+ calculateValueList: arrayValues,
+ rowCount: arrayValues.length,
+ columnCount: arrayValues[0]?.length || 0,
+ unitId: '',
+ sheetId: '',
+ row: -1,
+ column: -1,
+ });
+ }
+
+ private _handleAddressFunction() {
+ /**
+ * In Excel, to inject a defined name into a function that has positioning capabilities,
+ * such as using the INDIRECT function to reference a named range,
+ * you can write it as follows:
+ * =INDIRECT("DefinedName1")
+ */
+ if (this._functionExecutor.isAddress()) {
+ this._setDefinedNamesForFunction();
+ }
+ }
+
+ private _mapVariantsToValues(variants: BaseValueObject[]) {
+ return variants.map((variant) => {
+ if (variant.isArray()) {
+ return (variant as ArrayValueObject).toValue();
+ }
+ return variant.getValue();
+ });
+ }
+
private _calculate(variants: BaseValueObject[]) {
// Check the number of parameters
const { minParams, maxParams } = this._functionExecutor;
if (minParams !== -1 && maxParams !== -1 && (variants.length < minParams || variants.length > maxParams)) {
return ErrorValueObject.create(ErrorType.NA);
}
-
let resultVariant: NodeValueType;
this._setRefInfo();
if (this._functionExecutor.isCustom()) {
const resultVariantCustom = this._functionExecutor.calculateCustom(
- ...variants.map((variant) => {
- if (variant.isArray()) {
- return (variant as ArrayValueObject).toValue();
- }
+ ...this._mapVariantsToValues(variants)
+ ) as FormulaFunctionValueType;
+
+ resultVariant = this._handleCustomResult(resultVariantCustom);
+ } else {
+ this._handleAddressFunction();
+ resultVariant = this._functionExecutor.calculate(...variants);
+ }
- return variant.getValue();
- })
+ return resultVariant;
+ }
+
+ private async _calculateAsync(variants: BaseValueObject[]) {
+ // Check the number of parameters
+ const { minParams, maxParams } = this._functionExecutor;
+ if (minParams !== -1 && maxParams !== -1 && (variants.length < minParams || variants.length > maxParams)) {
+ return ErrorValueObject.create(ErrorType.NA);
+ }
+
+ let resultVariant: NodeValueType;
+
+ this._setRefInfo();
+
+ if (this._functionExecutor.isCustom()) {
+ const resultVariantCustom = await this._functionExecutor.calculateCustom(
+ ...this._mapVariantsToValues(variants)
);
- if (typeof resultVariantCustom !== 'object' || resultVariantCustom == null) {
- resultVariant = ValueObjectFactory.create(resultVariantCustom);
- } else {
- const arrayValues = transformToValueObject(resultVariantCustom);
-
- resultVariant = ArrayValueObject.create({
- calculateValueList: arrayValues,
- rowCount: arrayValues.length,
- columnCount: arrayValues[0]?.length || 0,
- unitId: '',
- sheetId: '',
- row: -1,
- column: -1,
- });
- }
+
+ resultVariant = this._handleCustomResult(resultVariantCustom);
} else {
- /**
- * In Excel, to inject a defined name into a function that has positioning capabilities,
- * such as using the INDIRECT function to reference a named range,
- * you can write it as follows:
- * =INDIRECT("DefinedName1")
- */
- if (this._functionExecutor.isAddress()) {
- this._setDefinedNamesForFunction();
- }
+ this._handleAddressFunction();
resultVariant = this._functionExecutor.calculate(...variants);
}
diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.ts
index 0bdb62f04a..d7277a5df7 100644
--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts
+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts
@@ -27,6 +27,8 @@ import { BaseValueObject, ErrorValueObject } from './base-value-object';
export type PrimitiveValueType = string | boolean | number | null;
+export type FormulaFunctionValueType = PrimitiveValueType | PrimitiveValueType[][];
+
export class NullValueObject extends BaseValueObject {
private static _instance: NullValueObject;
diff --git a/packages/engine-formula/src/facade/f-formula.ts b/packages/engine-formula/src/facade/f-formula.ts
index c1bcc57d5c..b9aa9ff922 100644
--- a/packages/engine-formula/src/facade/f-formula.ts
+++ b/packages/engine-formula/src/facade/f-formula.ts
@@ -24,11 +24,16 @@ import { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, SetFormulaCalculationNotification
*/
export class FFormula extends FBase {
constructor(
- @Inject(ICommandService) private readonly _commandService: ICommandService,
+ @Inject(ICommandService) protected readonly _commandService: ICommandService,
@Inject(Injector) protected readonly _injector: Injector,
@IConfigService protected readonly _configService: IConfigService
) {
super();
+ this._initialize();
+ }
+
+ _initialize(): void {
+ // do nothing
}
/**
diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.ts
index f7f20bb5b6..789660d589 100644
--- a/packages/engine-formula/src/functions/base-function.ts
+++ b/packages/engine-formula/src/functions/base-function.ts
@@ -19,6 +19,7 @@ import type { IFunctionNames } from '../basics/function';
import type { BaseReferenceObject, FunctionVariantType, NodeValueType } from '../engine/reference-object/base-reference-object';
import type { ArrayBinarySearchType } from '../engine/utils/compare';
import type { ArrayValueObject } from '../engine/value-object/array-value-object';
+import type { FormulaFunctionValueType } from '../engine/value-object/primitive-object';
import type { FormulaDataModel } from '../models/formula-data.model';
import type { IDefinedNameMapItem } from '../services/defined-names.service';
import { ErrorType } from '../basics/error-type';
@@ -33,7 +34,7 @@ import { ArrayOrderSearchType } from '../engine/utils/compare';
import { serializeRangeToRefString } from '../engine/utils/reference';
import { convertTonNumber } from '../engine/utils/value-object';
import { type BaseValueObject, ErrorValueObject } from '../engine/value-object/base-value-object';
-import { NullValueObject, NumberValueObject, type PrimitiveValueType } from '../engine/value-object/primitive-object';
+import { NullValueObject, NumberValueObject } from '../engine/value-object/primitive-object';
export class BaseFunction {
private _unitId: Nullable<string>;
@@ -191,8 +192,8 @@ export class BaseFunction {
}
calculateCustom(
- ...arg: Array<PrimitiveValueType | PrimitiveValueType[][]>
- ): PrimitiveValueType | PrimitiveValueType[][] {
+ ...arg: Array<FormulaFunctionValueType>
+ ): FormulaFunctionValueType | Promise<FormulaFunctionValueType> {
return null;
}
diff --git a/packages/engine-formula/src/functions/custom-function.ts b/packages/engine-formula/src/functions/custom-function.ts
index 4c9a5baf02..b86c7dfbb1 100644
--- a/packages/engine-formula/src/functions/custom-function.ts
+++ b/packages/engine-formula/src/functions/custom-function.ts
@@ -21,3 +21,9 @@ export class CustomFunction extends BaseFunction {
return true;
}
}
+
+export class AsyncCustomFunction extends CustomFunction {
+ override isAsync(): boolean {
+ return true;
+ }
+}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 466e41f355..e0bc678a0f 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -99,7 +99,7 @@ export { handleRefStringInfo } from './engine/utils/reference';
export { generateStringWithSequence, type ISequenceNode, sequenceNodeType } from './engine/utils/sequence';
export { ArrayValueObject, ValueObjectFactory } from './engine/value-object/array-value-object';
export { BaseValueObject, ErrorValueObject } from './engine/value-object/base-value-object';
-export type { PrimitiveValueType } from './engine/value-object/primitive-object';
+export type { FormulaFunctionValueType, PrimitiveValueType } from './engine/value-object/primitive-object';
export { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from './engine/value-object/primitive-object';
export { functionArray } from './functions/array/function-map';
export { FUNCTION_NAMES_ARRAY } from './functions/array/function-names';
@@ -108,7 +108,7 @@ export { functionCompatibility } from './functions/compatibility/function-map';
export { FUNCTION_NAMES_COMPATIBILITY } from './functions/compatibility/function-names';
export { functionCube } from './functions/cube/function-map';
export { FUNCTION_NAMES_CUBE } from './functions/cube/function-names';
-export { CustomFunction } from './functions/custom-function';
+export { AsyncCustomFunction, CustomFunction } from './functions/custom-function';
export { functionDatabase } from './functions/database/function-map';
export { FUNCTION_NAMES_DATABASE } from './functions/database/function-names';
export { functionDate } from './functions/date/function-map';
diff --git a/packages/facade/src/apis/__tests__/facade.spec.ts b/packages/facade/src/apis/__tests__/facade.spec.ts
index df8ef21a24..83e90fa852 100644
--- a/packages/facade/src/apis/__tests__/facade.spec.ts
+++ b/packages/facade/src/apis/__tests__/facade.spec.ts
@@ -367,4 +367,38 @@ describe('Test FUniver', () => {
expect(worksheet.getComments().length).toBe(0);
expect(range.getComment()).toBeNull();
});
+
+ it('Function registerFunction should handle async function', () => {
+ const functionName = 'ASYNCFUNC';
+ const functionsDisposable = univerAPI.getFormula().registerFunction(functionName, () => {
+ return 42;
+ }, 'Async custom function');
+
+ const descriptionService = get(IDescriptionService);
+ const functionInfo = descriptionService.getFunctionInfo(functionName);
+
+ expect(functionInfo?.functionName).toBe(functionName);
+
+ functionsDisposable.dispose();
+
+ const functionInfoAfterDispose = descriptionService.getFunctionInfo(functionName);
+ expect(functionInfoAfterDispose).toBeUndefined();
+ });
+
+ it('Function registerFunction should handle async array function', () => {
+ const functionName = 'ASYNCARRAY';
+ const functionsDisposable = univerAPI.getFormula().registerAsyncFunction(functionName, async () => {
+ return [[1, 2], [3, 4]];
+ }, 'Async array function');
+
+ const descriptionService = get(IDescriptionService);
+ const functionInfo = descriptionService.getFunctionInfo(functionName);
+
+ expect(functionInfo?.functionName).toBe(functionName);
+
+ functionsDisposable.dispose();
+
+ const functionInfoAfterDispose = descriptionService.getFunctionInfo(functionName);
+ expect(functionInfoAfterDispose).toBeUndefined();
+ });
});
diff --git a/packages/sheets-formula/src/facade/f-formula.ts b/packages/sheets-formula/src/facade/f-formula.ts
index 475f66dd7f..1a33410d8e 100644
--- a/packages/sheets-formula/src/facade/f-formula.ts
+++ b/packages/sheets-formula/src/facade/f-formula.ts
@@ -14,11 +14,13 @@
* limitations under the License.
*/
-import type { CalculationMode, IUniverSheetsFormulaBaseConfig } from '@univerjs/sheets-formula';
+import type { IDisposable, ILocales } from '@univerjs/core';
-import { IConfigService, ILogService, LifecycleService, LifecycleStages } from '@univerjs/core';
-import { FFormula } from '@univerjs/engine-formula';
-import { PLUGIN_CONFIG_KEY_BASE } from '@univerjs/sheets-formula';
+import type { IFunctionInfo } from '@univerjs/engine-formula';
+import type { CalculationMode, IRegisterAsyncFunction, IRegisterFunction, ISingleFunctionRegisterParams, IUniverSheetsFormulaBaseConfig } from '@univerjs/sheets-formula';
+import { debounce, IConfigService, ILogService, LifecycleService, LifecycleStages } from '@univerjs/core';
+import { FFormula, SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
+import { IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionService } from '@univerjs/sheets-formula';
export interface IFFormulaSheetsMixin {
/**
@@ -27,9 +29,176 @@ export interface IFFormulaSheetsMixin {
* @returns
*/
setInitialFormulaComputing(calculationMode: CalculationMode): void;
+
+ /**
+ * Register a custom synchronous formula function.
+ *
+ * @param name - The name of the function to register. This will be used in formulas (e.g., =MYFUNC())
+ * @param func - The implementation of the function
+ * @param description - A string describing the function's purpose and usage
+ * @returns A disposable object that will unregister the function when disposed
+ * @example
+ * ```js
+ * univerAPI.getFormula().registerFunction('HELLO', (name) => `Hello, ${name}!`, 'A simple greeting function');
+ *
+ * // Use the function in a cell
+ * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue('World');
+ * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A2').setValue({ f: '=HELLO(A1)' });
+ * // A2 will display: "Hello, World!"
+ * ```
+ * @example
+ * ```js
+ * univerAPI.getFormula().registerFunction(
+ * 'DISCOUNT',
+ * (price, discountPercent) => price * (1 - discountPercent / 100),
+ * 'Calculates final price after discount'
+ * );
+ *
+ * // Use in cell
+ * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue(100);
+ * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A2').setValue({ f: '=DISCOUNT(A1, 20)' });
+ * // A2 will display: 80
+ * ```
+ */
+ registerFunction(name: string, func: IRegisterFunction, description?: string): IDisposable;
+
+ /**
+ * Register a custom synchronous formula function with localization support.
+ *
+ * @param name - The name of the function to register. This will be used in formulas (e.g., =MYFUNC())
+ * @param func - The implementation of the function
+ * @param options - Object containing locales and description
+ * @returns A disposable object that will unregister the function when disposed
+ *
+ * @example
+ * ```js
+ * univerAPI.getFormula().registerFunction('HELLO',
+ * (name) => {
+ * return `Hello, ${name}!`;
+ * },
+ * {
+ * description: 'customFunction.HELLO.description',
+ * locales: {
+ * 'zhCN': {
+ * 'customFunction' : {
+ * 'HELLO' : {
+ * 'description': '一个简单的问候函数'
+ * }
+ * }
+ * },
+ * 'enUS': {
+ * 'customFunction' : {
+ * 'HELLO' : {
+ * 'description': 'A simple greeting function'
+ * }
+ * }
+ * }
+ * }
+ * }
+ * );
+ *
+ * // Use in cell
+ * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue({ f: '=HELLO("John")' });
+ * // A1 will display: "Hello, John!"
+ * ```
+ */
+ registerFunction(name: string, func: IRegisterFunction, { locales, description }: { locales?: ILocales; description?: string | IFunctionInfo }): IDisposable;
+
+ /**
+ * Register a custom asynchronous formula function.
+ *
+ * @param name - The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC())
+ * @param func - The async implementation of the function
+ * @returns A disposable object that will unregister the function when disposed
+ *
+ * @example
+ * ```js
+ * univerAPI.getFormula().registerAsyncFunction('RANDOM_DELAYED',
+ * async () => {
+ * await new Promise(resolve => setTimeout(resolve, 500));
+ * return Math.random();
+ * },
+ * 'Mock a random number generation function'
+ * );
+ *
+ * // Use in cell
+ * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue({ f: '=RANDOM_DELAYED()' });
+ * // After 0.5 second, A1 will display a random number
+ * ```
+ */
+ registerAsyncFunction(name: string, func: IRegisterAsyncFunction, description?: string): IDisposable;
+ /**
+ * Register a custom asynchronous formula function with description.
+ *
+ * @param name - The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC())
+ * @param func - The async implementation of the function
+ * @param description - A string describing the function's purpose and usage
+ * @returns A disposable object that will unregister the function when disposed
+ *
+ * @example
+ * ```js
+ * // Mock a user score fetching function
+ * univerAPI.getFormula().registerAsyncFunction('FETCH_USER_SCORE',
+ * async (userId) => {
+ * await new Promise(resolve => setTimeout(resolve, 1000));
+ * // Mock fetching user score from database
+ * return userId * 10 + Math.floor(Math.random() * 20);
+ * },
+ * {
+ * description: 'customFunction.description.FETCH_USER_SCORE',
+ * locales: {
+ * 'zhCN': {
+ * 'customFunction': {
+ * 'description': {
+ * 'FETCH_USER_SCORE': '从数据库中获取用户分数'
+ * }
+ * }
+ * },
+ * 'enUS': {
+ * 'customFunction': {
+ * 'description': {
+ * 'FETCH_USER_SCORE': 'Mock fetching user score from database'
+ * }
+ * }
+ * }
+ * }
+ * }
+ * );
+ *
+ * // Use in cell
+ * univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1').setValue({ f: '=FETCH_USER_SCORE(42)' });
+ * // After 1 second, A1 will display a score
+ * ```
+ */
+ registerAsyncFunction(name: string, func: IRegisterAsyncFunction, { locales, description }: { locales?: ILocales; description?: string | IFunctionInfo }): IDisposable;
}
export class FFormulaSheetsMixin extends FFormula implements IFFormulaSheetsMixin {
+ /**
+ * registerFunction may be executed multiple times, triggering multiple formula forced refreshes
+ */
+ declare private _debouncedFormulaCalculation: () => void;
+
+ /**
+ * Initialize the FUniver instance.
+ *
+ * @private
+ */
+ override _initialize(): void {
+ this._debouncedFormulaCalculation = debounce(() => {
+ this._commandService.executeCommand(
+ SetFormulaCalculationStartMutation.id,
+ {
+ commands: [],
+ forceCalculation: true,
+ },
+ {
+ onlyLocal: true,
+ }
+ );
+ }, 10);
+ }
+
override setInitialFormulaComputing(calculationMode: CalculationMode): void {
const lifecycleService = this._injector.get(LifecycleService);
const lifecycleStage = lifecycleService.stage;
@@ -49,6 +218,58 @@ export class FFormulaSheetsMixin extends FFormula implements IFFormulaSheetsMixi
config.initialFormulaComputing = calculationMode;
}
+
+ override registerFunction(name: string, func: IRegisterFunction): IDisposable;
+ override registerFunction(name: string, func: IRegisterFunction, description: string): IDisposable;
+ override registerFunction(
+ name: string,
+ func: IRegisterFunction,
+ options?: string | { locales?: ILocales; description?: string | IFunctionInfo }
+ ): IDisposable {
+ let registerFunctionService = this._injector.get(IRegisterFunctionService);
+
+ if (!registerFunctionService) {
+ this._injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
+ registerFunctionService = this._injector.get(IRegisterFunctionService);
+ }
+
+ const params: ISingleFunctionRegisterParams = {
+ name,
+ func,
+ description: typeof options === 'string' ? options : options?.description ?? '',
+ locales: typeof options === 'object' ? options.locales : undefined,
+ };
+
+ const functionsDisposable = registerFunctionService.registerFunction(params);
+ this._debouncedFormulaCalculation();
+ return functionsDisposable;
+ }
+
+ override registerAsyncFunction(name: string, func: IRegisterAsyncFunction): IDisposable;
+ override registerAsyncFunction(name: string, func: IRegisterAsyncFunction, description: string): IDisposable;
+ override registerAsyncFunction(
+ name: string,
+ func: IRegisterAsyncFunction,
+ options?: string | { locales?: ILocales; description?: string | IFunctionInfo }
+ ): IDisposable {
+ let registerFunctionService = this._injector.get(IRegisterFunctionService);
+
+ if (!registerFunctionService) {
+ this._injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
+ registerFunctionService = this._injector.get(IRegisterFunctionService);
+ }
+
+ const params: ISingleFunctionRegisterParams = {
+ name,
+ func,
+ description: typeof options === 'string' ? options : options?.description ?? '',
+ locales: typeof options === 'object' ? options.locales : undefined,
+ };
+
+ const functionsDisposable = registerFunctionService.registerAsyncFunction(params);
+ this._debouncedFormulaCalculation();
+ return functionsDisposable;
+ }
}
FFormula.extend(FFormulaSheetsMixin);
diff --git a/packages/sheets-formula/src/facade/f-univer.ts b/packages/sheets-formula/src/facade/f-univer.ts
index a5a7f932cb..08181a2bc5 100644
--- a/packages/sheets-formula/src/facade/f-univer.ts
+++ b/packages/sheets-formula/src/facade/f-univer.ts
@@ -22,7 +22,7 @@ import { type IRegisterFunctionParams, IRegisterFunctionService, RegisterFunctio
export interface IFUniverSheetsFormulaMixin {
/**
* Register a function to the spreadsheet.
- *
+ * @deprecated Use `univerAPI.getFormula().registerFunction` instead.
* @param {IRegisterFunctionParams} config The configuration of the function.
* @returns {IDisposable} The disposable instance.
*/
diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.ts
index fd0198044e..ad2c576eea 100644
--- a/packages/sheets-formula/src/index.ts
+++ b/packages/sheets-formula/src/index.ts
@@ -19,6 +19,7 @@ export { OtherFormulaMarkDirty } from './commands/mutations/formula.mutation';
export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';
export { TriggerCalculationController } from './controllers/trigger-calculation.controller';
export { CalculationMode, type IUniverSheetsFormulaBaseConfig, PLUGIN_CONFIG_KEY_BASE } from './controllers/config.schema';
+export type { IRegisterAsyncFunction, IRegisterFunction, ISingleFunctionRegisterParams } from './services/register-function.service';
// #region - all commands
diff --git a/packages/sheets-formula/src/services/register-function.service.ts b/packages/sheets-formula/src/services/register-function.service.ts
index 3257ca5ecc..c1e14632f1 100644
--- a/packages/sheets-formula/src/services/register-function.service.ts
+++ b/packages/sheets-formula/src/services/register-function.service.ts
@@ -15,15 +15,19 @@
*/
import type { IDisposable, ILocales } from '@univerjs/core';
-import type { IFunctionInfo, PrimitiveValueType } from '@univerjs/engine-formula';
+import type { FormulaFunctionValueType, IFunctionInfo } from '@univerjs/engine-formula';
import { createIdentifier, Disposable, DisposableCollection, Inject, LocaleService, Optional, toDisposable } from '@univerjs/core';
-import { CustomFunction, FunctionType, IFunctionService } from '@univerjs/engine-formula';
+import { AsyncCustomFunction, CustomFunction, FunctionType, IFunctionService } from '@univerjs/engine-formula';
import { IDescriptionService } from './description.service';
import { IRemoteRegisterFunctionService } from './remote/remote-register-function.service';
export type IRegisterFunction = (
- ...arg: Array<PrimitiveValueType | PrimitiveValueType[][]>
-) => PrimitiveValueType | PrimitiveValueType[][];
+ ...arg: Array<FormulaFunctionValueType>
+) => FormulaFunctionValueType;
+
+export type IRegisterAsyncFunction = (
+ ...arg: Array<FormulaFunctionValueType>
+) => Promise<FormulaFunctionValueType>;
// [[Function, FunctionName, Description]]
export type IRegisterFunctionList = [[IRegisterFunction, string, string?]];
@@ -80,12 +84,47 @@ export interface IRegisterFunctionService {
* @param params
*/
registerFunctions(params: IRegisterFunctionParams): IDisposable;
+
+ /**
+ * register a single function
+ * @param params
+ */
+ registerFunction(params: ISingleFunctionRegisterParams): IDisposable;
+
+ /**
+ * register a single async function
+ * @param params
+ */
+ registerAsyncFunction(params: ISingleFunctionRegisterParams): IDisposable;
}
export const IRegisterFunctionService = createIdentifier<IRegisterFunctionService>(
'sheets-formula.register-function-service'
);
+export interface ISingleFunctionRegisterParams {
+ /**
+ * function name
+ */
+ name: string;
+ /**
+ * function calculation
+ */
+ func: IRegisterFunction | IRegisterAsyncFunction;
+ /**
+ * function description
+ */
+ description: string | IFunctionInfo;
+ /**
+ * function locales
+ */
+ locales?: ILocales;
+ /**
+ * function async
+ */
+ async?: boolean;
+}
+
export class RegisterFunctionService extends Disposable implements IRegisterFunctionService {
constructor(
@Inject(LocaleService) private readonly _localeService: LocaleService,
@@ -97,6 +136,14 @@ export class RegisterFunctionService extends Disposable implements IRegisterFunc
super();
}
+ registerFunction(params: ISingleFunctionRegisterParams): IDisposable {
+ return this._registerSingleFunction(params);
+ }
+
+ registerAsyncFunction(params: ISingleFunctionRegisterParams): IDisposable {
+ return this._registerSingleFunction({ ...params, async: true });
+ }
+
registerFunctions(params: IRegisterFunctionParams): IDisposable {
const { locales, description, calculate } = params;
@@ -132,6 +179,46 @@ export class RegisterFunctionService extends Disposable implements IRegisterFunc
return disposables;
}
+ private _registerSingleFunction(params: ISingleFunctionRegisterParams): IDisposable {
+ const { name, func, description, locales, async = false } = params;
+ const disposables = new DisposableCollection();
+
+ // Handle i18n
+ if (locales) {
+ this._localeService.load(locales);
+ }
+
+ // Handle description
+ if (typeof description === 'string') {
+ const functionInfo: IFunctionInfo = {
+ functionName: name,
+ functionType: FunctionType.User,
+ description,
+ abstract: description || '',
+ functionParameter: [],
+ };
+ disposables.add(this._descriptionService.registerDescriptions([functionInfo]));
+ } else {
+ disposables.add(this._descriptionService.registerDescriptions([description]));
+ }
+
+ // Handle function registration
+ const instance = async ? new AsyncCustomFunction(name) : new CustomFunction(name);
+ instance.calculateCustom = func;
+ this._functionService.registerExecutors(instance);
+ disposables.add(toDisposable(() => this._functionService.unregisterExecutors(name)));
+
+ // Handle remote registration if available
+ if (this._remoteRegisterFunctionService) {
+ this._remoteRegisterFunctionService.registerAsyncFunctions([[func.toString(), name]]);
+ disposables.add(
+ toDisposable(() => this._remoteRegisterFunctionService!.unregisterFunctions([name]))
+ );
+ }
+
+ return disposables;
+ }
+
private _registerLocalExecutors(list: IRegisterFunctionList): IDisposable {
const names = list.map(([_func, name]) => name);
const functions = list.map(([func, name]) => {
diff --git a/packages/sheets-formula/src/services/remote/remote-register-function.service.ts b/packages/sheets-formula/src/services/remote/remote-register-function.service.ts
index f89dff9617..b118bb0920 100644
--- a/packages/sheets-formula/src/services/remote/remote-register-function.service.ts
+++ b/packages/sheets-formula/src/services/remote/remote-register-function.service.ts
@@ -15,11 +15,12 @@
*/
import type { BaseFunction } from '@univerjs/engine-formula';
-import { CustomFunction, IFunctionService } from '@univerjs/engine-formula';
import { createIdentifier } from '@univerjs/core';
+import { AsyncCustomFunction, CustomFunction, IFunctionService } from '@univerjs/engine-formula';
export interface IRemoteRegisterFunctionService {
registerFunctions(serializedFuncs: Array<[string, string]>): Promise<void>;
+ registerAsyncFunctions(serializedFuncs: Array<[string, string]>): Promise<void>;
unregisterFunctions(names: string[]): Promise<void>;
}
@@ -42,6 +43,14 @@ export class RemoteRegisterFunctionService implements IRemoteRegisterFunctionSer
this._functionService.registerExecutors(...functionList);
}
+ async registerAsyncFunctions(serializedFuncs: Array<[string, string]>): Promise<void> {
+ const functionList = serializedFuncs.map(([func, name]) => {
+ return createAsyncFunction(func, name);
+ });
+
+ this._functionService.registerExecutors(...functionList);
+ }
+
async unregisterFunctions(names: string[]): Promise<void> {
this._functionService.unregisterDescriptions(...names);
}
@@ -52,6 +61,13 @@ function createFunction(functionString: string, functionName: string) {
// eslint-disable-next-line no-new-func
const functionCalculate = new Function(`return ${functionString}`)();
instance.calculateCustom = functionCalculate;
+ return instance as BaseFunction;
+}
+function createAsyncFunction(functionString: string, functionName: string) {
+ const instance = new AsyncCustomFunction(functionName);
+ // eslint-disable-next-line no-new-func
+ const functionCalculate = new Function(`return ${functionString}`)();
+ instance.calculateCustom = functionCalculate;
return instance as BaseFunction;
}