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: use rpc to register custom functions and remove mutations (#2738)

Wenzhao Hu9a17a6eabacb
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 97a1925c2c..946e3ad953 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -28,7 +28,6 @@ import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
import { UniverSheetsPlugin } from '@univerjs/sheets';
import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
-import { UniverSheetsConditionalFormattingPlugin } from '@univerjs/sheets-conditional-formatting';
import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';
import { UniverDebuggerPlugin } from '@univerjs/debugger';
@@ -36,8 +35,6 @@ import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';
import type { IThreadCommentMentionDataSource } from '@univerjs/thread-comment-ui';
import { IThreadCommentMentionDataService, UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';
-import { UniverThreadCommentPlugin } from '@univerjs/thread-comment';
-import { UniverSheetsThreadCommentBasePlugin } from '@univerjs/sheets-thread-comment-base';
import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';
import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';
@@ -47,7 +44,6 @@ import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';
import { FUniver } from '@univerjs/facade';
import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
-import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';
import { UniverSheetsSortUIPlugin } from '@univerjs/sheets-sort-ui';
import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';
import { enUS, ruRU, viVN, zhCN, zhTW } from '../locales';
@@ -71,57 +67,34 @@ const univer = new Univer({
logLevel: LogLevel.VERBOSE,
});
-// core plugins
-univer.registerPlugin(UniverDocsPlugin, {
- hasScroll: false,
-});
-univer.registerPlugin(UniverRenderEnginePlugin);
-univer.registerPlugin(UniverUIPlugin, {
- container: 'app',
-});
-window.univerAPI = FUniver.newAPI(univer);
+univer.registerPlugin(UniverRPCMainThreadPlugin, {
+ workerURL: './worker.js',
+} as IUniverRPCMainThreadConfig);
+univer.registerPlugin(UniverDocsPlugin, { hasScroll: false });
+univer.registerPlugin(UniverRenderEnginePlugin);
+univer.registerPlugin(UniverUIPlugin, { container: 'app' });
univer.registerPlugin(UniverDocsUIPlugin);
-
-univer.registerPlugin(UniverSheetsPlugin, {
- notExecuteFormula: true,
-});
+univer.registerPlugin(UniverSheetsPlugin, { notExecuteFormula: true });
univer.registerPlugin(UniverSheetsUIPlugin);
// sheet feature plugins
-
univer.registerPlugin(UniverSheetsNumfmtPlugin);
univer.registerPlugin(UniverSheetsZenEditorPlugin);
-univer.registerPlugin(UniverFormulaEnginePlugin, {
- notExecuteFormula: true,
-});
-univer.registerPlugin(UniverSheetsFormulaPlugin);
-univer.registerPlugin(UniverRPCMainThreadPlugin, {
- workerURL: './worker.js',
-} as IUniverRPCMainThreadConfig);
-
+univer.registerPlugin(UniverFormulaEnginePlugin, { notExecuteFormula: true });
+univer.registerPlugin(UniverSheetsFormulaPlugin, { notExecuteFormula: true });
+// hyperlink
univer.registerPlugin(UniverSheetsHyperLinkUIPlugin);
-
// data validation
univer.registerPlugin(UniverSheetsDataValidationPlugin);
-
// sort
-univer.registerPlugin(UniverSheetsSortPlugin);
univer.registerPlugin(UniverSheetsSortUIPlugin);
-
-// sheet condition formatting
-univer.registerPlugin(UniverSheetsConditionalFormattingPlugin);
+// condition formatting
univer.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);
-
// drawing
univer.registerPlugin(UniverSheetsDrawingUIPlugin);
// univer.registerPlugin(UniverDocsDrawingUIPlugin);
-// create univer sheet instance
-if (!IS_E2E) {
- univer.createUnit(UniverInstanceType.UNIVER_SHEET, DEFAULT_WORKBOOK_DATA_DEMO);
-}
-
const mockUser = {
userID: 'Owner_qxVnhPbQ',
name: 'Owner',
@@ -152,11 +125,8 @@ class CustomMentionDataService implements IThreadCommentMentionDataService {
}
}
-univer.registerPlugin(UniverThreadCommentPlugin);
-univer.registerPlugin(UniverThreadCommentUIPlugin, {
- overrides: [[IThreadCommentMentionDataService, { useClass: CustomMentionDataService }]],
-});
-univer.registerPlugin(UniverSheetsThreadCommentBasePlugin);
+// comment
+univer.registerPlugin(UniverThreadCommentUIPlugin, { overrides: [[IThreadCommentMentionDataService, { useClass: CustomMentionDataService }]] });
univer.registerPlugin(UniverSheetsThreadCommentPlugin);
// debugger plugin
@@ -166,12 +136,9 @@ const injector = univer.__getInjector();
const userManagerService = injector.get(UserManagerService);
userManagerService.setCurrentUser(mockUser);
-declare global {
- // eslint-disable-next-line ts/naming-convention
- interface Window {
- univer?: Univer;
- univerAPI?: ReturnType<typeof FUniver.newAPI>;
- }
+// create univer sheet instance
+if (!IS_E2E) {
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, DEFAULT_WORKBOOK_DATA_DEMO);
}
setTimeout(() => {
@@ -182,3 +149,12 @@ setTimeout(() => {
}, LOAD_LAZY_PLUGINS_TIMEOUT);
window.univer = univer;
+window.univerAPI = FUniver.newAPI(univer);
+
+declare global {
+ // eslint-disable-next-line ts/naming-convention
+ interface Window {
+ univer?: Univer;
+ univerAPI?: ReturnType<typeof FUniver.newAPI>;
+ }
+}
diff --git a/examples/src/sheets/worker.ts b/examples/src/sheets/worker.ts
index 179c9d99cb..bc72b2cdfc 100644
--- a/examples/src/sheets/worker.ts
+++ b/examples/src/sheets/worker.ts
@@ -18,6 +18,7 @@ import { LocaleType, LogLevel, Univer } from '@univerjs/core';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc';
import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverRemoteSheetsFormulaPlugin } from '@univerjs/sheets-formula';
// Univer web worker is also a univer application.
const univer = new Univer({
@@ -28,6 +29,7 @@ const univer = new Univer({
univer.registerPlugin(UniverSheetsPlugin, { onlyRegisterFormulaRelatedMutations: true });
univer.registerPlugin(UniverFormulaEnginePlugin);
univer.registerPlugin(UniverRPCWorkerThreadPlugin);
+univer.registerPlugin(UniverRemoteSheetsFormulaPlugin);
declare let self: WorkerGlobalScope & typeof globalThis & { univer: Univer };
self.univer = univer;
diff --git a/packages/engine-formula/src/commands/mutations/unregister-function.mutation.ts b/packages/engine-formula/src/commands/mutations/unregister-function.mutation.ts
deleted file mode 100644
index bdae6c944e..0000000000
--- a/packages/engine-formula/src/commands/mutations/unregister-function.mutation.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { 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.ts
index 1971290e0f..c497c03eb7 100644
--- a/packages/engine-formula/src/controller/formula.controller.ts
+++ b/packages/engine-formula/src/controller/formula.controller.ts
@@ -39,7 +39,6 @@ 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';
@@ -97,7 +96,6 @@ export class FormulaController extends Disposable {
RemoveSuperTableMutation,
SetSuperTableOptionMutation,
RegisterFunctionMutation,
- UnregisterFunctionMutation,
].forEach((mutation) => {
this._commandService.registerCommand(mutation);
this._dataSyncPrimaryController?.registerSyncingMutations(mutation);
diff --git a/packages/engine-formula/src/controller/register-function.controller.ts b/packages/engine-formula/src/controller/register-function.controller.ts
deleted file mode 100644
index 35b1c64c42..0000000000
--- a/packages/engine-formula/src/controller/register-function.controller.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { 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 no-new-func
- const functionCalculate = new Function(`return ${functionString}`)();
- instance.calculateCustom = functionCalculate;
-
- return instance as BaseFunction;
-}
diff --git a/packages/engine-formula/src/functions/custom-function.ts b/packages/engine-formula/src/functions/custom-function.ts
new file mode 100644
index 0000000000..4c9a5baf02
--- /dev/null
+++ b/packages/engine-formula/src/functions/custom-function.ts
@@ -0,0 +1,23 @@
+/**
+ * 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 { BaseFunction } from './base-function';
+
+export class CustomFunction extends BaseFunction {
+ override isCustom(): boolean {
+ return true;
+ }
+}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index df14b39158..f6cb4f1efe 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -67,6 +67,7 @@ export { StringValueObject, NullValueObject } from './engine/value-object/primit
export { functionArray } from './functions/array/function-map';
export { FUNCTION_NAMES_ARRAY } from './functions/array/function-names';
export { BaseFunction } from './functions/base-function';
+export { CustomFunction } from './functions/custom-function';
export { functionCompatibility } from './functions/compatibility/function-map';
export { FUNCTION_NAMES_COMPATIBILITY } from './functions/compatibility/function-names';
export { functionCube } from './functions/cube/function-map';
@@ -144,6 +145,5 @@ export {
export { SetFormulaDataMutation, type ISetFormulaDataMutationParams } from './commands/mutations/set-formula-data.mutation';
export { SetOtherFormulaMutation, RemoveOtherFormulaMutation, type ISetOtherFormulaMutationParams, type IRemoveOtherFormulaMutationParams } from './commands/mutations/set-other-formula.mutation';
export { SetSuperTableMutation, RemoveSuperTableMutation, SetSuperTableOptionMutation } from './commands/mutations/set-super-table.mutation';
-export { UnregisterFunctionMutation } from './commands/mutations/unregister-function.mutation';
// #endregion
diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.ts
index 16b21d5a54..39190a09ed 100644
--- a/packages/engine-formula/src/plugin.ts
+++ b/packages/engine-formula/src/plugin.ts
@@ -21,7 +21,6 @@ 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';
@@ -120,7 +119,6 @@ export class UniverFormulaEnginePlugin extends Plugin {
//Controller
[CalculateController],
[SetOtherFormulaController],
- [RegisterFunctionController],
[SetDependencyController],
// Calculation engine
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index 84c1d3d368..129989b2d7 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -35,9 +35,7 @@ import { ISocketService, WebSocketService } from '@univerjs/network';
import { RangeProtectionRuleModel, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import {
DescriptionService,
- FormulaCustomFunctionService,
IDescriptionService,
- IFormulaCustomFunctionService,
IRegisterFunctionService,
RegisterFunctionService,
} from '@univerjs/sheets-formula';
@@ -137,7 +135,6 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
]);
injector.add([IFunctionService, { useClass: FunctionService }]);
- injector.add([IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }]);
injector.add([ISocketService, { useClass: WebSocketService }]);
injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
diff --git a/packages/facade/src/apis/__tests__/facade.spec.ts b/packages/facade/src/apis/__tests__/facade.spec.ts
index c19e5d5374..5350d69d0d 100644
--- a/packages/facade/src/apis/__tests__/facade.spec.ts
+++ b/packages/facade/src/apis/__tests__/facade.spec.ts
@@ -30,7 +30,7 @@ import type {
import {
IRenderManagerService } from '@univerjs/engine-render';
import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';
-import { RegisterFunctionMutation, SetFormulaCalculationStartMutation, UnregisterFunctionMutation } from '@univerjs/engine-formula';
+import { RegisterFunctionMutation, SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import { IDescriptionService } from '@univerjs/sheets-formula';
import type { FUniver } from '../facade';
import { createFacadeTestBed } from './create-test-bed';
@@ -64,7 +64,6 @@ describe('Test FUniver', () => {
commandService.registerCommand(SetRangeValuesCommand);
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(RegisterFunctionMutation);
- commandService.registerCommand(UnregisterFunctionMutation);
commandService.registerCommand(SetStyleCommand);
commandService.registerCommand(SetFormulaCalculationStartMutation);
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 31532261d0..aff038e6b0 100644
--- a/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/sheets/__tests__/create-test-bed.ts
@@ -30,9 +30,7 @@ import { ISocketService, WebSocketService } from '@univerjs/network';
import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import {
DescriptionService,
- FormulaCustomFunctionService,
IDescriptionService,
- IFormulaCustomFunctionService,
IRegisterFunctionService,
RegisterFunctionService,
} from '@univerjs/sheets-formula';
@@ -96,7 +94,6 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depen
},
]);
injector.add([IFunctionService, { useClass: FunctionService }]);
- injector.add([IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }]);
injector.add([ISocketService, { useClass: WebSocketService }]);
dependencies?.forEach((d) => injector.add(d));
diff --git a/packages/rpc/src/index.ts b/packages/rpc/src/index.ts
index 906260509d..5d665465e3 100644
--- a/packages/rpc/src/index.ts
+++ b/packages/rpc/src/index.ts
@@ -30,5 +30,5 @@ export {
RemoteSyncServiceName,
} from './services/remote-instance/remote-instance.service';
export { ChannelService, IRPCChannelService } from './services/rpc/channel.service';
-export { ChannelClient, ChannelServer, type IMessageProtocol } from './services/rpc/rpc.service';
+export { ChannelClient, ChannelServer, type IMessageProtocol, fromModule, toModule } from './services/rpc/rpc.service';
export { IRemoteSyncService } from './services/remote-instance/remote-instance.service';
diff --git a/packages/sheets-formula/package.json b/packages/sheets-formula/package.json
index 9456bb978c..ddc3a9522a 100644
--- a/packages/sheets-formula/package.json
+++ b/packages/sheets-formula/package.json
@@ -69,6 +69,7 @@
"@univerjs/docs": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
+ "@univerjs/rpc": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
"@univerjs/ui": "workspace:*",
@@ -86,6 +87,7 @@
"@univerjs/docs": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
+ "@univerjs/rpc": "workspace:*",
"@univerjs/shared": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-numfmt": "workspace:*",
diff --git a/packages/sheets-formula/src/controllers/formula-ui.controller.ts b/packages/sheets-formula/src/controllers/formula-ui.controller.ts
index ecde1a1cae..73479c1c02 100644
--- a/packages/sheets-formula/src/controllers/formula-ui.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-ui.controller.ts
@@ -48,6 +48,7 @@ import { FormulaEditorShowController } from './formula-editor-show.controller';
export interface IUniverSheetsFormulaConfig {
menu: MenuConfig;
+ notExecuteFormula?: boolean;
description: IFunctionInfo[];
function: Array<[Ctor<BaseFunction>, IFunctionNames]>;
}
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index f264871920..3830c04083 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -17,10 +17,11 @@
import { DependentOn, Plugin, Tools, UniverInstanceType } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-
+import { fromModule, IRPCChannelService, toModule } from '@univerjs/rpc';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { IRefSelectionsService, SheetsSelectionsService } from '@univerjs/sheets';
+
import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
import { ActiveDirtyController } from './controllers/active-dirty.controller';
import { ArrayFormulaDisplayController } from './controllers/array-formula-display.controller';
@@ -31,12 +32,7 @@ import type { IUniverSheetsFormulaConfig } from './controllers/formula-ui.contro
import { DefaultSheetFormulaConfig, FormulaUIController } from './controllers/formula-ui.controller';
import { TriggerCalculationController } from './controllers/trigger-calculation.controller';
import { UpdateFormulaController } from './controllers/update-formula.controller';
-
import { DescriptionService, IDescriptionService } from './services/description.service';
-import {
- FormulaCustomFunctionService,
- IFormulaCustomFunctionService,
-} from './services/formula-custom-function.service';
import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
import { IRegisterFunctionService, RegisterFunctionService } from './services/register-function.service';
import { DefinedNameController } from './controllers/defined-name.controller';
@@ -46,6 +42,28 @@ import { FormulaAlertRenderController } from './controllers/formula-alert-render
import { FormulaRenderManagerController } from './controllers/formula-render.controller';
import { RefSelectionsRenderService } from './services/render-services/ref-selections.render-service';
import { PromptController } from './controllers/prompt.controller';
+import { IRemoteRegisterFunctionService, RemoteRegisterFunctionService, RemoteRegisterFunctionServiceName } from './services/remote/remote-register-function.service';
+
+@DependentOn(UniverFormulaEnginePlugin)
+export class UniverRemoteSheetsFormulaPlugin extends Plugin {
+ static override pluginName = 'SHEETS_FORMULA_REMOTE_PLUGIN';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ private readonly _config = {},
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([RemoteRegisterFunctionService]);
+ injector.get(IRPCChannelService).registerChannel(
+ RemoteRegisterFunctionServiceName,
+ fromModule(injector.get(RemoteRegisterFunctionService))
+ );
+ }
+}
/**
* The configuration of the formula UI plugin.
@@ -66,29 +84,11 @@ export class UniverSheetsFormulaPlugin extends Plugin {
}
override onStarting(): void {
- this._registerDependencies();
- }
-
- override onRendered(): void {
- this._registerRenderModules();
- }
-
- private _registerRenderModules(): void {
- ([
- [RefSelectionsRenderService],
- [FormulaAlertRenderController],
- ] as Dependency[]).forEach((dep) => {
- this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, dep));
- });
- }
-
- private _registerDependencies(): void {
const j = this._injector;
const dependencies: Dependency[] = [
[IFormulaPromptService, { useClass: FormulaPromptService }],
[IRefSelectionsService, { useClass: SheetsSelectionsService }],
[IDescriptionService, { useFactory: () => j.createInstance(DescriptionService, this._config?.description) }],
- [IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }],
[IRegisterFunctionService, { useClass: RegisterFunctionService }],
[FormulaRefRangeService],
[RegisterOtherFormulaService],
@@ -105,8 +105,26 @@ export class UniverSheetsFormulaPlugin extends Plugin {
[PromptController],
];
+ // If the plugin do not execute formula, it should delegate a remote calculator.
+ // So custom functions should be synced to that remote calculator.
+ if (this._config.notExecuteFormula) {
+ const rpcChannelService = j.get(IRPCChannelService);
+ dependencies.push([IRemoteRegisterFunctionService, {
+ useFactory: () => toModule<IRemoteRegisterFunctionService>(rpcChannelService.requestChannel(RemoteRegisterFunctionServiceName)),
+ }]);
+ }
+
dependencies.forEach((dependency) => j.add(dependency));
}
+
+ override onRendered(): void {
+ ([
+ [RefSelectionsRenderService],
+ [FormulaAlertRenderController],
+ ] as Dependency[]).forEach((dep) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, dep));
+ });
+ }
}
export class UniverSheetsFormulaMobilePlugin extends Plugin {
@@ -136,7 +154,6 @@ export class UniverSheetsFormulaMobilePlugin extends Plugin {
useFactory: () => this._injector.createInstance(DescriptionService, this._config?.description),
},
],
- [IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }],
[IRegisterFunctionService, { useClass: RegisterFunctionService }],
[FormulaRefRangeService],
[RegisterOtherFormulaService],
diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.ts
index cbd9b3121c..9619971187 100644
--- a/packages/sheets-formula/src/index.ts
+++ b/packages/sheets-formula/src/index.ts
@@ -14,16 +14,13 @@
* limitations under the License.
*/
-export { UniverSheetsFormulaPlugin, UniverSheetsFormulaMobilePlugin } from './formula-ui-plugin';
+export { UniverRemoteSheetsFormulaPlugin, UniverSheetsFormulaPlugin, UniverSheetsFormulaMobilePlugin } from './formula-ui-plugin';
export { IDescriptionService } from './services/description.service';
export { DescriptionService } from './services/description.service';
-export {
- FormulaCustomFunctionService,
- IFormulaCustomFunctionService,
-} from './services/formula-custom-function.service';
export type { IRegisterFunctionParams, IUnregisterFunctionParams } from './services/register-function.service';
export { RegisterFunctionService } from './services/register-function.service';
export { IRegisterFunctionService } from './services/register-function.service';
+export { IRemoteRegisterFunctionService, RemoteRegisterFunctionService } from './services/remote/remote-register-function.service';
export { FormulaRefRangeService } from './services/formula-ref-range.service';
export { RegisterOtherFormulaService } from './services/register-other-formula.service';
export type { IFormulaInfo, IOtherFormulaResult } from './services/formula-common';
diff --git a/packages/sheets-formula/src/services/formula-custom-function.service.ts b/packages/sheets-formula/src/services/formula-custom-function.service.ts
deleted file mode 100644
index 570903cb9b..0000000000
--- a/packages/sheets-formula/src/services/formula-custom-function.service.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { Disposable, ICommandService, toDisposable } from '@univerjs/core';
-import type { PrimitiveValueType } from '@univerjs/engine-formula';
-import { RegisterFunctionMutation, UnregisterFunctionMutation } from '@univerjs/engine-formula';
-import type { IDisposable } from '@wendellhu/redi';
-import { createIdentifier } from '@wendellhu/redi';
-
-export type IRegisterFunction = (
- ...arg: Array<PrimitiveValueType | PrimitiveValueType[][]>
-) => PrimitiveValueType | PrimitiveValueType[][];
-
-// [[Function, FunctionName, Description]]
-export type IRegisterFunctionList = [[IRegisterFunction, string, string?]];
-
-export interface IFormulaCustomFunctionService {
- /**
- * register descriptions
- * @param functionList
- */
- registerFunctions(functionList: IRegisterFunctionList): IDisposable;
-}
-
-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): IDisposable {
- const functionNameList: string[] = []; // used to unregister functions
- const functions = functionList.map((func) => {
- functionNameList.push(func[1]);
- return [func[0].toString(), func[1]];
- });
-
- // Synchronous to worker
- this._commandService.executeCommand(
- RegisterFunctionMutation.id,
- {
- functions,
- },
- {
- local: true,
- }
- );
-
- return toDisposable(() => {
- this._commandService.executeCommand(
- UnregisterFunctionMutation.id,
- {
- functions: functionNameList,
- },
- {
- local: true,
- }
- );
- });
- }
-}
diff --git a/packages/sheets-formula/src/services/register-function.service.ts b/packages/sheets-formula/src/services/register-function.service.ts
index 21df441278..163c983cdf 100644
--- a/packages/sheets-formula/src/services/register-function.service.ts
+++ b/packages/sheets-formula/src/services/register-function.service.ts
@@ -15,15 +15,29 @@
*/
import type { ILocales } from '@univerjs/core';
-import { Disposable, LocaleService, toDisposable } from '@univerjs/core';
-import type { IFunctionInfo } from '@univerjs/engine-formula';
-import { FunctionType, IFunctionService } from '@univerjs/engine-formula';
+import { Disposable, DisposableCollection, LocaleService, toDisposable } from '@univerjs/core';
+import type { IFunctionInfo, PrimitiveValueType } from '@univerjs/engine-formula';
+import { CustomFunction, FunctionType, IFunctionService } from '@univerjs/engine-formula';
import type { IDisposable } from '@wendellhu/redi';
-import { createIdentifier, Inject } from '@wendellhu/redi';
+import { createIdentifier, Inject, Optional } from '@wendellhu/redi';
import { IDescriptionService } from './description.service';
-import type { IRegisterFunctionList } from './formula-custom-function.service';
-import { IFormulaCustomFunctionService } from './formula-custom-function.service';
+import { IRemoteRegisterFunctionService } from './remote/remote-register-function.service';
+
+export type IRegisterFunction = (
+ ...arg: Array<PrimitiveValueType | PrimitiveValueType[][]>
+) => PrimitiveValueType | PrimitiveValueType[][];
+
+// [[Function, FunctionName, Description]]
+export type IRegisterFunctionList = [[IRegisterFunction, string, string?]];
+
+export interface IFormulaCustomFunctionService {
+ /**
+ * register descriptions
+ * @param functionList
+ */
+ registerFunctions(functionList: IRegisterFunctionList): IDisposable;
+}
/**
* Register function operation params
@@ -60,25 +74,28 @@ export interface IUnregisterFunctionParams {
functionNames: string[];
}
+/**
+ * This
+ */
export interface IRegisterFunctionService {
/**
* register descriptions
- * @param functionList
+ * @param params
*/
registerFunctions(params: IRegisterFunctionParams): IDisposable;
}
export const IRegisterFunctionService = createIdentifier<IRegisterFunctionService>(
- 'formula-ui.register-function-service'
+ 'sheets-formula.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
+ @IFunctionService private readonly _functionService: IFunctionService,
+ @Optional(IRemoteRegisterFunctionService)
+ private readonly _remoteRegisterFunctionService?: IRemoteRegisterFunctionService
) {
super();
}
@@ -92,12 +109,11 @@ export class RegisterFunctionService extends Disposable implements IRegisterFunc
this._localeService.load(locales);
}
- let descriptionDisposable: IDisposable;
- // description
+ const disposables = new DisposableCollection();
if (description) {
- descriptionDisposable = this._descriptionService.registerDescriptions(description);
+ disposables.add(this._descriptionService.registerDescriptions(description));
} else {
- const descriptionList: IFunctionInfo[] = calculate.map(([func, functionName, functionIntroduction]) => {
+ const descriptionList: IFunctionInfo[] = calculate.map(([_func, functionName, functionIntroduction]) => {
return {
functionName,
functionType: FunctionType.User,
@@ -107,15 +123,38 @@ export class RegisterFunctionService extends Disposable implements IRegisterFunc
};
});
- descriptionDisposable = this._functionService.registerDescriptions(...descriptionList);
+ disposables.add(this._functionService.registerDescriptions(...descriptionList));
}
// calculation
- const functionsDisposable = this._formulaCustomFunctionService.registerFunctions(calculate);
+ disposables.add(this._registerLocalExecutors(calculate));
+ if (this._remoteRegisterFunctionService) {
+ disposables.add(this._registerRemoteExecutors(calculate));
+ }
- return toDisposable(() => {
- functionsDisposable.dispose();
- descriptionDisposable.dispose();
+ return disposables;
+ }
+
+ private _registerLocalExecutors(list: IRegisterFunctionList): IDisposable {
+ const names = list.map(([_func, name]) => name);
+ const functions = list.map(([func, name]) => {
+ const instance = new CustomFunction(name);
+ instance.calculateCustom = func;
+ return instance;
});
+
+ this._functionService.registerExecutors(...functions);
+ return toDisposable(() => this._functionService.unregisterExecutors(...names));
+ }
+
+ private _registerRemoteExecutors(list: IRegisterFunctionList): IDisposable {
+ const functionNameList: string[] = []; // used to unregister functions
+ const functions = list.map(([func, name]) => {
+ functionNameList.push(name);
+ return [func.toString(), name] as [string, string];
+ });
+
+ this._remoteRegisterFunctionService!.registerFunctions(functions);
+ return toDisposable(() => this._remoteRegisterFunctionService!.unregisterFunctions(functionNameList));
}
}
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
new file mode 100644
index 0000000000..74826d9c02
--- /dev/null
+++ b/packages/sheets-formula/src/services/remote/remote-register-function.service.ts
@@ -0,0 +1,57 @@
+/**
+ * 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 { BaseFunction } from '@univerjs/engine-formula';
+import { CustomFunction, IFunctionService } from '@univerjs/engine-formula';
+import { createIdentifier } from '@wendellhu/redi';
+
+export interface IRemoteRegisterFunctionService {
+ registerFunctions(serializedFuncs: Array<[string, string]>): Promise<void>;
+ unregisterFunctions(names: string[]): Promise<void>;
+}
+
+export const RemoteRegisterFunctionServiceName = 'sheets-formula.remote-register-function.service';
+export const IRemoteRegisterFunctionService = createIdentifier<IRemoteRegisterFunctionService>(RemoteRegisterFunctionServiceName);
+
+/**
+ * This class should resident in the remote process.
+ */
+export class RemoteRegisterFunctionService implements IRemoteRegisterFunctionService {
+ constructor(
+ @IFunctionService private readonly _functionService: IFunctionService
+ ) {}
+
+ async registerFunctions(serializedFuncs: Array<[string, string]>): Promise<void> {
+ const functionList = serializedFuncs.map(([func, name]) => {
+ return createFunction(func, name);
+ });
+
+ this._functionService.registerExecutors(...functionList);
+ }
+
+ async unregisterFunctions(names: string[]): Promise<void> {
+ this._functionService.unregisterDescriptions(...names);
+ }
+}
+
+function createFunction(functionString: string, functionName: string) {
+ const instance = new CustomFunction(functionName);
+ // eslint-disable-next-line no-new-func
+ const functionCalculate = new Function(`return ${functionString}`)();
+ instance.calculateCustom = functionCalculate;
+
+ return instance as BaseFunction;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0923c731e7..8bff532ef0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1750,6 +1750,9 @@ importers:
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
+ '@univerjs/rpc':
+ specifier: workspace:*
+ version: link:../rpc
'@univerjs/shared':
specifier: workspace:*
version: link:../../common/shared