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): open register event api (#5806)

wpxp123456ef11c97a32d6
diff --git a/examples/src/sheets/custom/custom-register-event.ts b/examples/src/sheets/custom/custom-register-event.ts
new file mode 100644
index 0000000000..38e222ae3f
--- /dev/null
+++ b/examples/src/sheets/custom/custom-register-event.ts
@@ -0,0 +1,190 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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 { Univer } from '@univerjs/core';
+import type { FUniver, IEventBase } from '@univerjs/core/facade';
+import type { IRemoveColByRangeCommandParams } from '@univerjs/sheets';
+import type { FWorkbook, FWorksheet } from '@univerjs/sheets/facade';
+import { CanceledError, ICommandService } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { RemoveColByRangeCommand } from '@univerjs/sheets';
+import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';
+import { IContextMenuService } from '@univerjs/ui';
+
+interface IMainRightClickEventParams extends IEventBase {
+ event: MouseEvent;
+ row?: number;
+ column?: number;
+}
+
+interface IRemoveColumnEventParams extends IEventBase {
+ workbook: FWorkbook;
+ worksheet: FWorksheet;
+ startColumn: number;
+ endColumn: number;
+}
+
+interface IBeforeRemoveColumnEventParams extends IEventBase {
+ workbook: FWorkbook;
+ worksheet: FWorksheet;
+ startColumn: number;
+ endColumn: number;
+}
+
+interface ICustomEventParamConfig {
+ MainRightClickEvent: IMainRightClickEventParams;
+ RemoveColumnEvent: IRemoveColumnEventParams;
+ BeforeRemoveColumnEvent: IBeforeRemoveColumnEventParams;
+}
+
+export function customRegisterEvent(univer: Univer, univerAPI: FUniver) {
+ univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {
+ if (stage === univerAPI.Enum.LifecycleStages.Steady) {
+ registerMainRightClickEvent(univer, univerAPI);
+ registerRemoveColumnEvent(univer, univerAPI);
+ registerBeforeRemoveColumnEvent(univer, univerAPI);
+
+ univerAPI.addEvent('MainRightClickEvent', (params) => {
+ const { row, column } = params;
+ console.warn(`Right clicked on cell at ${univerAPI.Util.tools.chatAtABC(column as number)}${row as number + 1}`);
+ // If the cell is A1, do not show the context menu
+ if (row === 0 && column === 0) {
+ params.cancel = true;
+ }
+ });
+
+ univerAPI.addEvent('RemoveColumnEvent', (params) => {
+ const { startColumn, endColumn } = params;
+ console.warn(`Removed columns from ${univerAPI.Util.tools.chatAtABC(startColumn)} to ${univerAPI.Util.tools.chatAtABC(endColumn)}`);
+ });
+
+ const beforeRemoveColumnEventDisposable = univerAPI.addEvent('BeforeRemoveColumnEvent', (params) => {
+ const { startColumn, endColumn } = params;
+ console.warn(`Before removing columns from ${univerAPI.Util.tools.chatAtABC(startColumn)} to ${univerAPI.Util.tools.chatAtABC(endColumn)}`);
+ // If the column to be deleted includes column C to E, prevent the deletion
+ if (!(startColumn > 4 || endColumn < 2)) {
+ params.cancel = true;
+ console.warn('Cannot delete column C to E');
+ }
+ });
+
+ // Remove the BeforeRemoveColumnEvent listener after 10 seconds
+ setTimeout(() => {
+ beforeRemoveColumnEventDisposable.dispose();
+ console.warn('BeforeRemoveColumnEvent listener has been removed, you can delete any columns now.');
+ }, 10000);
+ }
+ });
+}
+
+function registerMainRightClickEvent(univer: Univer, univerAPI: FUniver) {
+ const fWorkbook = univerAPI.getActiveWorkbook();
+ if (!fWorkbook) return;
+
+ const fWorksheet = fWorkbook.getActiveSheet();
+ if (!fWorksheet) return;
+
+ const injector = univer.__getInjector();
+ const renderManagerService = injector.get(IRenderManagerService);
+ const render = renderManagerService.getRenderById(fWorkbook.getId());
+ if (!render) return;
+
+ const { components } = render;
+ const mainComponent = components.get(SHEET_VIEW_KEY.MAIN);
+ if (!mainComponent) return;
+
+ const contextMenuService = injector.get(IContextMenuService);
+
+ univerAPI.registerEventHandler(
+ 'MainRightClickEvent',
+ () => mainComponent.onPointerDown$.subscribeEvent((event) => {
+ if (event.button !== 2) return;
+
+ const activeRange = fWorksheet.getActiveRange();
+ const eventParams: IMainRightClickEventParams = {
+ event,
+ row: activeRange?.getRow() ?? 0,
+ column: activeRange?.getColumn() ?? 0,
+ };
+
+ univerAPI.fireEvent('MainRightClickEvent', eventParams);
+
+ if (eventParams.cancel) {
+ requestAnimationFrame(() => {
+ contextMenuService.hideContextMenu();
+ });
+ }
+ })
+ );
+}
+
+function registerRemoveColumnEvent(univer: Univer, univerAPI: FUniver) {
+ const injector = univer.__getInjector();
+ const commandService = injector.get(ICommandService);
+
+ univerAPI.registerEventHandler(
+ 'RemoveColumnEvent',
+ () => commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id !== RemoveColByRangeCommand.id) return;
+
+ const target = univerAPI.getCommandSheetTarget(commandInfo);
+ if (!target) return;
+
+ const { range } = commandInfo.params as IRemoveColByRangeCommandParams;
+ const eventParams: IRemoveColumnEventParams = {
+ workbook: target.workbook,
+ worksheet: target.worksheet,
+ startColumn: range.startColumn,
+ endColumn: range.endColumn,
+ };
+
+ univerAPI.fireEvent('RemoveColumnEvent', eventParams);
+ })
+ );
+}
+
+function registerBeforeRemoveColumnEvent(univer: Univer, univerAPI: FUniver) {
+ const injector = univer.__getInjector();
+ const commandService = injector.get(ICommandService);
+
+ univerAPI.registerEventHandler(
+ 'BeforeRemoveColumnEvent',
+ () => commandService.beforeCommandExecuted((commandInfo) => {
+ if (commandInfo.id !== RemoveColByRangeCommand.id) return;
+
+ const target = univerAPI.getCommandSheetTarget(commandInfo);
+ if (!target) return;
+
+ const { range } = commandInfo.params as IRemoveColByRangeCommandParams;
+ const eventParams: IBeforeRemoveColumnEventParams = {
+ workbook: target.workbook,
+ worksheet: target.worksheet,
+ startColumn: range.startColumn,
+ endColumn: range.endColumn,
+ };
+
+ univerAPI.fireEvent('BeforeRemoveColumnEvent', eventParams);
+
+ if (eventParams.cancel) {
+ throw new CanceledError();
+ }
+ })
+ );
+}
+
+declare module '@univerjs/core/facade' {
+ interface IEventParamConfig extends ICustomEventParamConfig { }
+}
diff --git a/examples/src/sheets/custom-plugin/custom-shortcut/commands/commands/custom.command.ts b/examples/src/sheets/custom/custom-shortcut/commands/commands/custom.command.ts
similarity index 100%
rename from examples/src/sheets/custom-plugin/custom-shortcut/commands/commands/custom.command.ts
rename to examples/src/sheets/custom/custom-shortcut/commands/commands/custom.command.ts
diff --git a/examples/src/sheets/custom-plugin/custom-shortcut/controllers/shortcuts/custom.shortcut.ts b/examples/src/sheets/custom/custom-shortcut/controllers/shortcuts/custom.shortcut.ts
similarity index 100%
rename from examples/src/sheets/custom-plugin/custom-shortcut/controllers/shortcuts/custom.shortcut.ts
rename to examples/src/sheets/custom/custom-shortcut/controllers/shortcuts/custom.shortcut.ts
diff --git a/examples/src/sheets/custom-plugin/custom-shortcut/index.ts b/examples/src/sheets/custom/custom-shortcut/index.ts
similarity index 100%
rename from examples/src/sheets/custom-plugin/custom-shortcut/index.ts
rename to examples/src/sheets/custom/custom-shortcut/index.ts
diff --git a/examples/src/sheets/custom-plugin/custom-shortcut/plugin.ts b/examples/src/sheets/custom/custom-shortcut/plugin.ts
similarity index 100%
rename from examples/src/sheets/custom-plugin/custom-shortcut/plugin.ts
rename to examples/src/sheets/custom/custom-shortcut/plugin.ts
diff --git a/examples/src/sheets/custom-plugin/import-csv-button.ts b/examples/src/sheets/custom/import-csv-button.ts
similarity index 100%
rename from examples/src/sheets/custom-plugin/import-csv-button.ts
rename to examples/src/sheets/custom/import-csv-button.ts
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index e5e409c8fd..ff299715da 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -50,8 +50,9 @@ import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
import { UniverUIPlugin } from '@univerjs/ui';
import { UniverVue3AdapterPlugin } from '@univerjs/ui-adapter-vue3';
import { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component';
-import { UniverSheetsCustomShortcutPlugin } from './custom-plugin/custom-shortcut';
-import ImportCSVButtonPlugin from './custom-plugin/import-csv-button';
+import { customRegisterEvent } from './custom/custom-register-event';
+import { UniverSheetsCustomShortcutPlugin } from './custom/custom-shortcut';
+import ImportCSVButtonPlugin from './custom/import-csv-button';
import '@univerjs/sheets/facade';
import '@univerjs/ui/facade';
@@ -187,6 +188,8 @@ function createNewInstance() {
window.univer = univer;
window.univerAPI = FUniver.newAPI(univer);
+
+ customRegisterEvent(univer, window.univerAPI!);
}
createNewInstance();
diff --git a/packages/core/src/facade/f-univer.ts b/packages/core/src/facade/f-univer.ts
index 632fbef3fb..904e9cce6d 100644
--- a/packages/core/src/facade/f-univer.ts
+++ b/packages/core/src/facade/f-univer.ts
@@ -96,7 +96,7 @@ export class FUniver extends Disposable {
protected _eventRegistry = new FEventRegistry();
- protected registerEventHandler = (event: string, handler: () => IDisposable | Subscription): IDisposable => {
+ registerEventHandler = (event: string, handler: () => IDisposable | Subscription): IDisposable => {
return this._eventRegistry.registerEventHandler(event, handler);
};
@@ -483,7 +483,7 @@ export class FUniver extends Disposable {
* this.fireEvent(univerAPI.Event.LifeCycleChanged, params);
* ```
*/
- protected fireEvent<T extends keyof IEventParamConfig>(event: T, params: IEventParamConfig[T]): boolean | undefined {
+ fireEvent<T extends keyof IEventParamConfig>(event: T, params: IEventParamConfig[T]): boolean | undefined {
return this._eventRegistry.fireEvent(event, params);
}