Skip to content

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

feat(facade): create websocket api (#1120)

Dushusir177c5dae99b2
diff --git a/packages/facade/package.json b/packages/facade/package.json
index 8338c17027..0f9fd8edf1 100644
--- a/packages/facade/package.json
+++ b/packages/facade/package.json
@@ -48,6 +48,7 @@
"@univerjs/engine-formula": "workspace:*",
"@univerjs/sheets-formula": "workspace:*",
"@univerjs/sheets-numfmt": "workspace:*",
+ "@univerjs/network": "workspace:*",
"@wendellhu/redi": "^0.12.13",
"rxjs": "^7.8.1"
},
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
new file mode 100644
index 0000000000..0a1549a00a
--- /dev/null
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -0,0 +1,124 @@
+/**
+ * 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 { IWorkbookData, Workbook } from '@univerjs/core';
+import {
+ ILogService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ PluginType,
+ Univer,
+} from '@univerjs/core';
+import { FunctionService, IFunctionService } from '@univerjs/engine-formula';
+import { ISocketService, WebSocketService } from '@univerjs/network';
+import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
+import {
+ DescriptionService,
+ enUS,
+ FormulaCustomFunctionService,
+ IDescriptionService,
+ IFormulaCustomFunctionService,
+ IRegisterFunctionService,
+ RegisterFunctionService,
+ zhCN,
+} from '@univerjs/sheets-formula';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { FUniver } from '../facade';
+
+function getTestWorkbookDataDemo(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'sheet1',
+ cellData: {},
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ };
+}
+
+export interface ITestBed {
+ univer: Univer;
+ get: Injector['get'];
+ sheet: Workbook;
+ univerAPI: FUniver;
+}
+
+export function createTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]): ITestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([SelectionManagerService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
+ injector.add([
+ IDescriptionService,
+ {
+ useFactory: () => this._injector.createInstance(DescriptionService, undefined),
+ },
+ ]);
+ injector.add([IFunctionService, { useClass: FunctionService }]);
+ injector.add([IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }]);
+ injector.add([ISocketService, { useClass: WebSocketService }]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+ }
+
+ injector.get(LocaleService).load({ zhCN, enUS });
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || getTestWorkbookDataDemo());
+
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+ const logService = injector.get(ILogService);
+
+ logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs
+
+ const univerAPI = FUniver.newAPI(injector);
+
+ return {
+ univer,
+ get: injector.get.bind(injector),
+ sheet,
+ univerAPI,
+ };
+}
diff --git a/packages/facade/src/apis/__tests__/facade.spec.ts b/packages/facade/src/apis/__tests__/facade.spec.ts
new file mode 100644
index 0000000000..264dcf0041
--- /dev/null
+++ b/packages/facade/src/apis/__tests__/facade.spec.ts
@@ -0,0 +1,119 @@
+/**
+ * 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.
+ */
+
+/* eslint-disable no-magic-numbers */
+
+import type { ICellData, IStyleData, Nullable } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand } from '@univerjs/sheets';
+import type { Injector } from '@wendellhu/redi';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import type { FUniver } from '../facade';
+import { createTestBed } from './create-test-bed';
+
+describe('Test FUniver', () => {
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let univerAPI: FUniver;
+ let getValueByPosition: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Nullable<ICellData>;
+ let getStyleByPosition: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Nullable<IStyleData>;
+
+ beforeEach(() => {
+ const testBed = createTestBed();
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetStyleCommand);
+
+ getValueByPosition = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Nullable<ICellData> =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValue();
+
+ getStyleByPosition = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Nullable<IStyleData> => {
+ const value = getValueByPosition(startRow, startColumn, endRow, endColumn);
+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();
+ if (value && styles) {
+ return styles.getStyleByCell(value);
+ }
+ };
+ });
+
+ it('Function executeCommand', () => {
+ univerAPI.executeCommand(SetRangeValuesCommand.id, {
+ subUnitId: 'sheet1',
+ unitId: 'test',
+ range: {
+ startRow: 1,
+ startColumn: 1,
+ endRow: 2,
+ endColumn: 2,
+ },
+
+ value: [
+ [{ v: 1 }, { v: 2 }],
+ [{ v: 3 }, { v: 4 }],
+ ],
+ });
+
+ expect(getValueByPosition(1, 1, 1, 1)).toStrictEqual({
+ v: 1,
+ t: 2,
+ });
+ expect(getValueByPosition(1, 2, 1, 2)).toStrictEqual({
+ v: 2,
+ t: 2,
+ });
+ expect(getValueByPosition(2, 1, 2, 1)).toStrictEqual({
+ v: 3,
+ t: 2,
+ });
+ expect(getValueByPosition(2, 2, 2, 2)).toStrictEqual({
+ v: 4,
+ t: 2,
+ });
+ });
+
+ it('Function createSocket', () => {
+ expect(() => univerAPI.createSocket('URL')).toThrowError();
+ });
+});
diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.ts
index 1d6d111a5a..8bee3b278a 100644
--- a/packages/facade/src/apis/facade.ts
+++ b/packages/facade/src/apis/facade.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { CommandListener, IWorkbookData } from '@univerjs/core';
+import type { CommandListener, IExecutionOptions, IWorkbookData } from '@univerjs/core';
import {
BorderStyleTypes,
ICommandService,
@@ -23,10 +23,11 @@ import {
Univer,
WrapStrategy,
} from '@univerjs/core';
+import { ISocketService, WebSocketService } from '@univerjs/network';
import type { IRegisterFunctionParams, IUnregisterFunctionParams } from '@univerjs/sheets-formula';
import { IRegisterFunctionService } from '@univerjs/sheets-formula';
import type { IDisposable } from '@wendellhu/redi';
-import { Inject, Injector } from '@wendellhu/redi';
+import { Inject, Injector, Quantity } from '@wendellhu/redi';
import { FWorkbook } from './sheet/f-workbook';
@@ -36,6 +37,12 @@ export class FUniver {
*/
static newAPI(wrapped: Univer | Injector): FUniver {
const injector = wrapped instanceof Univer ? wrapped.__getInjector() : wrapped;
+ // Is unified registration required?
+ const socketService = injector.get(ISocketService, Quantity.OPTIONAL);
+ if (!socketService) {
+ injector.add([ISocketService, { useClass: WebSocketService }]);
+ }
+
return injector.createInstance(FUniver);
}
@@ -46,7 +53,8 @@ export class FUniver {
@Inject(Injector) private readonly _injector: Injector,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
- @IRegisterFunctionService private readonly _registerFunctionService: IRegisterFunctionService
+ @IRegisterFunctionService private readonly _registerFunctionService: IRegisterFunctionService,
+ @ISocketService private readonly _ws: ISocketService
) {}
/**
@@ -86,10 +94,18 @@ export class FUniver {
return this._injector.createInstance(FWorkbook, workbook);
}
+ /**
+ * Register a function to the spreadsheet.
+ * @param config
+ */
registerFunction(config: IRegisterFunctionParams) {
this._registerFunctionService.registerFunctions(config);
}
+ /**
+ * Unregister a function from the spreadsheet.
+ * @param config
+ */
unregisterFunction(config: IUnregisterFunctionParams) {
this._registerFunctionService.unregisterFunctions(config);
}
@@ -126,10 +142,40 @@ export class FUniver {
* @returns A function to dispose the listening.
*/
onCommandExecuted(callback: CommandListener): IDisposable {
- return this._commandService.onCommandExecuted((command) => {
- callback(command);
+ return this._commandService.onCommandExecuted((command, options?: IExecutionOptions) => {
+ callback(command, options);
});
}
+ /**
+ * Execute command
+ * @param id Command id
+ * @param params Command params
+ * @param options Command options
+ * @returns Command Promise
+ */
+ executeCommand<P extends object = object, R = boolean>(
+ id: string,
+ params?: P,
+ options?: IExecutionOptions
+ ): Promise<R> {
+ return this._commandService.executeCommand(id, params, options);
+ }
+
+ /**
+ * Set WebSocket URL for WebSocketService
+ * @param url WebSocketService URL
+ * @returns WebSocket info and callback
+ */
+ createSocket(url: string) {
+ const ws = this._ws.createSocket(url);
+
+ if (!ws) {
+ throw new Error('[WebSocketService]: failed to create socket!');
+ }
+
+ return ws;
+ }
+
// @endregion
}
diff --git a/packages/facade/src/apis/sheet/__tests__/create-test-bed.ts b/packages/facade/src/apis/sheet/__tests__/create-test-bed.ts
index 3bb37110d0..35f96b7a4c 100644
--- a/packages/facade/src/apis/sheet/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/sheet/__tests__/create-test-bed.ts
@@ -26,6 +26,7 @@ import {
Univer,
} from '@univerjs/core';
import { FunctionService, IFunctionService } from '@univerjs/engine-formula';
+import { ISocketService, WebSocketService } from '@univerjs/network';
import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
import {
DescriptionService,
@@ -49,6 +50,7 @@ function getTestWorkbookDataDemo(): IWorkbookData {
sheets: {
sheet1: {
id: 'sheet1',
+ name: 'sheet1',
cellData: {},
},
},
@@ -86,9 +88,15 @@ export function createTestBed(workbookConfig?: IWorkbookData, dependencies?: Dep
injector.add([SelectionManagerService]);
injector.add([SheetInterceptorService]);
injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
- injector.add([IDescriptionService, { useClass: DescriptionService }]);
+ injector.add([
+ IDescriptionService,
+ {
+ useFactory: () => this._injector.createInstance(DescriptionService, undefined),
+ },
+ ]);
injector.add([IFunctionService, { useClass: FunctionService }]);
injector.add([IFormulaCustomFunctionService, { useClass: FormulaCustomFunctionService }]);
+ injector.add([ISocketService, { useClass: WebSocketService }]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 338e67d05c..89f7a519f7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -586,6 +586,9 @@ importers:
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../engine-formula
+ '@univerjs/network':
+ specifier: workspace:*
+ version: link:../network
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets