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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(formula): register function (#928)
Dushusir3511862e4944
diff --git a/packages/engine-formula/src/commands/mutations/register-function.mutation.ts b/packages/engine-formula/src/commands/mutations/register-function.mutation.tsnew file mode 100644index 0000000000..e1a81ec7ef--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/register-function.mutation.ts@@ -0,0 +1,39 @@+/**+ * 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 { IMutation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++/**+ *+ * Register function in main thread, then send function to worker thread.+ *+ * In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.+ * It requires setting local to true during execution.+ */++export interface IRegisterFunctionMutationParam {+ /**+ * function string, function name+ */+ functions: [[string, string]];+}++export const RegisterFunctionMutation: IMutation<IRegisterFunctionMutationParam> = {+ id: 'formula.mutation.register-function',+ type: CommandType.MUTATION,+ handler: () => true,+};diff --git a/packages/engine-formula/src/commands/mutations/unregister-function.mutation.ts b/packages/engine-formula/src/commands/mutations/unregister-function.mutation.tsnew file mode 100644index 0000000000..bdae6c944e--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/unregister-function.mutation.ts@@ -0,0 +1,39 @@+/**+ * 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 { IMutation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++/**+ *+ * Register function in main thread, then send function to worker thread.+ *+ * In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.+ * It requires setting local to true during execution.+ */++export interface IUnregisterFunctionMutationParam {+ /**+ * Function string+ */+ functions: string[];+}++export const UnregisterFunctionMutation: IMutation<IUnregisterFunctionMutationParam> = {+ id: 'formula.mutation.unregister-function',+ type: CommandType.MUTATION,+ handler: () => true,+};diff --git a/packages/engine-formula/src/controller/formula.controller.ts b/packages/engine-formula/src/controller/formula.controller.tsindex 1e54765d9c..c0c0baaca9 100644--- a/packages/engine-formula/src/controller/formula.controller.ts+++ b/packages/engine-formula/src/controller/formula.controller.ts@@ -19,6 +19,7 @@ import type { Ctor } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import type { IFunctionNames } from '../basics/function';+import { RegisterFunctionMutation } from '../commands/mutations/register-function.mutation';import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';import {@@ -38,6 +39,7 @@ import {SetSuperTableMutation,SetSuperTableOptionMutation,} from '../commands/mutations/set-super-table.mutation';+import { UnregisterFunctionMutation } from '../commands/mutations/unregister-function.mutation';import { functionArray } from '../functions/array/function-map';import type { BaseFunction } from '../functions/base-function';import { functionCompatibility } from '../functions/compatibility/function-map';@@ -60,6 +62,7 @@ import { IFunctionService } from '../services/function.service';@OnLifecycle(LifecycleStages.Ready, FormulaController)export class FormulaController extends Disposable {constructor(+ private _function: Array<[Ctor<BaseFunction>, IFunctionNames]>,@ICommandService private readonly _commandService: ICommandService,@Inject(Injector) private readonly _injector: Injector,@IFunctionService private readonly _functionService: IFunctionService@@ -93,33 +96,39 @@ export class FormulaController extends Disposable {SetSuperTableMutation,RemoveSuperTableMutation,SetSuperTableOptionMutation,+ RegisterFunctionMutation,+ UnregisterFunctionMutation,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}private _registerFunctions() {- const functions: BaseFunction[] = [- ...functionArray,- ...functionCompatibility,- ...functionCube,- ...functionDatabase,- ...functionDate,- ...functionEngineering,- ...functionFinancial,- ...functionInformation,- ...functionLogical,- ...functionLookup,- ...functionMath,- ...functionMeta,- ...functionStatistical,- ...functionText,- ...functionUniver,- ...functionWeb,- ].map((registerObject) => {- const Func = registerObject[0] as Ctor<BaseFunction>;- const name = registerObject[1] as IFunctionNames;+ const functions: BaseFunction[] = (+ [+ ...functionArray,+ ...functionCompatibility,+ ...functionCube,+ ...functionDatabase,+ ...functionDate,+ ...functionEngineering,+ ...functionFinancial,+ ...functionInformation,+ ...functionLogical,+ ...functionLookup,+ ...functionMath,+ ...functionMeta,+ ...functionStatistical,+ ...functionText,+ ...functionUniver,+ ...functionWeb,+ ] as Array<[Ctor<BaseFunction>, IFunctionNames]>+ )+ .concat(this._function)+ .map((registerObject) => {+ const Func = registerObject[0] as Ctor<BaseFunction>;+ const name = registerObject[1] as IFunctionNames;- return new Func(name);- });+ return new Func(name);+ });this._functionService.registerExecutors(...functions);}diff --git a/packages/engine-formula/src/controller/register-function.controller.ts b/packages/engine-formula/src/controller/register-function.controller.tsnew file mode 100644index 0000000000..989301ba0f--- /dev/null+++ b/packages/engine-formula/src/controller/register-function.controller.ts@@ -0,0 +1,93 @@+/**+ * 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 } from '@univerjs/core';+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';++import type { IRegisterFunctionMutationParam } from '../commands/mutations/register-function.mutation';+import { RegisterFunctionMutation } from '../commands/mutations/register-function.mutation';+import type { IUnregisterFunctionMutationParam } from '../commands/mutations/unregister-function.mutation';+import { UnregisterFunctionMutation } from '../commands/mutations/unregister-function.mutation';+import { BaseFunction } from '../functions/base-function';+import { FormulaDataModel } from '../models/formula-data.model';+import { IFunctionService } from '../services/function.service';++@OnLifecycle(LifecycleStages.Ready, RegisterFunctionController)+export class RegisterFunctionController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,+ @IFunctionService private readonly _functionService: IFunctionService+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo, options) => {+ if (command.id === RegisterFunctionMutation.id) {+ const params = command.params as IRegisterFunctionMutationParam;++ if (params == null) {+ return;+ }++ const { functions } = params;++ const functionList = functions.map((func) => {+ const functionString = func[0];+ const functionName = func[1];++ return createFunction(functionString, functionName);+ });+ this._functionService.registerExecutors(...functionList);+ } else if (command.id === UnregisterFunctionMutation.id) {+ const params = command.params as IUnregisterFunctionMutationParam;++ if (params == null) {+ return;+ }++ const { functions } = params;++ this._functionService.unregisterExecutors(...functions);+ }+ })+ );+ }+}++class CustomFunction extends BaseFunction {+ override isCustom(): boolean {+ return true;+ }+}++function createFunction(functionString: string, functionName: string) {+ const instance = new CustomFunction(functionName);+ // eslint-disable-next-line @typescript-eslint/no-implied-eval+ const functionCalculate = new Function(`return ${functionString}`)();+ instance.calculateCustom = functionCalculate;++ return instance as BaseFunction;+}diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex c04e637d52..399daee798 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -35,6 +35,7 @@ export { includeFormulaLexerToken, isFormulaLexerToken, normalizeSheetName } froexport { convertUnitDataToRuntime } from './basics/runtime';export { matchToken } from './basics/token';export { compareToken } from './basics/token';+export { RegisterFunctionMutation } from './commands/mutations/register-function.mutation';export {type ISetArrayFormulaDataMutationParams,SetArrayFormulaDataMutation,@@ -64,6 +65,7 @@ export {SetSuperTableMutation,SetSuperTableOptionMutation,} from './commands/mutations/set-super-table.mutation';+export { UnregisterFunctionMutation } from './commands/mutations/unregister-function.mutation';export { LexerNode } from './engine/analysis/lexer-node';export { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';export { BaseReferenceObject, type FunctionVariantType } from './engine/reference-object/base-reference-object';@@ -71,6 +73,7 @@ export { RangeReferenceObject } from './engine/reference-object/range-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 { NumberValueObject } from './engine/value-object/primitive-object';export { BooleanValueObject } from './engine/value-object/primitive-object';export { StringValueObject } from './engine/value-object/primitive-object';diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex 8f6c78b281..788e8b2d2e 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -15,11 +15,13 @@*/import { Plugin } from '@univerjs/core';-import type { Dependency } from '@wendellhu/redi';+import type { Ctor, Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';+import type { IFunctionNames } from './basics/function';import { CalculateController } from './controller/calculate.controller';import { FormulaController } from './controller/formula.controller';+import { RegisterFunctionController } from './controller/register-function.controller';import { SetDefinedNameController } from './controller/set-defined-name.controller';import { SetFeatureCalculationController } from './controller/set-feature-calculation.controller';import { SetOtherFormulaController } from './controller/set-other-formula.controller';@@ -39,6 +41,7 @@ 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 { BaseFunction } from './functions/base-function';import { FormulaDataModel } from './models/formula-data.model';import { CalculateFormulaService } from './services/calculate-formula.service';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from './services/current-data.service';@@ -56,6 +59,7 @@ const PLUGIN_NAME = 'base-formula-engine';interface IUniverFormulaEngine {notExecuteFormula?: boolean;+ function: Array<[Ctor<BaseFunction>, IFunctionNames]>;}export class UniverFormulaEnginePlugin extends Plugin {@@ -85,7 +89,12 @@ export class UniverFormulaEnginePlugin extends Plugin {[LexerTreeBuilder],//Controllers- [FormulaController],+ [+ FormulaController,+ {+ useFactory: () => this._injector.createInstance(FormulaController, this._config?.function || []),+ },+ ],[SetFeatureCalculationController],];@@ -104,6 +113,7 @@ export class UniverFormulaEnginePlugin extends Plugin {[SetDefinedNameController],[SetOtherFormulaController],[SetSuperTableController],+ [RegisterFunctionController],// Calculation engine[FormulaDependencyGenerator],diff --git a/packages/engine-formula/src/services/function.service.ts b/packages/engine-formula/src/services/function.service.tsindex 5a9afdc0ba..3f53436873 100644--- a/packages/engine-formula/src/services/function.service.ts+++ b/packages/engine-formula/src/services/function.service.ts@@ -43,6 +43,8 @@ export interface IFunctionService {hasExecutor(functionToken: IFunctionNames): boolean;+ unregisterExecutors(...functionTokens: IFunctionNames[]): void;+registerDescriptions(...functions: IFunctionInfo[]): void;getDescriptions(): Map<IFunctionNames, IFunctionInfo>;@@ -50,6 +52,8 @@ export interface IFunctionService {getDescription(functionToken: IFunctionNames): Nullable<IFunctionInfo>;hasDescription(functionToken: IFunctionNames): boolean;++ unregisterDescriptions(...functionTokens: IFunctionNames[]): void;}export class FunctionService extends Disposable implements IFunctionService {@@ -81,6 +85,13 @@ export class FunctionService extends Disposable implements IFunctionService {return this._functionExecutors.has(functionToken);}+ unregisterExecutors(...functionTokens: IFunctionNames[]) {+ for (let i = 0; i < functionTokens.length; i++) {+ const functionToken = functionTokens[i];+ this._functionExecutors.delete(functionToken);+ }+ }+registerDescriptions(...descriptions: IFunctionInfo[]) {for (let i = 0; i < descriptions.length; i++) {const description = descriptions[i];@@ -99,6 +110,13 @@ export class FunctionService extends Disposable implements IFunctionService {hasDescription(functionToken: IFunctionNames) {return this._functionDescriptions.has(functionToken);}++ unregisterDescriptions(...functionTokens: IFunctionNames[]) {+ for (let i = 0; i < functionTokens.length; i++) {+ const functionToken = functionTokens[i];+ this._functionDescriptions.delete(functionToken);+ }+ }}export const IFunctionService = createIdentifier<FunctionService>('univer.formula.function.service');diff --git a/packages/facade/package.json b/packages/facade/package.jsonindex 3b65ecad0d..635f97701b 100644--- a/packages/facade/package.json+++ b/packages/facade/package.json@@ -45,6 +45,7 @@"dependencies": {"@univerjs/core": "workspace:*","@univerjs/sheets": "workspace:*",+ "@univerjs/sheets-formula": "workspace:*","@wendellhu/redi": "^0.12.13","rxjs": "^7.8.1"},diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.tsindex 126138f49a..f3fd34d361 100644--- a/packages/facade/src/apis/facade.ts+++ b/packages/facade/src/apis/facade.ts@@ -15,7 +15,9 @@*/import type { IWorkbookData } from '@univerjs/core';-import { IUniverInstanceService, Univer } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, Univer } from '@univerjs/core';+import type { IRegisterFunctionParams, IUnregisterFunctionParams } from '@univerjs/sheets-formula';+import { IRegisterFunctionService } from '@univerjs/sheets-formula';import { Inject, Injector } from '@wendellhu/redi';import { FWorkbook } from './sheet/f-workbook';@@ -31,7 +33,9 @@ export class FUniver {constructor(@Inject(Injector) private readonly _injector: Injector,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @ICommandService private readonly _commandService: ICommandService,+ @IRegisterFunctionService private readonly _registerFunctionService: IRegisterFunctionService) {}createUniverSheet(data: IWorkbookData): FWorkbook {@@ -47,4 +51,12 @@ export class FUniver {return this._injector.createInstance(FWorkbook, workbook);}++ registerFunction(config: IRegisterFunctionParams) {+ this._registerFunctionService.registerFunctions(config);+ }++ unregisterFunction(config: IUnregisterFunctionParams) {+ this._registerFunctionService.unregisterFunctions(config);+ }}diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.tsindex d682c5d976..d8b666ea44 100644--- a/packages/sheets-formula/src/formula-ui-plugin.ts+++ b/packages/sheets-formula/src/formula-ui-plugin.ts@@ -15,8 +15,8 @@*/import { IUniverInstanceService, LocaleService, Plugin, PluginType } from '@univerjs/core';-import type { IFunctionInfo } from '@univerjs/engine-formula';-import type { Dependency } from '@wendellhu/redi';+import type { BaseFunction, IFunctionInfo, IFunctionNames } from '@univerjs/engine-formula';+import type { Ctor, Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';@@ -33,12 +33,20 @@ import { UpdateFormulaController } from './controllers/update-formula.controllerimport { zhCN } from './locale';import { ActiveDirtyManagerService, IActiveDirtyManagerService } from './services/active-dirty-manager.service';import { DescriptionService, IDescriptionService } from './services/description.service';+import {+ FormulaCustomFunctionService,+ IFormulaCustomFunctionService,+} from './services/formula-custom-function.service';import { FormulaInputService, IFormulaInputService } from './services/formula-input.service';import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';+import { IRegisterFunctionService, RegisterFunctionService } from './services/register-function.service';-// TODO@Dushusir: user config IFunctionInfo, we will register all function info in formula engine+/**+ * The configuration of the formula UI plugin.+ */interface IFormulaUIConfig {description: IFunctionInfo[];+ function: Array<[Ctor<BaseFunction>, IFunctionNames]>;}export class UniverSheetsFormulaPlugin extends Plugin {static override type = PluginType.Sheet;@@ -65,10 +73,13 @@ export class UniverSheetsFormulaPlugin extends Plugin {IDescriptionService,{useFactory: () =>- this._injector.createInstance(DescriptionService, this._config?.description || []), // TODO@Dusuhir: initialize config with asynchronous method?+ this._injector.createInstance(DescriptionService, this._config?.description || []),},],+ [IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }],[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [IRegisterFunctionService, { useClass: RegisterFunctionService }],+// controllers[FormulaUIController],[PromptController],diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.tsindex 3afcd0d705..7eb05fb162 100644--- a/packages/sheets-formula/src/index.ts+++ b/packages/sheets-formula/src/index.ts@@ -16,3 +16,5 @@export { UniverSheetsFormulaPlugin } from './formula-ui-plugin';export { enUS, zhCN } from './locale';+export type { IRegisterFunctionParams, IUnregisterFunctionParams } from './services/register-function.service';+export { IRegisterFunctionService } from './services/register-function.service';diff --git a/packages/sheets-formula/src/locale/function-list/math/ja-JP.ts b/packages/sheets-formula/src/locale/function-list/math/ja-JP.tsindex d848afa28b..1f418d5bd0 100644--- a/packages/sheets-formula/src/locale/function-list/math/ja-JP.ts+++ b/packages/sheets-formula/src/locale/function-list/math/ja-JP.ts@@ -1018,8 +1018,14 @@ export default {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ number1: {+ name: '数値1',+ detail: '加算する最初の数。 ここには 4 のような数値、B6 のようなセル参照、B2:B8 のようなセル範囲を指定できます。',+ },+ number2: {+ name: '数値2',+ detail: 'これは、加算する 2 番目の数値です。 この方法で最大 255 個の数値を指定することができます。',+ },},},SUMIF: {diff --git a/packages/sheets-formula/src/services/description.service.ts b/packages/sheets-formula/src/services/description.service.tsindex f80cf54c9f..4e65950c09 100644--- a/packages/sheets-formula/src/services/description.service.ts+++ b/packages/sheets-formula/src/services/description.service.ts@@ -80,18 +80,31 @@ export interface IDescriptionService {* @returns*/getSearchListByType(type: number): ISearchItem[];++ /**+ * register descriptions+ * @param functionList+ */+ registerDescriptions(functionList: IFunctionInfo[]): void;++ /**+ * unregister descriptions+ * @param functionList+ */+ unregisterDescriptions(functionNames: string[]): void;}export const IDescriptionService = createIdentifier<IDescriptionService>('formula-ui.description-service');export class DescriptionService implements IDescriptionService, IDisposable {+ private _descriptions: IFunctionInfo[] = [];+constructor(private _description: IFunctionInfo[],@IFunctionService private readonly _functionService: IFunctionService,@Inject(LocaleService) private readonly _localeService: LocaleService) {this._initialize();- this._registerDescription();}dispose(): void {@@ -153,15 +166,27 @@ export class DescriptionService implements IDescriptionService, IDisposable {return searchList;}+ registerDescriptions(description: IFunctionInfo[]) {+ this._descriptions = this._descriptions.concat(description);+ this._registerDescriptions();+ }++ unregisterDescriptions(functionNames: string[]) {+ this._descriptions = this._descriptions.filter((item) => !functionNames.includes(item.functionName));++ this._functionService.unregisterDescriptions(...functionNames);+ }+private _initialize() {this._localeService.localeChanged$.subscribe(() => {- this._registerDescription();+ this._registerDescriptions();});- }- private _registerDescription() {- const localeService = this._localeService;+ this._initDescription();+ this._registerDescriptions();+ }+ private _initDescription() {// TODO@Dushusir: Remove filtering after all formulas have been implementedconst functions = [...functionArray,@@ -186,8 +211,13 @@ export class DescriptionService implements IDescriptionService, IDisposable {return functions.includes(item.functionName as IFunctionNames);});- const functionList = filterFunctionList.concat(this._description || []);- const functionListLocale = functionList.map((functionInfo) => ({+ this._descriptions = filterFunctionList.concat(this._description);+ }++ private _registerDescriptions() {+ const localeService = this._localeService;++ const functionListLocale = this._descriptions.map((functionInfo) => ({functionName: getFunctionName(functionInfo, localeService),functionType: functionInfo.functionType,description: localeService.t(functionInfo.description),diff --git a/packages/sheets-formula/src/services/formula-custom-function.service.ts b/packages/sheets-formula/src/services/formula-custom-function.service.tsnew file mode 100644index 0000000000..c38ec57740--- /dev/null+++ b/packages/sheets-formula/src/services/formula-custom-function.service.ts@@ -0,0 +1,74 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, ICommandService } from '@univerjs/core';+import type { PrimitiveValueType } from '@univerjs/engine-formula';+import { RegisterFunctionMutation, UnregisterFunctionMutation } from '@univerjs/engine-formula';+import { createIdentifier } from '@wendellhu/redi';++export type IRegisterFunction = (+ ...arg: Array<PrimitiveValueType | PrimitiveValueType[][]>+) => PrimitiveValueType | PrimitiveValueType[][];++export type IRegisterFunctionList = [[IRegisterFunction, string, string?]];++export interface IFormulaCustomFunctionService {+ /**+ * register descriptions+ * @param functionList+ */+ registerFunctions(functionList: IRegisterFunctionList): void;++ unregisterFunctions(functionList: string[]): void;+}++export const IFormulaCustomFunctionService = createIdentifier<IFormulaCustomFunctionService>(+ 'formula-ui.formula-custom-function-service'+);++export class FormulaCustomFunctionService extends Disposable implements IFormulaCustomFunctionService {+ constructor(@ICommandService private readonly _commandService: ICommandService) {+ super();+ }++ registerFunctions(functionList: IRegisterFunctionList) {+ const functions = functionList.map((func) => [func[0].toString(), func[1]]);++ // Synchronous to worker+ this._commandService.executeCommand(+ RegisterFunctionMutation.id,+ {+ functions,+ },+ {+ local: true,+ }+ );+ }++ unregisterFunctions(functionList: string[]) {+ // Synchronous to worker+ this._commandService.executeCommand(+ UnregisterFunctionMutation.id,+ {+ functions: functionList,+ },+ {+ local: true,+ }+ );+ }+}diff --git a/packages/sheets-formula/src/services/register-function.service.ts b/packages/sheets-formula/src/services/register-function.service.tsnew file mode 100644index 0000000000..0191adcc87--- /dev/null+++ b/packages/sheets-formula/src/services/register-function.service.ts@@ -0,0 +1,126 @@+/**+ * 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 { ILocales } from '@univerjs/core';+import { Disposable, LocaleService } from '@univerjs/core';+import type { IFunctionInfo } from '@univerjs/engine-formula';+import { FunctionType, IFunctionService } from '@univerjs/engine-formula';+import { createIdentifier, Inject } from '@wendellhu/redi';++import { IDescriptionService } from './description.service';+import type { IRegisterFunctionList } from './formula-custom-function.service';+import { IFormulaCustomFunctionService } from './formula-custom-function.service';++/**+ * Register function operation params+ */+export interface IRegisterFunctionParams {+ /**+ * i18n+ */+ locales?: ILocales;++ /**+ * function description+ */+ description?: IFunctionInfo[];++ /**+ * function calculation+ */+ calculate: IRegisterFunctionList;+}++/**+ * Unregister function operation params+ */+export interface IUnregisterFunctionParams {+ /**+ * Remove i18n+ */+ localeKeys?: string[];++ /**+ * Function name+ */+ functionNames: string[];+}++export interface IRegisterFunctionService {+ /**+ * register descriptions+ * @param functionList+ */+ registerFunctions(params: IRegisterFunctionParams): void;++ unregisterFunctions(params: IUnregisterFunctionParams): void;+}++export const IRegisterFunctionService = createIdentifier<IRegisterFunctionService>(+ 'formula-ui.register-function-service'+);++export class RegisterFunctionService extends Disposable implements IRegisterFunctionService {+ constructor(+ @Inject(LocaleService) private readonly _localeService: LocaleService,+ @Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,+ @Inject(IFormulaCustomFunctionService)+ private readonly _formulaCustomFunctionService: IFormulaCustomFunctionService,+ @IFunctionService private readonly _functionService: IFunctionService+ ) {+ super();+ }++ registerFunctions(params: IRegisterFunctionParams) {+ const { locales, description, calculate } = params;++ // i18n+ if (locales) {+ this._localeService.load(locales);+ }++ // description+ if (description) {+ this._descriptionService.registerDescriptions(description);+ } else {+ const descriptionList: IFunctionInfo[] = calculate.map(([func, functionName, functionIntroduction]) => {+ return {+ functionName,+ functionType: FunctionType.User,+ description: '',+ abstract: functionIntroduction || '',+ functionParameter: [],+ };+ });++ this._functionService.registerDescriptions(...descriptionList);+ }++ // calculation+ this._formulaCustomFunctionService.registerFunctions(calculate);+ }++ unregisterFunctions(params: IUnregisterFunctionParams) {+ const { localeKeys, functionNames } = params;++ // remove i18n, @Dushusir: after localeService has remove method+ // localeKeys && this._localeService.remove(localeKeys);++ this._descriptionService.unregisterDescriptions(functionNames);++ this._formulaCustomFunctionService.unregisterFunctions(functionNames);+ }+}diff --git a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsxindex f507c48def..61c47d7071 100644--- a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx+++ b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx@@ -62,23 +62,13 @@ export function HelpFunction() {const { left, top, height } = position;- const localeInfo: IFunctionInfo = {- functionName: functionInfo.functionName,- functionType: functionInfo.functionType,- description: localeService.t(functionInfo.description),- abstract: localeService.t(functionInfo.abstract),- functionParameter: functionInfo.functionParameter.map((item) => ({- name: localeService.t(item.name),- detail: localeService.t(item.detail),- example: item.example,- require: item.require,- repeat: item.repeat,- })),- };+ if (functionInfo.description === '' && functionInfo.functionParameter.length === 0) {+ return;+ }setOffset([left, top + height]);setParamIndex(paramIndex);- setFunctionInfo(localeInfo);+ setFunctionInfo(functionInfo);setDecoratorPosition({ left, top });setVisible(visible);});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cd9b341c11..943e1a1a6b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -586,6 +586,9 @@ importers:'@univerjs/sheets':specifier: workspace:*version: link:../sheets+ '@univerjs/sheets-formula':+ specifier: workspace:*+ version: link:../sheets-formula'@wendellhu/redi':specifier: ^0.12.13version: 0.12.13@@ -3047,33 +3050,33 @@ packages:chalk: 4.1.2dev: true- /@csstools/[email protected](@csstools/[email protected]):- resolution: {integrity: sha512-abypo6m9re3clXA00eu5syw+oaPHbJTPapu9C4pzNsJ4hdZDzushT50Zhu+iIYXgEe1CxnRMn7ngsbV+MLrlpQ==}+ /@csstools/[email protected](@csstools/[email protected]):+ resolution: {integrity: sha512-sLYGdAdEY2x7TSw9FtmdaTrh2wFtRJO5VMbBrA8tEqEod7GEggFmxTSK9XqExib3yMuYNcvcTdCZIP6ukdjAIA==}engines: {node: ^14 || ^16 || >=18}peerDependencies:- '@csstools/css-tokenizer': ^2.2.3+ '@csstools/css-tokenizer': ^2.2.1dependencies:- '@csstools/css-tokenizer': 2.2.3+ '@csstools/css-tokenizer': 2.2.1dev: true- /@csstools/[email protected]:- resolution: {integrity: sha512-pp//EvZ9dUmGuGtG1p+n17gTHEOqu9jO+FiCUjNN3BDmyhdA2Jq9QsVeR7K8/2QCK17HSsioPlTW9ZkzoWb3Lg==}+ /@csstools/[email protected]:+ resolution: {integrity: sha512-Zmsf2f/CaEPWEVgw29odOj+WEVoiJy9s9NOv5GgNY9mZ1CZ7394By6wONrONrTsnNDv6F9hR02nvFihrGVGHBg==}engines: {node: ^14 || ^16 || >=18}dev: true- resolution: {integrity: sha512-lHPKJDkPUECsyAvD60joYfDmp8UERYxHGkFfyLJFTVK/ERJe0sVlIFLXU5XFxdjNDTerp5L4KeaKG+Z5S94qxQ==}+ resolution: {integrity: sha512-IxVBdYzR8pYe89JiyXQuYk4aVVoCPhMJkz6ElRwlVysjwURTsTk/bmY/z4FfeRE+CRBMlykPwXEVUg8lThv7AQ==}engines: {node: ^14 || ^16 || >=18}peerDependencies:- '@csstools/css-parser-algorithms': ^2.5.0- '@csstools/css-tokenizer': ^2.2.3+ '@csstools/css-parser-algorithms': ^2.3.2+ '@csstools/css-tokenizer': ^2.2.1dependencies:- '@csstools/css-parser-algorithms': 2.5.0(@csstools/[email protected])- '@csstools/css-tokenizer': 2.2.3+ '@csstools/css-parser-algorithms': 2.3.2(@csstools/[email protected])+ '@csstools/css-tokenizer': 2.2.1dev: true- /@csstools/[email protected]([email protected]):- resolution: {integrity: sha512-NPljRHkq4a14YzZ3YD406uaxh7s0g6eAq3L9aLOWywoqe8PkYamAvtsh7KNX6c++ihDrJ0RiU+/z7rGnhlZ5ww==}+ /@csstools/[email protected]([email protected]):+ resolution: {integrity: sha512-hBI9tfBtuPIi885ZsZ32IMEU/5nlZH/KOVYJCOh7gyMxaVLGmLedYqFN6Ui1LXkI8JlC8IsuC0rF0btcRZKd5g==}engines: {node: ^14 || ^16 || >=18}peerDependencies:postcss-selector-parser: ^6.0.13@@ -12341,10 +12344,10 @@ packages:engines: {node: ^14.13.1 || >=16.0.0}hasBin: truedependencies:- '@csstools/css-parser-algorithms': 2.5.0(@csstools/[email protected])- '@csstools/css-tokenizer': 2.2.3- '@csstools/media-query-list-parser': 2.1.7(@csstools/[email protected])(@csstools/[email protected])- '@csstools/selector-specificity': 3.0.1([email protected])+ '@csstools/css-parser-algorithms': 2.3.2(@csstools/[email protected])+ '@csstools/css-tokenizer': 2.2.1+ '@csstools/media-query-list-parser': 2.1.5(@csstools/[email protected])(@csstools/[email protected])+ '@csstools/selector-specificity': 3.0.0([email protected])balanced-match: 2.0.0colord: 2.9.3cosmiconfig: 8.3.6([email protected])